answer stringlengths 17 10.2M |
|---|
package eu.amidst.examples;
import COM.hugin.HAPI.*;
import COM.hugin.HAPI.Class;
import eu.amidst.core.database.Attributes;
import eu.amidst.core.database.DataBase;
import eu.amidst.core.database.DataInstance;
import eu.amidst.core.database.DataOnDisk;
import eu.amidst.core.database.filereaders.DynamicDataOnDiskFromFile;
import eu.amidst.core.database.filereaders.arffFileReader.ARFFDataReader;
import eu.amidst.core.huginlink.*;
import eu.amidst.core.learning.DynamicNaiveBayesClassifier;
import eu.amidst.core.models.BayesianNetwork;
import eu.amidst.core.models.DynamicBayesianNetwork;
import eu.amidst.core.utils.BayesianNetworkGenerator;
import eu.amidst.core.utils.BayesianNetworkSampler;
import eu.amidst.core.variables.DynamicVariables;
import eu.amidst.core.variables.Variable;
import java.io.IOException;
import java.util.*;
public class InferenceDemo {
public static void printBeliefs (Domain domainObject) throws ExceptionHugin {
domainObject.getNodes().stream().forEach((node) -> {
try {
System.out.print("\n" + node.getName()+ ": ");
int numStates = (int)((LabelledDCNode)node).getNumberOfStates();
for (int j=0;j<numStates;j++){
System.out.print(((LabelledDCNode) node).getBelief(j) + " ");
}
} catch (ExceptionHugin exceptionHugin) {
exceptionHugin.printStackTrace();
}
});
}
public static void demo() throws ExceptionHugin, IOException {
BayesianNetworkGenerator.setNumberOfContinuousVars(0);
BayesianNetworkGenerator.setNumberOfDiscreteVars(3);
BayesianNetworkGenerator.setNumberOfStates(2);
BayesianNetwork bn = BayesianNetworkGenerator.generateNaiveBayes(new Random(0));
int sampleSize = 20;
BayesianNetworkSampler sampler = new BayesianNetworkSampler(bn);
sampler.setParallelMode(false);
String file = "./datasets/randomdata.arff";
sampler.sampleToAnARFFFile(file,sampleSize);
DataBase data = new DynamicDataOnDiskFromFile(new ARFFDataReader(file));
DynamicNaiveBayesClassifier model = new DynamicNaiveBayesClassifier();
model.setClassVarID(data.getAttributes().getNumberOfAttributes() - 1);
model.setParallelMode(true);
model.learn(data);
DynamicBayesianNetwork amidstDBN = model.getDynamicBNModel();
//We randomly initialize the parensets Time 0 because parameters are wrongly learnt due
//to the data sample only contains 1 data sequence.
Random rand = new Random(0);
amidstDBN.getDistributionsTime0().forEach(w -> w.randomInitialization(rand));
System.out.println(amidstDBN.toString());
Class huginDBN = DBNConverterToHugin.convertToHugin(amidstDBN);
String nameModel = "huginDBNFromAMIDST";
huginDBN.setName(nameModel);
String outFile = new String("networks/"+nameModel+".net");
huginDBN.saveAsNet(outFile);
System.out.println("Hugin network saved in \"" + outFile + "\"" + "."); |
package org.openstack.nova.model;
import java.io.Serializable;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.codehaus.jackson.annotate.JsonAnySetter;
import org.codehaus.jackson.annotate.JsonProperty;
import org.codehaus.jackson.map.annotate.JsonRootName;
@JsonRootName("server")
public class Server implements Serializable {
public static final class Addresses implements Serializable {
public static final class Address implements Serializable {
private String version;
private String addr;
/**
* @return the version
*/
public String getVersion() {
return version;
}
/**
* @return the addr
*/
public String getAddr() {
return addr;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "Address [version=" + version + ", addr=" + addr + "]";
}
}
private Map<String, List<Address>> addresses = new HashMap<String, List<Address>>();
@JsonAnySetter
public void add(String key, List<Address> value) {
addresses.put(key, value);
}
/**
* @return the ip address List Map
*/
public Map<String, List<Address>> getAddresses() {
return addresses;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "Addresses List Map [" + addresses + "]";
}
}
public static final class Fault {
private Integer code;
private String message;
private Calendar created;
/**
* @return the code
*/
public Integer getCode() {
return code;
}
/**
* @return the message
*/
public String getMessage() {
return message;
}
/**
* @return the created
*/
public Calendar getCreated() {
return created;
}
}
private String id;
private String name;
private Addresses addresses;
private List<Link> links;
private Image image;
private Flavor flavor;
private String accessIPv4;
private String accessIPv6;
@JsonProperty("config_drive")
private String configDrive;
private String status;
private Integer progress;
private Fault fault;
@JsonProperty("tenant_id")
private String tenantId;
@JsonProperty("user_id")
private String userId;
@JsonProperty("key_name")
private String keyName;
private String hostId;
private String updated;
private String created;
private Map<String, String> metadata;
@JsonProperty("security_groups")
private List<SecurityGroup> securityGroups;
@JsonProperty("OS-EXT-STS:task_state")
private String taskState;
@JsonProperty("OS-EXT-STS:power_state")
private String powerState;
@JsonProperty("OS-EXT-STS:vm_state")
private String vmState;
@JsonProperty("OS-EXT-SRV-ATTR:host")
private String host;
@JsonProperty("OS-EXT-SRV-ATTR:instance_name")
private String instanceName;
@JsonProperty("OS-EXT-SRV-ATTR:hypervisor_hostname")
private String hypervisorHostname;
@JsonProperty("OS-DCF:diskConfig")
private String diskConfig;
private String uuid;
private String adminPass;
/**
* @return the id
*/
public String getId() {
return id;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @return the addresses
*/
public Addresses getAddresses() {
return addresses;
}
/**
* @return the links
*/
public List<Link> getLinks() {
return links;
}
/**
* @return the image
*/
public Image getImage() {
return image;
}
/**
* @param image the image to set
*/
public void setImage(Image image) {
this.image = image;
}
/**
* @return the flavor
*/
public Flavor getFlavor() {
return flavor;
}
/**
* @param flavor the flavor to set
*/
public void setFlavor(Flavor flavor) {
this.flavor = flavor;
}
/**
* @return the accessIPv4
*/
public String getAccessIPv4() {
return accessIPv4;
}
/**
* @return the accessIPv6
*/
public String getAccessIPv6() {
return accessIPv6;
}
/**
* @return the configDrive
*/
public String getConfigDrive() {
return configDrive;
}
/**
* @return the status
*/
public String getStatus() {
return status;
}
/**
* @return the progress
*/
public Integer getProgress() {
return progress;
}
/**
* @return the fault
*/
public Fault getFault() {
return fault;
}
/**
* @return the tenantId
*/
public String getTenantId() {
return tenantId;
}
/**
* @return the userId
*/
public String getUserId() {
return userId;
}
/**
* @return the keyName
*/
public String getKeyName() {
return keyName;
}
/**
* @return the hostId
*/
public String getHostId() {
return hostId;
}
/**
* @return the updated
*/
public String getUpdated() {
return updated;
}
/**
* @return the created
*/
public String getCreated() {
return created;
}
/**
* @return the metadata
*/
public Map<String, String> getMetadata() {
return metadata;
}
/**
* @return the securityGroups
*/
public List<SecurityGroup> getSecurityGroups() {
return securityGroups;
}
/**
* @return the taskState
*/
public String getTaskState() {
return taskState;
}
/**
* @return the powerState
*/
public String getPowerState() {
return powerState;
}
/**
* @return the vmState
*/
public String getVmState() {
return vmState;
}
/**
* @return the host
*/
public String getHost() {
return host;
}
/**
* @return the instanceName
*/
public String getInstanceName() {
return instanceName;
}
/**
* @return the hypervisorHostname
*/
public String getHypervisorHostname() {
return hypervisorHostname;
}
/**
* @return the diskConfig
*/
public String getDiskConfig() {
return diskConfig;
}
/**
* @return the uuid
*/
public String getUuid() {
return uuid;
}
/**
* @return the adminPass
*/
public String getAdminPass() {
return adminPass;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "Server [id=" + id + ", name=" + name + ", addresses="
+ addresses + ", links=" + links + ", image=" + image
+ ", flavor=" + flavor + ", accessIPv4=" + accessIPv4
+ ", accessIPv6=" + accessIPv6 + ", configDrive=" + configDrive
+ ", status=" + status + ", progress=" + progress + ", fault="
+ fault + ", tenantId=" + tenantId + ", userId=" + userId
+ ", keyName=" + keyName + ", hostId=" + hostId + ", updated="
+ updated + ", created=" + created + ", metadata=" + metadata
+ ", securityGroups=" + securityGroups + ", taskState="
+ taskState + ", powerState=" + powerState + ", vmState="
+ vmState + ", host=" + host + ", instanceName=" + instanceName
+ ", hypervisorHostname=" + hypervisorHostname
+ ", diskConfig=" + diskConfig + ", uuid=" + uuid
+ ", adminPass=" + adminPass + "]";
}
} |
package fr.insee.rmes.api.codes;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import fr.insee.rmes.api.codes.cj.CJQueries;
import fr.insee.rmes.api.codes.cj.CategorieJuridiqueNiveauII;
import fr.insee.rmes.api.codes.cj.CategorieJuridiqueNiveauIII;
import fr.insee.rmes.api.codes.na1973.GroupeNA1973;
import fr.insee.rmes.api.codes.na1973.Na1973Queries;
import fr.insee.rmes.api.codes.naf1993.ClasseNAF1993;
import fr.insee.rmes.api.codes.naf1993.Naf1993Queries;
import fr.insee.rmes.api.codes.naf2003.ClasseNAF2003;
import fr.insee.rmes.api.codes.naf2003.Naf2003Queries;
import fr.insee.rmes.api.codes.naf2008.ClasseNAF2008;
import fr.insee.rmes.api.codes.naf2008.Naf2008Queries;
import fr.insee.rmes.api.codes.naf2008.SousClasseNAF2008;
import fr.insee.rmes.api.utils.CSVUtils;
import fr.insee.rmes.api.utils.ResponseUtils;
import fr.insee.rmes.api.utils.SparqlUtils;
@Path("/codes")
public class CodesAPI {
private static Logger logger = LogManager.getLogger(CodesAPI.class);
@Path("/cj/n2/{code: [0-9]{2}}")
@GET
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public Response getCategorieJuridiqueNiveauII(@PathParam("code") String code, @HeaderParam("Accept") String header) {
logger.debug("Received GET request for CJ 2nd level " + code);
CategorieJuridiqueNiveauII cjNiveau2 = new CategorieJuridiqueNiveauII(code);
String csvResult = SparqlUtils.executeSparqlQuery(CJQueries.getCategorieJuridiqueNiveauII(code));
CSVUtils.populatePOJO(csvResult, cjNiveau2);
if (cjNiveau2.getUri() == null) return Response.status(Status.NOT_FOUND).entity("").build();
return Response.ok(ResponseUtils.produceResponse(cjNiveau2, header)).build();
}
@Path("/cj/n3/{code: [0-9]{4}}")
@GET
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public Response getCategorieJuridiqueNiveauIII(@PathParam("code") String code, @HeaderParam("Accept") String header) {
logger.debug("Received GET request for CJ 3rd level " + code);
CategorieJuridiqueNiveauIII cjNiveau3 = new CategorieJuridiqueNiveauIII(code);
String csvResult = SparqlUtils.executeSparqlQuery(CJQueries.getCategorieJuridiqueNiveauIII(code));
CSVUtils.populatePOJO(csvResult, cjNiveau3);
if (cjNiveau3.getUri() == null) return Response.status(Status.NOT_FOUND).entity("").build();
return Response.ok(ResponseUtils.produceResponse(cjNiveau3, header)).build();
}
@Path("/nafr2/sousClasse/{code: [0-9]{2}\\.[0-9]{2}[A-Z]}")
@GET
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public Response getSousClasseNAF2008(@PathParam("code") String code, @HeaderParam("Accept") String header) {
logger.debug("Received GET request for NAF sub-class " + code);
SousClasseNAF2008 sousClasse = new SousClasseNAF2008(code);
String csvResult = SparqlUtils.executeSparqlQuery(Naf2008Queries.getSousClasseNAF2008(code));
CSVUtils.populatePOJO(csvResult, sousClasse);
if (sousClasse.getUri() == null) return Response.status(Status.NOT_FOUND).entity("").build();
return Response.ok(ResponseUtils.produceResponse(sousClasse, header)).build();
}
@Path("/nafr2/classe/{code: [0-9]{2}\\.[0-9]{2}}")
@GET
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public Response getClasseNAF2008(@PathParam("code") String code, @HeaderParam("Accept") String header) {
logger.debug("Received GET request for NAF rev. 2 class " + code);
ClasseNAF2008 classe = new ClasseNAF2008(code);
String csvResult = SparqlUtils.executeSparqlQuery(Naf2008Queries.getClasseNAF2008(code));
CSVUtils.populatePOJO(csvResult, classe);
if (classe.getUri() == null) return Response.status(Status.NOT_FOUND).entity("").build();
return Response.ok(ResponseUtils.produceResponse(classe, header)).build();
}
@Path("/nafr1/classe/{code: [0-9]{2}\\.[0-9][A-Z]}")
@GET
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public Response getClasseNAF2003(@PathParam("code") String code, @HeaderParam("Accept") String header) {
logger.debug("Received GET request for NAF rev. 1 class " + code);
ClasseNAF2003 classe = new ClasseNAF2003(code);
String csvResult = SparqlUtils.executeSparqlQuery(Naf2003Queries.getClasseNAF2003(code));
CSVUtils.populatePOJO(csvResult, classe);
if (classe.getUri() == null) return Response.status(Status.NOT_FOUND).entity("").build();
return Response.ok(ResponseUtils.produceResponse(classe, header)).build();
}
@Path("/naf/classe/{code: [0-9]{2}\\.[0-9][A-Z]}")
@GET
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public Response getClasseNAF1993(@PathParam("code") String code, @HeaderParam("Accept") String header) {
logger.debug("Received GET request for NAF class " + code);
ClasseNAF1993 classe = new ClasseNAF1993(code);
String csvResult = SparqlUtils.executeSparqlQuery(Naf1993Queries.getClasseNAF1993(code));
CSVUtils.populatePOJO(csvResult, classe);
if (classe.getUri() == null) return Response.status(Status.NOT_FOUND).entity("").build();
return Response.ok(ResponseUtils.produceResponse(classe, header)).build();
}
@Path("/na73/groupe/{code: [0-9]{2}\\.[0-9]{2}}")
@GET
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public Response getClasseNA1973(@PathParam("code") String code, @HeaderParam("Accept") String header) {
logger.debug("Received GET request for NA 1973 group " + code);
GroupeNA1973 groupe = new GroupeNA1973(code);
String csvResult = SparqlUtils.executeSparqlQuery(Na1973Queries.getGroupeNA1973(code));
CSVUtils.populatePOJO(csvResult, groupe);
if (groupe.getUri() == null) return Response.status(Status.NOT_FOUND).entity("").build();
return Response.ok(ResponseUtils.produceResponse(groupe, header)).build();
}
} |
package i5.las2peer.tools;
import i5.las2peer.api.ConnectorException;
import i5.las2peer.api.Service;
import i5.las2peer.classLoaders.ClassLoaderException;
import i5.las2peer.classLoaders.L2pClassLoader;
import i5.las2peer.classLoaders.libraries.FileSystemRepository;
import i5.las2peer.execution.L2pServiceException;
import i5.las2peer.httpConnector.HttpConnector;
import i5.las2peer.p2p.Node;
import i5.las2peer.p2p.NodeException;
import i5.las2peer.p2p.PastryNodeImpl;
import i5.las2peer.persistency.MalformedXMLException;
import i5.las2peer.security.Agent;
import i5.las2peer.security.AgentException;
import i5.las2peer.security.L2pSecurityException;
import i5.las2peer.security.ServiceAgent;
import i5.las2peer.testing.MockAgentFactory;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Hashtable;
import java.util.Vector;
public class ServiceStarter {
public static final String DEFAULT_LOG = "./log/las2peer.log";
public static final String DEFAULT_BOOTSTRAP = "127.0.0.1:9000";
public static final int DEFAULT_PORT = 9010;
public static final String DEFAULT_PASTRY_DIR = ".pastry_data";
public static final String DEFAULT_SERVICE ="./service/";
/**
* walk through the given parameter values, check all parameters and return a corresponding hashtable
*
* @param argv
*
* @return hashtable with parsed parameters
*/
@SuppressWarnings("unchecked")
private static Hashtable<String, Object> parseParameters ( String[] argv ) {
Hashtable<String, Object> result = new Hashtable<String, Object> ();
result.put("servicedirs", new Vector<String>());
Vector<String> serviceClasses = new Vector<String> ();
Vector<String> serviceXmls = new Vector<String > ();
Hashtable<String,String> htAgentPasses = new Hashtable<String, String>();
int lauf = 0;
while ( lauf < argv.length ) {
if ( argv[lauf].equals( "-c")) {
lauf++;
if ( serviceClasses.contains( argv[lauf]))
throw new IllegalArgumentException ( argv[lauf] + " is given more than once!");
serviceClasses.add ( argv[lauf]);
lauf ++;
} else if ( argv[lauf].equals ( "-x")) {
lauf++;
if ( serviceXmls.contains( argv[lauf]))
throw new IllegalArgumentException ( argv[lauf] + " is given more than once!");
htAgentPasses.put( argv[lauf], argv[lauf+1]);
serviceXmls.add ( argv[lauf]);
lauf +=2;
} else if ( argv[lauf].equals ( "-l")) {
if ( result.containsKey( "logprefix"))
throw new IllegalArgumentException ( "-l given more than once!");
result.put( "logfile", argv[lauf+1]);
lauf += 2;
} else if ( argv[lauf].equals ( "-d")) {
((Vector<String>)result.get( "servicedirs")).add(argv[lauf+1]);
lauf += 2;
} else if ( argv[lauf].equals ( "-b")) {
if ( result.containsKey("bootstrap"))
throw new IllegalArgumentException ( "-b given more than once!");
result.put( "bootstrap", argv[lauf+1]);
lauf += 2;
} else if ( argv[lauf].equals ( "-n")) {
if ( result.containsKey("pastryDir"))
throw new IllegalArgumentException ( "-n given more than once!");
result.put( "pastryDir", argv[lauf+1]);
lauf += 2;
} else if ( argv[lauf].equals ( "-p")) {
if ( result.containsKey("port"))
throw new IllegalArgumentException ( "-p given more than once!");
result.put( "port", Integer.parseInt( argv[lauf+1]));
lauf += 2;
} else if ( argv[lauf].equals ( "-http") ) {
if ( serviceClasses.contains( "startHttp" ))
throw new IllegalArgumentException ( argv[lauf] + " is given more than once!");
lauf++;
int port = 8080;
if ( lauf < (argv.length ) && !argv[lauf].startsWith("-")) {
port = Integer.valueOf( argv[lauf]);
lauf ++;
}
result.put("startHttp", port);
} else {
printHelp ( "unkown parameter: " + argv[lauf] );
System.exit ( 10 );
}
}
result.put( "serviceClasses", serviceClasses);
result.put( "serviceXmls", serviceXmls);
result.put ( "agentPasses", htAgentPasses);
if ( serviceClasses.size() + serviceXmls.size() == 0 )
throw new IllegalArgumentException ( "You have to give at least one -x or -c parameter to start a service node!");
return result;
}
/**
* set the default values for all missing parameters
*
* @param parameters
*/
@SuppressWarnings("unchecked")
private static void addDefaultValues ( Hashtable<String, Object> parameters ) {
if ( ! parameters.containsKey("bootstrap"))
parameters.put( "bootstrap", DEFAULT_BOOTSTRAP);
if ( ! parameters.containsKey("port"))
parameters.put( "port", DEFAULT_PORT);
if ( ! parameters.containsKey("pastryDir"))
parameters.put( "pastryDir", DEFAULT_PASTRY_DIR);
if ( ! parameters.containsKey("servicedirs") || ((Vector<String>) parameters.get("servicedirs")).size() == 0 ) {
Vector<String> servicedirs = new Vector<String> ();
servicedirs.add (DEFAULT_SERVICE);
parameters.put ( "servicedirs", servicedirs);
}
if ( ! parameters.containsKey("logprefix"))
parameters.put( "logprefix", DEFAULT_LOG);
}
/**
* print an error message to standard error and the normal help message to standard out
* @param message
*/
private static void printHelp ( String message ) {
System.err.println ( message + "\n" );
printHelp ();
}
/**
* print a simple help message to standard out
*/
private static void printHelp () {
System.out.println( "Start a node hosting one or more services. "
+"At least one of the parameters -x or -c is needed. "
+"Optional parameters are -p, -d, -l, -n, -b and -http. See the Java Docs of the "
+"i5.las2peer.tools.ServiceStarter class for further information." );
}
/**
* set up the classloader
*
* @return a class loader looking into the given directories
*
*/
private static L2pClassLoader setupClassLoader( Vector<String> servicedirs ) {
return new L2pClassLoader( new FileSystemRepository ( servicedirs.toArray(new String[0])), ServiceStarter.class.getClassLoader() );
}
/**
* register all given agents to the running las2peer node
*
* @param node
* @param agents
*
* @throws L2pServiceException
*/
private static void launchAgents(PastryNodeImpl node,
Vector<ServiceAgent> agents) throws L2pServiceException {
for ( ServiceAgent agent: agents ) {
try {
node.registerReceiver(agent);
System.out.println ( "registered Agent " + agent.getId());
if ( agent instanceof ServiceAgent )
System.out.println ( " -> Service: " + ((ServiceAgent) agent).getServiceClassName() );
} catch ( Exception e) {
e.printStackTrace();
throw new L2pServiceException ( "Error registering the service agent to the node! " + e.getMessage());
}
}
}
/**
* start a pastry node implementation of a las2peer network node
* @param cl
*
* @param parameters
*
* @return a running node
* @throws NodeException
*/
private static PastryNodeImpl startNode( L2pClassLoader cl, Hashtable<String, Object> parameters ) throws NodeException {
String bootstrap = (String) parameters.get("bootstrap");
int port = (Integer) parameters.get("port");
PastryNodeImpl node = new PastryNodeImpl(cl, port, bootstrap);
node.setLogfilePrefix((String) parameters.get("logprefix"));
node.launch();
return node;
}
/**
* create new service agents for the given service classes
* and store them as [class].agent.xml files in the current directory.
*
* The corresponding passphrases will be collected in the file passphrases.txt
* @param cl
*
* @param vector
* @return
* @throws AgentException
*/
private static Vector<ServiceAgent> createAgents(L2pClassLoader cl, Vector<String> vector) throws AgentException {
if ( vector.size() == 0 )
return new Vector<ServiceAgent> ();
Vector<ServiceAgent> result = new Vector<ServiceAgent> ();
Hashtable<String, String> passphrases = new Hashtable<String, String > ();
StringBuffer passphraseOut = new StringBuffer();
for ( String clsName : vector ) {
try {
cl.registerService(clsName);
@SuppressWarnings("unchecked")
Class<? extends Service> cls = (Class<? extends Service>) cl.getServiceClass(clsName);
String passphrase = SimpleTools.createRandomString(20);
ServiceAgent agent = ServiceAgent.generateNewAgent(cls.getName(), passphrase);
passphrases.put(clsName, passphrase );
int counter = 0;
File agentFile = new File ( clsName + ".agent.xml");
while ( agentFile.exists() ) {
agentFile = new File ( clsName + ".agent." + counter + ".xml");
counter++;
}
// write agent XML file
PrintStream ps = new PrintStream ( new FileOutputStream ( agentFile ));
ps.print( agent.toXmlString() );
ps.close();
System.out.println ( "Written " + agentFile );
passphraseOut.append ( agentFile + "\t:\t" + passphrase + "\n");
agent.unlockPrivateKey(passphrase);
result.add ( agent );
} catch ( ClassCastException e ) {
throw new AgentException ( "clsName is not a Service class!");
} catch ( ClassLoaderException e ) {
e.printStackTrace();
throw new AgentException ( "Service class " + clsName + " cannot be found: " + e.getMessage());
} catch ( L2pSecurityException e ) {
throw new AgentException ( "Strange key problems while generating agent for service " + clsName );
} catch ( CryptoException e ) {
throw new AgentException ( "Strange crypto problems while generating agent for service " + clsName );
} catch ( Exception e ) {
e.printStackTrace();
throw new AgentException ( "Unable to write agent file for " + clsName + ": " + e .getMessage());
}
}
// write passphrase file
File passFile = new File ( "passphrases.txt" );
int counter = 0;
while ( passFile.exists ()) {
passFile = new File ( "passphrases." + counter + ".txt");
counter ++;
}
try {
PrintStream ps = new PrintStream ( new FileOutputStream ( passFile ));
ps.println(passphraseOut);
ps.close();
} catch ( Exception e ) {
throw new AgentException ( "error writing the passphrase file " + passFile + ": " + e.getMessage());
}
return result;
}
/**
* load and unlock the agents from the given XML files
*
* @param xmlFiles strings defining XML files containing service agent information
* @param passphrases passphrases for the service agents' keys
*
* @return vector with all loaded and unlocked agents
* @throws AgentException
*/
private static Vector<ServiceAgent> loadAgents(Vector<String> xmlFiles,
Hashtable<String, String> passphrases) throws AgentException {
Vector<ServiceAgent> result = new Vector<ServiceAgent> ();
for ( String file: xmlFiles ) {
try {
ServiceAgent loaded = ServiceAgent.createFromXml( FileContentReader.read ( file ));
loaded.unlockPrivateKey(passphrases.get(file));
result.add ( loaded );
System.out.println( "loaded agent from " + file );
} catch (MalformedXMLException e) {
throw new AgentException ( "Xml format problems with agent XML file " + file );
} catch (IOException e) {
throw new AgentException ( "Error opening XML file " + file );
} catch (L2pSecurityException e) {
throw new AgentException ( "Security exception unlocking agent file " + file + " -- wrong passphrase?");
}
}
return result;
}
/**
* Main method for command line usage.
*
* Standard parameters are
* <table>
* <tr><th>-c [classname]</th><td>class name of a service to start, a new (temporary) agent will be generated and stored to class.agent.xml in the launch directory</td><td>multiple</td></tr>
* <tr><td>-x [xmlfile] [passphrase]</th><td>Name of an XML file containing a {@link i5.las2peer.security.ServiceAgent} immediately followed by the passphrase to unlock the private key of the service agent<td><td>multiple</td></tr>
* </table>
*
* At least one value for -c or -x needs to be given.
*
* Optional parameters are:
*
* <table>
* <tr><th>parameter</th><th>default</th><th>how often</th><th>description</th></tr>
* <tr><th>-l [file prefix]</th><td>./log/las2peer-node.</td><td>once</td><td>prefix for the log file generated by the las2peer node, the prefix will be followed by the ID of the pastry node in the P2P network</td></tr>
* <tr><th>-d [dirname]</th><td>./lib/</td><td>once</td><td>name of the directory for the class loader library</td></tr>
* <tr><th>-b [bootstrap]</th><td>somehost:9000</td><td>once</td><td>Bootstrap to connect to</td></tr>
* <tr><th>-n [dirname]</th><td>.pastry_data</td><td>once</td><td>node temporary directory</td></tr>
* <tr><th>-p [portnumber]</th><td>9000</td><td>once</td><td>port to listen to</td><tr>
* <tr><th>-http [portnumber]</th><td>--</td><td>once</td><td>Start the http connector at the given port. The port number is optional. If none is given, the connector will be started at port 8080.</td></tr>
* </table>
*
* @param argv
*/
@SuppressWarnings("unchecked")
public static void main ( String[] argv ) {
try {
Hashtable<String, Object> parameters = parseParameters ( argv );
addDefaultValues ( parameters );
L2pClassLoader cl = setupClassLoader( (Vector<String>) parameters.get("servicedirs"));
Vector<ServiceAgent> agentsFromXml = loadAgents (
(Vector<String>) parameters.get("serviceXmls"),
(Hashtable<String,String>) parameters.get("agentPasses")
);
Vector<ServiceAgent> newAgents = createAgents (
cl,
(Vector<String>) parameters.get("serviceClasses"));
PastryNodeImpl n = startNode( cl, parameters );
launchAgents ( n, agentsFromXml );
launchAgents ( n, newAgents );
System.out.println ( "node has been started! ...\n\n");
if ( parameters.containsKey("startHttp"))
startHttpConnector(n, (Integer) parameters.get("startHttp"));
} catch ( IllegalArgumentException e ) {
printHelp ( e.getMessage() );
System.exit(10);
} catch ( L2pServiceException e ) {
printHelp ( e.getMessage () );
System.exit(200);
} catch ( AgentException e ) {
printHelp ( e.getMessage() );
System.exit(10);
} catch ( NodeException e ) {
printHelp ( "Error starting the las2peer node: " + e.getMessage ());
System.exit( 100 );
}
}
private static void startHttpConnector ( Node node, final int iPort ) {
try {
System.out.println ( "Starting Http Connector!");
final HttpConnector connector = new HttpConnector ();
connector.setHttpPort( iPort );
connector.start( node );
System.out.println ( " -> waiting a little");
try {
System.in.read();
} catch (IOException e) {
}
} catch (FileNotFoundException e) {
System.out.println ( " --> Error finding connector logfile!" + e );
} catch (ConnectorException e) {
System.out.println ( " --> problems starting the connector: " + e);
}
}
} |
package io.fabric8.maven.docker;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import io.fabric8.maven.docker.config.*;
import io.fabric8.maven.docker.model.Network;
import io.fabric8.maven.docker.service.QueryService;
import io.fabric8.maven.docker.service.RunService;
import io.fabric8.maven.docker.service.ServiceHub;
import io.fabric8.maven.docker.util.PomLabel;
import io.fabric8.maven.docker.access.DockerAccessException;
import io.fabric8.maven.docker.log.LogDispatcher;
import io.fabric8.maven.docker.model.Container;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.Execute;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
/**
* Mojo for stopping containers. If called together with <code>docker:start</code> (i.e.
* when configured for integration testing in a lifefcycle phase), then only the container
* started by this goal will be stopped and removed by default (this can be tuned with the
* system property <code>docker.keepContainer</code>).
*
* If this goal is called standalone, then <em>all</em> containers are stopped, for which images
* has been configured in the pom.xml
*
* @author roland
* @since 26.03.14
*
*/
@Mojo(name = "stop", defaultPhase = LifecyclePhase.POST_INTEGRATION_TEST)
@Execute(phase = LifecyclePhase.INITIALIZE)
public class StopMojo extends AbstractDockerMojo {
@Parameter(property = "docker.keepRunning", defaultValue = "false")
private boolean keepRunning;
/**
* Whether to create the customs networks (user-defined bridge networks) before starting automatically
*/
@Parameter(property = "docker.autoCreateCustomNetworks", defaultValue = "false")
protected boolean autoCreateCustomNetworks;
@Parameter( property = "docker.allContainers", defaultValue = "false" )
private boolean allContainers;
@Parameter( property = "docker.sledgeHammer", defaultValue = "false" )
private boolean sledgeHammer;
@Override
protected void executeInternal(ServiceHub hub) throws MojoExecutionException, DockerAccessException {
QueryService queryService = hub.getQueryService();
RunService runService = hub.getRunService();
PomLabel pomLabel = getPomLabel();
if (!keepRunning) {
if (invokedTogetherWithDockerStart()) {
runService.stopStartedContainers(keepContainer, removeVolumes, autoCreateCustomNetworks, pomLabel);
} else {
stopContainers(queryService, runService, pomLabel);
}
}
// Switch off all logging
LogDispatcher dispatcher = getLogDispatcher(hub);
dispatcher.untrackAllContainerLogs();
}
private void stopContainers(QueryService queryService, RunService runService, PomLabel pomLabel) throws DockerAccessException {
Collection<Network> networksToRemove = getNetworksToRemove(queryService, pomLabel);
for (ImageConfiguration image : getResolvedImages()) {
for (Container container : getContainersToStop(queryService, image)) {
if (shouldStopContainer(container, pomLabel, image)) {
runService.stopContainer(container.getId(), image, keepContainer, removeVolumes);
}
}
}
runService.removeCustomNetworks(networksToRemove);
}
// If naming strategy is alias stop a container with this name, otherwise get all containers with this image's name
private List<Container> getContainersToStop(QueryService queryService, ImageConfiguration image) throws DockerAccessException {
List<Container> containers = Collections.emptyList();
RunImageConfiguration.NamingStrategy strategy = image.getRunConfiguration().getNamingStrategy();
//Do not fail if container is not found
try {
if (strategy == RunImageConfiguration.NamingStrategy.alias) {
Container container = queryService.getContainer(image.getAlias());
if (container != null) {
containers = Collections.singletonList(container);
}
} else {
containers = queryService.getContainersForImage(image.getName());
}
if(containers == null) {
containers = Collections.emptyList();
}
} catch (Exception ex) {
log.warn("%s", ex.getMessage());
containers = Collections.emptyList();
}
return containers;
}
private boolean shouldStopContainer(Container container, PomLabel pomLabel, ImageConfiguration image) {
if (isStopAllContainers()) {
return true;
}
RunImageConfiguration.NamingStrategy strategy = image.getRunConfiguration().getNamingStrategy();
if (RunImageConfiguration.NamingStrategy.alias.equals(strategy)) {
if(container.getName().equals(image.getAlias())) {
return true;
}
return false;
} else {
String key = pomLabel.getKey();
Map<String, String> labels = container.getLabels();
return labels.containsKey(key) && pomLabel.equals(new PomLabel(labels.get(key)));
}
}
private boolean isStopAllContainers() {
return (allContainers || sledgeHammer);
}
private boolean invokedTogetherWithDockerStart() {
Boolean startCalled = (Boolean) getPluginContext().get(CONTEXT_KEY_START_CALLED);
return startCalled != null && startCalled;
}
private Set<Network> getNetworksToRemove(QueryService queryService, PomLabel pomLabel) throws DockerAccessException {
if (!autoCreateCustomNetworks) {
return Collections.emptySet();
}
Set<Network> customNetworks = new HashSet<>();
Set<Network> networks = queryService.getNetworks();
for (ImageConfiguration image : getResolvedImages()) {
final NetworkConfig config = image.getRunConfiguration().getNetworkingConfig();
if (config.isCustomNetwork()) {
Network network = getNetworkByName(networks, config.getCustomNetwork());
if (network != null) {
customNetworks.add(network);
for (Container container : getContainersToStop(queryService, image)) {
if (!shouldStopContainer(container, pomLabel, image)) {
// it's sill in use don't collect it
customNetworks.remove(network);
}
}
}
}
}
return customNetworks;
}
private Network getNetworkByName(Set<Network> networks, String networkName) {
for (Network network : networks) {
if (networkName.equals(network.getName())) {
return network;
}
}
return null;
}
} |
package javaslang.collection;
import java.io.Serializable;
import java.util.Comparator;
/**
* <strong>INTERNAL API - This class is subject to change.</strong>
*/
final class Comparators {
private Comparators() {
}
/**
* Returns the natural comparator for type U, i.e. treating it as {@code Comparable<? super U>}.
* The returned comparator is also {@code java.io.Serializable}.
* <p>
* Please note that this will lead to runtime exceptions, if U is not Comparable.
*
* @param <U> The type
* @return The natural Comparator of type U
*/
@SuppressWarnings("unchecked")
static <U> SerializableComparator<U> naturalComparator() {
return (o1, o2) -> ((Comparable<U>) o1).compareTo(o2);
}
/**
* Needed for serialization of sortable collections which internally need a comparator.
* <p>
* In general the comparator may be
* <ul>
* <li>a concrete class</li>
* <li>a lambda</li>
* <li>a method reference</li>
* </ul>
*
* @param <T> the type of objects that may be compared by this comparator
*/
@FunctionalInterface
interface SerializableComparator<T> extends Comparator<T>, Serializable {
}
} |
package jcifs.smb;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.Objects;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jcifs.Address;
import jcifs.CIFSContext;
import jcifs.CIFSException;
import jcifs.DfsReferralData;
import jcifs.NetbiosAddress;
import jcifs.RuntimeCIFSException;
import jcifs.SmbConstants;
import jcifs.SmbResourceLocator;
import jcifs.internal.util.StringUtil;
import jcifs.netbios.NbtAddress;
import jcifs.netbios.UniAddress;
/**
*
*
* This mainly tracks two locations:
* - canonical URL path: path component of the URL: this is used to reconstruct URLs to resources and is not adjusted by
* DFS referrals. (E.g. a resource with a DFS root's parent will still point to the DFS root not the share it's actually
* located in).
* - share + uncpath within it: This is the relevant information for most SMB requests. Both are adjusted by DFS
* referrals. Nested resources will inherit the information already resolved by the parent resource.
*
* Invariant:
* A directory resource must have a trailing slash/backslash for both URL and UNC path at all times.
*
* @author mbechler
*
*/
class SmbResourceLocatorImpl implements SmbResourceLocatorInternal, Cloneable {
private static final Logger log = LoggerFactory.getLogger(SmbResourceLocatorImpl.class);
private final URL url;
private DfsReferralData dfsReferral = null; // For getDfsPath() and getServerWithDfs()
private String unc; // Initially null; set by getUncPath; never ends with '/'
private String canon; // Initially null; set by getUncPath; dir must end with '/'
private String share; // Can be null
private Address[] addresses;
private int addressIndex;
private int type;
private CIFSContext ctx;
/**
*
* @param ctx
* @param u
*/
public SmbResourceLocatorImpl ( CIFSContext ctx, URL u ) {
this.ctx = ctx;
this.url = u;
}
/**
* {@inheritDoc}
*
* @see java.lang.Object#clone()
*/
@Override
protected SmbResourceLocatorImpl clone () {
SmbResourceLocatorImpl loc = new SmbResourceLocatorImpl(this.ctx, this.url);
loc.canon = this.canon;
loc.share = this.share;
loc.dfsReferral = this.dfsReferral;
loc.unc = this.unc;
if ( this.addresses != null ) {
loc.addresses = new UniAddress[this.addresses.length];
System.arraycopy(this.addresses, 0, loc.addresses, 0, this.addresses.length);
}
loc.addressIndex = this.addressIndex;
loc.type = this.type;
return loc;
}
/**
* @param context
* @param name
*/
void resolveInContext ( SmbResourceLocator context, String name ) {
String shr = context.getShare();
if ( shr != null ) {
this.dfsReferral = context.getDfsReferral();
}
int last = name.length() - 1;
boolean trailingSlash = false;
if ( last >= 0 && name.charAt(last) == '/' ) {
trailingSlash = true;
name = name.substring(0, last);
}
if ( shr == null ) {
String[] nameParts = name.split("/");
// server is set through URL, however it's still in the name
int pos = 0;
if ( context.getServer() == null ) {
pos = 1;
}
// first remaining path element would be share
if ( nameParts.length > pos ) {
this.share = nameParts[ pos++ ];
}
// all other remaining path elements are actual path
if ( nameParts.length > pos ) {
String[] remainParts = new String[nameParts.length - pos];
System.arraycopy(nameParts, pos, remainParts, 0, nameParts.length - pos);
this.unc = "\\" + StringUtil.join("\\", remainParts) + ( trailingSlash ? "\\" : "" );
this.canon = "/" + this.share + "/" + StringUtil.join("/", remainParts) + ( trailingSlash ? "/" : "" );
}
else {
this.unc = "\\";
if ( this.share != null ) {
this.canon = "/" + this.share + ( trailingSlash ? "/" : "" );
}
else {
this.canon = "/";
}
}
}
else {
String uncPath = context.getUNCPath();
if ( uncPath.equals("\\") ) {
// context share != null, so the remainder is path
this.unc = '\\' + name.replace('/', '\\') + ( trailingSlash ? "\\" : "" );
this.canon = context.getURLPath() + name + ( trailingSlash ? "/" : "" );
this.share = shr;
}
else {
this.unc = uncPath + name.replace('/', '\\') + ( trailingSlash ? "\\" : "" );
this.canon = context.getURLPath() + name + ( trailingSlash ? "/" : "" );
this.share = shr;
}
}
}
/**
* {@inheritDoc}
*
* @see jcifs.SmbResourceLocator#getDfsReferral()
*/
@Override
public DfsReferralData getDfsReferral () {
return this.dfsReferral;
}
/**
* {@inheritDoc}
*
* @see jcifs.SmbResourceLocator#getName()
*/
@Override
public String getName () {
String urlpath = getURLPath();
String shr = getShare();
if ( urlpath.length() > 1 ) {
int i = urlpath.length() - 2;
while ( urlpath.charAt(i) != '/' ) {
i
}
return urlpath.substring(i + 1);
}
else if ( shr != null ) {
return shr + '/';
}
else if ( this.url.getHost().length() > 0 ) {
return this.url.getHost() + '/';
}
else {
return "smb:
}
}
/**
* {@inheritDoc}
*
* @see jcifs.SmbResourceLocator#getParent()
*/
@Override
public String getParent () {
String str = this.url.getAuthority();
if ( str != null && !str.isEmpty() ) {
StringBuffer sb = new StringBuffer("smb:
sb.append(str);
String urlpath = getURLPath();
if ( urlpath.length() > 1 ) {
sb.append(urlpath);
}
else {
sb.append('/');
}
str = sb.toString();
int i = str.length() - 2;
while ( str.charAt(i) != '/' ) {
i
}
return str.substring(0, i + 1);
}
return "smb:
}
/**
* {@inheritDoc}
*
* @see jcifs.SmbResourceLocator#getPath()
*/
@Override
public String getPath () {
return this.url.toString();
}
/**
* {@inheritDoc}
*
* @see jcifs.SmbResourceLocator#getCanonicalURL()
*/
@Override
public String getCanonicalURL () {
String str = this.url.getAuthority();
if ( str != null && !str.isEmpty() ) {
return "smb://" + this.url.getAuthority() + this.getURLPath();
}
return "smb:
}
@Override
public String getUNCPath () {
if ( this.unc == null ) {
canonicalizePath();
}
return this.unc;
}
@Override
public String getURLPath () {
if ( this.unc == null ) {
canonicalizePath();
}
return this.canon;
}
@Override
public String getShare () {
if ( this.unc == null ) {
canonicalizePath();
}
return this.share;
}
/**
* {@inheritDoc}
*
* @see jcifs.SmbResourceLocator#getServerWithDfs()
*/
@Override
public String getServerWithDfs () {
if ( this.dfsReferral != null ) {
return this.dfsReferral.getServer();
}
return getServer();
}
/**
* {@inheritDoc}
*
* @see jcifs.SmbResourceLocator#getServer()
*/
@Override
public String getServer () {
String str = this.url.getHost();
if ( str.length() == 0 ) {
return null;
}
return str;
}
/**
* {@inheritDoc}
*
* @see jcifs.SmbResourceLocator#getDfsPath()
*/
@Override
public String getDfsPath () {
if ( this.dfsReferral == null ) {
return null;
}
return "smb:/" + this.dfsReferral.getServer() + "/" + this.dfsReferral.getShare() + this.getUNCPath().replace('\\', '/');
}
/**
* {@inheritDoc}
*
* @see jcifs.SmbResourceLocator#getPort()
*/
@Override
public int getPort () {
return this.url.getPort();
}
/**
* {@inheritDoc}
*
* @see jcifs.SmbResourceLocator#getURL()
*/
@Override
public URL getURL () {
return this.url;
}
/**
*
* {@inheritDoc}
*
* @see jcifs.smb.SmbResourceLocatorInternal#shouldForceSigning()
*/
@Override
public boolean shouldForceSigning () {
return this.ctx.getConfig().isIpcSigningEnforced() && !this.ctx.getCredentials().isAnonymous() && isIPC();
}
/**
* {@inheritDoc}
*
* @see jcifs.SmbResourceLocator#isIPC()
*/
@Override
public boolean isIPC () {
String shr = this.getShare();
if ( shr == null || "IPC$".equals(getShare()) ) {
if ( log.isDebugEnabled() ) {
log.debug("Share is IPC " + this.share);
}
return true;
}
return false;
}
/**
* @param t
*/
void updateType ( int t ) {
this.type = t;
}
/**
* {@inheritDoc}
*
* @see jcifs.SmbResourceLocator#getType()
*/
@Override
public int getType () throws CIFSException {
if ( this.type == 0 ) {
if ( getUNCPath().length() > 1 ) {
this.type = SmbConstants.TYPE_FILESYSTEM;
}
else if ( getShare() != null ) {
if ( getShare().equals("IPC$") ) {
this.type = SmbConstants.TYPE_NAMED_PIPE;
}
else {
this.type = SmbConstants.TYPE_SHARE;
}
}
else if ( this.url.getAuthority() == null || this.url.getAuthority().isEmpty() ) {
this.type = SmbConstants.TYPE_WORKGROUP;
}
else {
try {
NetbiosAddress nbaddr = getAddress().unwrap(NetbiosAddress.class);
if ( nbaddr != null ) {
int code = nbaddr.getNameType();
if ( code == 0x1d || code == 0x1b ) {
this.type = SmbConstants.TYPE_WORKGROUP;
return this.type;
}
}
}
catch ( CIFSException e ) {
if ( ! ( e.getCause() instanceof UnknownHostException ) ) {
throw e;
}
log.debug("Unknown host", e);
}
this.type = SmbConstants.TYPE_SERVER;
}
}
return this.type;
}
/**
* {@inheritDoc}
*
* @see jcifs.SmbResourceLocator#isWorkgroup()
*/
@Override
public boolean isWorkgroup () throws CIFSException {
if ( this.type == SmbConstants.TYPE_WORKGROUP || this.url.getHost().length() == 0 ) {
this.type = SmbConstants.TYPE_WORKGROUP;
return true;
}
if ( getShare() == null ) {
NetbiosAddress addr = getAddress().unwrap(NetbiosAddress.class);
if ( addr != null ) {
int code = addr.getNameType();
if ( code == 0x1d || code == 0x1b ) {
this.type = SmbConstants.TYPE_WORKGROUP;
return true;
}
}
this.type = SmbConstants.TYPE_SERVER;
}
return false;
}
@Override
public Address getAddress () throws CIFSException {
if ( this.addressIndex == 0 )
return getFirstAddress();
return this.addresses[ this.addressIndex - 1 ];
}
static String queryLookup ( String query, String param ) {
char in[] = query.toCharArray();
int i, ch, st, eq;
st = eq = 0;
for ( i = 0; i < in.length; i++ ) {
ch = in[ i ];
if ( ch == '&' ) {
if ( eq > st ) {
String p = new String(in, st, eq - st);
if ( p.equalsIgnoreCase(param) ) {
eq++;
return new String(in, eq, i - eq);
}
}
st = i + 1;
}
else if ( ch == '=' ) {
eq = i;
}
}
if ( eq > st ) {
String p = new String(in, st, eq - st);
if ( p.equalsIgnoreCase(param) ) {
eq++;
return new String(in, eq, in.length - eq);
}
}
return null;
}
Address getFirstAddress () throws CIFSException {
this.addressIndex = 0;
if ( this.addresses == null ) {
String host = this.url.getHost();
String path = this.url.getPath();
String query = this.url.getQuery();
try {
if ( query != null ) {
String server = queryLookup(query, "server");
if ( server != null && server.length() > 0 ) {
this.addresses = new UniAddress[1];
this.addresses[ 0 ] = this.ctx.getNameServiceClient().getByName(server);
}
String address = queryLookup(query, "address");
if ( address != null && address.length() > 0 ) {
byte[] ip = java.net.InetAddress.getByName(address).getAddress();
this.addresses = new UniAddress[1];
this.addresses[ 0 ] = new UniAddress(java.net.InetAddress.getByAddress(host, ip));
}
}
else if ( host.length() == 0 ) {
try {
Address addr = this.ctx.getNameServiceClient().getNbtByName(NbtAddress.MASTER_BROWSER_NAME, 0x01, null);
this.addresses = new UniAddress[1];
this.addresses[ 0 ] = this.ctx.getNameServiceClient().getByName(addr.getHostAddress());
}
catch ( UnknownHostException uhe ) {
log.debug("Unknown host", uhe);
if ( this.ctx.getConfig().getDefaultDomain() == null ) {
throw uhe;
}
this.addresses = this.ctx.getNameServiceClient().getAllByName(this.ctx.getConfig().getDefaultDomain(), true);
}
}
else if ( path.length() == 0 || path.equals("/") ) {
this.addresses = this.ctx.getNameServiceClient().getAllByName(host, true);
}
else {
this.addresses = this.ctx.getNameServiceClient().getAllByName(host, false);
}
}
catch ( UnknownHostException e ) {
throw new CIFSException("Failed to lookup address for name " + host, e);
}
}
return getNextAddress();
}
Address getNextAddress () {
Address addr = null;
if ( this.addressIndex < this.addresses.length )
addr = this.addresses[ this.addressIndex++ ];
return addr;
}
boolean hasNextAddress () {
return this.addressIndex < this.addresses.length;
}
/**
* {@inheritDoc}
*
* @see jcifs.SmbResourceLocator#isRoot()
*/
@Override
public boolean isRoot () {
// length == 0 should not happen
return getShare() == null && getUNCPath().length() <= 1;
}
/**
* @throws MalformedURLException
*
*/
private synchronized void canonicalizePath () {
char[] in = this.url.getPath().toCharArray();
char[] out = new char[in.length];
int length = in.length, prefixLen = 0, state = 0;
/*
* The canonicalization routine
*/
for ( int i = 0; i < length; i++ ) {
switch ( state ) {
case 0:
if ( in[ i ] != '/' ) {
// Checked exception (e.g. MalformedURLException) would be better
// but this would be a nightmare API wise
throw new RuntimeCIFSException("Invalid smb: URL: " + this.url);
}
out[ prefixLen++ ] = in[ i ];
state = 1;
break;
case 1:
if ( in[ i ] == '/' ) {
break;
}
else if ( in[ i ] == '.' && ( ( i + 1 ) >= length || in[ i + 1 ] == '/' ) ) {
i++;
break;
}
else if ( ( i + 1 ) < length && in[ i ] == '.' && in[ i + 1 ] == '.' && ( ( i + 2 ) >= length || in[ i + 2 ] == '/' ) ) {
i += 2;
if ( prefixLen == 1 )
break;
do {
prefixLen
}
while ( prefixLen > 1 && out[ prefixLen - 1 ] != '/' );
break;
}
state = 2;
case 2:
if ( in[ i ] == '/' ) {
state = 1;
}
out[ prefixLen++ ] = in[ i ];
break;
}
}
this.canon = new String(out, 0, prefixLen);
if ( prefixLen > 1 ) {
prefixLen
int firstSep = this.canon.indexOf('/', 1);
if ( firstSep < 0 ) {
this.share = this.canon.substring(1);
this.unc = "\\";
}
else if ( firstSep == prefixLen ) {
this.share = this.canon.substring(1, firstSep);
this.unc = "\\";
}
else {
this.share = this.canon.substring(1, firstSep);
this.unc = this.canon.substring(firstSep, prefixLen + 1).replace('/', '\\');
}
}
else {
this.canon = "/";
this.share = null;
this.unc = "\\";
}
}
/**
* {@inheritDoc}
*
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode () {
int hash;
try {
hash = getAddress().hashCode();
}
catch ( CIFSException uhe ) {
hash = getServer().toUpperCase().hashCode();
}
return hash + getURLPath().toUpperCase().hashCode();
}
/**
* {@inheritDoc}
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals ( Object obj ) {
if ( ! ( obj instanceof SmbResourceLocatorImpl ) ) {
return false;
}
SmbResourceLocatorImpl o = (SmbResourceLocatorImpl) obj;
/*
* If uncertain, pathNamesPossiblyEqual returns true.
* Comparing canonical paths is definitive.
*/
if ( pathNamesPossiblyEqual(this.url.getPath(), o.url.getPath()) ) {
if ( getURLPath().equalsIgnoreCase(o.getURLPath()) ) {
try {
return getAddress().equals(o.getAddress());
}
catch ( CIFSException uhe ) {
log.debug("Unknown host", uhe);
return getServer().equalsIgnoreCase(o.getServer());
}
}
}
return false;
}
private static boolean pathNamesPossiblyEqual ( String path1, String path2 ) {
int p1, p2, l1, l2;
// if unsure return this method returns true
p1 = path1.lastIndexOf('/');
p2 = path2.lastIndexOf('/');
l1 = path1.length() - p1;
l2 = path2.length() - p2;
// anything with dots voids comparison
if ( l1 > 1 && path1.charAt(p1 + 1) == '.' )
return true;
if ( l2 > 1 && path2.charAt(p2 + 1) == '.' )
return true;
return l1 == l2 && path1.regionMatches(true, p1, path2, p2, l1);
}
/**
*
* {@inheritDoc}
*
* @see jcifs.smb.SmbResourceLocatorInternal#overlaps(jcifs.SmbResourceLocator)
*/
@Override
public boolean overlaps ( SmbResourceLocator other ) throws CIFSException {
String tp = getCanonicalURL();
String op = other.getCanonicalURL();
return getAddress().equals(other.getAddress()) && tp.regionMatches(true, 0, op, 0, Math.min(tp.length(), op.length()));
}
/**
* @param dr
* @param reqPath
* @return UNC path the redirect leads to
*/
@Override
public String handleDFSReferral ( DfsReferralData dr, String reqPath ) {
if ( Objects.equals(this.dfsReferral, dr) ) {
return this.unc;
}
this.dfsReferral = dr;
String oldUncPath = getUNCPath();
int pathConsumed = dr.getPathConsumed();
if ( pathConsumed < 0 ) {
log.warn("Path consumed out of range " + pathConsumed);
pathConsumed = 0;
}
else if ( pathConsumed > this.unc.length() ) {
log.warn("Path consumed out of range " + pathConsumed);
pathConsumed = oldUncPath.length();
}
if ( log.isDebugEnabled() ) {
log.debug("UNC is '" + oldUncPath + "'");
log.debug("Consumed '" + oldUncPath.substring(0, pathConsumed) + "'");
}
String dunc = oldUncPath.substring(pathConsumed);
if ( log.isDebugEnabled() ) {
log.debug("Remaining '" + dunc + "'");
}
if ( dunc.equals("") || dunc.equals("\\") ) {
dunc = "\\";
this.type = SmbConstants.TYPE_SHARE;
}
if ( !dr.getPath().isEmpty() ) {
dunc = "\\" + dr.getPath() + dunc;
}
if ( dunc.charAt(0) != '\\' ) {
log.warn("No slash at start of remaining DFS path " + dunc);
}
this.unc = dunc;
if ( dr.getShare() != null && !dr.getShare().isEmpty() ) {
this.share = dr.getShare();
}
if ( reqPath != null && reqPath.endsWith("\\") && !dunc.endsWith("\\") ) {
dunc += "\\";
}
return dunc;
}
/**
* {@inheritDoc}
*
* @see java.lang.Object#toString()
*/
@Override
public String toString () {
StringBuilder sb = new StringBuilder(this.url.toString());
sb.append('[');
if ( this.unc != null ) {
sb.append("unc=");
sb.append(this.unc);
}
if ( this.canon != null ) {
sb.append("canon=");
sb.append(this.canon);
}
if ( this.dfsReferral != null ) {
sb.append("dfsReferral=");
sb.append(this.dfsReferral);
}
sb.append(']');
return sb.toString();
}
} |
package net.ontrack.backend.db;
public interface SQL {
// Projects
String PROJECT = "SELECT * FROM PROJECT WHERE ID = :id";
String PROJECT_LIST = "SELECT ID, NAME, DESCRIPTION FROM PROJECT ORDER BY NAME";
String PROJECT_CREATE = "INSERT INTO PROJECT (NAME, DESCRIPTION) VALUES (:name, :description)";
String PROJECT_DELETE = "DELETE FROM PROJECT WHERE ID = :id";
String PROJECT_UPDATE = "UPDATE PROJECT SET NAME = :name, DESCRIPTION = :description WHERE ID = :id";
String PROJECT_BY_NAME = "SELECT * FROM PROJECT WHERE NAME = :name";
// Branches
String BRANCH = "SELECT * FROM BRANCH WHERE ID = :id";
String BRANCH_LIST = "SELECT ID, PROJECT, NAME, DESCRIPTION FROM BRANCH WHERE PROJECT = :project ORDER BY ID ASC";
String BRANCH_CREATE = "INSERT INTO BRANCH (PROJECT, NAME, DESCRIPTION) VALUES (:project, :name, :description)";
String BRANCH_DELETE = "DELETE FROM BRANCH WHERE ID = :id";
String BRANCH_UPDATE = "UPDATE BRANCH SET NAME = :name, DESCRIPTION = :description WHERE ID = :id";
String BRANCH_BY_NAME = "SELECT * FROM BRANCH WHERE NAME = :name";
// Builds
String BUILD = "SELECT * FROM BUILD WHERE ID = :id";
String BUILD_LAST_BY_BRANCH = "SELECT * FROM BUILD WHERE BRANCH = :branch ORDER BY ID DESC LIMIT 1";
String BUILD_LIST = "SELECT * FROM BUILD WHERE BRANCH = :branch ORDER BY ID DESC LIMIT :count OFFSET :offset";
String BUILD_CREATE = "INSERT INTO BUILD (BRANCH, NAME, DESCRIPTION) VALUES (:branch, :name, :description)";
String BUILD_BY_NAME = "SELECT * FROM BUILD WHERE NAME = :name";
String BUILD_BY_BRANCH_AND_NAME = "SELECT ID FROM BUILD WHERE BRANCH = :branch AND NAME = :name";
String BUILD_BY_BRANCH_AND_NUMERIC_NAME = "SELECT ID FROM (SELECT * FROM BUILD WHERE BRANCH = :branch AND NAME REGEXP '[0-9]+') WHERE CONVERT(NAME,INT) >= CONVERT(:name,INT) ORDER BY CONVERT(NAME,INT)";
String BUILD_LAST_FOR_PROMOTION_LEVEL = "SELECT BUILD FROM PROMOTED_RUN WHERE PROMOTION_LEVEL = :promotionLevel ORDER BY BUILD DESC LIMIT 1";
String BUILD_DELETE = "DELETE FROM BUILD WHERE ID = :id";
// Validation stamps
long VALIDATION_STAMP_IMAGE_MAXSIZE = 4096;
String VALIDATION_STAMP = "SELECT ID, BRANCH, NAME, DESCRIPTION, PROMOTION_LEVEL, ORDERNB, OWNER_ID FROM VALIDATION_STAMP WHERE ID = :id";
String VALIDATION_STAMP_BY_BRANCH_AND_NAME = "SELECT ID, BRANCH, NAME, DESCRIPTION, PROMOTION_LEVEL, ORDERNB, OWNER_ID FROM VALIDATION_STAMP WHERE BRANCH = :branch AND NAME = :name";
String VALIDATION_STAMP_LIST = "SELECT ID, BRANCH, NAME, DESCRIPTION, PROMOTION_LEVEL, ORDERNB, OWNER_ID FROM VALIDATION_STAMP WHERE BRANCH = :branch ORDER BY ORDERNB";
String VALIDATION_STAMP_CREATE = "INSERT INTO VALIDATION_STAMP (BRANCH, NAME, DESCRIPTION, ORDERNB) VALUES (:branch, :name, :description, :orderNb)";
String VALIDATION_STAMP_DELETE = "DELETE FROM VALIDATION_STAMP WHERE ID = :id";
String VALIDATIONSTAMP_IMAGE_UPDATE = "UPDATE VALIDATION_STAMP SET IMAGE = :image WHERE ID = :id";
String VALIDATIONSTAMP_IMAGE = "SELECT IMAGE FROM VALIDATION_STAMP WHERE ID = :id";
String VALIDATION_STAMP_PROMOTION_LEVEL = "UPDATE VALIDATION_STAMP SET PROMOTION_LEVEL = :promotionLevel WHERE ID = :id";
String VALIDATION_STAMP_FOR_PROMOTION_LEVEL = "SELECT ID, BRANCH, NAME, DESCRIPTION, PROMOTION_LEVEL, ORDERNB, OWNER_ID FROM VALIDATION_STAMP WHERE PROMOTION_LEVEL = :promotionLevel ORDER BY ORDERNB";
String VALIDATION_STAMP_WITHOUT_PROMOTION_LEVEL = "SELECT ID, BRANCH, NAME, DESCRIPTION, PROMOTION_LEVEL, ORDERNB, OWNER_ID FROM VALIDATION_STAMP WHERE BRANCH = :branch AND PROMOTION_LEVEL IS NULL ORDER BY ORDERNB";
String VALIDATION_STAMP_UPDATE = "UPDATE VALIDATION_STAMP SET NAME = :name, DESCRIPTION = :description WHERE ID = :id";
String VALIDATION_STAMP_COUNT = "SELECT COUNT(*) FROM VALIDATION_STAMP WHERE BRANCH = :branch";
String VALIDATION_STAMP_HIGHER = "SELECT ID FROM VALIDATION_STAMP WHERE BRANCH = :branch AND ORDERNB > :orderNb ORDER BY ORDERNB ASC LIMIT 1";
String VALIDATION_STAMP_LOWER = "SELECT ID FROM VALIDATION_STAMP WHERE BRANCH = :branch AND ORDERNB < :orderNb ORDER BY ORDERNB DESC LIMIT 1";
String VALIDATION_STAMP_LEVELNB = "SELECT ORDERNB FROM VALIDATION_STAMP WHERE ID = :id";
String VALIDATION_STAMP_SET_LEVELNB = "UPDATE VALIDATION_STAMP SET ORDERNB = :orderNb WHERE ID = :id";
String VALIDATION_STAMP_CHANGE_OWNER = "UPDATE VALIDATION_STAMP SET OWNER_ID = :owner WHERE ID = :id";
// Promotion levels
long PROMOTION_LEVEL_IMAGE_MAXSIZE = 4096;
String PROMOTION_LEVEL = "SELECT * FROM PROMOTION_LEVEL WHERE ID = :id";
String PROMOTION_LEVEL_LIST = "SELECT * FROM PROMOTION_LEVEL WHERE BRANCH = :branch ORDER BY LEVELNB DESC";
String PROMOTION_LEVEL_COUNT = "SELECT COUNT(*) FROM PROMOTION_LEVEL WHERE BRANCH = :branch";
String PROMOTION_LEVEL_CREATE = "INSERT INTO PROMOTION_LEVEL (BRANCH, NAME, DESCRIPTION, LEVELNB, AUTOPROMOTE) VALUES (:branch, :name, :description, :levelNb, FALSE)";
String PROMOTION_LEVEL_IMAGE_UPDATE = "UPDATE PROMOTION_LEVEL SET IMAGE = :image WHERE ID = :id";
String PROMOTION_LEVEL_IMAGE = "SELECT IMAGE FROM PROMOTION_LEVEL WHERE ID = :id";
String PROMOTION_LEVEL_HIGHER = "SELECT ID FROM PROMOTION_LEVEL WHERE BRANCH = :branch AND LEVELNB > :levelNb ORDER BY LEVELNB ASC LIMIT 1";
String PROMOTION_LEVEL_LOWER = "SELECT ID FROM PROMOTION_LEVEL WHERE BRANCH = :branch AND LEVELNB < :levelNb ORDER BY LEVELNB DESC LIMIT 1";
String PROMOTION_LEVEL_LEVELNB = "SELECT LEVELNB FROM PROMOTION_LEVEL WHERE ID = :id";
String PROMOTION_LEVEL_SET_LEVELNB = "UPDATE PROMOTION_LEVEL SET LEVELNB = :levelNb WHERE ID = :id";
String PROMOTION_LEVEL_DELETE = "DELETE FROM PROMOTION_LEVEL WHERE ID = :id";
String PROMOTION_LEVEL_UPDATE_LEVEL_NB_AFTER_DELETE = "UPDATE PROMOTION_LEVEL SET LEVELNB = LEVELNB - 1 WHERE LEVELNB > :levelNb";
String PROMOTION_LEVEL_UPDATE = "UPDATE PROMOTION_LEVEL SET NAME = :name, DESCRIPTION = :description WHERE ID = :id";
String PROMOTION_LEVEL_AUTO_PROMOTE = "UPDATE PROMOTION_LEVEL SET AUTOPROMOTE = :flag WHERE ID = :id";
String PROMOTION_LEVEL_BY_BRANCH_AND_NAME = "SELECT * FROM PROMOTION_LEVEL WHERE BRANCH = :branch AND NAME = :name";
// Validation runs
String VALIDATION_RUN = "SELECT R.* FROM VALIDATION_RUN R WHERE R.ID = :id";
String VALIDATION_RUN_CREATE = "INSERT INTO VALIDATION_RUN (BUILD, VALIDATION_STAMP, DESCRIPTION, RUN_ORDER) VALUES (:build, :validationStamp, :description, :runOrder)";
String VALIDATION_RUN_FOR_BUILD_AND_STAMP = "SELECT * FROM VALIDATION_RUN WHERE BUILD = :build AND VALIDATION_STAMP = :validationStamp ORDER BY ID ASC";
String VALIDATION_RUN_LAST_FOR_BUILD_AND_STAMP = "SELECT * FROM VALIDATION_RUN WHERE BUILD = :build AND VALIDATION_STAMP = :validationStamp ORDER BY ID DESC LIMIT 1";
String VALIDATION_RUN_COUNT_FOR_BUILD_AND_STAMP = "SELECT COUNT(*) FROM VALIDATION_RUN WHERE BUILD = :build AND VALIDATION_STAMP = :validationStamp";
String VALIDATION_RUN_HISTORY = "(SELECT VR.ID AS VRID, VR.RUN_ORDER AS RUN_ORDER, B.ID AS BUILD, NULL AS STATUS, CONTENT, AUTHOR, AUTHOR_ID, COMMENT_TIMESTAMP AS EVENT_TIMESTAMP\n" +
"FROM COMMENT C\n" +
"INNER JOIN VALIDATION_RUN VR ON VR.ID = C.VALIDATION_RUN\n" +
"INNER JOIN BUILD B ON B.ID = VR.BUILD\n" +
"WHERE B.BRANCH = :branch AND VR.VALIDATION_STAMP = :validationStamp AND VR.ID <= :validationRun)\n" +
"UNION\n" +
"(SELECT VR.ID, VR.RUN_ORDER AS RUN_ORDER, B.ID AS BUILD, VRS.STATUS, VRS.DESCRIPTION AS CONTENT, VRS.AUTHOR, VRS.AUTHOR_ID, VRS.STATUS_TIMESTAMP AS EVENT_TIMESTAMP\n" +
"FROM VALIDATION_RUN_STATUS VRS\n" +
"INNER JOIN VALIDATION_RUN VR ON VR.ID = VRS.VALIDATION_RUN\n" +
"INNER JOIN BUILD B ON B.ID = VR.BUILD\n" +
"WHERE B.BRANCH = :branch AND VR.VALIDATION_STAMP = :validationStamp AND VR.ID <= :validationRun)\n" +
"ORDER BY BUILD DESC, RUN_ORDER DESC, EVENT_TIMESTAMP DESC\n" +
"LIMIT :count OFFSET :offset";
String VALIDATION_RUN_LAST_OF_BUILD_BY_VALIDATION_STAMP = "SELECT DISTINCT(BUILD) FROM VALIDATION_RUN WHERE VALIDATION_STAMP = :validationStamp ORDER BY BUILD DESC LIMIT :limit";
// Validation run statuses
String VALIDATION_RUN_STATUS_CREATE = "INSERT INTO VALIDATION_RUN_STATUS (VALIDATION_RUN, STATUS, DESCRIPTION, AUTHOR, AUTHOR_ID, STATUS_TIMESTAMP) VALUES (:validationRun, :status, :description, :author, :authorId, :statusTimestamp)";
String VALIDATION_RUN_STATUS_LAST = "SELECT * FROM VALIDATION_RUN_STATUS WHERE VALIDATION_RUN = :id ORDER BY ID DESC LIMIT 1";
String VALIDATION_RUN_STATUS_BY_NAME = "SELECT * FROM VALIDATION_RUN_STATUS WHERE UPPER(DESCRIPTION) LIKE :text";
String VALIDATION_RUN_STATUS_RENAME_AUTHOR = "UPDATE VALIDATION_RUN_STATUS SET AUTHOR = :name WHERE AUTHOR_ID = :id";
// Promoted runs
String PROMOTED_RUN_DELETE = "DELETE FROM PROMOTED_RUN WHERE PROMOTION_LEVEL = :promotionLevel AND BUILD = :build";
String PROMOTED_RUN_CREATE = "INSERT INTO PROMOTED_RUN (PROMOTION_LEVEL, BUILD, AUTHOR_ID, AUTHOR, CREATION, DESCRIPTION) VALUES (:promotionLevel, :build, :authorId, :author, :creation, :description)";
String PROMOTED_RUN = "SELECT * FROM PROMOTED_RUN WHERE BUILD = :build AND PROMOTION_LEVEL = :promotionLevel";
String PROMOTION_LEVEL_FOR_BUILD = "SELECT L.* FROM PROMOTION_LEVEL L, PROMOTED_RUN R WHERE R.PROMOTION_LEVEL = L.ID AND R.BUILD = :build ORDER BY L.LEVELNB";
String PROMOTED_EARLIEST_RUN = "SELECT BUILD FROM PROMOTED_RUN WHERE BUILD >= :build AND PROMOTION_LEVEL = :promotionLevel ORDER BY BUILD ASC LIMIT 1";
String PROMOTED_RUN_BY_PROMOTION_LEVEL = "SELECT * FROM PROMOTED_RUN WHERE PROMOTION_LEVEL = :promotionLevel ORDER BY BUILD DESC LIMIT :count OFFSET :offset";
String PROMOTED_RUN_BY_BUILD = "SELECT PR.* FROM PROMOTED_RUN PR INNER JOIN PROMOTION_LEVEL PL ON PL.ID = PR.PROMOTION_LEVEL WHERE PR.BUILD = :build ORDER BY PL.LEVELNB ";
String PROMOTED_RUN_REMOVE = "DELETE FROM PROMOTED_RUN WHERE BUILD = :build AND PROMOTION_LEVEL = :promotionLevel";
// Audit
String ENTITY_NAME = "SELECT %s FROM %s WHERE ID = :id";
String EVENT_VALUE_INSERT = "INSERT INTO EVENT_VALUES (EVENT, PROP_NAME, PROP_VALUE) VALUES (:id, :name, :value)";
String EVENT_VALUE_LIST = "SELECT PROP_NAME, PROP_VALUE FROM EVENT_VALUES WHERE EVENT = :id";
String EVENT = "SELECT * FROM EVENTS WHERE ID = :id";
String EVENTS_TO_SEND = "SELECT * FROM EVENTS WHERE SENT IS NULL OR SENT IS FALSE ORDER BY ID ASC";
String EVENT_SENT = "UPDATE EVENTS SET SENT = TRUE WHERE ID = :id";
String EVENTS_RENAME_AUTHOR = "UPDATE EVENTS SET AUTHOR = :name WHERE AUTHOR_ID = :id";
// Accounts
String ACCOUNT_AUTHENTICATE = "SELECT ID, NAME, FULLNAME, EMAIL, ROLENAME, MODE FROM ACCOUNTS WHERE MODE = 'builtin' AND NAME = :user AND PASSWORD = :password";
String ACCOUNT_ROLE = "SELECT ROLENAME FROM ACCOUNTS WHERE MODE = :mode AND NAME = :user";
String ACCOUNT_BY_NAME = "SELECT ID, NAME, FULLNAME, EMAIL, ROLENAME, MODE FROM ACCOUNTS WHERE MODE = :mode AND NAME = :user";
String ACCOUNT = "SELECT * FROM ACCOUNTS WHERE ID = :id";
String ACCOUNT_LIST = "SELECT ID, NAME, FULLNAME, EMAIL, ROLENAME, MODE FROM ACCOUNTS ORDER BY NAME";
String ACCOUNT_CREATE = "INSERT INTO ACCOUNTS (NAME, FULLNAME, EMAIL, ROLENAME, MODE, PASSWORD) VALUES (:name, :fullName, :email, :roleName, :mode, :password)";
String ACCOUNT_DELETE = "DELETE FROM ACCOUNTS WHERE ID = :id";
String ACCOUNT_UPDATE = "UPDATE ACCOUNTS SET NAME = :name, FULLNAME = :fullName, EMAIL = :email, ROLENAME = :roleName WHERE ID = :id";
String ACCOUNT_CHANGE_PASSWORD = "UPDATE ACCOUNTS SET PASSWORD = :newPassword WHERE ID = :id AND MODE = 'builtin' AND PASSWORD = :oldPassword";
// Configuration
String CONFIGURATION_GET = "SELECT VALUE FROM CONFIGURATION WHERE NAME = :name";
String CONFIGURATION_DELETE = "DELETE FROM CONFIGURATION WHERE NAME = :name";
String CONFIGURATION_INSERT = "INSERT INTO CONFIGURATION (NAME, VALUE) VALUES (:name, :value)";
// Comments
String COMMENT_CREATE = "INSERT INTO COMMENT (%s, CONTENT, AUTHOR, AUTHOR_ID, COMMENT_TIMESTAMP) VALUES (:id, :content, :author, :author_id, :comment_timestamp)";
String COMMENT_RENAME_AUTHOR = "UPDATE COMMENT SET AUTHOR = :name WHERE AUTHOR_ID = :id";
String COMMENT_FOR_ENTITY = "SELECT * FROM COMMENT WHERE %s = :id ORDER BY ID DESC LIMIT :count OFFSET :offset";
// Properties
String PROPERTY_DELETE = "DELETE FROM PROPERTIES WHERE %s = :entityId AND EXTENSION = :extension AND NAME = :name";
String PROPERTY_INSERT = "INSERT INTO PROPERTIES (EXTENSION, NAME, VALUE, %s) VALUES (:extension, :name, :value, :entityId)";
String PROPERTY_ALL = "SELECT * FROM PROPERTIES WHERE %s = :entityId ORDER BY EXTENSION, NAME";
String PROPERTY_VALUE = "SELECT * FROM PROPERTIES WHERE %s = :entityId AND EXTENSION = :extension AND NAME = :name";
// Subscriptions
String SUBSCRIPTION_DELETE = "DELETE FROM SUBSCRIPTION WHERE ACCOUNT = :account AND %s = :entityId";
String SUBSCRIPTION_CREATE = "INSERT INTO SUBSCRIPTION (ACCOUNT, %s) VALUES (:account, :entityId)";
String SUBSCRIPTION_BY_ACCOUNT = "SELECT * FROM SUBSCRIPTION WHERE ACCOUNT = :account";
// Filter on validation stamps
String VALIDATION_STAMP_SELECTION_EXISTS = "SELECT ID FROM VALIDATION_STAMP_SELECTION WHERE ACCOUNT = :account AND VALIDATION_STAMP = :validationStamp LIMIT 1";
String VALIDATION_STAMP_SELECTION_DELETE = "DELETE VALIDATION_STAMP_SELECTION WHERE ACCOUNT = :account AND VALIDATION_STAMP = :validationStamp";
String VALIDATION_STAMP_SELECTION_INSERT = "INSERT INTO VALIDATION_STAMP_SELECTION (ACCOUNT, VALIDATION_STAMP) VALUES (:account, :validationStamp)";
// Build cleanup
String BUILD_CLEANUP_DELETE = "DELETE FROM BUILD_CLEANUP WHERE BRANCH = :branch";
String BUILD_CLEANUP_INSERT = "INSERT INTO BUILD_CLEANUP (BRANCH, RETENTION) VALUES (:branch, :retention)";
String BUILD_CLEANUP_PROMOTION_INSERT = "INSERT INTO BUILD_CLEANUP_PROMOTION (BUILD_CLEANUP, PROMOTION_LEVEL) VALUES (:buildCleanup, :promotionLevel)";
String BUILD_CLEANUP_FIND_BY_BRANCH = "SELECT * FROM BUILD_CLEANUP WHERE BRANCH = :branch";
String BUILD_CLEANUP_PROMOTION_BY_ID = "SELECT PROMOTION_LEVEL FROM BUILD_CLEANUP_PROMOTION WHERE BUILD_CLEANUP = :id";
String BUILD_CLEANUP = "SELECT DISTINCT(B.ID)" +
"FROM BUILD B\n" +
"INNER JOIN EVENTS E ON E.BUILD = B.ID AND E.EVENT_TYPE = 'BUILD_CREATED'\n" +
"WHERE B.BRANCH = :branch\n" +
"AND DATEDIFF('DAY', E.EVENT_TIMESTAMP, :now) > :retention\n" +
"AND (SELECT COUNT(*) FROM PROMOTED_RUN PR WHERE PR.BUILD = B.ID AND PR.PROMOTION_LEVEL IN (%s)) = 0\n" +
"ORDER BY B.ID";
// Dashboards
String DASHBOARD_VALIDATION_STAMP_EXISTS = "SELECT VALIDATION_STAMP FROM DASHBOARD_VALIDATION_STAMP WHERE VALIDATION_STAMP = :validationStamp AND BRANCH = :branch";
String DASHBOARD_VALIDATION_STAMP_INSERT = "INSERT INTO DASHBOARD_VALIDATION_STAMP (BRANCH, VALIDATION_STAMP) VALUES (:branch, :validationStamp)";
String DASHBOARD_VALIDATION_STAMP_DELETE = "DELETE FROM DASHBOARD_VALIDATION_STAMP WHERE VALIDATION_STAMP = :validationStamp AND BRANCH = :branch";
} |
package jiconfont.swing;
import jiconfont.IconBuilder;
import jiconfont.IconCode;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.font.TextLayout;
import java.awt.image.BufferedImage;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
public class IconBuilderSwing
extends IconBuilder<IconBuilderSwing, Color, Float> {
public static IconBuilderSwing newIcon(IconCode icon) {
return new IconBuilderSwing(icon);
}
protected IconBuilderSwing(IconCode icon) {
super(icon);
setColor(Color.BLACK);
}
public final IconBuilderSwing setSize(int size) {
return setSize((float) size);
}
public final Icon buildIcon() {
return new ImageIcon(buildImage());
}
public final Image buildImage() {
return buildImage(Character.toString(getIcon().getUnicode()));
}
private BufferedImage buildImage(String text) {
Font font = buildFont();
JLabel label = new JLabel(text);
label.setFont(font);
Dimension dim = label.getPreferredSize();
label.setSize(dim);
int width = dim.width;
int height = dim.height;
BufferedImage bufImage =
new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
label.paint(bufImage.createGraphics());
return bufImage;
}
protected final Font buildFont() {
try {
Font font =
Font.createFont(Font.TRUETYPE_FONT, getIcon().getFontInputStream());
return font.deriveFont(getSize());
}
catch (Exception ex) {
Logger.getLogger(IconBuilderSwing.class.getName()).log(Level.SEVERE,
"Font load failure", ex);
}
return null;
}
@Override
protected Class<IconBuilderSwing> getIconFontClass() {
return IconBuilderSwing.class;
}
} |
package mcjty.efab.blocks.tank;
import mcjty.efab.blocks.GenericEFabMultiBlockPart;
import mcjty.efab.config.GeneralConfiguration;
import mcjty.efab.tools.FluidTools;
import mcjty.efab.tools.InventoryHelper;
import mcjty.lib.container.BaseBlock;
import mcjty.lib.container.EmptyContainer;
import mcjty.theoneprobe.api.TextStyleClass;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.block.properties.PropertyEnum;
import net.minecraft.block.state.BlockStateContainer;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.util.ITooltipFlag;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TextComponentString;
import net.minecraft.util.text.TextFormatting;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fml.client.registry.ClientRegistry;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import java.util.List;
public class TankBlock extends GenericEFabMultiBlockPart<TankTE, EmptyContainer> {
public static final AxisAlignedBB EMPTY = new AxisAlignedBB(0, 0, 0, 0, 0, 0);
public static final PropertyEnum<EnumTankState> STATE = PropertyEnum.create("state", EnumTankState.class, EnumTankState.values());
public TankBlock() {
super(Material.IRON, TankTE.class, EmptyContainer.class, TankItemBlock.class, "tank", false);
}
@Override
public RotationType getRotationType() {
return RotationType.HORIZROTATION;
}
@Override
public void addInformation(ItemStack stack, World playerIn, List<String> tooltip, ITooltipFlag advanced) {
super.addInformation(stack, playerIn, tooltip, advanced);
tooltip.add(TextFormatting.WHITE + "This tank can store " + TextFormatting.GREEN + GeneralConfiguration.tankCapacity + TextFormatting.WHITE + " mb");
tooltip.add(TextFormatting.WHITE + "Combine tanks by placing them");
tooltip.add(TextFormatting.WHITE + "on top of each other");
tooltip.add(TextFormatting.WHITE + "Used for " + TextFormatting.GREEN + "liquid" + TextFormatting.WHITE + " and "
+ TextFormatting.GREEN + "steam" + TextFormatting.WHITE + " crafting");
if (stack.hasTagCompound()) {
NBTTagCompound tagCompound = stack.getTagCompound();
FluidStack fluid = FluidStack.loadFluidStackFromNBT(tagCompound.getCompoundTag("fluid"));
tooltip.add(TextFormatting.GRAY + "Fluid: " + TextFormatting.BLUE + fluid.amount + "mb (" + fluid.getLocalizedName() + ")");
}
}
@SideOnly(Side.CLIENT)
@Override
public void initModel() {
super.initModel();
ClientRegistry.bindTileEntitySpecialRenderer(TankTE.class, new TankRenderer());
}
@Override
@SideOnly(Side.CLIENT)
public AxisAlignedBB getSelectedBoundingBox(IBlockState state, World worldIn, BlockPos pos) {
return EMPTY;
}
@Override
@SideOnly(Side.CLIENT)
public boolean shouldSideBeRendered(IBlockState state, IBlockAccess worldIn, BlockPos pos, EnumFacing side) {
return false;
}
@Override
public boolean isBlockNormalCube(IBlockState state) {
return false;
}
@Override
public boolean isOpaqueCube(IBlockState state) {
return false;
}
@Override
public boolean onBlockActivated(World world, BlockPos pos, IBlockState state, EntityPlayer player, EnumHand hand, EnumFacing side, float hitX, float hitY, float hitZ) {
if (!world.isRemote) {
ItemStack heldItem = player.getHeldItem(EnumHand.MAIN_HAND);
TileEntity te = world.getTileEntity(pos);
if (te instanceof TankTE) {
TankTE tankTE = (TankTE) te;
if (!heldItem.isEmpty()) {
if (FluidTools.isEmptyContainer(heldItem)) {
extractIntoContainer(player, tankTE);
return true;
} else if (FluidTools.isFilledContainer(heldItem)) {
fillFromContainer(player, world, tankTE);
return true;
}
}
FluidStack fluid = tankTE.getFluid();
if (fluid == null || fluid.amount <= 0) {
ITextComponent component = new TextComponentString("Tank is empty");
if (player instanceof EntityPlayer) {
player.sendStatusMessage(component, false);
} else {
player.sendMessage(component);
}
} else {
ITextComponent component = new TextComponentString("Tank contains " + fluid.amount + "mb of " + fluid.getLocalizedName());
if (player instanceof EntityPlayer) {
player.sendStatusMessage(component, false);
} else {
player.sendMessage(component);
}
}
}
}
return true;
}
private void fillFromContainer(EntityPlayer player, World world, TankTE tank) {
ItemStack heldItem = player.getHeldItem(EnumHand.MAIN_HAND);
if (heldItem.isEmpty()) {
return;
}
ItemStack container = heldItem.copy().splitStack(1);
FluidStack fluidStack = FluidTools.convertBucketToFluid(container);
if (fluidStack != null) {
int filled = tank.getHandler().fill(fluidStack, false);
if (filled == fluidStack.amount) {
// Success
tank.getHandler().fill(fluidStack, true);
if (!player.capabilities.isCreativeMode) {
heldItem.splitStack(1);
ItemStack emptyContainer = FluidTools.drainContainer(container);
mcjty.efab.tools.InventoryHelper.giveItemToPlayer(player, emptyContainer);
}
}
}
}
private void extractIntoContainer(EntityPlayer player, TankTE tank) {
FluidStack drained = tank.getHandler().drain(1, false);
if (drained != null) {
ItemStack heldItem = player.getHeldItem(EnumHand.MAIN_HAND);
if (heldItem.isEmpty()) {
return;
}
ItemStack container = heldItem.copy().splitStack(1);
int capacity = FluidTools.getCapacity(drained, container);
if (capacity != 0) {
drained = tank.getHandler().drain(capacity, false);
if (drained != null && drained.amount == capacity) {
tank.getHandler().drain(capacity, true);
ItemStack filledContainer = FluidTools.fillContainer(drained, container);
if (!filledContainer.isEmpty()) {
heldItem.splitStack(1);
InventoryHelper.giveItemToPlayer(player, filledContainer);
}
}
}
player.openContainer.detectAndSendChanges();
}
}
@Override
public void neighborChanged(IBlockState state, World world, BlockPos pos, Block blockIn, BlockPos fromPos) {
super.neighborChanged(state, world, pos, blockIn, fromPos);
// @todo: on 1.11 we could have used the position from which the update is coming
world.markBlockRangeForRenderUpdate(pos, pos);
}
@Override
public IBlockState getActualState(IBlockState state, IBlockAccess worldIn, BlockPos pos) {
// boolean half = isNeedToBeHalf(worldIn.getBlockState(pos.down()).getBlock());
boolean tankUp = worldIn.getBlockState(pos.up()).getBlock() == this;
boolean tankDown = worldIn.getBlockState(pos.down()).getBlock() == this;
EnumTankState s;
if (tankUp && tankDown) {
s = EnumTankState.MIDDLE;
} else if (tankUp) {
s = EnumTankState.BOTTOM;
} else if (tankDown) {
s = EnumTankState.TOP;
} else {
s = EnumTankState.FULL;
}
return state.withProperty(STATE, s);
}
@Override
protected BlockStateContainer createBlockState() {
return new BlockStateContainer(this, FACING_HORIZ, STATE);
}
} |
package mho.haskellesque.numbers;
import org.jetbrains.annotations.NotNull;
import java.math.BigInteger;
import java.util.Optional;
public class Numbers {
public static @NotNull Optional<Integer> readInteger(@NotNull String s) {
if (s.startsWith("0x") || s.startsWith("-0") || s.length() > 1 && s.charAt(0) == '0') return Optional.empty();
try {
return Optional.of(Integer.parseInt(s));
} catch (NumberFormatException e) {
return Optional.empty();
}
}
public static @NotNull Optional<BigInteger> readBigInteger(@NotNull String s) {
if (s.startsWith("0x") || s.startsWith("-0") || s.length() > 1 && s.charAt(0) == '0') return Optional.empty();
try {
return Optional.of(new BigInteger(s));
} catch (NumberFormatException e) {
return Optional.empty();
}
}
public static float successor(float f) {
if (Float.isNaN(f) || f > 0 && Float.isInfinite(f))
throw new ArithmeticException(f + " does not have a successor");
if (f == 0.0f) return Float.MIN_VALUE;
int floatBits = Float.floatToIntBits(f);
return Float.intBitsToFloat(f > 0 ? floatBits + 1 : floatBits - 1);
}
public static float predecessor(float f) {
if (Float.isNaN(f) || f < 0 && Float.isInfinite(f))
throw new ArithmeticException(f + " does not have a predecessor");
if (f == 0.0f) return -Float.MIN_VALUE;
int floatBits = Float.floatToIntBits(f);
return Float.intBitsToFloat(f > 0 ? floatBits - 1 : floatBits + 1);
}
public static double successor(double d) {
if (Double.isNaN(d) || d > 0 && Double.isInfinite(d))
throw new ArithmeticException(d + " does not have a successor");
if (d == 0.0) return Double.MIN_VALUE;
long doubleBits = Double.doubleToLongBits(d);
return Double.longBitsToDouble(d > 0 ? doubleBits + 1 : doubleBits - 1);
}
public static double predecessor(double d) {
if (Double.isNaN(d) || d < 0 && Double.isInfinite(d))
throw new ArithmeticException(d + " does not have a predecessor");
if (d == 0.0) return -Double.MIN_VALUE;
long doubleBits = Double.doubleToLongBits(d);
return Double.longBitsToDouble(d > 0 ? doubleBits - 1 : doubleBits + 1);
}
public static @NotNull Optional<Float> floatFromPair(int mantissa, int exponent) {
if ((mantissa & 1) == 0) {
return Optional.empty();
}
boolean sign = mantissa > 0;
BigInteger bigMantissa = BigInteger.valueOf(mantissa);
int bitLength = bigMantissa.bitLength();
int rawExp = bitLength + exponent - 1;
if (rawExp < -149) {
return Optional.empty();
}
BigInteger rawMantissa;
if (rawExp < -126) {
int padding = exponent + 149;
if (padding < 0) return Optional.empty();
rawMantissa = bigMantissa.shiftLeft(padding);
rawExp = 0;
} else {
int padding = 24 - bitLength;
if (padding < 0) return Optional.empty();
rawMantissa = bigMantissa.clearBit(bitLength - 1).shiftLeft(padding);
if (rawExp < -126 || rawExp > 127) return Optional.empty();
rawExp += 127;
}
int bits = rawExp;
bits <<= 23;
bits |= rawMantissa.intValue();
float f = Float.intBitsToFloat(bits);
return Optional.of(sign ? f : -f);
}
public static @NotNull Optional<Double> doubleFromPair(long mantissa, int exponent) {
if ((mantissa & 1) == 0) {
return Optional.empty();
}
boolean sign = mantissa > 0;
BigInteger bigMantissa = BigInteger.valueOf(mantissa);
int bitLength = bigMantissa.bitLength();
int rawExp = bitLength + exponent - 1;
if (rawExp < -1074) {
return Optional.empty();
}
BigInteger rawMantissa;
if (rawExp < -1022) {
int padding = exponent + 1074;
if (padding < 0) return Optional.empty();
rawMantissa = bigMantissa.shiftLeft(padding);
rawExp = 0;
} else {
int padding = 53 - bitLength;
if (padding < 0) return Optional.empty();
rawMantissa = bigMantissa.clearBit(bitLength - 1).shiftLeft(padding);
if (rawExp < -1022 || rawExp > 1023) return Optional.empty();
rawExp += 1023;
}
long bits = rawExp;
bits <<= 52;
bits |= rawMantissa.longValue();
double d = Double.longBitsToDouble(bits);
return Optional.of(sign ? d : -d);
}
} |
package edu.umd.cs.findbugs;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.StringTokenizer;
import org.apache.bcel.classfile.JavaClass;
import org.apache.bcel.classfile.Method;
import org.apache.bcel.generic.ConstantPoolGen;
import org.apache.bcel.generic.InstructionHandle;
import org.apache.bcel.generic.InvokeInstruction;
import org.apache.bcel.generic.MethodGen;
import edu.umd.cs.findbugs.ba.XField;
import edu.umd.cs.findbugs.ba.XMethod;
import edu.umd.cs.findbugs.ba.bcp.FieldVariable;
import edu.umd.cs.findbugs.visitclass.DismantleBytecode;
import edu.umd.cs.findbugs.visitclass.PreorderVisitor;
import edu.umd.cs.findbugs.xml.XMLAttributeList;
import edu.umd.cs.findbugs.xml.XMLOutput;
/**
* An instance of a bug pattern.
* A BugInstance consists of several parts:
* <p/>
* <ul>
* <li> the type, which is a string indicating what kind of bug it is;
* used as a key for the FindBugsMessages resource bundle
* <li> the priority; how likely this instance is to actually be a bug
* <li> a list of <em>annotations</em>
* </ul>
* <p/>
* The annotations describe classes, methods, fields, source locations,
* and other relevant context information about the bug instance.
* Every BugInstance must have at least one ClassAnnotation, which
* describes the class in which the instance was found. This is the
* "primary class annotation".
* <p/>
* <p> BugInstance objects are built up by calling a string of <code>add</code>
* methods. (These methods all "return this", so they can be chained).
* Some of the add methods are specialized to get information automatically from
* a BetterVisitor or DismantleBytecode object.
*
* @author David Hovemeyer
* @see BugAnnotation
*/
public class BugInstance implements Comparable, XMLWriteableWithMessages, Serializable, Cloneable {
private static final long serialVersionUID = 1L;
private String type;
private int priority;
private ArrayList<BugAnnotation> annotationList;
private int cachedHashCode;
private String annotationText;
private BugProperty propertyListHead, propertyListTail;
private String uniqueId;
private String activeIntervalCollection;
/**
* This value is used to indicate that the cached hashcode
* is invalid, and should be recomputed.
*/
private static final int INVALID_HASH_CODE = 0;
/**
* This value is used to indicate whether BugInstances should be reprioritized very low,
* when the BugPattern is marked as experimental
*/
private static boolean adjustExperimental = false;
/**
* Constructor.
*
* @param type the bug type
* @param priority the bug priority
*/
public BugInstance(String type, int priority) {
this.type = type;
this.priority = priority < Detector.HIGH_PRIORITY
? Detector.HIGH_PRIORITY : priority;
annotationList = new ArrayList<BugAnnotation>(4);
cachedHashCode = INVALID_HASH_CODE;
annotationText = "";
activeIntervalCollection = "";
if (adjustExperimental && isExperimental())
this.priority = Detector.EXP_PRIORITY;
}
//@Override
public Object clone() {
BugInstance dup;
try {
dup = (BugInstance) super.clone();
// Do deep copying of mutable objects
for (int i = 0; i < dup.annotationList.size(); ++i) {
dup.annotationList.set(i, (BugAnnotation) dup.annotationList.get(i).clone());
}
dup.propertyListHead = dup.propertyListTail = null;
for (Iterator<BugProperty> i = propertyIterator(); i.hasNext(); ) {
dup.addProperty((BugProperty) i.next().clone());
}
return dup;
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("impossible", e);
}
}
/**
* Create a new BugInstance.
* This is the constructor that should be used by Detectors.
*
* @param detector the Detector that is reporting the BugInstance
* @param type the bug type
* @param priority the bug priority
*/
public BugInstance(Detector detector, String type, int priority) {
this(type, priority);
if (detector != null) {
// Adjust priority if required
DetectorFactory factory =
DetectorFactoryCollection.instance().getFactoryByClassName(detector.getClass().getName());
if (factory != null) {
this.priority += factory.getPriorityAdjustment();
if (this.priority < 0)
this.priority = 0;
}
}
if (adjustExperimental && isExperimental())
this.priority = Detector.EXP_PRIORITY;
}
public static void setAdjustExperimental(boolean adjust) {
adjustExperimental = adjust;
}
/**
* Get the bug type.
*/
public String getType() {
return type;
}
/**
* Get the BugPattern.
*/
public BugPattern getBugPattern() {
return I18N.instance().lookupBugPattern(getType());
}
/**
* Get the bug priority.
*/
public int getPriority() {
return priority;
}
/**
* Set the bug priority.
*/
public void setPriority(int p) {
priority = p < Detector.HIGH_PRIORITY
? Detector.HIGH_PRIORITY : p;
}
/**
* Is this bug instance the result of an experimental detector?
*/
public boolean isExperimental() {
BugPattern pattern = I18N.instance().lookupBugPattern(type);
return (pattern != null) ? pattern.isExperimental() : false;
}
/**
* Get the primary class annotation, which indicates where the bug occurs.
*/
public ClassAnnotation getPrimaryClass() {
return (ClassAnnotation) findAnnotationOfType(ClassAnnotation.class);
}
/**
* Get the primary method annotation, which indicates where the bug occurs.
*/
public MethodAnnotation getPrimaryMethod() {
return (MethodAnnotation) findAnnotationOfType(MethodAnnotation.class);
}
/**
* Get the primary method annotation, which indicates where the bug occurs.
*/
public FieldAnnotation getPrimaryField() {
return (FieldAnnotation) findAnnotationOfType(FieldAnnotation.class);
}
/**
* Find the first BugAnnotation in the list of annotations
* that is the same type or a subtype as the given Class parameter.
*
* @param cls the Class parameter
* @return the first matching BugAnnotation of the given type,
* or null if there is no such BugAnnotation
*/
private BugAnnotation findAnnotationOfType(Class<? extends BugAnnotation> cls) {
for (Iterator<BugAnnotation> i = annotationIterator(); i.hasNext();) {
BugAnnotation annotation = i.next();
if (cls.isAssignableFrom(annotation.getClass()))
return annotation;
}
return null;
}
/**
* Get the primary source line annotation.
*
* @return the source line annotation, or null if there is
* no source line annotation
*/
public SourceLineAnnotation getPrimarySourceLineAnnotation() {
// Highest priority: return the first top level source line annotation
Iterator<BugAnnotation> i = annotationList.iterator();
while (i.hasNext()) {
BugAnnotation annotation = i.next();
if (annotation instanceof SourceLineAnnotation)
return (SourceLineAnnotation) annotation;
}
// Second priority: return the source line annotation describing the
// primary method
MethodAnnotation primaryMethodAnnotation = getPrimaryMethod();
if (primaryMethodAnnotation != null)
return primaryMethodAnnotation.getSourceLines();
else
return null;
}
/**
* Get an Iterator over all bug annotations.
*/
public Iterator<BugAnnotation> annotationIterator() {
return annotationList.iterator();
}
/**
* Get the abbreviation of this bug instance's BugPattern.
* This is the same abbreviation used by the BugCode which
* the BugPattern is a particular species of.
*/
public String getAbbrev() {
BugPattern pattern = I18N.instance().lookupBugPattern(getType());
return pattern != null ? pattern.getAbbrev() : "<unknown bug pattern>";
}
/**
* Set the user annotation text.
*
* @param annotationText the user annotation text
*/
public void setAnnotationText(String annotationText) {
this.annotationText = annotationText;
}
/**
* Get the user annotation text.
*
* @return the user annotation text
*/
public String getAnnotationText() {
return annotationText;
}
/**
* Determine whether or not the annotation text contains
* the given word.
*
* @param word the word
* @return true if the annotation text contains the word, false otherwise
*/
public boolean annotationTextContainsWord(String word) {
return getTextAnnotationWords().contains(word);
}
/**
* Get set of words in the text annotation.
*/
public Set<String> getTextAnnotationWords() {
HashSet<String> result = new HashSet<String>();
StringTokenizer tok = new StringTokenizer(annotationText, " \t\r\n\f.,:;-");
while (tok.hasMoreTokens()) {
result.add(tok.nextToken());
}
return result;
}
/**
* Get the BugInstance's unique id.
*
* @return the unique id, or null if no unique id has been assigned
*/
public String getUniqueId() {
return uniqueId;
}
/**
* Set the unique id of the BugInstance.
*
* @param uniqueId the unique id
*/
public void setUniqueId(String uniqueId) {
this.uniqueId = uniqueId;
}
/**
* Get the collection of TimestampIntervals indicating when this
* BugInstance is/was active. Note that modications made to the
* object returned will <em>not</em> affect the BugInstance.
*
* @return the TimestampIntervalCollection
*/
public TimestampIntervalCollection getActiveIntervalCollection() {
try {
return TimestampIntervalCollection.decode(activeIntervalCollection);
} catch (InvalidTimestampIntervalException e) {
return new TimestampIntervalCollection();
}
}
/**
* Set the collection of TimestampIntervals indicating when this
* BugInstance is/was active.
*
* @param collection the TimestampIntervalCollection
*/
public void setActiveIntervalCollection(TimestampIntervalCollection collection) {
this.activeIntervalCollection = TimestampIntervalCollection.encode(collection);
}
private class BugPropertyIterator implements Iterator<BugProperty> {
private BugProperty prev, cur;
private boolean removed;
/* (non-Javadoc)
* @see java.util.Iterator#hasNext()
*/
public boolean hasNext() {
return findNext() != null;
}
/* (non-Javadoc)
* @see java.util.Iterator#next()
*/
public BugProperty next() {
BugProperty next = findNext();
if (next == null)
throw new NoSuchElementException();
prev = cur;
cur = next;
removed = false;
return cur;
}
/* (non-Javadoc)
* @see java.util.Iterator#remove()
*/
public void remove() {
if (cur == null || removed)
throw new IllegalStateException();
if (prev == null) {
propertyListHead = cur.getNext();
} else {
prev.setNext(cur.getNext());
}
if (cur == propertyListTail) {
propertyListTail = prev;
}
removed = true;
}
private BugProperty findNext() {
return cur == null ? propertyListHead : cur.getNext();
}
};
/**
* Get value of given property.
*
* @param name name of the property to get
* @return the value of the named property, or null if
* the property has not been set
*/
public String getProperty(String name) {
BugProperty prop = lookupProperty(name);
return prop != null ? prop.getValue() : null;
}
/**
* Get value of given property, returning given default
* value if the property has not been set.
*
* @param name name of the property to get
* @param defaultValue default value to return if propery is not set
* @return the value of the named property, or the default
* value if the property has not been set
*/
public String getProperty(String name, String defaultValue) {
String value = getProperty(name);
return value != null ? value : defaultValue;
}
/**
* Get an Iterator over the properties defined in this BugInstance.
*
* @return Iterator over properties
*/
public Iterator<BugProperty> propertyIterator() {
return new BugPropertyIterator();
}
/**
* Set value of given property.
*
* @param name name of the property to set
* @param value the value of the property
* @return this object, so calls can be chained
*/
public BugInstance setProperty(String name, String value) {
BugProperty prop = lookupProperty(name);
if (prop != null) {
prop.setValue(value);
} else {
prop = new BugProperty(name, value);
addProperty(prop);
}
return this;
}
/**
* Look up a property by name.
*
* @param name name of the property to look for
* @return the BugProperty with the given name,
* or null if the property has not been set
*/
public BugProperty lookupProperty(String name) {
BugProperty prop = propertyListHead;
while (prop != null) {
if (prop.getName().equals(name))
break;
prop = prop.getNext();
}
return prop;
}
/**
* Delete property with given name.
*
* @param name name of the property to delete
* @return true if a property with that name was deleted,
* or false if there is no such property
*/
public boolean deleteProperty(String name) {
BugProperty prev = null;
BugProperty prop = propertyListHead;
while (prop != null) {
if (prop.getName().equals(name))
break;
prev = prop;
prop = prop.getNext();
}
if (prop != null) {
if (prev != null) {
// Deleted node in interior or at tail of list
prev.setNext(prop.getNext());
} else {
// Deleted node at head of list
propertyListHead = prop.getNext();
}
if (prop.getNext() == null) {
// Deleted node at end of list
propertyListTail = prev;
}
return true;
} else {
// No such property
return false;
}
}
private void addProperty(BugProperty prop) {
if (propertyListTail != null) {
propertyListTail.setNext(prop);
propertyListTail = prop;
} else {
propertyListHead = propertyListTail = prop;
}
prop.setNext(null);
}
/**
* Add a Collection of BugAnnotations.
*
* @param annotationCollection Collection of BugAnnotations
*/
public void addAnnotations(Collection<BugAnnotation> annotationCollection) {
for (BugAnnotation annotation : annotationCollection) {
add(annotation);
}
}
/**
* Add a class annotation and a method annotation for the class and method
* which the given visitor is currently visiting.
*
* @param visitor the BetterVisitor
* @return this object
*/
public BugInstance addClassAndMethod(PreorderVisitor visitor) {
addClass(visitor);
addMethod(visitor);
return this;
}
/**
* Add class and method annotations for given method.
*
* @param methodAnnotation the method
* @return this object
*/
public BugInstance addClassAndMethod(MethodAnnotation methodAnnotation) {
addClass(methodAnnotation.getClassName());
addMethod(methodAnnotation);
return this;
}
/**
* Add class and method annotations for given method.
*
* @param methodGen the method
* @param sourceFile source file the method is defined in
* @return this object
*/
public BugInstance addClassAndMethod(MethodGen methodGen, String sourceFile) {
addClass(methodGen.getClassName());
addMethod(methodGen, sourceFile);
return this;
}
/**
* Add a class annotation. If this is the first class annotation added,
* it becomes the primary class annotation.
*
* @param className the name of the class
* @return this object
*/
public BugInstance addClass(String className) {
ClassAnnotation classAnnotation = new ClassAnnotation(className);
add(classAnnotation);
return this;
}
/**
* Add a class annotation. If this is the first class annotation added,
* it becomes the primary class annotation.
*
* @param jclass the JavaClass object for the class
* @return this object
*/
public BugInstance addClass(JavaClass jclass) {
addClass(jclass.getClassName());
return this;
}
/**
* Add a class annotation for the class that the visitor is currently visiting.
*
* @param visitor the BetterVisitor
* @return this object
*/
public BugInstance addClass(PreorderVisitor visitor) {
String className = visitor.getDottedClassName();
addClass(className);
return this;
}
/**
* Add a class annotation for the superclass of the class the visitor
* is currently visiting.
*
* @param visitor the BetterVisitor
* @return this object
*/
public BugInstance addSuperclass(PreorderVisitor visitor) {
String className = visitor.getSuperclassName();
addClass(className);
return this;
}
/**
* Add a field annotation.
*
* @param className name of the class containing the field
* @param fieldName the name of the field
* @param fieldSig type signature of the field
* @param isStatic whether or not the field is static
* @return this object
*/
public BugInstance addField(String className, String fieldName, String fieldSig, boolean isStatic) {
addField(new FieldAnnotation(className, fieldName, fieldSig, isStatic));
return this;
}
/**
* Add a field annotation
*
* @param fieldAnnotation the field annotation
* @return this object
*/
public BugInstance addField(FieldAnnotation fieldAnnotation) {
add(fieldAnnotation);
return this;
}
/**
* Add a field annotation for a FieldVariable matched in a ByteCodePattern.
*
* @param field the FieldVariable
* @return this object
*/
public BugInstance addField(FieldVariable field) {
return addField(field.getClassName(), field.getFieldName(), field.getFieldSig(), field.isStatic());
}
/**
* Add a field annotation for an XField.
*
* @param xfield the XField
* @return this object
*/
public BugInstance addField(XField xfield) {
return addField(xfield.getClassName(), xfield.getName(), xfield.getSignature(), xfield.isStatic());
}
/**
* Add a field annotation for the field which has just been accessed
* by the method currently being visited by given visitor.
* Assumes that a getfield/putfield or getstatic/putstatic
* has just been seen.
*
* @param visitor the DismantleBytecode object
* @return this object
*/
public BugInstance addReferencedField(DismantleBytecode visitor) {
FieldAnnotation f = FieldAnnotation.fromReferencedField(visitor);
addField(f);
return this;
}
/**
* Add a field annotation for the field referenced by the FieldAnnotation parameter
*/
public BugInstance addReferencedField(FieldAnnotation fa) {
addField(fa);
return this;
}
/**
* Add a field annotation for the field which is being visited by
* given visitor.
*
* @param visitor the visitor
* @return this object
*/
public BugInstance addVisitedField(PreorderVisitor visitor) {
FieldAnnotation f = FieldAnnotation.fromVisitedField(visitor);
addField(f);
return this;
}
/**
* Add a method annotation. If this is the first method annotation added,
* it becomes the primary method annotation.
*
* @param className name of the class containing the method
* @param methodName name of the method
* @param methodSig type signature of the method
* @return this object
*/
public BugInstance addMethod(String className, String methodName, String methodSig) {
addMethod(new MethodAnnotation(className, methodName, methodSig));
return this;
}
/**
* Add a method annotation. If this is the first method annotation added,
* it becomes the primary method annotation.
* If the method has source line information, then a SourceLineAnnotation
* is added to the method.
*
* @param methodGen the MethodGen object for the method
* @param sourceFile source file method is defined in
* @return this object
*/
public BugInstance addMethod(MethodGen methodGen, String sourceFile) {
MethodAnnotation methodAnnotation =
new MethodAnnotation(methodGen.getClassName(), methodGen.getName(), methodGen.getSignature());
addMethod(methodAnnotation);
addSourceLinesForMethod(methodAnnotation, SourceLineAnnotation.fromVisitedMethod(methodGen, sourceFile));
return this;
}
/**
* Add a method annotation. If this is the first method annotation added,
* it becomes the primary method annotation.
* If the method has source line information, then a SourceLineAnnotation
* is added to the method.
*
* @param javaClass the class the method is defined in
* @param method the method
* @return this object
*/
public BugInstance addMethod(JavaClass javaClass, Method method) {
MethodAnnotation methodAnnotation =
new MethodAnnotation(javaClass.getClassName(), method.getName(), method.getSignature());
SourceLineAnnotation methodSourceLines = SourceLineAnnotation.forEntireMethod(
javaClass,
method);
methodAnnotation.setSourceLines(methodSourceLines);
addMethod(methodAnnotation);
return this;
}
/**
* Add a method annotation for the method which the given visitor is currently visiting.
* If the method has source line information, then a SourceLineAnnotation
* is added to the method.
*
* @param visitor the BetterVisitor
* @return this object
*/
public BugInstance addMethod(PreorderVisitor visitor) {
MethodAnnotation methodAnnotation = MethodAnnotation.fromVisitedMethod(visitor);
addMethod(methodAnnotation);
addSourceLinesForMethod(methodAnnotation, SourceLineAnnotation.fromVisitedMethod(visitor));
return this;
}
/**
* Add a method annotation for the method which has been called
* by the method currently being visited by given visitor.
* Assumes that the visitor has just looked at an invoke instruction
* of some kind.
*
* @param visitor the DismantleBytecode object
* @return this object
*/
public BugInstance addCalledMethod(DismantleBytecode visitor) {
String className = visitor.getDottedClassConstantOperand();
String methodName = visitor.getNameConstantOperand();
String methodSig = visitor.getDottedSigConstantOperand();
addMethod(className, methodName, methodSig);
describe("METHOD_CALLED");
return this;
}
/**
* Add a method annotation.
*
* @return this object
*/
public BugInstance addCalledMethod(String className, String methodName, String methodSig) {
addMethod(className, methodName, methodSig);
describe("METHOD_CALLED");
return this;
}
/**
* Add a method annotation for the method which is called by given
* instruction.
*
* @param methodGen the method containing the call
* @param inv the InvokeInstruction
* @return this object
*/
public BugInstance addCalledMethod(MethodGen methodGen, InvokeInstruction inv) {
ConstantPoolGen cpg = methodGen.getConstantPool();
String className = inv.getClassName(cpg);
String methodName = inv.getMethodName(cpg);
String methodSig = inv.getSignature(cpg);
addMethod(className, methodName, methodSig);
describe("METHOD_CALLED");
return this;
}
/**
* Add a MethodAnnotation from an XMethod.
*
* @param xmethod the XMethod
* @return this object
*/
public BugInstance addMethod(XMethod xmethod) {
addMethod(MethodAnnotation.fromXMethod(xmethod));
return this;
}
/**
* Add a method annotation. If this is the first method annotation added,
* it becomes the primary method annotation.
*
* @param methodAnnotation the method annotation
* @return this object
*/
public BugInstance addMethod(MethodAnnotation methodAnnotation) {
add(methodAnnotation);
return this;
}
/**
* Add an integer annotation.
*
* @param value the integer value
* @return this object
*/
public BugInstance addInt(int value) {
add(new IntAnnotation(value));
return this;
}
/**
* Add a source line annotation.
*
* @param sourceLine the source line annotation
* @return this object
*/
public BugInstance addSourceLine(SourceLineAnnotation sourceLine) {
add(sourceLine);
return this;
}
/**
* Add a source line annotation for instruction whose PC is given
* in the method that the given visitor is currently visiting.
* Note that if the method does not have line number information, then
* no source line annotation will be added.
*
* @param visitor a BetterVisitor that is currently visiting the method
* @param pc bytecode offset of the instruction
* @return this object
*/
public BugInstance addSourceLine(PreorderVisitor visitor, int pc) {
SourceLineAnnotation sourceLineAnnotation = SourceLineAnnotation.fromVisitedInstruction(visitor, pc);
if (sourceLineAnnotation != null)
add(sourceLineAnnotation);
return this;
}
/**
* Add a source line annotation for the given instruction in the given method.
* Note that if the method does not have line number information, then
* no source line annotation will be added.
*
* @param methodGen the method being visited
* @param sourceFile source file the method is defined in
* @param handle the InstructionHandle containing the visited instruction
* @return this object
*/
public BugInstance addSourceLine(MethodGen methodGen, String sourceFile, InstructionHandle handle) {
SourceLineAnnotation sourceLineAnnotation = SourceLineAnnotation.fromVisitedInstruction(methodGen, sourceFile, handle);
if (sourceLineAnnotation != null)
add(sourceLineAnnotation);
return this;
}
/**
* Add a source line annotation describing a range of instructions.
*
* @param methodGen the method
* @param sourceFile source file the method is defined in
* @param start the start instruction in the range
* @param end the end instruction in the range (inclusive)
* @return this object
*/
public BugInstance addSourceLine(MethodGen methodGen, String sourceFile, InstructionHandle start, InstructionHandle end) {
// Make sure start and end are really in the right order.
if (start.getPosition() > end.getPosition()) {
InstructionHandle tmp = start;
start = end;
end = tmp;
}
SourceLineAnnotation sourceLineAnnotation = SourceLineAnnotation.fromVisitedInstructionRange(methodGen, sourceFile, start, end);
if (sourceLineAnnotation != null)
add(sourceLineAnnotation);
return this;
}
/**
* Add a source line annotation describing the
* source line numbers for a range of instructions in the method being
* visited by the given visitor.
* Note that if the method does not have line number information, then
* no source line annotation will be added.
*
* @param visitor a BetterVisitor which is visiting the method
* @param startPC the bytecode offset of the start instruction in the range
* @param endPC the bytecode offset of the end instruction in the range
* @return this object
*/
public BugInstance addSourceLineRange(PreorderVisitor visitor, int startPC, int endPC) {
SourceLineAnnotation sourceLineAnnotation = SourceLineAnnotation.fromVisitedInstructionRange(visitor, startPC, endPC);
if (sourceLineAnnotation != null)
add(sourceLineAnnotation);
return this;
}
/**
* Add a source line annotation for instruction currently being visited
* by given visitor.
* Note that if the method does not have line number information, then
* no source line annotation will be added.
*
* @param visitor a DismantleBytecode visitor that is currently visiting the instruction
* @return this object
*/
public BugInstance addSourceLine(DismantleBytecode visitor) {
SourceLineAnnotation sourceLineAnnotation = SourceLineAnnotation.fromVisitedInstruction(visitor);
if (sourceLineAnnotation != null)
add(sourceLineAnnotation);
return this;
}
/**
* Add a non-specific source line annotation.
* This will result in the entire source file being displayed.
*
* @param className the class name
* @param sourceFile the source file name
* @return this object
*/
public BugInstance addUnknownSourceLine(String className, String sourceFile) {
SourceLineAnnotation sourceLineAnnotation = SourceLineAnnotation.createUnknown(className, sourceFile);
if (sourceLineAnnotation != null)
add(sourceLineAnnotation);
return this;
}
/**
* Format a string describing this bug instance.
*
* @return the description
*/
public String getMessage() {
String pattern = I18N.instance().getMessage(type);
FindBugsMessageFormat format = new FindBugsMessageFormat(pattern);
return format.format((BugAnnotation[]) annotationList.toArray(new BugAnnotation[annotationList.size()]));
}
/**
* Add a description to the most recently added bug annotation.
*
* @param description the description to add
* @return this object
*/
public BugInstance describe(String description) {
annotationList.get(annotationList.size() - 1).setDescription(description);
return this;
}
/**
* Convert to String.
* This method returns the "short" message describing the bug,
* as opposed to the longer format returned by getMessage().
* The short format is appropriate for the tree view in a GUI,
* where the annotations are listed separately as part of the overall
* bug instance.
*/
public String toString() {
return I18N.instance().getShortMessage(type);
}
public void writeXML(XMLOutput xmlOutput) throws IOException {
writeXML(xmlOutput, false);
}
public void writeXML(XMLOutput xmlOutput, boolean addMessages) throws IOException {
XMLAttributeList attributeList = new XMLAttributeList()
.addAttribute("type", type)
.addAttribute("priority", String.valueOf(priority));
BugPattern pattern = getBugPattern();
if (pattern != null) {
// The bug abbreviation and pattern category are
// emitted into the XML for informational purposes only.
// (The information is redundant, but might be useful
// for processing tools that want to make sense of
// bug instances without looking at the plugin descriptor.)
attributeList.addAttribute("abbrev", pattern.getAbbrev());
attributeList.addAttribute("category", pattern.getCategory());
}
// Add a uid attribute, if we have a unique id.
if (getUniqueId() != null) {
attributeList.addAttribute("uid", getUniqueId());
}
// Add active interval collection.
if (activeIntervalCollection != null) {
attributeList.addAttribute("active", activeIntervalCollection);
}
xmlOutput.openTag(ELEMENT_NAME, attributeList);
if (!annotationText.equals("")) {
xmlOutput.openTag("UserAnnotation");
xmlOutput.writeCDATA(annotationText);
xmlOutput.closeTag("UserAnnotation");
}
if (addMessages) {
BugPattern bugPattern = getBugPattern();
xmlOutput.openTag("ShortMessage");
xmlOutput.writeText(bugPattern != null ? bugPattern.getShortDescription() : this.toString());
xmlOutput.closeTag("ShortMessage");
xmlOutput.openTag("LongMessage");
xmlOutput.writeText(this.getMessage());
xmlOutput.closeTag("LongMessage");
}
for (Iterator<BugAnnotation> i = annotationList.iterator(); i.hasNext();) {
BugAnnotation annotation = i.next();
annotation.writeXML(xmlOutput, addMessages);
}
if (propertyListHead != null) {
BugProperty prop = propertyListHead;
while (prop != null) {
prop.writeXML(xmlOutput);
prop = prop.getNext();
}
}
xmlOutput.closeTag(ELEMENT_NAME);
}
private static final String ELEMENT_NAME = "BugInstance";
private static final String USER_ANNOTATION_ELEMENT_NAME = "UserAnnotation";
void add(BugAnnotation annotation) {
if (annotation == null)
throw new IllegalStateException("Missing BugAnnotation!");
// Add to list
annotationList.add(annotation);
// This object is being modified, so the cached hashcode
// must be invalidated
cachedHashCode = INVALID_HASH_CODE;
}
private void addSourceLinesForMethod(MethodAnnotation methodAnnotation, SourceLineAnnotation sourceLineAnnotation) {
if (sourceLineAnnotation != null) {
// Note: we don't add the source line annotation directly to
// the bug instance. Instead, we stash it in the MethodAnnotation.
// It is much more useful there, and it would just be distracting
// if it were displayed in the UI, since it would compete for attention
// with the actual bug location source line annotation (which is much
// more important and interesting).
methodAnnotation.setSourceLines(sourceLineAnnotation);
}
}
public int hashCode() {
if (cachedHashCode == INVALID_HASH_CODE) {
int hashcode = type.hashCode() + priority;
Iterator<BugAnnotation> i = annotationIterator();
while (i.hasNext())
hashcode += i.next().hashCode();
if (hashcode == INVALID_HASH_CODE)
hashcode = INVALID_HASH_CODE+1;
cachedHashCode = hashcode;
}
return cachedHashCode;
}
public boolean equals(Object o) {
if (!(o instanceof BugInstance))
return false;
BugInstance other = (BugInstance) o;
if (!type.equals(other.type) || priority != other.priority)
return false;
if (annotationList.size() != other.annotationList.size())
return false;
int numAnnotations = annotationList.size();
for (int i = 0; i < numAnnotations; ++i) {
BugAnnotation lhs = annotationList.get(i);
BugAnnotation rhs = other.annotationList.get(i);
if (!lhs.equals(rhs))
return false;
}
return true;
}
public int compareTo(Object o) {
BugInstance other = (BugInstance) o;
int cmp;
cmp = type.compareTo(other.type);
if (cmp != 0)
return cmp;
cmp = priority - other.priority;
if (cmp != 0)
return cmp;
// Compare BugAnnotations lexicographically
int pfxLen = Math.min(annotationList.size(), other.annotationList.size());
for (int i = 0; i < pfxLen; ++i) {
BugAnnotation lhs = annotationList.get(i);
BugAnnotation rhs = other.annotationList.get(i);
cmp = lhs.compareTo(rhs);
if (cmp != 0)
return cmp;
}
// All elements in prefix were the same,
// so use number of elements to decide
return annotationList.size() - other.annotationList.size();
}
}
// vim:ts=4 |
package mytown.proxies;
import mytown.config.Config;
import mytown.core.Localization;
import mytown.util.Constants;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
public class LocalizationProxy {
private static Logger logger = LogManager.getLogger("MyTown2.Localization");
private static Localization localization;
/**
* Loads the {@link Localization}. First tries to load it from config/MyTown/Localization, then the classpath, then loads en_US in its place
*/
public static void load() {
try {
InputStream is = null;
File file = new File(Constants.CONFIG_FOLDER + "/localization/" + Config.localization + ".lang");
if (file.exists()) {
is = new FileInputStream(file);
}
if (is == null) {
is = LocalizationProxy.class.getResourceAsStream("/localization/" + Config.localization + ".lang");
}
if (is == null) {
is = LocalizationProxy.class.getResourceAsStream("/localization/en_US.lang");
logger.warn("Reverting to en_US.lang because {} does not exist!", Config.localization + ".lang");
}
LocalizationProxy.localization = new Localization(new InputStreamReader(is));
LocalizationProxy.localization.load();
} catch (Exception ex) {
logger.warn("Failed to load localization!", ex);
}
}
public static Localization getLocalization() {
return LocalizationProxy.localization;
}
} |
package edu.umd.cs.findbugs;
import java.io.IOException;
import java.io.Serializable;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.StringTokenizer;
import org.apache.bcel.Constants;
import org.apache.bcel.classfile.JavaClass;
import org.apache.bcel.classfile.Method;
import org.apache.bcel.generic.ConstantPoolGen;
import org.apache.bcel.generic.InstructionHandle;
import org.apache.bcel.generic.InvokeInstruction;
import org.apache.bcel.generic.MethodGen;
import org.apache.bcel.generic.Type;
import org.objectweb.asm.tree.ClassNode;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.annotations.NonNull;
import edu.umd.cs.findbugs.annotations.Nullable;
import edu.umd.cs.findbugs.ba.AnalysisContext;
import edu.umd.cs.findbugs.ba.ClassContext;
import edu.umd.cs.findbugs.ba.Hierarchy2;
import edu.umd.cs.findbugs.ba.JavaClassAndMethod;
import edu.umd.cs.findbugs.ba.Location;
import edu.umd.cs.findbugs.ba.XFactory;
import edu.umd.cs.findbugs.ba.XField;
import edu.umd.cs.findbugs.ba.XMethod;
import edu.umd.cs.findbugs.ba.bcp.FieldVariable;
import edu.umd.cs.findbugs.classfile.CheckedAnalysisException;
import edu.umd.cs.findbugs.classfile.ClassDescriptor;
import edu.umd.cs.findbugs.classfile.FieldDescriptor;
import edu.umd.cs.findbugs.classfile.Global;
import edu.umd.cs.findbugs.classfile.IAnalysisCache;
import edu.umd.cs.findbugs.classfile.MethodDescriptor;
import edu.umd.cs.findbugs.util.ClassName;
import edu.umd.cs.findbugs.visitclass.DismantleBytecode;
import edu.umd.cs.findbugs.visitclass.PreorderVisitor;
import edu.umd.cs.findbugs.xml.XMLAttributeList;
import edu.umd.cs.findbugs.xml.XMLOutput;
/**
* An instance of a bug pattern.
* A BugInstance consists of several parts:
* <p/>
* <ul>
* <li> the type, which is a string indicating what kind of bug it is;
* used as a key for the FindBugsMessages resource bundle
* <li> the priority; how likely this instance is to actually be a bug
* <li> a list of <em>annotations</em>
* </ul>
* <p/>
* The annotations describe classes, methods, fields, source locations,
* and other relevant context information about the bug instance.
* Every BugInstance must have at least one ClassAnnotation, which
* describes the class in which the instance was found. This is the
* "primary class annotation".
* <p/>
* <p> BugInstance objects are built up by calling a string of <code>add</code>
* methods. (These methods all "return this", so they can be chained).
* Some of the add methods are specialized to get information automatically from
* a BetterVisitor or DismantleBytecode object.
*
* @author David Hovemeyer
* @see BugAnnotation
*/
public class BugInstance implements Comparable<BugInstance>, XMLWriteableWithMessages, Serializable, Cloneable {
private static final long serialVersionUID = 1L;
private String type;
private int priority;
private ArrayList<BugAnnotation> annotationList;
private int cachedHashCode;
private @CheckForNull BugDesignation userDesignation;
private BugProperty propertyListHead, propertyListTail;
private String uniqueId;
private String oldInstanceHash;
private String instanceHash;
private int instanceOccurrenceNum;
private int instanceOccurrenceMax;
/*
* The following fields are used for tracking Bug instances across multiple versions of software.
* They are meaningless in a BugCollection for just one version of software.
*/
private long firstVersion = 0;
private long lastVersion = -1;
private boolean introducedByChangeOfExistingClass;
private boolean removedByChangeOfPersistingClass;
/**
* This value is used to indicate that the cached hashcode
* is invalid, and should be recomputed.
*/
private static final int INVALID_HASH_CODE = 0;
/**
* This value is used to indicate whether BugInstances should be reprioritized very low,
* when the BugPattern is marked as experimental
*/
private static boolean adjustExperimental = false;
private static Set<String> missingBugTypes = Collections.synchronizedSet(new HashSet<String>());
/**
* Constructor.
*
* @param type the bug type
* @param priority the bug priority
*/
public BugInstance(String type, int priority) {
this.type = type;
this.priority = priority;
annotationList = new ArrayList<BugAnnotation>(4);
cachedHashCode = INVALID_HASH_CODE;
BugPattern p = I18N.instance().lookupBugPattern(type);
if (p == null) {
if (missingBugTypes.add(type)) {
String msg = "Can't find definition of bug type " + type;
AnalysisContext.logError(msg, new IllegalArgumentException(msg));
}
} else
this.priority += p.getPriorityAdjustment();
if (adjustExperimental && isExperimental())
this.priority = Detector.EXP_PRIORITY;
boundPriority();
}
private void boundPriority() {
priority = boundedPriority(priority);
}
@Override
public Object clone() {
BugInstance dup;
try {
dup = (BugInstance) super.clone();
// Do deep copying of mutable objects
for (int i = 0; i < dup.annotationList.size(); ++i) {
dup.annotationList.set(i, (BugAnnotation) dup.annotationList.get(i).clone());
}
dup.propertyListHead = dup.propertyListTail = null;
for (Iterator<BugProperty> i = propertyIterator(); i.hasNext(); ) {
dup.addProperty((BugProperty) i.next().clone());
}
return dup;
} catch (CloneNotSupportedException e) {
throw new AssertionError(e);
}
}
/**
* Create a new BugInstance.
* This is the constructor that should be used by Detectors.
*
* @param detector the Detector that is reporting the BugInstance
* @param type the bug type
* @param priority the bug priority
*/
public BugInstance(Detector detector, String type, int priority) {
this(type, priority);
if (detector != null) {
// Adjust priority if required
DetectorFactory factory =
DetectorFactoryCollection.instance().getFactoryByClassName(detector.getClass().getName());
if (factory != null) {
this.priority += factory.getPriorityAdjustment();
boundPriority();
}
}
}
/**
* Create a new BugInstance.
* This is the constructor that should be used by Detectors.
*
* @param detector the Detector2 that is reporting the BugInstance
* @param type the bug type
* @param priority the bug priority
*/
public BugInstance(Detector2 detector, String type, int priority) {
this(type, priority);
if (detector != null) {
// Adjust priority if required
DetectorFactory factory =
DetectorFactoryCollection.instance().getFactoryByClassName(detector.getDetectorClassName());
if (factory != null) {
this.priority += factory.getPriorityAdjustment();
boundPriority();
}
}
}
public static void setAdjustExperimental(boolean adjust) {
adjustExperimental = adjust;
}
/**
* Get the bug type.
*/
public String getType() {
return type;
}
/**
* Get the BugPattern.
*/
public @NonNull BugPattern getBugPattern() {
BugPattern result = I18N.instance().lookupBugPattern(getType());
if (result != null) return result;
AnalysisContext.logError("Unable to find description of bug pattern " + getType());
result = I18N.instance().lookupBugPattern("UNKNOWN");
if (result != null) return result;
return BugPattern.REALLY_UNKNOWN;
}
/**
* Get the bug priority.
*/
public int getPriority() {
return priority;
}
/**
* Get a string describing the bug priority and type.
* e.g. "High Priority Correctness"
* @return a string describing the bug priority and type
*/
public String getPriorityTypeString()
{
String priorityString = getPriorityString();
BugPattern bugPattern = this.getBugPattern();
//then get the category and put everything together
String categoryString;
if (bugPattern == null) categoryString = "Unknown category for " + getType();
else categoryString = I18N.instance().getBugCategoryDescription(bugPattern.getCategory());
return priorityString + " Priority " + categoryString;
//TODO: internationalize the word "Priority"
}
public String getPriorityTypeAbbreviation()
{
String priorityString = getPriorityAbbreviation();
return priorityString + " " + getCategoryAbbrev();
}
public String getCategoryAbbrev() {
BugPattern bugPattern = getBugPattern();
if (bugPattern == null) return "?";
return bugPattern.getCategoryAbbrev();
}
public String getPriorityString() {
//first, get the priority
int value = this.getPriority();
String priorityString;
if (value == Detector.HIGH_PRIORITY)
priorityString = edu.umd.cs.findbugs.L10N.getLocalString("sort.priority_high", "High");
else if (value == Detector.NORMAL_PRIORITY)
priorityString = edu.umd.cs.findbugs.L10N.getLocalString("sort.priority_normal", "Medium");
else if (value == Detector.LOW_PRIORITY)
priorityString = edu.umd.cs.findbugs.L10N.getLocalString("sort.priority_low", "Low");
else if (value == Detector.EXP_PRIORITY)
priorityString = edu.umd.cs.findbugs.L10N.getLocalString("sort.priority_experimental", "Experimental");
else
priorityString = edu.umd.cs.findbugs.L10N.getLocalString("sort.priority_ignore", "Ignore"); // This probably shouldn't ever happen, but what the hell, let's be complete
return priorityString;
}
public String getPriorityAbbreviation() {
return getPriorityString().substring(0,1);
}
/**
* Set the bug priority.
*/
public void setPriority(int p) {
priority = boundedPriority(p);
}
private int boundedPriority(int p) {
return Math.max(Detector.HIGH_PRIORITY, Math.min(Detector.IGNORE_PRIORITY, p));
}
public void raisePriority() {
priority = boundedPriority(priority-1);
}
public void lowerPriority() {
priority = boundedPriority(priority+1);
}
public void lowerPriorityALot() {
priority = boundedPriority(priority+2);
}
/**
* Is this bug instance the result of an experimental detector?
*/
public boolean isExperimental() {
BugPattern pattern = getBugPattern();
return (pattern != null) && pattern.isExperimental();
}
/**
* Get the primary class annotation, which indicates where the bug occurs.
*/
public ClassAnnotation getPrimaryClass() {
return findAnnotationOfType(ClassAnnotation.class);
}
/**
* Get the primary method annotation, which indicates where the bug occurs.
*/
public MethodAnnotation getPrimaryMethod() {
return findAnnotationOfType(MethodAnnotation.class);
}
/**
* Get the primary method annotation, which indicates where the bug occurs.
*/
public FieldAnnotation getPrimaryField() {
return findAnnotationOfType(FieldAnnotation.class);
}
public BugInstance lowerPriorityIfDeprecated() {
MethodAnnotation m = getPrimaryMethod();
if (m != null && XFactory.createXMethod(m).isDeprecated())
lowerPriority();
FieldAnnotation f = getPrimaryField();
if (f != null && XFactory.createXField(f).isDeprecated())
lowerPriority();
return this;
}
/**
* Find the first BugAnnotation in the list of annotations
* that is the same type or a subtype as the given Class parameter.
*
* @param cls the Class parameter
* @return the first matching BugAnnotation of the given type,
* or null if there is no such BugAnnotation
*/
private <T extends BugAnnotation> T findAnnotationOfType(Class<T> cls) {
for (Iterator<BugAnnotation> i = annotationIterator(); i.hasNext();) {
BugAnnotation annotation = i.next();
if (cls.isAssignableFrom(annotation.getClass()))
return cls.cast(annotation);
}
return null;
}
public LocalVariableAnnotation getPrimaryLocalVariableAnnotation() {
for (BugAnnotation annotation : annotationList)
if (annotation instanceof LocalVariableAnnotation)
return (LocalVariableAnnotation) annotation;
return null;
}
/**
* Get the primary source line annotation.
* There is guaranteed to be one (unless some Detector constructed
* an invalid BugInstance).
*
* @return the source line annotation
*/
public SourceLineAnnotation getPrimarySourceLineAnnotation() {
// Highest priority: return the first top level source line annotation
for (BugAnnotation annotation : annotationList) {
if (annotation instanceof SourceLineAnnotation
&& annotation.getDescription().equals(SourceLineAnnotation.DEFAULT_ROLE))
return (SourceLineAnnotation) annotation;
}
for (BugAnnotation annotation : annotationList) {
if (annotation instanceof SourceLineAnnotation)
return (SourceLineAnnotation) annotation;
}
// Next: Try primary method, primary field, primary class
SourceLineAnnotation srcLine;
if ((srcLine = inspectPackageMemberSourceLines(getPrimaryMethod())) != null)
return srcLine;
if ((srcLine = inspectPackageMemberSourceLines(getPrimaryField())) != null)
return srcLine;
if ((srcLine = inspectPackageMemberSourceLines(getPrimaryClass())) != null)
return srcLine;
// Last resort: throw exception
throw new IllegalStateException("BugInstance must contain at least one class, method, or field annotation");
}
public String getInstanceKey() {
StringBuilder buf = new StringBuilder(type);
for (BugAnnotation annotation : annotationList) {
if (annotation instanceof SourceLineAnnotation || annotation instanceof MethodAnnotation && !annotation.isSignificant()) {
// do nothing
} else {
buf.append(":");
buf.append(annotation.format("hash", null));
}
}
return buf.toString();
}
/**
* If given PackageMemberAnnotation is non-null, return its
* SourceLineAnnotation.
*
* @param packageMember
* a PackageMemberAnnotation
* @return the PackageMemberAnnotation's SourceLineAnnotation, or null if
* there is no SourceLineAnnotation
*/
private SourceLineAnnotation inspectPackageMemberSourceLines(PackageMemberAnnotation packageMember) {
return (packageMember != null) ? packageMember.getSourceLines() : null;
}
/**
* Get an Iterator over all bug annotations.
*/
public Iterator<BugAnnotation> annotationIterator() {
return annotationList.iterator();
}
/**
* Get an Iterator over all bug annotations.
*/
public List<? extends BugAnnotation> getAnnotations() {
return annotationList;
}
/**
* Get the abbreviation of this bug instance's BugPattern.
* This is the same abbreviation used by the BugCode which
* the BugPattern is a particular species of.
*/
public String getAbbrev() {
BugPattern pattern = getBugPattern();
return pattern != null ? pattern.getAbbrev() : "<unknown bug pattern>";
}
/** set the user designation object. This will clobber any
* existing annotationText (or any other BugDesignation field). */
public void setUserDesignation(BugDesignation bd) {
userDesignation = bd;
}
/** return the user designation object, which may be null.
*
* A previous calls to getSafeUserDesignation(), setAnnotationText(),
* or setUserDesignation() will ensure it will be non-null
* [barring an intervening setUserDesignation(null)].
* @see #getNonnullUserDesignation() */
@Nullable public BugDesignation getUserDesignation() {
return userDesignation;
}
/** return the user designation object, creating one if
* necessary. So calling
* <code>getSafeUserDesignation().setDesignation("HARMLESS")</code>
* will always work without the possibility of a NullPointerException.
* @see #getUserDesignation() */
@NonNull public BugDesignation getNonnullUserDesignation() {
if (userDesignation == null)
userDesignation = new BugDesignation();
return userDesignation;
}
/** Get the user designation key.
* E.g., "MOSTLY_HARMLESS", "CRITICAL", "NOT_A_BUG", etc.
*
* If the user designation object is null,returns UNCLASSIFIED.
*
* To set the user designation key, call
* <code>getSafeUserDesignation().setDesignation("HARMLESS")</code>.
*
* @see I18N#getUserDesignation(String key)
* @return the user designation key
*/
@NonNull public String getUserDesignationKey() {
BugDesignation userDesignation = this.userDesignation;
if (userDesignation == null) return BugDesignation.UNCLASSIFIED;
return userDesignation.getDesignationKey();
}
/**
* Set the user annotation text.
*
* @param annotationText the user annotation text
*/
public void setAnnotationText(String annotationText) {
getNonnullUserDesignation().setAnnotationText(annotationText);
}
/**
* Get the user annotation text.
*
* @return the user annotation text
*/
@NonNull public String getAnnotationText() {
BugDesignation userDesignation = this.userDesignation;
if (userDesignation == null) return "";
String s = userDesignation.getAnnotationText();
if (s == null) return "";
return s;
}
/**
* Determine whether or not the annotation text contains
* the given word.
*
* @param word the word
* @return true if the annotation text contains the word, false otherwise
*/
public boolean annotationTextContainsWord(String word) {
return getTextAnnotationWords().contains(word);
}
/**
* Get set of words in the text annotation.
*/
public Set<String> getTextAnnotationWords() {
HashSet<String> result = new HashSet<String>();
StringTokenizer tok = new StringTokenizer(getAnnotationText(), " \t\r\n\f.,:;-");
while (tok.hasMoreTokens()) {
result.add(tok.nextToken());
}
return result;
}
/**
* Get the BugInstance's unique id.
*
* @return the unique id, or null if no unique id has been assigned
*
* Deprecated, since it isn't persistent
*/
@Deprecated
public String getUniqueId() {
return uniqueId;
}
/**
* Set the unique id of the BugInstance.
*
* @param uniqueId the unique id
*
* * Deprecated, since it isn't persistent
*/
@Deprecated
void setUniqueId(String uniqueId) {
this.uniqueId = uniqueId;
}
private class BugPropertyIterator implements Iterator<BugProperty> {
private BugProperty prev, cur;
private boolean removed;
/* (non-Javadoc)
* @see java.util.Iterator#hasNext()
*/
public boolean hasNext() {
return findNext() != null;
}
/* (non-Javadoc)
* @see java.util.Iterator#next()
*/
public BugProperty next() {
BugProperty next = findNext();
if (next == null)
throw new NoSuchElementException();
prev = cur;
cur = next;
removed = false;
return cur;
}
/* (non-Javadoc)
* @see java.util.Iterator#remove()
*/
public void remove() {
if (cur == null || removed)
throw new IllegalStateException();
if (prev == null) {
propertyListHead = cur.getNext();
} else {
prev.setNext(cur.getNext());
}
if (cur == propertyListTail) {
propertyListTail = prev;
}
removed = true;
}
private BugProperty findNext() {
return cur == null ? propertyListHead : cur.getNext();
}
}
/**
* Get value of given property.
*
* @param name name of the property to get
* @return the value of the named property, or null if
* the property has not been set
*/
public String getProperty(String name) {
BugProperty prop = lookupProperty(name);
return prop != null ? prop.getValue() : null;
}
/**
* Get value of given property, returning given default
* value if the property has not been set.
*
* @param name name of the property to get
* @param defaultValue default value to return if propery is not set
* @return the value of the named property, or the default
* value if the property has not been set
*/
public String getProperty(String name, String defaultValue) {
String value = getProperty(name);
return value != null ? value : defaultValue;
}
/**
* Get an Iterator over the properties defined in this BugInstance.
*
* @return Iterator over properties
*/
public Iterator<BugProperty> propertyIterator() {
return new BugPropertyIterator();
}
/**
* Set value of given property.
*
* @param name name of the property to set
* @param value the value of the property
* @return this object, so calls can be chained
*/
public BugInstance setProperty(String name, String value) {
BugProperty prop = lookupProperty(name);
if (prop != null) {
prop.setValue(value);
} else {
prop = new BugProperty(name, value);
addProperty(prop);
}
return this;
}
/**
* Look up a property by name.
*
* @param name name of the property to look for
* @return the BugProperty with the given name,
* or null if the property has not been set
*/
public BugProperty lookupProperty(String name) {
BugProperty prop = propertyListHead;
while (prop != null) {
if (prop.getName().equals(name))
break;
prop = prop.getNext();
}
return prop;
}
/**
* Delete property with given name.
*
* @param name name of the property to delete
* @return true if a property with that name was deleted,
* or false if there is no such property
*/
public boolean deleteProperty(String name) {
BugProperty prev = null;
BugProperty prop = propertyListHead;
while (prop != null) {
if (prop.getName().equals(name))
break;
prev = prop;
prop = prop.getNext();
}
if (prop != null) {
if (prev != null) {
// Deleted node in interior or at tail of list
prev.setNext(prop.getNext());
} else {
// Deleted node at head of list
propertyListHead = prop.getNext();
}
if (prop.getNext() == null) {
// Deleted node at end of list
propertyListTail = prev;
}
return true;
} else {
// No such property
return false;
}
}
private void addProperty(BugProperty prop) {
if (propertyListTail != null) {
propertyListTail.setNext(prop);
propertyListTail = prop;
} else {
propertyListHead = propertyListTail = prop;
}
prop.setNext(null);
}
/**
* Add a Collection of BugAnnotations.
*
* @param annotationCollection Collection of BugAnnotations
*/
public BugInstance addAnnotations(Collection<? extends BugAnnotation> annotationCollection) {
for (BugAnnotation annotation : annotationCollection) {
add(annotation);
}
return this;
}
public BugInstance addClassAndMethod(MethodDescriptor methodDescriptor) {
addClass(methodDescriptor.getSlashedClassName());
add(MethodAnnotation.fromMethodDescriptor(methodDescriptor));
return this;
}
/**
* Add a class annotation and a method annotation for the class and method
* which the given visitor is currently visiting.
*
* @param visitor the BetterVisitor
* @return this object
*/
public BugInstance addClassAndMethod(PreorderVisitor visitor) {
addClass(visitor);
addMethod(visitor);
return this;
}
/**
* Add class and method annotations for given method.
*
* @param methodAnnotation the method
* @return this object
*/
public BugInstance addClassAndMethod(MethodAnnotation methodAnnotation) {
addClass(methodAnnotation.getClassName());
addMethod(methodAnnotation);
return this;
}
/**
* Add class and method annotations for given method.
*
* @param methodGen the method
* @param sourceFile source file the method is defined in
* @return this object
*/
public BugInstance addClassAndMethod(MethodGen methodGen, String sourceFile) {
addClass(methodGen.getClassName());
addMethod(methodGen, sourceFile);
return this;
}
/**
* Add class and method annotations for given class and method.
*
* @param javaClass the class
* @param method the method
* @return this object
*/
public BugInstance addClassAndMethod(JavaClass javaClass, Method method) {
addClass(javaClass.getClassName());
addMethod(javaClass, method);
return this;
}
/**
* Add a class annotation. If this is the first class annotation added,
* it becomes the primary class annotation.
*
* @param className the name of the class
* @param sourceFileName the source file of the class
* @return this object
* @deprecated use addClass(String) instead
*/
@Deprecated
public BugInstance addClass(String className, String sourceFileName) {
ClassAnnotation classAnnotation = new ClassAnnotation(className);
add(classAnnotation);
return this;
}
/**
* Add a class annotation. If this is the first class annotation added,
* it becomes the primary class annotation.
*
* @param className the name of the class
* @return this object
*/
public BugInstance addClass(String className) {
className = ClassName.toDottedClassName(className);
ClassAnnotation classAnnotation = new ClassAnnotation(className);
add(classAnnotation);
return this;
}
/**
* Add a class annotation for the classNode.
*
* @param classNode the ASM visitor
* @return this object
*/
public BugInstance addClass(ClassNode classNode) {
ClassAnnotation classAnnotation = new ClassAnnotation(classNode.name);
add(classAnnotation);
return this;
}
/**
* Add a class annotation. If this is the first class annotation added,
* it becomes the primary class annotation.
*
* @param classDescriptor the class to add
* @return this object
*/
public BugInstance addClass(ClassDescriptor classDescriptor) {
add(ClassAnnotation.fromClassDescriptor(classDescriptor));
return this;
}
/**
* Add a class annotation. If this is the first class annotation added,
* it becomes the primary class annotation.
*
* @param jclass the JavaClass object for the class
* @return this object
*/
public BugInstance addClass(JavaClass jclass) {
addClass(jclass.getClassName());
return this;
}
/**
* Add a class annotation for the class that the visitor is currently visiting.
*
* @param visitor the BetterVisitor
* @return this object
*/
public BugInstance addClass(PreorderVisitor visitor) {
String className = visitor.getDottedClassName();
addClass(className);
return this;
}
/**
* Add a class annotation for the superclass of the class the visitor
* is currently visiting.
*
* @param visitor the BetterVisitor
* @return this object
*/
public BugInstance addSuperclass(PreorderVisitor visitor) {
String className = visitor.getSuperclassName();
addClass(className);
return this;
}
public BugInstance addType(String typeDescriptor) {
TypeAnnotation typeAnnotation = new TypeAnnotation(typeDescriptor);
add(typeAnnotation);
return this;
}
public BugInstance addFoundAndExpectedType(Type foundType, Type expectedType) {
add( new TypeAnnotation(foundType, TypeAnnotation.FOUND_ROLE));
add( new TypeAnnotation(expectedType, TypeAnnotation.EXPECTED_ROLE));
return this;
}
public BugInstance addFoundAndExpectedType(String foundType, String expectedType) {
add( new TypeAnnotation(foundType, TypeAnnotation.FOUND_ROLE));
add( new TypeAnnotation(expectedType, TypeAnnotation.EXPECTED_ROLE));
return this;
}
public BugInstance addEqualsMethodUsed(ClassDescriptor expectedClass) {
try {
Set<XMethod> targets = Hierarchy2.resolveVirtualMethodCallTargets(expectedClass, "equals", "(Ljava/lang/Object;)Z",
false, false);
addEqualsMethodUsed(targets);
} catch (ClassNotFoundException e) {
AnalysisContext.reportMissingClass(e);
}
return this;
}
public BugInstance addEqualsMethodUsed(@CheckForNull Collection<XMethod> equalsMethods) {
if (equalsMethods == null) return this;
if (equalsMethods.size() < 5) {
for (XMethod m : equalsMethods) {
addMethod(m).describe(MethodAnnotation.METHOD_EQUALS_USED);
}
} else {
addMethod(equalsMethods.iterator().next()).describe(MethodAnnotation.METHOD_EQUALS_USED);
}
return this;
}
public BugInstance addTypeOfNamedClass(String typeName) {
TypeAnnotation typeAnnotation = new TypeAnnotation("L" + typeName.replace('.','/')+";");
add(typeAnnotation);
return this;
}
public BugInstance addType(ClassDescriptor c) {
TypeAnnotation typeAnnotation = new TypeAnnotation("L" + c.getClassName()+";");
add(typeAnnotation);
return this;
}
/**
* Add a field annotation.
*
* @param className name of the class containing the field
* @param fieldName the name of the field
* @param fieldSig type signature of the field
* @param isStatic whether or not the field is static
* @return this object
*/
public BugInstance addField(String className, String fieldName, String fieldSig, boolean isStatic) {
addField(new FieldAnnotation(className, fieldName, fieldSig, isStatic));
return this;
}
/**
* Add a field annotation.
*
* @param className name of the class containing the field
* @param fieldName the name of the field
* @param fieldSig type signature of the field
* @param accessFlags access flags for the field
* @return this object
*/
public BugInstance addField(String className, String fieldName, String fieldSig, int accessFlags) {
addField(new FieldAnnotation(className, fieldName, fieldSig, accessFlags));
return this;
}
public BugInstance addField(PreorderVisitor visitor) {
FieldAnnotation fieldAnnotation = FieldAnnotation.fromVisitedField(visitor);
return addField(fieldAnnotation);
}
/**
* Add a field annotation
*
* @param fieldAnnotation the field annotation
* @return this object
*/
public BugInstance addField(FieldAnnotation fieldAnnotation) {
add(fieldAnnotation);
return this;
}
/**
* Add a field annotation for a FieldVariable matched in a ByteCodePattern.
*
* @param field the FieldVariable
* @return this object
*/
public BugInstance addField(FieldVariable field) {
return addField(field.getClassName(), field.getFieldName(), field.getFieldSig(), field.isStatic());
}
/**
* Add a field annotation for an XField.
*
* @param xfield the XField
* @return this object
*/
public BugInstance addOptionalField(@CheckForNull XField xfield) {
if (xfield == null) return this;
return addField(xfield.getClassName(), xfield.getName(), xfield.getSignature(), xfield.isStatic());
}
/**
* Add a field annotation for an XField.
*
* @param xfield the XField
* @return this object
*/
public BugInstance addField(XField xfield) {
return addField(xfield.getClassName(), xfield.getName(), xfield.getSignature(), xfield.isStatic());
}
/**
* Add a field annotation for a FieldDescriptor.
*
* @param fieldDescriptor the FieldDescriptor
* @return this object
*/
public BugInstance addField(FieldDescriptor fieldDescriptor) {
FieldAnnotation fieldAnnotation = FieldAnnotation.fromFieldDescriptor(fieldDescriptor);
add(fieldAnnotation);
return this;
}
/**
* Add a field annotation for the field which has just been accessed
* by the method currently being visited by given visitor.
* Assumes that a getfield/putfield or getstatic/putstatic
* has just been seen.
*
* @param visitor the DismantleBytecode object
* @return this object
*/
public BugInstance addReferencedField(DismantleBytecode visitor) {
FieldAnnotation f = FieldAnnotation.fromReferencedField(visitor);
addField(f);
return this;
}
/**
* Add a field annotation for the field referenced by the FieldAnnotation parameter
*/
public BugInstance addReferencedField(FieldAnnotation fa) {
addField(fa);
return this;
}
/**
* Add a field annotation for the field which is being visited by
* given visitor.
*
* @param visitor the visitor
* @return this object
*/
public BugInstance addVisitedField(PreorderVisitor visitor) {
FieldAnnotation f = FieldAnnotation.fromVisitedField(visitor);
addField(f);
return this;
}
/**
* Local variable adders
*/
public BugInstance addOptionalLocalVariable(DismantleBytecode dbc, OpcodeStack.Item item) {
int register = item.getRegisterNumber();
if (register >= 0)
this.add(LocalVariableAnnotation.getLocalVariableAnnotation(dbc.getMethod(), register, dbc.getPC()-1, dbc.getPC()));
return this;
}
/**
* Add a method annotation. If this is the first method annotation added,
* it becomes the primary method annotation.
*
* @param className name of the class containing the method
* @param methodName name of the method
* @param methodSig type signature of the method
* @param isStatic true if the method is static, false otherwise
* @return this object
*/
public BugInstance addMethod(String className, String methodName, String methodSig, boolean isStatic) {
addMethod(MethodAnnotation.fromForeignMethod(className, methodName, methodSig, isStatic));
return this;
}
/**
* Add a method annotation. If this is the first method annotation added,
* it becomes the primary method annotation.
*
* @param className name of the class containing the method
* @param methodName name of the method
* @param methodSig type signature of the method
* @param accessFlags accessFlags for the method
* @return this object
*/
public BugInstance addMethod(String className, String methodName, String methodSig, int accessFlags) {
addMethod(MethodAnnotation.fromForeignMethod(className, methodName, methodSig, accessFlags));
return this;
}
/**
* Add a method annotation. If this is the first method annotation added,
* it becomes the primary method annotation.
* If the method has source line information, then a SourceLineAnnotation
* is added to the method.
*
* @param methodGen the MethodGen object for the method
* @param sourceFile source file method is defined in
* @return this object
*/
public BugInstance addMethod(MethodGen methodGen, String sourceFile) {
String className = methodGen.getClassName();
MethodAnnotation methodAnnotation =
new MethodAnnotation(className, methodGen.getName(), methodGen.getSignature(), methodGen.isStatic());
addMethod(methodAnnotation);
addSourceLinesForMethod(methodAnnotation, SourceLineAnnotation.fromVisitedMethod(methodGen, sourceFile));
return this;
}
/**
* Add a method annotation. If this is the first method annotation added,
* it becomes the primary method annotation.
* If the method has source line information, then a SourceLineAnnotation
* is added to the method.
*
* @param javaClass the class the method is defined in
* @param method the method
* @return this object
*/
public BugInstance addMethod(JavaClass javaClass, Method method) {
MethodAnnotation methodAnnotation =
new MethodAnnotation(javaClass.getClassName(), method.getName(), method.getSignature(), method.isStatic());
SourceLineAnnotation methodSourceLines = SourceLineAnnotation.forEntireMethod(
javaClass,
method);
methodAnnotation.setSourceLines(methodSourceLines);
addMethod(methodAnnotation);
return this;
}
/**
* Add a method annotation. If this is the first method annotation added,
* it becomes the primary method annotation.
* If the method has source line information, then a SourceLineAnnotation
* is added to the method.
*
* @param classAndMethod JavaClassAndMethod identifying the method to add
* @return this object
*/
public BugInstance addMethod(JavaClassAndMethod classAndMethod) {
return addMethod(classAndMethod.getJavaClass(), classAndMethod.getMethod());
}
/**
* Add a method annotation for the method which the given visitor is currently visiting.
* If the method has source line information, then a SourceLineAnnotation
* is added to the method.
*
* @param visitor the BetterVisitor
* @return this object
*/
public BugInstance addMethod(PreorderVisitor visitor) {
MethodAnnotation methodAnnotation = MethodAnnotation.fromVisitedMethod(visitor);
addMethod(methodAnnotation);
addSourceLinesForMethod(methodAnnotation, SourceLineAnnotation.fromVisitedMethod(visitor));
return this;
}
/**
* Add a method annotation for the method which has been called
* by the method currently being visited by given visitor.
* Assumes that the visitor has just looked at an invoke instruction
* of some kind.
*
* @param visitor the DismantleBytecode object
* @return this object
*/
public BugInstance addCalledMethod(DismantleBytecode visitor) {
return addMethod(MethodAnnotation.fromCalledMethod(visitor)).describe(MethodAnnotation.METHOD_CALLED);
}
/**
* Add a method annotation.
*
* @param className name of class containing called method
* @param methodName name of called method
* @param methodSig signature of called method
* @param isStatic true if called method is static, false if not
* @return this object
*/
public BugInstance addCalledMethod(String className, String methodName, String methodSig, boolean isStatic) {
return addMethod(MethodAnnotation.fromCalledMethod(className, methodName, methodSig, isStatic)).describe(MethodAnnotation.METHOD_CALLED);
}
/**
* Add a method annotation for the method which is called by given
* instruction.
*
* @param methodGen the method containing the call
* @param inv the InvokeInstruction
* @return this object
*/
public BugInstance addCalledMethod(ConstantPoolGen cpg, InvokeInstruction inv) {
String className = inv.getClassName(cpg);
String methodName = inv.getMethodName(cpg);
String methodSig = inv.getSignature(cpg);
addMethod(className, methodName, methodSig, inv.getOpcode() == Constants.INVOKESTATIC);
describe(MethodAnnotation.METHOD_CALLED);
return this;
}
/**
* Add a method annotation for the method which is called by given
* instruction.
*
* @param methodGen the method containing the call
* @param inv the InvokeInstruction
* @return this object
*/
public BugInstance addCalledMethod(MethodGen methodGen, InvokeInstruction inv) {
ConstantPoolGen cpg = methodGen.getConstantPool();
return addCalledMethod(cpg, inv);
}
/**
* Add a MethodAnnotation from an XMethod.
*
* @param xmethod the XMethod
* @return this object
*/
public BugInstance addMethod(XMethod xmethod) {
addMethod(MethodAnnotation.fromXMethod(xmethod));
return this;
}
/**
* Add a method annotation. If this is the first method annotation added,
* it becomes the primary method annotation.
*
* @param methodAnnotation the method annotation
* @return this object
*/
public BugInstance addMethod(MethodAnnotation methodAnnotation) {
add(methodAnnotation);
return this;
}
/**
* Add an integer annotation.
*
* @param value the integer value
* @return this object
*/
public BugInstance addInt(int value) {
add(new IntAnnotation(value));
return this;
}
/*
* Add an annotation about a parameter
* @param index parameter index, starting from 0
* @param role the role used to describe the parameter
*/
public BugInstance addParameterAnnotation(int index, String role) {
return addInt(index+1).describe(role);
}
/**
* Add a String annotation.
*
* @param value the String value
* @return this object
*/
public BugInstance addString(String value) {
add(new StringAnnotation(value));
return this;
}
/**
* Add a String annotation.
*
* @param c the char value
* @return this object
*/
public BugInstance addString(char c) {
add(new StringAnnotation(Character.toString(c)));
return this;
}
/**
* Add a source line annotation.
*
* @param sourceLine the source line annotation
* @return this object
*/
public BugInstance addSourceLine(SourceLineAnnotation sourceLine) {
add(sourceLine);
return this;
}
/**
* Add a source line annotation for instruction whose PC is given
* in the method that the given visitor is currently visiting.
* Note that if the method does not have line number information, then
* no source line annotation will be added.
*
* @param visitor a BytecodeScanningDetector that is currently visiting the method
* @param pc bytecode offset of the instruction
* @return this object
*/
public BugInstance addSourceLine(BytecodeScanningDetector visitor, int pc) {
SourceLineAnnotation sourceLineAnnotation =
SourceLineAnnotation.fromVisitedInstruction(visitor.getClassContext(), visitor, pc);
if (sourceLineAnnotation != null)
add(sourceLineAnnotation);
return this;
}
/**
* Add a source line annotation for instruction whose PC is given
* in the method that the given visitor is currently visiting.
* Note that if the method does not have line number information, then
* no source line annotation will be added.
*
* @param classContext the ClassContext
* @param visitor a PreorderVisitor that is currently visiting the method
* @param pc bytecode offset of the instruction
* @return this object
*/
public BugInstance addSourceLine(ClassContext classContext, PreorderVisitor visitor, int pc) {
SourceLineAnnotation sourceLineAnnotation =
SourceLineAnnotation.fromVisitedInstruction(classContext, visitor, pc);
if (sourceLineAnnotation != null)
add(sourceLineAnnotation);
return this;
}
/**
* Add a source line annotation for the given instruction in the given method.
* Note that if the method does not have line number information, then
* no source line annotation will be added.
*
* @param classContext the ClassContext
* @param methodGen the method being visited
* @param sourceFile source file the method is defined in
* @param handle the InstructionHandle containing the visited instruction
* @return this object
*/
public BugInstance addSourceLine(ClassContext classContext, MethodGen methodGen, String sourceFile, @NonNull InstructionHandle handle) {
SourceLineAnnotation sourceLineAnnotation =
SourceLineAnnotation.fromVisitedInstruction(classContext, methodGen, sourceFile, handle);
if (sourceLineAnnotation != null)
add(sourceLineAnnotation);
return this;
}
/**
* Add a source line annotation describing a range of instructions.
*
* @param classContext the ClassContext
* @param methodGen the method
* @param sourceFile source file the method is defined in
* @param start the start instruction in the range
* @param end the end instruction in the range (inclusive)
* @return this object
*/
public BugInstance addSourceLine(ClassContext classContext, MethodGen methodGen, String sourceFile, InstructionHandle start, InstructionHandle end) {
// Make sure start and end are really in the right order.
if (start.getPosition() > end.getPosition()) {
InstructionHandle tmp = start;
start = end;
end = tmp;
}
SourceLineAnnotation sourceLineAnnotation =
SourceLineAnnotation.fromVisitedInstructionRange(classContext, methodGen, sourceFile, start, end);
if (sourceLineAnnotation != null)
add(sourceLineAnnotation);
return this;
}
/**
* Add source line annotation for given Location in a method.
*
* @param classContext the ClassContext
* @param method the Method
* @param location the Location in the method
* @return this BugInstance
*/
public BugInstance addSourceLine(ClassContext classContext, Method method, Location location) {
return addSourceLine(classContext, method, location.getHandle());
}
/**
* Add source line annotation for given Location in a method.
*
* @param methodDescriptor the method
* @param location the Location in the method
* @return this BugInstance
*/
public BugInstance addSourceLine(MethodDescriptor methodDescriptor, Location location) {
try {
IAnalysisCache analysisCache = Global.getAnalysisCache();
ClassContext classContext = analysisCache.getClassAnalysis(ClassContext.class, methodDescriptor.getClassDescriptor());
Method method = analysisCache.getMethodAnalysis(Method.class, methodDescriptor);
return addSourceLine(classContext, method, location);
} catch (CheckedAnalysisException e) {
return addSourceLine(SourceLineAnnotation.createReallyUnknown(methodDescriptor.getClassDescriptor().toDottedClassName()));
}
}
/**
* Add source line annotation for given Location in a method.
*
* @param classContext the ClassContext
* @param method the Method
* @param handle InstructionHandle of an instruction in the method
* @return this BugInstance
*/
public BugInstance addSourceLine(ClassContext classContext, Method method, InstructionHandle handle) {
SourceLineAnnotation sourceLineAnnotation =
SourceLineAnnotation.fromVisitedInstruction(classContext, method, handle.getPosition());
if (sourceLineAnnotation != null)
add(sourceLineAnnotation);
return this;
}
/**
* Add a source line annotation describing the
* source line numbers for a range of instructions in the method being
* visited by the given visitor.
* Note that if the method does not have line number information, then
* no source line annotation will be added.
*
* @param visitor a BetterVisitor which is visiting the method
* @param startPC the bytecode offset of the start instruction in the range
* @param endPC the bytecode offset of the end instruction in the range
* @return this object
*/
public BugInstance addSourceLineRange(BytecodeScanningDetector visitor, int startPC, int endPC) {
SourceLineAnnotation sourceLineAnnotation =
SourceLineAnnotation.fromVisitedInstructionRange(visitor.getClassContext(), visitor, startPC, endPC);
if (sourceLineAnnotation != null)
add(sourceLineAnnotation);
return this;
}
/**
* Add a source line annotation describing the
* source line numbers for a range of instructions in the method being
* visited by the given visitor.
* Note that if the method does not have line number information, then
* no source line annotation will be added.
*
* @param classContext the ClassContext
* @param visitor a BetterVisitor which is visiting the method
* @param startPC the bytecode offset of the start instruction in the range
* @param endPC the bytecode offset of the end instruction in the range
* @return this object
*/
public BugInstance addSourceLineRange(ClassContext classContext, PreorderVisitor visitor, int startPC, int endPC) {
SourceLineAnnotation sourceLineAnnotation =
SourceLineAnnotation.fromVisitedInstructionRange(classContext, visitor, startPC, endPC);
if (sourceLineAnnotation != null)
add(sourceLineAnnotation);
return this;
}
/**
* Add a source line annotation for instruction currently being visited
* by given visitor.
* Note that if the method does not have line number information, then
* no source line annotation will be added.
*
* @param visitor a BytecodeScanningDetector visitor that is currently visiting the instruction
* @return this object
*/
public BugInstance addSourceLine(BytecodeScanningDetector visitor) {
SourceLineAnnotation sourceLineAnnotation =
SourceLineAnnotation.fromVisitedInstruction(visitor);
if (sourceLineAnnotation != null)
add(sourceLineAnnotation);
return this;
}
/**
* Add a non-specific source line annotation.
* This will result in the entire source file being displayed.
*
* @param className the class name
* @param sourceFile the source file name
* @return this object
*/
public BugInstance addUnknownSourceLine(String className, String sourceFile) {
SourceLineAnnotation sourceLineAnnotation = SourceLineAnnotation.createUnknown(className, sourceFile);
if (sourceLineAnnotation != null)
add(sourceLineAnnotation);
return this;
}
/**
* Format a string describing this bug instance.
*
* @return the description
*/
public String getMessageWithoutPrefix() {
BugPattern bugPattern = getBugPattern();
String pattern, shortPattern;
pattern = getLongDescription();
shortPattern = bugPattern.getShortDescription();
try {
FindBugsMessageFormat format = new FindBugsMessageFormat(pattern);
return format.format(annotationList.toArray(new BugAnnotation[annotationList.size()]), getPrimaryClass());
} catch (RuntimeException e) {
AnalysisContext.logError("Error generating bug msg ", e);
return shortPattern + " [Error generating customized description]";
}
}
String getLongDescription() {
return getBugPattern().getLongDescription().replaceAll("BUG_PATTERN", type);
}
public String getAbridgedMessage() {
BugPattern bugPattern = getBugPattern();
String pattern, shortPattern;
if (bugPattern == null)
shortPattern = pattern = "Error2: missing bug pattern for key " + type;
else {
pattern = getLongDescription().replaceAll(" in \\{1\\}", "");
shortPattern = bugPattern.getShortDescription();
}
try {
FindBugsMessageFormat format = new FindBugsMessageFormat(pattern);
return format.format(annotationList.toArray(new BugAnnotation[annotationList.size()]), getPrimaryClass());
} catch (RuntimeException e) {
AnalysisContext.logError("Error generating bug msg ", e);
return shortPattern + " [Error3 generating customized description]";
}
}
/**
* Format a string describing this bug instance.
*
* @return the description
*/
public String getMessage() {
BugPattern bugPattern = getBugPattern();
String pattern = bugPattern.getAbbrev() + ": " + getLongDescription();
FindBugsMessageFormat format = new FindBugsMessageFormat(pattern);
try {
return format.format(annotationList.toArray(new BugAnnotation[annotationList.size()]), getPrimaryClass());
} catch (RuntimeException e) {
AnalysisContext.logError("Error generating bug msg ", e);
return bugPattern.getShortDescription() + " [Error generating customized description]";
}
}
/**
* Format a string describing this bug pattern, with the priority and type at the beginning.
* e.g. "(High Priority Correctness) Guaranteed null pointer dereference..."
*/
public String getMessageWithPriorityType() {
return "(" + this.getPriorityTypeString() + ") " + this.getMessage();
}
public String getMessageWithPriorityTypeAbbreviation() {
return this.getPriorityTypeAbbreviation() + " "+ this.getMessage();
}
/**
* Add a description to the most recently added bug annotation.
*
* @param description the description to add
* @return this object
*/
public BugInstance describe(String description) {
annotationList.get(annotationList.size() - 1).setDescription(description);
return this;
}
/**
* Convert to String.
* This method returns the "short" message describing the bug,
* as opposed to the longer format returned by getMessage().
* The short format is appropriate for the tree view in a GUI,
* where the annotations are listed separately as part of the overall
* bug instance.
*/
@Override
public String toString() {
return I18N.instance().getShortMessage(type);
}
public void writeXML(XMLOutput xmlOutput) throws IOException {
writeXML(xmlOutput, false, false);
}
public void writeXML(XMLOutput xmlOutput, boolean addMessages, boolean isPrimary) throws IOException {
XMLAttributeList attributeList = new XMLAttributeList()
.addAttribute("type", type)
.addAttribute("priority", String.valueOf(priority));
BugPattern pattern = getBugPattern();
if (pattern != null) {
// The bug abbreviation and pattern category are
// emitted into the XML for informational purposes only.
// (The information is redundant, but might be useful
// for processing tools that want to make sense of
// bug instances without looking at the plugin descriptor.)
attributeList.addAttribute("abbrev", pattern.getAbbrev());
attributeList.addAttribute("category", pattern.getCategory());
}
if (addMessages) {
// Add a uid attribute, if we have a unique id.
if (getUniqueId() != null) {
attributeList.addAttribute("uid", getUniqueId());
}
attributeList.addAttribute("instanceHash", getInstanceHash());
attributeList.addAttribute("instanceOccurrenceNum", Integer.toString(getInstanceOccurrenceNum()));
attributeList.addAttribute("instanceOccurrenceMax", Integer.toString(getInstanceOccurrenceMax()));
}
if (firstVersion > 0) attributeList.addAttribute("first", Long.toString(firstVersion));
if (lastVersion >= 0) attributeList.addAttribute("last", Long.toString(lastVersion));
if (introducedByChangeOfExistingClass)
attributeList.addAttribute("introducedByChange", "true");
if (removedByChangeOfPersistingClass)
attributeList.addAttribute("removedByChange", "true");
xmlOutput.openTag(ELEMENT_NAME, attributeList);
if (userDesignation != null) {
userDesignation.writeXML(xmlOutput);
}
if (addMessages) {
BugPattern bugPattern = getBugPattern();
xmlOutput.openTag("ShortMessage");
xmlOutput.writeText(bugPattern != null ? bugPattern.getShortDescription() : this.toString());
xmlOutput.closeTag("ShortMessage");
xmlOutput.openTag("LongMessage");
if (FindBugsDisplayFeatures.isAbridgedMessages()) xmlOutput.writeText(this.getAbridgedMessage());
else xmlOutput.writeText(this.getMessageWithoutPrefix());
xmlOutput.closeTag("LongMessage");
}
Map<BugAnnotation,Void> primaryAnnotations;
if (addMessages) {
primaryAnnotations = new IdentityHashMap<BugAnnotation,Void>();
primaryAnnotations.put(getPrimarySourceLineAnnotation(), null);
primaryAnnotations.put(getPrimaryClass(), null);
primaryAnnotations.put(getPrimaryField(), null);
primaryAnnotations.put(getPrimaryMethod(), null);
} else {
primaryAnnotations = Collections.<BugAnnotation,Void>emptyMap();
}
boolean foundSourceAnnotation = false;
for (BugAnnotation annotation : annotationList) {
if (annotation instanceof SourceLineAnnotation)
foundSourceAnnotation = true;
annotation.writeXML(xmlOutput, addMessages, primaryAnnotations.containsKey(annotation));
}
if (!foundSourceAnnotation && addMessages) {
SourceLineAnnotation synth = getPrimarySourceLineAnnotation();
if (synth != null) {
synth.setSynthetic(true);
synth.writeXML(xmlOutput, addMessages, false);
}
}
if (propertyListHead != null) {
BugProperty prop = propertyListHead;
while (prop != null) {
prop.writeXML(xmlOutput);
prop = prop.getNext();
}
}
xmlOutput.closeTag(ELEMENT_NAME);
}
private static final String ELEMENT_NAME = "BugInstance";
private static final String USER_ANNOTATION_ELEMENT_NAME = "UserAnnotation";
public BugInstance addOptionalAnnotation(@CheckForNull BugAnnotation annotation) {
if (annotation == null) return this;
return add(annotation);
}
public BugInstance addOptionalAnnotation(@CheckForNull BugAnnotation annotation, String role) {
if (annotation == null) return this;
return add(annotation).describe(role);
}
public BugInstance add(BugAnnotation annotation) {
if (annotation == null)
throw new IllegalStateException("Missing BugAnnotation!");
// Add to list
annotationList.add(annotation);
// This object is being modified, so the cached hashcode
// must be invalidated
cachedHashCode = INVALID_HASH_CODE;
return this;
}
public BugInstance addValueSource(OpcodeStack.Item item, Method method, int pc) {
LocalVariableAnnotation lv = LocalVariableAnnotation.getLocalVariableAnnotation(method, item, pc);
if (lv != null && lv.isNamed()) {
add(lv);
} else {
XField xField = item.getXField();
if (xField != null)
addField(xField).describe(FieldAnnotation.LOADED_FROM_ROLE);
else {
XMethod xMethod = item.getReturnValueOf();
if (xMethod != null)
addMethod(xMethod).describe(MethodAnnotation.METHOD_RETURN_VALUE_OF);
}
}
return this;
}
private void addSourceLinesForMethod(MethodAnnotation methodAnnotation, SourceLineAnnotation sourceLineAnnotation) {
if (sourceLineAnnotation != null) {
// Note: we don't add the source line annotation directly to
// the bug instance. Instead, we stash it in the MethodAnnotation.
// It is much more useful there, and it would just be distracting
// if it were displayed in the UI, since it would compete for attention
// with the actual bug location source line annotation (which is much
// more important and interesting).
methodAnnotation.setSourceLines(sourceLineAnnotation);
}
}
@Override
public int hashCode() {
if (cachedHashCode == INVALID_HASH_CODE) {
int hashcode = type.hashCode() + priority;
Iterator<BugAnnotation> i = annotationIterator();
while (i.hasNext())
hashcode += i.next().hashCode();
if (hashcode == INVALID_HASH_CODE)
hashcode = INVALID_HASH_CODE+1;
cachedHashCode = hashcode;
}
return cachedHashCode;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof BugInstance))
return false;
BugInstance other = (BugInstance) o;
if (!type.equals(other.type) || priority != other.priority)
return false;
if (annotationList.size() != other.annotationList.size())
return false;
int numAnnotations = annotationList.size();
for (int i = 0; i < numAnnotations; ++i) {
BugAnnotation lhs = annotationList.get(i);
BugAnnotation rhs = other.annotationList.get(i);
if (!lhs.equals(rhs))
return false;
}
return true;
}
public int compareTo(BugInstance other) {
int cmp;
cmp = type.compareTo(other.type);
if (cmp != 0)
return cmp;
cmp = priority - other.priority;
if (cmp != 0)
return cmp;
// Compare BugAnnotations lexicographically
int pfxLen = Math.min(annotationList.size(), other.annotationList.size());
for (int i = 0; i < pfxLen; ++i) {
BugAnnotation lhs = annotationList.get(i);
BugAnnotation rhs = other.annotationList.get(i);
cmp = lhs.compareTo(rhs);
if (cmp != 0)
return cmp;
}
// All elements in prefix were the same,
// so use number of elements to decide
return annotationList.size() - other.annotationList.size();
}
/**
* @param firstVersion The firstVersion to set.
*/
public void setFirstVersion(long firstVersion) {
this.firstVersion = firstVersion;
if (lastVersion >= 0 && firstVersion > lastVersion)
throw new IllegalArgumentException(
firstVersion + ".." + lastVersion);
}
/**
* @return Returns the firstVersion.
*/
public long getFirstVersion() {
return firstVersion;
}
/**
* @param lastVersion The lastVersion to set.
*/
public void setLastVersion(long lastVersion) {
if (lastVersion >= 0 && firstVersion > lastVersion)
throw new IllegalArgumentException(
firstVersion + ".." + lastVersion);
this.lastVersion = lastVersion;
}
/**
* @return Returns the lastVersion.
*/
public long getLastVersion() {
return lastVersion;
}
public boolean isDead() {
return lastVersion != -1;
}
/**
* @param introducedByChangeOfExistingClass The introducedByChangeOfExistingClass to set.
*/
public void setIntroducedByChangeOfExistingClass(boolean introducedByChangeOfExistingClass) {
this.introducedByChangeOfExistingClass = introducedByChangeOfExistingClass;
}
/**
* @return Returns the introducedByChangeOfExistingClass.
*/
public boolean isIntroducedByChangeOfExistingClass() {
return introducedByChangeOfExistingClass;
}
/**
* @param removedByChangeOfPersistingClass The removedByChangeOfPersistingClass to set.
*/
public void setRemovedByChangeOfPersistingClass(boolean removedByChangeOfPersistingClass) {
this.removedByChangeOfPersistingClass = removedByChangeOfPersistingClass;
}
/**
* @return Returns the removedByChangeOfPersistingClass.
*/
public boolean isRemovedByChangeOfPersistingClass() {
return removedByChangeOfPersistingClass;
}
/**
* @param instanceHash The instanceHash to set.
*/
public void setInstanceHash(String instanceHash) {
this.instanceHash = instanceHash;
}
/**
* @param oldInstanceHash The oldInstanceHash to set.
*/
public void setOldInstanceHash(String oldInstanceHash) {
this.oldInstanceHash = oldInstanceHash;
}
private static final boolean DONT_HASH = SystemProperties.getBoolean("findbugs.dontHash");
/**
* @return Returns the instanceHash.
*/
public String getInstanceHash() {
if (instanceHash != null) return instanceHash;
MessageDigest digest = null;
try { digest = MessageDigest.getInstance("MD5");
} catch (Exception e2) {
// OK, we won't digest
}
instanceHash = getInstanceKey();
if (digest != null && !DONT_HASH) {
byte [] data = digest.digest(instanceHash.getBytes());
String tmp = new BigInteger(1,data).toString(16);
instanceHash = tmp;
}
return instanceHash;
}
public boolean isInstanceHashConsistent() {
return oldInstanceHash == null || instanceHash.equals(oldInstanceHash);
}
/**
* @param instanceOccurrenceNum The instanceOccurrenceNum to set.
*/
public void setInstanceOccurrenceNum(int instanceOccurrenceNum) {
this.instanceOccurrenceNum = instanceOccurrenceNum;
}
/**
* @return Returns the instanceOccurrenceNum.
*/
public int getInstanceOccurrenceNum() {
return instanceOccurrenceNum;
}
/**
* @param instanceOccurrenceMax The instanceOccurrenceMax to set.
*/
public void setInstanceOccurrenceMax(int instanceOccurrenceMax) {
this.instanceOccurrenceMax = instanceOccurrenceMax;
}
/**
* @return Returns the instanceOccurrenceMax.
*/
public int getInstanceOccurrenceMax() {
return instanceOccurrenceMax;
}
}
// vim:ts=4 |
package edu.umd.cs.findbugs.gui;
import java.util.*;
import java.io.*;
/**
* A project in the GUI.
* This consists of some number of Jar files, and (optionally)
* some number of source directories.
*
* @author David Hovemeyer
*/
public class Project {
/** Project filename. */
private String fileName;
/** The list of jar files. */
private ArrayList jarList;
/** The list of source directories. */
private ArrayList srcDirList;
/** Number of analysis runs done so far on this project. */
private int numAnalysisRuns;
/** Creates a new instance of Project */
public Project(String fileName) {
this.fileName = fileName;
jarList = new ArrayList();
srcDirList = new ArrayList();
numAnalysisRuns = 0;
}
/** Get the project filename. */
public String getFileName() { return fileName; }
/**
* Set the project filename.
* @param fileName the new filename
*/
public void setFileName(String fileName) {
this.fileName = fileName;
}
/**
* Add a Jar file to the project.
* @param fileName the jar file to add
* @return true if the jar file was added, or false if the jar
* file was already present
*/
public boolean addJar(String fileName) {
if (!jarList.contains(fileName)) {
jarList.add(fileName);
return true;
} else
return false;
}
/*
* Add a source directory to the project.
* @param dirName the directory to add
* @return true if the source directory was added, or false if the
* source directory was already present
*/
public boolean addSourceDir(String dirName) {
if (!srcDirList.contains(dirName)) {
srcDirList.add(dirName);
return true;
} else
return false;
}
/**
* Get the number of jar files in the project.
* @return the number of jar files in the project
*/
public int getNumJarFiles() { return jarList.size(); }
/**
* Get the given Jar file.
* @param num the number of the jar file
* @return the name of the jar file
*/
public String getJarFile(int num) { return (String) jarList.get(num); }
/**
* Remove jar file at given index.
* @param num index of the jar file to remove
*/
public void removeJarFile(int num) {
jarList.remove(num);
}
/**
* Get the number of source directories in the project.
* @return the number of source directories in the project
*/
public int getNumSourceDirs() { return srcDirList.size(); }
/**
* Get the given source directory.
* @param num the number of the source directory
* @return the source directory
*/
public String getSourceDir(int num) { return (String) srcDirList.get(num); }
/**
* Remove source directory at given index.
* @param num index of the source directory to remove
*/
public void removeSourceDir(int num) {
srcDirList.remove(num);
}
/**
* Get Jar files as an array of Strings.
*/
public String[] getJarFileArray() {
return (String[]) jarList.toArray(new String[0]);
}
/**
* Get source dirs as an array of Strings.
*/
public String[] getSourceDirArray() {
return (String[]) srcDirList.toArray(new String[0]);
}
/**
* Get the source dir list.
*/
public List getSourceDirList() {
return srcDirList;
}
/**
* Get the number of the next analysis run.
* The runs are numbered starting at 1.
*/
public int getNextAnalysisRun() {
return ++numAnalysisRuns;
}
private static final String JAR_FILES_KEY = "[Jar files]";
private static final String SRC_DIRS_KEY = "[Source dirs]";
/**
* Save the project to an output stream.
* @param out the OutputStream to write the project to
* @throws IOException if an error occurs while writing
*/
public void write(OutputStream out) throws IOException {
PrintWriter writer = new PrintWriter(new OutputStreamWriter(out));
writer.println(JAR_FILES_KEY);
for (Iterator i = jarList.iterator(); i.hasNext(); ) {
String jarFile = (String) i.next();
writer.println(jarFile);
}
writer.println(SRC_DIRS_KEY);
for (Iterator i = srcDirList.iterator(); i.hasNext(); ) {
String srcDir = (String) i.next();
writer.println(srcDir);
}
writer.close();
}
/**
* Read the project from an input stream.
* @param in the InputStream to read the project from
* @throws IOException if an error occurs while reading
*/
public void read(InputStream in) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
line = reader.readLine();
if (line == null || !line.equals(JAR_FILES_KEY)) throw new IOException("Bad format: missing jar files key");
while ((line = reader.readLine()) != null && !line.equals(SRC_DIRS_KEY)) {
jarList.add(line);
}
if (line == null) throw new IOException("Bad format: missing source dirs key");
while ((line = reader.readLine()) != null) {
srcDirList.add(line);
}
reader.close();
}
public String toString() {
String name = fileName;
int lastSep = name.lastIndexOf(File.separatorChar);
if (lastSep >= 0)
name = name.substring(lastSep + 1);
return name;
}
} |
// Revision 1.1 1999-01-31 13:33:08+00 sm11td
// Initial revision
package Debrief.Wrappers;
import java.awt.Color;
import java.awt.Font;
import java.awt.Point;
import java.beans.IntrospectionException;
import java.beans.MethodDescriptor;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyDescriptor;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.Vector;
import Debrief.ReaderWriter.Replay.FormatTracks;
import Debrief.Tools.Properties.TrackColorModePropertyEditor;
import Debrief.Wrappers.DynamicTrackShapes.DynamicTrackShapeSetWrapper;
import Debrief.Wrappers.DynamicTrackShapes.DynamicTrackShapeWrapper;
import Debrief.Wrappers.Track.AbsoluteTMASegment;
import Debrief.Wrappers.Track.CoreTMASegment;
import Debrief.Wrappers.Track.DynamicInfillSegment;
import Debrief.Wrappers.Track.PlanningSegment;
import Debrief.Wrappers.Track.RelativeTMASegment;
import Debrief.Wrappers.Track.SplittableLayer;
import Debrief.Wrappers.Track.TrackColorModeHelper;
import Debrief.Wrappers.Track.TrackColorModeHelper.DeferredDatasetColorMode;
import Debrief.Wrappers.Track.TrackColorModeHelper.TrackColorMode;
import Debrief.Wrappers.Track.TrackSegment;
import Debrief.Wrappers.Track.TrackWrapper_Support;
import Debrief.Wrappers.Track.TrackWrapper_Support.FixSetter;
import Debrief.Wrappers.Track.TrackWrapper_Support.SegmentList;
import Debrief.Wrappers.Track.TrackWrapper_Test;
import Debrief.Wrappers.Track.WormInHoleOffset;
import MWC.GUI.BaseLayer;
import MWC.GUI.CanvasType;
import MWC.GUI.DynamicPlottable;
import MWC.GUI.Editable;
import MWC.GUI.FireExtended;
import MWC.GUI.FireReformatted;
import MWC.GUI.HasEditables.ProvidesContiguousElements;
import MWC.GUI.Layer;
import MWC.GUI.Layers;
import MWC.GUI.MessageProvider;
import MWC.GUI.PlainWrapper;
import MWC.GUI.Plottable;
import MWC.GUI.Plottables;
import MWC.GUI.Plottables.IteratorWrapper;
import MWC.GUI.Canvas.CanvasTypeUtilities;
import MWC.GUI.Properties.FractionPropertyEditor;
import MWC.GUI.Properties.LabelLocationPropertyEditor;
import MWC.GUI.Properties.LineStylePropertyEditor;
import MWC.GUI.Properties.LineWidthPropertyEditor;
import MWC.GUI.Properties.NullableLocationPropertyEditor;
import MWC.GUI.Properties.TimeFrequencyPropertyEditor;
import MWC.GUI.Shapes.DraggableItem;
import MWC.GUI.Shapes.HasDraggableComponents;
import MWC.GUI.Shapes.TextLabel;
import MWC.GUI.Shapes.Symbols.SymbolFactoryPropertyEditor;
import MWC.GUI.Shapes.Symbols.Vessels.WorldScaledSym;
import MWC.GenericData.Duration;
import MWC.GenericData.HiResDate;
import MWC.GenericData.TimePeriod;
import MWC.GenericData.Watchable;
import MWC.GenericData.WatchableList;
import MWC.GenericData.WorldArea;
import MWC.GenericData.WorldDistance;
import MWC.GenericData.WorldDistance.ArrayLength;
import MWC.GenericData.WorldLocation;
import MWC.GenericData.WorldSpeed;
import MWC.GenericData.WorldVector;
import MWC.TacticalData.Fix;
import MWC.Utilities.TextFormatting.FormatRNDateTime;
/**
* the TrackWrapper maintains the GUI and data attributes of the whole track iteself, but the
* responsibility for the fixes within the track are demoted to the FixWrapper
*/
public class TrackWrapper extends MWC.GUI.PlainWrapper implements
WatchableList, MWC.GUI.Layer, DraggableItem, HasDraggableComponents,
ProvidesContiguousElements, ISecondaryTrack, DynamicPlottable
{
// member variables
/**
* class containing editable details of a track
*/
public final class trackInfo extends Editable.EditorType implements
Editable.DynamicDescriptors
{
/**
* constructor for this editor, takes the actual track as a parameter
*
* @param data
* track being edited
*/
public trackInfo(final TrackWrapper data)
{
super(data, data.getName(), "");
}
@Override
public final MethodDescriptor[] getMethodDescriptors()
{
// just add the reset color field first
final Class<TrackWrapper> c = TrackWrapper.class;
final MethodDescriptor[] _methodDescriptors =
new MethodDescriptor[]
{
method(c, "exportThis", null, "Export Shape"),
method(c, "resetLabels", null, "Reset DTG Labels"),
method(c, "calcCourseSpeed", null,
"Generate calculated Course and Speed")};
return _methodDescriptors;
}
@Override
public final String getName()
{
return super.getName();
}
@Override
public final PropertyDescriptor[] getPropertyDescriptors()
{
try
{
final PropertyDescriptor[] _coreDescriptors =
new PropertyDescriptor[]
{
displayExpertLongProp("SymbolType", "Symbol type",
"the type of symbol plotted for this label", FORMAT,
SymbolFactoryPropertyEditor.class),
displayExpertLongProp("LineThickness", "Line thickness",
"the width to draw this track", FORMAT,
LineWidthPropertyEditor.class),
expertProp("Name", "the track name"),
displayExpertProp("InterpolatePoints", "Interpolate points",
"whether to interpolate points between known data points",
SPATIAL),
expertProp("Color", "the track color", FORMAT),
displayExpertProp("EndTimeLabels", "Start/End time labels",
"Whether to label track start/end with 6-figure DTG",
VISIBILITY),
displayExpertProp("SymbolColor", "Symbol color",
"the color of the symbol (when used)", FORMAT),
displayExpertProp(
"PlotArrayCentre",
"Plot array centre",
"highlight the sensor array centre when non-zero array length provided",
VISIBILITY),
displayExpertProp("TrackFont", "Track font",
"the track label font", FORMAT),
displayExpertProp("NameVisible", "Name visible",
"show the track label", VISIBILITY),
displayExpertProp("PositionsVisible", "Positions visible",
"show individual Positions", VISIBILITY),
displayExpertProp("NameAtStart", "Name at start",
"whether to show the track name at the start (or end)",
VISIBILITY),
displayExpertProp("LinkPositions", "Link positions",
"whether to join the track points", VISIBILITY),
expertProp("Visible", "whether the track is visible",
VISIBILITY),
displayExpertLongProp("NameLocation", "Name location",
"relative location of track label", FORMAT,
MWC.GUI.Properties.NullableLocationPropertyEditor.class),
displayExpertLongProp("LabelFrequency", "Label frequency",
"the label frequency", TEMPORAL,
MWC.GUI.Properties.TimeFrequencyPropertyEditor.class),
displayExpertLongProp("SymbolFrequency", "Symbol frequency",
"the symbol frequency", TEMPORAL,
MWC.GUI.Properties.TimeFrequencyPropertyEditor.class),
displayExpertLongProp("ResampleDataAt", "Resample data at",
"the data sample rate", TEMPORAL,
MWC.GUI.Properties.TimeFrequencyPropertyEditor.class),
displayExpertLongProp("ArrowFrequency", "Arrow frequency",
"the direction marker frequency", TEMPORAL,
MWC.GUI.Properties.TimeFrequencyPropertyEditor.class),
displayProp("CustomTrailLength", "Custom Snail Trail",
"to specify a custom snail trail length",
Editable.EditorType.TEMPORAL),
displayExpertLongProp("CustomVectorStretch",
"Custom Vector Stretch",
"to specify a custom snail vector stretch",
Editable.EditorType.TEMPORAL, FractionPropertyEditor.class),
displayExpertLongProp("LineStyle", "Line style",
"the line style used to join track points", TEMPORAL,
MWC.GUI.Properties.LineStylePropertyEditor.class)};
PropertyDescriptor[] res;
// SPECIAL CASE: if we have a world scaled symbol, provide
// editors for
// the symbol size
final TrackWrapper item = (TrackWrapper) this.getData();
if (item._theSnailShape instanceof WorldScaledSym)
{
// yes = better create height/width editors
final PropertyDescriptor[] _coreDescriptorsWithSymbols =
new PropertyDescriptor[_coreDescriptors.length + 2];
System.arraycopy(_coreDescriptors, 0, _coreDescriptorsWithSymbols, 2,
_coreDescriptors.length);
_coreDescriptorsWithSymbols[0] =
displayExpertProp("SymbolLength", "Symbol length",
"Length of symbol", FORMAT);
_coreDescriptorsWithSymbols[1] =
displayExpertProp("SymbolWidth", "Symbol width",
"Width of symbol", FORMAT);
// and now use the new value
res = _coreDescriptorsWithSymbols;
}
else
{
res = _coreDescriptors;
}
// TRACK COLORING HANDLING
final List<TrackColorMode> datasets = getTrackColorModes();
if (datasets.size() > 0)
{
// store the datasets
TrackColorModePropertyEditor.setCustomModes(datasets);
final List<PropertyDescriptor> tmpList =
new ArrayList<PropertyDescriptor>();
tmpList.addAll(Arrays.asList(res));
// insert the editor
tmpList.add(displayExpertLongProp("TrackColorMode",
"Track Coloring Mode", "the mode in which to color the track",
FORMAT, TrackColorModePropertyEditor.class));
// ok. if we're in a measuremd mode, it may have a mode selector
res = tmpList.toArray(res);
// NOTE: this info class to implement Editable.DynamicDescriptors
// to avoid these descriptors being cached
}
return res;
}
catch (final IntrospectionException e)
{
return super.getPropertyDescriptors();
}
}
}
/**
* utility class to let us iterate through all positions without having to copy/paste them into a
* new object
*
* @author Ian
*
*/
private static class WrappedIterators implements Enumeration<Editable>
{
private final List<Enumeration<Editable>> lists = new ArrayList<>();
private int currentList = 0;
private Enumeration<Editable> currentIter;
public WrappedIterators()
{
currentIter = null;
}
public WrappedIterators(final SegmentList segments)
{
final Enumeration<Editable> ele = segments.elements();
while (ele.hasMoreElements())
{
final TrackSegment seg = (TrackSegment) ele.nextElement();
lists.add(seg.elements());
}
currentIter = this.lists.get(0);
}
public void add(final Enumeration<MWC.GUI.Editable> item)
{
lists.add(item);
if (currentIter == null)
{
currentIter = lists.get(0);
}
}
@Override
public boolean hasMoreElements()
{
while (currentList < lists.size() - 1 && !currentIter.hasMoreElements())
{
currentList++;
currentIter = lists.get(currentList);
}
return currentIter.hasMoreElements();
}
@Override
public Editable nextElement()
{
while (currentList < lists.size() - 1 && !currentIter.hasMoreElements())
{
currentList++;
currentIter = lists.get(currentList);
}
return currentIter.nextElement();
}
}
private static final String SOLUTIONS_LAYER_NAME = "Solutions";
public static final String SENSORS_LAYER_NAME = "Sensors";
public static final String DYNAMIC_SHAPES_LAYER_NAME = "Dynamic Shapes";
/**
* keep track of versions - version id
*/
static final long serialVersionUID = 1;
private static String checkTheyAreNotOverlapping(final Editable[] subjects)
{
// first, check they don't overlap.
// start off by collecting the periods
final TimePeriod[] _periods =
new TimePeriod.BaseTimePeriod[subjects.length];
for (int i = 0; i < subjects.length; i++)
{
final Editable editable = subjects[i];
TimePeriod thisPeriod = null;
if (editable instanceof TrackWrapper)
{
final TrackWrapper tw = (TrackWrapper) editable;
thisPeriod =
new TimePeriod.BaseTimePeriod(tw.getStartDTG(), tw.getEndDTG());
}
else if (editable instanceof TrackSegment)
{
final TrackSegment ts = (TrackSegment) editable;
thisPeriod = new TimePeriod.BaseTimePeriod(ts.startDTG(), ts.endDTG());
}
_periods[i] = thisPeriod;
}
// now test them.
String failedMsg = null;
for (int i = 0; i < _periods.length; i++)
{
final TimePeriod timePeriod = _periods[i];
for (int j = 0; j < _periods.length; j++)
{
final TimePeriod timePeriod2 = _periods[j];
// check it's not us
if (timePeriod2 != timePeriod)
{
if (timePeriod.overlaps(timePeriod2))
{
failedMsg =
"'" + subjects[i].getName() + "' and '" + subjects[j].getName()
+ "'";
break;
}
}
}
}
return failedMsg;
}
/**
*
* @param newTrack
* @param reference
* Note: these parameters are tested here
* @see TrackWrapper_Test#testTrackMerge1()
*/
private static void copyStyling(final TrackWrapper newTrack,
final TrackWrapper reference)
{
// Note: see link in javadoc for where these are tested
newTrack.setSymbolType(reference.getSymbolType());
newTrack.setSymbolWidth(reference.getSymbolWidth());
newTrack.setSymbolLength(reference.getSymbolLength());
newTrack.setSymbolColor(reference.getSymbolColor());
}
private static void duplicateFixes(final SegmentList sl,
final TrackSegment target)
{
final Enumeration<Editable> segs = sl.elements();
while (segs.hasMoreElements())
{
final TrackSegment segment = (TrackSegment) segs.nextElement();
if (segment instanceof CoreTMASegment)
{
final CoreTMASegment ct = (CoreTMASegment) segment;
final TrackSegment newSeg = new TrackSegment(ct);
duplicateFixes(newSeg, target);
}
else
{
duplicateFixes(segment, target);
}
}
}
private static void duplicateFixes(final TrackSegment source,
final TrackSegment target)
{
// ok, retrieve the points in the track segment
final Enumeration<Editable> tsPts = source.elements();
while (tsPts.hasMoreElements())
{
final FixWrapper existingFW = (FixWrapper) tsPts.nextElement();
final Fix existingFix = existingFW.getFix();
final Fix newFix = existingFix.makeCopy();
final FixWrapper newF = new FixWrapper(newFix);
// also duplicate the label
newF.setLabel(existingFW.getLabel());
target.addFix(newF);
}
}
/**
* put the other objects into this one as children
*
* @param wrapper
* whose going to receive it
* @param theLayers
* the top level layers object
* @param parents
* the track wrapppers containing the children
* @param subjects
* the items to insert.
*/
public static void groupTracks(final TrackWrapper target,
final Layers theLayers, final Layer[] parents, final Editable[] subjects)
{
// ok, loop through the subjects, adding them onto the target
for (int i = 0; i < subjects.length; i++)
{
final Layer thisL = (Layer) subjects[i];
final TrackWrapper thisP = (TrackWrapper) parents[i];
if (thisL != target)
{
// is it a plain segment?
if (thisL instanceof TrackWrapper)
{
// pass down through the positions/segments
final Enumeration<Editable> pts = thisL.elements();
while (pts.hasMoreElements())
{
final Editable obj = pts.nextElement();
if (obj instanceof SegmentList)
{
final SegmentList sl = (SegmentList) obj;
final Enumeration<Editable> segs = sl.elements();
while (segs.hasMoreElements())
{
final TrackSegment ts = (TrackSegment) segs.nextElement();
// reset the name if we need to
if (ts.getName().startsWith("Posi"))
{
ts.setName(FormatRNDateTime.toString(ts.startDTG().getDate()
.getTime()));
}
target.add(ts);
}
}
else
{
if (obj instanceof TrackSegment)
{
final TrackSegment ts = (TrackSegment) obj;
// reset the name if we need to
if (ts.getName().startsWith("Posi"))
{
ts.setName(FormatRNDateTime.toString(ts.startDTG().getDate()
.getTime()));
}
// and remember it
target.add(ts);
}
}
}
}
else
{
// get it's data, and add it to the target
target.add(thisL);
}
// and remove the layer from it's parent
if (thisL instanceof TrackSegment)
{
thisP.removeElement(thisL);
// does this just leave an empty husk?
if (thisP.numFixes() == 0)
{
// may as well ditch it anyway
theLayers.removeThisLayer(thisP);
}
}
else
{
// we'll just remove it from the top level layer
theLayers.removeThisLayer(thisL);
}
}
}
}
/**
* perform a merge of the supplied tracks.
*
* @param recipient
* the final recipient of the other items
* @param theLayers
* @param parents
* the parent tracks for the supplied items
* @param subjects
* the actual selected items
* @param _newName
* name to give to the merged object
* @return sufficient information to undo the merge
*/
public static int mergeTracks(final TrackWrapper newTrack,
final Layers theLayers, final Editable[] subjects)
{
// check that the legs don't overlap
final String failedMsg = checkTheyAreNotOverlapping(subjects);
// how did we get on?
if (failedMsg != null)
{
MessageProvider.Base.Provider.show("Merge tracks", "Sorry, " + failedMsg
+ " overlap in time. Please correct this and retry",
MessageProvider.ERROR);
return MessageProvider.ERROR;
}
// ok, loop through the subjects, adding them onto the target
for (int i = 0; i < subjects.length; i++)
{
final Layer thisL = (Layer) subjects[i];
// is it a plain segment?
if (thisL instanceof TrackWrapper)
{
// is this the first one? If so, we'll copy the symbol setup
if (i == 0)
{
final TrackWrapper track = (TrackWrapper) thisL;
copyStyling(newTrack, track);
}
// pass down through the positions/segments
final Enumeration<Editable> pts = thisL.elements();
while (pts.hasMoreElements())
{
final Editable obj = pts.nextElement();
if (obj instanceof SegmentList)
{
final SegmentList sl = (SegmentList) obj;
final TrackSegment newT = new TrackSegment(TrackSegment.ABSOLUTE);
duplicateFixes(sl, newT);
newTrack.add(newT);
}
else if (obj instanceof TrackSegment)
{
final TrackSegment ts = (TrackSegment) obj;
// ok, duplicate the fixes in this segment
final TrackSegment newT = new TrackSegment(TrackSegment.ABSOLUTE);
duplicateFixes(ts, newT);
// and add it to the new track
newTrack.append(newT);
}
}
}
else if (thisL instanceof TrackSegment)
{
final TrackSegment ts = (TrackSegment) thisL;
// ok, duplicate the fixes in this segment
final TrackSegment newT = new TrackSegment(ts.getPlotRelative());
duplicateFixes(ts, newT);
// and add it to the new track
newTrack.append(newT);
// is this the first one? If so, we'll copy the symbol setup
if (i == 0)
{
final TrackWrapper track = ts.getWrapper();
copyStyling(newTrack, track);
}
}
else if (thisL instanceof SegmentList)
{
final SegmentList sl = (SegmentList) thisL;
// is this the first one? If so, we'll copy the symbol setup
if (i == 0)
{
final TrackWrapper track = sl.getWrapper();
copyStyling(newTrack, track);
}
// it's absolute, since merged tracks are always
// absolute
final TrackSegment newT = new TrackSegment(TrackSegment.ABSOLUTE);
// ok, duplicate the fixes in this segment
duplicateFixes(sl, newT);
// and add it to the new track
newTrack.append(newT);
}
}
// and store the new track
theLayers.addThisLayer(newTrack);
return MessageProvider.OK;
}
/**
* perform a merge of the supplied tracks.
*
* @param target
* the final recipient of the other items
* @param theLayers
* @param parents
* the parent tracks for the supplied items
* @param subjects
* the actual selected items
* @return sufficient information to undo the merge
*/
public static int mergeTracksInPlace(final Editable target,
final Layers theLayers, final Layer[] parents, final Editable[] subjects)
{
// where we dump the new data points
Layer receiver = (Layer) target;
// check that the legs don't overlap
final String failedMsg = checkTheyAreNotOverlapping(subjects);
// how did we get on?
if (failedMsg != null)
{
MessageProvider.Base.Provider.show("Merge tracks", "Sorry, " + failedMsg
+ " overlap in time. Please correct this and retry",
MessageProvider.ERROR);
return MessageProvider.ERROR;
}
// right, if the target is a TMA track, we have to change it into a
// proper
// track, since
// the merged tracks probably contain manoeuvres
if (target instanceof CoreTMASegment)
{
final CoreTMASegment tma = (CoreTMASegment) target;
final TrackSegment newSegment = new TrackSegment(tma);
// now do some fancy footwork to remove the target from the wrapper,
// and
// replace it with our new segment
newSegment.getWrapper().removeElement(target);
newSegment.getWrapper().add(newSegment);
// store the new segment into the receiver
receiver = newSegment;
}
// ok, loop through the subjects, adding them onto the target
for (int i = 0; i < subjects.length; i++)
{
final Layer thisL = (Layer) subjects[i];
final TrackWrapper thisP = (TrackWrapper) parents[i];
// is this the target item (note we're comparing against the item
// passed
// in, not our
// temporary receiver, since the receiver may now be a tracksegment,
// not a
// TMA segment
if (thisL != target)
{
// is it a plain segment?
if (thisL instanceof TrackWrapper)
{
// pass down through the positions/segments
final Enumeration<Editable> pts = thisL.elements();
while (pts.hasMoreElements())
{
final Editable obj = pts.nextElement();
if (obj instanceof SegmentList)
{
final SegmentList sl = (SegmentList) obj;
final Enumeration<Editable> segs = sl.elements();
while (segs.hasMoreElements())
{
final TrackSegment ts = (TrackSegment) segs.nextElement();
receiver.add(ts);
}
}
else
{
final Layer ts = (Layer) obj;
receiver.append(ts);
}
}
}
else
{
// get it's data, and add it to the target
receiver.append(thisL);
}
// and remove the layer from it's parent
if (thisL instanceof TrackSegment)
{
thisP.removeElement(thisL);
// does this just leave an empty husk?
if (thisP.numFixes() == 0)
{
// may as well ditch it anyway
theLayers.removeThisLayer(thisP);
}
}
else
{
// we'll just remove it from the top level layer
theLayers.removeThisLayer(thisL);
}
}
}
return MessageProvider.OK;
}
/**
* whether to interpolate points in this track
*/
private boolean _interpolatePoints = false;
/**
* the end of the track to plot the label
*/
private boolean _LabelAtStart = true;
private HiResDate _lastLabelFrequency = new HiResDate(0);
private HiResDate _lastSymbolFrequency = new HiResDate(0);
private HiResDate _lastArrowFrequency = new HiResDate(0);
private HiResDate _lastDataFrequency = new HiResDate(0,
TimeFrequencyPropertyEditor.SHOW_ALL_FREQUENCY);
/**
* whether to show a time label at the start/end of the track
*
*/
private boolean _endTimeLabels = true;
/**
* the width of this track
*/
private int _lineWidth = 3;
/**
* the style of this line
*
*/
private int _lineStyle = CanvasType.SOLID;
/**
* whether or not to link the Positions
*/
private boolean _linkPositions;
/**
* whether to show a highlight for the array centre
*
*/
private boolean _plotArrayCentre;
/**
* our editable details
*/
protected transient Editable.EditorType _myEditor = null;
/**
* keep a list of points waiting to be plotted
*
*/
transient private int[] _myPts;
/**
* when plotting a track, we end up calling "get visible period" very frequently. So, we'll cache
* it, together with the time the cached version was generated. This will let us decide whether to
* recalculate, or to use a cached version
*
*/
transient private TimePeriod _cachedPeriod = null;
/**
* the time that we last calculated the time period
*
*/
transient private long _timeCachedPeriodCalculated = 0;
/**
* the sensor tracks for this vessel
*/
final private BaseLayer _mySensors;
/**
* the dynamic shapes for this vessel
*/
final private BaseLayer _myDynamicShapes;
/**
* the TMA solutions for this vessel
*/
final private BaseLayer _mySolutions;
/**
* keep track of how far we are through our array of points
*
*/
transient private int _ptCtr = 0;
/**
* whether or not to show the Positions
*/
private boolean _showPositions;
/**
* the label describing this track
*/
private final MWC.GUI.Shapes.TextLabel _theLabel;
/**
* the list of wrappers we hold
*/
protected SegmentList _thePositions;
/**
* the symbol to pass on to a snail plotter
*/
private MWC.GUI.Shapes.Symbols.PlainSymbol _theSnailShape;
/**
* flag for if there is a pending update to track - particularly if it's a relative one
*/
private boolean _relativeUpdatePending = false;
// member functions
transient private HiResDate lastDTG;
transient private FixWrapper lastFix;
/**
* working parameters
*/
transient private WorldArea _myWorldArea;
transient private final PropertyChangeListener _locationListener;
transient private PropertyChangeListener _childTrackMovedListener;
private Duration _customTrailLength = null;
private Double _customVectorStretch = null;
/**
* how to shade the track
*
*/
private TrackColorModeHelper.TrackColorMode _trackColorMode =
TrackColorModeHelper.LegacyTrackColorModes.PER_FIX;
// constructors
/**
* Wrapper for a Track (a series of position fixes). It combines the data with the formatting
* details
*/
public TrackWrapper()
{
_mySensors = new SplittableLayer(true);
_mySensors.setName(SENSORS_LAYER_NAME);
_myDynamicShapes = new SplittableLayer(true);
_myDynamicShapes.setName(DYNAMIC_SHAPES_LAYER_NAME);
_mySolutions = new BaseLayer(true);
_mySolutions.setName(SOLUTIONS_LAYER_NAME);
// create a property listener for when fixes are moved
_locationListener = new PropertyChangeListener()
{
@Override
public void propertyChange(final PropertyChangeEvent arg0)
{
fixMoved();
}
};
_childTrackMovedListener = new PropertyChangeListener()
{
@Override
public void propertyChange(final PropertyChangeEvent evt)
{
// child track move. remember that we need to recalculate & redraw
setRelativePending();
// also share the good news
firePropertyChange(PlainWrapper.LOCATION_CHANGED, null, System
.currentTimeMillis());
}
};
_linkPositions = true;
// start off with positions showing (although the default setting for a
// fix
// is to not show a symbol anyway). We need to make this "true" so that
// when a fix position is set to visible it is not over-ridden by this
// setting
_showPositions = true;
_theLabel = new MWC.GUI.Shapes.TextLabel(new WorldLocation(0, 0, 0), null);
// set an initial location for the label
setNameLocation(NullableLocationPropertyEditor.AUTO);
// initialise the symbol to use for plotting this track in snail mode
_theSnailShape =
MWC.GUI.Shapes.Symbols.SymbolFactory.createSymbol("Submarine");
// declare our arrays
_thePositions = new TrackWrapper_Support.SegmentList();
_thePositions.setWrapper(this);
}
/**
* add the indicated point to the track
*
* @param point
* the point to add
*/
@Override
public void add(final MWC.GUI.Editable point)
{
// see what type of object this is
if (point instanceof FixWrapper)
{
final FixWrapper fw = (FixWrapper) point;
fw.setTrackWrapper(this);
addFix(fw);
}
// is this a sensor?
else if (point instanceof SensorWrapper)
{
final SensorWrapper swr = (SensorWrapper) point;
// see if we already have a sensor with this name
SensorWrapper existing = null;
final Enumeration<Editable> enumer = _mySensors.elements();
while (enumer.hasMoreElements())
{
final SensorWrapper oldS = (SensorWrapper) enumer.nextElement();
// does this have the same name?
if (oldS.getName().equals(swr.getName()))
{
// yes - ok, remember it
existing = oldS;
// and append the data points
existing.append(swr);
}
}
// did we find it already?
if (existing == null)
{
// nope, so store it
_mySensors.add(swr);
}
// tell the sensor about us
swr.setHost(this);
// and the track name (if we're loading from REP it will already
// know
// the name, but if this data is being pasted in, it may start with
// a different
// parent track name - so override it here)
swr.setTrackName(this.getName());
}
// is this a dynamic shape?
else if (point instanceof DynamicTrackShapeSetWrapper)
{
final DynamicTrackShapeSetWrapper swr =
(DynamicTrackShapeSetWrapper) point;
// just check we don't alraedy have it
if (_myDynamicShapes.contains(swr))
{
MWC.Utilities.Errors.Trace
.trace("Don't allow duplicate shape set name:" + swr.getName());
}
else
{
// add to our list
_myDynamicShapes.add(swr);
// tell the sensor about us
swr.setHost(this);
}
}
// is this a TMA solution track?
else if (point instanceof TMAWrapper)
{
final TMAWrapper twr = (TMAWrapper) point;
// add to our list
_mySolutions.add(twr);
// tell the sensor about us
twr.setHost(this);
// and the track name (if we're loading from REP it will already
// know
// the name, but if this data is being pasted in, it may start with
// a different
// parent track name - so override it here)
twr.setTrackName(this.getName());
}
else if (point instanceof TrackSegment)
{
final TrackSegment seg = (TrackSegment) point;
seg.setWrapper(this);
_thePositions.addSegment((TrackSegment) point);
// hey, sort out the positions
sortOutRelativePositions();
// special case - see if it's a relative TMA segment,
// we many need some more sorting
if (point instanceof RelativeTMASegment)
{
final RelativeTMASegment newRelativeSegment =
(RelativeTMASegment) point;
// ok, try to update the layers. get the layers for an
// existing segment
final SegmentList sl = this.getSegments();
final Enumeration<Editable> sEnum = sl.elements();
while (sEnum.hasMoreElements())
{
final TrackSegment mySegment = (TrackSegment) sEnum.nextElement();
if (mySegment != newRelativeSegment)
{
// ok, it's not this one. try the layers
if (mySegment instanceof RelativeTMASegment)
{
final RelativeTMASegment myRelativeSegnent =
(RelativeTMASegment) mySegment;
final Layers myExistingLayers = myRelativeSegnent.getLayers();
if (myExistingLayers != newRelativeSegment.getLayers())
{
newRelativeSegment.setLayers(myExistingLayers);
break;
}
}
}
}
}
// we also need to listen for a child moving
seg.addPropertyChangeListener(CoreTMASegment.ADJUSTED,
_childTrackMovedListener);
}
else if (point instanceof Layer)
{
final Layer layer = (Layer) point;
final Enumeration<Editable> items = layer.elements();
while (items.hasMoreElements())
{
final Editable thisE = items.nextElement();
add(thisE);
}
}
else
{
MWC.GUI.Dialogs.DialogFactory.showMessage("Add point",
"Sorry it is not possible to add:" + point.getName() + " to "
+ this.getName());
}
}
public void addFix(final FixWrapper theFix)
{
// do we have any track segments
if (_thePositions.isEmpty())
{
// nope, add one
final TrackSegment firstSegment = new TrackSegment(TrackSegment.ABSOLUTE);
firstSegment.setName("Positions");
_thePositions.addSegment(firstSegment);
}
// add fix to last track segment
final TrackSegment last = (TrackSegment) _thePositions.last();
last.addFix(theFix);
// tell the fix about it's daddy
theFix.setTrackWrapper(this);
if (_myWorldArea == null)
{
_myWorldArea = new WorldArea(theFix.getLocation(), theFix.getLocation());
}
else
{
_myWorldArea.extend(theFix.getLocation());
}
// flush any cached values for time period & lists of positions
flushPeriodCache();
flushPositionCache();
}
/**
* append this other layer to ourselves (although we don't really bother with it)
*
* @param other
* the layer to add to ourselves
*/
@Override
public void append(final Layer other)
{
boolean modified = false;
// is it a track?
if ((other instanceof TrackWrapper) || (other instanceof TrackSegment))
{
// yes, break it down.
final java.util.Enumeration<Editable> iter = other.elements();
while (iter.hasMoreElements())
{
final Editable nextItem = iter.nextElement();
if (nextItem instanceof Layer)
{
append((Layer) nextItem);
modified = true;
}
else
{
add(nextItem);
modified = true;
}
}
}
else
{
// nope, just add it to us.
add(other);
modified = true;
}
if (modified)
{
setRelativePending();
}
}
/**
* Calculates Course & Speed for the track.
*/
public void calcCourseSpeed()
{
// step through our fixes
final Enumeration<Editable> iter = getPositionIterator();
FixWrapper prevFw = null;
while (iter.hasMoreElements())
{
final FixWrapper currFw = (FixWrapper) iter.nextElement();
if (prevFw == null)
{
prevFw = currFw;
}
else
{
// calculate the course
final WorldVector wv =
currFw.getLocation().subtract(prevFw.getLocation());
prevFw.getFix().setCourse(wv.getBearing());
// also, set the correct label alignment
currFw.resetLabelLocation();
// calculate the speed
// get distance in meters
final WorldDistance wd = new WorldDistance(wv);
final double distance = wd.getValueIn(WorldDistance.METRES);
// get time difference in seconds
final long timeDifference =
(currFw.getTime().getMicros() - prevFw.getTime().getMicros()) / 1000000;
// get speed in meters per second and convert it to knots
final WorldSpeed speed =
new WorldSpeed(distance / timeDifference, WorldSpeed.M_sec);
final double knots =
WorldSpeed.convert(WorldSpeed.M_sec, WorldSpeed.Kts, speed
.getValue());
prevFw.setSpeed(knots);
prevFw = currFw;
}
}
// if it's a DR track this will probably change things
setRelativePending();
}
private void checkPointsArray()
{
// is our points store long enough?
if ((_myPts == null) || (_myPts.length < numFixes() * 2))
{
_myPts = new int[numFixes() * 2];
}
// reset the points counter
_ptCtr = 0;
}
/**
* instruct this object to clear itself out, ready for ditching
*/
@Override
public final void closeMe()
{
// and my objects
// first ask them to close themselves
final Enumeration<Editable> it = getPositionIterator();
while (it.hasMoreElements())
{
final Editable val = it.nextElement();
if (val instanceof PlainWrapper)
{
final PlainWrapper pw = (PlainWrapper) val;
pw.closeMe();
}
else if (val instanceof TrackSegment)
{
final TrackSegment ts = (TrackSegment) val;
// and clear the parent item
ts.setWrapper(null);
// we also need to stop listen for a child moving
ts.removePropertyChangeListener(CoreTMASegment.ADJUSTED,
_childTrackMovedListener);
}
}
// now ditch them
_thePositions.removeAllElements();
_thePositions = null;
// and my objects
// first ask the sensors to close themselves
if (_mySensors != null)
{
final Enumeration<Editable> it2 = _mySensors.elements();
while (it2.hasMoreElements())
{
final Object val = it2.nextElement();
if (val instanceof PlainWrapper)
{
final PlainWrapper pw = (PlainWrapper) val;
pw.closeMe();
}
}
// now ditch them
_mySensors.removeAllElements();
}
// and my objects
// first ask the sensors to close themselves
if (_myDynamicShapes != null)
{
final Enumeration<Editable> it2 = _myDynamicShapes.elements();
while (it2.hasMoreElements())
{
final Object val = it2.nextElement();
if (val instanceof PlainWrapper)
{
final PlainWrapper pw = (PlainWrapper) val;
pw.closeMe();
}
}
// now ditch them
_myDynamicShapes.removeAllElements();
}
// now ask the solutions to close themselves
if (_mySolutions != null)
{
final Enumeration<Editable> it2 = _mySolutions.elements();
while (it2.hasMoreElements())
{
final Object val = it2.nextElement();
if (val instanceof PlainWrapper)
{
final PlainWrapper pw = (PlainWrapper) val;
pw.closeMe();
}
}
// now ditch them
_mySolutions.removeAllElements();
}
// and our utility objects
lastFix = null;
// and our editor
_myEditor = null;
// now get the parent to close itself
super.closeMe();
}
/**
* switch the two track sections into one track section
*
* @param res
* the previously split track sections
*/
public void combineSections(final Vector<TrackSegment> res)
{
// ok, remember the first
final TrackSegment keeper = res.firstElement();
// now remove them all, adding them to the first
final Iterator<TrackSegment> iter = res.iterator();
while (iter.hasNext())
{
final TrackSegment pl = iter.next();
if (pl != keeper)
{
keeper.append((Layer) pl);
}
removeElement(pl);
}
// and put the keepers back in
add(keeper);
// and remember we need an update
setRelativePending();
}
@Override
public int compareTo(final Plottable arg0)
{
Integer answer = null;
// SPECIAL PROCESSING: we wish to push TMA tracks to the top of any
// tracks shown in the outline view.
// is he a track?
if (arg0 instanceof TrackWrapper)
{
final TrackWrapper other = (TrackWrapper) arg0;
// yes, he's a track. See if we're a relative track
final boolean iAmTMA = isTMATrack();
// is he relative?
final boolean heIsTMA = other.isTMATrack();
if (heIsTMA)
{
// ok, he's a TMA segment. now we need to sort out if we are.
if (iAmTMA)
{
// we're both relative, compare names
answer = getName().compareTo(other.getName());
}
else
{
// only he is relative, he comes first
answer = 1;
}
}
else
{
// he's not relative. am I?
if (iAmTMA)
{
// I am , so go first
answer = -1;
}
}
}
else
{
// we're a track, they're not - put us at the end!
answer = 1;
}
// if we haven't worked anything out yet, just use the parent implementation
if (answer == null)
{
answer = super.compareTo(arg0);
}
return answer;
}
/**
* return our tiered data as a single series of elements
*
* @return
*/
@Override
public Enumeration<Editable> contiguousElements()
{
final WrappedIterators we = new WrappedIterators();
if (_mySensors != null)
{
final Enumeration<Editable> iter = _mySensors.elements();
while (iter.hasMoreElements())
{
final SensorWrapper sw = (SensorWrapper) iter.nextElement();
// is it visible?
if (sw.getVisible())
{
we.add(sw.elements());
}
}
}
if (_myDynamicShapes != null)
{
final Enumeration<Editable> iter = _myDynamicShapes.elements();
while (iter.hasMoreElements())
{
final DynamicTrackShapeSetWrapper sw =
(DynamicTrackShapeSetWrapper) iter.nextElement();
// is it visible?
if (sw.getVisible())
{
we.add(sw.elements());
}
}
}
if (_mySolutions != null)
{
final Enumeration<Editable> iter = _mySolutions.elements();
while (iter.hasMoreElements())
{
final TMAWrapper sw = (TMAWrapper) iter.nextElement();
if (sw.getVisible())
{
we.add(sw.elements());
}
}
}
if (_thePositions != null)
{
we.add(getPositionIterator());
}
return we;
}
/**
* this accessor is present for debug/testing purposes only. Do not use outside testing!
*
* @return the length of the list of screen points waiting to be plotted
*/
public int debug_GetPointCtr()
{
return _ptCtr;
}
/**
* this accessor is present for debug/testing purposes only. Do not use outside testing!
*
* @return the list of screen locations about to be plotted
*/
public int[] debug_GetPoints()
{
return _myPts;
}
/**
* get an enumeration of the points in this track
*
* @return the points in this track
*/
@Override
public Enumeration<Editable> elements()
{
final TreeSet<Editable> res = new TreeSet<Editable>();
if (!_mySensors.isEmpty())
{
res.add(_mySensors);
}
if (!_myDynamicShapes.isEmpty())
{
res.add(_myDynamicShapes);
}
if (!_mySolutions.isEmpty())
{
res.add(_mySolutions);
}
// ok, we want to wrap our fast-data as a set of plottables
// see how many track segments we have
if (_thePositions.size() == 1)
{
// just the one, insert it
res.add(_thePositions.first());
}
else
{
// more than one, insert them as a tree
res.add(_thePositions);
}
return new TrackWrapper_Support.IteratorWrapper(res.iterator());
}
/**
* export this track to REPLAY file
*/
@Override
public final void exportShape()
{
// call the method in PlainWrapper
this.exportThis();
}
/**
* filter the list to the specified time period, then inform any listeners (such as the time
* stepper)
*
* @param start
* the start dtg of the period
* @param end
* the end dtg of the period
*/
@Override
public final void filterListTo(final HiResDate start, final HiResDate end)
{
final Enumeration<Editable> fixWrappers = getPositionIterator();
while (fixWrappers.hasMoreElements())
{
final FixWrapper fw = (FixWrapper) fixWrappers.nextElement();
final HiResDate dtg = fw.getTime();
if ((dtg.greaterThanOrEqualTo(start)) && (dtg.lessThanOrEqualTo(end)))
{
fw.setVisible(true);
}
else
{
fw.setVisible(false);
}
}
// now do the same for our sensor data
if (_mySensors != null)
{
final Enumeration<Editable> iter = _mySensors.elements();
while (iter.hasMoreElements())
{
final WatchableList sw = (WatchableList) iter.nextElement();
sw.filterListTo(start, end);
} // through the sensors
} // whether we have any sensors
// now do the same for our sensor arc data
if (_myDynamicShapes != null)
{
final Enumeration<Editable> iter = _myDynamicShapes.elements();
while (iter.hasMoreElements())
{
final WatchableList sw = (WatchableList) iter.nextElement();
sw.filterListTo(start, end);
} // through the sensor arcs
} // whether we have any sensor arcs
if (_mySolutions != null)
{
final Enumeration<Editable> iter = _mySolutions.elements();
while (iter.hasMoreElements())
{
final WatchableList sw = (WatchableList) iter.nextElement();
sw.filterListTo(start, end);
} // through the sensors
} // whether we have any sensors
// do we have any property listeners?
if (getSupport() != null)
{
final Debrief.GUI.Tote.StepControl.somePeriod newPeriod =
new Debrief.GUI.Tote.StepControl.somePeriod(start, end);
getSupport().firePropertyChange(WatchableList.FILTERED_PROPERTY, null,
newPeriod);
}
}
// editing parameters
@Override
public void findNearestHotSpotIn(final Point cursorPos,
final WorldLocation cursorLoc, final ComponentConstruct currentNearest,
final Layer parentLayer)
{
// initialise thisDist, since we're going to be over-writing it
WorldDistance thisDist = new WorldDistance(0, WorldDistance.DEGS);
// cycle through the fixes
final Enumeration<Editable> fixes = getPositionIterator();
while (fixes.hasMoreElements())
{
final FixWrapper thisF = (FixWrapper) fixes.nextElement();
// only check it if it's visible
if (thisF.getVisible())
{
// how far away is it?
thisDist = thisF.getLocation().rangeFrom(cursorLoc, thisDist);
final WorldLocation fixLocation =
new WorldLocation(thisF.getLocation())
{
private static final long serialVersionUID = 1L;
@Override
public void addToMe(final WorldVector delta)
{
super.addToMe(delta);
thisF.setFixLocation(this);
}
};
// try range
currentNearest.checkMe(this, thisDist, null, parentLayer, fixLocation);
}
}
}
@Override
public void findNearestHotSpotIn(final Point cursorPos,
final WorldLocation cursorLoc, final LocationConstruct currentNearest,
final Layer parentLayer, final Layers theData)
{
// initialise thisDist, since we're going to be over-writing it
WorldDistance thisDist = new WorldDistance(0, WorldDistance.DEGS);
// cycle through the fixes
final Enumeration<Editable> fixes = getPositionIterator();
while (fixes.hasMoreElements())
{
final FixWrapper thisF = (FixWrapper) fixes.nextElement();
if (thisF.getVisible())
{
// how far away is it?
thisDist = thisF.getLocation().rangeFrom(cursorLoc, thisDist);
// is it closer?
currentNearest.checkMe(this, thisDist, null, parentLayer);
}
}
}
public void findNearestSegmentHotspotFor(final WorldLocation cursorLoc,
final Point cursorPt, final LocationConstruct currentNearest)
{
// initialise thisDist, since we're going to be over-writing it
WorldDistance thisDist;
// cycle through the track segments
final Collection<Editable> segments = _thePositions.getData();
for (final Iterator<Editable> iterator = segments.iterator(); iterator
.hasNext();)
{
final TrackSegment thisSeg = (TrackSegment) iterator.next();
if (thisSeg.getVisible())
{
// how far away is it?
thisDist =
new WorldDistance(thisSeg.rangeFrom(cursorLoc), WorldDistance.DEGS);
// is it closer?
currentNearest.checkMe(thisSeg, thisDist, null, this);
}
}
}
/**
* one of our fixes has moved. better tell any bits that rely on the locations of our bits
*
* @param theFix
* the fix that moved
*/
public void fixMoved()
{
if (_mySensors != null)
{
final Enumeration<Editable> iter = _mySensors.elements();
while (iter.hasMoreElements())
{
final SensorWrapper nextS = (SensorWrapper) iter.nextElement();
nextS.setHost(this);
}
}
if (_myDynamicShapes != null)
{
final Enumeration<Editable> iter = _myDynamicShapes.elements();
while (iter.hasMoreElements())
{
final DynamicTrackShapeSetWrapper nextS =
(DynamicTrackShapeSetWrapper) iter.nextElement();
nextS.setHost(this);
}
}
}
/**
* ensure the cached set of raw positions gets cleared
*
*/
public void flushPeriodCache()
{
_cachedPeriod = null;
}
/**
* ensure the cached set of raw positions gets cleared
*
*/
public void flushPositionCache()
{
}
/**
* return the arrow frequencies for the track
*
* @return frequency in seconds
*/
public final HiResDate getArrowFrequency()
{
return _lastArrowFrequency;
}
/**
* calculate a position the specified distance back along the ownship track (note, we always
* interpolate the parent track position)
*
* @param searchTime
* the time we're looking at
* @param sensorOffset
* how far back the sensor should be
* @param wormInHole
* whether to plot a straight line back, or make sensor follow ownship
* @return the location
*/
public FixWrapper getBacktraceTo(final HiResDate searchTime,
final ArrayLength sensorOffset, final boolean wormInHole)
{
FixWrapper res = null;
// special case - for single point tracks
if (isSinglePointTrack())
{
TrackSegment seg = (TrackSegment) _thePositions.elements().nextElement();
return (FixWrapper) seg.first();
}
if (wormInHole && sensorOffset != null)
{
res = WormInHoleOffset.getWormOffsetFor(this, searchTime, sensorOffset);
}
else
{
final boolean parentInterpolated = getInterpolatePoints();
setInterpolatePoints(true);
final MWC.GenericData.Watchable[] list = getNearestTo(searchTime);
// and restore the interpolated value
setInterpolatePoints(parentInterpolated);
FixWrapper wa = null;
if (list.length > 0)
{
wa = (FixWrapper) list[0];
}
// did we find it?
if (wa != null)
{
// yes, store it
res = new FixWrapper(wa.getFix().makeCopy());
// ok, are we dealing with an offset?
if (sensorOffset != null)
{
// get the current heading
final double hdg = wa.getCourse();
// and calculate where it leaves us
final WorldVector vector = new WorldVector(hdg, sensorOffset, null);
// now apply this vector to the origin
res.setLocation(new WorldLocation(res.getLocation().add(vector)));
}
}
}
return res;
}
/**
* what geographic area is covered by this track?
*
* @return get the outer bounds of the area
*/
@Override
public final WorldArea getBounds()
{
// we no longer just return the bounds of the track, because a portion
// of the track may have been made invisible.
// instead, we will pass through the full dataset and find the outer
// bounds
// of the visible area
WorldArea res = null;
if (!getVisible())
{
// hey, we're invisible, return null
}
else
{
final Enumeration<Editable> it = getPositionIterator();
while (it.hasMoreElements())
{
final FixWrapper fw = (FixWrapper) it.nextElement();
// is this point visible?
if (fw.getVisible())
{
// has our data been initialised?
if (res == null)
{
// no, initialise it
res = new WorldArea(fw.getLocation(), fw.getLocation());
}
else
{
// yes, extend to include the new area
res.extend(fw.getLocation());
}
}
}
// also extend to include our sensor data
if (_mySensors != null)
{
final Enumeration<Editable> iter = _mySensors.elements();
while (iter.hasMoreElements())
{
final PlainWrapper sw = (PlainWrapper) iter.nextElement();
final WorldArea theseBounds = sw.getBounds();
if (theseBounds != null)
{
if (res == null)
{
res = new WorldArea(theseBounds);
}
else
{
res.extend(sw.getBounds());
}
}
} // step through the sensors
} // whether we have any sensors
// also extend to include our sensor data
if (_myDynamicShapes != null)
{
final Enumeration<Editable> iter = _myDynamicShapes.elements();
while (iter.hasMoreElements())
{
final Plottable sw = (Plottable) iter.nextElement();
final WorldArea theseBounds = sw.getBounds();
if (theseBounds != null)
{
if (res == null)
{
res = new WorldArea(theseBounds);
}
else
{
res.extend(sw.getBounds());
}
}
} // step through the sensors
}
// and our solution data
if (_mySolutions != null)
{
final Enumeration<Editable> iter = _mySolutions.elements();
while (iter.hasMoreElements())
{
final PlainWrapper sw = (PlainWrapper) iter.nextElement();
final WorldArea theseBounds = sw.getBounds();
if (theseBounds != null)
{
if (res == null)
{
res = new WorldArea(theseBounds);
}
else
{
res.extend(sw.getBounds());
}
}
} // step through the sensors
} // whether we have any sensors
} // whether we're visible
// SPECIAL CASE: if we're a DR track, the positions all
// have the same value
if (res != null)
{
// have we ended up with an empty area?
if (res.getHeight() == 0)
{
// ok - force a bounds update
sortOutRelativePositions();
// and retrieve the bounds of hte first segment
res = this.getSegments().first().getBounds();
}
}
return res;
}
/**
* length of trail to plot
*/
public final Duration getCustomTrailLength()
{
return _customTrailLength;
}
/**
* length of trail to plot
*/
public final double getCustomVectorStretch()
{
final double res;
// do we have a value?
if (_customVectorStretch != null)
{
res = _customVectorStretch;
}
else
{
res = 0;
}
return res;
}
/**
* get the list of sensor arcs for this track
*/
public final BaseLayer getDynamicShapes()
{
return _myDynamicShapes;
}
/**
* the time of the last fix
*
* @return the DTG
*/
@Override
public final HiResDate getEndDTG()
{
HiResDate dtg = null;
final TimePeriod res = getTimePeriod();
if (res != null)
{
dtg = res.getEndDTG();
}
return dtg;
}
/**
* whether to show time labels at the start/end of the track
*
* @return yes/no
*/
public boolean getEndTimeLabels()
{
return _endTimeLabels;
}
/**
* the editable details for this track
*
* @return the details
*/
@Override
public Editable.EditorType getInfo()
{
if (_myEditor == null)
{
_myEditor = new trackInfo(this);
}
return _myEditor;
}
/**
* create a new, interpolated point between the two supplied
*
* @param previous
* the previous point
* @param next
* the next point
* @return and interpolated point
*/
private final FixWrapper getInterpolatedFix(final FixWrapper previous,
final FixWrapper next, final HiResDate requestedDTG)
{
FixWrapper res = null;
// do we have a start point
if (previous == null)
{
res = next;
}
// hmm, or do we have an end point?
if (next == null)
{
res = previous;
}
// did we find it?
if (res == null)
{
res = FixWrapper.interpolateFix(previous, next, requestedDTG);
}
return res;
}
@Override
public final boolean getInterpolatePoints()
{
return _interpolatePoints;
}
/**
* get the set of fixes contained within this time period (inclusive of both end values)
*
* @param start
* start DTG
* @param end
* end DTG
* @return series of fixes
*/
@Override
public final Collection<Editable> getItemsBetween(final HiResDate start,
final HiResDate end)
{
SortedSet<Editable> set = null;
// does our track contain any data at all
if (!_thePositions.isEmpty())
{
// see if we have _any_ points in range
if ((getStartDTG().greaterThan(end)) || (getEndDTG().lessThan(start)))
{
// don't bother with it.
}
else
{
// SPECIAL CASE! If we've been asked to show interpolated data
// points,
// then
// we should produce a series of items between the indicated
// times. How
// about 1 minute resolution?
if (getInterpolatePoints())
{
final long ourInterval = 1000 * 60; // one minute
set = new TreeSet<Editable>();
for (long newTime = start.getDate().getTime(); newTime < end
.getDate().getTime(); newTime += ourInterval)
{
final HiResDate newD = new HiResDate(newTime);
final Watchable[] nearestOnes = getNearestTo(newD);
if (nearestOnes.length > 0)
{
final FixWrapper nearest = (FixWrapper) nearestOnes[0];
set.add(nearest);
}
}
}
else
{
// bugger that - get the real data
final Enumeration<Editable> iter = getPositionIterator();
set = new TreeSet<Editable>();
final TimePeriod period = new TimePeriod.BaseTimePeriod(start, end);
while (iter.hasMoreElements())
{
final FixWrapper nextF = (FixWrapper) iter.nextElement();
final HiResDate dtg = nextF.getDateTimeGroup();
if (period.contains(dtg))
{
set.add(nextF);
}
else if (dtg.greaterThan(end))
{
// ok, we've passed the end
break;
}
}
// // have a go..
// if (starter == null)
// starter = new FixWrapper(new Fix((start), _zeroLocation, 0.0, 0.0));
// else
// starter.getFix().setTime(new HiResDate(0, start.getMicros() - 1));
// if (finisher == null)
// finisher =
// new FixWrapper(new Fix(new HiResDate(0, end.getMicros() + 1),
// _zeroLocation, 0.0, 0.0));
// else
// finisher.getFix().setTime(new HiResDate(0, end.getMicros() + 1));
// // ok, ready, go for it.
// set = getPositionsBetween(starter, finisher);
}
}
}
return set;
}
/**
* method to allow the setting of label frequencies for the track
*
* @return frequency to use
*/
public final HiResDate getLabelFrequency()
{
return this._lastLabelFrequency;
}
/**
* what is the style used for plotting this track?
*
* @return
*/
public int getLineStyle()
{
return _lineStyle;
}
/**
* the line thickness (convenience wrapper around width)
*
* @return
*/
@Override
public int getLineThickness()
{
return _lineWidth;
}
/**
* whether to link points
*
* @return
*/
public boolean getLinkPositions()
{
return _linkPositions;
}
/**
* just have the one property listener - rather than an anonymous class
*
* @return
*/
public PropertyChangeListener getLocationListener()
{
return _locationListener;
}
/**
* name of this Track (normally the vessel name)
*
* @return the name
*/
@Override
public final String getName()
{
return _theLabel.getString();
}
/**
* whether to show the track label at the start or end of the track
*
* @return yes/no to indicate <I>At Start</I>
*/
public final boolean getNameAtStart()
{
return _LabelAtStart;
}
/**
* the relative location of the label
*
* @return the relative location
*/
public final Integer getNameLocation()
{
return _theLabel.getRelativeLocation();
}
/**
* whether the track label is visible or not
*
* @return yes/no
*/
public final boolean getNameVisible()
{
return _theLabel.getVisible();
}
/**
* find the fix nearest to this time (or the first fix for an invalid time)
*
* @param DTG
* the time of interest
* @return the nearest fix
*/
@Override
public final Watchable[] getNearestTo(final HiResDate srchDTG)
{
/**
* we need to end up with a watchable, not a fix, so we need to work our way through the fixes
*/
FixWrapper res = null;
// check that we do actually contain some data
if (_thePositions.isEmpty())
{
return new Watchable[]
{};
}
else if (isSinglePointTrack())
{
TrackSegment seg = (TrackSegment) _thePositions.elements().nextElement();
FixWrapper fix = (FixWrapper) seg.first();
return new Watchable[]
{fix};
}
// special case - if we've been asked for an invalid time value
if (srchDTG == TimePeriod.INVALID_DATE)
{
final TrackSegment seg = (TrackSegment) _thePositions.first();
final FixWrapper fix = (FixWrapper) seg.first();
// just return our first location
return new MWC.GenericData.Watchable[]
{fix};
}
else if ((srchDTG.equals(lastDTG)) && (lastFix != null))
{
// see if this is the DTG we have just requestsed
res = lastFix;
}
else
{
final TrackSegment firstSeg = (TrackSegment) _thePositions.first();
final TrackSegment lastSeg = (TrackSegment) _thePositions.last();
if ((firstSeg != null) && (!firstSeg.isEmpty()))
{
// see if this DTG is inside our data range
// in which case we will just return null
final FixWrapper theFirst = (FixWrapper) firstSeg.first();
final FixWrapper theLast = (FixWrapper) lastSeg.last();
if ((srchDTG.greaterThan(theFirst.getTime()))
&& (srchDTG.lessThanOrEqualTo(theLast.getTime())))
{
// yes it's inside our data range, find the first fix
// after the indicated point
final Enumeration<Editable> pIter = getPositionIterator();
FixWrapper previous = null;
while (pIter.hasMoreElements())
{
final FixWrapper fw = (FixWrapper) pIter.nextElement();
if (fw.getVisible())
{
if (fw.getDTG().greaterThanOrEqualTo(srchDTG))
{
res = fw;
break;
}
// and remember the previous one
previous = fw;
}
}
// right, that's the first points on or before the indicated
// DTG. Are we
// meant
// to be interpolating?
if (res != null)
{
if (getInterpolatePoints())
{
if (!res.getTime().equals(srchDTG))
{
// do we know the previous time?
if (previous != null)
{
// cool, sort out the interpolated point USING
// THE ORIGINAL
// SEARCH TIME
res = getInterpolatedFix(previous, res, srchDTG);
// and reset the label
res.resetName();
}
}
}
}
}
else if (srchDTG.equals(theFirst.getDTG()))
{
// aaah, special case. just see if we're after a data point
// that's the
// same
// as our start time
res = theFirst;
}
}
// and remember this fix
lastFix = res;
lastDTG = srchDTG;
}
if (res != null)
{
return new MWC.GenericData.Watchable[]
{res};
}
else
{
return new MWC.GenericData.Watchable[]
{};
}
}
public boolean getPlotArrayCentre()
{
return _plotArrayCentre;
}
/**
* provide iterator for all positions that doesn't require a new list to be generated
*
* @return iterator through all positions
*/
public Enumeration<Editable> getPositionIterator()
{
// loop through segments
// final Enumeration<Editable> segs = _thePositions.elements();
// List<TrackSegment> list = new ArrayList<TrackSegment>();
// while (segs.hasMoreElements())
// // get this segment
// final TrackSegment seg = (TrackSegment) segs.nextElement();
// list.add(seg);
return new WrappedIterators(_thePositions);
}
/**
* whether positions are being shown
*
* @return
*/
public final boolean getPositionsVisible()
{
return _showPositions;
}
/**
* method to allow the setting of data sampling frequencies for the track & sensor data
*
* @return frequency to use
*/
public final HiResDate getResampleDataAt()
{
return this._lastDataFrequency;
}
/**
* get our child segments
*
* @return
*/
public SegmentList getSegments()
{
return _thePositions;
}
/**
* get the list of sensors for this track
*/
public final BaseLayer getSensors()
{
return _mySensors;
}
/**
* return the symbol to be used for plotting this track in snail mode
*/
@Override
public final MWC.GUI.Shapes.Symbols.PlainSymbol getSnailShape()
{
return _theSnailShape;
}
/**
* get the list of sensors for this track
*/
public final BaseLayer getSolutions()
{
return _mySolutions;
}
// watchable (tote related) parameters
/**
* the earliest fix in the track
*
* @return the DTG
*/
@Override
public final HiResDate getStartDTG()
{
HiResDate res = null;
final TimePeriod period = getTimePeriod();
if (period != null)
{
res = period.getStartDTG();
}
return res;
}
/**
* get the color used to plot the symbol
*
* @return the color
*/
public final Color getSymbolColor()
{
return _theSnailShape.getColor();
}
/**
* return the symbol frequencies for the track
*
* @return frequency in seconds
*/
public final HiResDate getSymbolFrequency()
{
return _lastSymbolFrequency;
}
public WorldDistance getSymbolLength()
{
WorldDistance res = null;
if (_theSnailShape instanceof WorldScaledSym)
{
final WorldScaledSym sym = (WorldScaledSym) _theSnailShape;
res = sym.getLength();
}
return res;
}
/**
* get the type of this symbol
*/
public final String getSymbolType()
{
return _theSnailShape.getType();
}
public WorldDistance getSymbolWidth()
{
WorldDistance res = null;
if (_theSnailShape instanceof WorldScaledSym)
{
final WorldScaledSym sym = (WorldScaledSym) _theSnailShape;
res = sym.getWidth();
}
return res;
}
private TimePeriod getTimePeriod()
{
TimePeriod res = null;
final Enumeration<Editable> segs = _thePositions.elements();
while (segs.hasMoreElements())
{
final TrackSegment seg = (TrackSegment) segs.nextElement();
// do we have a dtg?
if ((seg.startDTG() != null) && (seg.endDTG() != null))
{
// yes, get calculating
if (res == null)
{
res = new TimePeriod.BaseTimePeriod(seg.startDTG(), seg.endDTG());
}
else
{
res.extend(seg.startDTG());
res.extend(seg.endDTG());
}
}
}
return res;
}
/**
* the colour of the points on the track
*
* @return the colour
*/
public final Color getTrackColor()
{
return getColor();
}
/**
* get the mode used to color the track
*
* @return
*/
public TrackColorMode getTrackColorMode()
{
// ok, see if we're using a deferred mode. If we are, we should correct it
if (_trackColorMode instanceof DeferredDatasetColorMode)
{
_trackColorMode =
TrackColorModeHelper.sortOutDeferredMode(
(DeferredDatasetColorMode) _trackColorMode, this);
}
return _trackColorMode;
}
public List<TrackColorMode> getTrackColorModes()
{
return TrackColorModeHelper.getAdditionalTrackColorModes(this);
}
/**
* font handler
*
* @return the font to use for the label
*/
public final java.awt.Font getTrackFont()
{
return _theLabel.getFont();
}
/**
* get the set of fixes contained within this time period which haven't been filtered, and which
* have valid depths. The isVisible flag indicates whether a track has been filtered or not. We
* also have the getVisibleFixesBetween method (below) which decides if a fix is visible if it is
* set to Visible, and it's label or symbol are visible.
* <p/>
* We don't have to worry about a valid depth, since 3d doesn't show points with invalid depth
* values
*
* @param start
* start DTG
* @param end
* end DTG
* @return series of fixes
*/
public final Collection<Editable> getUnfilteredItems(final HiResDate start,
final HiResDate end)
{
// see if we have _any_ points in range
if ((getStartDTG().greaterThan(end)) || (getEndDTG().lessThan(start)))
{
return null;
}
if (this.getVisible() == false)
{
return null;
}
// get ready for the output
final Vector<Editable> res = new Vector<Editable>(0, 1);
// put the data into a period
final TimePeriod thePeriod = new TimePeriod.BaseTimePeriod(start, end);
// step through our fixes
final Enumeration<Editable> iter = getPositionIterator();
while (iter.hasMoreElements())
{
final FixWrapper fw = (FixWrapper) iter.nextElement();
if (fw.getVisible())
{
// is it visible?
if (thePeriod.contains(fw.getTime()))
{
// hey, it's valid - continue
res.add(fw);
}
}
}
return res;
}
/**
* Determine the time period for which we have visible locations
*
* @return
*/
public TimePeriod getVisiblePeriod()
{
// ok, have we determined the visible period recently?
final long tNow = System.currentTimeMillis();
// how long does the cached value remain valid for?
final long ALLOWABLE_PERIOD = 500;
if (_cachedPeriod != null
&& tNow - _timeCachedPeriodCalculated < ALLOWABLE_PERIOD)
{
// still in date, use the last calculated period
}
else
{
// ok, calculate a new one
TimePeriod res = null;
final Enumeration<Editable> pos = getPositionIterator();
while (pos.hasMoreElements())
{
final FixWrapper editable = (FixWrapper) pos.nextElement();
if (editable.getVisible())
{
final HiResDate thisT = editable.getTime();
if (res == null)
{
res = new TimePeriod.BaseTimePeriod(thisT, thisT);
}
else
{
res.extend(thisT);
}
}
}
// ok, store the new time period
_cachedPeriod = res;
// remember when it was calculated
_timeCachedPeriodCalculated = tNow;
}
return _cachedPeriod;
}
/**
* whether this object has editor details
*
* @return yes/no
*/
@Override
public final boolean hasEditor()
{
return true;
}
@Override
public boolean hasOrderedChildren()
{
return false;
}
/**
* accessor to determine if this is a relative track
*
* @return
*/
public boolean isTMATrack()
{
boolean res = false;
if (_thePositions != null && !_thePositions.isEmpty()
&& _thePositions.first() instanceof CoreTMASegment)
{
res = true;
}
return res;
}
/**
* whether this is single point track. Single point tracks get special processing.
*
* @return
*/
public boolean isSinglePointTrack()
{
final boolean res;
if (_thePositions.size() == 1)
{
TrackSegment first =
(TrackSegment) _thePositions.elements().nextElement();
// we want to avoid getting the size() of the list.
// So, do fancy trick to check the first element is non-null,
// and the second is null
Enumeration<Editable> elems = first.elements();
if (elems != null && elems.hasMoreElements()
&& elems.nextElement() != null && !elems.hasMoreElements())
{
res = true;
}
else
{
res = false;
}
}
else
{
res = false;
}
return res;
}
public boolean isVisibleAt(final HiResDate dtg)
{
boolean res = false;
// special case - single track
if (isSinglePointTrack())
{
// we'll assume it's never ending.
res = true;
}
else
{
final TimePeriod visiblePeriod = getVisiblePeriod();
if (visiblePeriod != null)
{
res = visiblePeriod.contains(dtg);
}
}
return res;
}
/**
* quick accessor for how many fixes we have
*
* @return
*/
public int numFixes()
{
int res = 0;
// loop through segments
final Enumeration<Editable> segs = _thePositions.elements();
while (segs.hasMoreElements())
{
// get this segment
final TrackSegment seg = (TrackSegment) segs.nextElement();
res += seg.size();
}
return res;
}
/**
* draw this track (we can leave the Positions to draw themselves)
*
* @param dest
* the destination
*/
@Override
public final void paint(final CanvasType dest)
{
// check we are visible and have some track data, else we won't work
if (!getVisible() || this.getStartDTG() == null)
{
return;
}
// set the thickness for this track
dest.setLineWidth(_lineWidth);
// and set the initial colour for this track
if (getColor() != null)
{
dest.setColor(getColor());
}
// firstly plot the solutions
if (_mySolutions.getVisible())
{
final Enumeration<Editable> iter = _mySolutions.elements();
while (iter.hasMoreElements())
{
final TMAWrapper sw = (TMAWrapper) iter.nextElement();
// just check that the sensor knows we're it's parent
if (sw.getHost() == null)
{
sw.setHost(this);
}
// and do the paint
sw.paint(dest);
} // through the solutions
} // whether the solutions are visible
// now plot the sensors
if (_mySensors.getVisible())
{
final Enumeration<Editable> iter = _mySensors.elements();
while (iter.hasMoreElements())
{
final SensorWrapper sw = (SensorWrapper) iter.nextElement();
// just check that the sensor knows we're it's parent
if (sw.getHost() == null)
{
sw.setHost(this);
}
// and do the paint
sw.paint(dest);
} // through the sensors
} // whether the sensor layer is visible
// and now the track itself
// just check if we are drawing anything at all
if ((!getLinkPositions() || getLineStyle() == LineStylePropertyEditor.UNCONNECTED)
&& (!_showPositions))
{
return;
}
// let the fixes draw themselves in
final List<FixWrapper> endPoints = paintFixes(dest);
final boolean plotted_anything = !endPoints.isEmpty();
// and draw the track label
// still, we only plot the track label if we have plotted any
// points
if (getNameVisible() && plotted_anything)
{
// just see if we have multiple segments. if we do,
// name them individually
if (this._thePositions.size() <= 1)
{
paintSingleTrackLabel(dest, endPoints);
}
else
{
// we've got multiple segments, name them
paintMultipleSegmentLabel(dest);
}
} // if the label is visible
// lastly - paint any TMA or planning segment labels
paintVectorLabels(dest);
}
@Override
public void paint(final CanvasType dest, final long time)
{
if (!getVisible())
{
return;
}
// set the thickness for this track
dest.setLineWidth(_lineWidth);
// and set the initial colour for this track
if (getColor() != null)
{
dest.setColor(getColor());
}
// we plot only the dynamic arcs because they are MovingPlottable
if (_myDynamicShapes.getVisible())
{
final Enumeration<Editable> iter = _myDynamicShapes.elements();
while (iter.hasMoreElements())
{
final DynamicTrackShapeSetWrapper sw =
(DynamicTrackShapeSetWrapper) iter.nextElement();
// and do the paint
sw.paint(dest, time);
}
}
}
/**
* paint the fixes for this track
*
* @param dest
* @return a collection containing the first & last visible fix
*/
private List<FixWrapper> paintFixes(final CanvasType dest)
{
// collate a list of the start & end points
final List<FixWrapper> endPoints = new ArrayList<FixWrapper>();
// use the track color mode
final TrackColorMode tMode = getTrackColorMode();
// we need an array to store the polyline of points in. Check it's big
// enough
checkPointsArray();
// we draw tracks as polylines. But we can't do that
// if the color/style changes. So, we have to track their values
Color lastCol = null;
final int defaultlineStyle = getLineStyle();
FixWrapper lastFix = null;
// update DR positions (if necessary)
if (_relativeUpdatePending)
{
// ok, generate the points on the relative track
sortOutRelativePositions();
// and clear the flag
_relativeUpdatePending = false;
}
// cycle through the segments
final Enumeration<Editable> segments = _thePositions.elements();
while (segments.hasMoreElements())
{
final TrackSegment seg = (TrackSegment) segments.nextElement();
// is it a single point segment?
final boolean singlePointSegment = seg.size() == 1;
// how shall we plot this segment?
final int thisLineStyle;
// is the parent using the default style?
if (defaultlineStyle == CanvasType.SOLID)
{
// yes, let's override it, if the segment wants to
thisLineStyle = seg.getLineStyle();
}
else
{
// no, we're using a custom style - don't override it.
thisLineStyle = defaultlineStyle;
}
// is this segment visible?
if (!seg.getVisible())
{
// nope, jump to the next
continue;
}
final Enumeration<Editable> fixWrappers = seg.elements();
while (fixWrappers.hasMoreElements())
{
final FixWrapper fw = (FixWrapper) fixWrappers.nextElement();
// have a look at the last fix. we defer painting the fix label,
// because we want to know the id of the last visible fix, since
// we may need to paint it's label in 6 DTG
if ((getPositionsVisible() && lastFix != null && lastFix.getVisible())
|| singlePointSegment)
{
// is this the first visible fix?
final boolean isFirstVisibleFix = endPoints.size() == 1;
// special handling. if we only have one point in the segment,
// we treat it as the last fix
final FixWrapper newLastFix;
if (lastFix == null)
{
newLastFix = fw;
}
else
{
newLastFix = lastFix;
}
// more special processing - for single-point segments
final boolean symWasVisible = newLastFix.getSymbolShowing();
if (singlePointSegment)
{
newLastFix.setSymbolShowing(true);
}
paintIt(dest, newLastFix, getEndTimeLabels() && isFirstVisibleFix,
false);
if (singlePointSegment)
{
newLastFix.setSymbolShowing(symWasVisible);
}
}
// now there's a chance that our fix has forgotten it's
// parent,
// particularly if it's the victim of a
// copy/paste operation. Tell it about it's children
fw.setTrackWrapper(this);
final Color thisFixColor = tMode.colorFor(fw);
// do our job of identifying the first & last date value
if (fw.getVisible())
{
// ok, see if this is the first one
if (endPoints.size() == 0)
{
endPoints.add(fw);
}
else
{
// have we already got an end value?
if (endPoints.size() == 2)
{
// yes, drop it
endPoints.remove(1);
}
// store a new end value
endPoints.add(fw);
}
}
else
{
// nope. Don't join it to the last position.
// ok, if we've built up a polygon, we need to write it
// now
paintSetOfPositions(dest, lastCol, thisLineStyle);
}
// remember this fix, used for relative tracks
lastFix = fw;
// ok, we only do this writing to screen if the actual
// position is visible
if (!fw.getVisible())
{
continue;
}
final java.awt.Point thisP = dest.toScreen(fw.getLocation());
// just check that there's enough GUI to create the plot
// (i.e. has a point been returned)
if (thisP == null)
{
return endPoints;
}
// are we
if (getLinkPositions()
&& (getLineStyle() != LineStylePropertyEditor.UNCONNECTED))
{
// right, just check if we're a different colour to
// the previous one
final Color thisCol = thisFixColor;
// do we know the previous colour
if (lastCol == null)
{
lastCol = thisCol;
}
// is this to be joined to the previous one?
if (fw.getLineShowing())
{
// so, grow the the polyline, unless we've got a
// colour change...
if (thisCol != lastCol)
{
// double check we haven't been modified
if (_ptCtr > _myPts.length)
{
continue;
}
// add our position to the list - we'll output
// the polyline at the end
if (_ptCtr < _myPts.length - 1)
{
_myPts[_ptCtr++] = thisP.x;
_myPts[_ptCtr++] = thisP.y;
}
// yup, better get rid of the previous
// polygon
paintSetOfPositions(dest, lastCol, thisLineStyle);
}
// add our position to the list - we'll output
// the polyline at the end
if (_ptCtr > _myPts.length - 1)
{
continue;
}
_myPts[_ptCtr++] = thisP.x;
_myPts[_ptCtr++] = thisP.y;
}
else
{
// nope, output however much line we've got so
// far - since this
// line won't be joined to future points
paintSetOfPositions(dest, thisCol, thisLineStyle);
// start off the next line
_myPts[_ptCtr++] = thisP.x;
_myPts[_ptCtr++] = thisP.y;
}
/*
* set the colour of the track from now on to this colour, so that the "link" to the next
* fix is set to this colour if left unchanged
*/
dest.setColor(thisFixColor);
// and remember the last colour
lastCol = thisCol;
}
}// while fixWrappers has more elements
// ok - paint the label for the last visible point
if (getPositionsVisible())
{
if (endPoints.size() > 1)
{
// special handling. If it's a planning segment, we hide the
// last fix, unless it's the very last segment
// do we have more legs?
final boolean hasMoreLegs = segments.hasMoreElements();
// is this a planning track?
final boolean isPlanningTrack = this instanceof CompositeTrackWrapper;
// ok, we hide the last point for planning legs, if there are
// more legs to come
final boolean forceHideLabel = isPlanningTrack && hasMoreLegs;
// ok, get painting
paintIt(dest, endPoints.get(1), getEndTimeLabels(), forceHideLabel);
}
}
// ok, just see if we have any pending polylines to paint
paintSetOfPositions(dest, lastCol, thisLineStyle);
}
return endPoints;
}
/**
* paint this fix, overriding the label if necessary (since the user may wish to have 6-figure
* DTGs at the start & end of the track
*
* @param dest
* where we paint to
* @param thisF
* the fix we're painting
* @param isEndPoint
* whether point is one of the ends
* @param forceHideLabel
* whether we wish to hide the label
*/
private void paintIt(final CanvasType dest, final FixWrapper thisF,
final boolean isEndPoint, final boolean forceHideLabel)
{
// have a look at the last fix. we defer painting the fix label,
// because we want to know the id of the last visible fix, since
// we may need to paint it's label in 6 DTG
final boolean isVis = thisF.getLabelShowing();
final String fmt = thisF.getLabelFormat();
final String lblVal = thisF.getLabel();
// are we plotting DTG at ends?
if (isEndPoint)
{
// set the custom format for our end labels (6-fig DTG)
thisF.setLabelFormat("ddHHmm");
thisF.setLabelShowing(true);
}
if (forceHideLabel)
{
thisF.setLabelShowing(false);
}
// this next method just paints the fix. we've put the
// call into paintThisFix so we can override the painting
// in the CompositeTrackWrapper class
paintThisFix(dest, thisF.getLocation(), thisF);
// do we need to restore it?
if (isEndPoint)
{
thisF.setLabelFormat(fmt);
thisF.setLabelShowing(isVis);
thisF.setLabel(lblVal);
}
if (forceHideLabel)
{
thisF.setLabelShowing(isVis);
}
}
private void paintMultipleSegmentLabel(final CanvasType dest)
{
final Enumeration<Editable> posis = _thePositions.elements();
while (posis.hasMoreElements())
{
final TrackSegment thisE = (TrackSegment) posis.nextElement();
// is this segment visible?
if (!thisE.getVisible())
{
continue;
}
// does it have visible data points?
if (thisE.isEmpty())
{
continue;
}
// if this is a TMA segment, we plot the name 1/2 way along. If it isn't
// we plot it at the start
if (thisE instanceof CoreTMASegment)
{
// just move along - we plot the name
// a the mid-point
}
else
{
final WorldLocation theLoc = thisE.getTrackStart();
// hey, don't abuse the track label - create a fresh one each time
final TextLabel label = new TextLabel(theLoc, thisE.getName());
// copy the font from the parent
label.setFont(_theLabel.getFont());
// is the first track a DR track?
if (thisE.getPlotRelative())
{
label.setFont(label.getFont().deriveFont(Font.ITALIC));
}
else if (_theLabel.getFont().isItalic())
{
label.setFont(label.getFont().deriveFont(Font.PLAIN));
}
// just see if this is a planning segment, with its own colors
final Color color;
if (thisE instanceof PlanningSegment)
{
final PlanningSegment ps = (PlanningSegment) thisE;
color = ps.getColor();
}
else
{
color = getColor();
}
label.setColor(color);
label.setLocation(theLoc);
label.paint(dest);
}
}
}
// LAYER support methods
/**
* paint any polyline that we've built up
*
* @param dest
* - where we're painting to
* @param thisCol
* @param lineStyle
*/
private void paintSetOfPositions(final CanvasType dest, final Color thisCol,
final int lineStyle)
{
if (_ptCtr > 0)
{
dest.setColor(thisCol);
dest.setLineStyle(lineStyle);
final int[] poly = new int[_ptCtr];
System.arraycopy(_myPts, 0, poly, 0, _ptCtr);
dest.drawPolyline(poly);
dest.setLineStyle(CanvasType.SOLID);
// and reset the counter
_ptCtr = 0;
}
}
private void paintSingleTrackLabel(final CanvasType dest,
final List<FixWrapper> endPoints)
{
// check that we have found a location for the label
if (_theLabel.getLocation() == null)
{
return;
}
// check that we have set the name for the label
if (_theLabel.getString() == null)
{
_theLabel.setString(getName());
}
// does the first label have a colour?
fixLabelColor();
// ok, sort out the correct location
final FixWrapper hostFix;
if (getNameAtStart() || endPoints.size() == 1)
{
// ok, we're choosing to use the start for the location. Or,
// we've only got one fix - in which case the end "is" the start
hostFix = endPoints.get(0);
}
else
{
hostFix = endPoints.get(1);
}
// sort out the location
_theLabel.setLocation(hostFix.getLocation());
// and the relative location
// hmm, if we're plotting date labels at the ends,
// shift the track name so that it's opposite
Integer oldLoc = null;
if (this.getEndTimeLabels())
{
oldLoc = getNameLocation();
// is it auto-locate?
if(oldLoc == NullableLocationPropertyEditor.AUTO)
{
// ok, automatically locate it
final int theLoc =
LabelLocationPropertyEditor.oppositeFor(hostFix.getLabelLocation());
setNameLocation(theLoc);
}
}
// and paint it
_theLabel.paint(dest);
// ok, restore the user-favourite location
if (oldLoc != null)
{
_theLabel.setRelativeLocation(oldLoc);
}
}
private void fixLabelColor()
{
if (_theLabel.getColor() == null)
{
// check we have a colour
Color labelColor = getColor();
// did we ourselves have a colour?
if (labelColor == null)
{
// nope - do we have any legs?
final Enumeration<Editable> numer = this.getPositionIterator();
if (numer.hasMoreElements())
{
// ok, use the colour of the first point
final FixWrapper pos = (FixWrapper) numer.nextElement();
labelColor = pos.getColor();
}
}
_theLabel.setColor(labelColor);
}
}
/**
* get the fix to paint itself
*
* @param dest
* @param lastLocation
* @param fw
*/
protected void paintThisFix(final CanvasType dest,
final WorldLocation lastLocation, final FixWrapper fw)
{
fw.paintMe(dest, lastLocation, getTrackColorMode().colorFor(fw));
}
/**
* draw vector labels for any TMA tracks
*
* @param dest
*/
private void paintVectorLabels(final CanvasType dest)
{
// cycle through the segments
final Enumeration<Editable> segments = _thePositions.elements();
while (segments.hasMoreElements())
{
final TrackSegment seg = (TrackSegment) segments.nextElement();
// is this segment visible?
if (!seg.getVisible())
{
// nope, jump to the next
continue;
}
// paint only visible planning segments
if (seg instanceof PlanningSegment)
{
final PlanningSegment ps = (PlanningSegment) seg;
ps.paintLabel(dest);
}
else if (seg instanceof CoreTMASegment)
{
final CoreTMASegment tma = (CoreTMASegment) seg;
// check the segment has some data
if (!seg.isEmpty())
{
final WorldLocation firstLoc = seg.first().getBounds().getCentre();
final WorldLocation lastLoc = seg.last().getBounds().getCentre();
final Font f = new Font("Sans Serif", Font.PLAIN, 11);
final Color c = _theLabel.getColor();
// tell the segment it's being stretched
final String spdTxt =
MWC.Utilities.TextFormatting.GeneralFormat
.formatOneDecimalPlace(tma.getSpeed().getValueIn(
WorldSpeed.Kts));
// copied this text from RelativeTMASegment
double courseVal = tma.getCourse();
if (courseVal < 0)
{
courseVal += 360;
}
String textLabel =
"[" + spdTxt + " kts " + (int) courseVal + "\u00B0]";
// ok, now plot it
CanvasTypeUtilities.drawLabelOnLine(dest, textLabel, f, c, firstLoc,
lastLoc, 1.2, true);
textLabel = tma.getName().replace(TextLabel.NEWLINE_MARKER, " ");
CanvasTypeUtilities.drawLabelOnLine(dest, textLabel, f, c, firstLoc,
lastLoc, 1.2, false);
}
}
}
}
/**
* return the range from the nearest corner of the track
*
* @param other
* the other location
* @return the range
*/
@Override
public final double rangeFrom(final WorldLocation other)
{
double nearest = -1;
// do we have a track?
if (_myWorldArea != null)
{
// find the nearest point on the track
nearest = _myWorldArea.rangeFrom(other);
}
return nearest;
}
/**
* remove the requested item from the track
*
* @param point
* the point to remove
*/
@Override
public final void removeElement(final Editable point)
{
boolean modified = false;
// just see if it's a sensor which is trying to be removed
if (point instanceof SensorWrapper)
{
_mySensors.removeElement(point);
// tell the sensor wrapper to forget about us
final TacticalDataWrapper sw = (TacticalDataWrapper) point;
sw.setHost(null);
// remember that we've made a change
modified = true;
}
else if (point instanceof TMAWrapper)
{
_mySolutions.removeElement(point);
// tell the sensor wrapper to forget about us
final TacticalDataWrapper sw = (TacticalDataWrapper) point;
sw.setHost(null);
// remember that we've made a change
modified = true;
}
else if (point instanceof SensorContactWrapper)
{
// ok, cycle through our sensors, try to remove this contact...
final Enumeration<Editable> iter = _mySensors.elements();
while (iter.hasMoreElements())
{
final SensorWrapper sw = (SensorWrapper) iter.nextElement();
// try to remove it from this one...
sw.removeElement(point);
// remember that we've made a change
modified = true;
}
}
else if (point instanceof DynamicTrackShapeWrapper)
{
// ok, cycle through our sensors, try to remove this contact...
final Enumeration<Editable> iter = _myDynamicShapes.elements();
while (iter.hasMoreElements())
{
final DynamicTrackShapeSetWrapper sw =
(DynamicTrackShapeSetWrapper) iter.nextElement();
// try to remove it from this one...
sw.removeElement(point);
// remember that we've made a change
modified = true;
}
}
else if (point instanceof TrackSegment)
{
_thePositions.removeElement(point);
// and clear the parent item
final TrackSegment ts = (TrackSegment) point;
ts.setWrapper(null);
// we also need to stop listen for a child moving
ts.removePropertyChangeListener(CoreTMASegment.ADJUSTED,
_childTrackMovedListener);
// remember that we've made a change
modified = true;
}
else if (point.equals(_mySensors))
{
// ahh, the user is trying to delete all the solution, cycle through
// them
final Enumeration<Editable> iter = _mySensors.elements();
while (iter.hasMoreElements())
{
final Editable editable = iter.nextElement();
// tell the sensor wrapper to forget about us
final TacticalDataWrapper sw = (TacticalDataWrapper) editable;
sw.setHost(null);
}
// and empty them out
_mySensors.removeAllElements();
// remember that we've made a change
modified = true;
}
else if (point.equals(_myDynamicShapes))
{
// ahh, the user is trying to delete all the solution, cycle through
// them
final Enumeration<Editable> iter = _myDynamicShapes.elements();
while (iter.hasMoreElements())
{
final Editable editable = iter.nextElement();
// tell the sensor wrapper to forget about us
final DynamicTrackShapeSetWrapper sw =
(DynamicTrackShapeSetWrapper) editable;
sw.setHost(null);
}
// and empty them out
_myDynamicShapes.removeAllElements();
// remember that we've made a change
modified = true;
}
else if (point.equals(_mySolutions))
{
// ahh, the user is trying to delete all the solution, cycle through
// them
final Enumeration<Editable> iter = _mySolutions.elements();
while (iter.hasMoreElements())
{
final Editable editable = iter.nextElement();
// tell the sensor wrapper to forget about us
final TacticalDataWrapper sw = (TacticalDataWrapper) editable;
sw.setHost(null);
}
// and empty them out
_mySolutions.removeAllElements();
// remember that we've made a change
modified = true;
}
else if (point instanceof FixWrapper)
{
final FixWrapper fw = (FixWrapper) point;
// loop through the segments
final Enumeration<Editable> segments = _thePositions.elements();
while (segments.hasMoreElements())
{
final TrackSegment seg = (TrackSegment) segments.nextElement();
seg.removeElement(point);
// and stop listening to it (if it's a fix)
fw.removePropertyChangeListener(PlainWrapper.LOCATION_CHANGED,
_locationListener);
// remember that we've made a change
modified = true;
// we've also got to clear the cache
flushPeriodCache();
flushPositionCache();
}
}
if (modified)
{
setRelativePending();
}
}
// track-shifting operation
// support for dragging the track around
/**
* pass through the track, resetting the labels back to their original DTG
*/
@FireReformatted
public void resetLabels()
{
FormatTracks.formatTrack(this);
}
@Override
public Enumeration<Editable> segments()
{
final TreeSet<Editable> res = new TreeSet<Editable>();
// ok, we want to wrap our fast-data as a set of plottables
// see how many track segments we have
if (_thePositions.size() == 1)
{
// just the one, insert it
res.add(_thePositions.first());
}
else
{
// more than one, insert them as a tree
res.add(_thePositions);
}
return new TrackWrapper_Support.IteratorWrapper(res.iterator());
}
/**
* how frequently symbols are placed on the track
*
* @param theVal
* frequency in seconds
*/
public final void setArrowFrequency(final HiResDate theVal)
{
this._lastArrowFrequency = theVal;
// set the "showPositions" parameter, as long as we are
// not setting the symbols off
if (theVal.getMicros() != 0.0)
{
this.setPositionsVisible(true);
}
final FixSetter setSymbols = new FixSetter()
{
@Override
public void execute(final FixWrapper fix, final boolean val)
{
fix.setArrowShowing(val);
}
};
setFixes(setSymbols, theVal);
}
/**
* set the colour of this track label
*
* @param theCol
* the colour
*/
@Override
@FireReformatted
public final void setColor(final Color theCol)
{
// do the parent
super.setColor(theCol);
// now do our processing
_theLabel.setColor(theCol);
}
/**
* length of trail to draw
*/
public final void setCustomTrailLength(final Duration len)
{
// just check that it's a non-null length
if (len != null)
{
if (len.getMillis() != 0)
{
_customTrailLength = len;
}
else
{
_customTrailLength = null;
}
}
}
/**
* length of trail to draw
*/
public final void setCustomVectorStretch(final double stretch)
{
_customVectorStretch = stretch;
}
/**
* whether to show time labels at the start/end of the track
*
* @param endTimeLabels
* yes/no
*/
@FireReformatted
public void setEndTimeLabels(final boolean endTimeLabels)
{
this._endTimeLabels = endTimeLabels;
}
/**
* the setter function which passes through the track
*/
private void setFixes(final FixSetter setter, final HiResDate theVal)
{
if (theVal == null)
{
return;
}
if (_thePositions.size() == 0)
{
return;
}
final long freq = theVal.getMicros();
// briefly check if we are revealing/hiding all times (ie if freq is 1
// or 0)
if (freq == TimeFrequencyPropertyEditor.SHOW_ALL_FREQUENCY)
{
// show all of the labels
final Enumeration<Editable> iter = getPositionIterator();
while (iter.hasMoreElements())
{
final FixWrapper fw = (FixWrapper) iter.nextElement();
setter.execute(fw, true);
}
}
else
{
// no, we're not just blindly doing all of them. do them at the
// correct
// frequency
// hide all of the labels/symbols first
final Enumeration<Editable> enumA = getPositionIterator();
while (enumA.hasMoreElements())
{
final FixWrapper fw = (FixWrapper) enumA.nextElement();
setter.execute(fw, false);
}
if (freq == 0)
{
// we can ignore this, since we have just hidden all of the
// points
}
else
{
if (getStartDTG() != null)
{
// pass through the track setting the values
// sort out the start and finish times
long start_time = getStartDTG().getMicros();
final long end_time = getEndDTG().getMicros();
// first check that there is a valid time period between start
// time
// and end time
if (start_time + freq < end_time)
{
long num = start_time / freq;
// we need to add one to the quotient if it has rounded down
if (start_time % freq == 0)
{
// start is at our freq, so we don't need to increment
}
else
{
num++;
}
// calculate new start time
start_time = num * freq;
}
else
{
// there is not one of our 'intervals' between the start and
// the end,
// so use the start time
}
long nextMarker = start_time / 1000L;
long freqMillis = freq / 1000L;
Enumeration<Editable> iter = this.getPositionIterator();
while (iter.hasMoreElements())
{
FixWrapper nextF = (FixWrapper) iter.nextElement();
long hisDate = nextF.getDTG().getDate().getTime();
if (hisDate >= nextMarker)
{
setter.execute(nextF, true);
// ok, move on to the next one
nextMarker += freqMillis;
}
}
}
}
}
}
@Override
public final void setInterpolatePoints(final boolean val)
{
_interpolatePoints = val;
}
/**
* set the label frequency (in seconds)
*
* @param theVal
* frequency to use
*/
public final void setLabelFrequency(final HiResDate theVal)
{
this._lastLabelFrequency = theVal;
final FixSetter setLabel = new FixSetter()
{
@Override
public void execute(final FixWrapper fix, final boolean val)
{
fix.setLabelShowing(val);
}
};
setFixes(setLabel, theVal);
}
/**
* set the style used for plotting the lines for this track
*
* @param val
*/
public void setLineStyle(final int val)
{
_lineStyle = val;
}
/**
* the line thickness (convenience wrapper around width)
*/
public void setLineThickness(final int val)
{
_lineWidth = val;
}
/**
* whether to link points
*
* @param linkPositions
*/
public void setLinkPositions(final boolean linkPositions)
{
_linkPositions = linkPositions;
}
/**
* set the name of this track (normally the name of the vessel
*
* @param theName
* the name as a String
*/
@Override
@FireReformatted
public final void setName(final String theName)
{
_theLabel.setString(theName);
}
/**
* whether to show the track name at the start or end of the track
*
* @param val
* yes no for <I>show label at start</I>
*/
public final void setNameAtStart(final boolean val)
{
_LabelAtStart = val;
}
/**
* the relative location of the label
*
* @param val
* the relative location
*/
public final void setNameLocation(final Integer val)
{
_theLabel.setRelativeLocation(val);
}
/**
* whether to show the track name
*
* @param val
* yes/no
*/
public final void setNameVisible(final boolean val)
{
_theLabel.setVisible(val);
}
public void setPlotArrayCentre(final boolean plotArrayCentre)
{
_plotArrayCentre = plotArrayCentre;
}
/**
* whether to show the position fixes
*
* @param val
* yes/no
*/
public final void setPositionsVisible(final boolean val)
{
_showPositions = val;
}
private void setRelativePending()
{
_relativeUpdatePending = true;
}
/**
* set the data frequency (in seconds) for the track & sensor data
*
* @param theVal
* frequency to use
*/
@FireExtended
public final void setResampleDataAt(final HiResDate theVal)
{
this._lastDataFrequency = theVal;
// have a go at trimming the start time to a whole number of intervals
final long interval = theVal.getMicros();
// do we have a start time (we may just be being tested...)
if (this.getStartDTG() == null)
{
return;
}
final long currentStart = this.getStartDTG().getMicros();
long startTime = (currentStart / interval) * interval;
// just check we're in the range
if (startTime < currentStart)
{
startTime += interval;
}
// move back to millis
startTime /= 1000L;
// just check it's not a barking frequency
if (theVal.getDate().getTime() <= 0)
{
// ignore, we don't need to do anything for a zero or a -1
}
else
{
final SegmentList segments = _thePositions;
final Enumeration<Editable> theEnum = segments.elements();
while (theEnum.hasMoreElements())
{
final TrackSegment seg = (TrackSegment) theEnum.nextElement();
seg.decimate(theVal, this, startTime);
}
// start off with the sensor data
if (_mySensors != null)
{
for (final Enumeration<Editable> iterator = _mySensors.elements(); iterator
.hasMoreElements();)
{
final SensorWrapper thisS = (SensorWrapper) iterator.nextElement();
thisS.decimate(theVal, startTime);
}
}
// now the solutions
if (_mySolutions != null)
{
for (final Enumeration<Editable> iterator = _mySolutions.elements(); iterator
.hasMoreElements();)
{
final TMAWrapper thisT = (TMAWrapper) iterator.nextElement();
thisT.decimate(theVal, startTime);
}
}
// ok, also set the arrow, symbol, label frequencies
setLabelFrequency(getLabelFrequency());
setSymbolFrequency(getSymbolFrequency());
setArrowFrequency(getArrowFrequency());
}
// remember we may need to regenerate positions, if we're a TMA solution
Editable firstLeg = getSegments().elements().nextElement();
if (firstLeg instanceof CoreTMASegment)
{
// setRelativePending();
sortOutRelativePositions();
}
}
public final void setSymbolColor(final Color col)
{
_theSnailShape.setColor(col);
}
/**
* how frequently symbols are placed on the track
*
* @param theVal
* frequency in seconds
*/
public final void setSymbolFrequency(final HiResDate theVal)
{
this._lastSymbolFrequency = theVal;
// set the "showPositions" parameter, as long as we are
// not setting the symbols off
if (theVal == null)
{
return;
}
if (theVal.getMicros() != 0.0)
{
this.setPositionsVisible(true);
}
final FixSetter setSymbols = new FixSetter()
{
@Override
public void execute(final FixWrapper fix, final boolean val)
{
fix.setSymbolShowing(val);
}
};
setFixes(setSymbols, theVal);
}
public void setSymbolLength(final WorldDistance symbolLength)
{
if (_theSnailShape instanceof WorldScaledSym)
{
final WorldScaledSym sym = (WorldScaledSym) _theSnailShape;
sym.setLength(symbolLength);
}
}
public final void setSymbolType(final String val)
{
// is this the type of our symbol?
if (val.equals(_theSnailShape.getType()))
{
// don't bother we're using it already
}
else
{
// remember the size of the symbol
final double scale = _theSnailShape.getScaleVal();
// remember the color of the symbol
final Color oldCol = _theSnailShape.getColor();
// replace our symbol with this new one
_theSnailShape = MWC.GUI.Shapes.Symbols.SymbolFactory.createSymbol(val);
_theSnailShape.setColor(oldCol);
_theSnailShape.setScaleVal(scale);
}
}
public void setSymbolWidth(final WorldDistance symbolWidth)
{
if (_theSnailShape instanceof WorldScaledSym)
{
final WorldScaledSym sym = (WorldScaledSym) _theSnailShape;
sym.setHeight(symbolWidth);
}
}
// note we are putting a track-labelled wrapper around the colour
// parameter, to make the properties window less confusing
/**
* the colour of the points on the track
*
* @param theCol
* the colour to use
*/
@FireReformatted
public final void setTrackColor(final Color theCol)
{
setColor(theCol);
}
/**
* set the mode used to color the track
*
* @param trackColorMode
*/
public void setTrackColorMode(final TrackColorMode trackColorMode)
{
this._trackColorMode = trackColorMode;
}
/**
* font handler
*
* @param font
* the font to use for the label
*/
public final void setTrackFont(final Font font)
{
_theLabel.setFont(font);
}
@Override
public void shift(final WorldLocation feature, final WorldVector vector)
{
feature.addToMe(vector);
// right, one of our fixes has moved. get the sensors to update
// themselves
fixMoved();
}
@Override
public void shift(final WorldVector vector)
{
boolean handled = false;
boolean updateAlreadyFired = false;
// check it contains a range
if (vector.getRange() > 0d)
{
// ok, move any tracks
final Enumeration<Editable> enumA = elements();
while (enumA.hasMoreElements())
{
final Object thisO = enumA.nextElement();
if (thisO instanceof TrackSegment)
{
final TrackSegment seg = (TrackSegment) thisO;
seg.shift(vector);
}
else if (thisO instanceof SegmentList)
{
final SegmentList list = (SegmentList) thisO;
final Collection<Editable> items = list.getData();
for (final Iterator<Editable> iterator = items.iterator(); iterator
.hasNext();)
{
final TrackSegment segment = (TrackSegment) iterator.next();
segment.shift(vector);
}
}
}
handled = true;
// ok, get the legs to re-generate themselves
updateAlreadyFired = sortOutRelativePositions();
}
// now update the other children - some
// are sensitive to ownship track
this.updateDependents(elements(), vector);
// did we move any dependents
if (handled && !updateAlreadyFired)
{
firePropertyChange(PlainWrapper.LOCATION_CHANGED, null, this._theLabel
.getLocation());
}
}
/**
* if we've got a relative track segment, it only learns where its individual fixes are once
* they've been initialised. This is where we do it.
*/
public boolean sortOutRelativePositions()
{
boolean moved = false;
boolean updateFired = false;
final Enumeration<Editable> segments = _thePositions.elements();
while (segments.hasMoreElements())
{
final TrackSegment seg = (TrackSegment) segments.nextElement();
// SPECIAL HANDLING, SEE IF IT'S A TMA SEGMENT TO BE PLOTTED IN
// RELATIVE MODE
final boolean isRelative = seg.getPlotRelative();
WorldLocation tmaLastLoc = null;
long tmaLastDTG = 0;
final Enumeration<Editable> fixWrappers = seg.elements();
while (fixWrappers.hasMoreElements())
{
final FixWrapper fw = (FixWrapper) fixWrappers.nextElement();
// now there's a chance that our fix has forgotten it's parent,
// particularly if it's the victim of a
// copy/paste operation. Tell it about it's children
fw.setTrackWrapper(this);
// ok, are we in relative?
if (isRelative)
{
final long thisTime = fw.getDateTimeGroup().getDate().getTime();
// ok, is this our first location?
if (tmaLastLoc == null)
{
final WorldLocation trackStart = seg.getTrackStart();
if (trackStart != null)
{
tmaLastLoc = new WorldLocation(trackStart);
}
}
else
{
// calculate a new vector
final long timeDelta = thisTime - tmaLastDTG;
if (lastFix != null)
{
final double courseRads;
final double speedKts;
if (seg instanceof CoreTMASegment)
{
final CoreTMASegment tmaSeg = (CoreTMASegment) seg;
courseRads = Math.toRadians(tmaSeg.getCourse());
speedKts = tmaSeg.getSpeed().getValueIn(WorldSpeed.Kts);
}
else
{
courseRads = lastFix.getCourse();
speedKts = lastFix.getSpeed();
}
// check it has a location.
final double depthM;
if (fw.getLocation() != null)
{
depthM = fw.getDepth();
}
else
{
// no location - we may be extending a TMA segment
depthM = tmaLastLoc.getDepth();
}
// use the value of depth as read in from the file
tmaLastLoc.setDepth(depthM);
final WorldVector thisVec =
seg.vectorFor(timeDelta, speedKts, courseRads);
tmaLastLoc.addToMe(thisVec);
}
}
lastFix = fw;
tmaLastDTG = thisTime;
if (tmaLastLoc != null)
{
// have we found any movement yet?
if (!moved && fw.getLocation() != null
&& !fw.getLocation().equals(tmaLastLoc))
{
moved = true;
}
// dump the location into the fix
fw.setFixLocationSilent(new WorldLocation(tmaLastLoc));
}
}
}
}
// did we do anything?
if (moved)
{
// get the child components to update,
// - including sending out a "moved" message
updateDependents(elements(), new WorldVector(0, 0, 0));
// also share the good news
firePropertyChange(PlainWrapper.LOCATION_CHANGED, null, System
.currentTimeMillis());
updateFired = true;
}
return updateFired;
}
/**
* split this whole track into two sub-tracks
*
* @param splitPoint
* the point at which we perform the split
* @param splitBeforePoint
* whether to put split before or after specified point
* @return a list of the new track segments (used for subsequent undo operations)
*/
public Vector<TrackSegment> splitTrack(final FixWrapper splitPoint,
final boolean splitBeforePoint)
{
FixWrapper splitPnt = splitPoint;
Vector<TrackSegment> res = null;
TrackSegment relevantSegment = null;
// are we still in one section?
if (_thePositions.size() == 1)
{
relevantSegment = (TrackSegment) _thePositions.first();
// yup, looks like we're going to be splitting it.
// better give it a proper name
relevantSegment.setName(relevantSegment.startDTG().getDate().toString());
}
else
{
// ok, find which segment contains our data
final Enumeration<Editable> segments = _thePositions.elements();
while (segments.hasMoreElements())
{
final TrackSegment seg = (TrackSegment) segments.nextElement();
if (seg.getData().contains(splitPnt))
{
relevantSegment = seg;
break;
}
}
}
if (relevantSegment == null)
{
throw new RuntimeException(
"failed to provide relevant segment, alg will break");
}
// hmm, if we're splitting after the point, we need to move along the
// bus by
// one
if (!splitBeforePoint)
{
final Collection<Editable> items = relevantSegment.getData();
final Iterator<Editable> theI = items.iterator();
Editable previous = null;
while (theI.hasNext())
{
final Editable thisE = theI.next();
// have we chosen to remember the previous item?
if (previous != null)
{
// yes, this must be the one we're after
splitPnt = (FixWrapper) thisE;
break;
}
// is this the one we're looking for?
if (thisE.equals(splitPnt))
{
// yup, remember it - we want to use the next value
previous = thisE;
}
}
}
// yup, do our first split
final SortedSet<Editable> p1 = relevantSegment.headSet(splitPnt);
final SortedSet<Editable> p2 = relevantSegment.tailSet(splitPnt);
// get our results ready
final TrackSegment ts1;
final TrackSegment ts2;
// aaah, just sort out if we are splitting a TMA segment, in which case
// want to create two
// tma segments, not track segments
if (relevantSegment instanceof RelativeTMASegment)
{
final RelativeTMASegment theTMA = (RelativeTMASegment) relevantSegment;
// find the ownship location at the relevant time
WorldLocation secondLegOrigin = null;
// get the time of the split
final HiResDate splitTime = splitPnt.getDateTimeGroup();
// aah, sort out if we are splitting before or after.
final SensorWrapper sensor = theTMA.getReferenceSensor();
if (sensor != null)
{
final Watchable[] nearestF = sensor.getNearestTo(splitTime);
if ((nearestF != null) && (nearestF.length > 0))
{
final SensorContactWrapper scw = (SensorContactWrapper) nearestF[0];
secondLegOrigin = scw.getCalculatedOrigin(null);
}
}
// if we couldn't get a sensor origin, try for the track origin
if (secondLegOrigin == null)
{
final Watchable firstMatch =
theTMA.getReferenceTrack().getNearestTo(splitTime)[0];
secondLegOrigin = firstMatch.getLocation();
}
final WorldVector secondOffset =
splitPnt.getLocation().subtract(secondLegOrigin);
// put the lists back into plottable layers
final RelativeTMASegment tr1 =
new RelativeTMASegment(theTMA, p1, theTMA.getOffset());
final RelativeTMASegment tr2 =
new RelativeTMASegment(theTMA, p2, secondOffset);
// update the freq's
tr1.setBaseFrequency(theTMA.getBaseFrequency());
tr2.setBaseFrequency(theTMA.getBaseFrequency());
// and store them
ts1 = tr1;
ts2 = tr2;
}
else if (relevantSegment instanceof AbsoluteTMASegment)
{
final AbsoluteTMASegment theTMA = (AbsoluteTMASegment) relevantSegment;
// aah, sort out if we are splitting before or after.
// find out the offset at the split point, so we can initiate it for
// the
// second part of the track
final Watchable[] matches =
this.getNearestTo(splitPnt.getDateTimeGroup());
final WorldLocation origin = matches[0].getLocation();
final FixWrapper t1Start = (FixWrapper) p1.first();
// put the lists back into plottable layers
final AbsoluteTMASegment tr1 =
new AbsoluteTMASegment(theTMA, p1, t1Start.getLocation(), null, null);
final AbsoluteTMASegment tr2 =
new AbsoluteTMASegment(theTMA, p2, origin, null, null);
// update the freq's
tr1.setBaseFrequency(((CoreTMASegment) relevantSegment)
.getBaseFrequency());
tr2.setBaseFrequency(((CoreTMASegment) relevantSegment)
.getBaseFrequency());
// and store them
ts1 = tr1;
ts2 = tr2;
}
else
{
// put the lists back into plottable layers
ts1 = new TrackSegment(p1);
ts2 = new TrackSegment(p2);
}
// now clear the positions
removeElement(relevantSegment);
// and put back our new layers
add(ts1);
add(ts2);
// remember them
res = new Vector<TrackSegment>();
res.add(ts1);
res.add(ts2);
return res;
}
/**
* extra parameter, so that jvm can produce a sensible name for this
*
* @return the track name, as a string
*/
@Override
public final String toString()
{
return "Track:" + getName();
}
public void trimTo(final TimePeriod period)
{
if (_mySensors != null)
{
final Enumeration<Editable> iter = _mySensors.elements();
while (iter.hasMoreElements())
{
final SensorWrapper sw = (SensorWrapper) iter.nextElement();
sw.trimTo(period);
}
}
if (_myDynamicShapes != null)
{
final Enumeration<Editable> iter = _myDynamicShapes.elements();
while (iter.hasMoreElements())
{
final DynamicTrackShapeSetWrapper sw =
(DynamicTrackShapeSetWrapper) iter.nextElement();
sw.trimTo(period);
}
}
if (_mySolutions != null)
{
final Enumeration<Editable> iter = _mySolutions.elements();
while (iter.hasMoreElements())
{
final TMAWrapper sw = (TMAWrapper) iter.nextElement();
sw.trimTo(period);
}
}
if (_thePositions != null)
{
final Enumeration<Editable> segments = _thePositions.elements();
while (segments.hasMoreElements())
{
final TrackSegment seg = (TrackSegment) segments.nextElement();
seg.trimTo(period);
}
}
}
/**
* move the whole of the track be the provided offset
*/
private final boolean updateDependents(final Enumeration<Editable> theEnum,
final WorldVector offset)
{
// keep track of if the track contains something that doesn't get
// dragged
boolean handledData = false;
// work through the elements
while (theEnum.hasMoreElements())
{
final Object thisO = theEnum.nextElement();
if (thisO instanceof DynamicInfillSegment)
{
final DynamicInfillSegment dd = (DynamicInfillSegment) thisO;
dd.reconstruct();
// ok - job well done
handledData = true;
}
else if (thisO instanceof TrackSegment)
{
// special case = we handle this higher
// up the call chain, since tracks
// have to move before any dependent children
// ok - job well done
handledData = true;
}
else if (thisO instanceof SegmentList)
{
final SegmentList list = (SegmentList) thisO;
final Collection<Editable> items = list.getData();
final IteratorWrapper enumer =
new Plottables.IteratorWrapper(items.iterator());
handledData = updateDependents(enumer, offset);
}
else if (thisO instanceof SensorWrapper)
{
final SensorWrapper sw = (SensorWrapper) thisO;
final Enumeration<Editable> enumS = sw.elements();
while (enumS.hasMoreElements())
{
final SensorContactWrapper scw =
(SensorContactWrapper) enumS.nextElement();
// does this fix have it's own origin?
final WorldLocation sensorOrigin = scw.getOrigin();
if (sensorOrigin == null)
{
// ok - get it to recalculate it
scw.clearCalculatedOrigin();
@SuppressWarnings("unused")
final WorldLocation newO = scw.getCalculatedOrigin(this);
// we don't use the newO - we're just
// triggering an update
}
else
{
// create new object to contain the updated location
final WorldLocation newSensorLocation =
new WorldLocation(sensorOrigin);
newSensorLocation.addToMe(offset);
// so the contact did have an origin, change it
scw.setOrigin(newSensorLocation);
}
} // looping through the contacts
// ok - job well done
handledData = true;
} // whether this is a sensor wrapper
else if (thisO instanceof TMAWrapper)
{
final TMAWrapper sw = (TMAWrapper) thisO;
final Enumeration<Editable> enumS = sw.elements();
while (enumS.hasMoreElements())
{
final TMAContactWrapper scw = (TMAContactWrapper) enumS.nextElement();
// does this fix have it's own origin?
final WorldLocation sensorOrigin = scw.getOrigin();
if (sensorOrigin != null)
{
// create new object to contain the updated location
final WorldLocation newSensorLocation =
new WorldLocation(sensorOrigin);
newSensorLocation.addToMe(offset);
// so the contact did have an origin, change it
scw.setOrigin(newSensorLocation);
}
} // looping through the contacts
// ok - job well done
handledData = true;
} // whether this is a TMA wrapper
else if (thisO instanceof BaseLayer)
{
// ok, loop through it
final BaseLayer bl = (BaseLayer) thisO;
handledData = updateDependents(bl.elements(), offset);
}
} // looping through this track
// ok, did we handle the data?
if (!handledData)
{
System.err.println("TrackWrapper problem; not able to shift:" + theEnum);
}
return handledData;
}
/**
* is this track visible between these time periods?
*
* @param start
* start DTG
* @param end
* end DTG
* @return yes/no
*/
public final boolean
visibleBetween(final HiResDate start, final HiResDate end)
{
boolean visible = false;
if (getStartDTG().lessThan(end) && (getEndDTG().greaterThan(start)))
{
visible = true;
}
return visible;
}
} |
package nom.bdezonia.zorbage.misc;
import java.math.BigDecimal;
import java.math.BigInteger;
/**
*
* @author Barry DeZonia
*
*/
public class Hasher {
public static final int PRIME = 23;
public static int hashCode(String v) {
return v.hashCode();
}
public static int hashCode(char v) {
return Character.hashCode(v);
}
public static int hashCode(boolean v) {
return Boolean.hashCode(v);
}
public static int hashCode(byte v) {
return Byte.hashCode(v);
}
public static int hashCode(short v) {
return Short.hashCode(v);
}
public static int hashCode(int v) {
return Integer.hashCode(v);
}
public static int hashCode(long v) {
return Long.hashCode(v);
}
public static int hashCode(float v) {
return Float.hashCode(v);
}
public static int hashCode(double v) {
return Double.hashCode(v);
}
public static int hashCode(BigInteger v) {
return v.hashCode();
}
public static int hashCode(BigDecimal v) {
return v.hashCode();
}
} |
// Revision 1.1 1999-01-31 13:33:08+00 sm11td
// Initial revision
package Debrief.Wrappers;
import java.awt.Color;
import java.awt.Font;
import java.awt.Point;
import java.beans.IntrospectionException;
import java.beans.MethodDescriptor;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyDescriptor;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.Vector;
import Debrief.ReaderWriter.Replay.FormatTracks;
import Debrief.Tools.Properties.TrackColorModePropertyEditor;
import Debrief.Wrappers.DynamicTrackShapes.DynamicTrackShapeSetWrapper;
import Debrief.Wrappers.DynamicTrackShapes.DynamicTrackShapeWrapper;
import Debrief.Wrappers.Track.AbsoluteTMASegment;
import Debrief.Wrappers.Track.CoreTMASegment;
import Debrief.Wrappers.Track.DynamicInfillSegment;
import Debrief.Wrappers.Track.PlanningSegment;
import Debrief.Wrappers.Track.RelativeTMASegment;
import Debrief.Wrappers.Track.SplittableLayer;
import Debrief.Wrappers.Track.TrackColorModeHelper;
import Debrief.Wrappers.Track.TrackColorModeHelper.DeferredDatasetColorMode;
import Debrief.Wrappers.Track.TrackColorModeHelper.TrackColorMode;
import Debrief.Wrappers.Track.TrackSegment;
import Debrief.Wrappers.Track.TrackWrapper_Support;
import Debrief.Wrappers.Track.TrackWrapper_Support.FixSetter;
import Debrief.Wrappers.Track.TrackWrapper_Support.SegmentList;
import Debrief.Wrappers.Track.TrackWrapper_Test;
import Debrief.Wrappers.Track.WormInHoleOffset;
import MWC.GUI.BaseLayer;
import MWC.GUI.CanvasType;
import MWC.GUI.Defaults;
import MWC.GUI.DynamicPlottable;
import MWC.GUI.Editable;
import MWC.GUI.FireExtended;
import MWC.GUI.FireReformatted;
import MWC.GUI.HasEditables.ProvidesContiguousElements;
import MWC.GUI.Layer;
import MWC.GUI.Layers;
import MWC.GUI.MessageProvider;
import MWC.GUI.PlainWrapper;
import MWC.GUI.Plottable;
import MWC.GUI.Plottables;
import MWC.GUI.Plottables.IteratorWrapper;
import MWC.GUI.Canvas.CanvasTypeUtilities;
import MWC.GUI.Properties.FractionPropertyEditor;
import MWC.GUI.Properties.LabelLocationPropertyEditor;
import MWC.GUI.Properties.LineStylePropertyEditor;
import MWC.GUI.Properties.LineWidthPropertyEditor;
import MWC.GUI.Properties.NullableLocationPropertyEditor;
import MWC.GUI.Properties.TimeFrequencyPropertyEditor;
import MWC.GUI.Shapes.DraggableItem;
import MWC.GUI.Shapes.HasDraggableComponents;
import MWC.GUI.Shapes.TextLabel;
import MWC.GUI.Shapes.Symbols.SymbolFactoryPropertyEditor;
import MWC.GUI.Shapes.Symbols.Vessels.WorldScaledSym;
import MWC.GenericData.Duration;
import MWC.GenericData.HiResDate;
import MWC.GenericData.TimePeriod;
import MWC.GenericData.Watchable;
import MWC.GenericData.WatchableList;
import MWC.GenericData.WorldArea;
import MWC.GenericData.WorldDistance;
import MWC.GenericData.WorldDistance.ArrayLength;
import MWC.GenericData.WorldLocation;
import MWC.GenericData.WorldSpeed;
import MWC.GenericData.WorldVector;
import MWC.TacticalData.Fix;
import MWC.Utilities.TextFormatting.FormatRNDateTime;
/**
* the TrackWrapper maintains the GUI and data attributes of the whole track iteself, but the
* responsibility for the fixes within the track are demoted to the FixWrapper
*/
public class TrackWrapper extends MWC.GUI.PlainWrapper implements WatchableList,
MWC.GUI.Layer, DraggableItem, HasDraggableComponents,
ProvidesContiguousElements, ISecondaryTrack, DynamicPlottable
{
// member variables
/**
* class containing editable details of a track
*/
public final class trackInfo extends Editable.EditorType implements
Editable.DynamicDescriptors
{
/**
* constructor for this editor, takes the actual track as a parameter
*
* @param data
* track being edited
*/
public trackInfo(final TrackWrapper data)
{
super(data, data.getName(), "");
}
@Override
public final MethodDescriptor[] getMethodDescriptors()
{
// just add the reset color field first
final Class<TrackWrapper> c = TrackWrapper.class;
final MethodDescriptor[] _methodDescriptors = new MethodDescriptor[]
{method(c, "exportThis", null, "Export Shape"), method(c, "resetLabels",
null, "Reset DTG Labels"), method(c, "calcCourseSpeed", null,
"Generate calculated Course and Speed")};
return _methodDescriptors;
}
@Override
public final String getName()
{
return super.getName();
}
@Override
public final PropertyDescriptor[] getPropertyDescriptors()
{
try
{
final PropertyDescriptor[] _coreDescriptors = new PropertyDescriptor[]
{displayExpertLongProp("SymbolType", "Symbol type",
"the type of symbol plotted for this label", FORMAT,
SymbolFactoryPropertyEditor.class), displayExpertLongProp(
"LineThickness", "Line thickness",
"the width to draw this track", FORMAT,
LineWidthPropertyEditor.class), expertProp("Name",
"the track name"), displayExpertProp("InterpolatePoints",
"Interpolate points",
"whether to interpolate points between known data points",
SPATIAL), expertProp("Color", "the track color",
FORMAT), displayExpertProp("EndTimeLabels",
"Start/End time labels",
"Whether to label track start/end with 6-figure DTG",
VISIBILITY), displayExpertProp("SymbolColor",
"Symbol color",
"the color of the symbol (when used)",
FORMAT), displayExpertProp(
"PlotArrayCentre", "Plot array centre",
"highlight the sensor array centre when non-zero array length provided",
VISIBILITY), displayExpertProp(
"TrackFont", "Track font",
"the track label font", FORMAT),
displayExpertProp("NameVisible", "Name visible",
"show the track label", VISIBILITY), displayExpertProp(
"PositionsVisible", "Positions visible",
"show individual Positions", VISIBILITY), displayExpertProp(
"NameAtStart", "Name at start",
"whether to show the track name at the start (or end)",
VISIBILITY), displayExpertProp("LinkPositions",
"Link positions",
"whether to join the track points", VISIBILITY),
expertProp("Visible", "whether the track is visible", VISIBILITY),
displayExpertLongProp("NameLocation", "Name location",
"relative location of track label", FORMAT,
MWC.GUI.Properties.NullableLocationPropertyEditor.class),
displayExpertLongProp("LabelFrequency", "Label frequency",
"the label frequency", TEMPORAL,
MWC.GUI.Properties.TimeFrequencyPropertyEditor.class),
displayExpertLongProp("SymbolFrequency", "Symbol frequency",
"the symbol frequency", TEMPORAL,
MWC.GUI.Properties.TimeFrequencyPropertyEditor.class),
displayExpertLongProp("ResampleDataAt", "Resample data at",
"the data sample rate", TEMPORAL,
MWC.GUI.Properties.TimeFrequencyPropertyEditor.class),
displayExpertLongProp("ArrowFrequency", "Arrow frequency",
"the direction marker frequency", TEMPORAL,
MWC.GUI.Properties.TimeFrequencyPropertyEditor.class),
displayProp("CustomTrailLength", "Custom Snail Trail",
"to specify a custom snail trail length",
Editable.EditorType.TEMPORAL), displayExpertLongProp(
"CustomVectorStretch", "Custom Vector Stretch",
"to specify a custom snail vector stretch",
Editable.EditorType.TEMPORAL, FractionPropertyEditor.class),
displayExpertLongProp("LineStyle", "Line style",
"the line style used to join track points", TEMPORAL,
MWC.GUI.Properties.LineStylePropertyEditor.class)};
PropertyDescriptor[] res;
// SPECIAL CASE: if we have a world scaled symbol, provide
// editors for
// the symbol size
final TrackWrapper item = (TrackWrapper) this.getData();
if (item._theSnailShape instanceof WorldScaledSym)
{
// yes = better create height/width editors
final PropertyDescriptor[] _coreDescriptorsWithSymbols =
new PropertyDescriptor[_coreDescriptors.length + 2];
System.arraycopy(_coreDescriptors, 0, _coreDescriptorsWithSymbols, 2,
_coreDescriptors.length);
_coreDescriptorsWithSymbols[0] = displayExpertProp("SymbolLength",
"Symbol length", "Length of symbol", FORMAT);
_coreDescriptorsWithSymbols[1] = displayExpertProp("SymbolWidth",
"Symbol width", "Width of symbol", FORMAT);
// and now use the new value
res = _coreDescriptorsWithSymbols;
}
else
{
res = _coreDescriptors;
}
// TRACK COLORING HANDLING
final List<TrackColorMode> datasets = getTrackColorModes();
if (datasets.size() > 0)
{
// store the datasets
TrackColorModePropertyEditor.setCustomModes(datasets);
final List<PropertyDescriptor> tmpList =
new ArrayList<PropertyDescriptor>();
tmpList.addAll(Arrays.asList(res));
// insert the editor
tmpList.add(displayExpertLongProp("TrackColorMode",
"Track Coloring Mode", "the mode in which to color the track",
FORMAT, TrackColorModePropertyEditor.class));
// ok. if we're in a measuremd mode, it may have a mode selector
res = tmpList.toArray(res);
// NOTE: this info class to implement Editable.DynamicDescriptors
// to avoid these descriptors being cached
}
return res;
}
catch (final IntrospectionException e)
{
return super.getPropertyDescriptors();
}
}
}
/**
* utility class to let us iterate through all positions without having to copy/paste them into a
* new object
*
* @author Ian
*
*/
public static class WrappedIterators implements Enumeration<Editable>
{
private final List<Enumeration<Editable>> lists = new ArrayList<>();
private int currentList = 0;
private Enumeration<Editable> currentIter;
private Editable current;
private Editable previous;
public WrappedIterators()
{
currentIter = null;
}
/**
* special class, used when we don't contain any data
*
* @author Ian
*
*/
private static class EmptyIterator implements Enumeration<Editable>
{
@Override
public boolean hasMoreElements()
{
return false;
}
@Override
public Editable nextElement()
{
return null;
}
}
public WrappedIterators(final SegmentList segments)
{
final Enumeration<Editable> ele = segments.elements();
while (ele.hasMoreElements())
{
final TrackSegment seg = (TrackSegment) ele.nextElement();
lists.add(seg.elements());
}
// if we have some data, return the first. Else, return an
// empty iterator
currentIter = lists.isEmpty() ? new EmptyIterator() : this.lists.get(0);
}
public void add(final Enumeration<MWC.GUI.Editable> item)
{
lists.add(item);
if (currentIter == null)
{
currentIter = lists.get(0);
}
}
public Editable currentElement()
{
return current;
}
@Override
public boolean hasMoreElements()
{
while (currentList < lists.size() - 1 && !currentIter.hasMoreElements())
{
currentList++;
currentIter = lists.get(currentList);
}
return currentIter.hasMoreElements();
}
@Override
public Editable nextElement()
{
while (currentList < lists.size() - 1 && !currentIter.hasMoreElements())
{
currentList++;
currentIter = lists.get(currentList);
}
// cache the previous value
previous = current;
// cache the current value
current = currentIter.nextElement();
return current;
}
public Editable previousElement()
{
return previous;
}
}
private static final String SOLUTIONS_LAYER_NAME = "Solutions";
public static final String SENSORS_LAYER_NAME = "Sensors";
public static final String DYNAMIC_SHAPES_LAYER_NAME = "Dynamic Shapes";
/**
* keep track of versions - version id
*/
static final long serialVersionUID = 1;
private static String checkTheyAreNotOverlapping(final Editable[] subjects)
{
// first, check they don't overlap.
// start off by collecting the periods
final TimePeriod[] _periods =
new TimePeriod.BaseTimePeriod[subjects.length];
for (int i = 0; i < subjects.length; i++)
{
final Editable editable = subjects[i];
TimePeriod thisPeriod = null;
if (editable instanceof TrackWrapper)
{
final TrackWrapper tw = (TrackWrapper) editable;
thisPeriod = new TimePeriod.BaseTimePeriod(tw.getStartDTG(), tw
.getEndDTG());
}
else if (editable instanceof TrackSegment)
{
final TrackSegment ts = (TrackSegment) editable;
thisPeriod = new TimePeriod.BaseTimePeriod(ts.startDTG(), ts.endDTG());
}
_periods[i] = thisPeriod;
}
// now test them.
String failedMsg = null;
for (int i = 0; i < _periods.length; i++)
{
final TimePeriod timePeriod = _periods[i];
for (int j = 0; j < _periods.length; j++)
{
final TimePeriod timePeriod2 = _periods[j];
// check it's not us
if (timePeriod2 != timePeriod)
{
if (timePeriod.overlaps(timePeriod2))
{
failedMsg = "'" + subjects[i].getName() + "' and '" + subjects[j]
.getName() + "'";
break;
}
}
}
}
return failedMsg;
}
/**
*
* @param newTrack
* @param reference
* Note: these parameters are tested here
* @see TrackWrapper_Test#testTrackMerge1()
*/
private static void copyStyling(final TrackWrapper newTrack,
final TrackWrapper reference)
{
// Note: see link in javadoc for where these are tested
newTrack.setSymbolType(reference.getSymbolType());
newTrack.setSymbolWidth(reference.getSymbolWidth());
newTrack.setSymbolLength(reference.getSymbolLength());
newTrack.setSymbolColor(reference.getSymbolColor());
}
private static void duplicateFixes(final SegmentList newSeg2,
final TrackSegment target, final Color infillShade)
{
final Enumeration<Editable> segs = newSeg2.elements();
while (segs.hasMoreElements())
{
final TrackSegment segment = (TrackSegment) segs.nextElement();
if (segment instanceof CoreTMASegment)
{
final CoreTMASegment ct = (CoreTMASegment) segment;
final TrackSegment newSeg = new TrackSegment(ct);
duplicateFixes(newSeg, target, infillShade);
}
else
{
duplicateFixes(segment, target, infillShade);
}
}
}
private static void duplicateFixes(final TrackSegment source,
final TrackSegment target, final Color infillShade)
{
// are we an infill?
final boolean isInfill = source instanceof DynamicInfillSegment;
// ok, retrieve the points in the track segment
final Enumeration<Editable> tsPts = source.elements();
while (tsPts.hasMoreElements())
{
final FixWrapper existingFW = (FixWrapper) tsPts.nextElement();
final Fix existingFix = existingFW.getFix();
final Fix newFix = existingFix.makeCopy();
final FixWrapper newF = new FixWrapper(newFix);
if (infillShade != null && isInfill)
{
newF.setColor(infillShade);
}
// also duplicate the label
newF.setLabel(existingFW.getLabel());
target.addFix(newF);
}
}
/**
* put the other objects into this one as children
*
* @param wrapper
* whose going to receive it
* @param theLayers
* the top level layers object
* @param parents
* the track wrapppers containing the children
* @param subjects
* the items to insert.
*/
public static void groupTracks(final TrackWrapper target,
final Layers theLayers, final Layer[] parents, final Editable[] subjects)
{
// ok, loop through the subjects, adding them onto the target
for (int i = 0; i < subjects.length; i++)
{
final Layer thisL = (Layer) subjects[i];
final TrackWrapper thisP = (TrackWrapper) parents[i];
if (thisL != target)
{
// is it a plain segment?
if (thisL instanceof TrackWrapper)
{
// pass down through the positions/segments
final Enumeration<Editable> pts = thisL.elements();
while (pts.hasMoreElements())
{
final Editable obj = pts.nextElement();
if (obj instanceof SegmentList)
{
final SegmentList sl = (SegmentList) obj;
final Enumeration<Editable> segs = sl.elements();
while (segs.hasMoreElements())
{
final TrackSegment ts = (TrackSegment) segs.nextElement();
// reset the name if we need to
if (ts.getName().startsWith("Posi"))
{
ts.setName(FormatRNDateTime.toString(ts.startDTG().getDate()
.getTime()));
}
target.add(ts);
}
}
else
{
if (obj instanceof TrackSegment)
{
final TrackSegment ts = (TrackSegment) obj;
// reset the name if we need to
if (ts.getName().startsWith("Posi"))
{
ts.setName(FormatRNDateTime.toString(ts.startDTG().getDate()
.getTime()));
}
// and remember it
target.add(ts);
}
}
}
}
else
{
// get it's data, and add it to the target
target.add(thisL);
}
// and remove the layer from it's parent
if (thisL instanceof TrackSegment)
{
thisP.removeElement(thisL);
// does this just leave an empty husk?
if (thisP.numFixes() == 0)
{
// may as well ditch it anyway
theLayers.removeThisLayer(thisP);
}
}
else
{
// we'll just remove it from the top level layer
theLayers.removeThisLayer(thisL);
}
}
}
}
/**
* perform a merge of the supplied tracks.
*
* @param recipient
* the final recipient of the other items
* @param theLayers
* @param parents
* the parent tracks for the supplied items
* @param subjects
* the actual selected items
* @param _newName
* name to give to the merged object
* @return sufficient information to undo the merge
*/
public static int mergeTracks(final TrackWrapper newTrack,
final Layers theLayers, final Editable[] subjects,
final Color infillShade)
{
// check that the legs don't overlap
final String failedMsg = checkTheyAreNotOverlapping(subjects);
// how did we get on?
if (failedMsg != null)
{
MessageProvider.Base.Provider.show("Merge tracks", "Sorry, " + failedMsg
+ " overlap in time. Please correct this and retry",
MessageProvider.ERROR);
return MessageProvider.ERROR;
}
// ok, loop through the subjects, adding them onto the target
for (int i = 0; i < subjects.length; i++)
{
final Layer thisL = (Layer) subjects[i];
// is it a plain segment?
if (thisL instanceof TrackWrapper)
{
// is this the first one? If so, we'll copy the symbol setup
if (i == 0)
{
final TrackWrapper track = (TrackWrapper) thisL;
copyStyling(newTrack, track);
}
// pass down through the positions/segments
final Enumeration<Editable> pts = thisL.elements();
while (pts.hasMoreElements())
{
final Editable obj = pts.nextElement();
if (obj instanceof SegmentList)
{
final SegmentList sl = (SegmentList) obj;
final TrackSegment newT = new TrackSegment(TrackSegment.ABSOLUTE);
duplicateFixes(sl, newT, infillShade);
newTrack.add(newT);
}
else if (obj instanceof TrackSegment)
{
final TrackSegment ts = (TrackSegment) obj;
// ok, duplicate the fixes in this segment
final TrackSegment newT = new TrackSegment(TrackSegment.ABSOLUTE);
duplicateFixes(ts, newT, infillShade);
// and add it to the new track
newTrack.append(newT);
}
}
}
else if (thisL instanceof TrackSegment)
{
final TrackSegment ts = (TrackSegment) thisL;
// ok, duplicate the fixes in this segment
final TrackSegment newT = new TrackSegment(ts.getPlotRelative());
duplicateFixes(ts, newT, infillShade);
// and add it to the new track
newTrack.append(newT);
// is this the first one? If so, we'll copy the symbol setup
if (i == 0)
{
final TrackWrapper track = ts.getWrapper();
copyStyling(newTrack, track);
}
}
else if (thisL instanceof SegmentList)
{
final SegmentList sl = (SegmentList) thisL;
// is this the first one? If so, we'll copy the symbol setup
if (i == 0)
{
final TrackWrapper track = sl.getWrapper();
copyStyling(newTrack, track);
}
// it's absolute, since merged tracks are always
// absolute
final TrackSegment newT = new TrackSegment(TrackSegment.ABSOLUTE);
// ok, duplicate the fixes in this segment
duplicateFixes(sl, newT, infillShade);
// and add it to the new track
newTrack.append(newT);
}
}
// and store the new track
theLayers.addThisLayer(newTrack);
return MessageProvider.OK;
}
/**
* perform a merge of the supplied tracks.
*
* @param target
* the final recipient of the other items
* @param theLayers
* @param parents
* the parent tracks for the supplied items
* @param subjects
* the actual selected items
* @return sufficient information to undo the merge
*/
public static int mergeTracksInPlace(final Editable target,
final Layers theLayers, final Layer[] parents, final Editable[] subjects)
{
// where we dump the new data points
Layer receiver = (Layer) target;
// check that the legs don't overlap
final String failedMsg = checkTheyAreNotOverlapping(subjects);
// how did we get on?
if (failedMsg != null)
{
MessageProvider.Base.Provider.show("Merge tracks", "Sorry, " + failedMsg
+ " overlap in time. Please correct this and retry",
MessageProvider.ERROR);
return MessageProvider.ERROR;
}
// right, if the target is a TMA track, we have to change it into a
// proper
// track, since
// the merged tracks probably contain manoeuvres
if (target instanceof CoreTMASegment)
{
final CoreTMASegment tma = (CoreTMASegment) target;
final TrackSegment newSegment = new TrackSegment(tma);
// now do some fancy footwork to remove the target from the wrapper,
// and
// replace it with our new segment
newSegment.getWrapper().removeElement(target);
newSegment.getWrapper().add(newSegment);
// store the new segment into the receiver
receiver = newSegment;
}
// ok, loop through the subjects, adding them onto the target
for (int i = 0; i < subjects.length; i++)
{
final Layer thisL = (Layer) subjects[i];
final TrackWrapper thisP = (TrackWrapper) parents[i];
// is this the target item (note we're comparing against the item
// passed
// in, not our
// temporary receiver, since the receiver may now be a tracksegment,
// not a
// TMA segment
if (thisL != target)
{
// is it a plain segment?
if (thisL instanceof TrackWrapper)
{
// pass down through the positions/segments
final Enumeration<Editable> pts = thisL.elements();
while (pts.hasMoreElements())
{
final Editable obj = pts.nextElement();
if (obj instanceof SegmentList)
{
final SegmentList sl = (SegmentList) obj;
final Enumeration<Editable> segs = sl.elements();
while (segs.hasMoreElements())
{
final TrackSegment ts = (TrackSegment) segs.nextElement();
receiver.add(ts);
}
}
else
{
final Layer ts = (Layer) obj;
receiver.append(ts);
}
}
}
else
{
// get it's data, and add it to the target
receiver.append(thisL);
}
// and remove the layer from it's parent
if (thisL instanceof TrackSegment)
{
thisP.removeElement(thisL);
// does this just leave an empty husk?
if (thisP.numFixes() == 0)
{
// may as well ditch it anyway
theLayers.removeThisLayer(thisP);
}
}
else
{
// we'll just remove it from the top level layer
theLayers.removeThisLayer(thisL);
}
}
}
return MessageProvider.OK;
}
/**
* whether to interpolate points in this track
*/
private boolean _interpolatePoints = false;
/**
* the end of the track to plot the label
*/
private boolean _LabelAtStart = true;
private HiResDate _lastLabelFrequency = new HiResDate(0);
private HiResDate _lastSymbolFrequency = new HiResDate(0);
private HiResDate _lastArrowFrequency = new HiResDate(0);
private HiResDate _lastDataFrequency = new HiResDate(0,
TimeFrequencyPropertyEditor.SHOW_ALL_FREQUENCY);
/**
* whether to show a time label at the start/end of the track
*
*/
private boolean _endTimeLabels = true;
/**
* the width of this track
*/
private int _lineWidth = 3;
/**
* the style of this line
*
*/
private int _lineStyle = CanvasType.SOLID;
/**
* whether or not to link the Positions
*/
private boolean _linkPositions;
/**
* whether to show a highlight for the array centre
*
*/
private boolean _plotArrayCentre;
/**
* our editable details
*/
protected transient Editable.EditorType _myEditor = null;
/**
* keep a list of points waiting to be plotted
*
*/
transient private int[] _myPts;
/**
* when plotting a track, we end up calling "get visible period" very frequently. So, we'll cache
* it, together with the time the cached version was generated. This will let us decide whether to
* recalculate, or to use a cached version
*
*/
transient private TimePeriod _cachedPeriod = null;
/**
* the time that we last calculated the time period
*
*/
transient private long _timeCachedPeriodCalculated = 0;
/**
* the sensor tracks for this vessel
*/
final private BaseLayer _mySensors;
/**
* the dynamic shapes for this vessel
*/
final private BaseLayer _myDynamicShapes;
/**
* the TMA solutions for this vessel
*/
final private BaseLayer _mySolutions;
/**
* keep track of how far we are through our array of points
*
*/
transient private int _ptCtr = 0;
/**
* whether or not to show the Positions
*/
private boolean _showPositions;
/**
* the label describing this track
*/
private final MWC.GUI.Shapes.TextLabel _theLabel;
/**
* the list of wrappers we hold
*/
protected SegmentList _thePositions;
/**
* the symbol to pass on to a snail plotter
*/
private MWC.GUI.Shapes.Symbols.PlainSymbol _theSnailShape;
/**
* flag for if there is a pending update to track - particularly if it's a relative one
*/
private boolean _relativeUpdatePending = false;
// member functions
transient private FixWrapper _lastFix;
/**
* working parameters
*/
transient private WorldArea _myWorldArea;
transient private final PropertyChangeListener _locationListener;
transient private PropertyChangeListener _childTrackMovedListener;
private Duration _customTrailLength = null;
private Double _customVectorStretch = null;
/**
* how to shade the track
*
*/
private TrackColorModeHelper.TrackColorMode _trackColorMode =
TrackColorModeHelper.LegacyTrackColorModes.PER_FIX;
/**
* cache the position iterator we last used. this prevents us from having to restart at the
* beginning when getNearestTo() is being called repetitively
*/
private transient WrappedIterators _lastPosIterator;
// constructors
/**
* Wrapper for a Track (a series of position fixes). It combines the data with the formatting
* details
*/
public TrackWrapper()
{
_mySensors = new SplittableLayer(true);
_mySensors.setName(SENSORS_LAYER_NAME);
_myDynamicShapes = new SplittableLayer(true);
_myDynamicShapes.setName(DYNAMIC_SHAPES_LAYER_NAME);
_mySolutions = new BaseLayer(true);
_mySolutions.setName(SOLUTIONS_LAYER_NAME);
// create a property listener for when fixes are moved
_locationListener = new PropertyChangeListener()
{
@Override
public void propertyChange(final PropertyChangeEvent arg0)
{
fixMoved();
}
};
_childTrackMovedListener = new PropertyChangeListener()
{
@Override
public void propertyChange(final PropertyChangeEvent evt)
{
// child track move. remember that we need to recalculate & redraw
setRelativePending();
// also share the good news
firePropertyChange(PlainWrapper.LOCATION_CHANGED, null, System
.currentTimeMillis());
}
};
_linkPositions = true;
// start off with positions showing (although the default setting for a
// fix
// is to not show a symbol anyway). We need to make this "true" so that
// when a fix position is set to visible it is not over-ridden by this
// setting
_showPositions = true;
_theLabel = new MWC.GUI.Shapes.TextLabel(new WorldLocation(0, 0, 0), null);
// set an initial location for the label
setNameLocation(NullableLocationPropertyEditor.AUTO);
// initialise the symbol to use for plotting this track in snail mode
_theSnailShape = MWC.GUI.Shapes.Symbols.SymbolFactory.createSymbol(
"Submarine");
// declare our arrays
_thePositions = new TrackWrapper_Support.SegmentList();
_thePositions.setWrapper(this);
}
/**
* add the indicated point to the track
*
* @param point
* the point to add
*/
@Override
public void add(final MWC.GUI.Editable point)
{
// see what type of object this is
if (point instanceof FixWrapper)
{
final FixWrapper fw = (FixWrapper) point;
fw.setTrackWrapper(this);
addFix(fw);
}
// is this a sensor?
else if (point instanceof SensorWrapper)
{
final SensorWrapper swr = (SensorWrapper) point;
// see if we already have a sensor with this name
SensorWrapper existing = null;
final Enumeration<Editable> enumer = _mySensors.elements();
while (enumer.hasMoreElements())
{
final SensorWrapper oldS = (SensorWrapper) enumer.nextElement();
// does this have the same name?
if (oldS.getName().equals(swr.getName()))
{
// yes - ok, remember it
existing = oldS;
// and append the data points
existing.append(swr);
}
}
// did we find it already?
if (existing == null)
{
// nope, so store it
_mySensors.add(swr);
}
// tell the sensor about us
swr.setHost(this);
// and the track name (if we're loading from REP it will already
// know
// the name, but if this data is being pasted in, it may start with
// a different
// parent track name - so override it here)
swr.setTrackName(this.getName());
}
// is this a dynamic shape?
else if (point instanceof DynamicTrackShapeSetWrapper)
{
final DynamicTrackShapeSetWrapper swr =
(DynamicTrackShapeSetWrapper) point;
// just check we don't alraedy have it
if (_myDynamicShapes.contains(swr))
{
MWC.Utilities.Errors.Trace.trace("Don't allow duplicate shape set name:"
+ swr.getName());
}
else
{
// add to our list
_myDynamicShapes.add(swr);
// tell the sensor about us
swr.setHost(this);
}
}
// is this a TMA solution track?
else if (point instanceof TMAWrapper)
{
final TMAWrapper twr = (TMAWrapper) point;
// add to our list
_mySolutions.add(twr);
// tell the sensor about us
twr.setHost(this);
// and the track name (if we're loading from REP it will already
// know
// the name, but if this data is being pasted in, it may start with
// a different
// parent track name - so override it here)
twr.setTrackName(this.getName());
}
else if (point instanceof TrackSegment)
{
final TrackSegment seg = (TrackSegment) point;
seg.setWrapper(this);
_thePositions.addSegment((TrackSegment) point);
// hey, sort out the positions
sortOutRelativePositions();
// special case - see if it's a relative TMA segment,
// we many need some more sorting
if (point instanceof RelativeTMASegment)
{
final RelativeTMASegment newRelativeSegment =
(RelativeTMASegment) point;
// ok, try to update the layers. get the layers for an
// existing segment
final SegmentList sl = this.getSegments();
final Enumeration<Editable> sEnum = sl.elements();
while (sEnum.hasMoreElements())
{
final TrackSegment mySegment = (TrackSegment) sEnum.nextElement();
if (mySegment != newRelativeSegment)
{
// ok, it's not this one. try the layers
if (mySegment instanceof RelativeTMASegment)
{
final RelativeTMASegment myRelativeSegnent =
(RelativeTMASegment) mySegment;
final Layers myExistingLayers = myRelativeSegnent.getLayers();
if (myExistingLayers != newRelativeSegment.getLayers())
{
newRelativeSegment.setLayers(myExistingLayers);
break;
}
}
}
}
}
// we also need to listen for a child moving
seg.addPropertyChangeListener(CoreTMASegment.ADJUSTED,
_childTrackMovedListener);
}
else if (point instanceof Layer)
{
// just check if it's a track - since we don't want to allow pasting
// TMA track into it's parent
final Layer layer = (Layer) point;
if (layer instanceof TrackWrapper)
{
TrackWrapper newTrack = (TrackWrapper) layer;
Enumeration<Editable> segs = newTrack.getSegments().elements();
while (segs.hasMoreElements())
{
Editable seg = segs.nextElement();
if (seg instanceof RelativeTMASegment)
{
RelativeTMASegment rel = (RelativeTMASegment) seg;
// hey, just check that we're not actually the reference
// for this segment
if (rel.getHostName().equals(this.getName()))
{
MessageProvider.Base.Provider.show("Paste track",
"Can't paste TMA track into it's reference track:" + this
.getName(), MessageProvider.ERROR);
return;
}
}
}
}
final Enumeration<Editable> items = layer.elements();
while (items.hasMoreElements())
{
final Editable thisE = items.nextElement();
add(thisE);
}
}
else
{
MWC.GUI.Dialogs.DialogFactory.showMessage("Add point",
"Sorry it is not possible to add:" + point.getName() + " to " + this
.getName());
}
}
public void addFix(final FixWrapper theFix)
{
// do we have any track segments
if (_thePositions.isEmpty())
{
// nope, add one
final TrackSegment firstSegment = new TrackSegment(TrackSegment.ABSOLUTE);
firstSegment.setName("Positions");
_thePositions.addSegment(firstSegment);
}
// add fix to last track segment
final TrackSegment last = (TrackSegment) _thePositions.last();
last.addFix(theFix);
// tell the fix about it's daddy
theFix.setTrackWrapper(this);
if (_myWorldArea == null)
{
_myWorldArea = new WorldArea(theFix.getLocation(), theFix.getLocation());
}
else
{
_myWorldArea.extend(theFix.getLocation());
}
// flush any cached values for time period & lists of positions
flushPeriodCache();
flushPositionCache();
}
/**
* append this other layer to ourselves (although we don't really bother with it)
*
* @param other
* the layer to add to ourselves
*/
@Override
public void append(final Layer other)
{
boolean modified = false;
// is it a track?
if ((other instanceof TrackWrapper) || (other instanceof TrackSegment))
{
// yes, break it down.
final java.util.Enumeration<Editable> iter = other.elements();
while (iter.hasMoreElements())
{
final Editable nextItem = iter.nextElement();
if (nextItem instanceof Layer)
{
append((Layer) nextItem);
modified = true;
}
else
{
add(nextItem);
modified = true;
}
}
}
else
{
// nope, just add it to us.
add(other);
modified = true;
}
if (modified)
{
setRelativePending();
}
}
/**
* Calculates Course & Speed for the track.
*/
public void calcCourseSpeed()
{
// step through our fixes
final Enumeration<Editable> iter = getPositionIterator();
FixWrapper prevFw = null;
while (iter.hasMoreElements())
{
final FixWrapper currFw = (FixWrapper) iter.nextElement();
if (prevFw == null)
{
prevFw = currFw;
}
else
{
// calculate the course
final WorldVector wv = currFw.getLocation().subtract(prevFw
.getLocation());
prevFw.getFix().setCourse(wv.getBearing());
// also, set the correct label alignment
currFw.resetLabelLocation();
// calculate the speed
// get distance in meters
final WorldDistance wd = new WorldDistance(wv);
final double distance = wd.getValueIn(WorldDistance.METRES);
// get time difference in seconds
final long timeDifference = (currFw.getTime().getMicros() - prevFw
.getTime().getMicros()) / 1000000;
// get speed in meters per second and convert it to knots
final WorldSpeed speed = new WorldSpeed(distance / timeDifference,
WorldSpeed.M_sec);
final double knots = WorldSpeed.convert(WorldSpeed.M_sec,
WorldSpeed.Kts, speed.getValue());
prevFw.setSpeed(knots);
prevFw = currFw;
}
}
// if it's a DR track this will probably change things
setRelativePending();
}
private void checkPointsArray()
{
// is our points store long enough?
if ((_myPts == null) || (_myPts.length < numFixes() * 2))
{
_myPts = new int[numFixes() * 2];
}
// reset the points counter
_ptCtr = 0;
}
public void clearPositions()
{
boolean modified = false;
final Enumeration<Editable> segments = _thePositions.elements();
while (segments.hasMoreElements())
{
final TrackSegment seg = (TrackSegment) segments.nextElement();
seg.removeAllElements();
// remember that we've made a change
modified = true;
// we've also got to clear the cache
flushPeriodCache();
flushPositionCache();
}
if (modified)
{
setRelativePending();
}
}
/**
* instruct this object to clear itself out, ready for ditching
*/
@Override
public final void closeMe()
{
// and my objects
// first ask them to close themselves
final Enumeration<Editable> it = getPositionIterator();
while (it.hasMoreElements())
{
final Editable val = it.nextElement();
if (val instanceof PlainWrapper)
{
final PlainWrapper pw = (PlainWrapper) val;
pw.closeMe();
}
else if (val instanceof TrackSegment)
{
final TrackSegment ts = (TrackSegment) val;
// and clear the parent item
ts.setWrapper(null);
// we also need to stop listen for a child moving
ts.removePropertyChangeListener(CoreTMASegment.ADJUSTED,
_childTrackMovedListener);
}
}
// now ditch them
_thePositions.removeAllElements();
_thePositions = null;
// and my objects
// first ask the sensors to close themselves
if (_mySensors != null)
{
final Enumeration<Editable> it2 = _mySensors.elements();
while (it2.hasMoreElements())
{
final Object val = it2.nextElement();
if (val instanceof PlainWrapper)
{
final PlainWrapper pw = (PlainWrapper) val;
pw.closeMe();
}
}
// now ditch them
_mySensors.removeAllElements();
}
// and my objects
// first ask the sensors to close themselves
if (_myDynamicShapes != null)
{
final Enumeration<Editable> it2 = _myDynamicShapes.elements();
while (it2.hasMoreElements())
{
final Object val = it2.nextElement();
if (val instanceof PlainWrapper)
{
final PlainWrapper pw = (PlainWrapper) val;
pw.closeMe();
}
}
// now ditch them
_myDynamicShapes.removeAllElements();
}
// now ask the solutions to close themselves
if (_mySolutions != null)
{
final Enumeration<Editable> it2 = _mySolutions.elements();
while (it2.hasMoreElements())
{
final Object val = it2.nextElement();
if (val instanceof PlainWrapper)
{
final PlainWrapper pw = (PlainWrapper) val;
pw.closeMe();
}
}
// now ditch them
_mySolutions.removeAllElements();
}
// and our utility objects
_lastFix = null;
// and our editor
_myEditor = null;
// now get the parent to close itself
super.closeMe();
}
/**
* switch the two track sections into one track section
*
* @param res
* the previously split track sections
*/
public void combineSections(final Vector<TrackSegment> res)
{
// ok, remember the first
final TrackSegment keeper = res.firstElement();
// now remove them all, adding them to the first
final Iterator<TrackSegment> iter = res.iterator();
while (iter.hasNext())
{
final TrackSegment pl = iter.next();
if (pl != keeper)
{
keeper.append((Layer) pl);
}
removeElement(pl);
}
// and put the keepers back in
add(keeper);
// and remember we need an update
setRelativePending();
}
@Override
public int compareTo(final Plottable arg0)
{
Integer answer = null;
// SPECIAL PROCESSING: we wish to push TMA tracks to the top of any
// tracks shown in the outline view.
// is he a track?
if (arg0 instanceof TrackWrapper)
{
final TrackWrapper other = (TrackWrapper) arg0;
// yes, he's a track. See if we're a relative track
final boolean iAmTMA = isTMATrack();
// is he relative?
final boolean heIsTMA = other.isTMATrack();
if (heIsTMA)
{
// ok, he's a TMA segment. now we need to sort out if we are.
if (iAmTMA)
{
// we're both relative, compare names
answer = getName().compareTo(other.getName());
}
else
{
// only he is relative, he comes first
answer = 1;
}
}
else
{
// he's not relative. am I?
if (iAmTMA)
{
// I am , so go first
answer = -1;
}
}
}
else
{
// we're a track, they're not - put us at the end!
answer = 1;
}
// if we haven't worked anything out yet, just use the parent implementation
if (answer == null)
{
answer = super.compareTo(arg0);
}
return answer;
}
/**
* return our tiered data as a single series of elements
*
* @return
*/
@Override
public Enumeration<Editable> contiguousElements()
{
final WrappedIterators we = new WrappedIterators();
if (_mySensors != null && _mySensors.getVisible())
{
final Enumeration<Editable> iter = _mySensors.elements();
while (iter.hasMoreElements())
{
final SensorWrapper sw = (SensorWrapper) iter.nextElement();
// is it visible?
if (sw.getVisible())
{
we.add(sw.elements());
}
}
}
if (_myDynamicShapes != null && _myDynamicShapes.getVisible())
{
final Enumeration<Editable> iter = _myDynamicShapes.elements();
while (iter.hasMoreElements())
{
final DynamicTrackShapeSetWrapper sw =
(DynamicTrackShapeSetWrapper) iter.nextElement();
// is it visible?
if (sw.getVisible())
{
we.add(sw.elements());
}
}
}
if (_mySolutions != null && _mySolutions.getVisible())
{
final Enumeration<Editable> iter = _mySolutions.elements();
while (iter.hasMoreElements())
{
final TMAWrapper sw = (TMAWrapper) iter.nextElement();
if (sw.getVisible())
{
we.add(sw.elements());
}
}
}
if (_thePositions != null && _thePositions.getVisible())
{
we.add(getPositionIterator());
}
return we;
}
/**
* this accessor is present for debug/testing purposes only. Do not use outside testing!
*
* @return the length of the list of screen points waiting to be plotted
*/
public int debug_GetPointCtr()
{
return _ptCtr;
}
/**
* this accessor is present for debug/testing purposes only. Do not use outside testing!
*
* @return the list of screen locations about to be plotted
*/
public int[] debug_GetPoints()
{
return _myPts;
}
/**
* get an enumeration of the points in this track
*
* @return the points in this track
*/
@Override
public Enumeration<Editable> elements()
{
final TreeSet<Editable> res = new TreeSet<Editable>();
if (!_mySensors.isEmpty())
{
res.add(_mySensors);
}
if (!_myDynamicShapes.isEmpty())
{
res.add(_myDynamicShapes);
}
if (!_mySolutions.isEmpty())
{
res.add(_mySolutions);
}
// ok, we want to wrap our fast-data as a set of plottables
// see how many track segments we have
if (_thePositions.size() == 1)
{
// just the one, insert it
res.add(_thePositions.first());
}
else
{
// more than one, insert them as a tree
res.add(_thePositions);
}
return new TrackWrapper_Support.IteratorWrapper(res.iterator());
}
// editing parameters
/**
* export this track to REPLAY file
*/
@Override
public final void exportShape()
{
// call the method in PlainWrapper
this.exportThis();
}
/**
* filter the list to the specified time period, then inform any listeners (such as the time
* stepper)
*
* @param start
* the start dtg of the period
* @param end
* the end dtg of the period
*/
@Override
public final void filterListTo(final HiResDate start, final HiResDate end)
{
final Enumeration<Editable> fixWrappers = getPositionIterator();
while (fixWrappers.hasMoreElements())
{
final FixWrapper fw = (FixWrapper) fixWrappers.nextElement();
final HiResDate dtg = fw.getTime();
if ((dtg.greaterThanOrEqualTo(start)) && (dtg.lessThanOrEqualTo(end)))
{
fw.setVisible(true);
}
else
{
fw.setVisible(false);
}
}
// now do the same for our sensor data
if (_mySensors != null)
{
final Enumeration<Editable> iter = _mySensors.elements();
while (iter.hasMoreElements())
{
final WatchableList sw = (WatchableList) iter.nextElement();
sw.filterListTo(start, end);
} // through the sensors
} // whether we have any sensors
// now do the same for our sensor arc data
if (_myDynamicShapes != null)
{
final Enumeration<Editable> iter = _myDynamicShapes.elements();
while (iter.hasMoreElements())
{
final WatchableList sw = (WatchableList) iter.nextElement();
sw.filterListTo(start, end);
} // through the sensor arcs
} // whether we have any sensor arcs
if (_mySolutions != null)
{
final Enumeration<Editable> iter = _mySolutions.elements();
while (iter.hasMoreElements())
{
final WatchableList sw = (WatchableList) iter.nextElement();
sw.filterListTo(start, end);
} // through the sensors
} // whether we have any sensors
// do we have any property listeners?
if (getSupport() != null)
{
final Debrief.GUI.Tote.StepControl.somePeriod newPeriod =
new Debrief.GUI.Tote.StepControl.somePeriod(start, end);
getSupport().firePropertyChange(WatchableList.FILTERED_PROPERTY, null,
newPeriod);
}
}
@Override
public void findNearestHotSpotIn(final Point cursorPos,
final WorldLocation cursorLoc, final ComponentConstruct currentNearest,
final Layer parentLayer)
{
// initialise thisDist, since we're going to be over-writing it
WorldDistance thisDist = new WorldDistance(0, WorldDistance.DEGS);
// cycle through the fixes
final Enumeration<Editable> fixes = getPositionIterator();
while (fixes.hasMoreElements())
{
final FixWrapper thisF = (FixWrapper) fixes.nextElement();
// only check it if it's visible
if (thisF.getVisible())
{
// how far away is it?
thisDist = thisF.getLocation().rangeFrom(cursorLoc, thisDist);
final WorldLocation fixLocation = new WorldLocation(thisF.getLocation())
{
private static final long serialVersionUID = 1L;
@Override
public void addToMe(final WorldVector delta)
{
super.addToMe(delta);
thisF.setFixLocation(this);
}
};
// try range
currentNearest.checkMe(this, thisDist, null, parentLayer, fixLocation);
}
}
}
@Override
public void findNearestHotSpotIn(final Point cursorPos,
final WorldLocation cursorLoc, final LocationConstruct currentNearest,
final Layer parentLayer, final Layers theData)
{
// initialise thisDist, since we're going to be over-writing it
WorldDistance thisDist = new WorldDistance(0, WorldDistance.DEGS);
// cycle through the fixes
final Enumeration<Editable> fixes = getPositionIterator();
while (fixes.hasMoreElements())
{
final FixWrapper thisF = (FixWrapper) fixes.nextElement();
if (thisF.getVisible())
{
// how far away is it?
thisDist = thisF.getLocation().rangeFrom(cursorLoc, thisDist);
// is it closer?
currentNearest.checkMe(this, thisDist, null, parentLayer);
}
}
}
public void findNearestSegmentHotspotFor(final WorldLocation cursorLoc,
final Point cursorPt, final LocationConstruct currentNearest)
{
// initialise thisDist, since we're going to be over-writing it
WorldDistance thisDist;
// cycle through the track segments
final Collection<Editable> segments = _thePositions.getData();
for (final Iterator<Editable> iterator = segments.iterator(); iterator
.hasNext();)
{
final TrackSegment thisSeg = (TrackSegment) iterator.next();
if (thisSeg.getVisible())
{
// how far away is it?
thisDist = new WorldDistance(thisSeg.rangeFrom(cursorLoc),
WorldDistance.DEGS);
// is it closer?
currentNearest.checkMe(thisSeg, thisDist, null, this);
}
}
}
private void fixLabelColor()
{
if (_theLabel.getColor() == null)
{
// check we have a colour
Color labelColor = getColor();
// did we ourselves have a colour?
if (labelColor == null)
{
// nope - do we have any legs?
final Enumeration<Editable> numer = this.getPositionIterator();
if (numer.hasMoreElements())
{
// ok, use the colour of the first point
final FixWrapper pos = (FixWrapper) numer.nextElement();
labelColor = pos.getColor();
}
}
_theLabel.setColor(labelColor);
}
}
/**
* one of our fixes has moved. better tell any bits that rely on the locations of our bits
*
* @param theFix
* the fix that moved
*/
public void fixMoved()
{
if (_mySensors != null)
{
final Enumeration<Editable> iter = _mySensors.elements();
while (iter.hasMoreElements())
{
final SensorWrapper nextS = (SensorWrapper) iter.nextElement();
nextS.setHost(this);
}
}
if (_myDynamicShapes != null)
{
final Enumeration<Editable> iter = _myDynamicShapes.elements();
while (iter.hasMoreElements())
{
final DynamicTrackShapeSetWrapper nextS =
(DynamicTrackShapeSetWrapper) iter.nextElement();
nextS.setHost(this);
}
}
}
/**
* ensure the cached set of raw positions gets cleared
*
*/
public void flushPeriodCache()
{
_cachedPeriod = null;
}
/**
* ensure the cached set of raw positions gets cleared
*
*/
public void flushPositionCache()
{
}
/**
* return the arrow frequencies for the track
*
* @return frequency in seconds
*/
public final HiResDate getArrowFrequency()
{
return _lastArrowFrequency;
}
/**
* calculate a position the specified distance back along the ownship track (note, we always
* interpolate the parent track position)
*
* @param searchTime
* the time we're looking at
* @param sensorOffset
* how far back the sensor should be
* @param wormInHole
* whether to plot a straight line back, or make sensor follow ownship
* @return the location
*/
public FixWrapper getBacktraceTo(final HiResDate searchTime,
final ArrayLength sensorOffset, final boolean wormInHole)
{
FixWrapper res = null;
// special case - for single point tracks
if (isSinglePointTrack())
{
final TrackSegment seg = (TrackSegment) _thePositions.elements()
.nextElement();
return (FixWrapper) seg.first();
}
if (wormInHole && sensorOffset != null)
{
res = WormInHoleOffset.getWormOffsetFor(this, searchTime, sensorOffset);
}
else
{
final boolean parentInterpolated = getInterpolatePoints();
setInterpolatePoints(true);
final MWC.GenericData.Watchable[] list = getNearestTo(searchTime);
// and restore the interpolated value
setInterpolatePoints(parentInterpolated);
FixWrapper wa = null;
if (list.length > 0)
{
wa = (FixWrapper) list[0];
}
// did we find it?
if (wa != null)
{
// yes, store it
res = new FixWrapper(wa.getFix().makeCopy());
// ok, are we dealing with an offset?
if (sensorOffset != null)
{
// get the current heading
final double hdg = wa.getCourse();
// and calculate where it leaves us
final WorldVector vector = new WorldVector(hdg, sensorOffset, null);
// now apply this vector to the origin
res.setLocation(new WorldLocation(res.getLocation().add(vector)));
}
}
}
return res;
}
/**
* what geographic area is covered by this track?
*
* @return get the outer bounds of the area
*/
@Override
public final WorldArea getBounds()
{
// we no longer just return the bounds of the track, because a portion
// of the track may have been made invisible.
// instead, we will pass through the full dataset and find the outer
// bounds
// of the visible area
WorldArea res = null;
if (!getVisible())
{
// hey, we're invisible, return null
}
else
{
final Enumeration<Editable> it = getPositionIterator();
while (it.hasMoreElements())
{
final FixWrapper fw = (FixWrapper) it.nextElement();
// is this point visible?
if (fw.getVisible())
{
// has our data been initialised?
if (res == null)
{
// no, initialise it
res = new WorldArea(fw.getLocation(), fw.getLocation());
}
else
{
// yes, extend to include the new area
res.extend(fw.getLocation());
}
}
}
// also extend to include our sensor data
if (_mySensors != null)
{
final Enumeration<Editable> iter = _mySensors.elements();
while (iter.hasMoreElements())
{
final PlainWrapper sw = (PlainWrapper) iter.nextElement();
final WorldArea theseBounds = sw.getBounds();
if (theseBounds != null)
{
if (res == null)
{
res = new WorldArea(theseBounds);
}
else
{
res.extend(sw.getBounds());
}
}
} // step through the sensors
} // whether we have any sensors
// also extend to include our sensor data
if (_myDynamicShapes != null)
{
final Enumeration<Editable> iter = _myDynamicShapes.elements();
while (iter.hasMoreElements())
{
final Plottable sw = (Plottable) iter.nextElement();
final WorldArea theseBounds = sw.getBounds();
if (theseBounds != null)
{
if (res == null)
{
res = new WorldArea(theseBounds);
}
else
{
res.extend(sw.getBounds());
}
}
} // step through the sensors
}
// and our solution data
if (_mySolutions != null)
{
final Enumeration<Editable> iter = _mySolutions.elements();
while (iter.hasMoreElements())
{
final PlainWrapper sw = (PlainWrapper) iter.nextElement();
final WorldArea theseBounds = sw.getBounds();
if (theseBounds != null)
{
if (res == null)
{
res = new WorldArea(theseBounds);
}
else
{
res.extend(sw.getBounds());
}
}
} // step through the sensors
} // whether we have any sensors
} // whether we're visible
// SPECIAL CASE: if we're a DR track, the positions all
// have the same value
if (res != null)
{
// have we ended up with an empty area?
if (res.getHeight() == 0)
{
// ok - force a bounds update
sortOutRelativePositions();
// and retrieve the bounds of hte first segment
res = this.getSegments().first().getBounds();
}
}
return res;
}
/**
* this accessor is only present to support testing. It should not be used externally
*
* @return the iterator we last used in getNearestTo()
*/
public WrappedIterators getCachedIterator()
{
return _lastPosIterator;
}
/**
* length of trail to plot
*/
public final Duration getCustomTrailLength()
{
return _customTrailLength;
}
/**
* length of trail to plot
*/
public final double getCustomVectorStretch()
{
final double res;
// do we have a value?
if (_customVectorStretch != null)
{
res = _customVectorStretch;
}
else
{
res = 0;
}
return res;
}
/**
* get the list of sensor arcs for this track
*/
public final BaseLayer getDynamicShapes()
{
return _myDynamicShapes;
}
/**
* the time of the last fix
*
* @return the DTG
*/
@Override
public final HiResDate getEndDTG()
{
HiResDate dtg = null;
final TimePeriod res = getTimePeriod();
if (res != null)
{
dtg = res.getEndDTG();
}
return dtg;
}
/**
* whether to show time labels at the start/end of the track
*
* @return yes/no
*/
public boolean getEndTimeLabels()
{
return _endTimeLabels;
}
/**
* the editable details for this track
*
* @return the details
*/
@Override
public Editable.EditorType getInfo()
{
if (_myEditor == null)
{
_myEditor = new trackInfo(this);
}
return _myEditor;
}
/**
* create a new, interpolated point between the two supplied
*
* @param previous
* the previous point
* @param next
* the next point
* @return and interpolated point
*/
private final FixWrapper getInterpolatedFix(final FixWrapper previous,
final FixWrapper next, final HiResDate requestedDTG)
{
FixWrapper res = null;
// do we have a start point
if (previous == null)
{
res = next;
}
// hmm, or do we have an end point?
if (next == null)
{
res = previous;
}
// did we find it?
if (res == null)
{
res = FixWrapper.interpolateFix(previous, next, requestedDTG);
}
return res;
}
@Override
public final boolean getInterpolatePoints()
{
return _interpolatePoints;
}
/**
* get the set of fixes contained within this time period (inclusive of both end values)
*
* @param start
* start DTG
* @param end
* end DTG
* @return series of fixes
*/
@Override
public final Collection<Editable> getItemsBetween(final HiResDate start,
final HiResDate end)
{
SortedSet<Editable> set = null;
// does our track contain any data at all
if (!_thePositions.isEmpty())
{
// see if we have _any_ points in range
if ((getStartDTG().greaterThan(end)) || (getEndDTG().lessThan(start)))
{
// don't bother with it.
}
else
{
// SPECIAL CASE! If we've been asked to show interpolated data
// points,
// then
// we should produce a series of items between the indicated
// times. How
// about 1 minute resolution?
if (getInterpolatePoints())
{
final long ourInterval = 1000 * 60; // one minute
set = new TreeSet<Editable>();
for (long newTime = start.getDate().getTime(); newTime < end.getDate()
.getTime(); newTime += ourInterval)
{
final HiResDate newD = new HiResDate(newTime);
final Watchable[] nearestOnes = getNearestTo(newD);
if (nearestOnes.length > 0)
{
final FixWrapper nearest = (FixWrapper) nearestOnes[0];
set.add(nearest);
}
}
}
else
{
// bugger that - get the real data
final Enumeration<Editable> iter = getPositionIterator();
set = new TreeSet<Editable>();
final TimePeriod period = new TimePeriod.BaseTimePeriod(start, end);
while (iter.hasMoreElements())
{
final FixWrapper nextF = (FixWrapper) iter.nextElement();
final HiResDate dtg = nextF.getDateTimeGroup();
if (period.contains(dtg))
{
set.add(nextF);
}
else if (dtg.greaterThan(end))
{
// ok, we've passed the end
break;
}
}
// // have a go..
// if (starter == null)
// starter = new FixWrapper(new Fix((start), _zeroLocation, 0.0, 0.0));
// else
// starter.getFix().setTime(new HiResDate(0, start.getMicros() - 1));
// if (finisher == null)
// finisher =
// new FixWrapper(new Fix(new HiResDate(0, end.getMicros() + 1),
// _zeroLocation, 0.0, 0.0));
// else
// finisher.getFix().setTime(new HiResDate(0, end.getMicros() + 1));
// // ok, ready, go for it.
// set = getPositionsBetween(starter, finisher);
}
}
}
return set;
}
/**
* method to allow the setting of label frequencies for the track
*
* @return frequency to use
*/
public final HiResDate getLabelFrequency()
{
return this._lastLabelFrequency;
}
/**
* what is the style used for plotting this track?
*
* @return
*/
public int getLineStyle()
{
return _lineStyle;
}
/**
* the line thickness (convenience wrapper around width)
*
* @return
*/
@Override
public int getLineThickness()
{
return _lineWidth;
}
/**
* whether to link points
*
* @return
*/
public boolean getLinkPositions()
{
return _linkPositions;
}
/**
* just have the one property listener - rather than an anonymous class
*
* @return
*/
public PropertyChangeListener getLocationListener()
{
return _locationListener;
}
/**
* name of this Track (normally the vessel name)
*
* @return the name
*/
@Override
public final String getName()
{
return _theLabel.getString();
}
/**
* whether to show the track label at the start or end of the track
*
* @return yes/no to indicate <I>At Start</I>
*/
public final boolean getNameAtStart()
{
return _LabelAtStart;
}
/**
* the relative location of the label
*
* @return the relative location
*/
public final Integer getNameLocation()
{
return _theLabel.getRelativeLocation();
}
/**
* whether the track label is visible or not
*
* @return yes/no
*/
public final boolean getNameVisible()
{
return _theLabel.getVisible();
}
/**
* find the fix nearest to this time (or the first fix for an invalid time)
*
* @param DTG
* the time of interest
* @return the nearest fix
*/
@Override
public final Watchable[] getNearestTo(final HiResDate srchDTG)
{
return getNearestTo(srchDTG, true);
}
/**
* find the fix nearest to this time (or the first fix for an invalid time)
*
* @param DTG
* the time of interest
* @param onlyVisible
* only consider visible fixes
* @return the nearest fix
*/
public final Watchable[] getNearestTo(final HiResDate srchDTG,
final boolean onlyVisible)
{
/**
* we need to end up with a watchable, not a fix, so we need to work our way through the fixes
*/
FixWrapper res = null;
// check that we do actually contain some data
if (_thePositions.isEmpty())
{
return new Watchable[]
{};
}
else if (isSinglePointTrack())
{
final TrackSegment seg = (TrackSegment) _thePositions.elements()
.nextElement();
final FixWrapper fix = (FixWrapper) seg.first();
return new Watchable[]
{fix};
}
// special case - if we've been asked for an invalid time value
if (srchDTG == TimePeriod.INVALID_DATE)
{
final TrackSegment seg = (TrackSegment) _thePositions.first();
final FixWrapper fix = (FixWrapper) seg.first();
// just return our first location
return new MWC.GenericData.Watchable[]
{fix};
}
else if (_lastFix != null && _lastFix.getDTG().equals(srchDTG))
{
// see if this is the DTG we have just requested
res = _lastFix;
}
else
{
final TrackSegment firstSeg = (TrackSegment) _thePositions.first();
final TrackSegment lastSeg = (TrackSegment) _thePositions.last();
if ((firstSeg != null) && (!firstSeg.isEmpty()))
{
// see if this DTG is inside our data range
// in which case we will just return null
final FixWrapper theFirst = (FixWrapper) firstSeg.first();
final FixWrapper theLast = (FixWrapper) lastSeg.last();
if ((srchDTG.greaterThan(theFirst.getTime())) && (srchDTG
.lessThanOrEqualTo(theLast.getTime())))
{
FixWrapper previous = null;
// do we already have a position iterator?
final Enumeration<Editable> pIter;
if (_lastPosIterator != null)
{
final FixWrapper thisPos = (FixWrapper) _lastPosIterator
.currentElement();
final FixWrapper prevPos = (FixWrapper) _lastPosIterator
.previousElement();
if (thisPos.getDTG().equals(srchDTG))
{
// ok, we know this answer, use it
res = thisPos;
pIter = null;
}
else if (thisPos.getDTG().lessThan(srchDTG))
{
// the current iterator is still valid, stick with it
pIter = _lastPosIterator;
previous = thisPos;
}
else if (prevPos != null && thisPos.getDTG().greaterThan(srchDTG)
&& prevPos.getDTG().lessThan(srchDTG))
{
// we're currently either side of the required value
// we don't need to restart the iterator
res = thisPos;
previous = prevPos;
pIter = _lastPosIterator;
}
else
{
// we've gone past the required value, and
// the previous value isn't of any use
pIter = getPositionIterator();
}
}
else
{
// we don't have a cached iterator, better create one then
pIter = getPositionIterator();
}
// yes it's inside our data range, find the first fix
// after the indicated point
if (res == null)
{
while (pIter.hasMoreElements())
{
final FixWrapper fw = (FixWrapper) pIter.nextElement();
if (!onlyVisible || fw.getVisible())
{
if (fw.getDTG().greaterThanOrEqualTo(srchDTG))
{
res = fw;
break;
}
// and remember the previous one
previous = fw;
}
}
}
// can we cache our iterator?
if (pIter != null && pIter.hasMoreElements())
{
// ok, it's still of value
_lastPosIterator = (WrappedIterators) pIter;
}
else
{
// nope, drop it.
_lastPosIterator = null;
}
// right, that's the first points on or before the indicated
// DTG. Are we
// meant
// to be interpolating?
if (res != null)
{
if (getInterpolatePoints())
{
if (!res.getTime().equals(srchDTG))
{
// do we know the previous time?
if (previous != null)
{
// cool, sort out the interpolated point USING
// THE ORIGINAL
// SEARCH TIME
res = getInterpolatedFix(previous, res, srchDTG);
// and reset the label
res.resetName();
}
}
}
}
}
else if (srchDTG.equals(theFirst.getDTG()))
{
// aaah, special case. just see if we're after a data point
// that's the
// same
// as our start time
res = theFirst;
}
}
// and remember this fix
_lastFix = res;
}
if (res != null)
{
return new MWC.GenericData.Watchable[]
{res};
}
else
{
return new MWC.GenericData.Watchable[]
{};
}
}
public boolean getPlotArrayCentre()
{
return _plotArrayCentre;
}
/**
* provide iterator for all positions that doesn't require a new list to be generated
*
* @return iterator through all positions
*/
public Enumeration<Editable> getPositionIterator()
{
return new WrappedIterators(_thePositions);
}
/**
* whether positions are being shown
*
* @return
*/
public final boolean getPositionsVisible()
{
return _showPositions;
}
/**
* method to allow the setting of data sampling frequencies for the track & sensor data
*
* @return frequency to use
*/
public final HiResDate getResampleDataAt()
{
return this._lastDataFrequency;
}
/**
* get our child segments
*
* @return
*/
public SegmentList getSegments()
{
return _thePositions;
}
/**
* get the list of sensors for this track
*/
public final BaseLayer getSensors()
{
return _mySensors;
}
/**
* return the symbol to be used for plotting this track in snail mode
*/
@Override
public final MWC.GUI.Shapes.Symbols.PlainSymbol getSnailShape()
{
return _theSnailShape;
}
/**
* get the list of sensors for this track
*/
public final BaseLayer getSolutions()
{
return _mySolutions;
}
// watchable (tote related) parameters
/**
* the earliest fix in the track
*
* @return the DTG
*/
@Override
public final HiResDate getStartDTG()
{
HiResDate res = null;
final TimePeriod period = getTimePeriod();
if (period != null)
{
res = period.getStartDTG();
}
return res;
}
/**
* get the color used to plot the symbol
*
* @return the color
*/
public final Color getSymbolColor()
{
return _theSnailShape.getColor();
}
/**
* return the symbol frequencies for the track
*
* @return frequency in seconds
*/
public final HiResDate getSymbolFrequency()
{
return _lastSymbolFrequency;
}
public WorldDistance getSymbolLength()
{
WorldDistance res = null;
if (_theSnailShape instanceof WorldScaledSym)
{
final WorldScaledSym sym = (WorldScaledSym) _theSnailShape;
res = sym.getLength();
}
return res;
}
/**
* get the type of this symbol
*/
public final String getSymbolType()
{
return _theSnailShape.getType();
}
public WorldDistance getSymbolWidth()
{
WorldDistance res = null;
if (_theSnailShape instanceof WorldScaledSym)
{
final WorldScaledSym sym = (WorldScaledSym) _theSnailShape;
res = sym.getWidth();
}
return res;
}
private TimePeriod getTimePeriod()
{
TimePeriod res = null;
final Enumeration<Editable> segs = _thePositions.elements();
while (segs.hasMoreElements())
{
final TrackSegment seg = (TrackSegment) segs.nextElement();
// do we have a dtg?
if ((seg.startDTG() != null) && (seg.endDTG() != null))
{
// yes, get calculating
if (res == null)
{
res = new TimePeriod.BaseTimePeriod(seg.startDTG(), seg.endDTG());
}
else
{
res.extend(seg.startDTG());
res.extend(seg.endDTG());
}
}
}
return res;
}
/**
* the colour of the points on the track
*
* @return the colour
*/
public final Color getTrackColor()
{
return getColor();
}
/**
* get the mode used to color the track
*
* @return
*/
public TrackColorMode getTrackColorMode()
{
// ok, see if we're using a deferred mode. If we are, we should correct it
if (_trackColorMode instanceof DeferredDatasetColorMode)
{
_trackColorMode = TrackColorModeHelper.sortOutDeferredMode(
(DeferredDatasetColorMode) _trackColorMode, this);
}
return _trackColorMode;
}
public List<TrackColorMode> getTrackColorModes()
{
return TrackColorModeHelper.getAdditionalTrackColorModes(this);
}
/**
* font handler
*
* @return the font to use for the label
*/
public final java.awt.Font getTrackFont()
{
return _theLabel.getFont();
}
/**
* get the set of fixes contained within this time period which haven't been filtered, and which
* have valid depths. The isVisible flag indicates whether a track has been filtered or not. We
* also have the getVisibleFixesBetween method (below) which decides if a fix is visible if it is
* set to Visible, and it's label or symbol are visible.
* <p/>
* We don't have to worry about a valid depth, since 3d doesn't show points with invalid depth
* values
*
* @param start
* start DTG
* @param end
* end DTG
* @return series of fixes
*/
public final Collection<Editable> getUnfilteredItems(final HiResDate start,
final HiResDate end)
{
// see if we have _any_ points in range
if ((getStartDTG().greaterThan(end)) || (getEndDTG().lessThan(start)))
{
return null;
}
if (this.getVisible() == false)
{
return null;
}
// get ready for the output
final Vector<Editable> res = new Vector<Editable>(0, 1);
// put the data into a period
final TimePeriod thePeriod = new TimePeriod.BaseTimePeriod(start, end);
// step through our fixes
final Enumeration<Editable> iter = getPositionIterator();
while (iter.hasMoreElements())
{
final FixWrapper fw = (FixWrapper) iter.nextElement();
if (fw.getVisible())
{
// is it visible?
if (thePeriod.contains(fw.getTime()))
{
// hey, it's valid - continue
res.add(fw);
}
}
}
return res;
}
/**
* Determine the time period for which we have visible locations
*
* @return
*/
public TimePeriod getVisiblePeriod()
{
// ok, have we determined the visible period recently?
final long tNow = System.currentTimeMillis();
// how long does the cached value remain valid for?
final long ALLOWABLE_PERIOD = 500;
if (_cachedPeriod != null && tNow
- _timeCachedPeriodCalculated < ALLOWABLE_PERIOD)
{
// still in date, use the last calculated period
}
else
{
// ok, calculate a new one
TimePeriod res = null;
final Enumeration<Editable> pos = getPositionIterator();
while (pos.hasMoreElements())
{
final FixWrapper editable = (FixWrapper) pos.nextElement();
if (editable.getVisible())
{
final HiResDate thisT = editable.getTime();
if (res == null)
{
res = new TimePeriod.BaseTimePeriod(thisT, thisT);
}
else
{
res.extend(thisT);
}
}
}
// ok, store the new time period
_cachedPeriod = res;
// remember when it was calculated
_timeCachedPeriodCalculated = tNow;
}
return _cachedPeriod;
}
/**
* whether this object has editor details
*
* @return yes/no
*/
@Override
public final boolean hasEditor()
{
return true;
}
@Override
public boolean hasOrderedChildren()
{
return false;
}
/**
* whether this is single point track. Single point tracks get special processing.
*
* @return
*/
public boolean isSinglePointTrack()
{
final boolean res;
if (_thePositions.size() == 1)
{
final TrackSegment first = (TrackSegment) _thePositions.elements()
.nextElement();
// we want to avoid getting the size() of the list.
// So, do fancy trick to check the first element is non-null,
// and the second is null
final Enumeration<Editable> elems = first.elements();
if (elems != null && elems.hasMoreElements() && elems
.nextElement() != null && !elems.hasMoreElements())
{
res = true;
}
else
{
res = false;
}
}
else
{
res = false;
}
return res;
}
/**
* accessor to determine if this is a relative track
*
* @return
*/
public boolean isTMATrack()
{
boolean res = false;
if (_thePositions != null && !_thePositions.isEmpty() && _thePositions
.first() instanceof CoreTMASegment)
{
res = true;
}
return res;
}
public boolean isVisibleAt(final HiResDate dtg)
{
boolean res = false;
// special case - single track
if (isSinglePointTrack())
{
// we'll assume it's never ending.
res = true;
}
else
{
final TimePeriod visiblePeriod = getVisiblePeriod();
if (visiblePeriod != null)
{
res = visiblePeriod.contains(dtg);
}
}
return res;
}
/**
* quick accessor for how many fixes we have
*
* @return
*/
public int numFixes()
{
int res = 0;
// loop through segments
final Enumeration<Editable> segs = _thePositions.elements();
while (segs.hasMoreElements())
{
// get this segment
final TrackSegment seg = (TrackSegment) segs.nextElement();
res += seg.size();
}
return res;
}
/**
* draw this track (we can leave the Positions to draw themselves)
*
* @param dest
* the destination
*/
@Override
public final void paint(final CanvasType dest)
{
// check we are visible and have some track data, else we won't work
if (!getVisible() || this.getStartDTG() == null)
{
return;
}
// set the thickness for this track
dest.setLineWidth(_lineWidth);
// and set the initial colour for this track
if (getColor() != null)
{
dest.setColor(getColor());
}
// firstly plot the solutions
if (_mySolutions.getVisible())
{
final Enumeration<Editable> iter = _mySolutions.elements();
while (iter.hasMoreElements())
{
final TMAWrapper sw = (TMAWrapper) iter.nextElement();
// just check that the sensor knows we're it's parent
if (sw.getHost() == null)
{
sw.setHost(this);
}
// and do the paint
sw.paint(dest);
} // through the solutions
} // whether the solutions are visible
// now plot the sensors
if (_mySensors.getVisible())
{
final Enumeration<Editable> iter = _mySensors.elements();
while (iter.hasMoreElements())
{
final SensorWrapper sw = (SensorWrapper) iter.nextElement();
// just check that the sensor knows we're it's parent
if (sw.getHost() == null)
{
sw.setHost(this);
}
// and do the paint
sw.paint(dest);
} // through the sensors
} // whether the sensor layer is visible
// and now the track itself
// just check if we are drawing anything at all
if ((!getLinkPositions()
|| getLineStyle() == LineStylePropertyEditor.UNCONNECTED)
&& (!_showPositions))
{
return;
}
// let the fixes draw themselves in
final List<FixWrapper> endPoints = paintFixes(dest);
final boolean plotted_anything = !endPoints.isEmpty();
// and draw the track label
// still, we only plot the track label if we have plotted any
// points
if (getNameVisible() && plotted_anything)
{
// just see if we have multiple segments. if we do,
// name them individually
if (this._thePositions.size() <= 1)
{
paintSingleTrackLabel(dest, endPoints);
}
else
{
// we've got multiple segments, name them
paintMultipleSegmentLabel(dest);
}
} // if the label is visible
// lastly - paint any TMA or planning segment labels
paintVectorLabels(dest);
}
@Override
public void paint(final CanvasType dest, final long time)
{
if (!getVisible())
{
return;
}
// set the thickness for this track
dest.setLineWidth(_lineWidth);
// and set the initial colour for this track
if (getColor() != null)
{
dest.setColor(getColor());
}
// we plot only the dynamic arcs because they are MovingPlottable
if (_myDynamicShapes.getVisible())
{
final Enumeration<Editable> iter = _myDynamicShapes.elements();
while (iter.hasMoreElements())
{
final DynamicTrackShapeSetWrapper sw =
(DynamicTrackShapeSetWrapper) iter.nextElement();
// and do the paint
sw.paint(dest, time);
}
}
}
/**
* paint the fixes for this track
*
* @param dest
* @return a collection containing the first & last visible fix
*/
private List<FixWrapper> paintFixes(final CanvasType dest)
{
// collate a list of the start & end points
final List<FixWrapper> endPoints = new ArrayList<FixWrapper>();
// use the track color mode
final TrackColorMode tMode = getTrackColorMode();
// we need an array to store the polyline of points in. Check it's big
// enough
checkPointsArray();
// we draw tracks as polylines. But we can't do that
// if the color/style changes. So, we have to track their values
Color lastCol = null;
final int defaultlineStyle = getLineStyle();
FixWrapper lastFix = null;
// update DR positions (if necessary)
if (_relativeUpdatePending)
{
// ok, generate the points on the relative track
sortOutRelativePositions();
// and clear the flag
_relativeUpdatePending = false;
}
// cycle through the segments
final Enumeration<Editable> segments = _thePositions.elements();
while (segments.hasMoreElements())
{
final TrackSegment seg = (TrackSegment) segments.nextElement();
// is it a single point segment?
final boolean singlePointSegment = seg.size() == 1;
// how shall we plot this segment?
final int thisLineStyle;
// is the parent using the default style?
if (defaultlineStyle == CanvasType.SOLID)
{
// yes, let's override it, if the segment wants to
thisLineStyle = seg.getLineStyle();
}
else
{
// no, we're using a custom style - don't override it.
thisLineStyle = defaultlineStyle;
}
// is this segment visible?
if (!seg.getVisible())
{
// nope, jump to the next
continue;
}
final Enumeration<Editable> fixWrappers = seg.elements();
while (fixWrappers.hasMoreElements())
{
final FixWrapper fw = (FixWrapper) fixWrappers.nextElement();
// have a look at the last fix. we defer painting the fix label,
// because we want to know the id of the last visible fix, since
// we may need to paint it's label in 6 DTG
if ((getPositionsVisible() && lastFix != null && lastFix.getVisible())
|| singlePointSegment)
{
// is this the first visible fix?
final boolean isFirstVisibleFix = endPoints.size() == 1;
// special handling. if we only have one point in the segment,
// we treat it as the last fix
final FixWrapper newLastFix;
if (lastFix == null)
{
newLastFix = fw;
}
else
{
newLastFix = lastFix;
}
// more special processing - for single-point segments
final boolean symWasVisible = newLastFix.getSymbolShowing();
if (singlePointSegment)
{
newLastFix.setSymbolShowing(true);
}
paintIt(dest, newLastFix, getEndTimeLabels() && isFirstVisibleFix,
false);
if (singlePointSegment)
{
newLastFix.setSymbolShowing(symWasVisible);
}
}
// now there's a chance that our fix has forgotten it's
// parent,
// particularly if it's the victim of a
// copy/paste operation. Tell it about it's children
fw.setTrackWrapper(this);
final Color thisFixColor = tMode.colorFor(fw);
// do our job of identifying the first & last date value
if (fw.getVisible())
{
// ok, see if this is the first one
if (endPoints.size() == 0)
{
endPoints.add(fw);
}
else
{
// have we already got an end value?
if (endPoints.size() == 2)
{
// yes, drop it
endPoints.remove(1);
}
// store a new end value
endPoints.add(fw);
}
}
else
{
// nope. Don't join it to the last position.
// ok, if we've built up a polygon, we need to write it
// now
paintSetOfPositions(dest, lastCol, thisLineStyle);
}
// remember this fix, used for relative tracks
lastFix = fw;
// ok, we only do this writing to screen if the actual
// position is visible
if (!fw.getVisible())
{
continue;
}
final java.awt.Point thisP = dest.toScreen(fw.getLocation());
// just check that there's enough GUI to create the plot
// (i.e. has a point been returned)
if (thisP == null)
{
return endPoints;
}
// are we
if (getLinkPositions()
&& (getLineStyle() != LineStylePropertyEditor.UNCONNECTED))
{
// right, just check if we're a different colour to
// the previous one
final Color thisCol = thisFixColor;
// do we know the previous colour
if (lastCol == null)
{
lastCol = thisCol;
}
// is this to be joined to the previous one?
if (fw.getLineShowing())
{
// so, grow the the polyline, unless we've got a
// colour change...
if (thisCol != lastCol)
{
// double check we haven't been modified
if (_ptCtr > _myPts.length)
{
continue;
}
// add our position to the list - we'll output
// the polyline at the end
if (_ptCtr < _myPts.length - 1)
{
_myPts[_ptCtr++] = thisP.x;
_myPts[_ptCtr++] = thisP.y;
}
// yup, better get rid of the previous
// polygon
paintSetOfPositions(dest, lastCol, thisLineStyle);
}
// add our position to the list - we'll output
// the polyline at the end
if (_ptCtr > _myPts.length - 1)
{
continue;
}
_myPts[_ptCtr++] = thisP.x;
_myPts[_ptCtr++] = thisP.y;
}
else
{
// nope, output however much line we've got so
// far - since this
// line won't be joined to future points
paintSetOfPositions(dest, thisCol, thisLineStyle);
// start off the next line
_myPts[_ptCtr++] = thisP.x;
_myPts[_ptCtr++] = thisP.y;
}
/*
* set the colour of the track from now on to this colour, so that the "link" to the next
* fix is set to this colour if left unchanged
*/
dest.setColor(thisFixColor);
// and remember the last colour
lastCol = thisCol;
}
} // while fixWrappers has more elements
// ok - paint the label for the last visible point
if (getPositionsVisible())
{
if (endPoints.size() > 1)
{
// special handling. If it's a planning segment, we hide the
// last fix, unless it's the very last segment
// do we have more legs?
final boolean hasMoreLegs = segments.hasMoreElements();
// is this a planning track?
final boolean isPlanningTrack = this instanceof CompositeTrackWrapper;
// ok, we hide the last point for planning legs, if there are
// more legs to come
final boolean forceHideLabel = isPlanningTrack && hasMoreLegs;
// ok, get painting
paintIt(dest, endPoints.get(1), getEndTimeLabels(), forceHideLabel);
}
}
// ok, just see if we have any pending polylines to paint
paintSetOfPositions(dest, lastCol, thisLineStyle);
}
return endPoints;
}
// LAYER support methods
/**
* paint this fix, overriding the label if necessary (since the user may wish to have 6-figure
* DTGs at the start & end of the track
*
* @param dest
* where we paint to
* @param thisF
* the fix we're painting
* @param isEndPoint
* whether point is one of the ends
* @param forceHideLabel
* whether we wish to hide the label
*/
private void paintIt(final CanvasType dest, final FixWrapper thisF,
final boolean isEndPoint, final boolean forceHideLabel)
{
// have a look at the last fix. we defer painting the fix label,
// because we want to know the id of the last visible fix, since
// we may need to paint it's label in 6 DTG
final boolean isVis = thisF.getLabelShowing();
final String fmt = thisF.getLabelFormat();
final String lblVal = thisF.getLabel();
// are we plotting DTG at ends?
if (isEndPoint)
{
// set the custom format for our end labels (6-fig DTG)
thisF.setLabelFormat("ddHHmm");
thisF.setLabelShowing(true);
}
if (forceHideLabel)
{
thisF.setLabelShowing(false);
}
// this next method just paints the fix. we've put the
// call into paintThisFix so we can override the painting
// in the CompositeTrackWrapper class
paintThisFix(dest, thisF.getLocation(), thisF);
// do we need to restore it?
if (isEndPoint)
{
thisF.setLabelFormat(fmt);
thisF.setLabelShowing(isVis);
thisF.setLabel(lblVal);
}
if (forceHideLabel)
{
thisF.setLabelShowing(isVis);
}
}
private void paintMultipleSegmentLabel(final CanvasType dest)
{
final Enumeration<Editable> posis = _thePositions.elements();
while (posis.hasMoreElements())
{
final TrackSegment thisE = (TrackSegment) posis.nextElement();
// is this segment visible?
if (!thisE.getVisible())
{
continue;
}
// does it have visible data points?
if (thisE.isEmpty())
{
continue;
}
// if this is a TMA segment, we plot the name 1/2 way along. If it isn't
// we plot it at the start
if (thisE instanceof CoreTMASegment)
{
// just move along - we plot the name
// a the mid-point
}
else
{
final WorldLocation theLoc = thisE.getTrackStart();
// hey, don't abuse the track label - create a fresh one each time
final TextLabel label = new TextLabel(theLoc, thisE.getName());
// copy the font from the parent
label.setFont(_theLabel.getFont());
// is the first track a DR track?
if (thisE.getPlotRelative())
{
label.setFont(label.getFont().deriveFont(Font.ITALIC));
}
else if (_theLabel.getFont().isItalic())
{
label.setFont(label.getFont().deriveFont(Font.PLAIN));
}
// just see if this is a planning segment, with its own colors
final Color color;
if (thisE instanceof PlanningSegment)
{
final PlanningSegment ps = (PlanningSegment) thisE;
color = ps.getColor();
}
else
{
color = getColor();
}
label.setColor(color);
label.setLocation(theLoc);
label.paint(dest);
}
}
}
/**
* paint any polyline that we've built up
*
* @param dest
* - where we're painting to
* @param thisCol
* @param lineStyle
*/
private void paintSetOfPositions(final CanvasType dest, final Color thisCol,
final int lineStyle)
{
if (_ptCtr > 0)
{
dest.setColor(thisCol);
dest.setLineStyle(lineStyle);
final int[] poly = new int[_ptCtr];
System.arraycopy(_myPts, 0, poly, 0, _ptCtr);
dest.drawPolyline(poly);
dest.setLineStyle(CanvasType.SOLID);
// and reset the counter
_ptCtr = 0;
}
}
private void paintSingleTrackLabel(final CanvasType dest,
final List<FixWrapper> endPoints)
{
// check that we have found a location for the label
if (_theLabel.getLocation() == null)
{
return;
}
// check that we have set the name for the label
if (_theLabel.getString() == null)
{
_theLabel.setString(getName());
}
// does the first label have a colour?
fixLabelColor();
// ok, sort out the correct location
final FixWrapper hostFix;
if (getNameAtStart() || endPoints.size() == 1)
{
// ok, we're choosing to use the start for the location. Or,
// we've only got one fix - in which case the end "is" the start
hostFix = endPoints.get(0);
}
else
{
hostFix = endPoints.get(1);
}
// sort out the location
_theLabel.setLocation(hostFix.getLocation());
// and the relative location
// hmm, if we're plotting date labels at the ends,
// shift the track name so that it's opposite
Integer oldLoc = null;
if (this.getEndTimeLabels())
{
oldLoc = getNameLocation();
// is it auto-locate?
if (oldLoc == NullableLocationPropertyEditor.AUTO)
{
// ok, automatically locate it
final int theLoc = LabelLocationPropertyEditor.oppositeFor(hostFix
.getLabelLocation());
setNameLocation(theLoc);
}
}
// and paint it
_theLabel.paint(dest);
// ok, restore the user-favourite location
if (oldLoc != null)
{
_theLabel.setRelativeLocation(oldLoc);
}
}
/**
* get the fix to paint itself
*
* @param dest
* @param lastLocation
* @param fw
*/
protected void paintThisFix(final CanvasType dest,
final WorldLocation lastLocation, final FixWrapper fw)
{
fw.paintMe(dest, lastLocation, getTrackColorMode().colorFor(fw));
}
/**
* draw vector labels for any TMA tracks
*
* @param dest
*/
private void paintVectorLabels(final CanvasType dest)
{
// cycle through the segments
final Enumeration<Editable> segments = _thePositions.elements();
while (segments.hasMoreElements())
{
final TrackSegment seg = (TrackSegment) segments.nextElement();
// is this segment visible?
if (!seg.getVisible())
{
// nope, jump to the next
continue;
}
// paint only visible planning segments
if (seg instanceof PlanningSegment)
{
final PlanningSegment ps = (PlanningSegment) seg;
ps.paintLabel(dest);
}
else if (seg instanceof CoreTMASegment)
{
final CoreTMASegment tma = (CoreTMASegment) seg;
// check the segment has some data
if (!seg.isEmpty())
{
final WorldLocation firstLoc = seg.first().getBounds().getCentre();
final WorldLocation lastLoc = seg.last().getBounds().getCentre();
final Font f = Defaults.getFont();
final Color c = _theLabel.getColor();
// tell the segment it's being stretched
final String spdTxt = MWC.Utilities.TextFormatting.GeneralFormat
.formatOneDecimalPlace(tma.getSpeed().getValueIn(WorldSpeed.Kts));
// copied this text from RelativeTMASegment
double courseVal = tma.getCourse();
if (courseVal < 0)
{
courseVal += 360;
}
String textLabel = "[" + spdTxt + " kts " + (int) courseVal
+ "\u00B0]";
// ok, now plot it
CanvasTypeUtilities.drawLabelOnLine(dest, textLabel, f, c, firstLoc,
lastLoc, 1.2, true);
textLabel = tma.getName().replace(TextLabel.NEWLINE_MARKER, " ");
CanvasTypeUtilities.drawLabelOnLine(dest, textLabel, f, c, firstLoc,
lastLoc, 1.2, false);
}
}
}
}
/**
* return the range from the nearest corner of the track
*
* @param other
* the other location
* @return the range
*/
@Override
public final double rangeFrom(final WorldLocation other)
{
double nearest = -1;
// do we have a track?
if (_myWorldArea != null)
{
// find the nearest point on the track
nearest = _myWorldArea.rangeFrom(other);
}
return nearest;
}
// track-shifting operation
// support for dragging the track around
/**
* remove the requested item from the track
*
* @param point
* the point to remove
*/
@Override
public final void removeElement(final Editable point)
{
boolean modified = false;
// just see if it's a sensor which is trying to be removed
if (point instanceof SensorWrapper)
{
_mySensors.removeElement(point);
// tell the sensor wrapper to forget about us
final TacticalDataWrapper sw = (TacticalDataWrapper) point;
sw.setHost(null);
// remember that we've made a change
modified = true;
}
else if (point instanceof TMAWrapper)
{
_mySolutions.removeElement(point);
// tell the sensor wrapper to forget about us
final TacticalDataWrapper sw = (TacticalDataWrapper) point;
sw.setHost(null);
// remember that we've made a change
modified = true;
}
else if (point instanceof SensorContactWrapper)
{
// ok, cycle through our sensors, try to remove this contact...
final Enumeration<Editable> iter = _mySensors.elements();
while (iter.hasMoreElements())
{
final SensorWrapper sw = (SensorWrapper) iter.nextElement();
// try to remove it from this one...
sw.removeElement(point);
// remember that we've made a change
modified = true;
}
}
else if (point instanceof DynamicTrackShapeWrapper)
{
// ok, cycle through our sensors, try to remove this contact...
final Enumeration<Editable> iter = _myDynamicShapes.elements();
while (iter.hasMoreElements())
{
final DynamicTrackShapeSetWrapper sw =
(DynamicTrackShapeSetWrapper) iter.nextElement();
// try to remove it from this one...
sw.removeElement(point);
// remember that we've made a change
modified = true;
}
}
else if (point instanceof TrackSegment)
{
_thePositions.removeElement(point);
// and clear the parent item
final TrackSegment ts = (TrackSegment) point;
ts.setWrapper(null);
// we also need to stop listen for a child moving
ts.removePropertyChangeListener(CoreTMASegment.ADJUSTED,
_childTrackMovedListener);
// remember that we've made a change
modified = true;
}
else if (point.equals(_mySensors))
{
// ahh, the user is trying to delete all the solution, cycle through
// them
final Enumeration<Editable> iter = _mySensors.elements();
while (iter.hasMoreElements())
{
final Editable editable = iter.nextElement();
// tell the sensor wrapper to forget about us
final TacticalDataWrapper sw = (TacticalDataWrapper) editable;
sw.setHost(null);
}
// and empty them out
_mySensors.removeAllElements();
// remember that we've made a change
modified = true;
}
else if (point.equals(_myDynamicShapes))
{
// ahh, the user is trying to delete all the solution, cycle through
// them
final Enumeration<Editable> iter = _myDynamicShapes.elements();
while (iter.hasMoreElements())
{
final Editable editable = iter.nextElement();
// tell the sensor wrapper to forget about us
final DynamicTrackShapeSetWrapper sw =
(DynamicTrackShapeSetWrapper) editable;
sw.setHost(null);
}
// and empty them out
_myDynamicShapes.removeAllElements();
// remember that we've made a change
modified = true;
}
else if (point.equals(_mySolutions))
{
// ahh, the user is trying to delete all the solution, cycle through
// them
final Enumeration<Editable> iter = _mySolutions.elements();
while (iter.hasMoreElements())
{
final Editable editable = iter.nextElement();
// tell the sensor wrapper to forget about us
final TacticalDataWrapper sw = (TacticalDataWrapper) editable;
sw.setHost(null);
}
// and empty them out
_mySolutions.removeAllElements();
// remember that we've made a change
modified = true;
}
else if (point instanceof FixWrapper)
{
final FixWrapper fw = (FixWrapper) point;
// loop through the segments
final Enumeration<Editable> segments = _thePositions.elements();
while (segments.hasMoreElements())
{
final TrackSegment seg = (TrackSegment) segments.nextElement();
seg.removeElement(point);
// and stop listening to it (if it's a fix)
fw.removePropertyChangeListener(PlainWrapper.LOCATION_CHANGED,
_locationListener);
// remember that we've made a change
modified = true;
// we've also got to clear the cache
flushPeriodCache();
flushPositionCache();
}
}
if (modified)
{
setRelativePending();
}
}
/**
* pass through the track, resetting the labels back to their original DTG
*/
@FireReformatted
public void resetLabels()
{
FormatTracks.formatTrack(this);
}
@Override
public Enumeration<Editable> segments()
{
final TreeSet<Editable> res = new TreeSet<Editable>();
// ok, we want to wrap our fast-data as a set of plottables
// see how many track segments we have
if (_thePositions.size() == 1)
{
// just the one, insert it
res.add(_thePositions.first());
}
else
{
// more than one, insert them as a tree
res.add(_thePositions);
}
return new TrackWrapper_Support.IteratorWrapper(res.iterator());
}
/**
* how frequently symbols are placed on the track
*
* @param theVal
* frequency in seconds
*/
public final void setArrowFrequency(final HiResDate theVal)
{
this._lastArrowFrequency = theVal;
// set the "showPositions" parameter, as long as we are
// not setting the symbols off
if (theVal.getMicros() != 0.0)
{
this.setPositionsVisible(true);
}
final FixSetter setSymbols = new FixSetter()
{
@Override
public void execute(final FixWrapper fix, final boolean val)
{
fix.setArrowShowing(val);
}
};
setFixes(setSymbols, theVal);
}
/**
* set the colour of this track label
*
* @param theCol
* the colour
*/
@Override
@FireReformatted
public final void setColor(final Color theCol)
{
// do the parent
super.setColor(theCol);
// now do our processing
_theLabel.setColor(theCol);
}
/**
* length of trail to draw
*/
public final void setCustomTrailLength(final Duration len)
{
// just check that it's a non-null length
if (len != null)
{
if (len.getMillis() != 0)
{
_customTrailLength = len;
}
else
{
_customTrailLength = null;
}
}
}
/**
* length of trail to draw
*/
public final void setCustomVectorStretch(final double stretch)
{
_customVectorStretch = stretch;
}
/**
* whether to show time labels at the start/end of the track
*
* @param endTimeLabels
* yes/no
*/
@FireReformatted
public void setEndTimeLabels(final boolean endTimeLabels)
{
this._endTimeLabels = endTimeLabels;
}
/**
* the setter function which passes through the track
*/
private void setFixes(final FixSetter setter, final HiResDate theVal)
{
if (theVal == null)
{
return;
}
if (_thePositions.size() == 0)
{
return;
}
final long freq = theVal.getMicros();
// briefly check if we are revealing/hiding all times (ie if freq is 1
// or 0)
if (freq == TimeFrequencyPropertyEditor.SHOW_ALL_FREQUENCY)
{
// show all of the labels
final Enumeration<Editable> iter = getPositionIterator();
while (iter.hasMoreElements())
{
final FixWrapper fw = (FixWrapper) iter.nextElement();
setter.execute(fw, true);
}
}
else
{
// no, we're not just blindly doing all of them. do them at the
// correct
// frequency
// hide all of the labels/symbols first
final Enumeration<Editable> enumA = getPositionIterator();
while (enumA.hasMoreElements())
{
final FixWrapper fw = (FixWrapper) enumA.nextElement();
setter.execute(fw, false);
}
if (freq == 0)
{
// we can ignore this, since we have just hidden all of the
// points
}
else
{
if (getStartDTG() != null)
{
// pass through the track setting the values
// sort out the start and finish times
long start_time = getStartDTG().getMicros();
final long end_time = getEndDTG().getMicros();
// first check that there is a valid time period between start
// time
// and end time
if (start_time + freq < end_time)
{
long num = start_time / freq;
// we need to add one to the quotient if it has rounded down
if (start_time % freq == 0)
{
// start is at our freq, so we don't need to increment
}
else
{
num++;
}
// calculate new start time
start_time = num * freq;
}
else
{
// there is not one of our 'intervals' between the start and
// the end,
// so use the start time
}
long nextMarker = start_time / 1000L;
final long freqMillis = freq / 1000L;
final Enumeration<Editable> iter = this.getPositionIterator();
while (iter.hasMoreElements())
{
final FixWrapper nextF = (FixWrapper) iter.nextElement();
final long hisDate = nextF.getDTG().getDate().getTime();
if (hisDate >= nextMarker)
{
// hmm, has there been a large jump?
if (hisDate - nextMarker <= freqMillis)
{
// no. Ok, show this item. If there's a larger
// jump, we don't automatically show this item,
// it's better to find the next marker time.
setter.execute(nextF, true);
}
// hmm, if we've just passed a huge gap, we may need to add
// a few intervals
while (nextMarker <= hisDate)
{
// carry on moving the next marker right
nextMarker += freqMillis;
}
}
}
}
}
}
}
@Override
public final void setInterpolatePoints(final boolean val)
{
_interpolatePoints = val;
// note: when we switch interpolation on or off, it can change
// the fix that is to be returned from getNearestTo().
// So, we should clear the lastDTG cached value
_lastFix = null;
}
/**
* set the label frequency (in seconds)
*
* @param theVal
* frequency to use
*/
public final void setLabelFrequency(final HiResDate theVal)
{
this._lastLabelFrequency = theVal;
final FixSetter setLabel = new FixSetter()
{
@Override
public void execute(final FixWrapper fix, final boolean val)
{
fix.setLabelShowing(val);
}
};
setFixes(setLabel, theVal);
}
/**
* set the style used for plotting the lines for this track
*
* @param val
*/
public void setLineStyle(final int val)
{
_lineStyle = val;
}
/**
* the line thickness (convenience wrapper around width)
*/
public void setLineThickness(final int val)
{
_lineWidth = val;
}
/**
* whether to link points
*
* @param linkPositions
*/
public void setLinkPositions(final boolean linkPositions)
{
_linkPositions = linkPositions;
}
/**
* set the name of this track (normally the name of the vessel
*
* @param theName
* the name as a String
*/
@Override
@FireReformatted
public final void setName(final String theName)
{
_theLabel.setString(theName);
}
/**
* whether to show the track name at the start or end of the track
*
* @param val
* yes no for <I>show label at start</I>
*/
public final void setNameAtStart(final boolean val)
{
_LabelAtStart = val;
}
/**
* the relative location of the label
*
* @param val
* the relative location
*/
public final void setNameLocation(final Integer val)
{
_theLabel.setRelativeLocation(val);
}
/**
* whether to show the track name
*
* @param val
* yes/no
*/
public final void setNameVisible(final boolean val)
{
_theLabel.setVisible(val);
}
public void setPlotArrayCentre(final boolean plotArrayCentre)
{
_plotArrayCentre = plotArrayCentre;
}
/**
* whether to show the position fixes
*
* @param val
* yes/no
*/
public final void setPositionsVisible(final boolean val)
{
_showPositions = val;
}
private void setRelativePending()
{
_relativeUpdatePending = true;
}
/**
* set the data frequency (in seconds) for the track & sensor data
*
* @param theVal
* frequency to use
*/
@FireExtended
public final void setResampleDataAt(final HiResDate theVal)
{
this._lastDataFrequency = theVal;
// have a go at trimming the start time to a whole number of intervals
final long interval = theVal.getMicros();
// do we have a start time (we may just be being tested...)
if (this.getStartDTG() == null)
{
return;
}
final long currentStart = this.getStartDTG().getMicros();
long startTime = (currentStart / interval) * interval;
// just check we're in the range
if (startTime < currentStart)
{
startTime += interval;
}
// move back to millis
startTime /= 1000L;
// just check it's not a barking frequency
if (theVal.getDate().getTime() <= 0)
{
// ignore, we don't need to do anything for a zero or a -1
}
else
{
final SegmentList segments = _thePositions;
final Enumeration<Editable> theEnum = segments.elements();
while (theEnum.hasMoreElements())
{
final TrackSegment seg = (TrackSegment) theEnum.nextElement();
seg.decimate(theVal, this, startTime);
}
// start off with the sensor data
if (_mySensors != null)
{
for (final Enumeration<Editable> iterator = _mySensors
.elements(); iterator.hasMoreElements();)
{
final SensorWrapper thisS = (SensorWrapper) iterator.nextElement();
thisS.decimate(theVal, startTime);
}
}
// now the solutions
if (_mySolutions != null)
{
for (final Enumeration<Editable> iterator = _mySolutions
.elements(); iterator.hasMoreElements();)
{
final TMAWrapper thisT = (TMAWrapper) iterator.nextElement();
thisT.decimate(theVal, startTime);
}
}
// ok, also set the arrow, symbol, label frequencies
setLabelFrequency(getLabelFrequency());
setSymbolFrequency(getSymbolFrequency());
setArrowFrequency(getArrowFrequency());
}
// remember we may need to regenerate positions, if we're a TMA solution
final Editable firstLeg = getSegments().elements().nextElement();
if (firstLeg instanceof CoreTMASegment)
{
// setRelativePending();
sortOutRelativePositions();
}
}
public final void setSymbolColor(final Color col)
{
_theSnailShape.setColor(col);
}
/**
* how frequently symbols are placed on the track
*
* @param theVal
* frequency in seconds
*/
public final void setSymbolFrequency(final HiResDate theVal)
{
this._lastSymbolFrequency = theVal;
// set the "showPositions" parameter, as long as we are
// not setting the symbols off
if (theVal == null)
{
return;
}
if (theVal.getMicros() != 0.0)
{
this.setPositionsVisible(true);
}
final FixSetter setSymbols = new FixSetter()
{
@Override
public void execute(final FixWrapper fix, final boolean val)
{
fix.setSymbolShowing(val);
}
};
setFixes(setSymbols, theVal);
}
public void setSymbolLength(final WorldDistance symbolLength)
{
if (_theSnailShape instanceof WorldScaledSym)
{
final WorldScaledSym sym = (WorldScaledSym) _theSnailShape;
sym.setLength(symbolLength);
}
}
public final void setSymbolType(final String val)
{
// is this the type of our symbol?
if (val.equals(_theSnailShape.getType()))
{
// don't bother we're using it already
}
else
{
// remember the size of the symbol
final double scale = _theSnailShape.getScaleVal();
// remember the color of the symbol
final Color oldCol = _theSnailShape.getColor();
// replace our symbol with this new one
_theSnailShape = MWC.GUI.Shapes.Symbols.SymbolFactory.createSymbol(val);
_theSnailShape.setColor(oldCol);
_theSnailShape.setScaleVal(scale);
}
}
public void setSymbolWidth(final WorldDistance symbolWidth)
{
if (_theSnailShape instanceof WorldScaledSym)
{
final WorldScaledSym sym = (WorldScaledSym) _theSnailShape;
sym.setHeight(symbolWidth);
}
}
// note we are putting a track-labelled wrapper around the colour
// parameter, to make the properties window less confusing
/**
* the colour of the points on the track
*
* @param theCol
* the colour to use
*/
@FireReformatted
public final void setTrackColor(final Color theCol)
{
setColor(theCol);
}
/**
* set the mode used to color the track
*
* @param trackColorMode
*/
public void setTrackColorMode(final TrackColorMode trackColorMode)
{
this._trackColorMode = trackColorMode;
}
/**
* font handler
*
* @param font
* the font to use for the label
*/
public final void setTrackFont(final Font font)
{
_theLabel.setFont(font);
}
@Override
public void shift(final WorldLocation feature, final WorldVector vector)
{
feature.addToMe(vector);
// right, one of our fixes has moved. get the sensors to update
// themselves
fixMoved();
}
@Override
public void shift(final WorldVector vector)
{
boolean handled = false;
boolean updateAlreadyFired = false;
// check it contains a range
if (vector.getRange() > 0d)
{
// ok, move any tracks
final Enumeration<Editable> enumA = elements();
while (enumA.hasMoreElements())
{
final Object thisO = enumA.nextElement();
if (thisO instanceof TrackSegment)
{
final TrackSegment seg = (TrackSegment) thisO;
seg.shift(vector);
}
else if (thisO instanceof SegmentList)
{
final SegmentList list = (SegmentList) thisO;
final Collection<Editable> items = list.getData();
for (final Iterator<Editable> iterator = items.iterator(); iterator
.hasNext();)
{
final TrackSegment segment = (TrackSegment) iterator.next();
segment.shift(vector);
}
}
}
handled = true;
// ok, get the legs to re-generate themselves
updateAlreadyFired = sortOutRelativePositions();
}
// now update the other children - some
// are sensitive to ownship track
this.updateDependents(elements(), vector);
// did we move any dependents
if (handled && !updateAlreadyFired)
{
firePropertyChange(PlainWrapper.LOCATION_CHANGED, null, this._theLabel
.getLocation());
}
}
/**
* if we've got a relative track segment, it only learns where its individual fixes are once
* they've been initialised. This is where we do it.
*/
public boolean sortOutRelativePositions()
{
boolean moved = false;
boolean updateFired = false;
FixWrapper lastFix = null;
final Enumeration<Editable> segments = _thePositions.elements();
while (segments.hasMoreElements())
{
final TrackSegment seg = (TrackSegment) segments.nextElement();
// SPECIAL HANDLING, SEE IF IT'S A TMA SEGMENT TO BE PLOTTED IN
// RELATIVE MODE
final boolean isRelative = seg.getPlotRelative();
WorldLocation tmaLastLoc = null;
long tmaLastDTG = 0;
final Enumeration<Editable> fixWrappers = seg.elements();
while (fixWrappers.hasMoreElements())
{
final FixWrapper fw = (FixWrapper) fixWrappers.nextElement();
// now there's a chance that our fix has forgotten it's parent,
// particularly if it's the victim of a
// copy/paste operation. Tell it about it's children
fw.setTrackWrapper(this);
// ok, are we in relative?
if (isRelative)
{
final long thisTime = fw.getDateTimeGroup().getDate().getTime();
// ok, is this our first location?
if (tmaLastLoc == null)
{
final WorldLocation trackStart = seg.getTrackStart();
if (trackStart != null)
{
tmaLastLoc = new WorldLocation(trackStart);
}
}
else
{
// calculate a new vector
final long timeDelta = thisTime - tmaLastDTG;
if (lastFix != null)
{
final double courseRads;
final double speedKts;
if (seg instanceof CoreTMASegment)
{
final CoreTMASegment tmaSeg = (CoreTMASegment) seg;
courseRads = Math.toRadians(tmaSeg.getCourse());
speedKts = tmaSeg.getSpeed().getValueIn(WorldSpeed.Kts);
}
else
{
courseRads = lastFix.getCourse();
speedKts = lastFix.getSpeed();
}
// check it has a location.
final double depthM;
if (fw.getLocation() != null)
{
depthM = fw.getDepth();
}
else
{
// no location - we may be extending a TMA segment
depthM = tmaLastLoc.getDepth();
}
// use the value of depth as read in from the file
tmaLastLoc.setDepth(depthM);
final WorldVector thisVec = seg.vectorFor(timeDelta, speedKts,
courseRads);
tmaLastLoc.addToMe(thisVec);
}
}
lastFix = fw;
tmaLastDTG = thisTime;
if (tmaLastLoc != null)
{
// have we found any movement yet?
if (!moved && fw.getLocation() != null && !fw.getLocation().equals(
tmaLastLoc))
{
moved = true;
}
// dump the location into the fix
fw.setFixLocationSilent(new WorldLocation(tmaLastLoc));
}
}
}
}
// did we do anything?
if (moved)
{
// get the child components to update,
// - including sending out a "moved" message
updateDependents(elements(), new WorldVector(0, 0, 0));
// also share the good news
firePropertyChange(PlainWrapper.LOCATION_CHANGED, null, System
.currentTimeMillis());
updateFired = true;
}
return updateFired;
}
/**
* split this whole track into two sub-tracks
*
* @param splitPoint
* the point at which we perform the split
* @param splitBeforePoint
* whether to put split before or after specified point
* @return a list of the new track segments (used for subsequent undo operations)
*/
public Vector<TrackSegment> splitTrack(final FixWrapper splitPoint,
final boolean splitBeforePoint)
{
FixWrapper splitPnt = splitPoint;
Vector<TrackSegment> res = null;
TrackSegment relevantSegment = null;
// are we still in one section?
if (_thePositions.size() == 1)
{
relevantSegment = (TrackSegment) _thePositions.first();
// yup, looks like we're going to be splitting it.
// better give it a proper name
relevantSegment.setName(relevantSegment.startDTG().getDate().toString());
}
else
{
// ok, find which segment contains our data
final Enumeration<Editable> segments = _thePositions.elements();
while (segments.hasMoreElements())
{
final TrackSegment seg = (TrackSegment) segments.nextElement();
if (seg.getData().contains(splitPnt))
{
relevantSegment = seg;
break;
}
}
}
if (relevantSegment == null)
{
throw new RuntimeException(
"failed to provide relevant segment, alg will break");
}
// hmm, if we're splitting after the point, we need to move along the
// bus by
// one
if (!splitBeforePoint)
{
final Collection<Editable> items = relevantSegment.getData();
final Iterator<Editable> theI = items.iterator();
Editable previous = null;
while (theI.hasNext())
{
final Editable thisE = theI.next();
// have we chosen to remember the previous item?
if (previous != null)
{
// yes, this must be the one we're after
splitPnt = (FixWrapper) thisE;
break;
}
// is this the one we're looking for?
if (thisE.equals(splitPnt))
{
// yup, remember it - we want to use the next value
previous = thisE;
}
}
}
// yup, do our first split
final SortedSet<Editable> p1 = relevantSegment.headSet(splitPnt);
final SortedSet<Editable> p2 = relevantSegment.tailSet(splitPnt);
// get our results ready
final TrackSegment ts1;
final TrackSegment ts2;
// aaah, just sort out if we are splitting a TMA segment, in which case
// want to create two
// tma segments, not track segments
if (relevantSegment instanceof RelativeTMASegment)
{
final RelativeTMASegment theTMA = (RelativeTMASegment) relevantSegment;
// find the ownship location at the relevant time
WorldLocation secondLegOrigin = null;
// get the time of the split
final HiResDate splitTime = splitPnt.getDateTimeGroup();
// aah, sort out if we are splitting before or after.
final SensorWrapper sensor = theTMA.getReferenceSensor();
if (sensor != null)
{
final Watchable[] nearestF = sensor.getNearestTo(splitTime);
if ((nearestF != null) && (nearestF.length > 0))
{
final SensorContactWrapper scw = (SensorContactWrapper) nearestF[0];
secondLegOrigin = scw.getCalculatedOrigin(null);
}
}
// if we couldn't get a sensor origin, try for the track origin
if (secondLegOrigin == null)
{
final Watchable firstMatch = theTMA.getReferenceTrack().getNearestTo(
splitTime)[0];
secondLegOrigin = firstMatch.getLocation();
}
final WorldVector secondOffset = splitPnt.getLocation().subtract(
secondLegOrigin);
// put the lists back into plottable layers
final RelativeTMASegment tr1 = new RelativeTMASegment(theTMA, p1, theTMA
.getOffset());
final RelativeTMASegment tr2 = new RelativeTMASegment(theTMA, p2,
secondOffset);
// and store them
ts1 = tr1;
ts2 = tr2;
}
else if (relevantSegment instanceof AbsoluteTMASegment)
{
final AbsoluteTMASegment theTMA = (AbsoluteTMASegment) relevantSegment;
// aah, sort out if we are splitting before or after.
// find out the offset at the split point, so we can initiate it for
// the
// second part of the track
final Watchable[] matches = this.getNearestTo(splitPnt
.getDateTimeGroup());
final WorldLocation origin = matches[0].getLocation();
final FixWrapper t1Start = (FixWrapper) p1.first();
// put the lists back into plottable layers
final AbsoluteTMASegment tr1 = new AbsoluteTMASegment(theTMA, p1, t1Start
.getLocation(), null, null);
final AbsoluteTMASegment tr2 = new AbsoluteTMASegment(theTMA, p2, origin,
null, null);
// and store them
ts1 = tr1;
ts2 = tr2;
}
else
{
// put the lists back into plottable layers
ts1 = new TrackSegment(p1);
ts2 = new TrackSegment(p2);
}
// ok. removing the host segment will delete any infills. So, be sure to re-attach them
reconnectInfills(relevantSegment, ts1, ts2);
// now clear the positions
removeElement(relevantSegment);
// and put back our new layers
add(ts1);
add(ts2);
// remember them
res = new Vector<TrackSegment>();
res.add(ts1);
res.add(ts2);
return res;
}
/**
* if a track segment is going to be split (and then deleted), re-attach any infills to one of the
* new segments
*
* @param toBeDeleted
* the segment that will be split
* @param newBefore
* the new first-half of the segment
* @param newAfter
* the new second-half of the segment
*/
private void reconnectInfills(TrackSegment toBeDeleted,
TrackSegment newBefore, TrackSegment newAfter)
{
// ok, loop through our legs
final Enumeration<Editable> lIter = getSegments().elements();
while (lIter.hasMoreElements())
{
final TrackSegment thisLeg = (TrackSegment) lIter.nextElement();
if (thisLeg instanceof DynamicInfillSegment)
{
final DynamicInfillSegment infill = (DynamicInfillSegment) thisLeg;
if (toBeDeleted.equals(infill.getBeforeSegment()))
{
// connect to new after
infill.configure(newAfter, infill.getAfterSegment());
}
else if (toBeDeleted.equals(infill.getAfterSegment()))
{
// connect to new before
infill.configure(infill.getBeforeSegment(), newBefore);
}
}
}
}
/**
* extra parameter, so that jvm can produce a sensible name for this
*
* @return the track name, as a string
*/
@Override
public final String toString()
{
return "Track:" + getName();
}
public void trimTo(final TimePeriod period)
{
if (_mySensors != null)
{
final Enumeration<Editable> iter = _mySensors.elements();
while (iter.hasMoreElements())
{
final SensorWrapper sw = (SensorWrapper) iter.nextElement();
sw.trimTo(period);
}
}
if (_myDynamicShapes != null)
{
final Enumeration<Editable> iter = _myDynamicShapes.elements();
while (iter.hasMoreElements())
{
final DynamicTrackShapeSetWrapper sw =
(DynamicTrackShapeSetWrapper) iter.nextElement();
sw.trimTo(period);
}
}
if (_mySolutions != null)
{
final Enumeration<Editable> iter = _mySolutions.elements();
while (iter.hasMoreElements())
{
final TMAWrapper sw = (TMAWrapper) iter.nextElement();
sw.trimTo(period);
}
}
if (_thePositions != null)
{
final Enumeration<Editable> segments = _thePositions.elements();
while (segments.hasMoreElements())
{
final TrackSegment seg = (TrackSegment) segments.nextElement();
seg.trimTo(period);
}
}
}
/**
* move the whole of the track be the provided offset
*/
private final boolean updateDependents(final Enumeration<Editable> theEnum,
final WorldVector offset)
{
// keep track of if the track contains something that doesn't get
// dragged
boolean handledData = false;
// work through the elements
while (theEnum.hasMoreElements())
{
final Object thisO = theEnum.nextElement();
if (thisO instanceof DynamicInfillSegment)
{
final DynamicInfillSegment dd = (DynamicInfillSegment) thisO;
dd.reconstruct();
// ok - job well done
handledData = true;
}
else if (thisO instanceof TrackSegment)
{
// special case = we handle this higher
// up the call chain, since tracks
// have to move before any dependent children
// ok - job well done
handledData = true;
}
else if (thisO instanceof SegmentList)
{
final SegmentList list = (SegmentList) thisO;
final Collection<Editable> items = list.getData();
final IteratorWrapper enumer = new Plottables.IteratorWrapper(items
.iterator());
handledData = updateDependents(enumer, offset);
}
else if (thisO instanceof SensorWrapper)
{
final SensorWrapper sw = (SensorWrapper) thisO;
final Enumeration<Editable> enumS = sw.elements();
while (enumS.hasMoreElements())
{
final SensorContactWrapper scw = (SensorContactWrapper) enumS
.nextElement();
// does this fix have it's own origin?
final WorldLocation sensorOrigin = scw.getOrigin();
if (sensorOrigin == null)
{
// ok - get it to recalculate it
scw.clearCalculatedOrigin();
@SuppressWarnings("unused")
final WorldLocation newO = scw.getCalculatedOrigin(this);
// we don't use the newO - we're just
// triggering an update
}
else
{
// create new object to contain the updated location
final WorldLocation newSensorLocation = new WorldLocation(
sensorOrigin);
newSensorLocation.addToMe(offset);
// so the contact did have an origin, change it
scw.setOrigin(newSensorLocation);
}
} // looping through the contacts
// ok - job well done
handledData = true;
} // whether this is a sensor wrapper
else if (thisO instanceof TMAWrapper)
{
final TMAWrapper sw = (TMAWrapper) thisO;
final Enumeration<Editable> enumS = sw.elements();
while (enumS.hasMoreElements())
{
final TMAContactWrapper scw = (TMAContactWrapper) enumS.nextElement();
// does this fix have it's own origin?
final WorldLocation sensorOrigin = scw.getOrigin();
if (sensorOrigin != null)
{
// create new object to contain the updated location
final WorldLocation newSensorLocation = new WorldLocation(
sensorOrigin);
newSensorLocation.addToMe(offset);
// so the contact did have an origin, change it
scw.setOrigin(newSensorLocation);
}
} // looping through the contacts
// ok - job well done
handledData = true;
} // whether this is a TMA wrapper
else if (thisO instanceof BaseLayer)
{
// ok, loop through it
final BaseLayer bl = (BaseLayer) thisO;
handledData = updateDependents(bl.elements(), offset);
}
} // looping through this track
// ok, did we handle the data?
if (!handledData)
{
System.err.println("TrackWrapper problem; not able to shift:" + theEnum);
}
return handledData;
}
/**
* is this track visible between these time periods?
*
* @param start
* start DTG
* @param end
* end DTG
* @return yes/no
*/
public final boolean visibleBetween(final HiResDate start,
final HiResDate end)
{
boolean visible = false;
if (getStartDTG().lessThan(end) && (getEndDTG().greaterThan(start)))
{
visible = true;
}
return visible;
}
} |
package openmods.reflection;
import java.lang.reflect.Method;
import com.google.common.base.Preconditions;
import com.google.common.base.Throwables;
public class MethodAccess {
public interface FunctionVar<R> {
public R call(Object target, Object... args);
}
private static class FunctionWrap<R> implements FunctionVar<R> {
private final Method method;
public FunctionWrap(Class<? extends R> returnCls, Method method) {
this.method = method;
Preconditions.checkArgument(returnCls.isAssignableFrom(method.getReturnType()), "Method '%s' has invalid return type", method);
}
@Override
@SuppressWarnings("unchecked")
public R call(Object target, Object... args) {
try {
return (R)method.invoke(target, args);
} catch (Throwable t) {
throw Throwables.propagate(t);
}
}
}
public interface Function0<R> {
public R call(Object target);
}
private static class Function0Impl<R> extends FunctionWrap<R> implements Function0<R> {
public Function0Impl(Class<? extends R> returnCls, Method method) {
super(returnCls, method);
}
@Override
public R call(Object target) {
return super.call(target);
}
}
public static <R> Function0<R> create(Class<? extends R> returnCls, Class<?> target, String... names) {
return new Function0Impl<R>(returnCls, ReflectionHelper.getMethod(target, names));
}
// R(P1)
public interface Function1<R, P1> {
public R call(Object target, P1 p1);
}
private static class Function1Impl<R, P1> extends FunctionWrap<R> implements Function1<R, P1> {
public Function1Impl(Class<? extends R> returnCls, Method method) {
super(returnCls, method);
}
@Override
public R call(Object target, P1 p1) {
return super.call(target, p1);
}
}
public static <R, P1> Function1<R, P1> create(Class<? extends R> returnCls, Class<?> target, Class<? extends P1> p1, String... names) {
return new Function1Impl<R, P1>(returnCls, ReflectionHelper.getMethod(target, names, p1));
}
// R(P1, P2)
public interface Function2<R, P1, P2> {
public R call(Object target, P1 p1, P2 p2);
}
private static class Function2Impl<R, P1, P2> extends FunctionWrap<R> implements Function2<R, P1, P2> {
public Function2Impl(Class<? extends R> returnCls, Method method) {
super(returnCls, method);
}
@Override
public R call(Object target, P1 p1, P2 p2) {
return super.call(target, p1, p2);
}
}
public static <R, P1, P2> Function2<R, P1, P2> create(Class<? extends R> returnCls, Class<?> target, Class<? extends P1> p1, Class<? extends P2> p2, String... names) {
return new Function2Impl<R, P1, P2>(returnCls, ReflectionHelper.getMethod(target, names, p1, p2));
}
// R(P1, P2, P3)
public interface Function3<R, P1, P2, P3> {
public R call(Object target, P1 p1, P2 p2, P3 p3);
}
private static class Function3Impl<R, P1, P2, P3> extends FunctionWrap<R> implements Function3<R, P1, P2, P3> {
public Function3Impl(Class<? extends R> returnCls, Method method) {
super(returnCls, method);
}
@Override
public R call(Object target, P1 p1, P2 p2, P3 p3) {
return super.call(target, p1, p2, p3);
}
}
public static <R, P1, P2, P3> Function3<R, P1, P2, P3> create(Class<? extends R> returnCls, Class<?> target, Class<? extends P1> p1, Class<? extends P2> p2, Class<? extends P3> p3, String... names) {
return new Function3Impl<R, P1, P2, P3>(returnCls, ReflectionHelper.getMethod(target, names, p1, p2, p3));
}
// R(P1, P2, P3, P4)
public interface Function4<R, P1, P2, P3, P4> {
public R call(Object target, P1 p1, P2 p2, P3 p3, P4 p4);
}
private static class Function4Impl<R, P1, P2, P3, P4> extends FunctionWrap<R> implements Function4<R, P1, P2, P3, P4> {
public Function4Impl(Class<? extends R> returnCls, Method method) {
super(returnCls, method);
}
@Override
public R call(Object target, P1 p1, P2 p2, P3 p3, P4 p4) {
return super.call(target, p1, p2, p3, p4);
}
}
public static <R, P1, P2, P3, P4> Function4<R, P1, P2, P3, P4> create(Class<? extends R> returnCls, Class<?> target, Class<? extends P1> p1, Class<? extends P2> p2, Class<? extends P3> p3, Class<? extends P4> p4, String... names) {
return new Function4Impl<R, P1, P2, P3, P4>(returnCls, ReflectionHelper.getMethod(target, names, p1, p2, p3, p4));
}
// R(P1, P2, P3, P4, P5)
public interface Function5<R, P1, P2, P3, P4, P5> {
public R call(Object target, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5);
}
private static class Function5Impl<R, P1, P2, P3, P4, P5> extends FunctionWrap<R> implements Function5<R, P1, P2, P3, P4, P5> {
public Function5Impl(Class<? extends R> returnCls, Method method) {
super(returnCls, method);
}
@Override
public R call(Object target, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5) {
return super.call(target, p1, p2, p3, p4, p5);
}
}
public static <R, P1, P2, P3, P4, P5> Function5<R, P1, P2, P3, P4, P5> create(Class<? extends R> returnCls, Class<?> target, Class<? extends P1> p1, Class<? extends P2> p2, Class<? extends P3> p3, Class<? extends P4> p4, Class<? extends P5> p5, String... names) {
return new Function5Impl<R, P1, P2, P3, P4, P5>(returnCls, ReflectionHelper.getMethod(target, names, p1, p2, p3, p4, p5));
}
} |
package org.basex.gui.layout;
import static org.basex.core.Text.*;
import static org.basex.gui.layout.BaseXKeys.*;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.Window;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentEvent;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseWheelEvent;
import java.util.Arrays;
import javax.swing.AbstractButton;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.border.MatteBorder;
import org.basex.gui.GUI;
import org.basex.gui.GUICommand;
import org.basex.gui.GUIConstants;
import org.basex.gui.GUIConstants.Fill;
import org.basex.io.IO;
import org.basex.util.TokenBuilder;
import org.basex.util.Undo;
import static org.basex.util.Token.*;
public class BaseXEditor extends BaseXPanel {
/** Text array to be written. */
protected transient BaseXTextTokens text = new BaseXTextTokens(EMPTY);
/** Renderer reference. */
protected final BaseXTextRenderer rend;
/** Scrollbar reference. */
private final BaseXBar scroll;
/** Undo history; if set to {@code null}, text will be read-only. */
protected final transient Undo undo;
/** Search field. */
private BaseXTextField find;
/**
* Default constructor.
* @param edit editable flag
* @param win parent window
*/
public BaseXEditor(final boolean edit, final Window win) {
super(win);
setFocusable(true);
setFocusTraversalKeysEnabled(!edit);
BaseXLayout.addInteraction(this, win);
addMouseMotionListener(this);
addMouseWheelListener(this);
addComponentListener(this);
addMouseListener(this);
addKeyListener(this);
addFocusListener(new FocusAdapter() {
@Override
public void focusGained(final FocusEvent e) {
if(isEnabled()) cursor(true);
}
@Override
public void focusLost(final FocusEvent e) {
cursor(false);
rend.cursor(false);
rend.repaint();
}
});
layout(new BorderLayout(4, 0));
scroll = new BaseXBar(this);
rend = new BaseXTextRenderer(text, scroll);
add(rend, BorderLayout.CENTER);
add(scroll, BorderLayout.EAST);
Undo un = null;
if(edit) {
setBackground(Color.white);
setBorder(new MatteBorder(1, 1, 0, 0, GUIConstants.color(6)));
un = new Undo();
} else {
mode(Fill.NONE);
}
undo = un;
new BaseXPopup(this, edit ?
new GUICommand[] { new UndoCmd(), new RedoCmd(), null, new CutCmd(),
new CopyCmd(), new PasteCmd(), new DelCmd(), null, new AllCmd() } :
new GUICommand[] { new CopyCmd(), null, new AllCmd() });
}
/**
* Sets the output text.
* @param t output text
*/
public void setText(final byte[] t) {
setText(t, t.length);
if(undo != null) undo.reset(t);
}
/**
* Adds a search dialog.
* @param f search field
*/
public final void setSearch(final BaseXTextField f) {
f.setSearch(this);
find = f;
}
/**
* Returns the cursor coordinates.
* @return line/column
*/
public final String pos() {
final int[] pos = rend.pos();
return pos[0] + " : " + pos[1];
}
/**
* Finds the specified term.
* @param t output text
* @param b backward browsing
*/
final void find(final String t, final boolean b) {
scroll(rend.find(t, b));
}
/**
* Displays the search term.
* @param y vertical position
*/
final void scroll(final int y) {
// updates the visible area
final int p = scroll.pos();
final int m = y + rend.fontH() * 3 - getHeight();
if(y != 0 && (p < m || p > y)) scroll.pos(y - getHeight() / 2);
repaint();
}
/**
* Sets the output text.
* @param t output text
* @param s text size
*/
public final void setText(final byte[] t, final int s) {
// remove invalid characters and compare old with new string
int ns = 0;
final int ts = text.size();
final byte[] tt = text.text;
boolean eq = true;
for(int r = 0; r < s; ++r) {
final byte b = t[r];
// support characters, highlighting codes, tabs and newlines
if(b >= ' ' || b <= TokenBuilder.MARK || b == 0x09 || b == 0x0A) {
t[ns++] = t[r];
}
eq &= ns < ts && ns < s && t[ns] == tt[ns];
}
eq &= ns == ts;
// new text is different...
if(!eq) {
text = new BaseXTextTokens(t, ns);
rend.setText(text);
scroll.pos(0);
}
if(undo != null) undo.store(t.length != ns ? Arrays.copyOf(t, ns) : t, 0);
SwingUtilities.invokeLater(calc);
}
/**
* Sets a syntax highlighter, based on the file format.
* @param file file reference
*/
public final void setSyntax(final IO file) {
// choose XML or XQuery highlighter
setSyntax(file.xml() ? new XMLSyntax() : new XQuerySyntax());
}
/**
* Sets a syntax highlighter.
* @param s syntax reference
*/
public final void setSyntax(final BaseXSyntax s) {
rend.setSyntax(s);
}
/**
* Sets a new cursor position.
* @param p cursor position
*/
public final void setCaret(final int p) {
text.setCaret(p);
showCursor(1);
cursor(true);
}
/**
* Jumps to the end of the text.
*/
public final void scrollToEnd() {
SwingUtilities.invokeLater(new Thread() {
@Override
public void run() {
text.pos(text.size());
text.setCaret();
showCursor(2);
}
});
}
/**
* Returns the output text.
* @return output text
*/
public final byte[] getText() {
return text.toArray();
}
@Override
public final void setFont(final Font f) {
super.setFont(f);
if(rend != null) {
rend.setFont(f);
rend.repaint();
}
}
/**
* Refreshes the syntax highlighting.
* @param s start of optional error mark
*/
public final void error(final int s) {
text.error(s);
rend.repaint();
}
@Override
public final void setEnabled(final boolean e) {
super.setEnabled(e);
rend.setEnabled(e);
scroll.setEnabled(e);
cursor(e);
}
/**
* Selects the whole text.
*/
final void selectAll() {
text.pos(0);
text.startMark();
text.pos(text.size());
text.endMark();
rend.repaint();
}
@Override
public final void mouseEntered(final MouseEvent e) {
gui.cursor(GUIConstants.CURSORTEXT);
}
@Override
public final void mouseExited(final MouseEvent e) {
gui.cursor(GUIConstants.CURSORARROW);
}
@Override
public void mouseReleased(final MouseEvent e) {
if(SwingUtilities.isLeftMouseButton(e)) rend.stopSelect();
}
@Override
public void mouseClicked(final MouseEvent e) {
if(!SwingUtilities.isMiddleMouseButton(e)) return;
if(!paste()) return;
finish();
repaint();
}
@Override
public final void mouseDragged(final MouseEvent e) {
if(!SwingUtilities.isLeftMouseButton(e)) return;
// selection mode
rend.select(scroll.pos(), e.getPoint(), true);
final int y = Math.max(20, Math.min(e.getY(), getHeight() - 20));
if(y != e.getY()) scroll.pos(scroll.pos() + e.getY() - y);
}
@Override
public final void mousePressed(final MouseEvent e) {
if(!isEnabled() || !isFocusable()) return;
requestFocusInWindow();
cursor(true);
if(SwingUtilities.isMiddleMouseButton(e)) copy();
if(SwingUtilities.isLeftMouseButton(e)) {
final int c = e.getClickCount();
if(c == 1) {
// selection mode
rend.select(scroll.pos(), e.getPoint(), false);
} else if(c == 2) {
selectWord();
} else {
selectLine();
}
} else if(!text.marked()) {
rend.select(scroll.pos(), e.getPoint(), false);
}
}
/**
* Selects the word at the cursor position.
*/
private void selectWord() {
text.pos(text.cursor());
final boolean ch = ftChar(text.prev(true));
while(text.pos() > 0) {
final int c = text.prev(true);
if(c == '\n' || ch != ftChar(c)) break;
}
if(text.pos() != 0) text.next(true);
text.startMark();
while(text.pos() < text.size()) {
final int c = text.curr();
if(c == '\n' || ch != ftChar(c)) break;
text.next(true);
}
text.endMark();
}
/**
* Selects the word at the cursor position.
*/
private void selectLine() {
text.pos(text.cursor());
text.bol(true);
text.startMark();
text.forward(Integer.MAX_VALUE, true);
text.endMark();
}
@Override
public void keyPressed(final KeyEvent e) {
if(modifier(e)) return;
// operations that change the focus are put first..
if(PREVTAB.is(e)) {
transferFocusBackward();
return;
}
if(NEXTTAB.is(e)) {
transferFocus();
return;
}
if(FIND.is(e)) {
if(find != null) find.requestFocusInWindow();
return;
}
// re-animate cursor
cursor(true);
// operations without cursor movement...
final int fh = rend.fontH();
if(SCROLLDOWN.is(e)) {
scroll.pos(scroll.pos() + fh);
return;
}
if(SCROLLUP.is(e)) {
scroll.pos(scroll.pos() - fh);
return;
}
if(COPY1.is(e) || COPY2.is(e)) {
copy();
return;
}
// set cursor position and reset last column
text.pos(text.cursor());
if(!PREVLINE.is(e) && !NEXTLINE.is(e)) lastCol = -1;
if(FINDNEXT.is(e) || FINDPREV.is(e) || FINDNEXT2.is(e) || FINDPREV2.is(e)) {
scroll(rend.find(FINDPREV.is(e) || FINDPREV2.is(e), true));
return;
}
if(SELECTALL.is(e)) {
selectAll();
text.setCaret();
return;
}
final boolean marking = e.isShiftDown() &&
!DELNEXT.is(e) && !DELPREV.is(e) && !PASTE2.is(e) && !COMMENT.is(e);
final boolean nomark = !text.marked();
if(marking && nomark) text.startMark();
boolean down = true;
boolean consumed = true;
// operations that consider the last text mark..
final byte[] txt = text.text;
if(NEXTWORD.is(e)) {
text.nextToken(marking);
} else if(PREVWORD.is(e)) {
text.prevToken(marking);
down = false;
} else if(TEXTSTART.is(e)) {
if(!marking) text.noMark();
text.pos(0);
down = false;
} else if(TEXTEND.is(e)) {
if(!marking) text.noMark();
text.pos(text.size());
} else if(LINESTART.is(e)) {
text.bol(marking);
down = false;
} else if(LINEEND.is(e)) {
text.forward(Integer.MAX_VALUE, marking);
} else if(NEXTPAGE.is(e)) {
down(getHeight() / fh, marking);
} else if(PREVPAGE.is(e)) {
up(getHeight() / fh, marking);
down = false;
} else if(NEXT.is(e)) {
text.next(marking);
} else if(PREV.is(e)) {
text.prev(marking);
down = false;
} else if(PREVLINE.is(e)) {
up(1, marking);
down = false;
} else if(NEXTLINE.is(e)) {
down(1, marking);
} else {
consumed = false;
}
if(marking) {
// refresh scroll position
text.endMark();
text.checkMark();
} else if(undo != null) {
// edit operations...
if(CUT1.is(e) || CUT2.is(e)) {
cut();
} else if(PASTE1.is(e) || PASTE2.is(e)) {
paste();
} else if(UNDO.is(e)) {
undo();
} else if(REDO.is(e)) {
redo();
} else if(COMMENT.is(e)) {
text.comment(rend.getSyntax());
} else if(DELLINEEND.is(e) || DELNEXTWORD.is(e) || DELNEXT.is(e)) {
if(nomark) {
if(text.pos() == text.size()) return;
text.startMark();
if(DELNEXTWORD.is(e)) {
text.nextToken(true);
} else if(DELLINEEND.is(e)) {
text.forward(Integer.MAX_VALUE, true);
} else {
text.next(true);
}
text.endMark();
}
undo.cursor(text.cursor());
text.delete();
} else if(DELLINESTART.is(e) || DELPREVWORD.is(e) || DELPREV.is(e)) {
if(nomark) {
if(text.pos() == 0) return;
text.startMark();
if(DELPREVWORD.is(e)) {
text.prevToken(true);
} else if(DELLINESTART.is(e)) {
text.bol(true);
} else {
text.prev();
}
text.endMark();
}
undo.cursor(text.cursor());
text.delete();
down = false;
} else {
consumed = false;
}
}
if(consumed) e.consume();
text.setCaret();
if(txt != text.text) rend.calc();
showCursor(down ? 2 : 0);
}
/**
* Displays the currently edited text area.
* @param align vertical alignment
*/
final void showCursor(final int align) {
// updates the visible area
final int p = scroll.pos();
final int y = rend.cursorY();
final int m = y + rend.fontH() * 3 - getHeight();
if(p < m || p > y) {
scroll.pos(align == 0 ? y : align == 1 ? y - getHeight() / 2 : m);
rend.repaint();
}
}
/**
* Moves the cursor down. The current column position is remembered in
* {@link #lastCol} and, if possible, restored.
* @param l number of lines to move cursor
* @param mark mark flag
*/
private void down(final int l, final boolean mark) {
if(!mark) text.noMark();
final int x = text.bol(mark);
if(lastCol == -1) lastCol = x;
for(int i = 0; i < l; ++i) {
text.forward(Integer.MAX_VALUE, mark);
text.next(mark);
}
text.forward(lastCol, mark);
if(text.pos() == text.size()) lastCol = -1;
}
/**
* Moves the cursor up.
* @param l number of lines to move cursor
* @param mark mark flag
*/
private void up(final int l, final boolean mark) {
if(!mark) text.noMark();
final int x = text.bol(mark);
if(lastCol == -1) lastCol = x;
if(text.pos() == 0) {
lastCol = -1;
return;
}
for(int i = 0; i < l; ++i) {
text.prev(mark);
text.bol(mark);
}
text.forward(lastCol, mark);
}
/** Last horizontal position. */
private int lastCol = -1;
@Override
public final void keyTyped(final KeyEvent e) {
if(undo == null || control(e) || DELNEXT.is(e) || DELPREV.is(e) ||
ESCAPE.is(e)) return;
text.pos(text.cursor());
boolean indent = false;
if(text.marked()) {
// count number of lines to indent
if(TAB.is(e)) {
final int s = Math.min(text.pos(), text.start());
final int l = Math.max(text.pos(), text.start()) - 1;
for(int p = s; p <= l && p < text.size(); p++) {
indent |= text.text[p] == '\n';
}
if(indent) text.indent(s, l, e.isShiftDown());
}
if(!indent) text.delete();
}
if(ENTER.is(e)) {
// adopt indentation from previous line
final StringBuilder sb = new StringBuilder().append(e.getKeyChar());
int s = 0, t = 0;
for(int p = text.pos() - 1; p >= 0; p
final byte b = text.text[p];
if(b == '\n') {
break;
} else if(b == '\t') {
t++;
} else if(b == ' ') {
s++;
} else {
t = 0;
s = 0;
}
}
for(int p = 0; p < t; p++) sb.append('\t');
for(int p = 0; p < s; p++) sb.append(' ');
text.add(sb.toString());
} else if(!indent) {
text.add(String.valueOf(e.getKeyChar()));
}
text.setCaret();
rend.calc();
showCursor(2);
e.consume();
}
@Override
public void keyReleased(final KeyEvent e) {
if(undo != null) undo.store(text.toArray(), text.cursor());
}
/**
* Releases a key or mouse. Can be overwritten to react on events.
* @param force force querying
*/
@SuppressWarnings("unused")
protected void release(final boolean force) { }
/**
* Undoes the text.
*/
protected final void undo() {
if(undo == null) return;
text = new BaseXTextTokens(undo.prev());
rend.setText(text);
text.pos(undo.cursor());
text.setCaret();
}
/**
* Redoes the text.
*/
protected final void redo() {
if(undo == null) return;
text = new BaseXTextTokens(undo.next());
rend.setText(text);
text.pos(undo.cursor());
text.setCaret();
}
/**
* Cuts the selected text to the clipboard.
*/
protected final void cut() {
text.pos(text.cursor());
if(copy()) delete();
}
/**
* Copies the selected text to the clipboard.
* @return true if text was copied
*/
protected final boolean copy() {
final String txt = text.copy();
if(txt.isEmpty()) {
text.noMark();
return false;
}
// copy selection to clipboard
final Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard();
clip.setContents(new StringSelection(txt), null);
return true;
}
/**
* Pastes the clipboard text.
* @return success flag
*/
protected final boolean paste() {
return paste(clip());
}
/**
* Pastes the specified string.
* @param txt string to be pasted
* @return success flag
*/
protected final boolean paste(final String txt) {
if(txt == null || undo == null) return false;
text.pos(text.cursor());
undo.cursor(text.cursor());
if(text.marked()) text.delete();
text.add(txt);
undo.store(text.toArray(), text.cursor());
return true;
}
/**
* Deletes the selected text.
*/
protected final void delete() {
if(undo == null) return;
text.pos(text.cursor());
undo.cursor(text.cursor());
text.delete();
undo.store(text.toArray(), text.cursor());
text.setCaret();
}
/**
* Returns the clipboard text.
* @return text
*/
final String clip() {
// copy selection to clipboard
final Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard();
final Transferable tr = clip.getContents(null);
if(tr != null) {
for(final Object o : BaseXLayout.contents(tr)) return o.toString();
}
return "";
}
/**
* Finishes a command.
*/
public void finish() {
text.setCaret();
rend.calc();
showCursor(2);
release(false);
}
/** Cursor. */
final Timer cursor = new Timer(500, new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
rend.cursor(!rend.cursor());
rend.repaint();
}
});
/**
* Handles the cursor thread; interrupts the old thread as soon as
* new one has been started.
* @param start start/stop flag
*/
protected final void cursor(final boolean start) {
cursor.stop();
if(start) cursor.start();
rend.cursor(start);
rend.repaint();
}
@Override
public final void mouseWheelMoved(final MouseWheelEvent e) {
scroll.pos(scroll.pos() + e.getUnitsToScroll() * 20);
rend.repaint();
}
@Override
public final void componentResized(final ComponentEvent e) {
scroll.pos(0);
SwingUtilities.invokeLater(calc);
}
/** Calculation counter. */
private final transient Thread calc = new Thread() {
@Override
public void run() {
rend.calc();
rend.repaint();
}
};
/** Text command. */
abstract class TextCmd implements GUICommand {
@Override
public boolean checked() {
return false;
}
@Override
public String help() {
return null;
}
@Override
public String key() {
return null;
}
}
/** Undo command. */
class UndoCmd extends TextCmd {
@Override
public void execute(final GUI main) {
undo();
finish();
}
@Override
public void refresh(final GUI main, final AbstractButton button) {
button.setEnabled(!undo.first());
}
@Override
public String label() {
return GUIUNDO;
}
}
/** Redo command. */
class RedoCmd extends TextCmd {
@Override
public void execute(final GUI main) {
redo();
finish();
}
@Override
public void refresh(final GUI main, final AbstractButton button) {
button.setEnabled(!undo.last());
}
@Override
public String label() {
return GUIREDO;
}
}
/** Cut command. */
class CutCmd extends TextCmd {
@Override
public void execute(final GUI main) {
cut();
finish();
}
@Override
public void refresh(final GUI main, final AbstractButton button) {
button.setEnabled(text.marked());
}
@Override
public String label() {
return GUICUT;
}
}
/** Copy command. */
class CopyCmd extends TextCmd {
@Override
public void execute(final GUI main) {
copy();
}
@Override
public void refresh(final GUI main, final AbstractButton button) {
button.setEnabled(text.marked());
}
@Override
public String label() {
return GUICOPY;
}
}
/** Paste command. */
class PasteCmd extends TextCmd {
@Override
public void execute(final GUI main) {
if(paste()) finish();
}
@Override
public void refresh(final GUI main, final AbstractButton button) {
button.setEnabled(clip() != null);
}
@Override
public String label() {
return GUIPASTE;
}
}
/** Delete command. */
class DelCmd extends TextCmd {
@Override
public void execute(final GUI main) {
delete();
finish();
}
@Override
public void refresh(final GUI main, final AbstractButton button) {
button.setEnabled(text.marked());
}
@Override
public String label() {
return GUIDELETE;
}
}
/** Select all command. */
class AllCmd extends TextCmd {
@Override
public void execute(final GUI main) {
selectAll();
}
@Override
public void refresh(final GUI main, final AbstractButton button) {
}
@Override
public String label() {
return GUIALL;
}
}
} |
package org.bouncycastle.asn1.x9;
import java.math.BigInteger;
import org.bouncycastle.asn1.ASN1EncodableVector;
import org.bouncycastle.asn1.ASN1Integer;
import org.bouncycastle.asn1.ASN1Object;
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.ASN1OctetString;
import org.bouncycastle.asn1.ASN1Primitive;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.DERBitString;
import org.bouncycastle.asn1.DERSequence;
import org.bouncycastle.math.ec.ECCurve;
/**
* ASN.1 def for Elliptic-Curve Curve structure. See
* X9.62, for further details.
*/
public class X9Curve
extends ASN1Object
implements X9ObjectIdentifiers
{
private ECCurve curve;
private byte[] seed;
private ASN1ObjectIdentifier fieldIdentifier = null;
public X9Curve(
ECCurve curve)
{
this.curve = curve;
this.seed = null;
setFieldIdentifier();
}
public X9Curve(
ECCurve curve,
byte[] seed)
{
this.curve = curve;
this.seed = seed;
setFieldIdentifier();
}
public X9Curve(
X9FieldID fieldID,
ASN1Sequence seq)
{
fieldIdentifier = fieldID.getIdentifier();
if (fieldIdentifier.equals(prime_field))
{
BigInteger p = ((ASN1Integer)fieldID.getParameters()).getValue();
X9FieldElement x9A = new X9FieldElement(p, (ASN1OctetString)seq.getObjectAt(0));
X9FieldElement x9B = new X9FieldElement(p, (ASN1OctetString)seq.getObjectAt(1));
curve = new ECCurve.Fp(p, x9A.getValue().toBigInteger(), x9B.getValue().toBigInteger());
}
else
{
if (fieldIdentifier.equals(characteristic_two_field))
{
// Characteristic two field
ASN1Sequence parameters = ASN1Sequence.getInstance(fieldID.getParameters());
int m = ((ASN1Integer)parameters.getObjectAt(0)).getValue().
intValue();
ASN1ObjectIdentifier representation
= (ASN1ObjectIdentifier)parameters.getObjectAt(1);
int k1 = 0;
int k2 = 0;
int k3 = 0;
if (representation.equals(tpBasis))
{
// Trinomial basis representation
k1 = ((ASN1Integer)parameters.getObjectAt(2)).getValue().
intValue();
}
else
{
// Pentanomial basis representation
ASN1Sequence pentanomial
= ASN1Sequence.getInstance(parameters.getObjectAt(2));
k1 = ((ASN1Integer)pentanomial.getObjectAt(0)).getValue().
intValue();
k2 = ((ASN1Integer)pentanomial.getObjectAt(1)).getValue().
intValue();
k3 = ((ASN1Integer)pentanomial.getObjectAt(2)).getValue().
intValue();
}
X9FieldElement x9A = new X9FieldElement(m, k1, k2, k3, (ASN1OctetString)seq.getObjectAt(0));
X9FieldElement x9B = new X9FieldElement(m, k1, k2, k3, (ASN1OctetString)seq.getObjectAt(1));
// TODO Is it possible to get the order (n) and cofactor(h) too?
curve = new ECCurve.F2m(m, k1, k2, k3, x9A.getValue().toBigInteger(), x9B.getValue().toBigInteger());
}
}
if (seq.size() == 3)
{
seed = ((DERBitString)seq.getObjectAt(2)).getBytes();
}
}
private void setFieldIdentifier()
{
if (curve instanceof ECCurve.Fp)
{
fieldIdentifier = prime_field;
}
else if (curve instanceof ECCurve.F2m)
{
fieldIdentifier = characteristic_two_field;
}
else
{
throw new IllegalArgumentException("This type of ECCurve is not "
+ "implemented");
}
}
public ECCurve getCurve()
{
return curve;
}
public byte[] getSeed()
{
return seed;
}
/**
* Produce an object suitable for an ASN1OutputStream.
* <pre>
* Curve ::= SEQUENCE {
* a FieldElement,
* b FieldElement,
* seed BIT STRING OPTIONAL
* }
* </pre>
*/
public ASN1Primitive toASN1Primitive()
{
ASN1EncodableVector v = new ASN1EncodableVector();
if (fieldIdentifier.equals(prime_field))
{
v.add(new X9FieldElement(curve.getA()).toASN1Primitive());
v.add(new X9FieldElement(curve.getB()).toASN1Primitive());
}
else if (fieldIdentifier.equals(characteristic_two_field))
{
v.add(new X9FieldElement(curve.getA()).toASN1Primitive());
v.add(new X9FieldElement(curve.getB()).toASN1Primitive());
}
if (seed != null)
{
v.add(new DERBitString(seed));
}
return new DERSequence(v);
}
} |
package org.broad.igv.track;
import htsjdk.tribble.Feature;
import htsjdk.tribble.TribbleException;
import org.broad.igv.logging.*;
import org.broad.igv.Globals;
import org.broad.igv.event.DataLoadedEvent;
import org.broad.igv.event.IGVEventBus;
import org.broad.igv.event.IGVEventObserver;
import org.broad.igv.feature.*;
import org.broad.igv.feature.Range;
import org.broad.igv.feature.genome.Genome;
import org.broad.igv.feature.genome.GenomeManager;
import org.broad.igv.prefs.Constants;
import org.broad.igv.prefs.PreferencesManager;
import org.broad.igv.renderer.*;
import org.broad.igv.tools.motiffinder.MotifFinderSource;
import org.broad.igv.ui.IGV;
import org.broad.igv.ui.UIConstants;
import org.broad.igv.ui.panel.ReferenceFrame;
import org.broad.igv.ui.util.MessageUtils;
import org.broad.igv.util.BrowserLauncher;
import org.broad.igv.util.ResourceLocator;
import org.broad.igv.util.StringUtils;
import org.broad.igv.variant.VariantTrack;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;
/**
* Track which displays features, typically showing regions of the genome
* in a qualitative way. Features are rendered using the specified FeatureRenderer.
* The gene track is an example of a feature track.
*
* @author jrobinso
*/
public class FeatureTrack extends AbstractTrack implements IGVEventObserver {
private static Logger log = LogManager.getLogger(FeatureTrack.class);
public static final int MINIMUM_FEATURE_SPACING = 5;
public static final int DEFAULT_MARGIN = 5;
public static final int NO_FEATURE_ROW_SELECTED = -1;
protected static final Color SELECTED_FEATURE_ROW_COLOR = new Color(100, 100, 100, 30);
private static final int DEFAULT_EXPANDED_HEIGHT = 35;
private static final int DEFAULT_SQUISHED_HEIGHT = 12;
private int expandedRowHeight = DEFAULT_EXPANDED_HEIGHT;
private int squishedRowHeight = DEFAULT_SQUISHED_HEIGHT;
boolean fatalLoadError = false;
Track.DisplayMode lastFeatureMode = null; // Keeps track of the feature display mode before an auto-switch to COLLAPSE
// TODO -- this is a memory leak, this cache needs cleared when the reference frame collection (gene list) changes
/**
* Map of reference frame name -> packed features
*/
protected Map<String, PackedFeatures<Feature>> packedFeaturesMap = Collections.synchronizedMap(new HashMap<>());
protected Renderer renderer;
private DataRenderer coverageRenderer;
// true == features, false = coverage
private boolean showFeatures = true;
public FeatureSource source;
//track which row of the expanded track is selected by the user. Selection goes away if tracks are collpased
protected int selectedFeatureRowIndex = NO_FEATURE_ROW_SELECTED;
//Feature selected by the user. This is repopulated on each handleDataClick() call.
protected IGVFeature selectedFeature = null;
int margin = DEFAULT_MARGIN;
private static boolean drawBorder = true;
private boolean alternateExonColor = false;
private String trackLine = null;
private boolean groupByStrand = false;
private String labelField;
public FeatureTrack() {
}
// TODO -- there are WAY too many constructors for this class
/**
* Constructor used by SpliceJunctionTrack, BlatTrack, and MotifTrack
*
* @param locator -- For splice junctions, ResourceLocator for associated alignment track. Null otherwise
* @param id
* @param name
*/
public FeatureTrack(ResourceLocator locator, String id, String name) {
super(locator, id, name);
setSortable(false);
}
/**
* Constructor with no ResourceLocator. Note: tracks using this constructor will not be recorded in the
* "Resources" section of session files. This method is used by ".genome" and gbk genome loaders.
*/
public FeatureTrack(String id, String name, FeatureSource source) {
super(null, id, name);
init(null, source);
setSortable(false);
}
/**
* Constructor specifically for BigWig data source
*
* @param locator
* @param id
* @param name
* @param source
*/
public FeatureTrack(ResourceLocator locator, String id, String name, FeatureSource source) {
super(locator, id, name);
init(locator, source);
setSortable(false);
}
public FeatureTrack(ResourceLocator locator, FeatureSource source) {
super(locator);
init(locator, source);
setSortable(false);
}
/**
* SMap files (bionano), MutationTrack
*/
public FeatureTrack(ResourceLocator locator, String id, FeatureSource source) {
super(locator, id, locator.getTrackName());
init(locator, source);
}
/**
* Create a new track which is a shallow copy of this one. Currently used by SashimiPlot.
*/
public FeatureTrack(FeatureTrack featureTrack) {
this(featureTrack.getId(), featureTrack.getName(), featureTrack.source);
}
protected void init(ResourceLocator locator, FeatureSource source) {
this.source = source;
setMinimumHeight(10);
coverageRenderer = new BarChartRenderer();
Integer vizWindow = locator == null ? null : locator.getVisibilityWindow();
if (vizWindow != null) {
visibilityWindow = vizWindow;
} else {
int sourceFeatureWindowSize = source.getFeatureWindowSize();
int defVisibilityWindow = PreferencesManager.getPreferences().getAsInt(Constants.DEFAULT_VISIBILITY_WINDOW);
if (sourceFeatureWindowSize > 0 && defVisibilityWindow > 0) { // Only apply a default if the feature source supports visibility window.
visibilityWindow = defVisibilityWindow * 1000;
} else {
visibilityWindow = sourceFeatureWindowSize;
}
}
this.renderer = locator != null && locator.getPath().endsWith("junctions.bed") ?
new SpliceJunctionRenderer() : new IGVFeatureRenderer();
IGVEventBus.getInstance().subscribe(DataLoadedEvent.class, this);
}
@Override
public void unload() {
super.unload();
if (source != null) {
source.close();
}
}
/**
* Called after features are finished loading, which can be asynchronous
*/
public void receiveEvent(Object e) {
if (e instanceof DataLoadedEvent) {
// DataLoadedEvent event = (DataLoadedEvent) e;
// if (IGV.hasInstance()) {
// // TODO -- WHY IS THIS HERE????
// //TODO Assuming this is necessary, there can be many data loaded events in succession,
// //don't want to layout for each one
// IGV.getInstance().layoutMainPanel();
} else {
log.warn("Unknown event type: " + e.getClass());
}
}
@Override
public int getHeight() {
if (!isVisible()) {
return 0;
}
int rowHeight = getDisplayMode() == DisplayMode.SQUISHED ? squishedRowHeight : expandedRowHeight;
int minHeight = margin + rowHeight * Math.max(1, getNumberOfFeatureLevels());
return Math.max(minHeight, super.getHeight());
}
public int getExpandedRowHeight() {
return expandedRowHeight;
}
public void setExpandedRowHeight(int expandedRowHeight) {
this.expandedRowHeight = expandedRowHeight;
}
public int getSquishedRowHeight() {
return squishedRowHeight;
}
public void setSquishedRowHeight(int squishedRowHeight) {
this.squishedRowHeight = squishedRowHeight;
}
public void setRendererClass(Class rc) {
try {
renderer = (Renderer) rc.getDeclaredConstructor().newInstance();
} catch (Exception ex) {
log.error("Error instatiating renderer ", ex);
}
}
public void setMargin(int margin) {
this.margin = margin;
}
@Override
public void setProperties(TrackProperties trackProperties) {
super.setProperties(trackProperties);
if (trackProperties.getFeatureVisibilityWindow() >= 0) {
setVisibilityWindow(trackProperties.getFeatureVisibilityWindow());
}
alternateExonColor = trackProperties.isAlternateExonColor();
}
public void setWindowFunction(WindowFunction type) {
// Ignored for feature tracks
}
/**
* Return the maximum number of features for any panel in this track. In whole genome view there is a single panel,
* but there are multiple in gene list view (one for each gene list).
*
* @return
*/
public int getNumberOfFeatureLevels() {
if (packedFeaturesMap.size() > 0) {
int n = 1;
for (PackedFeatures pf : packedFeaturesMap.values()) {
//dhmay adding null check. To my mind this shouldn't be necessary, but we're encountering
//it intermittently. Food for future thought
if (pf != null) {
n = Math.max(n, pf.getRowCount());
}
}
return n;
}
return 1;
}
/**
* Return a score over the interval. This is required by the track interface to support sorting.
*/
public float getRegionScore(String chr, int start, int end, int zoom, RegionScoreType scoreType, String frameName) {
try {
Iterator<Feature> features = source.getFeatures(chr, start, end);
if (features != null) {
if (scoreType == RegionScoreType.MUTATION_COUNT && this.getTrackType() == TrackType.MUTATION) {
int count = 0;
while (features.hasNext()) {
Feature f = features.next();
if (f.getStart() > end) {
break;
}
if (f.getEnd() >= start) {
count++;
}
}
return count;
} else if (scoreType == RegionScoreType.SCORE) {
// Average score of features in region. Note: Should the score be weighted by genomic size?
float regionScore = 0;
int nValues = 0;
while (features.hasNext()) {
Feature f = features.next();
if (f instanceof IGVFeature) {
if ((f.getEnd() >= start) && (f.getStart() <= end)) {
float value = ((IGVFeature) f).getScore();
regionScore += value;
nValues++;
}
}
}
if (nValues == 0) {
// No scores in interval
return -Float.MAX_VALUE;
} else {
return regionScore / nValues;
}
}
}
} catch (IOException e) {
log.error("Error counting features.", e);
}
return -Float.MAX_VALUE;
}
public Renderer getRenderer() {
if (renderer == null) {
setRendererClass(IGVFeatureRenderer.class);
}
return renderer;
}
/**
* Return a string for popup text.
*
* @param chr
* @param position in genomic coordinates
* @param mouseX
* @return
*/
public String getValueStringAt(String chr, double position, int mouseX, int mouseY, ReferenceFrame frame) {
if (showFeatures) {
List<Feature> allFeatures = getAllFeatureAt(position, mouseY, frame);
if (allFeatures == null) {
return null;
}
StringBuffer buf = new StringBuffer();
boolean firstFeature = true;
int maxNumber = 100;
int n = 1;
for (Feature feature : allFeatures) {
if (feature != null && feature instanceof IGVFeature) {
if (!firstFeature) {
buf.append("<hr><br>");
}
IGVFeature igvFeature = (IGVFeature) feature;
String vs = igvFeature.getValueString(position, mouseX, null);
buf.append(vs);
if (IGV.getInstance().isShowDetailsOnClick()) {
String url = getFeatureURL(igvFeature);
if (url != null) {
buf.append("<br/><a href=\"" + url + "\">" + url + "</a>");
}
}
firstFeature = false;
if (n > maxNumber) {
buf.append("...");
break;
}
}
n++;
}
return buf.toString();
} else {
int zoom = Math.max(0, frame.getZoom());
if (source == null) {
return null;
}
List<LocusScore> scores = source.getCoverageScores(chr, (int) position - 10, (int) position + 10, zoom);
if (scores == null) {
return "";
} else {
// give a +/- 2 pixel buffer, otherwise very narrow features will be missed.
double bpPerPixel = frame.getScale();
int minWidth = (int) (2 * bpPerPixel);
LocusScore score = (LocusScore) FeatureUtils.getFeatureAt(position, minWidth, scores);
return score == null ? null : "Mean count: " + score.getScore();
}
}
}
/**
* Return an info URL for a specific feature, constructed as follows
*
* @param igvFeature
* @return
*/
private String getFeatureURL(IGVFeature igvFeature) {
String url = igvFeature.getURL(); // Explicity URL setting
if (url == null) {
String trackURL = getFeatureInfoURL(); // Template
if (trackURL != null) {
String idOrName = igvFeature.getIdentifier() != null ?
igvFeature.getIdentifier() :
labelField != null ?
igvFeature.getDisplayName(labelField) :
igvFeature.getName();
url = trackURL.replaceAll("\\$\\$", StringUtils.encodeURL(idOrName));
}
}
return url;
}
@Override
public String getLabelField() {
return labelField;
}
public void setLabelField(String labelField) {
this.labelField = labelField;
}
/**
* Get all features which overlap the specified locus
*
* @return
*/
public List<Feature> getFeatures(String chr, int start, int end) {
List<Feature> features = new ArrayList<Feature>();
try {
Iterator<Feature> iter = source.getFeatures(chr, start, end);
while (iter.hasNext()) {
Feature f = iter.next();
if (f.getEnd() >= start && f.getStart() <= end) {
features.add(f);
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
return features;
}
/**
* @param position in genomic coordinates
* @param y pixel location in panel coordinates. // TODO offset by track origin before getting here?
* @param frame
* @return
*/
protected List<Feature> getAllFeatureAt(double position, int y, ReferenceFrame frame) {
// Determine the level number (for expanded tracks)
int featureRow = getFeatureRow(y);
return getFeaturesAtPositionInFeatureRow(position, featureRow, frame);
}
/**
* Determine which row the user clicked in and return the appropriate feature
*
* @param y
* @return
*/
private int getFeatureRow(int y) {
int rowHeight;
DisplayMode mode = getDisplayMode();
switch (mode) {
case SQUISHED:
rowHeight = getSquishedRowHeight();
break;
case EXPANDED:
rowHeight = getExpandedRowHeight();
break;
default:
rowHeight = getHeight();
}
return Math.max(0, (y - this.getY() - this.margin) / rowHeight);
}
/**
* Knowing the feature row, figure out which feature is at {@code position}.
*
* @param position
* @param featureRow
* @param frame
* @return
*/
public List<Feature> getFeaturesAtPositionInFeatureRow(double position, int featureRow, ReferenceFrame frame) {
PackedFeatures<Feature> packedFeatures = packedFeaturesMap.get(frame.getName());
if (packedFeatures == null) {
return null;
}
List<PackedFeatures<Feature>.FeatureRow> rows = packedFeatures.getRows();
if (featureRow < 0 || featureRow >= rows.size()) {
return null;
}
//If features are stacked we look at only the row.
//If they are collapsed on top of each other, we get all features in all rows
List<Feature> possFeatures;
if (getDisplayMode() == DisplayMode.COLLAPSED) {
possFeatures = packedFeatures.getFeatures();
} else {
possFeatures = rows.get(featureRow).getFeatures();
}
List<Feature> featureList = null;
if (possFeatures != null) {
// give a minum 2 pixel or 1/2 bp window, otherwise very narrow features will be missed.
double bpPerPixel = frame.getScale();
double minWidth = Math.max(0.5, MINIMUM_FEATURE_SPACING * bpPerPixel);
int maxFeatureLength = packedFeatures.getMaxFeatureLength();
featureList = FeatureUtils.getAllFeaturesAt(position, maxFeatureLength, minWidth, possFeatures);
}
return featureList;
}
public WindowFunction getWindowFunction() {
return WindowFunction.count;
}
@Override
public boolean handleDataClick(TrackClickEvent te) {
MouseEvent e = te.getMouseEvent();
// Toggle selection of row
if (getDisplayMode() != DisplayMode.COLLAPSED) {
int i = getFeatureRow(e.getY());
if (i == selectedFeatureRowIndex)
setSelectedFeatureRowIndex(FeatureTrack.NO_FEATURE_ROW_SELECTED);
else {
//make this track selected
setSelected(true);
//select the appropriate row
setSelectedFeatureRowIndex(i);
}
}
//For feature selection
selectedFeature = null;
Feature f = getFeatureAtMousePosition(te);
if (f != null && f instanceof IGVFeature) {
IGVFeature igvFeature = (IGVFeature) f;
if (selectedFeature != null && igvFeature.contains(selectedFeature) && (selectedFeature.contains(igvFeature))) {
//If something already selected, then if it's the same as this feature, deselect, otherwise, select
//this feature.
//todo: contains() might not do everything I want it to.
selectedFeature = null;
} else {
//if nothing already selected, or something else selected,
// select this feature
selectedFeature = igvFeature;
}
if (IGV.getInstance().isShowDetailsOnClick()) {
openTooltipWindow(te);
} else {
String url = getFeatureURL(igvFeature);
if (url != null) {
try {
BrowserLauncher.openURL(url);
} catch (IOException e1) {
log.error("Error launching url: " + url);
}
e.consume();
return true;
}
}
}
return false;
}
public Feature getFeatureAtMousePosition(TrackClickEvent te) {
MouseEvent e = te.getMouseEvent();
final ReferenceFrame referenceFrame = te.getFrame();
if (referenceFrame != null) {
double location = referenceFrame.getChromosomePosition(e);
List<Feature> features = getAllFeatureAt(location, e.getY(), referenceFrame);
return (features != null && features.size() > 0) ? features.get(0) : null;
} else {
return null;
}
}
/**
* Required by the interface, really not applicable to feature tracks
*/
public boolean isLogNormalized() {
return true;
}
public void overlay(RenderContext context, Rectangle rect) {
renderFeatures(context, rect);
}
@Override
public void setDisplayMode(DisplayMode mode) {
// Explicity setting the display mode overrides the automatic switch
lastFeatureMode = null;
for (PackedFeatures pf : packedFeaturesMap.values()) {
pf.pack(mode, groupByStrand);
}
super.setDisplayMode(mode);
}
@Override
public boolean isReadyToPaint(ReferenceFrame frame) {
if (!isShowFeatures(frame)) {
packedFeaturesMap.clear();
return true; // Ready by definition (nothing to paint)
} else {
PackedFeatures packedFeatures = packedFeaturesMap.get(frame.getName());
String chr = frame.getChrName();
int start = (int) frame.getOrigin();
int end = (int) frame.getEnd();
return (packedFeatures != null && packedFeatures.containsInterval(chr, start, end));
}
}
public void load(ReferenceFrame frame) {
loadFeatures(frame.getChrName(), (int) frame.getOrigin(), (int) frame.getEnd(), frame.getName());
}
/**
* Loads and segregates features into rows such that they do not overlap.
*
* @param chr
* @param start
* @param end
*/
protected void loadFeatures(final String chr, final int start, final int end, final String frame) {
if (source == null) {
return;
}
try {
int expandedStart;
int expandedEnd;
int vw = getVisibilityWindow();
if (vw > 0) {
int delta = (end - start) / 2;
expandedStart = start - delta;
expandedEnd = end + delta;
if (expandedEnd < 0) {
expandedEnd = Integer.MAX_VALUE; // overflow
}
} else {
expandedStart = 0;
expandedEnd = Integer.MAX_VALUE;
}
//Make sure we are only querying within the chromosome we allow for somewhat pathological cases of start
//being negative and end being outside, but only if directly queried. Our expansion should not
//set start < 0 or end > chromosomeLength
if (start >= 0) {
expandedStart = Math.max(0, expandedStart);
}
Genome genome = GenomeManager.getInstance().getCurrentGenome();
if (genome != null) {
Chromosome c = genome.getChromosome(chr);
if (c != null && end < c.getLength()) expandedEnd = Math.min(c.getLength(), expandedEnd);
}
Iterator<Feature> iter = source.getFeatures(chr, expandedStart, expandedEnd);
if (iter == null) {
PackedFeatures pf = new PackedFeatures(chr, expandedStart, expandedEnd);
packedFeaturesMap.put(frame, pf);
} else {
PackedFeatures pf = new PackedFeatures(chr, expandedStart, expandedEnd, iter, this.getDisplayMode(), groupByStrand);
packedFeaturesMap.put(frame, pf);
//log.warn("Loaded " + chr + " " + expandedStart + "-" + expandedEnd);
}
} catch (Exception e) {
// Mark the interval with an empty feature list to prevent an endless loop of load attempts.
PackedFeatures pf = new PackedFeatures(chr, start, end);
packedFeaturesMap.put(frame, pf);
String msg = "Error loading features for interval: " + chr + ":" + start + "-" + end + " <br>" + e.toString();
MessageUtils.showMessage(msg);
log.error(msg, e);
}
}
@Override
public void render(RenderContext context, Rectangle rect) {
Rectangle renderRect = new Rectangle(rect);
renderRect.y = renderRect.y + margin;
renderRect.height -= margin;
showFeatures = isShowFeatures(context.getReferenceFrame());
if (showFeatures) {
if (lastFeatureMode != null) {
super.setDisplayMode(lastFeatureMode);
lastFeatureMode = null;
}
renderFeatures(context, renderRect);
} else if (coverageRenderer != null) {
if (getDisplayMode() != DisplayMode.COLLAPSED) {
// An ugly hack, but we want to prevent this for vcf tracks
if (!(this instanceof VariantTrack)) {
lastFeatureMode = getDisplayMode();
super.setDisplayMode(DisplayMode.COLLAPSED);
}
}
renderCoverage(context, renderRect);
}
if (FeatureTrack.drawBorder) {
Graphics2D borderGraphics = context.getGraphic2DForColor(UIConstants.TRACK_BORDER_GRAY);
borderGraphics.drawLine(rect.x, rect.y, rect.x + rect.width, rect.y);
//TODO Fix height for variant track
borderGraphics.drawLine(rect.x, rect.y + rect.height, rect.x + rect.width, rect.y + rect.height);
}
}
protected boolean isShowFeatures(ReferenceFrame frame) {
if (frame.getChrName().equals(Globals.CHR_ALL)) {
return false;
} else {
double windowSize = frame.getEnd() - frame.getOrigin();
int vw = getVisibilityWindow();
return (vw <= 0 || windowSize <= vw);
}
}
protected void renderCoverage(RenderContext context, Rectangle inputRect) {
final String chr = context.getChr();
List<LocusScore> scores = (source != null && chr.equals(Globals.CHR_ALL)) ?
source.getCoverageScores(chr, (int) context.getOrigin(),
(int) context.getEndLocation(), context.getZoom()) :
null;
if (scores == null) {
Graphics2D g = context.getGraphic2DForColor(Color.gray);
Rectangle textRect = new Rectangle(inputRect);
// Keep text near the top of the track rectangle
textRect.height = Math.min(inputRect.height, 20);
String message = getZoomInMessage(chr);
GraphicUtils.drawCenteredText(message, textRect, g);
} else {
float max = getMaxEstimate(scores);
ContinuousColorScale cs = getColorScale();
if (cs != null) {
cs.setPosEnd(max);
}
if (this.dataRange == null) {
setDataRange(new DataRange(0, 0, max));
} else {
this.dataRange.maximum = max;
}
coverageRenderer.render(scores, context, inputRect, this);
}
}
protected String getZoomInMessage(String chr) {
return chr.equals(Globals.CHR_ALL) ? "Zoom in to see features." :
"Zoom in to see features, or right-click to increase Feature Visibility Window.";
}
private float getMaxEstimate(List<LocusScore> scores) {
float max = 0;
int n = Math.min(200, scores.size());
for (int i = 0; i < n; i++) {
max = Math.max(max, scores.get(i).getScore());
}
return max;
}
/**
* Render features in the given input rectangle.
*
* @param context
* @param inputRect
*/
protected void renderFeatures(RenderContext context, Rectangle inputRect) {
if (log.isTraceEnabled()) {
String msg = String.format("renderFeatures: %s frame: %s", getName(), context.getReferenceFrame().getName());
log.trace(msg);
}
PackedFeatures packedFeatures = packedFeaturesMap.get(context.getReferenceFrame().getName());
if (packedFeatures == null || !packedFeatures.overlapsInterval(context.getChr(), (int) context.getOrigin(), (int) context.getEndLocation() + 1)) {
return;
}
try {
renderFeatureImpl(context, inputRect, packedFeatures);
} catch (TribbleException e) {
log.error("Tribble error", e);
//Error loading features. We'll let the user decide if this is "fatal" or not.
if (!fatalLoadError) {
fatalLoadError = true;
boolean unload = MessageUtils.confirm("<html> Error loading features: " + e.getMessage() +
"<br>Unload track " + getName() + "?");
if (unload) {
Collection<Track> tmp = Arrays.asList((Track) this);
IGV.getInstance().deleteTracks(tmp);
IGV.getInstance().repaint();
} else {
fatalLoadError = false;
}
}
}
}
protected void renderFeatureImpl(RenderContext context, Rectangle inputRect, PackedFeatures packedFeatures) {
Renderer renderer = getRenderer();
if (getDisplayMode() == DisplayMode.COLLAPSED && !isGroupByStrand()) {
List<Feature> features = packedFeatures.getFeatures();
if (features != null) {
renderer.render(features, context, inputRect, this);
}
} else {
List<PackedFeatures.FeatureRow> rows = packedFeatures.getRows();
if (rows != null && rows.size() > 0) {
// Divide rectangle into equal height levels
double h = getDisplayMode() == DisplayMode.SQUISHED ? squishedRowHeight : expandedRowHeight;
Rectangle rect = new Rectangle(inputRect.x, inputRect.y, inputRect.width, (int) h);
int i = 0;
if (renderer instanceof FeatureRenderer) ((FeatureRenderer) renderer).reset();
for (PackedFeatures.FeatureRow row : rows) {
renderer.render(row.features, context, new Rectangle(rect), this);
if (selectedFeatureRowIndex == i) {
Graphics2D fontGraphics = context.getGraphic2DForColor(SELECTED_FEATURE_ROW_COLOR);
fontGraphics.fillRect(rect.x, rect.y, rect.width, rect.height);
}
rect.y += h;
i++;
}
}
}
}
/**
* Return the nextLine or previous feature relative to the center location.
* TODO -- investigate delegating this method to FeatureSource, where it might be possible to simplify the implementation
*
* @param chr
* @param center
* @param forward
* @return
* @throws IOException
*/
public Feature nextFeature(String chr, double center, boolean forward, ReferenceFrame frame) throws IOException {
Feature f = null;
boolean canScroll = (forward && !frame.windowAtEnd()) || (!forward && frame.getOrigin() > 0);
PackedFeatures packedFeatures = packedFeaturesMap.get(frame.getName());
// Compute a buffer to define "next"
double buffer = Math.max(1, frame.getScale());
if (packedFeatures != null && packedFeatures.containsInterval(chr, (int) center - 1, (int) center + 1)) {
if (packedFeatures.getFeatures().size() > 0 && canScroll) {
List<Feature> centerSortedFeatures = packedFeatures.getCenterSortedFeatures();
f = (forward ?
FeatureUtils.getFeatureCenteredAfter(center + buffer, centerSortedFeatures) :
FeatureUtils.getFeatureCenteredBefore(center - buffer, centerSortedFeatures));
}
}
if (f == null) {
int searchBuferSize = (int) (frame.getScale() * 1000);
f = FeatureTrackUtils.nextFeature(source, chr, packedFeatures.getStart(), packedFeatures.getEnd(), center, searchBuferSize, forward);
}
return f;
}
public void setVisibilityWindow(int windowSize) {
super.setVisibilityWindow(windowSize);
packedFeaturesMap.clear();
}
public int getSelectedFeatureRowIndex() {
return selectedFeatureRowIndex;
}
public void setSelectedFeatureRowIndex(int selectedFeatureRowIndex) {
this.selectedFeatureRowIndex = selectedFeatureRowIndex;
}
public IGVFeature getSelectedFeature() {
return selectedFeature;
}
public static boolean isDrawBorder() {
return drawBorder;
}
public static void setDrawBorder(boolean drawBorder) {
FeatureTrack.drawBorder = drawBorder;
}
public boolean isAlternateExonColor() {
return alternateExonColor;
}
/**
* This method exists for Plugin tracks. When restoring a session there is no guarantee of track
* order, so arguments referring to other tracks may fail to resolve. We update those references
* here after all tracks have been processed
*
* @param allTracks
*/
public void updateTrackReferences(List<Track> allTracks) {
}
/**
* Features are packed upon loading, effectively a cache.
* This clears that cache. Used to force a refresh
*
* @api
*/
public void clearPackedFeatures() {
this.packedFeaturesMap.clear();
}
/**
* Return currently loaded features. Used to export features to a file.
*
* @param frame
* @return
*/
public List<Feature> getVisibleFeatures(ReferenceFrame frame) {
PackedFeatures<Feature> packedFeatures = packedFeaturesMap.get(frame.getName());
if (packedFeatures == null) {
return Collections.emptyList();
} else {
Range currentRange = frame.getCurrentRange();
return packedFeatures.getFeatures()
.stream().filter(igvFeature ->
igvFeature.getEnd() >= currentRange.getStart() &&
igvFeature.getStart() <= currentRange.getEnd() &&
igvFeature.getChr().equals(currentRange.getChr()))
.collect(Collectors.toList());
}
}
public void setTrackLine(String trackLine) {
this.trackLine = trackLine;
}
/**
* Return "track" line information for exporting features to a file. Default is null, subclasses may override.
*
* @return
*/
public String getExportTrackLine() {
return trackLine;
}
public void setGroupByStrand(boolean selected) {
this.groupByStrand = selected;
for (PackedFeatures pf : packedFeaturesMap.values()) {
pf.pack(getDisplayMode(), groupByStrand);
}
}
public boolean isGroupByStrand() {
return groupByStrand;
}
@Override
public void marshalXML(Document document, Element element) {
element.setAttribute("groupByStrand", String.valueOf(groupByStrand));
if (labelField != null) {
element.setAttribute("featureNameProperty", labelField);
}
super.marshalXML(document, element);
}
@Override
public void unmarshalXML(Element element, Integer version) {
super.unmarshalXML(element, version);
if (element.hasAttribute("featureNameProperty")) {
this.labelField = element.getAttribute("featureNameProperty");
}
this.groupByStrand = "true".equals(element.getAttribute("groupByStrand"));
NodeList tmp = element.getElementsByTagName("SequenceMatchSource");
if (tmp.getLength() > 0) {
Element sourceElement = (Element) tmp.item(0);
MotifFinderSource source = new MotifFinderSource();
source.unmarshalXML(sourceElement, version);
this.source = source;
}
}
} |
package org.cojen.tupl.repl;
import java.io.File;
import java.io.InterruptedIOException;
import java.io.IOException;
import java.nio.ByteOrder;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.channels.OverlappingFileLockException;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.Checksum;
import java.util.concurrent.ConcurrentSkipListSet;
import java.util.concurrent.TimeUnit;
import org.cojen.tupl.io.CRC32C;
import org.cojen.tupl.io.Utils;
import org.cojen.tupl.util.Latch;
import org.cojen.tupl.util.Worker;
/**
* Standard StateLog implementation which stores data in file segments.
*
* @author Brian S O'Neill
*/
final class FileStateLog extends Latch implements StateLog {
/*
File naming:
<base>.md (metadata file)
<base>[.<prevTerm>].<term>.<start index> (log files)
Metadata file stores little-endian fields at offset 0 and 4096, alternating.
0: Magic number (long)
8: Encoding version (int)
12: Metadata counter (int)
16: Current term (long)
24: Voted for (long)
32: Highest prev log term (long)
40: Highest log term (long)
48: Highest contiguous log index (exclusive) (long)
56: Durable commit log index (exclusive) (long)
64: CRC32C (int)
Example segment files with base of "mydata.repl":
mydata.repl
mydata.repl.1.0.0
mydata.repl.1.4000
mydata.repl.1.8000
mydata.repl.2.9000.1
The prevTerm field is not required if it matches the term.
*/
private static final long MAGIC_NUMBER = 5267718596810043313L;
private static final int ENCODING_VERSION = 20171004;
private static final int SECTION_POW = 12;
private static final int SECTION_SIZE = 1 << SECTION_POW;
private static final int METADATA_SIZE = 68;
private static final int METADATA_FILE_SIZE = SECTION_SIZE + METADATA_SIZE;
private static final int COUNTER_OFFSET = 12;
private static final int CURRENT_TERM_OFFSET = 16;
private static final int CRC_OFFSET = METADATA_SIZE - 4;
private final File mBase;
private final Worker mWorker;
// Terms are keyed only by their start index.
private final ConcurrentSkipListSet<LKey<TermLog>> mTermLogs;
private final FileChannel mMetadataFile;
private final FileLock mMetadataLock;
private final MappedByteBuffer mMetadataBuffer;
private final Checksum mMetadataCrc;
private final LogInfo mMetadataInfo;
private int mMetadataCounter;
private long mMetadataHighestIndex;
private long mMetadataDurableIndex;
private long mCurrentTerm;
private long mVotedForId;
private TermLog mHighestTermLog;
private TermLog mCommitTermLog;
private TermLog mContigTermLog;
private boolean mClosed;
FileStateLog(File base) throws IOException {
base = FileTermLog.checkBase(base);
mBase = base;
mWorker = Worker.make(10, 15, TimeUnit.SECONDS, null);
mTermLogs = new ConcurrentSkipListSet<>();
mMetadataFile = FileChannel.open
(new File(base.getPath() + ".md").toPath(),
StandardOpenOption.READ,
StandardOpenOption.WRITE,
StandardOpenOption.CREATE,
StandardOpenOption.DSYNC);
try {
mMetadataLock = mMetadataFile.tryLock();
} catch (OverlappingFileLockException e) {
Utils.closeQuietly(mMetadataFile);
throw new IOException("Replicator is already open by current process");
}
if (mMetadataLock == null) {
Utils.closeQuietly(mMetadataFile);
throw new IOException("Replicator is open and locked by another process");
}
boolean mdFileExists = mMetadataFile.size() != 0;
mMetadataBuffer = mMetadataFile.map(FileChannel.MapMode.READ_WRITE, 0, METADATA_FILE_SIZE);
mMetadataBuffer.order(ByteOrder.LITTLE_ENDIAN);
mMetadataCrc = CRC32C.newInstance();
mMetadataInfo = new LogInfo();
if (!mdFileExists) {
// Prepare a new metadata file.
cleanMetadata(0, 0);
cleanMetadata(SECTION_SIZE, 1);
}
// Ensure existing contents are durable following a process restart.
mMetadataBuffer.force();
long counter0 = verifyMetadata(0);
long counter1 = verifyMetadata(SECTION_SIZE);
// Select the higher counter from the valid sections.
int counter, offset;
select: {
if (counter0 < 0) {
if (counter1 < 0) {
if (counter0 == -1 || counter1 == -1) {
throw new IOException("Metadata magic number is wrong");
}
throw new IOException("Metadata CRC mismatch");
}
} else if (counter1 < 0 || (((int) counter0) - (int) counter1) > 0) {
counter = (int) counter0;
offset = 0;
break select;
}
counter = (int) counter1;
offset = SECTION_SIZE;
}
if (((counter & 1) << SECTION_POW) != offset) {
throw new IOException("Metadata sections are swapped");
}
mMetadataCounter = counter;
mMetadataBuffer.clear();
mMetadataBuffer.position(offset + CURRENT_TERM_OFFSET);
long currentTerm = mMetadataBuffer.getLong();
long votedForId = mMetadataBuffer.getLong();
long highestPrevTerm = mMetadataBuffer.getLong();
long highestTerm = mMetadataBuffer.getLong();
long highestIndex = mMetadataBuffer.getLong();
long durableIndex = mMetadataBuffer.getLong();
if (currentTerm < highestTerm) {
throw new IOException("Current term is lower than highest term: " +
currentTerm + " < " + highestTerm);
}
if (highestIndex < durableIndex) {
throw new IOException("Highest index is lower than durable index: " +
highestIndex + " < " + durableIndex);
}
// Initialize mMetadataInfo with valid state. Note that the mCommitIndex field isn't
// actually used at all when persisting metadata, but initialize it anyhow.
mMetadataInfo.mTerm = highestTerm;
mMetadataInfo.mHighestIndex = highestIndex;
mMetadataInfo.mCommitIndex = durableIndex;
// Seemingly redundant, these fields are updated after the metadata file is written.
mMetadataHighestIndex = highestIndex;
mMetadataDurableIndex = durableIndex;
mCurrentTerm = currentTerm;
mVotedForId = votedForId;
// Open all the existing terms.
TreeMap<Long, List<String>> mTermFileNames = new TreeMap<>();
File parentFile = mBase.getParentFile();
String[] fileNames = parentFile.list();
if (fileNames != null && fileNames.length != 0) {
// This pattern captures the term, but it discards the optional prevTerm.
Pattern p = Pattern.compile(base.getName() + "\\.(\\d+)\\.\\d+(?:\\.\\d+)?");
for (String name : fileNames) {
Matcher m = p.matcher(name);
if (m.matches()) {
Long term = Long.valueOf(m.group(1));
if (term <= 0) {
throw new IOException("Illegal term: " + term);
}
if (term > highestTerm) {
// Delete all terms higher than the highest.
new File(parentFile, name).delete();
} else {
List<String> termNames = mTermFileNames.get(term);
if (termNames == null) {
termNames = new ArrayList<>();
mTermFileNames.put(term, termNames);
}
termNames.add(name);
}
}
}
}
long prevTerm = -1;
for (Map.Entry<Long, List<String>> e : mTermFileNames.entrySet()) {
long term = e.getKey();
TermLog termLog = FileTermLog.openTerm
(mWorker, mBase, prevTerm, term, -1, 0, highestIndex, e.getValue());
mTermLogs.add(termLog);
prevTerm = term;
}
if (!mTermLogs.isEmpty()) {
Iterator<LKey<TermLog>> it = mTermLogs.iterator();
TermLog termLog = (TermLog) it.next();
while (true) {
TermLog next;
if (it.hasNext()) {
next = (TermLog) it.next();
} else {
next = null;
}
if (next == null) {
break;
}
if (next.term() <= highestTerm) {
termLog.finishTerm(next.startIndex());
}
termLog = next;
}
}
if (mTermLogs.isEmpty()) {
// Create a primordial term.
mTermLogs.add(FileTermLog.newTerm(mWorker, mBase, highestPrevTerm, highestTerm,
highestIndex, durableIndex));
}
if (durableIndex > 0) {
commit(durableIndex);
}
}
private void cleanMetadata(int offset, int counter) {
MappedByteBuffer bb = mMetadataBuffer;
bb.clear();
bb.position(offset);
bb.limit(offset + METADATA_SIZE);
bb.putLong(MAGIC_NUMBER);
bb.putInt(ENCODING_VERSION);
bb.putInt(counter);
// Initialize current term, voted for, highest prev log term, highest log term, highest
// contiguous log index, and durable commit log index.
if (bb.position() != (offset + CURRENT_TERM_OFFSET)) {
throw new AssertionError();
}
for (int i=0; i<6; i++) {
bb.putLong(0);
}
if (bb.position() != (offset + CRC_OFFSET)) {
throw new AssertionError();
}
bb.limit(bb.position());
bb.position(offset);
mMetadataCrc.reset();
CRC32C.update(mMetadataCrc, bb);
bb.limit(offset + METADATA_SIZE);
bb.putInt((int) mMetadataCrc.getValue());
}
/**
* @return uint32 counter value, or -1 if wrong magic number, or -2 if CRC doesn't match
* @throws IOException if wrong magic number or encoding version
*/
private long verifyMetadata(int offset) throws IOException {
MappedByteBuffer bb = mMetadataBuffer;
bb.clear();
bb.position(offset);
bb.limit(offset + CRC_OFFSET);
if (bb.getLong() != MAGIC_NUMBER) {
return -1;
}
bb.position(offset);
mMetadataCrc.reset();
CRC32C.update(mMetadataCrc, bb);
bb.limit(offset + METADATA_SIZE);
int actual = bb.getInt();
if (actual != (int) mMetadataCrc.getValue()) {
return -2;
}
bb.clear();
bb.position(offset + 8);
bb.limit(offset + CRC_OFFSET);
int encoding = bb.getInt();
if (encoding != ENCODING_VERSION) {
throw new IOException("Metadata encoding version is unknown: " + encoding);
}
return bb.getInt() & 0xffffffffL;
}
@Override
public TermLog captureHighest(LogInfo info) {
acquireShared();
TermLog highestLog = mHighestTermLog;
if (highestLog != null && highestLog == mTermLogs.last()) {
highestLog.captureHighest(info);
releaseShared();
} else {
highestLog = doCaptureHighest(info, highestLog, true);
}
return highestLog;
}
// Must be called with shared latch held.
private TermLog doCaptureHighest(LogInfo info, TermLog highestLog, boolean releaseLatch) {
int size = mTermLogs.size();
if (size == 0) {
info.mTerm = 0;
info.mHighestIndex = 0;
info.mCommitIndex = 0;
if (releaseLatch) {
releaseShared();
}
return null;
}
if (highestLog != null) {
// Search again, in case log instance has been orphaned.
highestLog = (TermLog) mTermLogs.ceiling(highestLog); // findGe
}
if (highestLog == null) {
highestLog = (TermLog) mTermLogs.first();
}
while (true) {
TermLog nextLog = (TermLog) mTermLogs.higher(highestLog); // findGt
highestLog.captureHighest(info);
if (nextLog == null || info.mHighestIndex < nextLog.startIndex()) {
if (tryUpgrade()) {
mHighestTermLog = highestLog;
if (releaseLatch) {
releaseExclusive();
} else {
downgrade();
}
} else {
if (releaseLatch) {
releaseShared();
}
}
return highestLog;
}
highestLog = nextLog;
}
}
@Override
public void commit(long commitIndex) {
acquireShared();
TermLog commitLog = mCommitTermLog;
if (commitLog != null && commitLog == mTermLogs.last()) {
commitLog.commit(commitIndex);
releaseShared();
return;
}
int size = mTermLogs.size();
if (size == 0) {
releaseShared();
return;
}
if (commitLog != null) {
// Search again, in case log instance has been orphaned.
commitLog = (TermLog) mTermLogs.ceiling(commitLog); // findGe
}
if (commitLog == null) {
commitLog = (TermLog) mTermLogs.first();
}
LogInfo info = new LogInfo();
while (true) {
commitLog.captureHighest(info);
if (info.mCommitIndex < commitLog.endIndex()) {
break;
}
commitLog = (TermLog) mTermLogs.higher(commitLog); // findGt
}
if (commitLog != mCommitTermLog && tryUpgrade()) {
mCommitTermLog = commitLog;
downgrade();
}
// Pass the commit index to the terms in descending order, to prevent a race condition
// with the doCaptureHighest method. It iterates in ascending order, assuming that the
// commit index of a higher term cannot be lower. If the terms are committed in
// ascending order, latch coupling would be required to prevent the doCaptureHighest
// from going too far ahead. Descending order commit is simpler.
Iterator<LKey<TermLog>> it = mTermLogs.descendingIterator();
while (it.hasNext()) {
TermLog termLog = (TermLog) it.next();
termLog.commit(commitIndex);
if (termLog == commitLog) {
break;
}
}
releaseShared();
}
@Override
public long incrementCurrentTerm(int termIncrement, long candidateId) throws IOException {
if (termIncrement <= 0) {
throw new IllegalArgumentException();
}
synchronized (mMetadataInfo) {
mCurrentTerm += termIncrement;
mVotedForId = candidateId;
doSync();
return mCurrentTerm;
}
}
@Override
public long checkCurrentTerm(long term) throws IOException {
synchronized (mMetadataInfo) {
if (term > mCurrentTerm) {
mCurrentTerm = term;
mVotedForId = 0;
doSync();
}
return mCurrentTerm;
}
}
@Override
public boolean checkCandidate(long candidateId) throws IOException {
synchronized (mMetadataInfo) {
if (mVotedForId == candidateId) {
return true;
}
if (mVotedForId == 0) {
mVotedForId = candidateId;
doSync();
return true;
}
return false;
}
}
@Override
public void compact(long index) throws IOException {
Iterator<LKey<TermLog>> it = mTermLogs.iterator();
while (it.hasNext()) {
TermLog termLog = (TermLog) it.next();
if (termLog.compact(index)) {
it.remove();
} else {
break;
}
}
}
@Override
public void truncateAll(long prevTerm, long term, long index) throws IOException {
synchronized (mMetadataInfo) {
if (mClosed) {
throw new IOException("Closed");
}
TermLog highestLog;
acquireExclusive();
try {
compact(Long.MAX_VALUE);
// Create a new primordial term.
highestLog = FileTermLog.newTerm(mWorker, mBase, prevTerm, term, index, index);
mTermLogs.add(highestLog);
} finally {
releaseExclusive();
}
mMetadataInfo.mTerm = term;
mMetadataInfo.mHighestIndex = index;
mMetadataInfo.mCommitIndex = index;
mMetadataHighestIndex = index;
mMetadataDurableIndex = index;
syncMetadata(highestLog);
}
}
@Override
public boolean defineTerm(long prevTerm, long term, long index) throws IOException {
return defineTermLog(prevTerm, term, index) != null;
}
@Override
public TermLog termLogAt(long index) {
return (TermLog) mTermLogs.floor(new LKey.Finder<>(index)); // findLe
}
@Override
public void queryTerms(long startIndex, long endIndex, TermQuery results) {
if (startIndex >= endIndex) {
return;
}
LKey<TermLog> startKey = new LKey.Finder<>(startIndex);
LKey<TermLog> endKey = new LKey.Finder<>(endIndex);
LKey<TermLog> prev = mTermLogs.floor(startKey); // findLe
if (prev != null && ((TermLog) prev).endIndex() > startIndex) {
startKey = prev;
}
for (Object key : mTermLogs.subSet(startKey, endKey)) {
TermLog termLog = (TermLog) key;
results.term(termLog.prevTerm(), termLog.term(), termLog.startIndex());
}
}
@Override
public long checkForMissingData(long contigIndex, IndexRange results) {
acquireShared();
if (mTermLogs.isEmpty()) {
releaseShared();
return 0;
}
TermLog termLog = mContigTermLog;
if (termLog != null && termLog == mTermLogs.last()) {
releaseShared();
return termLog.checkForMissingData(contigIndex, results);
}
if (termLog != null) {
// Search again, in case log instance has been orphaned.
termLog = (TermLog) mTermLogs.ceiling(termLog); // findGe
}
if (termLog == null) {
termLog = (TermLog) mTermLogs.first();
}
final long originalContigIndex = contigIndex;
TermLog nextLog;
while (true) {
nextLog = (TermLog) mTermLogs.higher(termLog); // findGt
contigIndex = termLog.checkForMissingData(contigIndex, results);
if (contigIndex < termLog.endIndex() || nextLog == null) {
break;
}
termLog = nextLog;
}
if (termLog != mContigTermLog && tryUpgrade()) {
mContigTermLog = termLog;
if (nextLog == null) {
releaseExclusive();
return contigIndex;
}
downgrade();
}
if (contigIndex == originalContigIndex) {
// Scan ahead into all remaining terms.
while (nextLog != null) {
nextLog.checkForMissingData(0, results);
nextLog = (TermLog) mTermLogs.higher(nextLog); // findGt
}
}
releaseShared();
return contigIndex;
}
@Override
public LogWriter openWriter(long prevTerm, long term, long index) throws IOException {
TermLog termLog = defineTermLog(prevTerm, term, index);
return termLog == null ? null : termLog.openWriter(index);
}
/**
* @return null if not defined due to term mismatch
*/
// package-private for testing
TermLog defineTermLog(long prevTerm, long term, long index) throws IOException {
final LKey<TermLog> key = new LKey.Finder<>(index);
boolean exclusive = false;
acquireShared();
try {
TermLog termLog;
defineTermLog: while (true) {
termLog = (TermLog) mTermLogs.floor(key); // findLe
if (termLog == null) {
break defineTermLog;
}
long actualPrevTerm = termLog.prevTermAt(index);
if (prevTerm != actualPrevTerm) {
int removeCount = countConflictingEmptyTerms(prevTerm, index, termLog);
if (removeCount <= 0) {
termLog = null;
break defineTermLog;
}
// Remove the empty terms, but exclusive latch must be held.
if (!exclusive) {
if (tryUpgrade()) {
exclusive = true;
} else {
releaseShared();
acquireExclusive();
exclusive = true;
continue;
}
}
while (true) {
termLog.finishTerm(termLog.startIndex());
mTermLogs.remove(termLog);
removeCount
if (removeCount <= 0) {
break;
}
termLog = (TermLog) mTermLogs.lower(termLog);
}
continue;
}
long actualTerm = termLog.term();
if (term == actualTerm) {
// Term already exists.
break defineTermLog;
}
if (term < actualTerm) {
termLog = null;
break defineTermLog;
}
if (mClosed) {
throw new IOException("Closed");
}
if (!exclusive) {
if (tryUpgrade()) {
exclusive = true;
} else {
releaseShared();
acquireExclusive();
exclusive = true;
continue;
}
}
termLog.sync();
long commitIndex = termLog.finishTerm(index);
// Truncate and remove all higher conflicting term logs. Iterator might start
// with the term log just finished, facilitating its removal. Finishing again
// at the same index is harmless.
Iterator<LKey<TermLog>> it = mTermLogs.tailSet(key).iterator(); // viewGe
while (it.hasNext()) {
TermLog logGe = (TermLog) it.next();
logGe.finishTerm(index);
it.remove();
}
termLog = FileTermLog.newTerm(mWorker, mBase, prevTerm, term, index, commitIndex);
mTermLogs.add(termLog);
break defineTermLog;
}
return termLog;
} finally {
release(exclusive);
}
}
/**
* Checks if removing empty terms would resolve a prev term conflict.
* Caller must hold any latch.
*
* @return amount of terms to remove; 0 if the conflict cannot be resolved
*/
private int countConflictingEmptyTerms(long prevTerm, long index, TermLog termLog) {
int count = 1;
while (true) {
if (!termLog.isEmpty()) {
return 0;
}
termLog = (TermLog) mTermLogs.lower(termLog); // findLt
if (termLog == null) {
// Cannot remove the primordial term.
return 0;
}
if (prevTerm == termLog.prevTermAt(index)) {
return count;
}
count++;
}
}
@Override
public LogReader openReader(long index) {
LKey<TermLog> key = new LKey.Finder<>(index);
acquireShared();
try {
TermLog termLog = (TermLog) mTermLogs.floor(key); // findLe
if (termLog != null) {
return termLog.openReader(index);
}
termLog = (TermLog) mTermLogs.first();
throw new IllegalStateException
("Index is lower than start index: " + index + " < " + termLog.startIndex());
} finally {
releaseShared();
}
}
@Override
public void sync() throws IOException {
synchronized (mMetadataInfo) {
doSync();
}
}
@Override
public long syncCommit(long prevTerm, long term, long index) throws IOException {
synchronized (mMetadataInfo) {
if (mClosed) {
throw new IOException("Closed");
}
TermLog highestLog;
acquireShared();
try {
TermLog termLog = termLogAt(index);
if (termLog == null || term != termLog.term()
|| prevTerm != termLog.prevTermAt(index))
{
return -1;
}
highestLog = mHighestTermLog;
if (highestLog != null && highestLog == mTermLogs.last()) {
highestLog.captureHighest(mMetadataInfo);
} else {
highestLog = doCaptureHighest(mMetadataInfo, highestLog, false);
}
if (index > mMetadataInfo.mHighestIndex) {
return -1;
}
if (index <= mMetadataHighestIndex) {
// Nothing to do.
return mMetadataInfo.mCommitIndex;
}
highestLog.sync();
} finally {
releaseShared();
}
syncMetadata(highestLog);
return mMetadataInfo.mCommitIndex;
}
}
@Override
public boolean isDurable(long index) {
synchronized (mMetadataInfo) {
return index <= mMetadataDurableIndex;
}
}
@Override
public boolean commitDurable(long index) throws IOException {
synchronized (mMetadataInfo) {
if (mClosed) {
throw new IOException("Closed");
}
if (index <= mMetadataDurableIndex) {
return false;
}
checkDurable(index, mMetadataHighestIndex);
TermLog highestLog = captureHighest(mMetadataInfo);
checkDurable(index, mMetadataInfo.mCommitIndex);
syncMetadata(highestLog, index);
return true;
}
}
private static void checkDurable(long index, long highestIndex) {
if (index > highestIndex) {
throw new IllegalStateException("Commit index is too high: " + index
+ " > " + highestIndex);
}
}
// Caller must be synchronized on mMetadataInfo.
private void doSync() throws IOException {
if (mClosed) {
return;
}
TermLog highestLog;
acquireShared();
try {
highestLog = mHighestTermLog;
if (highestLog != null && highestLog == mTermLogs.last()) {
highestLog.captureHighest(mMetadataInfo);
highestLog.sync();
} else {
highestLog = doCaptureHighest(mMetadataInfo, highestLog, false);
if (highestLog != null) {
highestLog.sync();
}
}
} finally {
releaseShared();
}
syncMetadata(highestLog);
}
// Caller must be synchronized on mMetadataInfo.
private void syncMetadata(TermLog highestLog) throws IOException {
syncMetadata(highestLog, mMetadataDurableIndex);
}
// Caller must be synchronized on mMetadataInfo.
private void syncMetadata(TermLog highestLog, long durableIndex) throws IOException {
if (mClosed) {
return;
}
if (mMetadataInfo.mHighestIndex < durableIndex) {
throw new IllegalStateException("Highest index is lower than durable index: " +
mMetadataInfo.mHighestIndex + " < " + durableIndex);
}
int counter = mMetadataCounter + 1;
int offset = (counter & 1) << SECTION_POW;
long highestTerm = mMetadataInfo.mTerm;
long highestIndex = mMetadataInfo.mHighestIndex;
MappedByteBuffer bb = mMetadataBuffer;
bb.clear();
bb.position(offset + COUNTER_OFFSET);
bb.limit(offset + CRC_OFFSET);
bb.putInt(counter);
bb.putLong(mCurrentTerm);
bb.putLong(mVotedForId);
bb.putLong(highestLog == null ? highestTerm : highestLog.prevTermAt(highestIndex));
bb.putLong(highestTerm);
bb.putLong(highestIndex);
bb.putLong(durableIndex);
bb.position(offset);
mMetadataCrc.reset();
CRC32C.update(mMetadataCrc, bb);
bb.limit(offset + METADATA_SIZE);
bb.putInt((int) mMetadataCrc.getValue());
bb.force();
// Update field values only after successful file I/O.
mMetadataCounter = counter;
mMetadataHighestIndex = mMetadataInfo.mHighestIndex;
mMetadataDurableIndex = durableIndex;
}
@Override
public void close() throws IOException {
synchronized (mMetadataInfo) {
acquireExclusive();
try {
if (mClosed) {
return;
}
mClosed = true;
mMetadataLock.close();
mMetadataFile.close();
Utils.delete(mMetadataBuffer);
for (Object key : mTermLogs) {
((TermLog) key).close();
}
} finally {
releaseExclusive();
}
}
mWorker.join(true);
}
} |
package org.jasome.util;
import com.github.javaparser.ast.Node;
import com.github.javaparser.ast.body.MethodDeclaration;
import com.github.javaparser.ast.body.Parameter;
import com.github.javaparser.ast.body.VariableDeclarator;
import com.github.javaparser.ast.expr.*;
import com.github.javaparser.ast.stmt.BlockStmt;
import com.github.javaparser.ast.type.ClassOrInterfaceType;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.*;
import com.google.common.graph.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.jasome.input.Method;
import org.jasome.input.Package;
import org.jasome.input.Project;
import org.jasome.input.Type;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
public class CalculationUtils {
public static LoadingCache<Pair<MethodDeclaration, VariableDeclarator>, Boolean> isFieldAccessedWithinMethod = CacheBuilder.newBuilder()
.expireAfterWrite(10, TimeUnit.MINUTES)
.build(new CacheLoader<Pair<MethodDeclaration, VariableDeclarator>, Boolean>() {
@Override
public Boolean load(Pair<MethodDeclaration, VariableDeclarator> key) throws Exception {
MethodDeclaration method = key.getLeft();
VariableDeclarator variable = key.getRight();
if (!method.getBody().isPresent()) return false;
List<FieldAccessExpr> fieldAccesses = method.getBody().get().getNodesByType(FieldAccessExpr.class);
//If we have a field match we can just count it, it's directly prefixed with 'this.' so there's no room for shadowing
boolean anyDirectAccess = fieldAccesses.parallelStream().anyMatch(fieldAccessExpr -> fieldAccessExpr.getName().equals(variable.getName()));
if (anyDirectAccess) return true;
else {
List<NameExpr> nameAccesses = method.getBody().get().getNodesByType(NameExpr.class);
boolean anyIndirectAccess = nameAccesses
.parallelStream()
.anyMatch(nameAccessExpr -> {
List<BlockStmt> allBlocksFromMethodDeclarationToNameAccessExpr = getAllVariableDefinitionScopesBetweenMethodDefinitionAndNode(nameAccessExpr);
List<VariableDeclarator> variablesDefinedInMethod = method.getNodesByType(VariableDeclarator.class);
boolean isVariableRedefinedInScope = variablesDefinedInMethod
.parallelStream()
.anyMatch(variableDeclaration -> {
//if any of these variables have all their parents in the allBlocks list above, then that variable shadows nameExpr (as long as the name matches)
//It essentially means that this variable declaration is BETWEEN the variable access and the method declaration, which means this variable
//shadows the field when doing the name access. If this variable declaration were LOWER on the nesting chain or divergent entirely, it would
//have at least one block between it and the method declaration that ISN'T between the name access and the method
if (variableDeclaration.getName().equals(nameAccessExpr.getName())) {
List<BlockStmt> allBlocksFromMethodDeclarationToVariableDeclaration = getAllVariableDefinitionScopesBetweenMethodDefinitionAndNode(variableDeclaration);
return allBlocksFromMethodDeclarationToNameAccessExpr.containsAll(allBlocksFromMethodDeclarationToVariableDeclaration);
} else {
return false;
}
});
boolean isVariableRedefinedByMethodSignature = method.getParameters()
.parallelStream()
.anyMatch(parameter -> parameter.getName().equals(nameAccessExpr.getName()));
if (isVariableRedefinedInScope || isVariableRedefinedByMethodSignature) {
return false;
} else {
return nameAccessExpr.getName().equals(variable.getName());
}
});
if (anyIndirectAccess) return true;
}
return false;
}
});
private static List<BlockStmt> getAllVariableDefinitionScopesBetweenMethodDefinitionAndNode(Node theNode) {
List<BlockStmt> blocksOnPathToMethodDeclaration = new ArrayList<>();
while (!(theNode instanceof MethodDeclaration)) {
if (theNode instanceof BlockStmt) {
blocksOnPathToMethodDeclaration.add((BlockStmt) theNode);
}
if (theNode.getParentNode().isPresent()) {
theNode = theNode.getParentNode().get();
} else {
break;
}
}
return blocksOnPathToMethodDeclaration;
}
private static LoadingCache<Project, Graph<Type>> inheritanceGraph = CacheBuilder.newBuilder()
.expireAfterWrite(10, TimeUnit.MINUTES)
.build(new CacheLoader<Project, Graph<Type>>() {
@Override
public Graph<Type> load(Project project) throws Exception {
MutableGraph<Type> graph = GraphBuilder.directed().build();
Map<String, Type> allClassesByName = project.getPackages()
.parallelStream()
.map(Package::getTypes)
.flatMap(Set::stream)
.collect(Collectors.toMap(Type::getName, t -> t));
//TODO: make this a little smarter - basically when adding an edge based on a use, see if that 'use' is
//of a class that has the same name in multiple packages. if so, use the one in the current type's package.
//otherwise just pick one deterministically, we're not parsing import statements. Maybe pick the one
//whose package name has the most characters in common with the types ("closer"). What to do if equal?
//Can they be equal? would that mean that both target types have the same package, which wouldn't be allowed?
for (Type type : allClassesByName.values()) {
List<ClassOrInterfaceType> extendedTypes = type.getSource().getExtendedTypes();
List<ClassOrInterfaceType> implementedTypes = type.getSource().getImplementedTypes();
for (ClassOrInterfaceType extendedType : extendedTypes) {
if (allClassesByName.containsKey(extendedType.getName().getIdentifier())) {
graph.putEdge(allClassesByName.get(extendedType.getName().getIdentifier()), type);
}
}
for (ClassOrInterfaceType implementedType : implementedTypes) {
if (allClassesByName.containsKey(implementedType.getName().getIdentifier())) {
graph.putEdge(allClassesByName.get(implementedType.getName().getIdentifier()), type);
}
}
}
return graph;
}
});
public static Graph<Type> getInheritanceGraph(Project parentProject) {
MutableGraph<Type> graph = GraphBuilder.directed().build();
Multimap<String, Type> allClassesByName = HashMultimap.create();
parentProject.getPackages()
.parallelStream()
.map(Package::getTypes)
.flatMap(Set::stream)
.forEach(type -> allClassesByName.put(type.getName(), type));
Set<Type> allClasses = parentProject.getPackages()
.parallelStream()
.map(Package::getTypes)
.flatMap(Set::stream)
.collect(Collectors.toSet());
for (Type type :allClasses) {
List<ClassOrInterfaceType> extendedTypes = type.getSource().getExtendedTypes();
List<ClassOrInterfaceType> implementedTypes = type.getSource().getImplementedTypes();
graph.addNode(type);
List<ClassOrInterfaceType> parentTypes = new ArrayList<>();
parentTypes.addAll(extendedTypes);
parentTypes.addAll(implementedTypes);
for (ClassOrInterfaceType parentType : parentTypes) {
Optional<Type> closestType = getClosestTypeWithName(parentType.getName(), type);
closestType.ifPresent(c ->
graph.putEdge(c, type)
);
}
}
return ImmutableGraph.copyOf(graph);
}
public static Network<Method, Distinct<Expression>> getCallNetwork(Project parentProject) {
MutableNetwork<Method, Distinct<Expression>> network = NetworkBuilder.directed().allowsSelfLoops(true).allowsParallelEdges(true).build();
// Set<Method> allClassesByName = new HashSet<>();
Set<Method> allMethods = parentProject.getPackages()
.parallelStream()
.map(Package::getTypes)
.flatMap(Set::stream).map(Type::getMethods).flatMap(Set::stream).collect(Collectors.toSet());
for(Method method: allMethods) {
network.addNode(method);
List<MethodCallExpr> calls = method.getSource().getNodesByType(MethodCallExpr.class);
List<MethodReferenceExpr> references = method.getSource().getNodesByType(MethodReferenceExpr.class);
for(MethodCallExpr methodCall: calls) {
Optional<Method> methodCalled;
methodCalled = getMethodCalledByMethodExpression(method, methodCall);
network.addEdge(method, methodCalled.orElse(Method.UNKNOWN), Distinct.of(methodCall));
}
}
return ImmutableNetwork.copyOf(network);
}
private static Optional<Method> getMethodCalledByMethodExpression(Method containingMethod, MethodCallExpr methodCall) {
Optional<Expression> methodCallScope = methodCall.getScope();
Optional<Type> scopeType = determineTypeOf(methodCallScope.orElse(null), containingMethod);
if(scopeType.isPresent()) {
List<Method> inClassMethods = scopeType.get().getMethods().stream().collect(Collectors.toList());
Optional<Method> matching = inClassMethods.stream().filter(m->
m.getSource().getName().equals(methodCall.getName()) && m.getSource().getParameters().size() == methodCall.getArguments().size()
).findFirst();
return matching;
}
return Optional.empty();
}
private static Optional<Type> determineTypeOf(Expression scope, Method containingMethod) {
if(scope == null || scope instanceof ThisExpr) return Optional.of(containingMethod.getParentType());
if(scope instanceof NameExpr) {
SimpleName variableName = ((NameExpr)scope).getName();
Optional<com.github.javaparser.ast.type.Type> nameType = findTypeOfVariableDeclaration(variableName, scope);
if(nameType.isPresent()) {
if(nameType.get() instanceof ClassOrInterfaceType) {
Optional<Type> closestType = getClosestType((ClassOrInterfaceType) nameType.get(), containingMethod.getParentType());
return closestType;
} else {
return Optional.empty();
}
} else {
return Optional.empty();
}
}
return Optional.empty();
}
private static Optional<com.github.javaparser.ast.type.Type> findTypeOfVariableDeclaration(SimpleName variableName, Node scope) {
List<Node> scopeParents = getAllParentsUpToClassDefinition(scope);
Node topMostNode = scopeParents.get(0);
com.github.javaparser.ast.type.Type typeCandidate = null;
int longestChainLength = 0;
List<VariableDeclarator> variableDeclarations = topMostNode.getNodesByType(VariableDeclarator.class);
for(VariableDeclarator variableDeclarator: variableDeclarations) {
List<Node> variableParents = getAllParentsUpToClassDefinition(variableDeclarator);
if(scopeParents.containsAll(variableParents)) {
//This variable is defined in the scope we care about
if(variableParents.size() > longestChainLength) {
typeCandidate = variableDeclarator.getType();
longestChainLength = variableParents.size();
}
}
}
List<VariableDeclarationExpr> variableDeclarationExprs = topMostNode.getNodesByType(VariableDeclarationExpr.class);
for(VariableDeclarationExpr variableDeclarationExpr: variableDeclarationExprs) {
List<Node> variableParents = getAllParentsUpToClassDefinition(variableDeclarationExpr);
if(scopeParents.containsAll(variableParents)) {
//This variable is defined in the scope we care about
if(variableParents.size() > longestChainLength) {
typeCandidate = variableDeclarationExpr.getCommonType();
longestChainLength = variableParents.size();
}
}
}
List<Parameter> parameters = topMostNode.getNodesByType(Parameter.class);
for(Parameter parameter: parameters) {
List<Node> parameterParents = getAllParentsUpToClassDefinition(parameter);
if(scopeParents.containsAll(parameterParents)) {
//This variable is defined in the scope we care about
if(parameterParents.size() > longestChainLength) {
typeCandidate = parameter.getType();
longestChainLength = parameterParents.size();
}
}
}
return Optional.ofNullable(typeCandidate);
}
private static List<Node> getAllParentsUpToClassDefinition(Node scope) {
List<Node> parents = new ArrayList<>();
while(scope.getParentNode().isPresent()) {
Node parent = scope.getParentNode().get();
parents.add(parent);
scope = parent;
}
return Lists.reverse(parents);
}
//TODO: this desperately needs to be cached
private static Optional<Type> getClosestTypeWithName(SimpleName identifier, Type source) {
Multimap<SimpleName, Type> allClassesByName = HashMultimap.create();
source.getParentPackage().getParentProject().getPackages()
.parallelStream()
.map(Package::getTypes)
.flatMap(Set::stream)
.forEach(type -> allClassesByName.put(type.getSource().getName(), type));
Collection<Type> matchingTypes = allClassesByName.get(identifier);
List<Type> matchingTypesSortedByNumberOfCharactersInCommonWithSourcePackage = matchingTypes.stream().sorted(new Comparator<Type>() {
@Override
public int compare(Type t1, Type t2) {
int firstCharsInCommon = StringUtils.getCommonPrefix(source.getParentPackage().getName(), t1.getParentPackage().getName()).length();
int secondCharsInCommon = StringUtils.getCommonPrefix(source.getParentPackage().getName(), t2.getParentPackage().getName()).length();
return ((Integer) firstCharsInCommon).compareTo(secondCharsInCommon);
}
}).collect(Collectors.toList());
if(matchingTypesSortedByNumberOfCharactersInCommonWithSourcePackage.size() > 0) {
return Optional.of(matchingTypesSortedByNumberOfCharactersInCommonWithSourcePackage.get(0));
} else {
return Optional.empty();
}
}
private static Optional<Type> getClosestType(ClassOrInterfaceType target, Type source) {
Multimap<SimpleName, Type> allClassesByName = HashMultimap.create();
source.getParentPackage().getParentProject().getPackages()
.parallelStream()
.map(Package::getTypes)
.flatMap(Set::stream)
.forEach(type -> allClassesByName.put(type.getSource().getName(), type));
Collection<Type> matchingTypes = allClassesByName.get(target.getName());
List<Type> matchingTypesSortedByNumberOfCharactersInCommonWithSourcePackage = matchingTypes.stream().sorted(new Comparator<Type>() {
@Override
public int compare(Type t1, Type t2) {
int firstCharsInCommon = StringUtils.getCommonPrefix(source.getParentPackage().getName(), t1.getParentPackage().getName()).length();
int secondCharsInCommon = StringUtils.getCommonPrefix(source.getParentPackage().getName(), t2.getParentPackage().getName()).length();
return ((Integer) firstCharsInCommon).compareTo(secondCharsInCommon);
}
}).collect(Collectors.toList());
if(matchingTypesSortedByNumberOfCharactersInCommonWithSourcePackage.size() > 0) {
return Optional.of(matchingTypesSortedByNumberOfCharactersInCommonWithSourcePackage.get(0));
} else {
return Optional.empty();
}
}
} |
package org.jtrfp.trcl.ext.tr;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import javax.media.opengl.GL3;
import org.apache.commons.math3.linear.Array2DRowRealMatrix;
import org.apache.commons.math3.linear.RealMatrix;
import org.jtrfp.trcl.Camera;
import org.jtrfp.trcl.HUDSystem;
import org.jtrfp.trcl.RenderableSpacePartitioningGrid;
import org.jtrfp.trcl.beh.MatchDirection;
import org.jtrfp.trcl.beh.MatchPosition;
import org.jtrfp.trcl.beh.MatchPosition.OffsetMode;
import org.jtrfp.trcl.core.ControllerInput;
import org.jtrfp.trcl.core.ControllerInputs;
import org.jtrfp.trcl.core.Feature;
import org.jtrfp.trcl.core.FeatureFactory;
import org.jtrfp.trcl.core.TR;
import org.jtrfp.trcl.flow.Game;
import org.jtrfp.trcl.flow.IndirectProperty;
import org.jtrfp.trcl.flow.Mission;
import org.jtrfp.trcl.gpu.GPU;
import org.jtrfp.trcl.gpu.Model;
import org.jtrfp.trcl.img.vq.ColorPaletteVectorList;
import org.jtrfp.trcl.math.Vect3D;
import org.jtrfp.trcl.obj.Player;
import org.jtrfp.trcl.obj.RelevantEverywhere;
import org.jtrfp.trcl.obj.WorldObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class ViewSelect implements FeatureFactory<Game> {
//PROPERTIES
public static final String HUD_VISIBLE = "hudVisible";
//CONSTANTS
public static final String VIEW = "View Select",
INSTRUMENTS_VIEW = "Instruments View",
VIEW_MODE = "View Mode",
INSTRUMENT_MODE = "Instrument Mode";
private static final boolean INS_ENABLE = false;
private final ControllerInput view, iView;
@Autowired
private TR tr;
private Model cockpitModel;
private static final int TAIL_DISTANCE = 15000,
FLOAT_HEIGHT = 5000;
private interface ViewMode{
public void apply();
}
private interface InstrumentMode{
public boolean apply();
}
@Autowired
public ViewSelect(ControllerInputs inputs){
view = inputs.getControllerInput(VIEW);
iView = inputs.getControllerInput(INSTRUMENTS_VIEW);
}//end constructor
private class ViewSelectFeature implements Feature<Game>{
private boolean hudVisible = false;
private WorldObject cockpit;
private final PropertyChangeSupport pcs = new PropertyChangeSupport(this);
private ViewMode viewMode;
private InstrumentMode instrumentMode;
private boolean hudVisibility = false;
private int viewModeItr = 1, instrumentModeItr = 1;
private final ViewMode [] viewModes = new ViewMode[]{
new CockpitView(),
new OutsideView(),
new ChaseView()
};
private final InstrumentMode [] instrumentModes = new InstrumentMode[]{
new FullCockpitInstruments(),
new HeadsUpDisplayInstruments(),
new NoInstruments()
};
@Override
public void apply(Game game) {
System.out.println("ViewSelect apply()");
view .addPropertyChangeListener(new ViewSelectPropertyChangeListener());
iView.addPropertyChangeListener(new InstrumentViewSelectPropertyChangeListener());
///final IndirectProperty<Game> gameIP = new IndirectProperty<Game>();
//tr.addPropertyChangeListener(TR.GAME, gameIP);
final IndirectProperty<Mission> missionIP = new IndirectProperty<Mission>();
game.addPropertyChangeListener(Game.CURRENT_MISSION, missionIP);
//gameIP.setTarget(tr.getGame());
//Install when in gameplay
missionIP.addTargetPropertyChangeListener(Mission.MISSION_MODE, new PropertyChangeListener(){
@Override
public void propertyChange(PropertyChangeEvent evt) {
if(evt.getNewValue()!=null && evt.getNewValue() instanceof Mission.GameplayMode
&& !(evt.getOldValue() instanceof Mission.GameplayMode)){
setViewMode(getViewMode());
setInstrumentMode(getInstrumentMode());
verifyInstrumentIndexValidity();
}
else if(evt.getNewValue()==null){
noViewMode();
setInstrumentMode(new NoInstruments());
}
}});
}//end apply(...)
public ViewMode getViewMode() {
return viewMode;
}
public void setViewMode(ViewMode viewMode) {
final ViewMode oldViewMode = viewMode;
this.viewMode = viewMode;
pcs.firePropertyChange(VIEW_MODE, oldViewMode, viewMode);
if(viewMode!=null)
viewMode.apply();
else//Remove the state
noViewMode();
verifyInstrumentIndexValidity();
}//end setViewMode
public void noViewMode(){
final WorldObject cockpit = getCockpit();
cockpit.setVisible(false);
final Camera cam = tr.mainRenderer.get().getCamera();
cam.probeForBehavior(MatchPosition.class).setOffsetMode(MatchPosition.NULL);
}
public WorldObject getCockpit() {
if(cockpit == null){
cockpit = new Cockpit(tr);
cockpit.setModel(getCockpitModel());
cockpit.addBehavior(new MatchPosition());
cockpit.addBehavior(new MatchDirection());
tr.mainRenderer.get().getCamera().getRootGrid().add(cockpit);
cockpit.setVisible(false);
cockpit.notifyPositionChange();
}
return cockpit;
}
private void setHUDVisibility(boolean visible){
if(hudVisibility==visible)
return;
this.hudVisibility=visible;
final Game game = tr.getGame();
if(game==null)
return;
final HUDSystem hud = game.getHUDSystem();
final RenderableSpacePartitioningGrid grid = tr.getDefaultGrid();
if(!visible)
grid.nonBlockingRemoveBranch (hud);
else
grid.nonBlockingAddBranch (hud);
}//end setHUDVisibility(...)
private class NoInstruments implements InstrumentMode{
@Override
public boolean apply() {
setHUDVisibility(false);
getCockpit().setVisible(false);
return true;
}
}//end NoInstruments
private class FullCockpitInstruments implements InstrumentMode{
@Override
public boolean apply() {
if(!(getViewMode() instanceof CockpitView))
return false;
getCockpit().setVisible(true);
setHUDVisibility(true);
return true;
}
}//end FullCockpitInstruments
private class HeadsUpDisplayInstruments implements InstrumentMode{
@Override
public boolean apply() {
getCockpit().setVisible(false);
setHUDVisibility(true);
return true;
}//end HeadsUpDisplayInstruments
}//end HeadsUpDisplayInstruments
private class InstrumentViewSelectPropertyChangeListener implements PropertyChangeListener {
@Override
public void propertyChange(PropertyChangeEvent evt) {
final Game game = tr.getGame();
if(game==null)
return;
final Mission mission = game.getCurrentMission();
if(mission==null)
return;
if(mission.isSatelliteView())
return;
if(!(getViewMode() instanceof CockpitView))
return;
if((Double)evt.getNewValue()>.7)
proposeInstrumentIndex(++instrumentModeItr);
}
}//end InstrumentViewSelectPropertyChangeListener
private void verifyInstrumentIndexValidity(){
proposeInstrumentIndex(instrumentModeItr);
}
public void proposeInstrumentIndex(int index){
index%=instrumentModes.length;
instrumentModeItr=index;
if(!setInstrumentMode(instrumentModes[index]))
proposeInstrumentIndex(++index);
}
private class ViewSelectPropertyChangeListener implements PropertyChangeListener {
@Override
public void propertyChange(PropertyChangeEvent evt) {
final Game game = tr.getGame();
if(game==null)
return;
final Mission mission = game.getCurrentMission();
if(mission==null)
return;
if(mission.isSatelliteView())
return;
if((Double)evt.getNewValue()>.7)
setViewMode(viewModes[viewModeItr++%viewModes.length]);
}//end propertyChange(...)
}//end ViewSelectPropertyChangeListener
public class CockpitView implements ViewMode{
@Override
public void apply(){
final Game game = tr.getGame();
if(game==null)
return;
final Player player = game.getPlayer();
if(player==null)
return;
player.setVisible(false);
final WorldObject cockpit = getCockpit();
cockpit.probeForBehavior(MatchPosition.class) .setTarget(player);
cockpit.probeForBehavior(MatchDirection.class).setTarget(player);
//cockpit.setVisible(true);//TODO: Depend on "C" value
final Camera cam = tr.mainRenderer.get().getCamera();
cam.probeForBehavior(MatchPosition.class).setOffsetMode(MatchPosition.NULL);
final RealMatrix lookAtMatrix = new Array2DRowRealMatrix( new double[][]{//Identity
new double [] {1, 0, 0, 0},
new double [] {0, 1, 0, 0},
new double [] {0, 0, 1, 0},
new double [] {0, 0, 0, 1}
});
final RealMatrix topMatrix = new Array2DRowRealMatrix( new double[][]{//Identity
new double [] {1, 0, 0, 0},
new double [] {0, 1, 0, 0},
new double [] {0, 0, 1, 0},
new double [] {0, 0, 0, 1}
});
final MatchDirection md = cam.probeForBehavior(MatchDirection.class);
md.setEnable(true);
md.setLookAtMatrix4x4 (lookAtMatrix);
md.setTopMatrix4x4 (topMatrix);
}//end apply()
}//end CockpitView
public class OutsideView implements ViewMode{
@Override
public void apply(){
final Game game = tr.getGame();
if(game==null)
return;
final Player player = game.getPlayer();
if(player==null)
return;
player.setVisible(true);
getCockpit().setVisible(false);
final Camera cam = tr.mainRenderer.get().getCamera();
final MatchPosition mp = cam.probeForBehavior(MatchPosition.class);
mp.setOffsetMode(new OffsetMode(){
private double [] workArray = new double[3];
@Override
public void processPosition(double[] position, MatchPosition mp) {
final double [] lookAt = player.getHeadingArray();
System.arraycopy(lookAt, 0, workArray, 0, 3);
workArray[1]= workArray[0]!=0&&workArray[2]!=0?0:1;
Vect3D.normalize(workArray, workArray);
Vect3D.scalarMultiply(workArray, -TAIL_DISTANCE, workArray);
Vect3D.add(position, workArray, position);
}});
final RealMatrix lookAtMatrix = new Array2DRowRealMatrix( new double[][]{//Flat to horizon
new double [] {1, 0, 0, 0},
new double [] {0, 0, 0, 0},
new double [] {0, 0, 1, 0},
new double [] {0, 0, 0, 1}
});
final RealMatrix topMatrix = new Array2DRowRealMatrix( new double[][]{//Flat to horizon
new double [] {0, 0, 0, 0},
new double [] {0, 0, 0, 1},
new double [] {0, 0, 0, 0},
new double [] {0, 0, 0, 1}
});
final MatchDirection md = cam.probeForBehavior(MatchDirection.class);
md.setEnable(true);
md.setLookAtMatrix4x4 (lookAtMatrix);
md.setTopMatrix4x4 (topMatrix);
}//end apply()
}//end ForwardChaseView
public class ChaseView implements ViewMode{
@Override
public void apply(){
final Game game = tr.getGame();
if(game==null)
return;
final Player player = game.getPlayer();
if(player==null)
return;
player.setVisible(true);
getCockpit().setVisible(false);
final Camera cam = tr.mainRenderer.get().getCamera();
final MatchPosition mp = cam.probeForBehavior(MatchPosition.class);
mp.setOffsetMode(new OffsetMode(){
private double [] workArray = new double[3];
@Override
public void processPosition(double[] position, MatchPosition mp) {
final double [] lookAt = player.getHeadingArray();
System.arraycopy(lookAt, 0, workArray, 0, 3);
Vect3D.normalize(workArray, workArray);
//Need to take care of y before x and z due to dependency order.
workArray[1]*=-TAIL_DISTANCE;
workArray[1]+= FLOAT_HEIGHT*Math.sqrt(workArray[0]*workArray[0]+workArray[2]*workArray[2]);
workArray[0]*=-TAIL_DISTANCE;
workArray[2]*=-TAIL_DISTANCE;
Vect3D.add(position, workArray, position);
}});
final RealMatrix lookAtMatrix = new Array2DRowRealMatrix( new double[][]{//Flat to horizon
new double [] {1, 0, 0, 0},
new double [] {0, 1, 0, 0},
new double [] {0, 0, 1, 0},
new double [] {0, 0, 0, 1}
});
final RealMatrix topMatrix = new Array2DRowRealMatrix( new double[][]{//Flat to horizon
new double [] {1, 0, 0, 0},
new double [] {0, 1, 0, 0},
new double [] {0, 0, 1, 0},
new double [] {0, 0, 0, 1}
});
final MatchDirection md = cam.probeForBehavior(MatchDirection.class);
md.setEnable(true);
md.setLookAtMatrix4x4 (lookAtMatrix);
md.setTopMatrix4x4 (topMatrix);
}//end apply()
}//end BehindAbove
private class Cockpit extends WorldObject implements RelevantEverywhere{
public Cockpit(TR tr) {
super(tr);
}
@Override
public boolean supportsLoop(){
return false;
}
@Override
public boolean recalcMatrixWithEachFrame(){
return true;
}
}//end Cockpit
public InstrumentMode getInstrumentMode() {
return instrumentMode;
}
public boolean setInstrumentMode(InstrumentMode instrumentMode) {
if(!INS_ENABLE)return true;
final InstrumentMode oldInstrumentMode = instrumentMode;
this.instrumentMode = instrumentMode;
pcs.firePropertyChange(INSTRUMENT_MODE, oldInstrumentMode, instrumentMode);
if(instrumentMode!=null)
return instrumentMode.apply();
else
return new HeadsUpDisplayInstruments().apply();
}//end setInstrumentMode()
public ViewMode[] getViewModes() {
return viewModes;
}
}//end ViewSelectFeature
public Model getCockpitModel() {
if(cockpitModel==null){
final GPU gpu = tr.gpu.get();
final GL3 gl = gpu.getGl();
final ColorPaletteVectorList cpvl = tr.getGlobalPaletteVL();
try{cockpitModel = tr.getResourceManager().getBINModel("COCKMDL.BIN", cpvl, null, gl);}
catch(Exception e){e.printStackTrace();}
}//end if(null)
return cockpitModel;
}//end getCockpitModel()
public void setCockpitModel(Model cockpitModel) {
this.cockpitModel = cockpitModel;
}
@Override
public Feature<Game> newInstance(Game target) {
return new ViewSelectFeature();
}
@Override
public Class<Game> getTargetClass() {
return Game.class;
}
}//end ViewChange |
package org.sahagin.share;
import org.sahagin.share.srctree.SrcTree;
import org.sahagin.share.srctree.TestClass;
import org.sahagin.share.srctree.TestFunction;
public class SrcTreeChecker {
// TODO throw error if sub class has root method
// TODO throw error if class for root method is not root class
// TODO throw error if root class is page class
private static final String MSG_INVALID_PLACEHOLDER
= "TestDoc of \"%s\" contains invalid keyword \"%s\"";
public static void check(SrcTree srcTree) throws IllegalTestScriptException {
for (TestFunction func : srcTree.getRootFuncTable().getTestFunctions()) {
if (func.getTestDoc() != null && func.getTestDoc().contains("\\")) {
// TODO support back slash
throw new RuntimeException(String.format(
"back slash is not supported: %s", func.getTestDoc()));
}
String invalidKeyword = TestDocResolver.searchInvalidPlaceholder(func);
if (invalidKeyword != null) {
throw new IllegalTestScriptException(String.format(MSG_INVALID_PLACEHOLDER,
func.getQualifiedName(), invalidKeyword));
}
}
for (TestFunction func : srcTree.getSubFuncTable().getTestFunctions()) {
if (func.getTestDoc() != null && func.getTestDoc().contains("\\")) {
// TODO support back slash
throw new RuntimeException(String.format(
"back slash is not supported: %s", func.getTestDoc()));
}
String invalidKeyword = TestDocResolver.searchInvalidPlaceholder(func);
if (invalidKeyword != null) {
throw new IllegalTestScriptException(String.format(MSG_INVALID_PLACEHOLDER,
func.getQualifiedName(), invalidKeyword));
}
}
for (TestClass testClass: srcTree.getRootClassTable().getTestClasses()) {
if (testClass.getTestDoc() != null && testClass.getTestDoc().contains("\\")) {
// TODO support back slash
throw new RuntimeException(String.format(
"back slash is not supported: %s", testClass.getTestDoc()));
}
}
for (TestClass testClass: srcTree.getSubClassTable().getTestClasses()) {
if (testClass.getTestDoc() != null && testClass.getTestDoc().contains("\\")) {
// TODO support back slash
throw new RuntimeException(String.format(
"back slash is not supported: %s", testClass.getTestDoc()));
}
}
}
} |
package org.tbax.baxshops.items;
import org.bukkit.*;
import org.bukkit.block.Block;
import org.bukkit.block.banner.Pattern;
import org.bukkit.block.banner.PatternType;
import org.bukkit.block.data.type.WallSign;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.BannerMeta;
import org.bukkit.inventory.meta.Damageable;
import org.bukkit.inventory.meta.EnchantmentStorageMeta;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.plugin.java.JavaPlugin;
import org.jetbrains.annotations.NotNull;
import org.tbax.baxshops.BaxEntry;
import org.tbax.baxshops.BaxShop;
import org.tbax.baxshops.Format;
import org.tbax.baxshops.ShopPlugin;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.util.*;
@SuppressWarnings("JavaDoc")
public final class ItemUtil
{
private static final String MINECRAFT_VERSION;
private static final Method AS_NMS_COPY;
private static final Method GET_NAME;
private static Map<Integer, Material> legacyItems = null;
private static final Map<Material, Material> SIGN_TO_SIGN = new HashMap<>();
private static final List<Material> SIGN_TYPES = Arrays.asList(Material.SPRUCE_SIGN, Material.SPRUCE_WALL_SIGN,
Material.ACACIA_SIGN, Material.ACACIA_WALL_SIGN,
Material.BIRCH_SIGN, Material.BIRCH_WALL_SIGN,
Material.DARK_OAK_SIGN, Material.DARK_OAK_WALL_SIGN,
Material.JUNGLE_SIGN, Material.JUNGLE_WALL_SIGN,
Material.OAK_SIGN, Material.OAK_WALL_SIGN,
Material.LEGACY_SIGN, Material.LEGACY_WALL_SIGN, Material.LEGACY_SIGN_POST);
static {
String name = Bukkit.getServer().getClass().getPackage().getName();
MINECRAFT_VERSION = name.substring(name.lastIndexOf('.') + 1);
Method nmsCpyMthd = null;
Method getNmMthd = null;
try {
Class<?> itemStackCls = Class.forName("net.minecraft.server." + MINECRAFT_VERSION + ".ItemStack");
nmsCpyMthd = Class.forName("org.bukkit.craftbukkit." + MINECRAFT_VERSION + ".inventory.CraftItemStack")
.getMethod("asNMSCopy", ItemStack.class);
getNmMthd = itemStackCls.getMethod("getName");
}
catch (ReflectiveOperationException e) {
e.printStackTrace();
}
AS_NMS_COPY = nmsCpyMthd;
GET_NAME = getNmMthd;
SIGN_TO_SIGN.put(Material.OAK_WALL_SIGN, Material.OAK_SIGN);
SIGN_TO_SIGN.put(Material.ACACIA_WALL_SIGN, Material.ACACIA_SIGN);
SIGN_TO_SIGN.put(Material.BIRCH_WALL_SIGN, Material.BIRCH_SIGN);
SIGN_TO_SIGN.put(Material.DARK_OAK_WALL_SIGN, Material.DARK_OAK_SIGN);
SIGN_TO_SIGN.put(Material.SPRUCE_WALL_SIGN, Material.SPRUCE_SIGN);
SIGN_TO_SIGN.put(Material.JUNGLE_WALL_SIGN, Material.JUNGLE_SIGN);
SIGN_TO_SIGN.put(Material.LEGACY_WALL_SIGN, Material.LEGACY_SIGN);
SIGN_TO_SIGN.put(Material.LEGACY_SIGN_POST, Material.LEGACY_SIGN);
}
/**
* An array of items that can be damaged
*/
private static final Map<Material, Short> damageable = new HashMap<>();
/**
* A list of enchantment names
*/
private static final Map<Enchantment, Enchantable> enchants = new HashMap<>();
private ItemUtil()
{
}
public static List<BaxEntry> getItemFromAlias(String input, BaxShop shop)
{
String[] words = input.toUpperCase().split("_");
String normalizedInput = input.replace('_', ' ').toUpperCase();
int maxMatch = -1;
List<BaxEntry> entries = new ArrayList<>();
for(BaxEntry entry : shop) {
String entryName = entry.getName().toUpperCase();
if (Objects.equals(entryName, normalizedInput)) {
return Collections.singletonList(entry); // 100% match
}
else {
String[] entryWords = entryName.split(" ");
int matches = getMatches(entryWords, words);
if (matches == maxMatch) {
entries.add(entry);
}
else if (matches > maxMatch && matches > 0) {
entries.clear();
entries.add(entry);
maxMatch = matches;
}
}
}
return entries;
}
private static int getMatches(String[] array1, String[] array2)
{
int matches = 0;
for(String word1 : array1) {
for(String word2 : array2) {
if (word1.equals(word2)) {
++matches;
}
}
}
return matches;
}
/**
* Gets the name of an item.
*
* @param entry the shop entry
* @return the item's name
*/
public static String getName(BaxEntry entry)
{
return ItemUtil.getName(entry.getItemStack());
}
/**
* Gets the name of an item.
*
* @param item an item stack
* @return the item's name
*/
public static String getName(ItemStack item)
{
if (item.getType() == Material.ENCHANTED_BOOK) {
Map<Enchantment, Integer> enchants = EnchantMap.getEnchants(item);
if (enchants != null)
return EnchantMap.fullListString(enchants);
}
else if (isOminousBanner(item)) {
return ChatColor.GOLD + "Ominous Banner";
}
item = item.clone();
ItemMeta meta = item.getItemMeta();
if (meta != null) {
meta.setDisplayName(null);
item.setItemMeta(meta);
}
try {
Object nmsCopy = AS_NMS_COPY.invoke(null, item);
Object txtObj = GET_NAME.invoke(nmsCopy);
try {
return (String) txtObj;
}
catch (ClassCastException e) {
return (String)txtObj.getClass().getMethod("getText").invoke(txtObj);
}
}
catch (ReflectiveOperationException | ClassCastException e) {
ShopPlugin.logWarning("Could not get item name for " + item.getType());
return item.getType().toString();
}
}
public static boolean isOminousBanner(@NotNull ItemStack stack)
{
if (stack.getType() != Material.WHITE_BANNER)
return false;
BannerMeta bannerMeta = (BannerMeta)stack.getItemMeta();
return bannerMeta.getPatterns().containsAll(ominousPatterns());
}
private static List<Pattern> ominousPatterns()
{
Pattern[] patterns = new Pattern[8];
patterns[0] = new Pattern(DyeColor.CYAN, PatternType.RHOMBUS_MIDDLE);
patterns[1] = new Pattern(DyeColor.LIGHT_GRAY, PatternType.STRIPE_BOTTOM);
patterns[2] = new Pattern(DyeColor.GRAY, PatternType.STRIPE_CENTER);
patterns[3] = new Pattern(DyeColor.LIGHT_GRAY, PatternType.BORDER);
patterns[4] = new Pattern(DyeColor.BLACK, PatternType.STRIPE_MIDDLE);
patterns[5] = new Pattern(DyeColor.LIGHT_GRAY, PatternType.HALF_HORIZONTAL);
patterns[6] = new Pattern(DyeColor.LIGHT_GRAY, PatternType.CIRCLE_MIDDLE);
patterns[7] = new Pattern(DyeColor.BLACK, PatternType.BORDER);
return Arrays.asList(patterns);
}
public static String getEnchantName(Enchantment enchant)
{
Enchantable enchantable = enchants.get(enchant);
if (enchantable == null)
return Format.toFriendlyName(enchant.getKey().getKey());
return enchantable.getName();
}
/**
* Determines if a material can be damaged
* @param item
* @return
*/
public static boolean isDamageable(Material item)
{
return damageable.containsKey(item);
}
/**
* Gets the maximum damage for an item. This assumes damageability
* has been confirmed with isDamageable()
* @param item
* @return
*/
public static short getMaxDamage(Material item)
{
return damageable.get(item);
}
/**
* Loads the damageable items list from the damageable.txt resource.
* @param plugin
*/
public static void loadDamageable(ShopPlugin plugin)
{
InputStream stream = plugin.getResource("damageable.txt");
if (stream == null) {
return;
}
int i = 1;
try {
BufferedReader br = new BufferedReader(new InputStreamReader(stream));
String line;
while ((line = br.readLine()) != null) {
if (line.length() == 0 || line.charAt(0) == '
continue;
}
Scanner scanner = new Scanner(line);
Material material = Material.getMaterial(scanner.next());
short maxDamage = scanner.nextShort();
damageable.put(material, maxDamage);
i++;
}
stream.close();
}
catch (IOException e) {
plugin.getLogger().warning("Failed to readFromDisk damageable: " + e.toString());
}
catch (NoSuchElementException e) {
plugin.getLogger().info("loadDamageable broke at line: " + i);
e.printStackTrace();
}
}
/**
* Loads the enchantment names in enchants.txt
* @param plugin
*/
public static void loadEnchants(ShopPlugin plugin)
{
try (InputStream stream = plugin.getResource("enchants.yml")) {
YamlConfiguration enchantConfig = YamlConfiguration.loadConfiguration(new InputStreamReader(stream));
List<Map<?, ?>> section = enchantConfig.getMapList("enchants");
for (Map<?, ?> enchantMap : section) {
Enchantment enchantment = Enchantment.getByKey(new NamespacedKey(plugin, (String)enchantMap.get("enchantment")));
String name = (String) enchantMap.get("name");
boolean levels = (Boolean) enchantMap.get("levels");
enchants.put(enchantment, new Enchantable(name, levels));
}
}
catch (IOException e) {
plugin.getLogger().warning("Failed to readFromDisk enchants: " + e.toString());
}
}
public static boolean hasEnchantLevels(Enchantment enchantment)
{
return getEnchantable(enchantment).hasLevels();
}
public static Enchantable getEnchantable(Enchantment enchantment)
{
Enchantable enchantable = enchants.get(enchantment);
if (enchantable == null)
return new Enchantable(Format.toFriendlyName(enchantment.getKey().getKey()), true);
return enchantable;
}
public static boolean isSameBanner(ItemStack stack1, ItemStack stack2)
{
BannerMeta bannerMeta1, bannerMeta2;
if (stack1.getItemMeta() instanceof BannerMeta) {
bannerMeta1 = (BannerMeta)stack1.getItemMeta();
}
else {
return false;
}
if (stack2.getItemMeta() instanceof BannerMeta) {
bannerMeta2 = (BannerMeta)stack2.getItemMeta();
}
else {
return false;
}
if (stack1.getType() != stack2.getType())
return false;
if (bannerMeta1.numberOfPatterns() != bannerMeta2.numberOfPatterns())
return false;
for (int i = 0; i < bannerMeta1.numberOfPatterns(); ++i) {
if (!bannerMeta1.getPattern(i).equals(bannerMeta2.getPattern(i))) {
return false;
}
}
return true;
}
public static boolean isSameBook(ItemStack stack1, ItemStack stack2)
{
EnchantmentStorageMeta enchantmentMeta1, enchantmentMeta2;
if (stack1.getType() != Material.ENCHANTED_BOOK || stack2.getType() != Material.ENCHANTED_BOOK) {
return false;
}
enchantmentMeta1 = (EnchantmentStorageMeta)stack1.getItemMeta();
enchantmentMeta2 = (EnchantmentStorageMeta)stack2.getItemMeta();
if (enchantmentMeta1.getStoredEnchants().size() != enchantmentMeta2.getStoredEnchants().size()) {
return false;
}
for (Map.Entry<Enchantment, Integer> enchants : enchantmentMeta1.getStoredEnchants().entrySet()) {
if (!Objects.equals(enchantmentMeta2.getStoredEnchants().get(enchants.getKey()), enchants.getValue())) {
return false;
}
}
return true;
}
public static boolean isSimilar(ItemStack stack1, ItemStack stack2, boolean smartStack)
{
if (stack1 == stack2) return true;
if (stack1 == null || stack2 == null) return false;
if (!smartStack) return stack1.isSimilar(stack2);
if (!stack1.isSimilar(stack2)) {
return stack1.getType() == stack2.getType() &&
(isSameBook(stack1, stack2)
|| isSameBanner(stack1, stack2));
}
return true;
}
public static boolean isShop(ItemStack item)
{
return isSign(item)&&
item.hasItemMeta() &&
item.getItemMeta().hasLore() &&
item.getItemMeta().getLore().get(item.getItemMeta().getLore().size() - 1).startsWith(ChatColor.GRAY + "ID: ");
}
public static boolean isSign(ItemStack item)
{
return item != null && isSign(item.getType());
}
public static boolean isSign(Material type)
{
return type != null && SIGN_TYPES.contains(type);
}
public static BaxShop fromItem(ItemStack item)
{
String id = item.getItemMeta().getLore().get(item.getItemMeta().getLore().size() - 1).substring((ChatColor.GRAY + "ID: ").length());
BaxShop shop = ShopPlugin.getShopByShortId2(id); // try short id2
if (shop == null) {
shop = ShopPlugin.getShopByShortId(id); // try short id
if (shop == null) {
try {
return ShopPlugin.getShop(UUID.fromString(id)); // finally try full id
}
catch (IllegalArgumentException e) {
return null;
}
}
}
return shop;
}
public static String[] extractSignText(ItemStack item)
{
List<String> lore = item.getItemMeta().getLore().subList(0, item.getItemMeta().getLore().size() - 1);
String[] lines = new String[lore.size()];
for(int i = 0; i < lines.length; ++i) {
lines[i] = ChatColor.stripColor(lore.get(i));
}
return lines;
}
public static List<Material> getSignTypes()
{
return SIGN_TYPES;
}
public static ItemStack newDefaultSign()
{
return new ItemStack(getDefaultSignType(), 1);
}
public static Material getDefaultSignType()
{
return Material.OAK_SIGN;
}
public static Material toInventorySign(Material sign)
{
Material m = SIGN_TO_SIGN.get(sign);
return m == null ? sign : m;
}
public static Map<Integer, ? extends ItemStack> all(Inventory inventory, List<Material> materials)
{
Map<Integer, ItemStack> all = new HashMap<>();
for (Material material : materials) {
for(Map.Entry<? extends Integer, ? extends ItemStack> entry : inventory.all(material).entrySet()) {
all.put(entry.getKey(), entry.getValue());
}
}
return all;
}
@Deprecated
public static ItemStack fromItemId(int id)
{
return fromItemId(id, (short)0);
}
@Deprecated
public static ItemStack fromItemId(int id, short damage)
{
Material type = legacyItems.get(id);
if (type == null) return null;
return new ItemStack(type, 1, damage);
}
@Deprecated
public static Map<Integer, Material> getLegacyItems()
{
return legacyItems;
}
@Deprecated
public static Map<Integer, Material> loadLegacyItems(JavaPlugin plugin) throws IOException
{
legacyItems = new HashMap<>();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(plugin.getResource("legacy_items.txt")))) {
String line;
while((line = reader.readLine()) != null) {
int idx = line.indexOf(' ');
int id = Integer.parseInt(line.substring(0, idx));
Material material = Material.getMaterial(line.substring(idx).trim());
legacyItems.put(id, material);
}
}
return legacyItems;
}
public static int getDurability(ItemStack stack)
{
if (stack.getItemMeta() instanceof Damageable) {
Damageable damage = (Damageable) stack.getItemMeta();
return damage.getDamage();
}
return 0;
}
public static void setDurability(ItemStack stack, int durability)
{
if (stack.getItemMeta() instanceof Damageable) {
Damageable damage = (Damageable) stack.getItemMeta();
damage.setDamage(durability);
stack.setItemMeta((ItemMeta)damage);
}
}
public static List<Block> getSignOnBlock(Block block)
{
List<Block> signs = new ArrayList<>();
for (int x = -1; x <= 1; ++x) {
for (int y = -1; y <= 1; ++y) {
for(int z = -1; z <= 1; ++z) {
Location l = block.getLocation().add(x, y, z);
Block curr = l.getBlock();
if (ItemUtil.isSign(curr.getType())) {
if (curr.getBlockData() instanceof WallSign) {
WallSign sign = (WallSign)curr.getBlockData();
Block attached = curr.getRelative(sign.getFacing().getOppositeFace());
if (attached.getLocation().equals(block.getLocation())) {
signs.add(curr);
}
}
else {
Location below = l.subtract(0, 1, 0);
if (below.equals(block.getLocation())) {
signs.add(curr);
}
}
}
}
}
}
return signs;
}
} |
package org.testng;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
* A {@link SkipException} extension that transforms a skipped method
* into a failed method based on a time trigger.
* <p/>
* By default the time format is yyyy/MM/dd (according to {@code SimpleDateFormat}).
* You can customize this by using the specialized constructors. Suppported date
* formats are according to the {@code SimpleDateFormat}.
*
* @author <a href='mailto:the[dot]mindstorm[at]gmail[dot]com'>Alex Popescu</a>
* @since 5.6
*/
public class TimeBombSkipException extends SkipException {
private static final long serialVersionUID = -8599821478834048537L;
private static final SimpleDateFormat SDF= new SimpleDateFormat("yyyy/MM/dd");
private Calendar m_expireDate;
private DateFormat m_inFormat= SDF;
private DateFormat m_outFormat= SDF;
/**
* Creates a {@code TimeBombedSkipException} using the <tt>expirationDate</tt>.
* The format used for date comparison is <tt>yyyy/MM/dd</tt>
* @param msg exception message
* @param expirationDate time limit after which the SKIP becomes a FAILURE
*/
public TimeBombSkipException(String msg, Date expirationDate) {
super(msg);
initExpireDate(expirationDate);
}
/**
* Creates a {@code TimeBombedSkipException} using the <tt>expirationDate</tt>.
* The <tt>format</tt> parameter wiil be used for performing the time comparison.
* @param msg exception message
* @param expirationDate time limit after which the SKIP becomes a FAILURE
* @param format format for the time comparison
*/
public TimeBombSkipException(String msg, Date expirationDate, String format) {
super(msg);
m_inFormat= new SimpleDateFormat(format);
m_outFormat= new SimpleDateFormat(format);
initExpireDate(expirationDate);
}
/**
* Creates a {@code TimeBombedSkipException} using the <tt>date</tt>
* in the format <tt>yyyy/MM/dd</tt>.
* @param msg exception message
* @param date time limit after which the SKIP becomes a FAILURE
*/
public TimeBombSkipException(String msg, String date) {
super(msg);
initExpireDate(date);
}
/**
* Creates a {@code TimeBombedSkipException} using the <tt>date</tt>
* in the specified format <tt>format</tt>. The same format is used
* when performing the time comparison.
* @param msg exception message
* @param date time limit after which the SKIP becomes a FAILURE
* @param format format of the passed in <tt>date</tt> and of the time comparison
*/
public TimeBombSkipException(String msg, String date, String format) {
this(msg, date, format, format);
}
/**
* Creates a {@code TimeBombedSkipException} using the <tt>date</tt>
* in the specified format <tt>inFormat</tt>. The <tt>outFormat</tt> will be
* used to perform the time comparison and display.
* @param msg exception message
* @param date time limit after which the SKIP becomes a FAILURE
* @param inFormat format of the passed in <tt>date</tt>
* @param outFormat format of the time comparison
*/
public TimeBombSkipException(String msg, String date, String inFormat, String outFormat) {
super(msg);
m_inFormat= new SimpleDateFormat(inFormat);
m_outFormat= new SimpleDateFormat(outFormat);
initExpireDate(date);
}
/**
* Creates a {@code TimeBombedSkipException} using the <tt>expirationDate</tt>.
* The format used for date comparison is <tt>yyyy/MM/dd</tt>
* @param msg exception message
* @param expirationDate time limit after which the SKIP becomes a FAILURE
* @param cause the cause (which is saved for later retrieval by the
* {@link #getCause()} method). (A <tt>null</tt> value is
* permitted, and indicates that the cause is nonexistent or
* unknown.)
*/
public TimeBombSkipException(String msg, Date expirationDate, Throwable cause) {
super(msg, cause);
initExpireDate(expirationDate);
}
/**
* Creates a {@code TimeBombedSkipException} using the <tt>expirationDate</tt>.
* The <tt>format</tt> parameter wiil be used for performing the time comparison.
* @param msg exception message
* @param expirationDate time limit after which the SKIP becomes a FAILURE
* @param format format for the time comparison
* @param cause the cause (which is saved for later retrieval by the
* {@link #getCause()} method). (A <tt>null</tt> value is
* permitted, and indicates that the cause is nonexistent or
* unknown.)
*/
public TimeBombSkipException(String msg, Date expirationDate, String format, Throwable cause) {
super(msg, cause);
m_inFormat= new SimpleDateFormat(format);
m_outFormat= new SimpleDateFormat(format);
initExpireDate(expirationDate);
}
/**
* Creates a {@code TimeBombedSkipException} using the <tt>date</tt>
* in the format <tt>yyyy/MM/dd</tt>.
* @param msg exception message
* @param date time limit after which the SKIP becomes a FAILURE
* @param cause the cause (which is saved for later retrieval by the
* {@link #getCause()} method). (A <tt>null</tt> value is
* permitted, and indicates that the cause is nonexistent or
* unknown.)
*/
public TimeBombSkipException(String msg, String date, Throwable cause) {
super(msg, cause);
initExpireDate(date);
}
/**
* Creates a {@code TimeBombedSkipException} using the <tt>date</tt>
* in the specified format <tt>format</tt>. The same format is used
* when performing the time comparison.
* @param msg exception message
* @param date time limit after which the SKIP becomes a FAILURE
* @param format format of the passed in <tt>date</tt> and of the time comparison
* @param cause the cause (which is saved for later retrieval by the
* {@link #getCause()} method). (A <tt>null</tt> value is
* permitted, and indicates that the cause is nonexistent or
* unknown.)
*/
public TimeBombSkipException(String msg, String date, String format, Throwable cause) {
this(msg, date, format, format, cause);
}
/**
* Creates a {@code TimeBombedSkipException} using the <tt>date</tt>
* in the specified format <tt>inFormat</tt>. The <tt>outFormat</tt> will be
* used to perform the time comparison and display.
* @param msg exception message
* @param date time limit after which the SKIP becomes a FAILURE
* @param inFormat format of the passed in <tt>date</tt>
* @param outFormat format of the time comparison
* @param cause the cause (which is saved for later retrieval by the
* {@link #getCause()} method). (A <tt>null</tt> value is
* permitted, and indicates that the cause is nonexistent or
* unknown.)
*/
public TimeBombSkipException(String msg, String date, String inFormat, String outFormat, Throwable cause) {
super(msg, cause);
m_inFormat= new SimpleDateFormat(inFormat);
m_outFormat= new SimpleDateFormat(outFormat);
initExpireDate(date);
}
private void initExpireDate(Date expireDate) {
m_expireDate= Calendar.getInstance();
m_expireDate.setTime(expireDate);
}
private void initExpireDate(String date) {
try {
// SimpleDateFormat is not thread-safe, and m_inFormat
// is, by default, connected to the static SDF variable
synchronized( m_inFormat ){
Date d = m_inFormat.parse(date);
initExpireDate(d);
}
}
catch(ParseException pex) {
throw new TestNGException("Cannot parse date:" + date + " using pattern: " + m_inFormat, pex);
}
}
@Override
public boolean isSkip() {
if (null == m_expireDate) {
return false;
}
try {
Calendar now= Calendar.getInstance();
Date nowDate= m_inFormat.parse(m_inFormat.format(now.getTime()));
now.setTime(nowDate);
return !now.after(m_expireDate);
}
catch(ParseException pex) {
throw new TestNGException("Cannot compare dates.");
}
}
@Override
public String getMessage() {
if(isSkip()) {
return super.getMessage();
}
else {
return super.getMessage() + "; Test must have been enabled by: " + m_outFormat.format(m_expireDate.getTime());
}
}
@Override
public void printStackTrace(PrintStream s) {
reduceStackTrace();
super.printStackTrace(s);
}
@Override
public void printStackTrace(PrintWriter s) {
reduceStackTrace();
super.printStackTrace(s);
}
} |
package org.trello4j.core;
import java.net.URI;
import java.util.Map;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
import org.trello4j.TrelloException;
import org.trello4j.TrelloURI;
//TODO Remove class and move methods to TrelloTemplate
class TrelloAccessor {
// TODO: Reduce scope after refactoring
public final String apiKey;
public final String accessToken;
private final RestTemplate restTemplate;
TrelloAccessor(String apiKey, String accessToken) {
if (apiKey == null) {
throw new TrelloException("API key must be set, get one here: https://trello.com/1/appKey/generate");
}
this.apiKey = apiKey;
this.accessToken = accessToken;
this.restTemplate = new RestTemplate();
}
<T> T doGet(String uri, Class<T> responseType) {
try {
return restTemplate.exchange(uri, HttpMethod.GET, HttpEntity.EMPTY, responseType).getBody();
} catch (Exception e) {
return null;
}
}
<T> T doGet(String uri, ParameterizedTypeReference<T> typeReference) {
try {
return restTemplate.exchange(uri, HttpMethod.GET, HttpEntity.EMPTY, typeReference).getBody();
} catch (Exception e) {
return null;
}
}
boolean doPost(String uri, Map<String, ?> data) {
try {
restTemplate.exchange(buildUri(uri, data), HttpMethod.POST, HttpEntity.EMPTY, Object.class).getBody();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
<T> T doPost(String uri, Map<String, ?> data, Class<T> responseType) {
try {
return restTemplate.exchange(buildUri(uri, data), HttpMethod.POST, HttpEntity.EMPTY, responseType).getBody();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
<T> T doPost(String uri, Map<String, ?> data, ParameterizedTypeReference<T> typeReference) {
try {
return restTemplate.exchange(uri, HttpMethod.POST, HttpEntity.EMPTY, typeReference, data).getBody();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
boolean doPut(String uri, Map<String, ?> data) {
try {
restTemplate.exchange(buildUri(uri, data), HttpMethod.PUT, HttpEntity.EMPTY, Object.class).getBody();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
<T> T doPut(String uri, Map<String, ?> data, Class<T> responseType) {
try {
return restTemplate.exchange(buildUri(uri, data), HttpMethod.PUT, HttpEntity.EMPTY, responseType).getBody();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
<T> T doPut(String uri, Map<String, ?> data, ParameterizedTypeReference<T> typeReference) {
try {
return restTemplate.exchange(buildUri(uri, data), HttpMethod.PUT, HttpEntity.EMPTY, typeReference).getBody();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
boolean doDelete(String uri) {
try {
restTemplate.delete(uri);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public TrelloURI createTrelloUri(String uriTemplate, String... resources) {
return new TrelloURI(apiKey, accessToken, uriTemplate, resources);
}
private static URI buildUri(String uri, Map<String, ?> params) {
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(uri);
for (Map.Entry<String, ?> entry : params.entrySet()) {
builder = builder.queryParam(entry.getKey(), entry.getValue());
}
return builder.build().encode().toUri();
}
} |
package org.usfirst.frc.team4828;
import com.ctre.CANTalon;
import edu.wpi.first.wpilibj.Servo;
public class Shooter extends Thread {
private CANTalon shooterMotor;
private Servo indexer;
public ServoGroup servos;
private static final double SHOOTER_SPEED = 0.8;
private static final double SERVO_MULTIPLIER = 0.8;
private static final double P = .5;
private static final double I = 0;
private static final double D = 0;
private double indexerOpen = .8;
private double indexerClose = .2;
/**
* Create shooter object that encapsulates all associated servos and motors.
*
* @param motorPort port of main shooter wheel
* @param indexerPort port of indexer servo
* @param masterPort port of master angle control servo
* @param slavePort port of slave angle control servo
*/
public Shooter(int motorPort, int indexerPort, int masterPort, int slavePort) {
shooterMotor = new CANTalon(motorPort);
shooterMotor.changeControlMode(CANTalon.TalonControlMode.Speed);
shooterMotor.setPID(P, I, D);
indexer = new Servo(indexerPort);
servos = new ServoGroup(masterPort, slavePort);
}
/**
* Calibrates the indexer
*
* @param open double 0-1 open position
* @param close double 0-1 close position
*/
public void calibrateIndexer(double open, double close){
indexerOpen = open;
indexerClose = close;
}
public void spinUp() {
shooterMotor.set(SHOOTER_SPEED * (1 - servos.get() * SERVO_MULTIPLIER));
}
/**
* Start the shooter wheel.
*
* @param speed double 0-1 dictates fire speed
*/
public void spinUp(double speed) {
shooterMotor.set(speed * (1 - servos.get() * SERVO_MULTIPLIER));
}
/**
* Slow the shooter wheel to a halt.
*/
public void spinDown() {
shooterMotor.set(0);
}
/**
* Open indexer servo to allow fuel to contact the shooter wheel
*/
public void startShooter(){
indexer.set(indexerOpen);
}
/**
* Close indexer servo to block fuel from contacting the shooter wheel
*/
public void stopShooter(){
indexer.set(indexerClose);
}
/**
* Change the shooter motor back to normal speed control instead of PID.
*
* If they don't give us enough time to calibrate shooter PID, we will
* have to resort to the tried and true way of spinning the shooter
* wheel and not worry about it slowing down from contacting fuel.
*/
public void superSecretSafetyBackup(){
shooterMotor.changeControlMode(CANTalon.TalonControlMode.PercentVbus);
}
} |
package ru.r2cloud.predict;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import org.hipparchus.ode.events.Action;
import org.hipparchus.util.FastMath;
import org.orekit.bodies.BodyShape;
import org.orekit.bodies.GeodeticPoint;
import org.orekit.bodies.OneAxisEllipsoid;
import org.orekit.data.DataContext;
import org.orekit.data.DataProvidersManager;
import org.orekit.data.DirectoryCrawler;
import org.orekit.frames.Frame;
import org.orekit.frames.FramesFactory;
import org.orekit.frames.TopocentricFrame;
import org.orekit.propagation.SpacecraftState;
import org.orekit.propagation.analytical.tle.TLEPropagator;
import org.orekit.propagation.events.ElevationDetector;
import org.orekit.propagation.events.ElevationExtremumDetector;
import org.orekit.propagation.events.EventDetector;
import org.orekit.propagation.events.EventSlopeFilter;
import org.orekit.propagation.events.FilterType;
import org.orekit.propagation.events.handlers.EventHandler;
import org.orekit.time.AbsoluteDate;
import org.orekit.time.TimeScalesFactory;
import org.orekit.utils.Constants;
import org.orekit.utils.IERSConventions;
import org.orekit.utils.PVCoordinates;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.r2cloud.model.SatPass;
import ru.r2cloud.rotctrld.Position;
import ru.r2cloud.util.Configuration;
public class PredictOreKit {
private static final double PREDICT_INTERVAL = 3600. * 24 * 2;
private static final Logger LOG = LoggerFactory.getLogger(PredictOreKit.class);
private static final double SPEED_OF_LIGHT = 2.99792458E8;
private final double minElevation;
private final double guaranteedElevation;
private final Configuration config;
private final Frame earthFrame;
private final BodyShape earth;
public PredictOreKit(Configuration config) {
this.minElevation = config.getDouble("scheduler.elevation.min");
this.guaranteedElevation = config.getDouble("scheduler.elevation.guaranteed");
this.config = config;
File orekitData = new File(config.getProperty("scheduler.orekit.path"));
if (!orekitData.exists()) {
LOG.info("orekit master data doesn't exist. downloading now. it might take some time");
OreKitDataClient client = new OreKitDataClient(config.getProperties("scheduler.orekit.urls"));
try {
client.downloadAndSaveTo(orekitData.toPath());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
DataProvidersManager manager = DataContext.getDefault().getDataProvidersManager();
manager.addProvider(new DirectoryCrawler(orekitData));
earthFrame = FramesFactory.getITRF(IERSConventions.IERS_2010, true);
earth = new OneAxisEllipsoid(Constants.WGS84_EARTH_EQUATORIAL_RADIUS, Constants.WGS84_EARTH_FLATTENING, earthFrame);
}
public Long getDownlinkFreq(final Long freq, final long utcTimeMillis, TopocentricFrame currentLocation, final TLEPropagator tlePropagator) {
AbsoluteDate date = new AbsoluteDate(new Date(utcTimeMillis), TimeScalesFactory.getUTC());
PVCoordinates currentState = tlePropagator.getPVCoordinates(date);
final double rangeRate = currentLocation.getRangeRate(currentState, tlePropagator.getFrame(), date);
return (long) ((double) freq * (SPEED_OF_LIGHT - rangeRate) / SPEED_OF_LIGHT);
}
public Position getSatellitePosition(long utcTimeMillis, TopocentricFrame currentLocation, final TLEPropagator tlePropagator) {
AbsoluteDate date = new AbsoluteDate(new Date(utcTimeMillis), TimeScalesFactory.getUTC());
PVCoordinates currentState = tlePropagator.getPVCoordinates(date);
double azimuth = FastMath.toDegrees(currentLocation.getAzimuth(currentState.getPosition(), tlePropagator.getFrame(), date));
double elevation = FastMath.toDegrees(currentLocation.getElevation(currentState.getPosition(), tlePropagator.getFrame(), date));
Position result = new Position();
result.setAzimuth(azimuth);
result.setElevation(elevation);
return result;
}
public List<SatPass> calculateSchedule(Date current, TLEPropagator tlePropagator) {
List<SatPass> result = new ArrayList<>();
TopocentricFrame baseStationFrame = getPosition();
if (baseStationFrame == null) {
return Collections.emptyList();
}
AbsoluteDate initialDate = new AbsoluteDate(current, TimeScalesFactory.getUTC());
List<AbsoluteDate> max = new ArrayList<>();
ElevationExtremumDetector maxDetector = new ElevationExtremumDetector(600, 1, baseStationFrame).withMaxIter(48 * 60).withHandler(new EventHandler<ElevationExtremumDetector>() {
@Override
public Action eventOccurred(SpacecraftState s, ElevationExtremumDetector detector, boolean increasing) {
if (FastMath.toDegrees(detector.getElevation(s)) > guaranteedElevation) {
max.add(s.getDate());
}
return Action.CONTINUE;
}
});
tlePropagator.clearEventsDetectors();
tlePropagator.addEventDetector(new EventSlopeFilter<EventDetector>(maxDetector, FilterType.TRIGGER_ONLY_DECREASING_EVENTS));
tlePropagator.setSlaveMode();
tlePropagator.propagate(initialDate, new AbsoluteDate(initialDate, PREDICT_INTERVAL));
for (AbsoluteDate curMax : max) {
SatPass cur = findStartEnd(tlePropagator, baseStationFrame, curMax);
if (cur != null) {
if (cur.getStartMillis() < current.getTime()) {
cur.setStart(initialDate);
}
result.add(cur);
}
}
return result;
}
public SatPass calculateNext(Date current, TLEPropagator tlePropagator) {
TopocentricFrame baseStationFrame = getPosition();
if (baseStationFrame == null) {
return null;
}
AbsoluteDate initialDate = new AbsoluteDate(current, TimeScalesFactory.getUTC());
MaxElevationHandler maxElevationHandler = new MaxElevationHandler(guaranteedElevation);
ElevationExtremumDetector maxDetector = new ElevationExtremumDetector(600, 1, baseStationFrame).withMaxIter(48 * 60).withHandler(maxElevationHandler);
tlePropagator.clearEventsDetectors();
tlePropagator.addEventDetector(new EventSlopeFilter<EventDetector>(maxDetector, FilterType.TRIGGER_ONLY_DECREASING_EVENTS));
tlePropagator.setSlaveMode();
tlePropagator.propagate(initialDate, new AbsoluteDate(initialDate, PREDICT_INTERVAL));
if (maxElevationHandler.getDate() == null) {
return null;
}
return findStartEnd(tlePropagator, baseStationFrame, maxElevationHandler.getDate());
}
private SatPass findStartEnd(TLEPropagator tlePropagator, TopocentricFrame baseStationFrame, AbsoluteDate maxElevationTime) {
MinElevationHandler minElevationHandler = new MinElevationHandler();
ElevationDetector boundsDetector = new ElevationDetector(600, 1, baseStationFrame).withConstantElevation(FastMath.toRadians(minElevation)).withHandler(minElevationHandler);
tlePropagator.clearEventsDetectors();
tlePropagator.addEventDetector(boundsDetector);
// 20 mins before and 20 mins later
AbsoluteDate startDate = maxElevationTime.shiftedBy(-20 * 60.0);
tlePropagator.propagate(startDate, startDate.shiftedBy(40 * 60.0));
if (minElevationHandler.getStart() == null || minElevationHandler.getEnd() == null) {
return null;
}
SatPass result = new SatPass();
result.setStart(minElevationHandler.getStart());
result.setEnd(minElevationHandler.getEnd());
return result;
}
public TopocentricFrame getPosition() {
// get the current position
Double lat = config.getDouble("locaiton.lat");
Double lon = config.getDouble("locaiton.lon");
if (lat == null || lon == null) {
return null;
}
return getPosition(new GeodeticPoint(FastMath.toRadians(lat), FastMath.toRadians(lon), 0.0));
}
public TopocentricFrame getPosition(GeodeticPoint point) {
return new TopocentricFrame(earth, point, "station1");
}
} |
package sams.steven.algorithms;
/**
* Title: Merge Sort Algorithm
* Description: A Divide and Conquer algorithm to sort an array of random values into ascending order
* Company: DISC Brunel University
* @author Steven Sams
* @version 1.0
*/
public class MergeSort
{
private static void merge(int[] a, int start, int mid, int end) {
// size of the array be merged
int n = end - start + 1;
// intermediate storing array
int[] temp = new int[n];
// first element in the left sub array
int left = start;
// next element in the right sub array
int right = mid + 1;
// next position in temp
int j = 0;
/* Move the smaller element from left or right into temp while left and right have elements
left to compare, continue while the left and right sub arrays have elements remaining */
while (left <= mid && right <= end) {
if (a[left] < a[right]) { //when left sub array element is smaller than the corresponding right sub array element
temp[j] = a[left]; //copy left sub array element into its correct position in temp array
left++; //increment left sub array to the next element to be checked
} else { //when right sub array element is smaller than the corresponding left sub array element
temp[j] = a[right];
right++;
}
j++;
}
/* The proceeding two while loops are mutually exclusive
copy any remaining entries of the left sub array */
while (left <= mid) {
temp[j] = a[left];
left++;
j++;
}
// copy any remaining entries of the right sub array
while (right <= end) {
temp[j] = a[right];
right++;
j++;
}
// copy from the temp array
for (j = 0; j < n; j++)
a[start + j] = temp[j];
}
private static void sort(int[] a, int start, int end) {
if (start == end) // the direct solution, list has 1 element and is therefore sorted
return; // return to caller
int mid = (start + end) / 2; // find the centre element of the array
sort(a, start, mid); // recursively split the array down
sort(a, mid + 1, end); // along its centre element
merge(a, start, mid, end); // sub array recursively sorted up
}
} |
package se.lth.cs.connect.routes;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import iot.jcypher.database.IDBAccess;
// required for building queries and interpreting query results
import iot.jcypher.graph.GrNode;
import iot.jcypher.query.JcQueryResult;
import iot.jcypher.query.api.IClause;
import iot.jcypher.query.factories.clause.MATCH;
import iot.jcypher.query.factories.clause.OPTIONAL_MATCH;
import iot.jcypher.query.factories.clause.RETURN;
import iot.jcypher.query.factories.clause.WHERE;
import iot.jcypher.query.values.JcCollection;
import iot.jcypher.query.values.JcNode;
import iot.jcypher.query.values.JcRelation;
import ro.pippo.core.Messages;
import ro.pippo.core.PippoConstants;
import ro.pippo.core.PippoSettings;
import se.lth.cs.connect.Connect;
import se.lth.cs.connect.Graph;
import se.lth.cs.connect.RequestException;
import se.lth.cs.connect.TrustLevel;
import se.lth.cs.connect.modules.AccountSystem;
import se.lth.cs.connect.modules.Database;
import se.lth.cs.connect.modules.Mailman;
/**
* Handles account related actions.
*/
public class Account extends BackendRouter {
private String registerTemplate,
resetPasswordRequestTemplate,
resetPasswordSuccessTemplate,
notifyAdminOnVerify;
private String hostname, frontend, adminEmail;
/**
* Return an UTF-8, percent-encoded string. Used for base64-encoded tokens.
*/
private String urlencode(String toencode) {
try {
return URLEncoder.encode(toencode, PippoConstants.UTF8);
} catch (UnsupportedEncodingException uce) {
return toencode;
}
}
public Account(Connect app) {
super(app);
Messages msg = app.getMessages();
registerTemplate = msg.get("pippo.register", "en");
resetPasswordRequestTemplate = msg.get("pippo.passwordresetrequest", "en");
resetPasswordSuccessTemplate = msg.get("pippo.passwordresetsuccess", "en");
notifyAdminOnVerify = msg.get("pippo.notifyadminonverify", "en");
hostname = app.getPippoSettings().getString("hostname", "http://localhost:8080");
frontend = app.getPippoSettings().getString("frontend", "http://localhost:8181");
adminEmail = app.getPippoSettings().getString("administrator.email", "en");
}
private List<GrNode> queryCollections(IDBAccess access, String email, String rel) {
final JcNode coll = new JcNode("coll");
return Database.query(access, new IClause[]{
MATCH.node().label("user").property("email").value(email)
.relation().type(rel).node(coll).label("collection"),
RETURN.DISTINCT().value(coll)
}).resultOf(coll);
}
protected void setup(PippoSettings conf) {
// POST api.serp.se/v1/account/login HTTP/1.1
// email=...&passw=...
POST("/login", (rc) -> {
String email = rc.getParameter("email").toString();
String passw = rc.getParameter("passw").toString();
if (rc.getParameter("email").isEmpty())
throw new RequestException("Must provide an email using 'email'");
if (rc.getParameter("passw").isEmpty())
throw new RequestException("Must provide a password using 'passw'");
if (AccountSystem.authenticate(email, passw)) {
rc.resetSession();
rc.setSession("email", email);
rc.getResponse().ok();
} else {
throw new RequestException("Invalid email/password combination.");
}
});
// POST api.serp.se/v1/account/register HTTP/1.1
// email=...&passw=...
POST("/register", (rc) -> {
String email = rc.getParameter("email").toString();
String passw = rc.getParameter("passw").toString();
if (rc.getParameter("email").isEmpty())
throw new RequestException("Must specify an email address using 'email'.");
if (rc.getParameter("passw").isEmpty())
throw new RequestException("Must specify a password using 'passw'.");
if (!AccountSystem.createAccount(email, passw, TrustLevel.REGISTERED))
throw new RequestException("Email is already registered.");
String token = urlencode(AccountSystem.generateEmailToken(email));
String message = registerTemplate
.replace("{token}", token)
.replace("{hostname}", hostname);
app.getMailClient().
sendEmail(email, "SERP connect registration", message);
rc.resetSession();
rc.setSession("email", email);
rc.getResponse().ok();
});
// GET api.serp.se/v1/account/reset-password?email=... HTTP/1.1
POST("/reset-password", (rc) -> {
// randomize new password and send it to user
String email = rc.getParameter("email").toString();
if (rc.getParameter("email").isEmpty()) {
throw new RequestException("Must provide an email.");
} else if (AccountSystem.findByEmail(email) == null) {
throw new RequestException("Email is not registered.");
} else {
String token = urlencode(AccountSystem.generatePasswordToken(email));
String message = resetPasswordRequestTemplate
.replace("{token}", token)
.replace("{hostname}", hostname);
app.getMailClient().
sendEmail(email, "Password reset request", message);
rc.getResponse().ok();
}
});
GET("/friends", (rc)->{
final JcNode coll = new JcNode("coll");
//find all collections that a user have
String email = rc.getParameter("email").toString();
List<GrNode> res = Database.query(rc.getLocal("db"), new IClause[]{
MATCH.node().label("user").property("email").value(email)
.relation().type("MEMBER_OF").node(coll).label("collection"),
RETURN.DISTINCT().value(coll)
}).resultOf(coll);
Set<GrNode> total = new HashSet<GrNode>();
JcNode u = new JcNode("u");
boolean found;
//loop through all those collections and add all members inside the collections
for(int i=0; i<res.size(); i++){
List<GrNode> res2 = Database.query(rc.getLocal("db"), new IClause[]{
MATCH.node(u).label("user")
.relation().type("MEMBER_OF")
.node(coll).label("collection"),
WHERE.valueOf(coll.id()).EQUALS(res.get(0).getId()),
RETURN.DISTINCT().value(u)
}).resultOf(u);
found = false;
for(int j=0; j<res2.size(); j++){
Iterator<GrNode> it = total.iterator();
while(it.hasNext()){
if(it.next().getId()==res2.get(j).getId()){
found=true;
break;
}
}
if(!found){
total.add(res2.get(j));
}
}
}
Iterator<GrNode> it = total.iterator();
String[] ret = new String[total.size()];
int i=0;
while(it.hasNext()){
ret[i]=it.next().getProperty("email").toString().split("= ")[1];
i++;
}
rc.json().send(ret);
});
// GET api.serp.se/v1/account/reset-password?token=igotmypermitrighthere HTTP/1.1
GET("/reset-password", (rc) -> {
String token = rc.getParameter("token").toString();
if (rc.getParameter("token").isEmpty())
throw new RequestException("Must provide a reset token");
String email = AccountSystem.verifyResetPasswordToken(token);
if (email == null)
throw new RequestException("Invalid reset token!");
rc.resetSession();
rc.setSession("resetemail", email);
rc.redirect(frontend + "/resetpassword.html");
});
// POST api.serp.se/v1/account/reset-password-confirm
// passw=...
POST("/reset-password-confirm",(rc)-> {
if(rc.getSession("resetemail") == null)
throw new RequestException("Session 'resetemail' is not set");
if(rc.getParameter("passw").isEmpty()){
throw new RequestException("Must provide a password.");
}
String email = rc.getSession("resetemail").toString();
String password = rc.getParameter("passw").toString();
AccountSystem.changePassword(email, password);
rc.resetSession();
rc.setSession("email", email);
rc.getResponse().ok();
});
// GET api.serp.se/v1/account/verify?token=verifyaccounttoken HTTP/1.1
GET("/verify", (rc) -> {
String token = rc.getParameter("token").toString();
if (rc.getParameter("token").isEmpty())
throw new RequestException("Must provide a token.");
String email = AccountSystem.verifyEmail(token);
if (email == null)
throw new RequestException("Invalid token: " + token);
String message = notifyAdminOnVerify.replace("{email}", email);
app.getMailClient().
sendEmail(adminEmail, "SERP connect email registration", message);
rc.resetSession();
rc.setSession("email", email);
rc.redirect(frontend + "/profile.html");
});
// -- REQUIRES LOGIN --
ALL("/.*", (rc) -> {
if (rc.getSession("email") == null) {
throw new RequestException(401, "Not logged in.");
}
rc.next();
});
// GET api.serp.se/v1/account/login HTTP/1.1
GET("/login", (rc) -> {
rc.getResponse().ok();
});
// GET api.serp.se/v1/account/self HTTP/1.1
GET("/collections", (rc) -> {
final List<GrNode> groups = queryCollections(rc.getLocal("db"), rc.getSession("email"), "MEMBER_OF");
rc.status(200).json().send(Graph.Collection.fromList(groups));
});
// GET api.serp.se/v1/account/self HTTP/1.1
GET("/self", (rc) -> {
AccountSystem.Account user = AccountSystem.findByEmail(rc.getSession("email"));
final JcNode coll = new JcNode("coll");
final JcNode entry = new JcNode("entry");
JcQueryResult res = Database.query(rc.getLocal("db"), new IClause[]{
MATCH.node().label("user").property("email").value(user.email)
.relation().type("MEMBER_OF").node(coll).label("collection"),
OPTIONAL_MATCH.node(coll).relation().type("CONTAINS")
.node(entry).label("entry"),
// For some reason, it's incredibly hard to write:
// RETURN collect(DISTINCT coll), collect(DISTINCT entry)
RETURN.DISTINCT().value(coll),
RETURN.value(entry)
});
final List<GrNode> groups = res.resultOf(coll);
final List<GrNode> entries = res.resultOf(entry);
rc.status(200).json().send(new UserDetails(user, groups, entries));
});
// GET api.serp.se/v1/account/logout HTTP/1.1
POST("/logout", (rc) -> {
rc.resetSession();
rc.getResponse().ok();
});
// POST api.serp.se/v1/account/delete HTTP/1.1
POST("/delete", (rc) -> {
AccountSystem.deleteAccount(rc.getSession("email"));
rc.resetSession();
rc.getResponse().ok();
});
// POST api.serp.se/v1/account/change-password HTTP/1.1
// old=..&new=..
POST("/change-password", (rc) -> {
String oldpw = rc.getParameter("old").toString();
String newpw = rc.getParameter("new").toString();
if (!AccountSystem.authenticate(rc.getSession("email"), oldpw))
throw new RequestException("Invalid password.");
AccountSystem.changePassword(rc.getSession("email"), newpw);
rc.getResponse().ok();
});
// GET api.serp.se/v1/account/invites HTTP/1.1
GET("/invites", (rc) -> {
final String email = rc.getSession("email");
final List<GrNode> groups = queryCollections(rc.getLocal("db"), email, "INVITE");
rc.json().send(Graph.Collection.fromList(groups));
});
// GET api.serp.se/v1/account/some@email.com HTTP/1.1
GET("/{email}", (rc) -> {
AccountSystem.Account user = AccountSystem.findByEmail(rc.getSession("email"));
if (!TrustLevel.authorize(user.trust, TrustLevel.USER))
throw new RequestException(403, "Please verify your account email.");
String email = rc.getParameter("email").toString();
if (email == null || email.isEmpty())
throw new RequestException("No such email in database");
AccountSystem.Account query = AccountSystem.findByEmail(email);
if (query == null)
throw new RequestException("No such email in database");
final List<GrNode> groups = queryCollections(rc.getLocal("db"), email, "MEMBER_OF");
rc.status(200).json().send(new UserDetails(query, groups));
});
}
private static class UserDetails {
public String email, trust;
public int collection;
public Graph.Node[] entries;
public Graph.Collection[] collections;
public UserDetails(AccountSystem.Account user, List<GrNode> coll) {
this.email = user.email;
this.trust = TrustLevel.toString(user.trust);
this.collection = user.defaultCollection;
this.collections = Graph.Collection.fromList(coll);
}
public UserDetails(AccountSystem.Account user, List<GrNode> coll, List<GrNode> entries) {
this(user, coll);
this.entries = Graph.Node.fromList(entries);
}
}
public String getPrefix() { return "/v1/account"; }
} |
package seedu.address.model;
import java.util.Comparator;
import java.util.Date;
import java.util.Set;
import java.util.logging.Logger;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import seedu.address.commons.core.ComponentManager;
import seedu.address.commons.core.LogsCenter;
import seedu.address.commons.core.UnmodifiableObservableList;
import seedu.address.commons.events.model.TaskManagerChangedEvent;
import seedu.address.commons.events.ui.JumpToListRequestEvent;
import seedu.address.commons.exceptions.InvalidUndoCommandException;
import seedu.address.commons.util.CollectionUtil;
import seedu.address.model.datastructure.PartialSearch;
import seedu.address.model.label.Label;
import seedu.address.model.task.ReadOnlyTask;
import seedu.address.model.task.Task;
import seedu.address.model.task.UniqueTaskList;
import seedu.address.model.task.UniqueTaskList.TaskNotFoundException;
/**
* Represents the in-memory model of the task manager data.
* All changes to any model should be synchronized.
*/
public class ModelManager extends ComponentManager implements Model {
private static final Logger logger = LogsCenter.getLogger(ModelManager.class);
private TaskManager taskManager;
private final FilteredList<ReadOnlyTask> filteredTasks;
/**
* Initializes a ModelManager with the given taskManager and userPrefs.
*/
public ModelManager(ReadOnlyTaskManager taskManager, UserPrefs userPrefs) {
super();
assert !CollectionUtil.isAnyNull(taskManager, userPrefs);
logger.fine("Initializing with task manager: " + taskManager + " and user prefs " + userPrefs);
this.taskManager = new TaskManager(taskManager);
filteredTasks = new FilteredList<>(this.taskManager.getTaskList());
}
public ModelManager() {
this(new TaskManager(), new UserPrefs());
}
@Override
public void resetData(ReadOnlyTaskManager newData) {
taskManager.resetData(newData);
indicateTaskManagerChanged();
}
@Override
public ReadOnlyTaskManager getTaskManager() {
return taskManager;
}
/** Raises an event to indicate the model has changed */
private void indicateTaskManagerChanged() {
raise(new TaskManagerChangedEvent(taskManager));
}
//@@author A0162877N
/** Raises an event to indicate the model has changed */
private void focusOnListIndex(int index) {
raise(new JumpToListRequestEvent(index));
}
@Override
public synchronized void deleteTask(ReadOnlyTask target) throws TaskNotFoundException {
taskManager.removeTask(target);
indicateTaskManagerChanged();
}
//@@author A0162877N
@Override
public synchronized void addTask(Task task) throws UniqueTaskList.DuplicateTaskException {
taskManager.addTask(task);
indicateTaskManagerChanged();
setScrollToTask(task);
}
//@@author A0162877N
@Override
public void updateTask(int filteredTaskListIndex, ReadOnlyTask editedTask)
throws UniqueTaskList.DuplicateTaskException {
assert editedTask != null;
int taskManagerIndex = filteredTasks.getSourceIndex(filteredTaskListIndex);
taskManager.updateTask(taskManagerIndex, editedTask);
indicateTaskManagerChanged();
setScrollToTask(editedTask);
}
//@@author A0162877N
/**
* This method will find the index of the task in the filtered list
*/
private void setScrollToTask(ReadOnlyTask task) {
int indexInFilteredTask = filteredTasks.indexOf(task);
if (indexInFilteredTask < 0) {
updateFilteredListToShowAll();
indexInFilteredTask = filteredTasks.indexOf(task);
}
focusOnListIndex(indexInFilteredTask);
}
//@@author A0162877N
@Override
public void undoPrevious(ObservableList<ReadOnlyTask> oldTaskState, ObservableList<Label> oldLabelState)
throws InvalidUndoCommandException {
taskManager.undoData(oldTaskState, oldLabelState);
updateFilteredListToShowAll();
indicateTaskManagerChanged();
}
@Override
public UnmodifiableObservableList<ReadOnlyTask> getFilteredTaskList() {
sortFilteredTasks();
return new UnmodifiableObservableList<>(filteredTasks);
}
@Override
public UnmodifiableObservableList<ReadOnlyTask> getFilteredIncompleteTaskList() {
updateFilteredTaskList(false);
return new UnmodifiableObservableList<>(filteredTasks);
}
@Override
public void updateFilteredListToShowAll() {
updateFilteredTaskList(false);
}
@Override
public void updateFilteredTaskList(Date startDate, Date endDate) {
updateFilteredTaskListByDate(new DateFilter(startDate, endDate));
}
private void updateFilteredTaskList(Expression expression) {
filteredTasks.setPredicate(expression::satisfies);
}
@Override
public void updateFilteredTaskList(Set<String> keywords) {
updateFilteredTaskList(new PredicateExpression(new NameQualifier(keywords)));
sortFilteredTasks();
}
@Override
public void updateFilteredTaskList(Boolean isCompleted) {
updateFilteredTaskListByCompletion(new StatusFilter(isCompleted));
sortFilteredTasks();
}
private void updateFilteredTaskListByDate(DateFilter dateFilter) {
filteredTasks.setPredicate(dateFilter::run);
}
private void updateFilteredTaskListByCompletion(StatusFilter statusFilter) {
filteredTasks.setPredicate(statusFilter::run);
}
interface Expression {
boolean satisfies(ReadOnlyTask task);
String toString();
}
private class PredicateExpression implements Expression {
private final Qualifier qualifier;
PredicateExpression(Qualifier qualifier) {
this.qualifier = qualifier;
}
@Override
public boolean satisfies(ReadOnlyTask task) {
return qualifier.run(task);
}
@Override
public String toString() {
return qualifier.toString();
}
}
interface Qualifier {
boolean run(ReadOnlyTask task);
String toString();
}
private class NameQualifier implements Qualifier {
private Set<String> nameKeyWords;
NameQualifier(Set<String> nameKeyWords) {
this.nameKeyWords = nameKeyWords;
}
//@@author A0162877N
@Override
public boolean run(ReadOnlyTask task) {
String taskDetails = task.getAsSearchText();
PartialSearch partialSearch = new PartialSearch(taskDetails);
return (nameKeyWords.stream()
.filter(keyword -> partialSearch.search(keyword))
.findAny()
.isPresent());
}
@Override
public String toString() {
return "name=" + String.join(", ", nameKeyWords);
}
}
//@@author A0162877N
private class DateFilter {
private Date startTime;
private Date endTime;
DateFilter(Date startTime, Date endTime) {
this.startTime = startTime;
this.endTime = endTime;
}
public boolean run(ReadOnlyTask task) {
if (task.getDeadline().isPresent() && task.getStartTime().isPresent()) {
return (task.getDeadline().get().getDateTime().before(endTime)
&& task.getDeadline().get().getDateTime().after(startTime))
|| task.getDeadline().get().getDateTime().equals(endTime);
} else if (task.getDeadline().isPresent()) {
return task.getDeadline().get().getDateTime().before(endTime)
|| task.getDeadline().get().getDateTime().equals(endTime);
}
return false;
}
}
//@@author A0105287E
private class StatusFilter implements Qualifier {
private boolean isCompleted;
StatusFilter(boolean isCompleted) {
this.isCompleted = isCompleted;
}
public boolean run(ReadOnlyTask task) {
return task.isCompleted().booleanValue() == isCompleted;
}
}
//@@author A0105287E
private void sortFilteredTasks() {
Comparator<ReadOnlyTask> comparator = new Comparator<ReadOnlyTask> () {
public int compare(ReadOnlyTask task1, ReadOnlyTask task2) {
return task1.compareTo(task2);
}
};;
filteredTasks.sorted(comparator);
}
} |
package seedu.address.model;
import javafx.collections.transformation.FilteredList;
import seedu.address.commons.core.LogsCenter;
import seedu.address.commons.core.UnmodifiableObservableList;
import seedu.address.commons.util.StringUtil;
import seedu.address.model.task.Task;
import seedu.address.model.task.TaskDate;
import seedu.address.model.task.TaskType;
import seedu.address.model.tag.Tag;
import seedu.address.model.tag.UniqueTagList;
import seedu.address.model.task.Name;
import seedu.address.model.task.ReadOnlyTask;
import seedu.address.model.task.UniqueTaskList;
import seedu.address.model.task.UniqueTaskList.TaskNotFoundException;
import seedu.address.model.task.UniqueTaskList.TimeslotOverlapException;
import seedu.address.commons.events.model.TaskListChangedEvent;
import seedu.address.commons.events.model.FilePathChangeEvent;
import seedu.address.commons.core.ComponentManager;
import java.util.ArrayDeque;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import java.util.logging.Logger;
/**
* Represents the in-memory model of the address book data.
* All changes to any model should be synchronized.
*/
public class ModelManager extends ComponentManager implements Model {
private static final Logger logger = LogsCenter.getLogger(ModelManager.class);
private final TaskList taskList;
private final FilteredList<Task> filteredTasks;
/**
* Initializes a ModelManager with the given TaskList
* TaskList and its variables should not be null
*/
public ModelManager(TaskList src, UserPrefs userPrefs) {
super();
assert src != null;
assert userPrefs != null;
logger.fine("Initializing with address book: " + src + " and user prefs " + userPrefs);
taskList = new TaskList(src);
filteredTasks = new FilteredList<>(taskList.getTasks());
}
public ModelManager() {
this(new TaskList(), new UserPrefs());
}
public ModelManager(ReadOnlyTaskList initialData, UserPrefs userPrefs) {
taskList = new TaskList(initialData);
filteredTasks = new FilteredList<>(taskList.getTasks());
}
@Override
public void resetData(ReadOnlyTaskList newData) {
taskList.resetData(newData);
indicateTaskListChanged();
}
@Override
public ReadOnlyTaskList getTaskList() {
return taskList;
}
/** Raises an event to indicate the model has changed */
private void indicateTaskListChanged() {
raise(new TaskListChangedEvent(taskList));
}
@Override
public synchronized void deleteTask(ReadOnlyTask target) throws TaskNotFoundException {
taskList.removeTask(target);
indicateTaskListChanged();
}
@Override
public synchronized void editTask(ReadOnlyTask target, Name name, UniqueTagList tags,
TaskDate startDate, TaskDate endDate) throws TaskNotFoundException, TimeslotOverlapException {
taskList.updateTask(target, name, tags, startDate, endDate);
indicateTaskListChanged();
updateFilteredListToShowAll();
}
@Override
public synchronized void archiveTask(ReadOnlyTask target) throws TaskNotFoundException {
taskList.archiveTask(target);
indicateTaskListChanged();
updateFilteredListToShowAll();
}
@Override
public synchronized void addTask(Task task) throws UniqueTaskList.DuplicateTaskException, TimeslotOverlapException {
taskList.addTask(task);
updateFilteredListToShowAll();
indicateTaskListChanged();
}
@Override
public void changeDirectory(String filePath) {
// TODO Auto-generated method stub
raise(new FilePathChangeEvent(filePath));
}
@Override
public UnmodifiableObservableList<ReadOnlyTask> getFilteredTaskList() {
return new UnmodifiableObservableList<>(filteredTasks);
}
@Override
public void updateFilteredListToShowAll() {
filteredTasks.setPredicate(new PredicateExpression(new TypeQualifier(TaskType.COMPLETED))::unsatisfies);
}
@Override
public void updateFilteredTaskList(Set<String> keywords, Set<String> tags, Date startDate, Date endDate, Date deadline) {
updateFilteredTaskList(new PredicateExpression(new FindQualifier(keywords, tags, startDate, endDate, deadline)));
}
private void updateFilteredTaskList(Expression expression) {
filteredTasks.setPredicate(expression::satisfies);
}
interface Expression {
boolean satisfies(ReadOnlyTask task);
String toString();
}
private class PredicateExpression implements Expression {
private final Qualifier qualifier;
PredicateExpression(Qualifier qualifier) {
this.qualifier = qualifier;
}
@Override
public boolean satisfies(ReadOnlyTask task) {
return qualifier.run(task);
}
public boolean unsatisfies(ReadOnlyTask task) {
return !qualifier.run(task);
}
@Override
public String toString() {
return qualifier.toString();
}
}
interface Qualifier {
boolean run(ReadOnlyTask task);
String toString();
}
private class TypeQualifier implements Qualifier {
private TaskType typeKeyWords;
TypeQualifier(TaskType typeKeyWords) {
this.typeKeyWords = typeKeyWords;
}
@Override
public boolean run(ReadOnlyTask task) {
return task.getType().equals(typeKeyWords);
}
@Override
public String toString() {
return "type=" + typeKeyWords.toString();
}
}
private class NameQualifier implements Qualifier {
private Set<String> nameKeyWords;
NameQualifier(Set<String> nameKeyWords) {
this.nameKeyWords = nameKeyWords;
}
@Override
public boolean run(ReadOnlyTask task) {
if(nameKeyWords.isEmpty())
return true;
return nameKeyWords.stream()
.filter(keyword -> StringUtil.containsIgnoreCase(task.getName().fullName, keyword))
.findAny()
.isPresent();
}
@Override
public String toString() {
return "name=" + String.join(", ", nameKeyWords);
}
}
private class TagQualifier implements Qualifier {
private Set<String> tagSet;
TagQualifier(Set<String> tagSet) {
this.tagSet = tagSet;
}
private String tagToString(ReadOnlyTask task) {
Set<Tag> tagSet = task.getTags().toSet();
Set<String> tagStringSet = new HashSet<String>();
for(Tag t : tagSet) {
tagStringSet.add(t.tagName);
}
return String.join(" ", tagStringSet);
}
@Override
public boolean run(ReadOnlyTask task) {
if(tagSet.isEmpty()) {
return true;
}
return tagSet.stream()
.filter(tag -> StringUtil.containsIgnoreCase(tagToString(task), tag))
.findAny()
.isPresent();
}
@Override
public String toString() {
return "tag=" + String.join(", ", tagSet);
}
}
private class PeriodQualifier implements Qualifier {
private final int START_DATE_INDEX = 0;
private final int END_DATE_INDEX = 1;
private Date startTime;
private Date endTime;
PeriodQualifier(Date startTime, Date endTime) {
this.startTime = startTime;
this.endTime = endTime;
}
private Date[] extractTaskPeriod(ReadOnlyTask task) {
TaskType type = task.getType();
if(type.equals(TaskType.FLOATING)) {
return null;
}
if(task.getStartDate().getDate() == TaskDate.DATE_NOT_PRESENT
|| task.getEndDate().getDate() == TaskDate.DATE_NOT_PRESENT) {
return null;
}
Date startDate = new Date(task.getStartDate().getDate());
Date endDate = new Date(task.getEndDate().getDate());
return new Date[]{ startDate, endDate };
}
@Override
public boolean run(ReadOnlyTask task) {
if(this.startTime == null || this.endTime == null)
return true;
Date[] timeArray = extractTaskPeriod(task);
if(timeArray == null)
return false;
Date startDate = timeArray[START_DATE_INDEX];
Date endDate = timeArray[END_DATE_INDEX];
if((startDate.after(this.startTime)||(startDate.getDate()==this.startTime.getDate()&&startDate.getMonth()==this.startTime.getMonth()))
&& (endDate.before(this.endTime)||(endDate.getDate()==this.endTime.getDate()&&endDate.getMonth()==this.endTime.getMonth())))
return true;
return false;
}
@Override
public String toString() {
if(this.startTime == null || this.endTime == null)
return "";
return "start time=" + this.startTime.toString()
+ " end time=" + this.endTime.toString();
}
}
private class DeadlineQualifier implements Qualifier {
private Date deadline;
DeadlineQualifier(Date deadline) {
this.deadline = deadline;
}
@SuppressWarnings("deprecation")
@Override
public boolean run(ReadOnlyTask task) {
if(this.deadline == null)
return true;
if(task.getType().equals(TaskType.FLOATING))
return false;
if(task.getEndDate().getDate() == TaskDate.DATE_NOT_PRESENT)
return false;
Date deadline = new Date(task.getEndDate().getDate());
if(deadline.before(this.deadline)
&& task.getStartDate().getDate() == TaskDate.DATE_NOT_PRESENT)
return true;
if(deadline.getDate()==this.deadline.getDate()&&deadline.getMonth()==this.deadline.getMonth()
&& task.getStartDate().getDate() == TaskDate.DATE_NOT_PRESENT)
return true;
return false;
}
@Override
public String toString() {
if(this.deadline == null)
return "";
return "deadline=" + this.deadline.toString();
}
}
private class FindQualifier implements Qualifier {
private NameQualifier nameQualifier;
private TagQualifier tagQualifier;
private PeriodQualifier periodQualifier;
private DeadlineQualifier deadlineQualifier;
private TypeQualifier typeQualifier = null;
FindQualifier(Set<String> keywordSet, Set<String> tagSet, Date startTime, Date endTime, Date deadline) {
if(keywordSet.contains("-C"))
this.typeQualifier = new TypeQualifier(TaskType.COMPLETED);
if(keywordSet.contains("-F"))
this.typeQualifier = new TypeQualifier(TaskType.FLOATING);
this.nameQualifier = new NameQualifier(keywordSet);
this.tagQualifier = new TagQualifier(tagSet);
this.periodQualifier = new PeriodQualifier(startTime, endTime);
this.deadlineQualifier = new DeadlineQualifier(deadline);
}
@Override
public boolean run(ReadOnlyTask task) {
if(this.typeQualifier!=null)
return typeQualifier.run(task);
return nameQualifier.run(task)
&& tagQualifier.run(task)
&& periodQualifier.run(task)
&& deadlineQualifier.run(task);
}
@Override
public String toString() {
return nameQualifier.toString() + " "
+ tagQualifier.toString() + " "
+ periodQualifier.toString() + " "
+ deadlineQualifier.toString() + " ";
}
}
} |
package seedu.taskitty.model;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import seedu.taskitty.model.tag.Tag;
import seedu.taskitty.model.tag.UniqueTagList;
import seedu.taskitty.model.task.ReadOnlyTask;
import seedu.taskitty.model.task.Task;
import seedu.taskitty.model.task.UniqueTaskList;
import seedu.taskitty.model.task.UniqueTaskList.DuplicateMarkAsDoneException;
import java.util.*;
import java.util.stream.Collectors;
/**
* Wraps all data at the task-manager level
* Duplicates are not allowed (by .equals comparison)
*/
public class TaskManager implements ReadOnlyTaskManager {
private final UniqueTaskList tasks;
private final UniqueTagList tags;
{
tasks = new UniqueTaskList();
tags = new UniqueTagList();
}
public TaskManager() {}
/**
* Tasks and Tags are copied into this taskmanager
*/
public TaskManager(ReadOnlyTaskManager toBeCopied) {
this(toBeCopied.getUniqueTaskList(), toBeCopied.getUniqueTagList());
}
/**
* Tasks and Tags are copied into this taskmanager
*/
public TaskManager(UniqueTaskList tasks, UniqueTagList tags) {
resetData(tasks.getInternalList(), tags.getInternalList());
}
public static ReadOnlyTaskManager getEmptyTaskManager() {
return new TaskManager();
}
//// list overwrite operations
public ObservableList<Task> getAllTasks() {
return tasks.getInternalList();
}
public ObservableList<Task> getFilteredTodos() {
return tasks.getFilteredTaskList(Task.TASK_COMPONENT_COUNT);
}
public ObservableList<Task> getFilteredDeadlines() {
return tasks.getFilteredTaskList(Task.DEADLINE_COMPONENT_COUNT);
}
public ObservableList<Task> getFilteredEvents() {
return tasks.getFilteredTaskList(Task.EVENT_COMPONENT_COUNT);
}
public void setTasks(List<Task> tasks) {
this.tasks.getInternalList().setAll(tasks);
}
public void setTags(Collection<Tag> tags) {
this.tags.getInternalList().setAll(tags);
}
public void resetData(Collection<? extends ReadOnlyTask> newTasks, Collection<Tag> newTags) {
setTasks(newTasks.stream().map(Task::new).collect(Collectors.toList()));
setTags(newTags);
}
public void resetData(ReadOnlyTaskManager newData) {
resetData(newData.getTaskList(), newData.getTagList());
}
//// task-level operations
/**
* Adds a task to the task manager.
* Also checks the new task's tags and updates {@link #tags} with any new tags found,
* and updates the Tag objects in the task to point to those in {@link #tags}.
*
* @throws UniqueTaskList.DuplicatePersonException if an equivalent person already exists.
*/
public void addTask(Task p) throws UniqueTaskList.DuplicateTaskException {
syncTagsWithMasterList(p);
tasks.add(p);
}
/**
* Marks a task as done in the task manager.
*
* @throws UniqueTaskList.TaskNotFoundException if task is not found.
* @throws UniqueTaskList.DuplicateMarkAsDoneException if task has already been previously marked as done
*/
public void doneTask(ReadOnlyTask key) throws UniqueTaskList.DuplicateMarkAsDoneException, UniqueTaskList.TaskNotFoundException {
tasks.mark(key);
}
/**
* Adds a task to the task manager.
* Also checks the new task's tags and updates {@link #tags} with any new tags found,
* and updates the Tag objects in the task to point to those in {@link #tags}.
*
* @throws UniqueTaskList.DuplicatePersonException if an equivalent person already exists.
*/
public void addTask(Task p, int index) throws UniqueTaskList.DuplicateTaskException {
syncTagsWithMasterList(p);
tasks.add(index, p);
}
/**
* Ensures that every tag in this task:
* - exists in the master list {@link #tags}
* - points to a Tag object in the master list
*/
private void syncTagsWithMasterList(Task task) {
final UniqueTagList taskTags = task.getTags();
tags.mergeFrom(taskTags);
// Create map with values = tag object references in the master list
final Map<Tag, Tag> masterTagObjects = new HashMap<>();
for (Tag tag : tags) {
masterTagObjects.put(tag, tag);
}
// Rebuild the list of task tags using references from the master list
final Set<Tag> commonTagReferences = new HashSet<>();
for (Tag tag : taskTags) {
commonTagReferences.add(masterTagObjects.get(tag));
}
task.setTags(new UniqueTagList(commonTagReferences));
}
public boolean removeTask(ReadOnlyTask key) throws UniqueTaskList.TaskNotFoundException {
if (tasks.remove(key)) {
return true;
} else {
throw new UniqueTaskList.TaskNotFoundException();
}
}
//// tag-level operations
public void addTag(Tag t) throws UniqueTagList.DuplicateTagException {
tags.add(t);
}
//// util methods
@Override
public String toString() {
return tasks.getInternalList().size() + " tasks, " + tags.getInternalList().size() + " tags";
// TODO: refine later
}
@Override
public List<ReadOnlyTask> getTaskList() {
return Collections.unmodifiableList(tasks.getInternalList());
}
@Override
public List<Tag> getTagList() {
return Collections.unmodifiableList(tags.getInternalList());
}
@Override
public UniqueTaskList getUniqueTaskList() {
return this.tasks;
}
@Override
public UniqueTagList getUniqueTagList() {
return this.tags;
}
@Override
public boolean equals(Object other) {
return other == this // short circuit if same object
|| (other instanceof TaskManager // instanceof handles nulls
&& this.tasks.equals(((TaskManager) other).tasks)
&& this.tags.equals(((TaskManager) other).tags));
}
@Override
public int hashCode() {
// use this method for custom fields hashing instead of implementing your own
return Objects.hash(tasks, tags);
}
} |
package tk.mybatis.mapper.entity;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
import org.apache.ibatis.type.TypeHandler;
import tk.mybatis.mapper.MapperException;
import tk.mybatis.mapper.mapperhelper.EntityHelper;
import tk.mybatis.mapper.util.StringUtil;
import java.util.*;
/**
* Example
*
* @author liuzh
*/
public class Example implements IDynamicTableName {
protected String orderByClause;
protected boolean distinct;
protected boolean exists;
protected boolean notNull;
protected boolean forUpdate;
protected Set<String> selectColumns;
protected Set<String> excludeColumns;
protected String countColumn;
protected List<Criteria> oredCriteria;
protected Class<?> entityClass;
protected EntityTable table;
protected Map<String, EntityColumn> propertyMap;
protected String tableName;
protected OrderBy ORDERBY;
/**
* existstrue
*
* @param entityClass
*/
public Example(Class<?> entityClass) {
this(entityClass, true);
}
/**
* existsnotNullfalse
*
* @param entityClass
* @param exists - truefalse
*/
public Example(Class<?> entityClass, boolean exists) {
this(entityClass, exists, false);
}
/**
* exists
*
* @param entityClass
* @param exists - truefalse
* @param notNull - truefalse
*/
public Example(Class<?> entityClass, boolean exists, boolean notNull) {
this.exists = exists;
this.notNull = notNull;
oredCriteria = new ArrayList<Criteria>();
this.entityClass = entityClass;
table = EntityHelper.getEntityTable(entityClass);
//#159
propertyMap = table.getPropertyMap();
this.ORDERBY = new OrderBy(this, propertyMap);
}
public Class<?> getEntityClass() {
return entityClass;
}
public String getOrderByClause() {
return orderByClause;
}
public void setOrderByClause(String orderByClause) {
this.orderByClause = orderByClause;
}
public OrderBy orderBy(String property) {
this.ORDERBY.orderBy(property);
return this.ORDERBY;
}
public static class OrderBy {
private Example example;
private Boolean isProperty;
protected Map<String, EntityColumn> propertyMap;
protected boolean notNull;
public OrderBy(Example example, Map<String, EntityColumn> propertyMap) {
this.example = example;
this.propertyMap = propertyMap;
}
private String property(String property) {
if (propertyMap.containsKey(property)) {
return propertyMap.get(property).getColumn();
} else if (notNull) {
throw new MapperException("" + property + "!");
} else {
return null;
}
}
public OrderBy orderBy(String property) {
String column = property(property);
if (column == null) {
isProperty = false;
return this;
}
if (StringUtil.isNotEmpty(example.getOrderByClause())) {
example.setOrderByClause(example.getOrderByClause() + "," + column);
} else {
example.setOrderByClause(column);
}
isProperty = true;
return this;
}
public OrderBy desc() {
if (isProperty) {
example.setOrderByClause(example.getOrderByClause() + " DESC");
isProperty = false;
}
return this;
}
public OrderBy asc() {
if (isProperty) {
example.setOrderByClause(example.getOrderByClause() + " ASC");
isProperty = false;
}
return this;
}
}
public Set<String> getSelectColumns() {
if(selectColumns != null && selectColumns.size() > 0){
} else if(excludeColumns != null && excludeColumns.size() > 0){
Collection<EntityColumn> entityColumns = propertyMap.values();
selectColumns = new LinkedHashSet<String>(entityColumns.size() - excludeColumns.size());
for (EntityColumn column : entityColumns) {
if(!excludeColumns.contains(column.getColumn())){
selectColumns.add(column.getColumn());
}
}
}
return selectColumns;
}
/**
* selectProperties
*
* @param properties
* @return
*/
public Example excludeProperties(String... properties) {
if (properties != null && properties.length > 0) {
if (this.excludeColumns == null) {
this.excludeColumns = new LinkedHashSet<String>();
}
for (String property : properties) {
if (propertyMap.containsKey(property)) {
this.excludeColumns.add(propertyMap.get(property).getColumn());
}
}
}
return this;
}
/**
* -
*
* @param properties
* @return
*/
public Example selectProperties(String... properties) {
if (properties != null && properties.length > 0) {
if (this.selectColumns == null) {
this.selectColumns = new LinkedHashSet<String>();
}
for (String property : properties) {
if (propertyMap.containsKey(property)) {
this.selectColumns.add(propertyMap.get(property).getColumn());
}
}
}
return this;
}
public String getCountColumn() {
return countColumn;
}
/**
* count(property)
*
* @param property
*/
public void setCountProperty(String property) {
if (propertyMap.containsKey(property)) {
this.countColumn = propertyMap.get(property).getColumn();
}
}
public boolean isDistinct() {
return distinct;
}
public void setDistinct(boolean distinct) {
this.distinct = distinct;
}
public boolean isForUpdate() {
return forUpdate;
}
public void setForUpdate(boolean forUpdate) {
this.forUpdate = forUpdate;
}
public List<Criteria> getOredCriteria() {
return oredCriteria;
}
public void or(Criteria criteria) {
criteria.setAndOr("or");
oredCriteria.add(criteria);
}
public Criteria or() {
Criteria criteria = createCriteriaInternal();
criteria.setAndOr("or");
oredCriteria.add(criteria);
return criteria;
}
public void and(Criteria criteria) {
criteria.setAndOr("and");
oredCriteria.add(criteria);
}
public Criteria and() {
Criteria criteria = createCriteriaInternal();
criteria.setAndOr("and");
oredCriteria.add(criteria);
return criteria;
}
public Criteria createCriteria() {
Criteria criteria = createCriteriaInternal();
if (oredCriteria.size() == 0) {
criteria.setAndOr("and");
oredCriteria.add(criteria);
}
return criteria;
}
protected Criteria createCriteriaInternal() {
Criteria criteria = new Criteria(propertyMap, exists, notNull);
return criteria;
}
public void clear() {
oredCriteria.clear();
orderByClause = null;
distinct = false;
}
/**
*
*
* @param tableName
*/
public void setTableName(String tableName) {
this.tableName = tableName;
}
@Override
public String getDynamicTableName() {
return tableName;
}
protected abstract static class GeneratedCriteria {
protected List<Criterion> criteria;
protected boolean exists;
protected boolean notNull;
protected String andOr;
protected Map<String, EntityColumn> propertyMap;
protected GeneratedCriteria(Map<String, EntityColumn> propertyMap, boolean exists, boolean notNull) {
super();
this.exists = exists;
this.notNull = notNull;
criteria = new ArrayList<Criterion>();
this.propertyMap = propertyMap;
}
private String column(String property) {
if (propertyMap.containsKey(property)) {
return propertyMap.get(property).getColumn();
} else if (exists) {
throw new MapperException("" + property + "!");
} else {
return null;
}
}
private String property(String property) {
if (propertyMap.containsKey(property)) {
return property;
} else if (exists) {
throw new MapperException("" + property + "!");
} else {
return null;
}
}
public String getAndOr() {
return andOr;
}
public void setAndOr(String andOr) {
this.andOr = andOr;
}
public boolean isValid() {
return criteria.size() > 0;
}
public List<Criterion> getAllCriteria() {
return criteria;
}
public List<Criterion> getCriteria() {
return criteria;
}
protected void addCriterion(String condition) {
if (condition == null) {
throw new MapperException("Value for condition cannot be null");
}
if (condition.startsWith("null")) {
return;
}
criteria.add(new Criterion(condition));
}
protected void addCriterion(String condition, Object value, String property) {
if (value == null) {
if (notNull) {
throw new MapperException("Value for " + property + " cannot be null");
} else {
return;
}
}
if (property == null) {
return;
}
criteria.add(new Criterion(condition, value));
}
protected void addCriterion(String condition, Object value1, Object value2, String property) {
if (value1 == null || value2 == null) {
if (notNull) {
throw new MapperException("Between values for " + property + " cannot be null");
} else {
return;
}
}
if (property == null) {
return;
}
criteria.add(new Criterion(condition, value1, value2));
}
protected void addOrCriterion(String condition) {
if (condition == null) {
throw new MapperException("Value for condition cannot be null");
}
if (condition.startsWith("null")) {
return;
}
criteria.add(new Criterion(condition, true));
}
protected void addOrCriterion(String condition, Object value, String property) {
if (value == null) {
if (notNull) {
throw new MapperException("Value for " + property + " cannot be null");
} else {
return;
}
}
if (property == null) {
return;
}
criteria.add(new Criterion(condition, value, true));
}
protected void addOrCriterion(String condition, Object value1, Object value2, String property) {
if (value1 == null || value2 == null) {
if (notNull) {
throw new MapperException("Between values for " + property + " cannot be null");
} else {
return;
}
}
if (property == null) {
return;
}
criteria.add(new Criterion(condition, value1, value2, true));
}
public Criteria andIsNull(String property) {
addCriterion(column(property) + " is null");
return (Criteria) this;
}
public Criteria andIsNotNull(String property) {
addCriterion(column(property) + " is not null");
return (Criteria) this;
}
public Criteria andEqualTo(String property, Object value) {
addCriterion(column(property) + " =", value, property(property));
return (Criteria) this;
}
public Criteria andNotEqualTo(String property, Object value) {
addCriterion(column(property) + " <>", value, property(property));
return (Criteria) this;
}
public Criteria andGreaterThan(String property, Object value) {
addCriterion(column(property) + " >", value, property(property));
return (Criteria) this;
}
public Criteria andGreaterThanOrEqualTo(String property, Object value) {
addCriterion(column(property) + " >=", value, property(property));
return (Criteria) this;
}
public Criteria andLessThan(String property, Object value) {
addCriterion(column(property) + " <", value, property(property));
return (Criteria) this;
}
public Criteria andLessThanOrEqualTo(String property, Object value) {
addCriterion(column(property) + " <=", value, property(property));
return (Criteria) this;
}
public Criteria andIn(String property, Iterable values) {
addCriterion(column(property) + " in", values, property(property));
return (Criteria) this;
}
public Criteria andNotIn(String property, Iterable values) {
addCriterion(column(property) + " not in", values, property(property));
return (Criteria) this;
}
public Criteria andBetween(String property, Object value1, Object value2) {
addCriterion(column(property) + " between", value1, value2, property(property));
return (Criteria) this;
}
public Criteria andNotBetween(String property, Object value1, Object value2) {
addCriterion(column(property) + " not between", value1, value2, property(property));
return (Criteria) this;
}
public Criteria andLike(String property, String value) {
addCriterion(column(property) + " like", value, property(property));
return (Criteria) this;
}
public Criteria andNotLike(String property, String value) {
addCriterion(column(property) + " not like", value, property(property));
return (Criteria) this;
}
/**
*
*
* @param condition "length(countryname)<5"
* @return
*/
public Criteria andCondition(String condition) {
addCriterion(condition);
return (Criteria) this;
}
/**
* value
*
* @param condition "length(countryname)="
* @param value 5
* @return
*/
public Criteria andCondition(String condition, Object value) {
criteria.add(new Criterion(condition, value));
return (Criteria) this;
}
/**
* value
*
* @param condition "length(countryname)="
* @param value 5
* @param typeHandler
* @return
* @deprecated typeHandler4.x
*/
@Deprecated
public Criteria andCondition(String condition, Object value, String typeHandler) {
criteria.add(new Criterion(condition, value, typeHandler));
return (Criteria) this;
}
/**
* value
*
* @param condition "length(countryname)="
* @param value 5
* @param typeHandler
* @return
* @deprecated typeHandler4.x
*/
@Deprecated
public Criteria andCondition(String condition, Object value, Class<? extends TypeHandler> typeHandler) {
criteria.add(new Criterion(condition, value, typeHandler.getCanonicalName()));
return (Criteria) this;
}
/**
*
*
* @param param
* @author Bob {@link}0haizhu0@gmail.com
* @Date 2015717 12:48:08
*/
public Criteria andEqualTo(Object param) {
MetaObject metaObject = SystemMetaObject.forObject(param);
String[] properties = metaObject.getGetterNames();
for (String property : properties) {
//Map
if (propertyMap.get(property) != null) {
Object value = metaObject.getValue(property);
if (value != null) {
andEqualTo(property, value);
}
}
}
return (Criteria) this;
}
/**
* null is null
*
* @param param
*/
public Criteria andAllEqualTo(Object param) {
MetaObject metaObject = SystemMetaObject.forObject(param);
String[] properties = metaObject.getGetterNames();
for (String property : properties) {
//Map
if (propertyMap.get(property) != null) {
Object value = metaObject.getValue(property);
if (value != null) {
andEqualTo(property, value);
} else {
andIsNull(property);
}
}
}
return (Criteria) this;
}
public Criteria orIsNull(String property) {
addOrCriterion(column(property) + " is null");
return (Criteria) this;
}
public Criteria orIsNotNull(String property) {
addOrCriterion(column(property) + " is not null");
return (Criteria) this;
}
public Criteria orEqualTo(String property, Object value) {
addOrCriterion(column(property) + " =", value, property(property));
return (Criteria) this;
}
public Criteria orNotEqualTo(String property, Object value) {
addOrCriterion(column(property) + " <>", value, property(property));
return (Criteria) this;
}
public Criteria orGreaterThan(String property, Object value) {
addOrCriterion(column(property) + " >", value, property(property));
return (Criteria) this;
}
public Criteria orGreaterThanOrEqualTo(String property, Object value) {
addOrCriterion(column(property) + " >=", value, property(property));
return (Criteria) this;
}
public Criteria orLessThan(String property, Object value) {
addOrCriterion(column(property) + " <", value, property(property));
return (Criteria) this;
}
public Criteria orLessThanOrEqualTo(String property, Object value) {
addOrCriterion(column(property) + " <=", value, property(property));
return (Criteria) this;
}
public Criteria orIn(String property, Iterable values) {
addOrCriterion(column(property) + " in", values, property(property));
return (Criteria) this;
}
public Criteria orNotIn(String property, Iterable values) {
addOrCriterion(column(property) + " not in", values, property(property));
return (Criteria) this;
}
public Criteria orBetween(String property, Object value1, Object value2) {
addOrCriterion(column(property) + " between", value1, value2, property(property));
return (Criteria) this;
}
public Criteria orNotBetween(String property, Object value1, Object value2) {
addOrCriterion(column(property) + " not between", value1, value2, property(property));
return (Criteria) this;
}
public Criteria orLike(String property, String value) {
addOrCriterion(column(property) + " like", value, property(property));
return (Criteria) this;
}
public Criteria orNotLike(String property, String value) {
addOrCriterion(column(property) + " not like", value, property(property));
return (Criteria) this;
}
/**
*
*
* @param condition "length(countryname)<5"
* @return
*/
public Criteria orCondition(String condition) {
addOrCriterion(condition);
return (Criteria) this;
}
/**
* value
*
* @param condition "length(countryname)="
* @param value 5
* @return
*/
public Criteria orCondition(String condition, Object value) {
criteria.add(new Criterion(condition, value, true));
return (Criteria) this;
}
/**
*
*
* @param param
* @author Bob {@link}0haizhu0@gmail.com
* @Date 2015717 12:48:08
*/
public Criteria orEqualTo(Object param) {
MetaObject metaObject = SystemMetaObject.forObject(param);
String[] properties = metaObject.getGetterNames();
for (String property : properties) {
//Map
if (propertyMap.get(property) != null) {
Object value = metaObject.getValue(property);
if (value != null) {
orEqualTo(property, value);
}
}
}
return (Criteria) this;
}
/**
* null is null
*
* @param param
*/
public Criteria orAllEqualTo(Object param) {
MetaObject metaObject = SystemMetaObject.forObject(param);
String[] properties = metaObject.getGetterNames();
for (String property : properties) {
//Map
if (propertyMap.get(property) != null) {
Object value = metaObject.getValue(property);
if (value != null) {
orEqualTo(property, value);
} else {
orIsNull(property);
}
}
}
return (Criteria) this;
}
}
public static class Criteria extends GeneratedCriteria {
protected Criteria(Map<String, EntityColumn> propertyMap, boolean exists, boolean notNull) {
super(propertyMap, exists, notNull);
}
}
public static class Criterion {
private String condition;
private Object value;
private Object secondValue;
private String andOr;
private boolean noValue;
private boolean singleValue;
private boolean betweenValue;
private boolean listValue;
private String typeHandler;
protected Criterion(String condition) {
this(condition, false);
}
protected Criterion(String condition, Object value, String typeHandler) {
this(condition, value, typeHandler, false);
}
protected Criterion(String condition, Object value) {
this(condition, value, null, false);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
this(condition, value, secondValue, typeHandler, false);
}
protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null, false);
}
protected Criterion(String condition, boolean isOr) {
super();
this.condition = condition;
this.typeHandler = null;
this.noValue = true;
this.andOr = isOr ? "or" : "and";
}
protected Criterion(String condition, Object value, String typeHandler, boolean isOr) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
this.andOr = isOr ? "or" : "and";
if (value instanceof Collection<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
}
protected Criterion(String condition, Object value, boolean isOr) {
this(condition, value, null, isOr);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler, boolean isOr) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
this.andOr = isOr ? "or" : "and";
}
protected Criterion(String condition, Object value, Object secondValue, boolean isOr) {
this(condition, value, secondValue, null, isOr);
}
public String getCondition() {
return condition;
}
public Object getValue() {
return value;
}
public Object getSecondValue() {
return secondValue;
}
public String getAndOr() {
return andOr;
}
public void setAndOr(String andOr) {
this.andOr = andOr;
}
public boolean isNoValue() {
return noValue;
}
public boolean isSingleValue() {
return singleValue;
}
public boolean isBetweenValue() {
return betweenValue;
}
public boolean isListValue() {
return listValue;
}
public String getTypeHandler() {
return typeHandler;
}
}
} |
package top.quantic.sentry.discord;
import com.ibasco.agql.protocols.valve.steam.webapi.pojos.SteamBanStatus;
import com.ibasco.agql.protocols.valve.steam.webapi.pojos.SteamPlayerProfile;
import joptsimple.OptionParser;
import joptsimple.OptionSpec;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import sx.blah.discord.api.internal.json.objects.EmbedObject;
import sx.blah.discord.handle.obj.IMessage;
import sx.blah.discord.util.EmbedBuilder;
import top.quantic.sentry.discord.core.Command;
import top.quantic.sentry.discord.core.CommandBuilder;
import top.quantic.sentry.discord.module.CommandSupplier;
import top.quantic.sentry.service.GameQueryService;
import java.awt.*;
import java.time.Instant;
import java.util.Collections;
import java.util.List;
import static org.apache.commons.lang3.text.WordUtils.capitalizeFully;
import static top.quantic.sentry.discord.util.DiscordUtil.answer;
import static top.quantic.sentry.discord.util.DiscordUtil.sendMessage;
import static top.quantic.sentry.service.util.DateUtil.withRelative;
import static top.quantic.sentry.service.util.MiscUtil.getDominantColor;
import static top.quantic.sentry.service.util.SteamIdConverter.steam2To3;
import static top.quantic.sentry.service.util.SteamIdConverter.steamId64To2;
@Component
public class Steam implements CommandSupplier {
private static final Logger log = LoggerFactory.getLogger(Steam.class);
private static final String[] PERSONA_STATES = {
"Offline", "Online", "Busy", "Away", "Snooze", "Looking to trade", "Looking to play"
};
private final GameQueryService gameQueryService;
@Autowired
public Steam(GameQueryService gameQueryService) {
this.gameQueryService = gameQueryService;
}
@Override
public List<Command> getCommands() {
return Collections.singletonList(steam());
}
private Command steam() {
OptionParser parser = new OptionParser();
OptionSpec<String> nonOptSpec = parser.nonOptions("One or many SteamID32, SteamID64 or Community URL of a Steam user").ofType(String.class);
return CommandBuilder.of("steam")
.describedAs("Get information about a Steam user")
.in("Integrations")
.parsedBy(parser)
.onExecute(context -> {
IMessage message = context.getMessage();
String query = String.join(" ", context.getOptionSet().valuesOf(nonOptSpec));
answer(message, "Retrieving profile...");
Long steamId64 = gameQueryService.getSteamId64(query)
.exceptionally(t -> {
log.warn("Could not resolve {} to a steamId64", query, t);
return null;
}).join();
if (steamId64 == null) {
sendMessage(message.getChannel(), baseEmbed()
.withColor(new Color(0xaa0000))
.withTitle("Error")
.appendDescription("Could not resolve " + query + " to a valid Steam ID")
.build());
return;
}
sendMessage(message.getChannel(), getUserInfo(steamId64));
}).build();
}
private EmbedBuilder baseEmbed() {
return new EmbedBuilder()
.setLenient(true)
.withFooterIcon("https://upload.wikimedia.org/wikipedia/commons/thumb/8/83/Steam_icon_logo.svg/24px-Steam_icon_logo.svg.png")
.withFooterText("Steam");
}
private EmbedObject getUserInfo(Long steamId64) {
SteamPlayerProfile profile = gameQueryService.getPlayerProfile(steamId64)
.exceptionally(t -> {
log.warn("Could not get profile for {}", steamId64, t);
return null;
}).join();
List<SteamBanStatus> bans = gameQueryService.getPlayerBans(steamId64)
.exceptionally(t -> {
log.warn("Could not get ban info for {}", steamId64, t);
return null;
}).join();
if (profile == null) {
return baseEmbed()
.withColor(new Color(0xaa0000))
.withTitle("Error")
.appendDescription("Could not get profile information for " + steamId64)
.build();
}
String steam2Id = steamId64To2(steamId64);
String steam3Id = steam2To3(steam2Id);
EmbedBuilder builder = baseEmbed()
.withTitle(profile.getName())
.withColor(getDominantColor(profile.getAvatarUrl(), new Color(0x0e3496)))
.withThumbnail(profile.getAvatarFullUrl())
.withUrl("http://steamcommunity.com/profiles/" + steamId64)
.appendField("Steam3ID", steam3Id, true)
.appendField("SteamID32", steam2Id, true)
.appendField("SteamID64", "http://steamcommunity.com/profiles/" + steamId64, false);
if (isPublic(profile.getCommunityVisibilityState())) {
builder.appendField("Status", personaState(profile.getPersonaState()), true)
.appendField("Last Logoff", withRelative(Instant.ofEpochSecond(profile.getLastLogOff())), true)
.appendField("Joined", withRelative(Instant.ofEpochSecond(profile.getTimeCreated())), false);
} else {
builder.appendField("Status", "Private", true)
.appendField("Last Logoff", withRelative(Instant.ofEpochSecond(profile.getLastLogOff())), true);
}
if (bans != null) {
SteamBanStatus status = bans.stream().findAny().orElse(null);
if (status != null && (!"none".equals(status.getEconomyBan()) || status.isVacBanned() || status.isCommunityBanned())) {
builder.withColor(new Color(0xaa0000))
.appendField("Trade Ban", capitalizeFully(status.getEconomyBan()), true)
.appendField("VAC Ban", (status.isVacBanned() ? "Banned" : "None"), true)
.appendField("Community Ban", (status.isCommunityBanned() ? "Banned" : "None"), true);
}
}
return builder.appendField("UGC", "http:
.appendField("Logs.tf", "http://logs.tf/profile/" + steamId64, false)
.appendField("SizzlingStats", "http://sizzlingstats.com/player/" + steamId64, false)
.build();
}
private boolean isPublic(int communityVisibilityState) {
return communityVisibilityState == 3;
}
private String personaState(int value) {
if (value >= 0 && value <= 6) {
return PERSONA_STATES[value];
}
return "?";
}
} |
package totemic_commons.pokefenn;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import net.minecraft.block.Block;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.Mod.EventHandler;
import net.minecraftforge.fml.common.Mod.Instance;
import net.minecraftforge.fml.common.SidedProxy;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLMissingMappingsEvent;
import net.minecraftforge.fml.common.event.FMLMissingMappingsEvent.MissingMapping;
import net.minecraftforge.fml.common.event.FMLPostInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import net.minecraftforge.fml.common.registry.GameRegistry.Type;
import net.minecraftforge.fml.relauncher.ReflectionHelper;
import totemic_commons.pokefenn.api.TotemicAPI;
import totemic_commons.pokefenn.apiimpl.ApiImpl;
import totemic_commons.pokefenn.configuration.ConfigurationHandler;
import totemic_commons.pokefenn.lib.Strings;
@Mod(modid = Totemic.MOD_ID, name = Totemic.MOD_NAME, version = Totemic.MOD_VERSION, acceptedMinecraftVersions = "[1.11.2,)",
dependencies = "required-after:forge@[13.20.0.2228,)", guiFactory = "totemic_commons.pokefenn.configuration.TotemicGuiFactory",
updateJSON = "https://raw.githubusercontent.com/TeamTotemic/Totemic/version/version.json")
public final class Totemic
{
public static final String MOD_ID = "totemic";
public static final String MOD_NAME = "Totemic";
public static final String MOD_VERSION = "${version}";
@Instance(MOD_ID)
public static Totemic instance;
@SidedProxy(clientSide = "totemic_commons.pokefenn.ClientProxy", serverSide = "totemic_commons.pokefenn.CommonProxy")
public static CommonProxy proxy;
public static final ApiImpl api = new ApiImpl();
public static final CreativeTabs tabsTotem = new CreativeTabTotemic(CreativeTabs.getNextID(), MOD_NAME);
public static final Logger logger = LogManager.getLogger(MOD_NAME);
@EventHandler
public void preInit(FMLPreInitializationEvent event)
{
logger.info("Moma had a cow, Moma had a chicken... Dad was proud, he didn't care how!");
logger.info("Totemic is entering preinitialization stage");
ConfigurationHandler.init(new File(event.getModConfigurationDirectory(), "totemic.cfg"));
ReflectionHelper.setPrivateValue(TotemicAPI.class, null, api, "instance"); //The instance field is private, need reflection
proxy.preInit(event);
}
@EventHandler
public void init(FMLInitializationEvent event)
{
logger.info("Totemic is entering initialization stage");
proxy.init(event);
}
@EventHandler
public void postInit(FMLPostInitializationEvent event)
{
logger.info("Totemic is entering postinitialization stage");
proxy.postInit(event);
}
//TODO: Remove at some point
@EventHandler
public void missingMappings(FMLMissingMappingsEvent event)
{
if(event.get().isEmpty())
return;
logger.info("Totemic is remapping legacy block/item names");
Map<String, String> mappings = new HashMap<>();
mappings.put("cedarlog", Strings.CEDAR_LOG_NAME);
mappings.put("totembase", Strings.TOTEM_BASE_NAME);
mappings.put("totempole", Strings.TOTEM_POLE_NAME);
mappings.put("totemsapling", Strings.CEDAR_SAPLING_NAME);
mappings.put("totemleaves", Strings.CEDAR_LEAVES_NAME);
mappings.put("totemtorch", Strings.TOTEM_TORCH_NAME);
mappings.put("totemdrum", Strings.DRUM_NAME);
mappings.put("windchime", Strings.WIND_CHIME_NAME);
mappings.put("redcedarplank", Strings.CEDAR_PLANK_NAME);
mappings.put("redcedarstripped", Strings.STRIPPED_CEDAR_LOG_NAME);
mappings.put("totemictipi", Strings.TIPI_NAME);
mappings.put("dummytotemictipi", Strings.DUMMY_TIPI_NAME);
mappings.put("totemwhittlingknife", Strings.TOTEM_WHITTLING_KNIFE_NAME);
mappings.put("totemicstaff", Strings.TOTEMIC_STAFF_NAME);
mappings.put("subitems", Strings.SUB_ITEMS_NAME);
mappings.put("jingledress", Strings.JINGLE_DRESS_NAME);
mappings.put("barkstripper", Strings.BARK_STRIPPER_NAME);
mappings.put("ceremonialrattle", Strings.RATTLE_NAME);
mappings.put("buffaloitems", Strings.BUFFALO_ITEMS_NAME);
mappings.put("buffalomeat", Strings.BUFFALO_MEAT_NAME);
mappings.put("buffalocookedmeat", Strings.COOKED_BUFFALO_MEAT_NAME);
mappings.put("medicinebag", Strings.MEDICINE_BAG_NAME);
mappings.put("baykokbow", Strings.BAYKOK_BOW_NAME);
for(MissingMapping mm: event.get())
{
String newName = mappings.get(mm.resourceLocation.getResourcePath());
if(newName != null)
{
if(mm.type == Type.BLOCK)
mm.remap(Block.REGISTRY.getObject(new ResourceLocation(MOD_ID, newName)));
else
mm.remap(Item.REGISTRY.getObject(new ResourceLocation(MOD_ID, newName)));
}
}
}
} |
package mondrian.rolap;
import mondrian.olap.*;
import mondrian.rolap.agg.*;
import mondrian.rolap.aggmatcher.AggGen;
import org.apache.log4j.Logger;
import org.eigenbase.util.property.*;
import org.eigenbase.util.property.Property;
import java.util.*;
/**
* A <code>FastBatchingCellReader</code> doesn't really read cells: when asked
* to look up the values of stored measures, it lies, and records the fact
* that the value was asked for. Later, we can look over the values which
* are required, fetch them in an efficient way, and re-run the evaluation
* with a real evaluator.
*
* <p>NOTE: When it doesn't know the answer, it lies by returning an error
* object. The calling code must be able to deal with that.</p>
*
* <p>This class tries to minimize the amount of storage needed to record the
* fact that a cell was requested.</p>
*/
public class FastBatchingCellReader implements CellReader {
private static final Logger LOGGER =
Logger.getLogger(FastBatchingCellReader.class);
/**
* This static variable controls the generation of aggregate table sql.
*/
private static boolean generateAggregateSql =
MondrianProperties.instance().GenerateAggregateSql.get();
static {
// Trigger is used to lookup and change the value of the
// variable that controls generating aggregate table sql.
// Using a trigger means we don't have to look up the property eveytime.
MondrianProperties.instance().GenerateAggregateSql.addTrigger(
new TriggerBase(true) {
public void execute(Property property, String value) {
generateAggregateSql = property.booleanValue();
}
});
}
private final RolapCube cube;
private final Set pinnedSegments;
private final Map<BatchKey, Batch> batches;
private int requestCount;
RolapAggregationManager aggMgr = AggregationManager.instance();
/**
* Indicates that the reader given incorrect results.
*/
private boolean dirty;
public FastBatchingCellReader(RolapCube cube) {
this.cube = cube;
this.pinnedSegments = new HashSet();
this.batches = new HashMap<BatchKey, Batch>();
}
public Object get(Evaluator evaluator) {
final RolapEvaluator rolapEvaluator = (RolapEvaluator) evaluator;
Member[] currentMembers = rolapEvaluator.getCurrentMembers();
CellRequest request =
RolapAggregationManager.makeRequest(currentMembers, false, false);
if (request == null || request.isUnsatisfiable()) {
return Util.nullValue; // request out of bounds
}
// Try to retrieve a cell and simultaneously pin the segment which
// contains it.
Object o = aggMgr.getCellFromCache(request, pinnedSegments);
if (o == Boolean.TRUE) {
// Aggregation is being loaded. (todo: Use better value, or
// throw special exception)
return RolapUtil.valueNotReadyException;
}
if (o != null) {
return o;
}
// if there is no such cell, record that we need to fetch it, and
// return 'error'
recordCellRequest(request);
return RolapUtil.valueNotReadyException;
}
public int getMissCount() {
return requestCount;
}
void recordCellRequest(CellRequest request) {
if (request.isUnsatisfiable()) {
return;
}
++requestCount;
BitKey bitkey = request.getConstrainedColumnsBitKey();
BatchKey key = new BatchKey(bitkey, request.getMeasure().getStar());
Batch batch = batches.get(key);
if (batch == null) {
batch = new Batch(request);
batches.put(key, batch);
if (LOGGER.isDebugEnabled()) {
StringBuilder buf = new StringBuilder(100);
buf.append("FastBatchingCellReader: bitkey=");
buf.append(request.getConstrainedColumnsBitKey());
buf.append(Util.nl);
RolapStar.Column[] columns = request.getConstrainedColumns();
for (RolapStar.Column column : columns) {
buf.append(" ");
buf.append(column);
buf.append(Util.nl);
}
LOGGER.debug(buf.toString());
}
}
batch.add(request);
}
/**
* Returns whether this reader has told a lie. This is the case if there
* are pending batches to load or if {@link #setDirty(boolean)} has been
* called.
*/
boolean isDirty() {
return dirty || !batches.isEmpty();
}
boolean loadAggregations()
{
return loadAggregations(null);
}
/**
* Loads pending aggregations, if any.
*
* @param query the parent query object that initiated this
* call
*
* @return Whether any aggregations were loaded.
*/
boolean loadAggregations(Query query) {
long t1 = System.currentTimeMillis();
requestCount = 0;
if (batches.isEmpty() && !dirty) {
return false;
}
// Sort the batches into deterministic order.
List<Batch> batchList = new ArrayList<Batch>(batches.values());
Collections.sort(batchList, BatchComparator.instance);
// Load batches in turn.
for (Batch batch : batchList) {
if (query != null) {
query.checkCancelOrTimeout();
}
(batch).loadAggregation();
}
batches.clear();
if (LOGGER.isDebugEnabled()) {
long t2 = System.currentTimeMillis();
LOGGER.debug("loadAggregation (millis): " + (t2 - t1));
}
dirty = false;
return true;
}
/**
* Sets the flag indicating that the reader has told a lie.
*/
void setDirty(boolean dirty) {
this.dirty = dirty;
}
private static final Logger BATCH_LOGGER = Logger.getLogger(Batch.class);
class Batch {
// these are the CellRequest's constrained columns
final RolapStar.Column[] columns;
// this is the CellRequest's constrained column BitKey
final BitKey constrainedColumnsBitKey;
final List<RolapStar.Measure> measuresList = new ArrayList<RolapStar.Measure>();
final Set<ColumnConstraint>[] valueSets;
public Batch(CellRequest request) {
columns = request.getConstrainedColumns();
constrainedColumnsBitKey = request.getConstrainedColumnsBitKey();
valueSets = new HashSet[columns.length];
for (int i = 0; i < valueSets.length; i++) {
valueSets[i] = new HashSet<ColumnConstraint>();
}
}
public void add(CellRequest request) {
List<ColumnConstraint> values = request.getValueList();
for (int j = 0; j < columns.length; j++) {
valueSets[j].add(values.get(j));
}
RolapStar.Measure measure = request.getMeasure();
if (!measuresList.contains(measure)) {
assert (measuresList.size() == 0) ||
(measure.getStar() ==
(measuresList.get(0)).getStar()):
"Measure must belong to same star as other measures";
measuresList.add(measure);
}
}
/**
* This can only be called after the add method has been called.
*
* @return the RolapStar associated with the Batch's first Measure.
*/
private RolapStar getStar() {
RolapStar.Measure measure = measuresList.get(0);
return measure.getStar();
}
void loadAggregation() {
if (generateAggregateSql) {
RolapCube cube = FastBatchingCellReader.this.cube;
if (cube == null || cube.isVirtual()) {
StringBuilder buf = new StringBuilder(64);
buf.append("AggGen: Sorry, can not create SQL for virtual Cube \"");
buf.append(FastBatchingCellReader.this.cube.getName());
buf.append("\", operation not currently supported");
BATCH_LOGGER.error(buf.toString());
} else {
AggGen aggGen = new AggGen(
FastBatchingCellReader.this.cube.getStar(), columns);
if (aggGen.isReady()) {
// PRINT TO STDOUT - DO NOT USE BATCH_LOGGER
System.out.println("createLost:" +
Util.nl + aggGen.createLost());
System.out.println("insertIntoLost:" +
Util.nl + aggGen.insertIntoLost());
System.out.println("createCollapsed:" +
Util.nl + aggGen.createCollapsed());
System.out.println("insertIntoCollapsed:" +
Util.nl + aggGen.insertIntoCollapsed());
} else {
BATCH_LOGGER.error("AggGen failed");
}
}
}
long t1 = System.currentTimeMillis();
AggregationManager aggmgr = AggregationManager.instance();
ColumnConstraint[][] constraintses =
new ColumnConstraint[columns.length][];
for (int j = 0; j < columns.length; j++) {
Set valueSet = valueSets[j];
ColumnConstraint[] constraints;
if ((valueSet == null)) {
constraints = null;
} else {
constraints = new ColumnConstraint[valueSet.size()];
valueSet.toArray(constraints);
// Sort array to achieve determinism in generated SQL.
Arrays.sort(constraints);
}
constraintses[j] = constraints;
}
// TODO: optimize key sets; drop a constraint if more than x% of
// the members are requested; whether we should get just the cells
// requested or expand to a n-cube
// If the database cannot execute "count(distinct ...)", split the
// distinct aggregations out.
if (!getStar().getSqlQueryDialect().allowsCountDistinct()) {
while (true) {
// Scan for a measure based upon a distinct aggregation.
RolapStar.Measure distinctMeasure =
getFirstDistinctMeasure(measuresList);
if (distinctMeasure == null) {
break;
}
final String expr = distinctMeasure.getExpression().
getGenericExpression();
final List<RolapStar.Measure> distinctMeasuresList = new ArrayList<RolapStar.Measure>();
for (int i = 0; i < measuresList.size();) {
RolapStar.Measure measure =
measuresList.get(i);
if (measure.getAggregator().isDistinct() &&
measure.getExpression().getGenericExpression().
equals(expr))
{
measuresList.remove(i);
distinctMeasuresList.add(distinctMeasure);
} else {
i++;
}
}
RolapStar.Measure[] measures =
distinctMeasuresList.toArray(
new RolapStar.Measure[distinctMeasuresList.size()]);
aggmgr.loadAggregation(measures, columns,
constrainedColumnsBitKey,
constraintses, pinnedSegments);
}
}
final int measureCount = measuresList.size();
if (measureCount > 0) {
RolapStar.Measure[] measures =
measuresList.toArray(new RolapStar.Measure[measureCount]);
aggmgr.loadAggregation(
measures, columns,
constrainedColumnsBitKey,
constraintses, pinnedSegments);
}
if (BATCH_LOGGER.isDebugEnabled()) {
long t2 = System.currentTimeMillis();
BATCH_LOGGER.debug("Batch.loadAggregation (millis) " + (t2 - t1));
}
}
/**
* Returns the first measure based upon a distinct aggregation, or null if
* there is none.
*/
RolapStar.Measure getFirstDistinctMeasure(List<RolapStar.Measure> measuresList) {
for (int i = 0; i < measuresList.size(); i++) {
RolapStar.Measure measure = measuresList.get(i);
if (measure.getAggregator().isDistinct()) {
return measure;
}
}
return null;
}
}
/**
* This is needed because for a Virtual Cube: two CellRequests
* could have the same BitKey but have different underlying
* base cubes. Without this, one get the result in the
* SegmentArrayQuerySpec addMeasure Util.assertTrue being
* triggered (which is what happened).
*/
class BatchKey {
BitKey key;
RolapStar star;
BatchKey(BitKey key, RolapStar star) {
this.key = key;
this.star = star;
}
public int hashCode() {
return key.hashCode() ^ star.hashCode();
}
public boolean equals(Object other) {
if (other instanceof BatchKey) {
BatchKey bkey = (BatchKey) other;
return key.equals(bkey.key) && star.equals(bkey.star);
} else {
return false;
}
}
public String toString() {
return star.getFactTable().getTableName() + " " + key.toString();
}
}
private static class BatchComparator implements Comparator<Batch> {
static final BatchComparator instance = new BatchComparator();
private BatchComparator() {}
public int compare(
Batch o1, Batch o2) {
if (o1.columns.length != o2.columns.length) {
return o1.columns.length - o2.columns.length;
}
for (int i = 0; i < o1.columns.length; i++) {
int c = o1.columns[i].getName().compareTo(
o2.columns[i].getName());
if (c != 0) {
return c;
}
}
for (int i = 0; i < o1.columns.length; i++) {
int c = compare(o1.valueSets[i], o2.valueSets[i]);
if (c != 0) {
return c;
}
}
return 0;
}
<T> int compare(Set<T> set1, Set<T> set2) {
if (set1.size() != set2.size()) {
return set1.size() - set2.size();
}
Iterator<T> iter1 = set1.iterator();
Iterator<T> iter2 = set2.iterator();
while (iter1.hasNext()) {
T v1 = iter1.next();
T v2 = iter2.next();
int c = Util.compareKey(v1, v2);
if (c != 0) {
return c;
}
}
return 0;
}
}
}
// End FastBatchingCellReader.java |
package org.testng.reporters;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.testng.ITestContext;
import org.testng.ITestResult;
import org.testng.internal.IResultListener;
import org.testng.internal.Utils;
/**
* A JUnit XML report generator (replacing the original JUnitXMLReporter that was
* based on XML APIs).
*
* @author <a href='mailto:the[dot]mindstorm[at]gmail[dot]com'>Alex Popescu</a>
*/
public class JUnitXMLReporter implements IResultListener {
private static final Pattern ENTITY= Pattern.compile("&[a-zA-Z]+;.*");
private static final Pattern LESS= Pattern.compile("<");
private static final Pattern GREATER= Pattern.compile(">");
private static final Pattern SINGLE_QUOTE = Pattern.compile("'");
private static final Pattern QUOTE = Pattern.compile("\"");
private static final Map<String, Pattern> ATTR_ESCAPES= new HashMap<String, Pattern>();
static {
ATTR_ESCAPES.put("<", LESS);
ATTR_ESCAPES.put(">", GREATER);
ATTR_ESCAPES.put("'", SINGLE_QUOTE);
ATTR_ESCAPES.put(""", QUOTE);
}
private String m_outputFileName= null;
private File m_outputFile= null;
private ITestContext m_testContext= null;
/**
* keep lists of all the results
*/
private int m_numPassed= 0;
private int m_numFailed= 0;
private int m_numSkipped= 0;
private int m_numFailedButIgnored= 0;
private List<ITestResult> m_allTests= Collections.synchronizedList(new ArrayList<ITestResult>());
private List<ITestResult> m_configIssues= Collections.synchronizedList(new ArrayList<ITestResult>());
public void onTestStart(ITestResult result) {
}
/**
* Invoked each time a test succeeds.
*/
public void onTestSuccess(ITestResult tr) {
m_allTests.add(tr);
m_numPassed++;
}
public void onTestFailedButWithinSuccessPercentage(ITestResult tr) {
m_allTests.add(tr);
m_numFailedButIgnored++;
}
/**
* Invoked each time a test fails.
*/
public void onTestFailure(ITestResult tr) {
m_allTests.add(tr);
m_numFailed++;
}
/**
* Invoked each time a test is skipped.
*/
public void onTestSkipped(ITestResult tr) {
m_allTests.add(tr);
m_numSkipped++;
}
/**
* Invoked after the test class is instantiated and before
* any configuration method is called.
*
*/
public void onStart(ITestContext context) {
m_outputFileName= context.getOutputDirectory() + File.separator + context.getName() + ".xml";
m_outputFile= new File(m_outputFileName);
m_testContext= context;
}
/**
* Invoked after all the tests have run and all their
* Configuration methods have been called.
*
*/
public void onFinish(ITestContext context) {
generateReport();
}
/**
* @see org.testng.internal.IConfigurationListener#onConfigurationFailure(org.testng.ITestResult)
*/
public void onConfigurationFailure(ITestResult itr) {
m_configIssues.add(itr);
}
/**
* @see org.testng.internal.IConfigurationListener#onConfigurationSkip(org.testng.ITestResult)
*/
public void onConfigurationSkip(ITestResult itr) {
m_configIssues.add(itr);
}
/**
* @see org.testng.internal.IConfigurationListener#onConfigurationSuccess(org.testng.ITestResult)
*/
public void onConfigurationSuccess(ITestResult itr) {
}
/**
* generate the XML report given what we know from all the test results
*/
protected void generateReport() {
try {
XMLStringBuffer document= new XMLStringBuffer("");
document.setXmlDetails("1.0", "UTF-8");
Properties attrs= new Properties();
attrs.setProperty(XMLConstants.ATTR_NAME, encodeAttr(m_testContext.getName())); // ENCODE
attrs.setProperty(XMLConstants.ATTR_TESTS, "" + m_allTests.size());
attrs.setProperty(XMLConstants.ATTR_FAILURES, "" + m_numFailed);
attrs.setProperty(XMLConstants.ATTR_ERRORS, "0");
attrs.setProperty(XMLConstants.ATTR_TIME, ""
+ ((m_testContext.getEndDate().getTime() - m_testContext.getStartDate().getTime()) / 1000.0));
document.push(XMLConstants.TESTSUITE, attrs);
document.addEmptyElement(XMLConstants.PROPERTIES);
for(ITestResult tr : m_configIssues) {
createElement(document, tr);
}
for(ITestResult tr : m_allTests) {
createElement(document, tr);
}
document.pop();
BufferedWriter fw= new BufferedWriter(new FileWriter(m_outputFile));
fw.write(document.toXML());
fw.flush();
fw.close();
}
catch(IOException ioe) {
ioe.printStackTrace();
System.err.println("failed to create JUnitXML because of " + ioe);
}
}
private void createElement(XMLStringBuffer doc, ITestResult tr) {
Properties attrs= new Properties();
long elapsedTimeMillis= tr.getEndMillis() - tr.getStartMillis();
String name= tr.getMethod().isTest() ? tr.getName() : Utils.detailedMethodName(tr.getMethod(), false);
attrs.setProperty(XMLConstants.ATTR_NAME, name);
attrs.setProperty(XMLConstants.ATTR_CLASSNAME, tr.getTestClass().getRealClass().getName());
attrs.setProperty(XMLConstants.ATTR_TIME, "" + (((double) elapsedTimeMillis) / 1000));
if((ITestResult.FAILURE == tr.getStatus()) || (ITestResult.SKIP == tr.getStatus())) {
doc.push(XMLConstants.TESTCASE, attrs);
if(ITestResult.FAILURE == tr.getStatus()) {
createFailureElement(doc, tr);
}
else if(ITestResult.SKIP == tr.getStatus()) {
createSkipElement(doc, tr);
}
doc.pop();
}
else {
doc.addEmptyElement(XMLConstants.TESTCASE, attrs);
}
}
private void createFailureElement(XMLStringBuffer doc, ITestResult tr) {
Properties attrs= new Properties();
Throwable t= tr.getThrowable();
if(t != null) {
attrs.setProperty(XMLConstants.ATTR_TYPE, t.getClass().getName());
String message= t.getMessage();
if((message != null) && (message.length() > 0)) {
attrs.setProperty(XMLConstants.ATTR_MESSAGE, encodeAttr(message)); // ENCODE
}
doc.push(XMLConstants.FAILURE, attrs);
doc.addCDATA(Utils.stackTrace(t, false)[0]);
doc.pop();
}
else {
doc.addEmptyElement(XMLConstants.FAILURE); // THIS IS AN ERROR
}
}
private void createSkipElement(XMLStringBuffer doc, ITestResult tr) {
doc.addEmptyElement("skipped");
}
private String encodeAttr(String attr) {
String result= replaceAmpersand(attr, ENTITY);
for(Map.Entry<String, Pattern> e: ATTR_ESCAPES.entrySet()) {
result= e.getValue().matcher(result).replaceAll(e.getKey());
}
return result;
}
private String replaceAmpersand(String str, Pattern pattern) {
int start = 0;
int idx = str.indexOf('&', start);
if(idx == -1) return str;
StringBuffer result= new StringBuffer();
while(idx != -1) {
result.append(str.substring(start, idx));
if(pattern.matcher(str.substring(idx)).matches()) {
// do nothing it is an entity;
result.append("&");
}
else {
result.append("&");
}
start= idx + 1;
idx= str.indexOf('&', start);
}
result.append(str.substring(start));
return result.toString();
}
} |
package fi.cosky.sdk.tests;
import java.util.ArrayList;
import java.util.List;
import fi.cosky.sdk.*;
import fi.cosky.sdk.CoordinateData.CoordinateSystem;
public class TestHelper {
static API authenticate() {
String url = "";
String clientKey = "";
String clientSecret = "";
API api = new API(url);
api.authenticate(clientKey, clientSecret);
return api;
}
static UserData getOrCreateUser( API api ) {
ApiData apiData = api.navigate(ApiData.class, api.getRoot());
UserDataSet users = api.navigate(UserDataSet.class, apiData.getLink("list-users"));
UserData user = null;
if ( users.getItems() != null && users.getItems().size() < 1) {
user = new UserData();
ResponseData createdUser = api.navigate(ResponseData.class, apiData.getLink("create-user"), user);
user = api.navigate(UserData.class, createdUser.getLocation());
} else {
for (UserData u : users.getItems()) {
if (u.getId() == 1) user = u;
}
}
return user;
}
static RoutingProblemData createProblem(API api, UserData user) {
RoutingProblemData problem = new RoutingProblemData("exampleProblem");
ResponseData created = api.navigate(ResponseData.class, user.getLink("create-problem"), problem);
problem = api.navigate(RoutingProblemData.class, created.getLocation());
return problem;
}
static RoutingProblemData createProblemWithDemoData(API api, UserData user) {
RoutingProblemData problem = createProblem(api, user);
TestData.CreateDemoData(problem, api);
return problem;
}
static VehicleData getVehicle(API api, UserData user, RoutingProblemData problem) {
TestData.CreateDemoData(problem, api);
VehicleDataSet vehicles = api.navigate(VehicleDataSet.class, problem.getLink("list-vehicles"));
VehicleData vehicle = null;
for (VehicleData v : vehicles.getItems()) {
if (v.getId() == 1) vehicle = v;
}
return vehicle;
}
static TaskData getTask(API api, RoutingProblemData problem) {
CoordinateData pickup = new CoordinateData();
pickup.setLatitude(62.244958);
pickup.setLongitude(25.747143);
pickup.setSystem(CoordinateSystem.Euclidian);
LocationData pi = new LocationData();
pi.setCoordinatesData(pickup);
CoordinateData delivery = new CoordinateData();
delivery.setLatitude(62.244589);
delivery.setLongitude(25.74892);
delivery.setSystem(CoordinateSystem.Euclidian);
LocationData de = new LocationData();
de.setCoordinatesData(delivery);
CapacityData capacity = new CapacityData("Weight", 20);
List<CapacityData> capacities = new ArrayList<CapacityData>();
capacities.add(capacity);
TaskEventUpdateRequest task1 = new TaskEventUpdateRequest(Type.Pickup, pi, capacities);
TaskEventUpdateRequest task2 = new TaskEventUpdateRequest(Type.Delivery, de, capacities);
List<TaskEventUpdateRequest> both = new ArrayList<TaskEventUpdateRequest>();
both.add(task1);
both.add(task2);
TaskUpdateRequest task = new TaskUpdateRequest(both);
task.setName("testTask");
ResponseData createdTask = api.navigate(ResponseData.class, problem.getLink("create-task"), task);
TaskData td = api.navigate(TaskData.class, createdTask.getLocation());
return td;
}
} |
package functionaltests;
import java.io.File;
import java.net.URL;
import java.util.Map.Entry;
import org.junit.Assert;
import org.ow2.proactive.scheduler.common.job.JobId;
import org.ow2.proactive.scheduler.common.job.JobResult;
import org.ow2.proactive.scheduler.common.task.TaskResult;
import functionalTests.FunctionalTest;
/**
* This class tests a basic actions of a job submission to ProActive scheduler :
* Connection to scheduler, with authentication
* Register a monitor to Scheduler in order to receive events concerning
* job submission.
*
* Submit a Task flow job (test 1).
* After the job submission, the test monitor all jobs states changes, in order
* to observe its execution :
* job submitted (test 2),
* job pending to running (test 3),
* all task pending to running, and all tasks running to finished (test 4),
* job running to finished (test 5).
* After it retrieves job's result and check that all
* tasks results are available (test 6).
*
* @author The ProActive Team
* @date 2 jun 08
* @since ProActive Scheduling 1.0
*/
public class TestJobTaskFlowSubmission extends FunctionalTest {
private static URL jobDescriptor = TestJobTaskFlowSubmission.class
.getResource("/functionaltests/descriptors/Job_PI.xml");
/**
* Tests start here.
*
* @throws Throwable any exception that can be thrown during the test.
*/
@org.junit.Test
public void run() throws Throwable {
JobId id = SchedulerTHelper.testJobSubmission(new File(jobDescriptor.toURI()).getAbsolutePath());
// check result are not null
JobResult res = SchedulerTHelper.getJobResult(id);
Assert.assertFalse(SchedulerTHelper.getJobResult(id).hadException());
for (Entry<String, TaskResult> entry : res.getAllResults().entrySet()) {
Assert.assertNotNull(entry.getValue().value());
}
//remove job
SchedulerTHelper.removeJob(id);
SchedulerTHelper.waitForEventJobRemoved(id);
}
} |
package info.tregmine.teleport;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import java.util.logging.Logger;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;
import info.tregmine.Tregmine;
//import info.tregmine.api.TregminePlayer;
import info.tregmine.database.ConnectionPool;
public class Teleport extends JavaPlugin {
public final Logger log = Logger.getLogger("Minecraft");
public Tregmine tregmine = null;
public Player from = null;
@Override
public void onEnable(){
Plugin test = this.getServer().getPluginManager().getPlugin("Tregmine");
if(this.tregmine == null) {
if(test != null) {
this.tregmine = ((Tregmine)test);
} else {
log.info(this.getDescription().getName() + " " + this.getDescription().getVersion() + " - could not find Tregmine");
this.getServer().getPluginManager().disablePlugin(this);
}
}
}
@Override
public void onDisable(){
}
@Override
public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) {
String commandName = command.getName().toLowerCase();
if(!(sender instanceof Player)) {
return false;
} else {
from = (Player) sender;
}
info.tregmine.api.TregminePlayer tregminePlayer = this.tregmine.tregminePlayer.get(from.getName());
if(commandName.equals("tpto") && tregminePlayer.isAdmin()) {
Location loc = new Location(from.getWorld(), Integer.parseInt(args[0]), Integer.parseInt(args[1]),Integer.parseInt(args[2]) );
loc.getWorld().loadChunk(loc.getWorld().getChunkAt(loc));
if (loc.getWorld().isChunkLoaded(loc.getWorld().getChunkAt(loc))){
from.teleport(loc);
}
return true;
}
if(commandName.equals("home") && tregminePlayer.isDonator()) {
Home home = new Home(from.getName(), getServer());
if (args.length == 0) {
Location loc = home.get();
if (loc == null) {
from.sendMessage(ChatColor.RED + "Telogric lift malfunctioned. Teleportation failed.");
return true;
}
loc.getWorld().loadChunk(loc.getWorld().getChunkAt(loc));
if (loc.getWorld().isChunkLoaded(loc.getWorld().getChunkAt(loc))){
if (!loc.getWorld().getName().matches(from.getWorld().getName())) {
from.sendMessage(ChatColor.RED + "You can't use a home thats in another world!");
return true;
}
from.teleport(loc);
from.sendMessage(ChatColor.AQUA + "Hoci poci, little gnome. Magic worked, you're in your home!");
} else {
from.sendMessage(ChatColor.RED + "Loading your home chunk failed, try /home again.");
}
} else if ("save".matches(args[0])) {
if (from.getLocation().getWorld().getName().matches("world_the_end")) {
from.sendMessage(ChatColor.RED + "You can't set your home in The End");
return true;
}
if (info.tregmine.api.math.Distance.calc2d(this.getServer().getWorld("world").getSpawnLocation(), tregminePlayer.getLocation()) < 700) {
from.sendMessage(ChatColor.RED + "Telogric lift malfunctioned. Teleportation failed, to close to spawn.");
return true;
}
home.save(from.getLocation());
from.sendMessage(ChatColor.AQUA + "Home saved!");
} else if ("to".equals(args[0]) && (tregminePlayer.getMetaBoolean("mentor") || tregminePlayer.isAdmin())) {
if (args.length < 2) {
from.sendMessage(ChatColor.RED + "Usage: /home to <player>.");
return true;
}
String playerName = args[1];
Home playersHome = new Home(playerName, getServer());
Location loc = playersHome.get();
if (loc == null) {
from.sendMessage(ChatColor.RED + "Telogric lift malfunctioned. Teleportation failed.");
return true;
}
loc.getWorld().loadChunk(loc.getWorld().getChunkAt(loc));
if (loc.getWorld().isChunkLoaded(loc.getWorld().getChunkAt(loc))){
from.teleport(loc);
from.sendMessage(ChatColor.AQUA + "Like a drunken gnome, you fly across the world to " + playerName
+ "'s home. Try not to hit any birds.");
from.sendMessage(ChatColor.RED + "Loading of home chunk failed, try /home again");
}
}
return true;
}
if(commandName.equals("makewarp") && tregminePlayer.isAdmin()) {
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = ConnectionPool.getConnection();
stmt = conn.prepareStatement("insert into warps (name, x, y, z, yaw, pitch, world) values (?, ?, ?, ?, ?, ?, ?)");
Location loc = tregminePlayer.getLocation();
stmt.setString(1, args[0]);
stmt.setDouble(2, loc.getX());
stmt.setDouble(3, loc.getY());
stmt.setDouble(4, loc.getZ());
stmt.setFloat(5, loc.getYaw());
stmt.setFloat(6, loc.getPitch());
stmt.setString(7, loc.getWorld().getName());
stmt.execute();
tregminePlayer.sendMessage("Warp "+ args[0] +" created");
this.log.info("WARPCREATE: " + args[0] + " by " + tregminePlayer.getName());
} catch (SQLException e) {
tregminePlayer.sendMessage("Warp creation error");
throw new RuntimeException(e);
} finally {
if (stmt != null) {
try { stmt.close(); } catch (SQLException e) {}
}
if (conn != null) {
try { conn.close(); } catch (SQLException e) {}
}
}
return true;
}
if(commandName.equals("tp") && tregminePlayer.isTrusted()) {
try {
List<Player> to = this.getServer().matchPlayer(args[0]);
Tp tp = new Tp(from, to.get(0), this);
tp.hashCode();
return true;
} catch (Exception e) {
return false;
}
}
if(commandName.equals("s") && tregminePlayer.isAdmin()) {
Player victim = this.getServer().matchPlayer(args[0]).get(0);
if (victim != null ){
if (victim.getName().matches("einand")) {
from.sendMessage(ChatColor.RED + "Forbidden command.");
victim.sendMessage(from.getName() + " tried to summon you.");
return true;
}
info.tregmine.api.TregminePlayer victimPlayer = this.tregmine.tregminePlayer.get(victim.getName());
victim.setNoDamageTicks(200);
victim.teleport(from.getLocation());
victim.sendMessage(tregminePlayer.getChatName() + ChatColor.AQUA + " summoned you.");
from.sendMessage(ChatColor.AQUA + "You summoned " + victimPlayer.getChatName() + ChatColor.AQUA + " to yourself.");
} else {
from.sendMessage(ChatColor.RED + "Can't find user.");
}
return true;
}
if(commandName.equals("warp")) {
Warp warp = new Warp(this, from, args);
warp.run();
return true;
}
if (commandName.matches("spawn")) {
from.teleport(from.getWorld().getSpawnLocation());
return true;
}
return false;
}
@Override
public void onLoad() {
}
} |
package com.yagadi.enguage;
import com.yagadi.enguage.interpretant.Allopoiesis;
import com.yagadi.enguage.interpretant.Autoload;
import com.yagadi.enguage.interpretant.Concepts;
import com.yagadi.enguage.interpretant.Net;
import com.yagadi.enguage.interpretant.Repertoire;
import com.yagadi.enguage.object.Overlay;
import com.yagadi.enguage.object.Sofa;
import com.yagadi.enguage.util.Audit;
import com.yagadi.enguage.util.Fs;
import com.yagadi.enguage.util.Shell;
import com.yagadi.enguage.util.Strings;
import com.yagadi.enguage.vehicle.Question;
import com.yagadi.enguage.vehicle.Reply;
import com.yagadi.enguage.vehicle.Utterance;
import com.yagadi.enguage.vehicle.where.Where;
public class Enguage extends Shell {
public Enguage() { super( "Enguage" ); }
static private Audit audit = new Audit( "Enguage" );
/* Enguage is a singleton, so that its internals can refer to the outer instance.
*/
static private Enguage e = new Enguage();
static public Enguage get() { return e; }
static public void set( String location ) {
audit.in( "Engauge", "location=" + location );
if (!Fs.location( location ))
audit.FATAL( location + ": not found" );
else if (!Overlay.autoAttach())
audit.FATAL( "Ouch! Cannot autoAttach() to object space" );
else {
Concepts.names( location );
Allopoiesis.spokenInit();
Repertoire.primeUsedInit();
}
audit.out();
}
public Overlay o = Overlay.Get();
public void log( String s ) { audit.log( s ); }
private Config config = new Config();
public Enguage loadConfig() { config.load(); return this; }
@Override
public String interpret( Strings utterance ) {
audit.in( "interpret", utterance.toString() );
//if (!audit.tracing && !Audit.allTracing) audit.log( utterance.toString( Strings.SPACED ));
if (Reply.understood()) // from previous interpretation!
o.startTxn( Allopoiesis.undoIsEnabled() ); // all work in this new overlay
Reply r = Repertoire.interpret( new Utterance( utterance ));
// once processed, keep a copy
Utterance.previous( utterance );
String reply = r.toString( utterance );
if (Reply.understood()) {
o.finishTxn( Allopoiesis.undoIsEnabled() );
Allopoiesis.disambOff();
Allopoiesis.spoken( true );
} else {
// really lost track?
audit.debug( "Enguage:interpret(): not understood, forgeting to ignore: " + Repertoire.signs.ignore().toString() );
Repertoire.signs.ignoreNone();
aloudIs( true ); // sets aloud for whole session if reading from fp
}
// autoload() in Repertoire.interpret() -- there is a reason for this asymmetry
if (!Repertoire.isInducting() && !Autoload.ing()) Autoload.unload();
return audit.out( reply );
}
public static String interpret( String utterance ) {
return Enguage.get().interpret( new Strings( utterance ));
}
public static void loadConfig( String location ) {
set( location );
Enguage.get().loadConfig();
}
private static void testInterpret( String cmd, String expected ) {
if (expected != null)
audit.log( "enguage> "+ cmd );
String answer = Enguage.interpret( cmd );
if (expected != null)
if (!Reply.understood() && !Repertoire.prompt().equals( "" ))
audit.log( "Hint is:" + Repertoire.prompt() );
else if ( !expected.equals( "" )
&& !new Strings( answer )
.equalsIgnoreCase( new Strings( expected )))
audit.FATAL("reply:"+ answer +",\n expected:"+ expected );
else
audit.log( answer +"\n" );
}
private static void testInterpret( String cmd ) { testInterpret( cmd, "" );}
private static void usage() {
audit.LOG( "Usage: java -jar enguage.jar [-c <configDir>] [-p <port> | -s | -t ]" );
audit.LOG( "where: default config dir=\".src/assets\"" );
audit.LOG( " : -p <port> listens on a TCP/IP port" );
audit.LOG( " : -s runs Engauge as a shell" );
audit.LOG( " : -t runs a test sanity check" );
}
public static void main( String args[] ) {
if (args.length == 0)
usage();
else {
int argc = 0;
if (args.length > 1 && args[ argc ].equals( "-c" )) {
argc++;
Enguage.loadConfig( args[ argc++ ]);
} else
Enguage.loadConfig( "./src/assets" );
if ( args.length == argc + 1 && args[ argc ].equals( "-s" ))
e.aloudIs( true ).run();
else if (args.length == argc + 2 && args[ argc ].equals( "-p" ))
Net.server( args[ ++argc ]);
else if (args.length == argc + 1 && args[ argc ].equals( "-t" ))
sanityCheck();
else
usage();
} }
private static void sanityCheck() {
// useful ephemera
//Repertoire.signs.show();
//testInterpret( "detail on" );
//testInterpret( "tracing on" );
int level = 0;
if ( level == 0 || level == 1 ) {
audit.title( "The Non-Computable concept of NEED" );
// silently clear the decks
Question.primedAnswer( "yes" );
testInterpret( "i don't need anything", null );
testInterpret( "what do i need",
"you don't need anything." );
testInterpret( "i need 2 cups of coffee and a biscuit",
"ok, you need 2 cups of coffee, and a biscuit.");
testInterpret( "what do i need",
"you need 2 cups of coffee, and a biscuit.");
testInterpret( "how many coffees do i need",
"2, you need 2 coffees." );
testInterpret( "i don't need any coffee",
"ok, you don't need any coffee." );
testInterpret( "what do i need",
"you need a biscuit." );
audit.title( "Semantic Thrust" );
testInterpret( "i need to go to town",
"ok, you need to go to town." );
testInterpret( "what do i need",
"you need a biscuit, and to go to town." );
testInterpret( "i have a biscuit",
"ok, you don't need a biscuit." );
testInterpret( "i have to go to town",
"I know." );
testInterpret( "i don't need to go to town",
"ok, you don't need to go to town." );
Question.primedAnswer( "yes" );
testInterpret( "I have everything",
"ok, you don't need anything." );
testInterpret( "what do i need",
"you don't need anything." );
}
if ( level == 0 || level == 3 ) {
audit.title( "Verbal Arithmetical" );
testInterpret( "what is 1 + 2",
"1 plus 2 is 3.");
testInterpret( "times 2 all squared",
"times 2 all squared makes 36.");
testInterpret( "what is 36 + 4 all divided by 2",
"36 plus 4 all divided by 2 is 20." );
//testInterpret( "unset the value of subtotal", "ok." );
/*
testInterpret( "interpret the factorial of numeric phrase variable n thus", "go on." );
testInterpret( "first perform numeric evaluate variable n - 1", "go on." );
testInterpret( "then the factorial of whatever", "go on." );
testInterpret( "then times variable n", "go on." );
testInterpret( "then reply whatever", "go on." );
testInterpret( "ok", "ok." );
//Repertoire.signs.show( "OTF" );
testInterpret( "tracing on" );
//testInterpret( "the factorial of 3", "6." );
testInterpret( "tracing off" );
testInterpret( "unset the value of subtotal", "ok." );
//testInterpret( "on the phrase what is the factorial of numeric variable n reply the factorial of n is whatever" );
// */
}
if ( level == 0 || level == 4 ) {
audit.title( "Numerical Context" );
testInterpret( "i need a coffee",
"ok, you need a coffee." );
testInterpret( "and another",
"ok, you need 1 more coffee." );
testInterpret( "how many coffees do i need",
"2, you need 2 coffees." );
testInterpret( "i need a cup of tea",
"ok, you need a cup of tea." );
testInterpret( "and another coffee",
"ok, you need 1 more coffee." );
testInterpret( "what do i need",
"You need 3 coffees , and a cup of tea." );
}
if ( level == 0 || level == 5 ) {
audit.title( "Correction" );
testInterpret( "i need another coffee",
"ok, you need 1 more coffee.");
testInterpret( "no i need another 3",
"ok, you need 3 more coffees.");
testInterpret( "what do i need",
"you need 6 coffees, and a cup of tea.");
Question.primedAnswer( "yes" );
testInterpret( "i don't need anything",
"ok, you don't need anything." );
}
if ( level == 0 || level == 6 ) {
audit.title( "Disambiguation" );
testInterpret( "the eagle has landed"
//"Are you an ornithologist."
);
testInterpret( "no the eagle has landed"
//"So , you're talking about the novel."
);
testInterpret( "no the eagle has landed"
//"So you're talking about Apollo 11."
);
testInterpret( "no the eagle has landed"
//"I don't understand"
);
// Issue here: on DNU, we need to advance this on "the eagle has landed"
// i.e. w/o "no ..."
}
if ( level == 0 || level == 7 ) {
audit.title( "Temporal interpret" );
testInterpret( "what day is christmas day" );
//testInterpret( "what day is it today" );
audit.title( "Temporospatial concept MEETING" );
Where.doLocators();
new Sofa().interpret( new Strings( "entity create pub" ));
testInterpret( "I'm not meeting anybody",
"Ok , you're not meeting anybody." );
testInterpret( "At 7 I'm meeting my brother at the pub",
"Ok , you're meeting your brother at 7 at the pub." );
testInterpret( "When am I meeting my brother",
"You're meeting your brother at 7." );
testInterpret( "Where am I meeting my brother",
"You're meeting your brother at the pub." );
testInterpret( "Am I meeting my brother",
"Yes , you're meeting your brother." );
//testInterpret( "tracing on" );
testInterpret( "I'm meeting my sister at the pub" );
testInterpret( "When am I meeting my sister",
"I don't know when you're meeting your sister." );
//testInterpret( "tracing on" );
testInterpret( "When am I meeting my dad",
"i don't know if you're meeting your dad." );
testInterpret( "Where am I meeting my dad" ,
"i don't know if you're meeting your dad." );
}
if (level == 0 || level == 8) {
testInterpret( "tcpip localhost 999 \"999 is a test value for port address\"", "ok." );
testInterpret( "tcpip localhost 5678 \"this is a test, which will fail\"", "Sorry." );
}
if (level == 0 || level == 9) {
audit.title( "On-the-fly Langauge Learning" );
// First, what we can't say yet...
testInterpret( "my name is martin", "I don't understand." );
testInterpret( "if not reply i already know this", "I don't understand." );
testInterpret( "unset the value of name", "ok." );
// build-a-program...
testInterpret( "interpret my name is phrase variable name thus", "go on." );
testInterpret( "first set name to variable name", "go on." );
testInterpret( "then get the value of name", "go on." ); // not strictly necessary!
testInterpret( "then reply hello whatever", "go on." );
testInterpret( "and that is it", "ok." );
testInterpret( "my name is ruth", "hello ruth." );
testInterpret( "my name is martin", "hello martin." );
//...or to put it another way
testInterpret( "to the phrase i am called phrase variable name reply hi whatever", "go on." );
testInterpret( "this implies name gets set to variable name", "go on." );
testInterpret( "this implies name is not set to variable name", "go on." );
testInterpret( "if not reply i already know this", "go on." );
testInterpret( "ok", "ok." );
testInterpret( "i am called martin", "i already know this." );
// ...means.../...the means to...
// 1. from the-means-to repertoire
testInterpret( "to the phrase phrase variable x the means to phrase variable y reply i really do not understand", "go on." );
testInterpret( "that is it", "ok." );
testInterpret( "do we have the means to become rich", "I really don't understand." );
// 2. could this be built thus?
testInterpret( "to phrase variable this means phrase variable that reply ok", "go on." );
testInterpret( "this implies perform sign think variable that", "go on." );
testInterpret( "this implies perform sign create variable this", "go on." );
testInterpret( "ok", "ok." );
testInterpret( "just call me phrase variable name means i am called variable name", "ok." );
//Repertoire.signs.show( "OTF" );
testInterpret( "just call me martin", "i already know this." );
}
if ( level == 0 || level == 10 ) {
audit.title( "Ask: Confirmation" );
//testInterpret( "tracing on" );
Question.primedAnswer( "yes" );
testInterpret( "i have everything", "ok , you don't need anything." );
Question.primedAnswer( "no" );
testInterpret( "i have everything", "ok , let us leave things as they are." );
Question.primedAnswer( "i do not understand" );
testInterpret( "i have everything", "Ok , let us leave things as they are." );
}
audit.log( "PASSED" );
} } |
package mil.dds.anet.test.resources;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.GenericType;
import org.apache.commons.io.IOUtils;
import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.ImmutableMap;
import io.dropwizard.client.JerseyClientBuilder;
import mil.dds.anet.beans.Person;
public class GraphQLResourceTest extends AbstractResourceTest {
private Logger logger = LoggerFactory.getLogger(GraphQLResourceTest.class);
public GraphQLResourceTest() {
if (client == null) {
client = new JerseyClientBuilder(RULE.getEnvironment()).using(config).build("graphql test client");
}
}
@Test
public void test() {
Person arthur = getArthurDmin();
Person jack = getJackJackson();
Person steve = getSteveSteveson();
File testDir = new File("src/test/resources/graphQLTests/");
testDir.getAbsolutePath();
assertThat(testDir.isDirectory()).isTrue();
Map<String,Object> variables = new HashMap<String,Object>();
variables.put("personId", jack.getId().toString());
variables.put("positionId", jack.loadPosition().getId());
variables.put("orgId", steve.loadPosition().loadOrganization().getId());
variables.put("searchQuery", "hospital");
variables.put("reportId", jack.loadAttendedReports(0, 20).getList().get(0).getId());
variables.put("pageNum", 0);
variables.put("pageSize", 10);
variables.put("maxResults", 6);
logger.info("Using variables {}", variables);
for (File f : testDir.listFiles()) {
if (f.isFile()) {
try {
String raw = IOUtils.toString(new FileInputStream(f));
Map<String,Object> query = new HashMap<String,Object>();
for (Map.Entry<String, Object> entry : variables.entrySet()) {
raw = raw.replace("${" + entry.getKey() + "}", entry.getValue().toString());
}
query.put("query", "query { " + raw + "}");
query.put("variables", ImmutableMap.of());
logger.info("Processing file {}", f);
// Test POST request
Map<String,Object> respPost = httpQuery("/graphql", arthur)
.post(Entity.json(query), new GenericType<Map<String,Object>>() {});
doAsserts(f, respPost);
// Test GET request
Map<String,Object> respGet = httpQuery("/graphql?query=" + URLEncoder.encode("{" + raw + "}", "UTF-8"), arthur)
.get(new GenericType<Map<String,Object>>() {});
doAsserts(f, respGet);
// POST and GET responses should be equal
assertThat(respPost.get("data")).isEqualTo(respGet.get("data"));
} catch (IOException e) {
Assertions.fail("Unable to read file ", e);
}
}
}
}
private void doAsserts(File f, Map<String, Object> resp) {
assertThat(resp).isNotNull();
assertThat(resp.containsKey("errors"))
.as("Has Errors on %s : %s, %s",f.getName(),resp.get("errors"), resp.values().toString())
.isFalse();
assertThat(resp.containsKey("data")).as("Missing Data on " + f.getName(), resp).isTrue();
}
} |
package net.sf.jabb.util.text.test;
import java.util.Map;
import java.util.TreeSet;
import java.util.concurrent.atomic.AtomicLong;
import junit.framework.Assert;
import net.sf.jabb.util.stat.BasicFrequencyCounter;
import net.sf.jabb.util.text.NameDeduplicator;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class NameDeduplicatorTest {
static final int NUMBER_OF_THREADS = 50;
NameDeduplicator nd;
boolean stopNow = false;
BasicFrequencyCounter fc;
@Before
public void setUp() throws Exception {
nd = new NameDeduplicator();
fc = new BasicFrequencyCounter();
stopNow = false;
}
@After
public void tearDown() throws Exception {
}
@Test
public void test() throws InterruptedException {
//System.out.print("Starting threads: ");
Thread[] threads = new Thread[NUMBER_OF_THREADS];
for (int i = 0; i < NUMBER_OF_THREADS; i ++){
threads[i] = new Thread(){
public void run() {
while (!stopNow){
long l = nd.nextId("The Name");
fc.count(l);
}
}
};
threads[i].start();
}
//System.out.println("\nStarted " + NUMBER_OF_THREADS + " threads.");
Thread.sleep(10*1000);
stopNow = true;
//System.out.println("Stopping...");
for (Thread thread: threads){
thread.join();
}
//System.out.println("Checking...");
long id = 0;
for (Long k: new TreeSet<Long>(fc.getCounts().keySet())){
Assert.assertEquals(Long.valueOf(id), k);
Assert.assertEquals(1, fc.getCount(k));
id++;
}
//System.out.println("Done.");
}
} |
package org.cobu.randomsamplers;
import org.cobu.random.MersenneTwisterRandom;
import org.cobu.randomsamplers.weightedrecords.WeightedRecord;
import org.cobu.randomsamplers.weightedrecords.WeightedRecordAdapter;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
public class ReservoirSamplerWORTest {
private List<WeightedRecord> population = new ArrayList<WeightedRecord>();
@Before
public void setup() {
for (int i = 0; i < 4; i++) {
population.add(new WeightedRecordAdapter(i));
}
}
@Test
public void reservoirSizeOfOneStatistialTest() {
double[] histogram = new double[4];
int count = 100000;
for (int i = 0; i < count; i++) {
ReservoirSamplerWOR<WeightedRecord> rswor = new ReservoirSamplerWOR<WeightedRecord>(new MersenneTwisterRandom(), 1);
for (WeightedRecord p : population) {
rswor.add(p);
}
List<WeightedRecord> sample = rswor.getSamples();
int weight = (int) sample.get(0).getWeight();
histogram[weight] = histogram[weight] + 1;
}
for (int i = 0; i < histogram.length; i++) {
histogram[i]= histogram[i]/count;
}
double[] expected = {0, 1.0/6, 2.0/6, 3.0/6};
assertArrayEquals(expected, histogram, 0.01);
}
@Test
public void reservoirSizeOfOnePopulationSizeOfOne() {
ReservoirSamplerWOR<WeightedRecord> rswor = new ArraySamples(1);
WeightedRecord weightedRecord = new WeightedRecordAdapter(Double.NaN);
rswor.add(weightedRecord);
List<WeightedRecord> samples = rswor.getSamples();
assertEquals(1, samples.size());
assertSame(weightedRecord, samples.get(0));
}
@Test
public void reservoirSizeOfOnePopulationSizeTwoSelectsLowestWeight() {
final double[] probabilities = new double[]{0.5, 0.5};
ReservoirSamplerWOR<WeightedRecord> rswor = new ArraySamples(probabilities);
WeightedRecord smallerOne = new WeightedRecordAdapter(1.0);
WeightedRecord biggerOne = new WeightedRecordAdapter(2.0);
rswor.add(smallerOne);
rswor.add(biggerOne);
final List<WeightedRecord> samples = rswor.getSamples();
assertEquals(1, samples.size());
assertSame(biggerOne, samples.get(0));
}
private class ArraySamples extends ReservoirSamplerWOR<WeightedRecord> {
private final double[] values;
private int i;
public ArraySamples(double... values) {
super(null, 1);
this.values = values;
}
@Override
protected double nextRandomDouble() {
return values[i++];
}
}
} |
package org.jboss.aesh.console.script;
import org.jboss.aesh.console.BaseConsoleTest;
import org.jboss.aesh.console.Config;
import org.jboss.aesh.console.Console;
import org.jboss.aesh.console.ConsoleOperation;
import org.junit.Before;
import org.junit.Test;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertEquals;
public class ConsoleScriptTest extends BaseConsoleTest {
private List<String> lines;
@Before
public void readFile() throws IOException {
lines = new ArrayList<>();
BufferedReader br = new BufferedReader(new FileReader("src/test/resources/script1"));
String line = br.readLine();
while (line != null) {
if (line.trim().length() > 0 && !line.trim().startsWith("
lines.add(line);
line = br.readLine();
}
}
@Test
public void testScript() throws Throwable {
invokeTestConsole(new Setup() {
@Override
public void call(Console console, OutputStream out) throws Exception {
out.write(("run"+Config.getLineSeparator()).getBytes());
out.flush();
Thread.sleep(1000);
}
}, new ScriptCallback());
}
class ScriptCallback implements Verify {
private int count = 0;
@Override
public int call(Console console, ConsoleOperation output) throws InterruptedException {
if(output.getBuffer().equals("run")) {
count++;
//run script
for(String line : lines ) {
console.pushToInputStream(line);
if(!line.endsWith(Config.getLineSeparator()))
console.pushToInputStream(Config.getLineSeparator());
}
}
else {
if(count == 1 || count == 2) {
assertEquals("foo", output.getBuffer());
count++;
}
else if(count == 3) {
assertEquals("exit", output.getBuffer());
}
}
return 0;
}
}
} |
package org.jboss.msc.service;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import java.util.Collections;
import java.util.List;
import org.jboss.msc.service.util.LatchedFinishListener;
import org.junit.Test;
/**
* Test to verify ServiceController behavior.
*
* @author John E. Bailey
*/
public class ServiceControllerTestCase extends AbstractServiceTest {
@Test
public void testStartModes() throws Exception {
performTest(new ServiceTestInstance() {
@Override
public List<BatchBuilder> initializeBatches(ServiceContainer serviceContainer, LatchedFinishListener finishListener) throws Exception {
final BatchBuilder batch = serviceContainer.batchBuilder();
batch.addService(ServiceName.of("automatic"), Service.NULL).setInitialMode(ServiceController.Mode.AUTOMATIC).addListener(finishListener);
batch.addService(ServiceName.of("never"), Service.NULL).setInitialMode(ServiceController.Mode.NEVER);
batch.addService(ServiceName.of("immediate"), Service.NULL).setInitialMode(ServiceController.Mode.IMMEDIATE).addListener(finishListener);
batch.addService(ServiceName.of("on_demand"), Service.NULL).setInitialMode(ServiceController.Mode.ON_DEMAND);
return Collections.singletonList(batch);
}
@Override
public void performAssertions(ServiceContainer serviceContainer) throws Exception {
assertState(serviceContainer, ServiceName.of("automatic"), ServiceController.State.UP);
assertState(serviceContainer, ServiceName.of("never"), ServiceController.State.DOWN);
assertState(serviceContainer, ServiceName.of("immediate"), ServiceController.State.UP);
assertState(serviceContainer, ServiceName.of("on_demand"), ServiceController.State.DOWN);
}
});
}
@Test
public void testAutomatic() throws Exception {
performTest(new ServiceTestInstance() {
@Override
public List<BatchBuilder> initializeBatches(ServiceContainer serviceContainer, LatchedFinishListener finishListener) throws Exception {
final BatchBuilder batch = serviceContainer.batchBuilder();
batch.addService(ServiceName.of("automatic"), Service.NULL)
.setInitialMode(ServiceController.Mode.AUTOMATIC)
.addDependencies(ServiceName.of("never"));
batch.addService(ServiceName.of("never"), Service.NULL).setInitialMode(ServiceController.Mode.NEVER);
return Collections.singletonList(batch);
}
@Override
public void performAssertions(ServiceContainer serviceContainer) throws Exception {
Thread.sleep(50);
assertState(serviceContainer, ServiceName.of("automatic"), ServiceController.State.DOWN);
assertState(serviceContainer, ServiceName.of("never"), ServiceController.State.DOWN);
serviceContainer.getService(ServiceName.of("never")).setMode(ServiceController.Mode.IMMEDIATE);
Thread.sleep(50);
assertState(serviceContainer, ServiceName.of("automatic"), ServiceController.State.UP);
assertState(serviceContainer, ServiceName.of("never"), ServiceController.State.UP);
}
});
}
@Test
public void testOnDemand() throws Exception {
final ServiceContainer serviceContainer = ServiceContainer.Factory.create();
final BatchBuilder batch = serviceContainer.batchBuilder();
batch.addService(ServiceName.of("on_demand"), Service.NULL).setInitialMode(ServiceController.Mode.ON_DEMAND);
batch.install();
Thread.sleep(50);
assertState(serviceContainer, ServiceName.of("on_demand"), ServiceController.State.DOWN);
final BatchBuilder anotherBatch = serviceContainer.batchBuilder();
anotherBatch.addService(ServiceName.of("automatic"), Service.NULL)
.setInitialMode(ServiceController.Mode.AUTOMATIC)
.addDependencies(ServiceName.of("on_demand"));
anotherBatch.install();
Thread.sleep(50);
assertState(serviceContainer, ServiceName.of("on_demand"), ServiceController.State.DOWN);
final BatchBuilder yetAnotherBatch = serviceContainer.batchBuilder();
yetAnotherBatch.addService(ServiceName.of("immediate"), Service.NULL)
.setInitialMode(ServiceController.Mode.IMMEDIATE)
.addDependencies(ServiceName.of("on_demand"));
yetAnotherBatch.install();
Thread.sleep(50);
assertState(serviceContainer, ServiceName.of("on_demand"), ServiceController.State.UP);
assertState(serviceContainer, ServiceName.of("automatic"), ServiceController.State.UP);
assertState(serviceContainer, ServiceName.of("immediate"), ServiceController.State.UP);
serviceContainer.shutdown();
}
@Test
public void testAnotherOnDemand() throws Exception {
final ServiceContainer serviceContainer = ServiceContainer.Factory.create();
final BatchBuilder batch = serviceContainer.batchBuilder();
batch.addService(ServiceName.of("sbm"), Service.NULL).setInitialMode(ServiceController.Mode.ON_DEMAND);
batch.addService(ServiceName.of("nic1"), Service.NULL).setInitialMode(ServiceController.Mode.ON_DEMAND);
batch.addService(ServiceName.of("sb1"), Service.NULL)
.addDependencies(ServiceName.of("sbm"), ServiceName.of("nic1"))
.setInitialMode(ServiceController.Mode.ON_DEMAND);
batch.addService(ServiceName.of("server"), Service.NULL)
.setInitialMode(ServiceController.Mode.ON_DEMAND);
batch.addService(ServiceName.of("connector"), Service.NULL)
.addDependencies(ServiceName.of("sb1"), ServiceName.of("server"))
.setInitialMode(ServiceController.Mode.IMMEDIATE);
batch.install();
Thread.sleep(100);
assertState(serviceContainer, ServiceName.of("sbm"), ServiceController.State.UP);
assertState(serviceContainer, ServiceName.of("nic1"), ServiceController.State.UP);
assertState(serviceContainer, ServiceName.of("sb1"), ServiceController.State.UP);
assertState(serviceContainer, ServiceName.of("server"), ServiceController.State.UP);
assertState(serviceContainer, ServiceName.of("connector"), ServiceController.State.UP);
serviceContainer.shutdown();
}
@Test
public void testStop() throws Exception {
performTest(new ServiceTestInstance() {
@Override
public List<BatchBuilder> initializeBatches(ServiceContainer serviceContainer, LatchedFinishListener finishListener) throws Exception {
final BatchBuilder batch = serviceContainer.batchBuilder();
batch.addService(ServiceName.of("serviceOne"), Service.NULL)
.addDependencies(ServiceName.of("serviceTwo"));
batch.addService(ServiceName.of("serviceTwo"), Service.NULL);
batch.addListener(finishListener);
return Collections.singletonList(batch);
}
@Override
public void performAssertions(ServiceContainer serviceContainer) throws Exception {
assertState(serviceContainer, ServiceName.of("serviceOne"), ServiceController.State.UP);
assertState(serviceContainer, ServiceName.of("serviceTwo"), ServiceController.State.UP);
serviceContainer.getService(ServiceName.of("serviceTwo")).setMode(ServiceController.Mode.NEVER);
Thread.sleep(50);
assertState(serviceContainer, ServiceName.of("serviceOne"), ServiceController.State.DOWN);
assertState(serviceContainer, ServiceName.of("serviceTwo"), ServiceController.State.DOWN);
}
});
}
@Test
public void testRemove() throws Exception {
performTest(new ServiceTestInstance() {
@Override
public List<BatchBuilder> initializeBatches(ServiceContainer serviceContainer, LatchedFinishListener finishListener) throws Exception {
final BatchBuilder batch = serviceContainer.batchBuilder();
batch.addService(ServiceName.of("serviceOne"), Service.NULL)
.addDependencies(ServiceName.of("serviceTwo"));
batch.addService(ServiceName.of("serviceTwo"), Service.NULL);
batch.addListener(finishListener);
return Collections.singletonList(batch);
}
@Override
public void performAssertions(ServiceContainer serviceContainer) throws Exception {
assertState(serviceContainer, ServiceName.of("serviceOne"), ServiceController.State.UP);
assertState(serviceContainer, ServiceName.of("serviceTwo"), ServiceController.State.UP);
serviceContainer.getService(ServiceName.of("serviceTwo")).setMode(ServiceController.Mode.REMOVE);
Thread.sleep(50);
assertNull(serviceContainer.getService(ServiceName.of("serviceTwo")));
assertNull(serviceContainer.getService(ServiceName.of("serviceOne")));
}
});
}
@Test
public void testFailedStart() throws Exception {
final StartException startException = new StartException("Blahhhh");
performTest(new ServiceTestInstance() {
@Override
public List<BatchBuilder> initializeBatches(ServiceContainer serviceContainer, LatchedFinishListener finishListener) throws Exception {
final BatchBuilder batch = serviceContainer.batchBuilder();
batch.addService(ServiceName.of("serviceOne"), new Service<Void>() {
@Override
public void start(StartContext context) throws StartException {
throw startException;
}
@Override
public void stop(StopContext context) {
}
@Override
public Void getValue() throws IllegalStateException {
return null;
}
});
return Collections.singletonList(batch);
}
@Override
public void performAssertions(ServiceContainer serviceContainer) throws Exception {
Thread.sleep(50);
assertState(serviceContainer, ServiceName.of("serviceOne"), ServiceController.State.START_FAILED);
assertEquals(startException, serviceContainer.getService(ServiceName.of("serviceOne")).getStartException());
}
});
}
private static void assertState(final ServiceContainer serviceContainer, final ServiceName serviceName, final ServiceController.State state) {
assertEquals(state, serviceContainer.getService(serviceName).getState());
}
} |
package org.realityforge.tarrabah;
import javax.annotation.Nullable;
import javax.enterprise.context.spi.CreationalContext;
import javax.enterprise.inject.spi.Bean;
import javax.enterprise.inject.spi.InjectionTarget;
import org.apache.deltaspike.cdise.api.CdiContainer;
import org.apache.deltaspike.cdise.api.CdiContainerLoader;
import org.jboss.weld.manager.BeanManagerImpl;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
public abstract class AbstractContainerTest
{
@Nullable
private CdiContainer _cdiContainer;
@Nullable
private CreationalContext _context;
@SuppressWarnings( "unchecked" )
@BeforeMethod
public void setupContainer()
throws Exception
{
_cdiContainer = CdiContainerLoader.getCdiContainer();
_cdiContainer.boot();
_cdiContainer.getContextControl().startContexts();
_context = _cdiContainer.getBeanManager().createCreationalContext( null );
final InjectionTarget injectionTarget =
_cdiContainer.getBeanManager()
.createInjectionTarget( _cdiContainer.getBeanManager().createAnnotatedType( getClass() ) );
injectionTarget.inject( this, _context );
injectionTarget.postConstruct( this );
}
@AfterMethod
public void shutdownContainer()
throws Exception
{
if ( null != _context )
{
_context.release();
_context = null;
}
if ( null != _cdiContainer )
{
_cdiContainer.shutdown();
_cdiContainer = null;
}
}
} |
package org.smallvaluesofcool.misc.functional;
import org.junit.Assert;
import org.junit.Test;
import java.util.Collection;
import java.util.List;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.smallvaluesofcool.misc.Literals.listWith;
public class EagerTest {
@Test
public void shouldSumSuppliedInputUsingLongAccumulator() throws Exception {
// Given
Collection<Long> input = listWith(2L, 3L, 4L);
// When
Long actual = Eager.reduce(input, Eager.longAdditionAccumulator());
// Then
Assert.assertThat(actual, equalTo(9L));
}
@Test
public void shouldReduceOtherTypesUsingCustomFunction() throws Exception {
// Given
List<List<Integer>> inputLists = listWith(
listWith(1, 2, 3).build(),
listWith(4, 5, 6).build(),
listWith(7, 8, 9).build());
// When
List<Integer> actual = Eager.reduce(inputLists, new ReduceFunction<List<Integer>>() {
// Example flattening accumulator.
public List<Integer> accumulate(List<Integer> accumulator, List<Integer> element) {
accumulator.addAll(element);
return accumulator;
}
});
// Then
Assert.assertThat(actual, hasItems(1, 2, 3, 4, 5, 6, 7, 8, 9));
}
@Test
public void shouldReturnTrueIfAnyElementsSatisfyThePredicateFunction() {
// Given
List<Integer> inputNumbers = listWith(5, 10, 15, 20);
// When
Boolean result = Eager.any(inputNumbers, new Predicate<Integer>() {
@Override
public boolean matches(Integer item) {
return item > 15;
}
});
// Then
assertThat(result, is(true));
}
@Test
public void shouldReturnFalseIfNoElementsSatisfyThePredicateFunction() {
// Given
List<Integer> items = listWith(5, 10, 15, 20);
// When
Boolean result = Eager.any(items, new Predicate<Integer>() {
@Override
public boolean matches(Integer item) {
return item > 25;
}
});
// Then
assertThat(result, is(false));
}
@Test
public void shouldReturnTrueIfAllElementsSatisfyThePredicateFunction() {
// Given
List<String> items = listWith("dog", "cat", "fish", "budgie");
// When
Boolean result = Eager.all(items, new Predicate<String>() {
@Override
public boolean matches(String item) {
return item.length() > 2;
}
});
// Then
assertThat(result, is(true));
}
@Test
public void shouldReturnFalseIfAnyOfTheElementsDoNotSatisyThePredicateFunction() {
// Given
List<String> items = listWith("dog", "cat", "fish", "budgie");
// When
Boolean result = Eager.all(items, new Predicate<String>() {
@Override
public boolean matches(String item) {
return item.length() > 3;
}
});
// Then
assertThat(result, is(false));
}
@Test
public void shouldReturnTrueIfNoneOfTheElementsMatchesThePredicateFunction() {
// Given
List<Integer> items = listWith(1, 3, 5, 7);
// When
Boolean result = Eager.none(items, new Predicate<Integer>() {
@Override
public boolean matches(Integer item) {
return isEven(item);
}
private boolean isEven(Integer item) {
return item % 2 == 0;
}
});
// Then
assertThat(result, is(true));
}
@Test
public void shouldReturnFalseIfAnyOfTheElementsMatchesTePredicateFunction() {
// Given
List<Integer> items = listWith(1, 3, 6, 7);
// When
Boolean result = Eager.none(items, new Predicate<Integer>() {
@Override
public boolean matches(Integer item) {
return isEven(item);
}
private boolean isEven(Integer item) {
return item % 2 == 0;
}
});
// Then
assertThat(result, is(false));
}
@Test
public void shouldReturnMinValue() throws Exception {
// Given
List<String> list = listWith("a", "b", "c");
// When
String actual = Eager.min(list);
// Then
assertThat(actual, is("a"));
}
@Test
public void shouldReturnMaxValue() throws Exception {
// Given
List<Integer> list = listWith(2, 6, 3);
// When
Integer actual = Eager.max(list);
// Then
assertThat(actual, is(6));
}
@Test
public void shouldExecuteSuppliedFunctionOnEachElement() {
// Given
Iterable<Target> targets = listWith(mock(Target.class), mock(Target.class), mock(Target.class));
// When
Eager.each(targets, new DoFunction<Target>() {
@Override
public void actOn(Target input) {
input.doSomething();
}
});
// Then
for(Target target : targets) {
verify(target).doSomething();
}
}
private interface Target {
void doSomething();
}
} |
package redis.clients.jedis.tests;
import java.util.HashSet;
import java.util.Set;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.junit.Before;
import org.junit.Test;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisSentinelPool;
import redis.clients.jedis.Transaction;
import redis.clients.jedis.exceptions.JedisConnectionException;
import redis.clients.jedis.tests.utils.JedisSentinelTestUtil;
public class JedisSentinelPoolTest extends JedisTestBase {
private static final String MASTER_NAME = "mymaster";
protected static HostAndPort master = HostAndPortUtil.getRedisServers()
.get(2);
protected static HostAndPort slave1 = HostAndPortUtil.getRedisServers()
.get(3);
protected static HostAndPort sentinel1 = HostAndPortUtil
.getSentinelServers().get(1);
protected static HostAndPort sentinel2 = HostAndPortUtil
.getSentinelServers().get(3);
protected static Jedis sentinelJedis1;
protected static Jedis sentinelJedis2;
protected Set<String> sentinels = new HashSet<String>();
@Before
public void setUp() throws Exception {
sentinels.add(sentinel1.toString());
sentinels.add(sentinel2.toString());
sentinelJedis1 = new Jedis(sentinel1.getHost(), sentinel1.getPort());
sentinelJedis2 = new Jedis(sentinel2.getHost(), sentinel2.getPort());
}
@Test
public void ensureSafeTwiceFailover() throws InterruptedException {
JedisSentinelPool pool = new JedisSentinelPool(MASTER_NAME, sentinels,
new GenericObjectPoolConfig(), 1000, "foobared", 2);
forceFailover(pool);
// after failover sentinel needs a bit of time to stabilize before a new failover
Thread.sleep(100);
forceFailover(pool);
// you can test failover as much as possible
}
@Test
public void returnResourceShouldResetState() {
GenericObjectPoolConfig config = new GenericObjectPoolConfig();
config.setMaxTotal(1);
config.setBlockWhenExhausted(false);
JedisSentinelPool pool = new JedisSentinelPool(MASTER_NAME, sentinels,
config, 1000, "foobared", 2);
Jedis jedis = pool.getResource();
Jedis jedis2 = null;
try {
jedis.set("hello", "jedis");
Transaction t = jedis.multi();
t.set("hello", "world");
pool.returnResource(jedis);
jedis2 = pool.getResource();
assertTrue(jedis == jedis2);
assertEquals("jedis", jedis2.get("hello"));
} catch (JedisConnectionException e) {
if (jedis2 != null) {
pool.returnBrokenResource(jedis2);
jedis2 = null;
}
} finally {
if (jedis2 != null)
pool.returnResource(jedis2);
pool.destroy();
}
}
@Test
public void checkResourceIsCloseable() {
GenericObjectPoolConfig config = new GenericObjectPoolConfig();
config.setMaxTotal(1);
config.setBlockWhenExhausted(false);
JedisSentinelPool pool = new JedisSentinelPool(MASTER_NAME, sentinels,
config, 1000, "foobared", 2);
Jedis jedis = pool.getResource();
try {
jedis.set("hello", "jedis");
} finally {
jedis.close();
}
Jedis jedis2 = pool.getResource();
try {
assertEquals(jedis, jedis2);
} finally {
jedis2.close();
}
}
@Test
public void returnResourceWithNullResource() {
GenericObjectPoolConfig config = new GenericObjectPoolConfig();
config.setMaxTotal(1);
config.setBlockWhenExhausted(false);
JedisSentinelPool pool = new JedisSentinelPool(MASTER_NAME, sentinels,
config, 1000, "foobared", 2);
Jedis nullJedis = null;
pool.returnResource(nullJedis);
pool.destroy();
}
@Test
public void returnBrokenResourceWithNullResource() {
GenericObjectPoolConfig config = new GenericObjectPoolConfig();
config.setMaxTotal(1);
config.setBlockWhenExhausted(false);
JedisSentinelPool pool = new JedisSentinelPool(MASTER_NAME, sentinels,
config, 1000, "foobared", 2);
Jedis nullJedis = null;
pool.returnBrokenResource(nullJedis);
pool.destroy();
}
private void forceFailover(JedisSentinelPool pool)
throws InterruptedException {
HostAndPort oldMaster = pool.getCurrentHostMaster();
// jedis connection should be master
Jedis beforeFailoverJedis = pool.getResource();
assertEquals("PONG", beforeFailoverJedis.ping());
waitForFailover(pool, oldMaster);
Jedis afterFailoverJedis = pool.getResource();
assertEquals("PONG", afterFailoverJedis.ping());
assertEquals("foobared", afterFailoverJedis.configGet("requirepass").get(1));
assertEquals(2, afterFailoverJedis.getDB().intValue());
// returning both connections to the pool should not throw
beforeFailoverJedis.close();
afterFailoverJedis.close();
}
private void waitForFailover(JedisSentinelPool pool, HostAndPort oldMaster)
throws InterruptedException {
HostAndPort newMaster = JedisSentinelTestUtil
.waitForNewPromotedMaster(MASTER_NAME, sentinelJedis1, sentinelJedis2);
waitForJedisSentinelPoolRecognizeNewMaster(pool, newMaster);
}
private void waitForJedisSentinelPoolRecognizeNewMaster(
JedisSentinelPool pool, HostAndPort newMaster)
throws InterruptedException {
while (true) {
HostAndPort currentHostMaster = pool.getCurrentHostMaster();
if (newMaster.equals(currentHostMaster))
break;
System.out
.println("JedisSentinelPool's master is not yet changed, sleep...");
Thread.sleep(100);
}
}
} |
package webrefeicoes.controller;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import webrefeicoes.model.Funcionario;
public class FuncionarioController {
public static void main(String[] args) {
EntityManagerFactory factory = Persistence.createEntityManagerFactory("WebRefeicoes");
EntityManager em = factory.createEntityManager();
Funcionario func = new Funcionario();
func.setNome("Thiago Armele de Campos");
em.getTransaction().begin();
em.persist(func);
em.getTransaction().commit();
}
} |
package xyz.cloorc.example.springmvc.utils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManagerFactory;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.util.Iterator;
import java.util.Map;
public class HttpHelper {
private static SSLSocketFactory factory = null;
static {
KeyStore ksCACert = null;
try {
ksCACert = KeyStore.getInstance(KeyStore.getDefaultType());
//Initialise a TrustManagerFactory with the CA keyStore, default: lib/security/jssecacerts
ksCACert.load(new ClassPathResource("cacerts").getInputStream(), "123456".toCharArray());
TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
//Create new SSLContext using our new TrustManagerFactory
tmf.init(ksCACert);
SSLContext context = SSLContext.getInstance("TLS");
//Get a SSLSocketFactory from our SSLContext
context.init(null, tmf.getTrustManagers(), null);
//Set our custom SSLSocketFactory to be used by our HttpsURLConnection instance
factory = context.getSocketFactory();
} catch (KeyStoreException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (CertificateException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
}
public static String url(String url, Map<String,Object> params) {
if (null == url)
return null;
StringBuilder sb = new StringBuilder(url);
if (! url.endsWith("?"))
sb.append("?");
if (null != params) {
Iterator<Map.Entry<String, Object>> it = params.entrySet().iterator();
Map.Entry<String,Object> item;
while (it.hasNext()) {
item = it.next();
sb.append(item.getKey()).append("=").append(item.getValue()).append("&");
}
sb.deleteCharAt(sb.length() - 1);
}
return sb.toString();
}
public static void send (URLConnection connection, byte[] data) {
if (null == connection) {
return ;
}
OutputStream out = null;
try {
out = connection.getOutputStream();
out.write(data);
out.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (null != out)
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void send (URLConnection connection, File file) {
if (null == connection) {
return;
}
OutputStream ostream = null;
FileInputStream istream = null;
try {
ostream = connection.getOutputStream();
istream = new FileInputStream(file);
byte[] buf = new byte[1024];
int len;
while ((len = istream.read(buf)) != -1) {
ostream.write(buf, 0, len);
}
ostream.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (null != ostream)
ostream.close();
if (null != istream)
istream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static String receive (URLConnection connection) {
BufferedReader br = null;
StringBuilder objStrBuilder = new StringBuilder();
String objStr;
if (null == connection) {
return null;
}
try {
br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
while ((objStr = br.readLine()) != null) {
objStrBuilder.append(objStr);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (null != br)
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return objStrBuilder.toString();
}
public static URLConnection connect (String target, RequestMethod method, Map<String,String> headers) {
if (null == target) {
return null;
}
URL url = null;
try {
url = new URL(target);
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
}
URLConnection connection = null;
try {
connection = url.openConnection();
} catch (IOException e) {
e.printStackTrace();
return null;
}
if (connection instanceof HttpsURLConnection)
((HttpsURLConnection) connection).setSSLSocketFactory(factory);
connection.setDoInput(true);
if (method.equals(RequestMethod.POST)) {
connection.setDoOutput(true);
}
connection.setRequestProperty("Pragma", "no-cache");
connection.setRequestProperty("Cache-Control", "no-cache");
if (null != headers) {
Iterator<Map.Entry<String, String>> it = headers.entrySet().iterator();
Map.Entry<String,String> item;
while (it.hasNext()) {
item = it.next();
connection.setRequestProperty(item.getKey(), item.getValue());
}
}
return connection;
}
public static String post (String url, Map<String,String> headers, byte[] data) {
URLConnection connection = connect(url, RequestMethod.POST, headers);
if (null != connection) {
send(connection, data);
return receive(connection);
}
return null;
}
public static String post (String url, Map<String,String> headers, String fmt, Object... parameters) {
URLConnection connection = connect(url, RequestMethod.POST, headers);
if (null != connection) {
try {
send(connection, String.format(fmt, parameters).getBytes("UTF-8"));
return receive(connection);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
return null;
}
public static String get (String url, Map<String,String> headers, Map<String,Object> params) {
String target = url(url, params);
URLConnection connection = connect(target, RequestMethod.GET, headers);
if (null != connection) {
return receive(connection);
}
return null;
}
public static InputStream getInputStream (String url, Map<String,String> headers, Map<String,Object> params) throws IOException {
String target = url(url, params);
URLConnection connection = connect(target, RequestMethod.GET, headers);
if (null != connection) {
return connection.getInputStream();
}
return null;
}
} |
package app.akexorcist.bluetoothspp;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class Main extends Activity implements OnClickListener {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btnSimple = (Button) findViewById(R.id.btnSimple);
btnSimple.setOnClickListener(this);
Button btnListener = (Button) findViewById(R.id.btnListener);
btnListener.setOnClickListener(this);
Button btnAutoConnect = (Button) findViewById(R.id.btnAutoConnect);
btnAutoConnect.setOnClickListener(this);
Button btnDeviceList = (Button) findViewById(R.id.btnDeviceList);
btnDeviceList.setOnClickListener(this);
Button btnTerminal = (Button) findViewById(R.id.btnTerminal);
btnTerminal.setOnClickListener(this);
Button btnTurnOn = (Button) findViewById(R.id.btnTurnOn);
btnTurnOn.setOnClickListener(this);
Button btnTurnOff = (Button) findViewById(R.id.btnTurnOff);
btnTurnOff.setOnClickListener(this);
}
public void onClick(View v) {
int id = v.getId();
Intent intent = null;
switch (id) {
case R.id.btnSimple:
intent = new Intent(getApplicationContext(), SimpleActivity.class);
startActivity(intent);
break;
case R.id.btnListener:
intent = new Intent(getApplicationContext(), ListenerActivity.class);
startActivity(intent);
break;
case R.id.btnAutoConnect:
intent = new Intent(getApplicationContext(), AutoConnectActivity.class);
startActivity(intent);
break;
case R.id.btnDeviceList:
intent = new Intent(getApplicationContext(), DeviceListActivity.class);
startActivity(intent);
break;
case R.id.btnTerminal:
intent = new Intent(getApplicationContext(), TerminalActivity.class);
startActivity(intent);
break;
case R.id.btnTurnOn:
this.turnBluetoothOn();
break;
case R.id.btnTurnOff:
this.turnBluetoothOff();
break;
}
}
public void turnBluetoothOn(){
}
public void turnBluetoothOff(){
}
} |
package com.Ryan.Calculator;
import android.annotation.TargetApi;
import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import java.math.BigInteger;
public class MainActivity extends Activity
{
public Complex currentValue=Complex.ZERO;
/** Called when the activity is first created. */
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.HONEYCOMB)
{
getActionBar().hide();
if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.ICE_CREAM_SANDWICH)
findViewById(R.id.mainLayout).setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE);
}
setZero();
}
public Complex parseComplex(String num)
{
if (num==null || num.indexOf("Error", 0)==0 || num.indexOf("ERROR", 0)==0)
return Complex.ZERO;
if ("Not prime".equals(num) || "Not prime or composite".equals(num))
return Complex.ZERO;
if ("Prime".equals(num))
return Complex.ONE;
if (num.charAt(num.length()-1)=='\u03C0')
{
if (num.length()==1)
return Complex.PI;
else if (num.length()==2 && num.charAt(0)=='-') // If the string is two long and the first character is a negation
return Complex.negate(Complex.PI); // Return negative pi
return Complex.multiply(parseComplex(num.substring(0, num.length()-1)), Complex.PI);
}
if (num.charAt(num.length()-1)=='e')
{
if (num.length()==1)
return Complex.E;
else if (num.length()==2 && num.charAt(0)=='-') // If the string is two long and the first character is a negation
return Complex.negate(Complex.E); // Return negative e
return Complex.multiply(parseComplex(num.substring(0, num.length()-1)), Complex.E);
}
try {
return Complex.parseNaiveString(num);
}
catch (NumberFormatException ex) {
try {
return Complex.parseString(num);
}
catch (NumberFormatException e) {
setText("ERROR: Invalid number");
View v=findViewById(R.id.mainCalculateButton);
v.setOnClickListener(null); // Cancel existing computation
v.setVisibility(View.GONE); // Remove the button
return Complex.ZERO;
}
}
}
public String inIntTermsOfPi(double num)
{
if (num==0)
return "0";
double tmp=num/Math.PI;
int n=(int)tmp;
if (n==tmp)
{
if (n==-1) // If it is a negative, but otherwise 1
return "-\u03C0"; // Return negative pi
return (n==1 ? "" : Integer.toString(n))+"\u03C0";
}
else
return Double.toString(num);
}
public String inIntTermsOfPi(Complex num)
{
if (num.equals(Complex.ZERO)) // Special case: Prevents "0+0i"
return "0";
if (num.isReal())
return inIntTermsOfPi(num.real);
if (num.isImaginary())
return inIntTermsOfPi(num.imaginary)+'i';
String out=inIntTermsOfPi(num.real);
if (num.imaginary>0)
out+="+";
out+=inIntTermsOfPi(num.imaginary)+'i';
return out;
}
public String inIntTermsOfE(double num)
{
if (num==0)
return "0";
double tmp=num/Math.E;
int n=(int)tmp;
if (n==tmp)
{
if (n==-1) // If it is a negative, but otherwise 1
return "-e"; // Return negative e
return (n==1 ? "" : Integer.toString((int)tmp))+"e";
}
else
return Double.toString(num);
}
public String inIntTermsOfE(Complex num)
{
if (num.equals(Complex.ZERO)) // Special case: Prevents "0+0i"
return "0";
if (num.isReal())
return inIntTermsOfE(num.real);
if (num.isImaginary())
return inIntTermsOfE(num.imaginary)+'i';
String out=inIntTermsOfE(num.real);
if (num.imaginary>0)
out+="+";
out+=inIntTermsOfE(num.imaginary)+'i';
return out;
}
public String inIntTermsOfAny(double num)
{
if (Double.isNaN(num)) // "Last-resort" check
return "ERROR: Nonreal or non-numeric result."; // Trap NaN and return a generic error for it.
// Because of that check, we can guarantee that NaN's will not be floating around for more than one expression.
String out=inIntTermsOfPi(num);
if (!out.equals(Double.toString(num)))
return out;
else
return inIntTermsOfE(num);
}
public String inIntTermsOfAny(Complex num)
{
if (num.equals(Complex.ZERO)) // Special case: Prevents "0+0i"
return "0";
if (num.isReal())
return inIntTermsOfAny(num.real);
if (num.isImaginary())
return inIntTermsOfAny(num.imaginary)+'i';
String out=inIntTermsOfAny(num.real);
if (num.imaginary>0)
out+="+";
out+=inIntTermsOfAny(num.imaginary)+'i';
return out;
}
public void zero(View v)
{
setZero();
}
public void setZero(EditText ev)
{
setText("0", ev);
}
public void setZero()
{
setZero((EditText) findViewById(R.id.mainTextField));
}
public void setText(String n, EditText ev)
{
ev.setText(n);
ev.setSelection(0, n.length()); // Ensure the cursor is at the end
}
public void setText(String n)
{
setText(n, (EditText) findViewById(R.id.mainTextField));
}
public void terms(View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
setText(inIntTermsOfAny(parseComplex(ev.getText().toString())), ev);
}
public void decimal(View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
setText(Complex.toString(parseComplex(ev.getText().toString())), ev);
}
public Complex getValue(final EditText ev) // Parses the content of ev into a double.
{
return parseComplex(ev.getText().toString().trim());
}
public void doCalculate(final EditText ev, OnClickListener ocl) // Common code for buttons that use the mainCalculateButton.
{
doCalculate(ev, ocl, Complex.ZERO);
}
public void doCalculate(final EditText ev, OnClickListener ocl, Complex n) // Common code for buttons that use the mainCalculateButton, setting the default value to n rather than zero.
{
setText(inIntTermsOfAny(n), ev);
final Button b=(Button)findViewById(R.id.mainCalculateButton);
b.setVisibility(View.VISIBLE);
b.setOnClickListener(ocl);
}
public void add(View v)
{
final EditText ev=(EditText)findViewById(R.id.mainTextField);
currentValue=getValue(ev);
doCalculate(ev, new OnClickListener() {
@Override
public void onClick(View v) {
v.setOnClickListener(null);
String num = ev.getText().toString().trim();
if ("".equals(num))
return;
setText(inIntTermsOfAny(currentValue.addTo(parseComplex(num))), ev);
v.setVisibility(View.GONE);
}
});
}
public void subtract(View v)
{
final EditText ev=(EditText)findViewById(R.id.mainTextField);
currentValue=getValue(ev);
doCalculate(ev, new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
String num=ev.getText().toString().trim();
if ("".equals(num))
return;
setText(inIntTermsOfAny(currentValue.subtractTo(parseComplex(num))), ev);
v.setVisibility(View.GONE);
}
});
}
public void subtract2(View v)
{
final EditText ev=(EditText)findViewById(R.id.mainTextField);
currentValue=getValue(ev);
doCalculate(ev, new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
String num=ev.getText().toString().trim();
if ("".equals(num))
return;
setText(inIntTermsOfAny(parseComplex(num).subtractTo(currentValue)), ev);
v.setVisibility(View.GONE);
}
});
}
public void multiply(View v)
{
final EditText ev=(EditText)findViewById(R.id.mainTextField);
currentValue=getValue(ev);
doCalculate(ev, new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
String num=ev.getText().toString().trim();
if ("".equals(num))
return;
setText(inIntTermsOfAny(currentValue.multiplyTo(parseComplex(num))), ev);
v.setVisibility(View.GONE);
}
});
}
public void divide(View v)
{
final EditText ev=(EditText)findViewById(R.id.mainTextField);
currentValue=getValue(ev);
doCalculate(ev, new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
String num=ev.getText().toString().trim();
if ("".equals(num))
return;
Complex n=parseComplex(num);
if (n.equals(Complex.ZERO))
setText("Error: Divide by zero.");
else
setText(inIntTermsOfAny(currentValue.divideTo(n)), ev);
v.setVisibility(View.GONE);
}
}, 1);
}
public void divide2(View v)
{
final EditText ev=(EditText)findViewById(R.id.mainTextField);
currentValue=getValue(ev);
doCalculate(ev, new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
String num=ev.getText().toString().trim();
if ("".equals(num))
return;
Complex n=parseComplex(num);
if (n.equals(Complex.ZERO))
setText("Error: Divide by zero.");
else
setText(inIntTermsOfAny(n.divideTo(currentValue)), ev);
v.setVisibility(View.GONE);
}
}, 1);
}
public void remainder(View v)
{
final EditText ev=(EditText)findViewById(R.id.mainTextField);
currentValue=getValue(ev);
if (!Complex.round(currentValue).equals(currentValue))
{
setText("Error: Parameter is not an integer: "+ev.getText(), ev);
return;
}
doCalculate(ev, new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
String num=ev.getText().toString().trim();
if ("".equals(num))
return;
v.setVisibility(View.GONE);
Complex tmp=parseComplex(num);
if (!Complex.round(tmp).equals(tmp))
setText("Error: Parameter is not an integer: "+num, ev);
else if (Complex.round(tmp).equals(Complex.ZERO))
setText("Error: Divide by zero.");
else
setText(inIntTermsOfAny(Complex.round(currentValue).modulo(Complex.round(tmp))), ev);
}
}, 1);
}
public void remainder2(View v)
{
final EditText ev=(EditText)findViewById(R.id.mainTextField);
currentValue=getValue(ev);
if (!Complex.round(currentValue).equals(currentValue))
{
setText("Error: Parameter is not an integer: "+ev.getText(), ev);
return;
}
doCalculate(ev, new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
String num=ev.getText().toString().trim();
if ("".equals(num))
return;
v.setVisibility(View.GONE);
Complex tmp=parseComplex(num);
if (!Complex.round(tmp).equals(tmp))
setText("Error: Parameter is not an integer: "+num, ev);
else if (Complex.round(currentValue).equals(Complex.ZERO))
setText("Error: Divide by zero.");
else
setText(inIntTermsOfAny(Complex.round(tmp).modulo(Complex.round(currentValue))), ev);
}
}, 1);
}
public void e(View v)
{
setText("e");
}
public void pi(View v)
{
setText("\u03C0");
}
public void i(View v) { setText("i"); }
public void negate(View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
setText(inIntTermsOfAny(Complex.negate(Complex.ONE).multiplyTo(parseComplex(ev.getText().toString()))), ev);
}
public void sin(View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
setText(inIntTermsOfPi(Complex.sin(parseComplex(ev.getText().toString()))), ev);
}
public void cos(View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
setText(inIntTermsOfPi(Complex.cos(parseComplex(ev.getText().toString()))), ev);
}
public void tan(View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
setText(inIntTermsOfPi(Complex.tan(parseComplex(ev.getText().toString()))), ev);
}
public void arcsin(View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
setText(inIntTermsOfPi(Complex.asin(parseComplex(ev.getText().toString()))), ev);
}
public void arccos(View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
setText(inIntTermsOfPi(Complex.acos(parseComplex(ev.getText().toString()))), ev);
}
public void arctan(View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
setText(inIntTermsOfPi(Complex.atan(parseComplex(ev.getText().toString()))), ev);
}
public void exp(View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
setText(inIntTermsOfE(Complex.exp(parseComplex(ev.getText().toString()))), ev);
}
public void degrees(View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
setText((Complex.toDegrees(parseComplex(ev.getText().toString()))).toString(), ev);
}
public void radians(View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
setText(inIntTermsOfPi(Complex.toRadians(parseComplex(ev.getText().toString()))), ev);
}
public void radians2(View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
Complex tmp=parseComplex(ev.getText().toString());
tmp=Complex.divide(tmp, new Complex(180));
setText(Complex.toString(tmp)+'\u03C0', ev);
}
public void ln(View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
setText(inIntTermsOfE(Complex.ln(parseComplex(ev.getText().toString()))), ev);
}
public void log(View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
setText(inIntTermsOfAny(Complex.log10(parseComplex(ev.getText().toString()))), ev);
}
public void logb(View v)
{
final EditText ev=(EditText)findViewById(R.id.mainTextField);
currentValue=parseComplex(ev.getText().toString());
doCalculate(ev, new OnClickListener() {
@Override
public void onClick(View v) {
v.setOnClickListener(null);
String num = ev.getText().toString();
if ("".equals(num))
return;
setText(inIntTermsOfAny(Complex.log(currentValue, parseComplex(num))), ev);
v.setVisibility(View.GONE);
}
}, 10);
}
public void logb2(View v)
{
final EditText ev=(EditText)findViewById(R.id.mainTextField);
currentValue=parseComplex(ev.getText().toString());
doCalculate(ev,new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
String num=ev.getText().toString();
if ("".equals(num))
return;
setText(inIntTermsOfAny(Complex.log(parseComplex(num), currentValue)), ev);
v.setVisibility(View.GONE);
}
}, 10);
}
public void round(View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
setText(Complex.toString(Complex.round(parseComplex(ev.getText().toString()))));
}
public void sqrt(View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
Complex n=parseComplex(ev.getText().toString());
setText(inIntTermsOfAny(Complex.sqrt(n)), ev);
}
public void cbrt(View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
setText(inIntTermsOfAny(Complex.cbrt(parseComplex(ev.getText().toString()))), ev);
}
public void ceil(View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
setText(Complex.toString(Complex.ceil(parseComplex(ev.getText().toString()))), ev);
}
public void floor(View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
setText(Complex.toString(Complex.floor(parseComplex(ev.getText().toString()))), ev);
}
public void pow(View v)
{
final EditText ev=(EditText)findViewById(R.id.mainTextField);
currentValue=parseComplex(ev.getText().toString());
doCalculate(ev, new OnClickListener() {
@Override
public void onClick(View v) {
v.setOnClickListener(null);
String num = ev.getText().toString();
if (!"".equals(num))
setText(inIntTermsOfAny(Complex.pow(currentValue, parseComplex(num))), ev);
v.setVisibility(View.GONE);
}
}, currentValue);
}
public void pow2(View v)
{
final EditText ev=(EditText)findViewById(R.id.mainTextField);
currentValue=parseDouble(ev.getText().toString());
doCalculate(ev, new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
String num=ev.getText().toString();
if (!"".equals(num))
setText(inIntTermsOfAny(Math.pow(parseDouble(num), currentValue)), ev);
v.setVisibility(View.GONE);
}
}, currentValue);
}
public void abs (View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
setText(inIntTermsOfAny(Math.abs(parseDouble(ev.getText().toString()))), ev);
}
public void sinh(View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
setText(inIntTermsOfAny(Math.sinh(parseDouble(ev.getText().toString()))), ev);
}
public void expm(View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
setText(inIntTermsOfAny(Math.expm1(parseDouble(ev.getText().toString()))), ev);
}
public void cosh(View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
setText(inIntTermsOfAny(Math.cosh(parseDouble(ev.getText().toString()))), ev);
}
public void tanh(View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
setText(inIntTermsOfAny(Math.tanh(parseDouble(ev.getText().toString()))), ev);
}
public void lnp(View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
setText(inIntTermsOfAny(Math.log1p(parseDouble(ev.getText().toString()))), ev);
}
public void square(View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
double num=parseDouble(ev.getText().toString());
setText(inIntTermsOfAny(num*num), ev);
}
public void cube(View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
double num=parseDouble(ev.getText().toString());
setText(inIntTermsOfAny(num*num*num), ev);
}
public void isPrime(View v) {
EditText ev=(EditText)findViewById(R.id.mainTextField);
double num=parseDouble(ev.getText().toString());
int n=(int)Math.floor(num);
if (n!=num || n<1 || isDivisible(n,2)) {
setText("Not prime");
return;
}
if (n==1) {
setText("Not prime or composite");
return;
}
for (int i=3; i<=Math.sqrt(n); i+=2) {
if (isDivisible(n, i)) {
setText("Not prime");
return;
}
}
setText("Prime");
}
public boolean isDivisible(int num, int den) {
return num%den==0;
}
public double fastPow(double val, int power)
{
if (val==2)
return fastPow(power).doubleValue();
switch (power)
{
case 0:
return 1;
case 1:
return val;
case 2:
return val*val;
default:
if (power<0)
return 1/fastPow(val, -1*power);
if (power%2==0)
return fastPow(fastPow(val, 2), power>>1);
return val*fastPow(val, power-1);
}
}
public BigInteger fastPow(int pow) // 2 as base
{
return BigInteger.ZERO.flipBit(pow);
}
public void raise2(View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
double num=parseDouble(ev.getText().toString());
if (Math.round(num)==num) // Integer power. Use the fastpow() and a BigInteger.
setText(fastPow((int)Math.round(num)).toString(), ev);
else
setText(Double.toString(Math.pow(2, num)), ev);
}
} |
package com.google.sprint1;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import com.metaio.sdk.jni.Vector3d;
import android.os.Handler;
import android.provider.ContactsContract.Contacts.Data;
import android.util.Log;
public class MobileConnection {
private ServerSocket mServerSocket;
private List<InetAddress> mIPs;
private List<Peer> mPeers;
private InetAddress mIP;
private static final String TAG = "MobileConnection";
public static final int SERVER_PORT = 8196;
BlockingQueue<DataPackage> queue;
private int QUEUE_CAPACITY = 32;
private boolean handshakeActive = false;
public MobileConnection(Handler handler) {
mIPs = new ArrayList<InetAddress>();
mPeers = new ArrayList<Peer>();
queue = new ArrayBlockingQueue<DataPackage>(QUEUE_CAPACITY);
//Start a ServerThread
new Thread(new ServerThread()).start();
}
public synchronized void connectToPeer(InetAddress address, int port) {
if (!(mIPs.contains(address)) && mServerSocket.getInetAddress() != address)
{
mIPs.add(address);
Thread con = new Thread(new ConnectionThread(address));
con.start();
}else{
Log.d(TAG,"Already connected to: " + address);
}
}
public void tearDown() {
try {
mServerSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public synchronized void sendData(byte[] data)
{
if(!mPeers.isEmpty())
{
for(int i = 0; i < mPeers.size(); i++)
sendPackage(data, mPeers.get(i));
}else{
Log.d(TAG, "Cannot send data. Not connected to any peers.");
}
}
/** Send data to the sockets output stream */
private synchronized void sendPackage(byte[] data, Peer peer) {
try {
OutputStream outStream = peer.getOutputStream();
outStream.write(data);
outStream.flush();
} catch (UnknownHostException e) {
Log.d(TAG, "Unknown Host", e);
} catch (IOException e) {
Log.d(TAG, "I/O Exception", e);
} catch (Exception e) {
Log.d(TAG, "Error3", e);
}
}
/** Handshake is called when the serversocket accepts (finds) another peer
* it will add the Peer to the peerlist and start to listen to it.
* It also sends a list to all other peers it is connected to so the new peer can connect to them aswell
* @param socket
*/
private void handshake(Socket socket)
{
try {
//Check if already connected
if (!mIPs.contains(socket.getInetAddress()))
{
Peer peer = new Peer(socket);
Log.d(TAG, peer.getAdress() +" connected.");
Log.d(TAG, "SIZE OF MIPS: " + mIPs.size());
//Send back list with other peers
sendIPList(peer);
new Thread(new ListenerThread(peer)).start();
//Add this peer to the list
mPeers.add(peer);
mIPs.add(peer.getAdress());
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Sends back a list of peers to connect to
* @param peer
* @throws IOException
*/
private synchronized void sendIPList(Peer peer) throws IOException{
ByteBuffer buffer;
buffer = ByteBuffer.allocate(DataPackage.BUFFER_HEAD_SIZE + 4*mIPs.size() + 4);
buffer.putInt(4*mIPs.size()+ 4);
buffer.putChar(DataPackage.IP_LIST);
//ID assigned:
buffer.putInt(mIPs.size()+1);
buffer.putInt(4*mIPs.size()+ 4);
for (int i = 0; i < mIPs.size(); i++)
{
byte[] byteAddress = mIPs.get(i).getAddress();
buffer.put(byteAddress);
Log.d(TAG, "Created IP to send with size: " + byteAddress.length);
}
peer.getOutputStream().write(buffer.array());
peer.getOutputStream().flush();
buffer.clear();
Log.d(TAG, "Sent IP list");
}
/**
* Handle the object found in the outputstream and sends it to the correct place
* @param o
*/
private synchronized void handleData(DataPackage data)
{
switch (data.getOperationCode())
{
case DataPackage.BALL_FIRED:
fireBall(data.getData());
break;
case DataPackage.ANT:
updateAnt(data.getData());
break;
case DataPackage.IP_LIST:
resolveHandshake(data.getData());
break;
default:
break;
}
}
/** One ServerThread will run listening for new connections. */
class ServerThread implements Runnable {
public ServerThread()
{
}
@Override
public void run() {
try {
mServerSocket = new ServerSocket(SERVER_PORT);
mIP = mServerSocket.getInetAddress();
Log.d(TAG, "ServerSocket Created, waiting for connections.");
while (!Thread.currentThread().isInterrupted()) {
Socket socket = mServerSocket.accept();
//Connection found, init it.
handshake(socket);
}
} catch (IOException e) {
Log.e(TAG, "Error creating ServerSocket: ", e);
e.printStackTrace();
}
}
}
/** One ListenerThread is opened for each peer. It reads the inputStream continuously for data */
private class ListenerThread implements Runnable{
private final String TAG = "ListenerThread";
private Peer mPeer;
public ListenerThread(Peer peer) {
mPeer = peer;
}
public void run(){
Log.d(TAG, "Listening to: " + mPeer.getAdress());
while (!Thread.currentThread().isInterrupted()) {
DataPackage data = new DataPackage(mPeer.getInputStream());
handleData(data);
}
Log.d(TAG, "Stopped listening to: " + mPeer.getAdress());
}
}
private class ConnectionThread implements Runnable{
private InetAddress address;
public ConnectionThread(InetAddress address)
{
this.address =address;
}
public void run(){
try {
Socket socket = new Socket(address, SERVER_PORT);
Peer peer = new Peer(socket);
new Thread(new ListenerThread(peer)).start();
mPeers.add(peer);
mIPs.add(peer.getAdress());
Log.d(TAG, "Connected to: " + address);
} catch (IOException e) {
Log.e(TAG,"Error when connecting.", e);
e.printStackTrace();
}
}
}
//FUNCTIONS FOR UPDATING GAME STATE
private synchronized void fireBall(byte[] data)
{
ByteBuffer buffer = ByteBuffer.wrap(data);
int id = buffer.getInt();
Vector3d vel = new Vector3d(buffer.getFloat(),buffer.getFloat(),buffer.getFloat());
Vector3d pos = new Vector3d(buffer.getFloat(),buffer.getFloat(),buffer.getFloat());
GameState.getState().exsisting_paint_balls.get(id).fire(vel, pos);
}
private synchronized void updateAnt(byte[] data)
{
ByteBuffer buffer = ByteBuffer.wrap(data);
int id = buffer.getInt();
Vector3d pos = new Vector3d(buffer.getFloat(),buffer.getFloat(),buffer.getFloat());
//GameState.getState().ants.get(id).setPosition(pos);
}
private synchronized void resolveHandshake(byte[] data)
{
if (handshakeActive)
return;
handshakeActive = true;
ByteBuffer buffer = ByteBuffer.wrap(data);
GameState.getState().myPlayerID =buffer.getInt();
byte[] byteIP = new byte[4];
while (buffer.hasRemaining())
{
try {
buffer.get(byteIP);
connectToPeer(InetAddress.getByAddress(byteIP), SERVER_PORT);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Log.d(TAG, "Assigned ID: " + GameState.getState().myPlayerID);
}
} |
package com.iic.tapemeasure;
import android.app.Activity;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import org.apache.commons.logging.Log;
import java.util.Date;
public class MainActivity extends Activity {
private KolGenerator kolGenerator;
Handler handler = new Handler();
Button playButton;
Button listenButton;
WaveForm waveForm;
long soundPlayDate;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
kolGenerator = new KolGenerator();
playButton = (Button)findViewById(R.id.button);
listenButton = (Button)findViewById(R.id.button2);
playButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
playSoundLikeABoss();
}
});
listenButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
listenToSoundLikeABoss();
}
});
waveForm = (WaveForm)findViewById(R.id.view);
}
void listenToSoundLikeABoss() {
listenButton.setEnabled(false);
int audioFormat = AudioFormat.ENCODING_PCM_16BIT;
final int bufferSize = AudioRecord.getMinBufferSize(44100, AudioFormat.CHANNEL_IN_MONO, audioFormat);
final AudioRecord record = new AudioRecord(MediaRecorder.AudioSource.MIC, 44100, AudioFormat.CHANNEL_IN_MONO, audioFormat, bufferSize);
final short bytes[] = new short[bufferSize / 2];
record.startRecording();
getSamples();
final Thread thread = new Thread(new Runnable() {
public void run() {
while (true) {
record.read(bytes, 0, bufferSize / 2);
handler.post(new Runnable() {
public void run() {
for (short s : bytes) {
waveForm.AddSample(s);
}
}
});
}
}
});
thread.start();
}
void getSamples() {
// read
}
void playSoundLikeABoss() {
final Thread thread = new Thread(new Runnable() {
public void run() {
kolGenerator.genTone();
handler.post(new Runnable() {
public void run() {
kolGenerator.playSound();
}
});
}
});
thread.start();
soundPlayDate = System.currentTimeMillis();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
} |
package SyntacticAnalyzer;
public class Parser {
private Tokenizer tokenizer;
private Token lookAhead, currentToken;
public Parser(String filename) {
tokenizer = new Tokenizer(filename);
}
// analizador sintactico
public void analize() throws SyntacticException, LexicalException {
lookAhead = tokenizer.getToken();
currentToken = null;
Inicial();
}
public void match(String token) throws LexicalException, SyntacticException {
if (lookAhead.getToken().equals(token)) {
if (!token.equals("EOF")) {
currentToken = lookAhead;
lookAhead = tokenizer.getToken();
} else {
System.err.println("FIN DE ARCHIVO :O ");
}
} else {
throw new SyntacticException("Se esperaba: '" + token + "'\nSe encontro: '" + lookAhead.getToken() + "'\nNumero de linea: " + lookAhead.getLineNumber());
}
}
// no-terminales
private void Inicial() throws LexicalException, SyntacticException {
Clase();
ListaClases();
}
private void ListaClases() throws LexicalException, SyntacticException {
if (lookAhead.equals("class")) {
Clase();
ListaClases();
} else if (lookAhead.equals("EOF")) {
System.err.println("El analizador sintáctico termino exitosamente");
} else {
throw new SyntacticException("Se alcanzo EOF durante el análisis sintáctico.");
}
}
private void Clase() throws LexicalException, SyntacticException {
match("class");
match("id");
Herencia();
match("{");
ListaMiembros();
match("}");
}
private void Herencia() throws LexicalException, SyntacticException {
if (lookAhead.equals("extends")) {
match("extends");
match("id");
} else if (lookAhead.equals("{")) {
// Herencia -> lambda
// No hay herencia
} else {
throw new SyntacticException("Se esperaba la lista de miembros de la clase.");
}
}
private void ListaMiembros() throws LexicalException, SyntacticException {
if (lookAhead.equals("}")) {
// ListaMiembros -> lambda
// No hay mas miembros
} else {
Miembro();
ListaMiembros();
// Para no duplicar codigo dejamos que el control
// de lo haga Miembro()
}
}
private void Miembro() throws LexicalException, SyntacticException {
if (lookAhead.equals("var")) {
Atributo();
} else if (lookAhead.equals("id")) {
Ctor();
} else if (lookAhead.equals("static") || lookAhead.equals("dynamic")) {
Metodo();
} else {
throw new SyntacticException("Se esperaba la definicion de atributos, constructores o metodos.");
}
}
private void Atributo() throws LexicalException, SyntacticException {
match("var");
Tipo();
ListaDecVars();
match(";");
}
private void Metodo() throws LexicalException, SyntacticException {
ModMetodo();
TipoMetodo();
match("id");
ArgsFormales();
VarsLocales();
Bloque();
}
private void Ctor() throws LexicalException, SyntacticException {
match("id");
ArgsFormales();
VarsLocales();
Bloque();
}
private void ArgsFormales() throws LexicalException, SyntacticException {
match("(");
ArgsFormales_();
match(")");
}
private void ArgsFormales_() throws LexicalException, SyntacticException {
if (lookAhead.equals(")")) {
// ArgsFormales_ -> lambda
// No hay mas argumentos formales
} else {
ListaArgsFormales();
}
}
private void ListaArgsFormales() throws LexicalException, SyntacticException {
ArgFormal();
ListaArgsFormales_();
}
private void ListaArgsFormales_() throws LexicalException, SyntacticException {
if (lookAhead.equals(")")) {
// ListaArgsFormales_ -> lambda
// No hay mas argumentos formales
} else if (lookAhead.equals(",")) {
match(",");
ListaArgsFormales();
} else {
throw new SyntacticException("Se esperaban argumentos formales.");
}
}
private void ArgFormal() throws LexicalException, SyntacticException {
Tipo();
match("id");
}
private void VarsLocales() throws LexicalException, SyntacticException {
ListaAtributos();
}
private void ListaAtributos() throws LexicalException, SyntacticException {
if (lookAhead.equals("{")) {
// ListaAtributos -> lambda
// Bloque
// No hay mas atributos
} else if (lookAhead.equals("var")) {
Atributo();
ListaAtributos();
} else {
throw new SyntacticException("Se esperaban atributos.");
}
}
private void ModMetodo() throws LexicalException, SyntacticException {
if (lookAhead.equals("static")) {
match("static");
} else if (lookAhead.equals("dynamic")) {
match("dynamic");
} else {
throw new SyntacticException("Se esperaba el modo de ejecucion del metodo (static o dynamic).");
}
}
private void TipoMetodo() throws LexicalException, SyntacticException {
if (lookAhead.equals("void")) {
match("void");
} else {
Tipo();
}
}
private void Tipo() throws LexicalException, SyntacticException {
if (lookAhead.equals("id")) {
match("id");
} else {
TipoPrimitivo();
}
}
private void TipoPrimitivo() throws LexicalException, SyntacticException {
if (lookAhead.equals("boolean")) {
match("boolean");
} else if (lookAhead.equals("char")) {
match("char");
} else if (lookAhead.equals("int")) {
match("int");
} else if (lookAhead.equals("String")) {
match("String");
} else {
throw new SyntacticException("Se esperaba un tipo de dato.");
}
}
private void ListaDecVars() throws LexicalException, SyntacticException {
match("id");
ListaDecVars_();
}
private void ListaDecVars_() throws LexicalException, SyntacticException {
if (lookAhead.equals(";")) {
// ListaDecVars_ -> lambda
// No hay mas variables declaradas
} else if (lookAhead.equals(",")) {
match(",");
ListaDecVars();
} else {
throw new SyntacticException("Se esperaba una variable.");
}
}
private void Bloque() throws LexicalException, SyntacticException {
match("{");
ListaSentencias();
match("}");
}
private void ListaSentencias() throws LexicalException, SyntacticException {
if (lookAhead.equals("}")) {
// ListaSentencias -> lambda
// No hay mas sentencias
} else {
Sentencia();
// Delego el control de terminales o no-terminales a Sentencia()
ListaSentencias();
}
}
private void Sentencia() throws LexicalException, SyntacticException {
if (lookAhead.equals(";")) {
match(";");
} else if (lookAhead.equals("id")) {
Asignacion();
match(";");
} else if (lookAhead.equals("(")) {
SentenciaSimple();
match(";");
} else if (lookAhead.equals("if")) {
match("if");
match("(");
Expresion();
match(")");
Sentencia();
Sentencia_();
} else if (lookAhead.equals("while")) {
match("while");
match("(");
Expresion();
match(")");
Sentencia();
} else if (lookAhead.equals("for")) {
match("for");
match("(");
Asignacion();
match(";");
Expresion();
match(";");
Expresion();
match(")");
Sentencia();
} else if (lookAhead.equals("{")) {
Bloque();
} else if (lookAhead.equals("return")) {
match("return");
Sentencia__();
match(";");
} else {
throw new SyntacticException("Se esperaba una sentencia.");
}
}
private void Sentencia_() throws LexicalException, SyntacticException {
if (lookAhead.equals("else")) {
Sentencia();
} else {
// Sentencia_ -> lambda
// if-then sin else
}
}
private void Sentencia__() throws LexicalException, SyntacticException {
if (lookAhead.equals(";")) {
// Sentencia__ -> lambda
} else {
Expresion();
}
}
private void Asignacion() throws LexicalException, SyntacticException {
match("id");
match("=");
Expresion();
}
private void SentenciaSimple() throws LexicalException, SyntacticException {
match("(");
Expresion();
match(")");
}
private void Expresion() throws LexicalException, SyntacticException {
Expresion6();
}
private void Expresion6() throws LexicalException, SyntacticException {
Expresion5();
Expresion6_();
}
private void Expresion6_() throws LexicalException, SyntacticException {
if (lookAhead.equals("||")) {
match("||");
Expresion5();
Expresion6_();
} else {
// Expresion6_ -> lambda
}
}
private void Expresion5() throws LexicalException, SyntacticException {
Expresion4();
Expresion5_();
}
private void Expresion5_() throws LexicalException, SyntacticException {
if (lookAhead.equals("&&")) {
match("&&");
Expresion4();
Expresion5_();
} else {
// Expresion5_ -> lambda
}
}
private void Expresion4() throws LexicalException, SyntacticException {
Expresion3();
Expresion4_();
}
private void Expresion4_() throws LexicalException, SyntacticException {
if (lookAhead.equals("==") || lookAhead.equals("!=")) {
Operador4();
Expresion3();
Expresion4_();
} else {
// Expresion4_ -> lambda
}
}
private void Expresion3() throws LexicalException, SyntacticException {
Expresion2();
Expresion3_();
}
private void Expresion3_() throws LexicalException, SyntacticException {
if (lookAhead.equals("<") || lookAhead.equals(">") || lookAhead.equals(">=") || lookAhead.equals("<=")) {
Operador3();
Expresion2();
Expresion3_();
} else {
// Expresion3_ -> lambda
}
}
private void Expresion2() throws LexicalException, SyntacticException {
Expresion1();
Expresion2_();
}
private void Expresion2_() throws LexicalException, SyntacticException {
if (lookAhead.equals("+") || lookAhead.equals(">")) {
Operador2();
Expresion1();
Expresion2_();
} else {
// Expresion2_ -> lambda
}
}
private void Expresion1() throws LexicalException, SyntacticException {
Expresion0();
Expresion1_();
}
private void Expresion1_() throws LexicalException, SyntacticException {
if (lookAhead.equals("*") || lookAhead.equals("/")) {
Operador1();
Expresion0();
Expresion1_();
} else {
// Expresion1_ -> lambda
}
}
private void Expresion0() throws LexicalException, SyntacticException {
if (lookAhead.equals("!") || lookAhead.equals("+") || lookAhead.equals("-")) {
OperadorUnario();
Primario();
} else {
Primario();
}
}
private void Operador4() throws LexicalException, SyntacticException {
if (lookAhead.equals("==")) {
match("==");
} else if (lookAhead.equals("!=")) {
match("!=");
} else {
throw new SyntacticException("Se esperaba == o != .");
}
}
private void Operador3() throws LexicalException, SyntacticException {
if (lookAhead.equals("<")) {
match("<");
} else if (lookAhead.equals(">")) {
match(">");
} else if (lookAhead.equals(">=")) {
match(">=");
} else if (lookAhead.equals("<=")) {
match("<=");
} else {
throw new SyntacticException("Se esperaba <, >, <=, >= .");
}
}
private void Operador2() throws LexicalException, SyntacticException {
if (lookAhead.equals("+")) {
match("+");
} else if (lookAhead.equals("-")) {
match("-");
} else {
throw new SyntacticException("Se esperaba + o - .");
}
}
private void Operador1() throws LexicalException, SyntacticException {
if (lookAhead.equals("*")) {
match("*");
} else if (lookAhead.equals("/")) {
match("/");
} else {
throw new SyntacticException("Se esperaba * o / .");
}
}
private void OperadorUnario() throws LexicalException, SyntacticException {
if (lookAhead.equals("!")) {
match("!");
} else if (lookAhead.equals("+")) {
match("+");
} else if (lookAhead.equals("-")) {
match("-");
} else {
throw new SyntacticException("Se esperaba !, + o - .");
}
}
private void Primario() throws LexicalException, SyntacticException {
if (lookAhead.equals("this")) {
match("this");
} else if (lookAhead.equals("(")) {
match("(");
Expresion();
match(")");
ListaLlamadas();
} else if (lookAhead.equals("id")) {
match("id");
ListaLlamadas_();
} else if (lookAhead.equals("new")) {
match("new");
match("id");
ArgsActuales();
ListaLlamadas();
} else if (lookAhead.equals("id")) {
match("id");
ArgsActuales();
ListaLlamadas();
} else {
Literal();
}
}
private void ListaLlamadas() throws LexicalException, SyntacticException {
if (lookAhead.equals(".")) {
Llamada();
ListaLlamadas();
} else {
// ListaLlamadas -> lambda
}
}
private void ListaLlamadas_() throws LexicalException, SyntacticException {
if (lookAhead.equals("(")) {
ArgsActuales();
ListaLlamadas();
} else {
ListaLlamadas();
}
}
private void Llamada() throws LexicalException, SyntacticException {
match(".");
match("id");
ArgsActuales();
}
private void Literal() throws LexicalException, SyntacticException {
if (lookAhead.equals("null")) {
match("null");
} else if (lookAhead.equals("true")) {
match("true");
} else if (lookAhead.equals("false")) {
match("false");
} else if (lookAhead.equals("intLiteral")) {
match("intLiteral");
} else if (lookAhead.equals("charLiteral")) {
match("charLiteral");
} else if (lookAhead.equals("stringLiteral")) {
match("stringLiteral");
} else {
throw new SyntacticException("Se esperaba un literal.");
}
}
private void ArgsActuales() throws LexicalException, SyntacticException {
match("(");
ArgsActuales_();
match(")");
}
private void ArgsActuales_() throws LexicalException, SyntacticException {
if (lookAhead.equals("!") || lookAhead.equals("+") || lookAhead.equals("-") || lookAhead.equals("this") || lookAhead.equals("new") || lookAhead.equals("id") || lookAhead.equals("(") || lookAhead.equals("null") || lookAhead.equals("true") || lookAhead.equals("false") || lookAhead.equals("intLiteral") || lookAhead.equals("charLiteral") || lookAhead.equals("stringLiteral")) {
Expresion();
} else {
// ListaExps -> lambda
}
}
private void ListaExps() throws LexicalException, SyntacticException {
Expresion();
ListaExps_();
}
private void ListaExps_() throws LexicalException, SyntacticException {
if (lookAhead.equals(",")) {
match(",");
ListaExps();
} else {
// ListaExps_ -> lambda
}
}
} |
// associated documentation files (the "Software"), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge, publish, distribute,
// furnished to do so, subject to the following conditions:
// substantial portions of the Software.
// NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package com.onefishtwo.bbqtimer;
import android.annotation.TargetApi;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.AudioAttributes;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Build;
import android.os.SystemClock;
import android.text.Spanned;
import android.text.SpannedString;
import android.view.View;
import android.widget.RemoteViews;
import com.onefishtwo.bbqtimer.state.ApplicationState;
import androidx.annotation.DrawableRes;
import androidx.annotation.IdRes;
import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.annotation.RawRes;
import androidx.annotation.StringRes;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
import androidx.core.app.TaskStackBuilder;
import androidx.core.content.ContextCompat;
import androidx.media.app.NotificationCompat.DecoratedMediaCustomViewStyle;
import androidx.media.app.NotificationCompat.MediaStyle;
/**
* Manages the app's Android Notifications.
*/
public class Notifier {
private static final int NOTIFICATION_ID = 7;
private static final int FLAG_IMMUTABLE =
Build.VERSION.SDK_INT >= 23 ? PendingIntent.FLAG_IMMUTABLE : 0;
/**
* Construct a custom notification for this API level and higher. The custom notification really
* helps on Android 12 where MediaStyle's collapsed notification hides the Chronometer and the
* lock screen interferes with expanding the notification.
*
* API 24 is required for a count-down Chronometer and for
* NotificationCompat.DecoratedMediaCustomViewStyle to do more than MediaStyle.
*/
private static final int CUSTOM_NOTIFICATION_API_LEVEL = 24;
private static final SpannedString EMPTY_SPAN = new SpannedString("");
private static final long[] VIBRATE_PATTERN = {200, 40, 220, 80, 440, 45, 265, 55}; // ms off, on, off, ...
private static final int[][] ACTION_INDICES = {{}, {0}, {0, 1}, {0, 1, 2}};
static final String ALARM_NOTIFICATION_CHANNEL_ID = "alarmChannel";
// Was in release "2.5" (v15) and will remain immutable on devices while the app is installed:
// static final String CONTROLS_NOTIFICATION_CHANNEL_ID = "controlsChannel";
private static final int RUNNING_FLIPPER_CHILD = 0;
private static final int PAUSED_FLIPPER_CHILD = 1;
private static boolean builtNotificationChannels = false;
@NonNull
private final Context context;
@NonNull
private final NotificationManager notificationManager;
@NonNull
private final NotificationManagerCompat notificationManagerCompat;
private final int notificationLightColor;
private Bitmap largeIcon; // only for API < 24
private boolean soundAlarm = false; // whether the next notification should sound an alarm
private int numActions; // the number of action buttons added to the notification being built
public Notifier(@NonNull Context _context) {
this.context = _context;
notificationManager =
(NotificationManager) _context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManagerCompat = NotificationManagerCompat.from(_context);
notificationLightColor = ContextCompat.getColor(_context, R.color.notification_light_color);
}
/**
* Builder-style setter: Whether to make the next notification sound an alarm, vibrate, and
* flash the device LED. Initially set to false.
*/
@NonNull
public Notifier setAlarm(boolean _soundAlarm) {
this.soundAlarm = _soundAlarm;
return this;
}
private Uri getSoundUri(@RawRes int soundId) {
return Uri.parse("android.resource://" + context.getPackageName() + "/" + soundId);
}
/** Constructs a PendingIntent to use as a Notification Action. */
private PendingIntent makeActionIntent(String action) {
return TimerAppWidgetProvider.makeActionIntent(context, action);
}
/**
* Adds an action button to the given NotificationBuilder and to the
* {@link #setMediaStyleActionsInCompactView} list.
*/
private void addAction(@NonNull NotificationCompat.Builder builder, @DrawableRes int iconId,
@StringRes int titleId, PendingIntent intent) {
builder.addAction(iconId, context.getString(titleId), intent);
++numActions;
}
/**
* Makes the first 3 added {@link #addAction} actions appear in a MediaStyle notification
* view. The Media template should fit 3 actions in its collapsed view, 6 actions in expanded
* view, or 5 actions in expanded view with a large image but I haven't tested that.
*<p/>
* Calls builder.setColor() on some versions of Android to cope with OS vagaries.
*/
private void setMediaStyleActionsInCompactView(@NonNull NotificationCompat.Builder builder) {
int num = Math.min(numActions, ACTION_INDICES.length - 1);
if (num < 1) {
return;
}
MediaStyle style;
if (Build.VERSION.SDK_INT >= CUSTOM_NOTIFICATION_API_LEVEL) {
style = new DecoratedMediaCustomViewStyle();
} else {
style = new MediaStyle();
}
style.setShowActionsInCompactView(ACTION_INDICES[num]);
builder.setStyle(style);
// API 21 L - 22 L1: colors the notification area background needlessly.
// API 23 M: See below.
// API 24 N - API 27 O1: colors the small icon, action button, and app title color. Garish.
// API 28 P - API 30 R: colors the small icon and action button. Garish.
// API 31 S: See below.
// setColorized(false) didn't change any of these results.
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.M) {
// Android 6 M, API 23: setColor() colors the notification are background and avoids a
// low contrast dark gray text on darker gray background in the the heads-up case.
// setColor() also changes pull-down notifications and carries over from one
int workaroundColor = context.getColor(R.color.gray_text);
builder.setColor(workaroundColor);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
// Android 12, S, API 31: setColor() colors the small icon's circular background.
int iconBackgroundColor = context.getColor(R.color.dark_orange_red);
builder.setColor(iconBackgroundColor);
}
}
/**
* Returns a localized description of the timer's run state: "Running", "Paused 00:12.3"
* (optionally including the time value), or "Stopped".
*/
@NonNull
String timerRunState(@NonNull TimeCounter timer, boolean includeTime) {
if (timer.isRunning()) {
return context.getString(R.string.timer_running);
} else if (timer.isPaused()) {
Spanned pauseTime = includeTime ? timer.formatHhMmSsFraction() : EMPTY_SPAN;
return context.getString(R.string.timer_paused, pauseTime);
} else {
return context.getString(R.string.timer_stopped);
}
}
/**
* Returns a localized description of the periodic alarms.
*
* @param state the ApplicationState.
* @return a localized string like "Alarm every 2 minutes", or "" for no periodic alarms.
*/
@NonNull
String describePeriodicAlarms(@NonNull ApplicationState state) {
// Synthesize a "quantity" to select the right pluralization rule.
int reminderSecs = state.getSecondsPerReminder();
int quantity = MinutesChoices.secondsToMinutesPluralizationQuantity(reminderSecs);
String minutes = MainActivity.secondsToMinuteChoiceString(reminderSecs);
return state.isEnableReminders()
? context.getResources().getQuantityString(
R.plurals.notification_body, quantity, minutes)
: "";
}
/**
* <em>(Re)Opens</em> this app's notification with content depending on {@code state} and
* {@link #setAlarm(boolean)},
* <em>or cancels</em> the app's notification if there's nothing to show or sound.
*
* @param state the ApplicationState state to display.
*/
public void openOrCancel(@NonNull ApplicationState state) {
TimeCounter timer = state.getTimeCounter();
if (!timer.isStopped() || soundAlarm) {
Notification notification = buildNotification(state);
notificationManagerCompat.notify(NOTIFICATION_ID, notification);
} else {
cancelAll();
}
}
/**
* Returns true if the Alarm channel is configured On with enough Importance to hear alarms.
* After createNotificationChannelV26() creates the channels, the user can reconfigure them and
* the app can only set their names and descriptions. If users configure the Alarm channel to be
* silent but request Periodic Alarms, they'll think the app is broken.
*/
boolean isAlarmChannelOK() {
if (Build.VERSION.SDK_INT >= 26) {
NotificationChannel channel = notificationManager.getNotificationChannel(
ALARM_NOTIFICATION_CHANNEL_ID);
if (channel == null) { // The channel hasn't been created so it can't be broken.
return true;
}
int importance = channel.getImportance();
return importance >= NotificationManager.IMPORTANCE_DEFAULT;
}
return true;
}
/**
* Creates a notification channel that matches the parameters #buildNotification() uses. The
* "Alarm" channel sounds an alarm at heads-up High importance.
*/
@TargetApi(26)
private void createNotificationChannelV26() {
String name = context.getString(R.string.notification_alarm_channel_name);
String description = context.getString(R.string.notification_alarm_channel_description);
NotificationChannel channel = new NotificationChannel(
ALARM_NOTIFICATION_CHANNEL_ID, name, NotificationManager.IMPORTANCE_HIGH);
channel.setDescription(description);
channel.enableLights(true);
channel.setLightColor(notificationLightColor);
channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
channel.enableVibration(true);
channel.setVibrationPattern(VIBRATE_PATTERN);
{
AudioAttributes audioAttributes = new AudioAttributes.Builder()
//.setLegacyStreamType(AudioManager.STREAM_ALARM)
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_ALARM)
.build();
channel.setSound(getSoundUri(R.raw.cowbell4), audioAttributes);
}
channel.setShowBadge(false);
// Did not setBypassDnd(), setGroup().
notificationManager.createNotificationChannel(channel); // goofy naming
}
/** Creates notification channel(s) lazily (or updates the text) on Android O+. */
private void createNotificationChannels() {
if (Build.VERSION.SDK_INT < 26 || builtNotificationChannels) {
return;
}
createNotificationChannelV26();
builtNotificationChannels = true;
}
/** Update state (e.g. notification channel text) for a UI Locale change. */
void onLocaleChange() {
if (Build.VERSION.SDK_INT >= 26) {
NotificationChannel channel = notificationManager.getNotificationChannel(
ALARM_NOTIFICATION_CHANNEL_ID);
//noinspection VariableNotUsedInsideIf
if (channel != null) {
builtNotificationChannels = false;
createNotificationChannels();
}
}
}
/**
* Make and initialize the RemoteViews for a Custom Notification.
*<p/>
* Workaround: A paused Chronometer doesn't show a stable value, e.g. switching light/dark theme
* can change it, and it ignores its format string thus ruling out some workarounds.
* *SO* when the timer is paused, flip to a TextView.
*
* @param layoutId the layout resource ID for the RemoteViews.
* @param state the ApplicationState to show.
* @param countUpMessage the message to show next to the count-up (stopwatch) Chronometer. This
* Chronometer and its message are GONE if there are no periodic alarms.
* @param countDownMessage the message to show next to the count-down (timer) Chronometer.
* @return RemoteViews
*/
@NonNull
@TargetApi(24)
private RemoteViews makeRemoteViews(
@LayoutRes int layoutId, @NonNull ApplicationState state, @NonNull String countUpMessage,
@NonNull String countDownMessage) {
TimeCounter timer = state.getTimeCounter();
long elapsedTime = timer.getElapsedTime();
boolean isRunning = timer.isRunning();
long rt = SystemClock.elapsedRealtime();
long countUpBase = rt - elapsedTime;
@IdRes int childId = isRunning ? RUNNING_FLIPPER_CHILD : PAUSED_FLIPPER_CHILD;
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), layoutId);
// Count-up time and status
if (!isRunning) {
remoteViews.setTextViewText(R.id.pausedCountUp, TimeCounter.formatHhMmSs(elapsedTime));
}
remoteViews.setDisplayedChild(R.id.countUpViewFlipper, childId);
remoteViews.setChronometer(
R.id.countUpChronometer, countUpBase, null, isRunning);
remoteViews.setTextViewText(R.id.countUpMessage, countUpMessage);
// Count-down time and status
if (state.isEnableReminders()) {
long period = state.getMillisecondsPerReminder();
long countdownToNextAlarm = Math.max(period - elapsedTime % period + 999, 0);
long countdownBase = rt + countdownToNextAlarm;
if (!isRunning) {
remoteViews.setTextViewText(
R.id.pausedCountdown, TimeCounter.formatHhMmSs(countdownToNextAlarm));
}
remoteViews.setDisplayedChild(R.id.countdownViewFlipper, childId);
remoteViews.setChronometer(
R.id.countdownChronometer, countdownBase, null, isRunning);
remoteViews.setTextViewText(R.id.countdownMessage, countDownMessage);
} else {
remoteViews.setChronometer(
R.id.countdownChronometer, 0, null, false);
remoteViews.setViewVisibility(R.id.countdownChronometer, View.GONE);
remoteViews.setViewVisibility(R.id.countdownMessage, View.GONE);
}
return remoteViews;
}
/**
* Builds a notification. Its alarm sound, vibration, and LED light flashing are switched on/off
* by {@link #setAlarm(boolean)}.
*/
@NonNull
protected Notification buildNotification(@NonNull ApplicationState state) {
createNotificationChannels();
NotificationCompat.Builder builder =
new NotificationCompat.Builder(context, ALARM_NOTIFICATION_CHANNEL_ID)
.setPriority(NotificationCompat.PRIORITY_MAX)
.setCategory(NotificationCompat.CATEGORY_ALARM)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
{ // Construct the visible notification contents.
TimeCounter timer = state.getTimeCounter();
boolean isRunning = timer.isRunning();
builder.setSmallIcon(R.drawable.notification_icon)
.setContentTitle(context.getString(R.string.app_name));
// Android API < 24 stretches the small icon into a fuzzy large icon, so add a large
// icon. On API 24+, adopt the UI guideline, thus making the notification fit more in
// the compact form, which could help when the lock screen is set to
// "Show sensitive content only when unlocked".
if (Build.VERSION.SDK_INT < 24) {
if (largeIcon == null) {
largeIcon = BitmapFactory.decodeResource(context.getResources(),
R.drawable.ic_large_notification);
}
builder.setLargeIcon(largeIcon);
}
if (Build.VERSION.SDK_INT < CUSTOM_NOTIFICATION_API_LEVEL && isRunning) {
builder.setWhen(System.currentTimeMillis() - timer.getElapsedTime())
.setUsesChronometer(true);
} else {
// Hide the "when" field, which isn't useful while Paused, so it doesn't take space
// in the compact view along with 3 action buttons (Reset, Start, Stop).
builder.setShowWhen(false);
}
String alarmEvery = describePeriodicAlarms(state);
if (isRunning && state.isEnableReminders()) {
builder.setContentText(alarmEvery);
} else {
String runPauseStop = timerRunState(timer, true); // Running/Paused 00:12.3/Stopped
builder.setContentText(runPauseStop);
if (timer.isPaused()) {
builder.setSubText(context.getString(R.string.dismiss_tip));
} else if (isRunning) {
builder.setSubText(context.getString(R.string.no_reminders_tip));
}
}
if (Build.VERSION.SDK_INT >= CUSTOM_NOTIFICATION_API_LEVEL) {
String countUpMessage = timerRunState(timer, false); // Running/Paused/Stopped
RemoteViews notificationView = makeRemoteViews(
R.layout.custom_notification, state, countUpMessage, alarmEvery);
builder.setCustomContentView(notificationView);
builder.setCustomHeadsUpContentView(notificationView);
builder.setCustomBigContentView(notificationView);
}
numActions = 0;
{
// Make an Intent to launch the Activity from the notification.
Intent activityIntent = new Intent(context, MainActivity.class)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// So navigating back from the Activity goes from the app to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context)
.addParentStack(MainActivity.class)
.addNextIntent(activityIntent);
PendingIntent activityPendingIntent =
stackBuilder.getPendingIntent(0,
PendingIntent.FLAG_UPDATE_CURRENT + FLAG_IMMUTABLE);
builder.setContentIntent(activityPendingIntent);
// Action button to reset the timer.
if (timer.isPaused() && !timer.isPausedAt0()) {
PendingIntent resetIntent =
makeActionIntent(TimerAppWidgetProvider.ACTION_RESET);
addAction(builder, R.drawable.ic_action_replay, R.string.reset, resetIntent);
}
// Action button to run (start) the timer.
if (!isRunning) {
PendingIntent runIntent = makeActionIntent(TimerAppWidgetProvider.ACTION_RUN);
addAction(builder, R.drawable.ic_action_play, R.string.start, runIntent);
}
// Action button to pause the timer.
if (!timer.isPaused()) {
PendingIntent pauseIntent
= makeActionIntent(TimerAppWidgetProvider.ACTION_PAUSE);
addAction(builder, R.drawable.ic_action_pause, R.string.pause, pauseIntent);
}
// Action button to stop the timer.
PendingIntent stopIntent = makeActionIntent(TimerAppWidgetProvider.ACTION_STOP);
if (!timer.isStopped()) {
addAction(builder, R.drawable.ic_action_stop, R.string.stop, stopIntent);
}
// Allow stopping via dismissing the notification (unless it's "ongoing").
builder.setDeleteIntent(stopIntent);
setMediaStyleActionsInCompactView(builder);
}
if (isRunning) {
builder.setOngoing(true);
}
}
if (soundAlarm) {
builder.setSound(getSoundUri(R.raw.cowbell4), AudioManager.STREAM_ALARM);
builder.setVibrate(VIBRATE_PATTERN);
builder.setLights(notificationLightColor, 1000, 2000);
} else {
builder.setSilent(true);
}
return builder.build();
}
/** Cancels all of this app's notifications. */
public void cancelAll() {
notificationManagerCompat.cancelAll();
}
} |
package org.projectodd.stilts.stomp;
import org.jboss.logging.Logger;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class Heartbeat {
private static final double TOLERANCE_PERCENTAGE = 0.05;
private static final Logger log = Logger.getLogger( Heartbeat.class );
public Heartbeat() {
}
public void start(final Runnable callback) {
final int duration = calculateDuration(serverSend, clientReceive);
log.debugf("heartbeat duration: %d", duration);
if (duration > 0) {
future = heartbeatScheduler.schedule(new Runnable() {
@Override
public void run() {
long now = System.currentTimeMillis();
long lastUpdate = getLastUpdate();
long diff = now - lastUpdate;
double tolerance = duration * TOLERANCE_PERCENTAGE;
if (diff > duration - tolerance) {
log.tracef("HEARTBEAT : %s / %s", diff, duration);
try {
callback.run();
} catch (Exception e) {
log.error("Could not send heartbeat message:", e);
}
touch();
}
long targetDelay = lastUpdate + duration - now;
if (!stopped) {
future = heartbeatScheduler.schedule(this, targetDelay, TimeUnit.MILLISECONDS);
}
}
}, duration, TimeUnit.MILLISECONDS);
}
}
public void stop() {
stopped = true;
Future<?> future = this.future;
if (future != null) {
future.cancel(false);
}
}
public int calculateDuration(int senderDuration, int receiverDuration) {
if (senderDuration == 0 || receiverDuration == 0) {
return 0;
}
return Math.max( senderDuration, receiverDuration );
}
public int getClientReceive() {
return clientReceive;
}
public int getClientSend() {
return clientSend;
}
public long getLastUpdate() {
return lastUpdate;
}
public int getServerReceive() {
return serverReceive;
}
public int getServerSend() {
return serverSend;
}
public void setClientReceive(int clientReceive) {
this.clientReceive = clientReceive;
}
public void setClientSend(int clientSend) {
this.clientSend = clientSend;
}
public void setServerReceive(int serverReceive) {
this.serverReceive = serverReceive;
}
public void setServerSend(int serverSend) {
this.serverSend = serverSend;
}
public synchronized void touch() {
lastUpdate = System.currentTimeMillis();
}
public Future<?> getFuture() {
return future;
}
private int clientSend;
private int clientReceive;
private int serverSend = 1000;
private int serverReceive = 1000;
private long lastUpdate = System.currentTimeMillis();
private volatile boolean stopped = false;
private volatile Future<?> future;
private static final ScheduledExecutorService heartbeatScheduler = Executors.newScheduledThreadPool(4);
} |
package com.pr0gramm.app.ui;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import com.google.common.base.Optional;
import com.pr0gramm.app.R;
import com.pr0gramm.app.Settings;
import com.pr0gramm.app.SyncBroadcastReceiver;
import com.pr0gramm.app.feed.FeedFilter;
import com.pr0gramm.app.feed.FeedProxy;
import com.pr0gramm.app.feed.FeedType;
import com.pr0gramm.app.services.BookmarkService;
import com.pr0gramm.app.services.SingleShotService;
import com.pr0gramm.app.services.UserService;
import com.pr0gramm.app.ui.dialogs.ErrorDialogFragment;
import com.pr0gramm.app.ui.dialogs.UpdateDialogFragment;
import com.pr0gramm.app.ui.fragments.DrawerFragment;
import com.pr0gramm.app.ui.fragments.FeedFragment;
import com.pr0gramm.app.ui.fragments.PostPagerFragment;
import org.joda.time.Duration;
import org.joda.time.Instant;
import org.joda.time.Minutes;
import javax.annotation.Nullable;
import javax.inject.Inject;
import de.cketti.library.changelog.ChangeLog;
import roboguice.activity.RoboActionBarActivity;
import roboguice.inject.InjectView;
import rx.Observable;
import rx.Subscription;
import rx.functions.Actions;
import static com.google.common.base.MoreObjects.firstNonNull;
import static com.pr0gramm.app.ui.dialogs.ErrorDialogFragment.defaultOnError;
import static com.pr0gramm.app.ui.fragments.BusyDialogFragment.busyDialog;
import static rx.android.observables.AndroidObservable.bindActivity;
/**
* This is the main class of our pr0gramm app.
*/
public class MainActivity extends RoboActionBarActivity implements
DrawerFragment.OnFeedFilterSelected,
FragmentManager.OnBackStackChangedListener,
ScrollHideToolbarListener.ToolbarActivity,
MainActionHandler {
private final Handler handler = new Handler(Looper.getMainLooper());
private final ErrorDialogFragment.OnErrorDialogHandler errorHandler = new ActivityErrorHandler(this);
@InjectView(R.id.drawer_layout)
private DrawerLayout drawerLayout;
@InjectView(R.id.toolbar)
private Toolbar toolbar;
@Nullable
@InjectView(R.id.toolbar_container)
private View toolbarContainer;
@Inject
private UserService userService;
@Inject
private BookmarkService bookmarkService;
@Inject
private Settings settings;
@Inject
private SharedPreferences shared;
@Inject
private SingleShotService singleShotService;
private Subscription subscription;
private ActionBarDrawerToggle drawerToggle;
private ScrollHideToolbarListener scrollHideToolbarListener;
private boolean startedWithIntent;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// use toolbar as action bar
setSupportActionBar(toolbar);
// and hide it away on scrolling
scrollHideToolbarListener = new ScrollHideToolbarListener(
firstNonNull(toolbarContainer, toolbar));
// prepare drawer layout
drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.app_name, R.string.app_name);
drawerLayout.setDrawerListener(drawerToggle);
drawerLayout.setDrawerShadow(R.drawable.drawer_shadow, Gravity.START);
//noinspection ConstantConditions
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
drawerToggle.syncState();
// listen to fragment changes
getSupportFragmentManager().addOnBackStackChangedListener(this);
if (savedInstanceState == null) {
createDrawerFragment();
Intent intent = getIntent();
if (intent == null || Intent.ACTION_MAIN.equals(intent.getAction())) {
// load feed-fragment into view
gotoFeedFragment(new FeedFilter(), true);
} else {
startedWithIntent = true;
onNewIntent(intent);
}
}
ChangeLog changelog = new ChangeLog(this);
if (changelog.isFirstRun()) {
ChangeLogDialog dialog = new ChangeLogDialog();
dialog.show(getSupportFragmentManager(), null);
} else {
// start the update check.
UpdateDialogFragment.checkForUpdates(this, false);
}
addOriginalContentBookmarkOnce();
}
/**
* Adds a bookmark if there currently are no bookmarks.
*/
private void addOriginalContentBookmarkOnce() {
if (!singleShotService.isFirstTime("add_original_content_bookmarks"))
return;
bindActivity(this, bookmarkService.get().first()).subscribe(bookmarks -> {
if (bookmarks.isEmpty()) {
FeedFilter filter = new FeedFilter()
.withFeedType(FeedType.PROMOTED)
.withTags("original content");
bookmarkService.create(filter);
}
}, Actions.empty());
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
if (!Intent.ACTION_VIEW.equals(intent.getAction()))
return;
handleUri(intent.getData());
}
@Override
protected void onStart() {
super.onStart();
// trigger updates while the activity is running
sendSyncRequest.run();
}
@Override
protected void onStop() {
handler.removeCallbacks(sendSyncRequest);
super.onStop();
}
@Override
protected void onDestroy() {
getSupportFragmentManager().removeOnBackStackChangedListener(this);
try {
super.onDestroy();
} catch (RuntimeException ignored) {
}
}
@Override
public void onBackStackChanged() {
updateToolbarBackButton();
updateActionbarTitle();
DrawerFragment drawer = getDrawerFragment();
if (drawer != null) {
FeedFilter currentFilter = getCurrentFeedFilter();
// show the current item in the drawer
drawer.updateCurrentFilters(currentFilter);
}
}
private void updateActionbarTitle() {
String title;
FeedFilter filter = getCurrentFeedFilter();
if (filter == null) {
title = getString(R.string.pr0gramm);
} else {
title = FeedFilterFormatter.format(this, filter);
}
setTitle(title);
}
/**
* Returns the current feed filter. Might be null, if no filter could be detected.
*/
@Nullable
private FeedFilter getCurrentFeedFilter() {
// get the filter of the visible fragment.
FeedFilter currentFilter = null;
Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.content);
if (fragment != null) {
if (fragment instanceof FeedFragment) {
currentFilter = ((FeedFragment) fragment).getCurrentFilter();
}
if (fragment instanceof PostPagerFragment) {
currentFilter = ((PostPagerFragment) fragment).getCurrentFilter();
}
}
return currentFilter;
}
private void updateToolbarBackButton() {
FragmentManager fm = getSupportFragmentManager();
drawerToggle.setDrawerIndicatorEnabled(fm.getBackStackEntryCount() == 0);
drawerToggle.syncState();
}
private void createDrawerFragment() {
DrawerFragment fragment = new DrawerFragment();
getSupportFragmentManager().beginTransaction()
.replace(R.id.left_drawer, fragment)
.commit();
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
drawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (!drawerToggle.isDrawerIndicatorEnabled()) {
if (item.getItemId() == android.R.id.home) {
getSupportFragmentManager().popBackStack();
return true;
}
}
return drawerToggle.onOptionsItemSelected(item) || super.onOptionsItemSelected(item);
}
@Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(Gravity.START)) {
drawerLayout.closeDrawers();
return;
}
// at the end, go back to the "top" page before stopping everything.
if (getSupportFragmentManager().getBackStackEntryCount() == 0 && !startedWithIntent) {
FeedFilter filter = getCurrentFeedFilter();
if (filter != null && !isTopFilter(filter)) {
gotoFeedFragment(new FeedFilter(), true);
return;
}
}
super.onBackPressed();
}
private boolean isTopFilter(FeedFilter filter) {
return filter.isBasic() && filter.getFeedType() == FeedType.PROMOTED;
}
@Override
protected void onResume() {
super.onResume();
ErrorDialogFragment.setGlobalErrorDialogHandler(errorHandler);
Observable<UserService.LoginState> state = userService.getLoginStateObservable();
subscription = bindActivity(this, state).subscribe(this::onLoginStateChanged, Actions.empty());
onBackStackChanged();
}
@Override
protected void onPause() {
ErrorDialogFragment.unsetGlobalErrorDialogHandler(errorHandler);
if (subscription != null)
subscription.unsubscribe();
super.onPause();
}
private void onLoginStateChanged(UserService.LoginState state) {
if (state == UserService.LoginState.NOT_AUTHORIZED) {
// go back to the "top"-fragment
// gotoFeedFragment(new FeedFilter());
}
}
@Override
public void onPostClicked(FeedProxy feed, int idx) {
if (idx < 0 || idx >= feed.getItemCount())
return;
Fragment fragment = PostPagerFragment.newInstance(feed, idx);
getSupportFragmentManager().beginTransaction()
.replace(R.id.content, fragment)
.addToBackStack(null)
.commitAllowingStateLoss();
}
@Override
public void onLogoutClicked() {
bindActivity(this, userService.logout())
.lift(busyDialog(this))
.subscribe(Actions.empty(), defaultOnError());
}
@Override
public void onFeedFilterSelectedInNavigation(FeedFilter filter) {
gotoFeedFragment(filter, true);
drawerLayout.closeDrawers();
}
@Override
public void onOtherNavigationItemClicked() {
drawerLayout.closeDrawers();
}
@Override
public void onFeedFilterSelected(FeedFilter filter) {
gotoFeedFragment(filter, false);
}
@Override
public void pinFeedFilter(FeedFilter filter, String title) {
bookmarkService.create(filter, title).subscribe(Actions.empty(), defaultOnError());
drawerLayout.openDrawer(Gravity.START);
}
private void gotoFeedFragment(FeedFilter newFilter, boolean clear) {
gotoFeedFragment(newFilter, clear, Optional.<Long>absent());
}
private void gotoFeedFragment(FeedFilter newFilter, boolean clear, Optional<Long> start) {
if (isFinishing())
return;
if (clear) {
clearBackStack();
}
Fragment fragment = FeedFragment.newInstance(newFilter, start);
// and show the fragment
@SuppressLint("CommitTransaction")
FragmentTransaction transaction = getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content, fragment);
if (!clear)
transaction.addToBackStack(null);
try {
transaction.commit();
} catch (IllegalStateException ignored) {
}
// trigger a back-stack changed after adding the fragment.
new Handler().post(this::onBackStackChanged);
}
private DrawerFragment getDrawerFragment() {
return (DrawerFragment) getSupportFragmentManager()
.findFragmentById(R.id.left_drawer);
}
private void clearBackStack() {
getSupportFragmentManager().popBackStackImmediate(
null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
@Override
public ScrollHideToolbarListener getScrollHideToolbarListener() {
return scrollHideToolbarListener;
}
/**
* Handles a uri to something on pr0gramm
*
* @param uri The uri to handle
*/
private void handleUri(Uri uri) {
Optional<FeedFilterWithStart> result = FeedFilterWithStart.fromUri(uri);
if (result.isPresent()) {
FeedFilter filter = result.get().getFilter();
Optional<Long> start = result.get().getStart();
boolean clear = getSupportFragmentManager().getBackStackEntryCount() == 0;
gotoFeedFragment(filter, clear, start);
} else {
gotoFeedFragment(new FeedFilter(), true);
}
}
@SuppressWarnings("Convert2Lambda")
private final Runnable sendSyncRequest = new Runnable() {
private Instant lastUpdate = new Instant(0);
@Override
public void run() {
Instant now = Instant.now();
if (Minutes.minutesBetween(lastUpdate, now).getMinutes() > 4) {
Intent intent = new Intent(MainActivity.this, SyncBroadcastReceiver.class);
MainActivity.this.sendBroadcast(intent);
}
// reschedule
Duration delay = Minutes.minutes(5).toStandardDuration();
handler.postDelayed(this, delay.getMillis());
// and remember the last update time
lastUpdate = now;
}
};
} |
package com.snatik.matches.engine;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.TransitionDrawable;
import android.os.AsyncTask;
import android.os.Handler;
import android.util.Log;
import android.widget.ImageView;
import com.snatik.matches.R;
import com.snatik.matches.common.Memory;
import com.snatik.matches.common.Music;
import com.snatik.matches.common.SQLiteDB;
import com.snatik.matches.common.Shared;
import com.snatik.matches.engine.ScreenController.Screen;
import com.snatik.matches.events.EventObserverAdapter;
import com.snatik.matches.events.engine.FlipDownCardsEvent;
import com.snatik.matches.events.engine.GameWonEvent;
import com.snatik.matches.events.engine.HidePairCardsEvent;
import com.snatik.matches.events.ui.BackGameEvent;
import com.snatik.matches.events.ui.DifficultySelectedEvent;
import com.snatik.matches.events.ui.FlipCardEvent;
import com.snatik.matches.events.ui.NextGameEvent;
import com.snatik.matches.events.ui.ResetBackgroundEvent;
import com.snatik.matches.events.ui.StartEvent;
import com.snatik.matches.events.ui.ThemeSelectedEvent;
import com.snatik.matches.model.BoardArrangment;
import com.snatik.matches.model.BoardConfiguration;
import com.snatik.matches.model.Game;
import com.snatik.matches.model.GameState;
import com.snatik.matches.themes.Theme;
import com.snatik.matches.themes.Themes;
import com.snatik.matches.ui.PopupManager;
import com.snatik.matches.utils.Clock;
import com.snatik.matches.utils.Utils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
public class Engine extends EventObserverAdapter {
private static Engine mInstance = null;
private Game mPlayingGame = null;
private int mFlippedId = -1;
private int mToFlip = -1;
private ScreenController mScreenController;
private Theme mSelectedTheme;
private ImageView mBackgroundImage;
private Handler mHandler;
private Engine() {
mScreenController = ScreenController.getInstance();
mHandler = new Handler();
}
public static Engine getInstance() {
if (mInstance == null) {
mInstance = new Engine();
}
return mInstance;
}
public void start() {
Shared.eventBus.listen(DifficultySelectedEvent.TYPE, this);
Shared.eventBus.listen(FlipCardEvent.TYPE, this);
Shared.eventBus.listen(StartEvent.TYPE, this);
Shared.eventBus.listen(ThemeSelectedEvent.TYPE, this);
Shared.eventBus.listen(BackGameEvent.TYPE, this);
Shared.eventBus.listen(NextGameEvent.TYPE, this);
Shared.eventBus.listen(ResetBackgroundEvent.TYPE, this);
}
public void stop() {
mPlayingGame = null;
mBackgroundImage.setImageDrawable(null);
mBackgroundImage = null;
mHandler.removeCallbacksAndMessages(null);
mHandler = null;
Shared.eventBus.unlisten(DifficultySelectedEvent.TYPE, this);
Shared.eventBus.unlisten(FlipCardEvent.TYPE, this);
Shared.eventBus.unlisten(StartEvent.TYPE, this);
Shared.eventBus.unlisten(ThemeSelectedEvent.TYPE, this);
Shared.eventBus.unlisten(BackGameEvent.TYPE, this);
Shared.eventBus.unlisten(NextGameEvent.TYPE, this);
Shared.eventBus.unlisten(ResetBackgroundEvent.TYPE, this);
mInstance = null;
}
@Override
public void onEvent(ResetBackgroundEvent event) {
Drawable drawable = mBackgroundImage.getDrawable();
if (drawable != null) {
((TransitionDrawable) drawable).reverseTransition(2000);
} else {
new AsyncTask<Void, Void, Bitmap>() {
@Override
protected Bitmap doInBackground(Void... params) {
Bitmap bitmap = Utils.scaleDown(R.drawable.background, Utils.screenWidth(), Utils.screenHeight());
return bitmap;
}
protected void onPostExecute(Bitmap bitmap) {
mBackgroundImage.setImageBitmap(bitmap);
};
}.execute();
}
}
@Override
public void onEvent(StartEvent event) {
mScreenController.openScreen(Screen.THEME_SELECT);
}
@Override
public void onEvent(NextGameEvent event) {
PopupManager.closePopup();
int difficulty = mPlayingGame.boardConfiguration.difficulty;
if (mPlayingGame.gameState.achievedStars == 3 && difficulty < 6) {
difficulty++;
}
Shared.eventBus.notify(new DifficultySelectedEvent(difficulty));
}
@Override
public void onEvent(BackGameEvent event) {
PopupManager.closePopup();
mScreenController.openScreen(Screen.DIFFICULTY);
}
@Override
public void onEvent(ThemeSelectedEvent event) {
mSelectedTheme = event.theme;
mScreenController.openScreen(Screen.DIFFICULTY);
AsyncTask<Void, Void, TransitionDrawable> task = new AsyncTask<Void, Void, TransitionDrawable>() {
@Override
protected TransitionDrawable doInBackground(Void... params) {
Bitmap bitmap = Utils.scaleDown(R.drawable.background, Utils.screenWidth(), Utils.screenHeight());
Bitmap backgroundImage = Themes.getBackgroundImage(mSelectedTheme);
backgroundImage = Utils.crop(backgroundImage, Utils.screenHeight(), Utils.screenWidth());
Drawable backgrounds[] = new Drawable[2];
backgrounds[0] = new BitmapDrawable(Shared.context.getResources(), bitmap);
backgrounds[1] = new BitmapDrawable(Shared.context.getResources(), backgroundImage);
TransitionDrawable crossfader = new TransitionDrawable(backgrounds);
return crossfader;
}
@Override
protected void onPostExecute(TransitionDrawable result) {
super.onPostExecute(result);
mBackgroundImage.setImageDrawable(result);
result.startTransition(2000);
}
};
task.execute();
}
@Override
public void onEvent(DifficultySelectedEvent event) {
mFlippedId = -1;
mPlayingGame = new Game();
mPlayingGame.boardConfiguration = new BoardConfiguration(event.difficulty);
mPlayingGame.theme = mSelectedTheme;
mToFlip = mPlayingGame.boardConfiguration.numTiles;
// arrange board
arrangeBoard();
// start the screen
mScreenController.openScreen(Screen.GAME);
}
private void arrangeBoard() {
BoardConfiguration boardConfiguration = mPlayingGame.boardConfiguration;
BoardArrangment boardArrangment = new BoardArrangment();
// build pairs
// result {0,1,2,...n} // n-number of tiles
List<Integer> ids = new ArrayList<Integer>();
for (int i = 0; i < boardConfiguration.numTiles; i++) {
ids.add(i);
}
// shuffle
// result {4,10,2,39,...}
Collections.shuffle(ids);
// place the board
List<String> tileImageUrls = mPlayingGame.theme.tileImageUrls;
Collections.shuffle(tileImageUrls);
boardArrangment.pairs = new HashMap<Integer, Integer>();
boardArrangment.tileUrls = new HashMap<Integer, String>();
int j = 0;
for (int i = 0; i < ids.size(); i++) {
if (i + 1 < ids.size()) {
// {4,10}, {2,39}, ...
boardArrangment.pairs.put(ids.get(i), ids.get(i + 1));
// {10,4}, {39,2}, ...
boardArrangment.pairs.put(ids.get(i + 1), ids.get(i));
boardArrangment.tileUrls.put(ids.get(i), tileImageUrls.get(j));
boardArrangment.tileUrls.put(ids.get(i + 1), tileImageUrls.get(j));
i++;
j++;
}
}
mPlayingGame.boardArrangment = boardArrangment;
}
@Override
public void onEvent(FlipCardEvent event) {
// Log.i("my_tag", "Flip: " + event.id);
int id = event.id;
if (mFlippedId == -1) {
mFlippedId = id;
// Log.i("my_tag", "Flip: mFlippedId: " + event.id);
} else {
if (mPlayingGame.boardArrangment.isPair(mFlippedId, id)) {
// Log.i("my_tag", "Flip: is pair: " + mFlippedId + ", " + id);
// send event - hide id1, id2
Shared.eventBus.notify(new HidePairCardsEvent(mFlippedId, id), 1000);
// play music
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
Music.playCorrent();
}
}, 1000);
mToFlip -= 2;
if (mToFlip == 0) {
int passedSeconds = (int) (Clock.getInstance().getPassedTime() / 1000);
Clock.getInstance().pause();
int totalTime = mPlayingGame.boardConfiguration.time;
GameState gameState = new GameState();
mPlayingGame.gameState = gameState;
// remained seconds
gameState.remainedSeconds = totalTime - passedSeconds;
gameState.passedSeconds = passedSeconds;
// calc stars
if (passedSeconds <= totalTime / 2) {
gameState.achievedStars = 3;
} else if (passedSeconds <= totalTime - totalTime / 5) {
gameState.achievedStars = 2;
} else if (passedSeconds < totalTime) {
gameState.achievedStars = 1;
} else {
gameState.achievedStars = 0;
}
// calc score
gameState.achievedScore = mPlayingGame.boardConfiguration.difficulty * gameState.remainedSeconds * mPlayingGame.theme.id;
// save to memory
Memory.save(mPlayingGame.theme.id, mPlayingGame.boardConfiguration.difficulty, gameState.achievedStars);
Memory.saveTime(mPlayingGame.theme.id,mPlayingGame.boardConfiguration.difficulty,gameState.passedSeconds);
Shared.eventBus.notify(new GameWonEvent(gameState), 1200);
}
} else {
// Log.i("my_tag", "Flip: all down");
// send event - flip all down
Shared.eventBus.notify(new FlipDownCardsEvent(), 1000);
}
mFlippedId = -1;
// Log.i("my_tag", "Flip: mFlippedId: " + mFlippedId);
}
}
public Game getActiveGame() {
return mPlayingGame;
}
public Theme getSelectedTheme() {
return mSelectedTheme;
}
public void setBackgroundImageView(ImageView backgroundImage) {
mBackgroundImage = backgroundImage;
}
} |
package com.snatik.matches.themes;
import android.graphics.Bitmap;
import com.obosapps.matches.common.Shared;
import com.obosapps.matches.utils.Utils;
import java.util.ArrayList;
public class Themes {
public static String URI_DRAWABLE = "drawable:
public static Theme createAnimalsTheme() {
Theme theme = new Theme();
theme.id = 1;
theme.name = "Animals";
theme.backgroundImageUrl = URI_DRAWABLE + "back_animals";
theme.tileImageUrls = new ArrayList<String>();
// 40 drawables
for (int i = 1; i <= 28; i++) {
theme.tileImageUrls.add(URI_DRAWABLE + String.format("animals_%d", i));
}
return theme;
}
public static Theme createMosterTheme() {
Theme theme = new Theme();
theme.id = 2;
theme.name = "Mosters";
theme.backgroundImageUrl = URI_DRAWABLE + "back_horror";
theme.tileImageUrls = new ArrayList<String>();
// 40 drawables
for (int i = 1; i <= 40; i++) {
theme.tileImageUrls.add(URI_DRAWABLE + String.format("mosters_%d", i));
}
return theme;
}
public static Theme createEmojiTheme() {
Theme theme = new Theme();
theme.id = 2;
theme.name = "Emoji";
theme.backgroundImageUrl = URI_DRAWABLE + "background";
theme.tileImageUrls = new ArrayList<String>();
// 40 drawables
for (int i = 1; i <= 40; i++) {
theme.tileImageUrls.add(URI_DRAWABLE + String.format("emoji_%d", i));
}
return theme;
}
public static Bitmap getBackgroundImage(Theme theme) {
String drawableResourceName = theme.backgroundImageUrl.substring(Themes.URI_DRAWABLE.length());
int drawableResourceId = Shared.context.getResources().getIdentifier(drawableResourceName, "drawable", Shared.context.getPackageName());
Bitmap bitmap = Utils.scaleDown(drawableResourceId, Utils.screenWidth(), Utils.screenHeight());
return bitmap;
}
} |
package cz.tmapy.android.trex;
import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.location.Location;
import android.os.Bundle;
import android.os.PowerManager;
import android.preference.PreferenceManager;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.WindowManager;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import java.text.SimpleDateFormat;
import cz.tmapy.android.trex.update.Updater;
public class MainScreen extends ActionBarActivity {
private static final String TAG = "MainScreen";
private String mTargetServerURL;
private String mDeviceId;
private Boolean mKeepScreenOn = false;
private PowerManager.WakeLock mWakeLock;
//members for state saving
private String mLastLocationTime;
private String mLastLocationLat;
private String mLastLocationLon;
private String mLastLocationAlt;
private String mLastLocationSpeed;
private String mLastLocationBearing;
private String mLastServerResponse;
private final String STATE_LAST_LOCATION_TIME = "lastLocationTime";
private final String STATE_LAST_LOCATION_LAT = "lastLocationLast";
private final String STATE_LAST_LOCATION_LON = "lastLocationLon";
private final String STATE_LAST_LOCATION_ALT = "lastLocationAlt";
private final String STATE_LAST_LOCATION_SPEED = "lastLocationSpeed";
private final String STATE_LAST_LOCATION_BEARING = "lastLocationBearing";
private final String STATE_LAST_SERVER_RESPONSE = "lastServerResponse";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_screen);
final ToggleButton toggle = (ToggleButton) findViewById(R.id.toggle_start);
//sets toggle state before listener is attached
toggle.setChecked(getIntent().getBooleanExtra(Constants.EXTRAS_LOCALIZATION_IS_RUNNING, false));
toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
if (!startSending()) //cancel toggle switch when service' start is not successful
{
toggle.setChecked(false);
}
} else {
stopSending();
}
}
});
//Registrace broadcastreceiveru komunikaci se sluzbou (musi byt tady, aby fungoval i po nove inicializaci aplikace z notifikace
// The filter's action is BROADCAST_ACTION
IntentFilter mIntentFilter = new IntentFilter(Constants.LOCATION_BROADCAST);
// Instantiates a new mPositionReceiver
NewPositionReceiver mPositionReceiver = new NewPositionReceiver();
// Registers the mPositionReceiver and its intent filters
LocalBroadcastManager.getInstance(this).registerReceiver(mPositionReceiver, mIntentFilter);
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
mDeviceId = sharedPref.getString("pref_id", "");
mTargetServerURL = sharedPref.getString("pref_targetUrl", "");
mKeepScreenOn = sharedPref.getBoolean("pref_screen_on", false);
//if this is not orientation change (saved bundle doesn't exists) check for update
if (savedInstanceState == null && sharedPref.getBoolean("pref_check4update", true))
new Updater(this).execute();
//ACRA.getErrorReporter().putCustomData("myKey", "myValue");
//ACRA.getErrorReporter().handleException(new Exception("Test exception"));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main_screen, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
Intent intent = new Intent(this, Settings.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Start localizing and sending
*/
public Boolean startSending() {
if (!mTargetServerURL.isEmpty()) {
if (!mDeviceId.isEmpty()) {
if (!isServiceRunning(BackgroundLocationService.class)) {
//Keep CPU on
PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
mWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
"TRexWakelockTag");
mWakeLock.acquire();
if (mKeepScreenOn)
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
//Nastartovani sluzby
ComponentName comp = new ComponentName(getApplicationContext().getPackageName(), BackgroundLocationService.class.getName());
ComponentName service = getApplicationContext().startService(new Intent().setComponent(comp));
if (null == service) {
// something really wrong here
Toast.makeText(this, R.string.localiz_could_not_start, Toast.LENGTH_SHORT).show();
if (Constants.LOG_BASIC)
Log.e(TAG, "Could not start localization service " + comp.toString());
return false;
} else
return true;
} else {
Toast.makeText(this, R.string.localiz_run, Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(this, "Set device identifier", Toast.LENGTH_SHORT).show();
if (Constants.LOG_BASIC) Log.e(TAG, "Device identifier is not setted");
}
} else {
Toast.makeText(this, "Set target server URL", Toast.LENGTH_SHORT).show();
if (Constants.LOG_BASIC) Log.e(TAG, "Target server URL is not setted");
}
return false;
}
/**
* Switch off sending
*/
public void stopSending() {
if (isServiceRunning(BackgroundLocationService.class)) {
ComponentName comp = new ComponentName(getApplicationContext().getPackageName(), BackgroundLocationService.class.getName());
getApplicationContext().stopService(new Intent().setComponent(comp));
TextView dateText = (TextView) findViewById(R.id.text_position_date);
dateText.setText(null);
TextView latText = (TextView) findViewById(R.id.text_position_lat);
latText.setText(null);
TextView lonText = (TextView) findViewById(R.id.text_position_lon);
lonText.setText(null);
TextView altText = (TextView) findViewById(R.id.text_position_alt);
altText.setText(null);
TextView speedText = (TextView) findViewById(R.id.text_position_speed);
speedText.setText(null);
TextView speedBearing = (TextView) findViewById(R.id.text_position_bearing);
speedBearing.setText(null);
TextView respText = (TextView) findViewById(R.id.text_http_response);
respText.setText(null);
//remove flag, if any
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
if (mWakeLock != null) {
mWakeLock.release();
mWakeLock = null;
}
} else
Toast.makeText(this, R.string.localiz_not_run, Toast.LENGTH_SHORT).show();
}
private boolean isServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
/**
* This class uses the BroadcastReceiver framework to detect and handle new postition messages from
* the service
*/
private class NewPositionReceiver extends BroadcastReceiver {
// prevents instantiation by other packages.
private NewPositionReceiver() {
}
/**
* This method is called by the system when a broadcast Intent is matched by this class'
* intent filters
*
* @param context
* @param intent
*/
@Override
public void onReceive(Context context, Intent intent) {
Location lastLocation = (Location) intent.getExtras().get(Constants.EXTRAS_POSITION_DATA);
mLastServerResponse = intent.getStringExtra(Constants.EXTRAS_SERVER_RESPONSE);
if (lastLocation != null || mLastServerResponse != null) {
//2014-06-28T15:07:59
mLastLocationTime = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").format(lastLocation.getTime());
mLastLocationLat = Double.toString(lastLocation.getLatitude());
mLastLocationLon = Double.toString(lastLocation.getLongitude());
mLastLocationAlt = String.valueOf(lastLocation.getAltitude());
mLastLocationSpeed = String.valueOf(lastLocation.getSpeed());
mLastLocationBearing = String.valueOf(lastLocation.getBearing());
UpdateGUI();
}
}
}
private void UpdateGUI() {
TextView dateText = (TextView) findViewById(R.id.text_position_date);
dateText.setText(mLastLocationTime);
TextView latText = (TextView) findViewById(R.id.text_position_lat);
latText.setText(mLastLocationLat);
TextView lonText = (TextView) findViewById(R.id.text_position_lon);
lonText.setText(mLastLocationLon);
TextView altText = (TextView) findViewById(R.id.text_position_alt);
altText.setText(mLastLocationAlt);
TextView speedText = (TextView) findViewById(R.id.text_position_speed);
speedText.setText(mLastLocationSpeed);
TextView speedBearing = (TextView) findViewById(R.id.text_position_bearing);
speedBearing.setText(mLastLocationBearing);
TextView httpRespText = (TextView) findViewById(R.id.text_http_response);
httpRespText.setText(mLastServerResponse);
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
// Save the user's current state
savedInstanceState.putString(STATE_LAST_LOCATION_TIME, mLastLocationTime);
savedInstanceState.putString(STATE_LAST_LOCATION_LAT, mLastLocationLat);
savedInstanceState.putString(STATE_LAST_LOCATION_LON, mLastLocationLon);
savedInstanceState.putString(STATE_LAST_LOCATION_ALT, mLastLocationAlt);
savedInstanceState.putString(STATE_LAST_LOCATION_SPEED, mLastLocationSpeed);
savedInstanceState.putString(STATE_LAST_LOCATION_BEARING, mLastLocationBearing);
savedInstanceState.putString(STATE_LAST_SERVER_RESPONSE, mLastServerResponse);
}
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// Restore state members from saved instance
mLastLocationTime = savedInstanceState.getString(STATE_LAST_LOCATION_TIME);
mLastLocationLat = savedInstanceState.getString(STATE_LAST_LOCATION_LAT);
mLastLocationLon = savedInstanceState.getString(STATE_LAST_LOCATION_LON);
mLastLocationAlt = savedInstanceState.getString(STATE_LAST_LOCATION_ALT);
mLastLocationSpeed = savedInstanceState.getString(STATE_LAST_LOCATION_SPEED);
mLastLocationBearing = savedInstanceState.getString(STATE_LAST_LOCATION_BEARING);
mLastServerResponse = savedInstanceState.getString(STATE_LAST_SERVER_RESPONSE);
UpdateGUI();
}
} |
package de.htwdd.htwdresden;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Context;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import de.htwdd.htwdresden.interfaces.INavigation;
public class MainActivity extends AppCompatActivity implements INavigation {
private DrawerLayout mDrawerLayout;
private MenuItem mPreviousMenuItem;
private ActionBarDrawerToggle mDrawerToggle;
private ActionBar actionBar;
private NavigationView.OnNavigationItemSelectedListener onNavigationItemSelectedListener = new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Makriere im NavigationDrawer
setNavigationItem(item);
selectFragment(item.getItemId());
return false;
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.my_awesome_toolbar);
setSupportActionBar(toolbar);
actionBar = getSupportActionBar();
assert actionBar != null;
actionBar.setDisplayHomeAsUpEnabled(true);
// Hole Views
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
NavigationView mNavigationView = (NavigationView) findViewById(R.id.navigation_view);
// Actionbar Titel anpassen
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, 0, 0) {
public void onDrawerClosed(View view) {
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
public void onDrawerOpened(View drawerView) {
if (getCurrentFocus() != null && getCurrentFocus() instanceof EditText) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
setupDrawerContent(mNavigationView);
mDrawerLayout.setDrawerListener(mDrawerToggle);
// Setze Start-Fragment
if (savedInstanceState == null) {
onNavigationItemSelectedListener.onNavigationItemSelected(mNavigationView.getMenu().findItem(R.id.navigation_overview));
selectFragment(R.id.navigation_overview);
mPreviousMenuItem = mNavigationView.getMenu().findItem(R.id.navigation_overview);
mPreviousMenuItem.setChecked(true);
}
}
private void setupDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(onNavigationItemSelectedListener);
}
private void selectFragment(final int position) {
final FragmentManager fragmentManager = getFragmentManager();
fragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Fragment fragment;
String tag = null;
switch (position) {
case R.id.navigation_overview:
fragment = new Fragment();
tag = "overview";
break;
case R.id.navigation_mensa:
fragment = new MensaFragment();
break;
case R.id.navigation_timetable:
fragment = new TimetableFragment();
break;
case R.id.navigation_room_timetable:
fragment = new RoomTimetableFragment();
break;
case R.id.navigation_exams:
fragment = new ExamsFragment();
break;
case R.id.navigation_settings:
fragment = new SettingsFragment();
break;
case R.id.navigation_about:
fragment = new AboutFragment();
break;
case R.id.navigation_uni_administration:
fragment = new ManagementFragment();
break;
default:
fragment = new Fragment();
break;
}
// Fragment ersetzen
fragmentManager.beginTransaction().replace(R.id.activity_main_FrameLayout, fragment, tag).commitAllowingStateLoss();
}
}, 250);
// NavigationDrawer schliesen
mDrawerLayout.closeDrawers();
}
private void setNavigationItem(final MenuItem item) {
// Markiere aktuelles Feld
if (mPreviousMenuItem != null) {
mPreviousMenuItem.setChecked(false);
}
mPreviousMenuItem = item;
if (item != null)
item.setChecked(true);
}
@Override
public void onBackPressed() {
FragmentManager fragmentManager = getFragmentManager();
if (fragmentManager.getBackStackEntryCount() == 0)
if (fragmentManager.findFragmentByTag("overview") != null)
finish();
else {
NavigationView mNavigationView = (NavigationView) findViewById(R.id.navigation_view);
onNavigationItemSelectedListener.onNavigationItemSelected(mNavigationView.getMenu().findItem(R.id.navigation_overview));
}
else fragmentManager.popBackStack();
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
mDrawerToggle.onConfigurationChanged(newConfig);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// The action bar home/up action should open or close the drawer.
// ActionBarDrawerToggle will take care of this.
return mDrawerToggle.onOptionsItemSelected(item);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
if (mPreviousMenuItem != null)
outState.putInt("mPreviousMenuItem", mPreviousMenuItem.getItemId());
super.onSaveInstanceState(outState);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
if (savedInstanceState != null)
if (savedInstanceState.containsKey("mPreviousMenuItem")) {
NavigationView mNavigationView = (NavigationView) findViewById(R.id.navigation_view);
mPreviousMenuItem = mNavigationView.getMenu().findItem(R.id.navigation_overview);
mPreviousMenuItem.setChecked(false);
mPreviousMenuItem = mNavigationView.getMenu().findItem(savedInstanceState.getInt("mPreviousMenuItem"));
mPreviousMenuItem.setChecked(true);
}
}
@Override
public void setTitle(final String title) {
if (title == null || title.isEmpty())
actionBar.setTitle(R.string.app_name);
else actionBar.setTitle(title);
}
@Override
public void setNavigationItem(int item) {
NavigationView mNavigationView = (NavigationView) findViewById(R.id.navigation_view);
setNavigationItem(mNavigationView.getMenu().findItem(item));
}
} |
package net.privacylayer.app;
import android.util.Base64;
import java.io.UnsupportedEncodingException;
import java.security.Key;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.Random;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class AESPlatform {
// AES-GCM parameters
public static final int DEFAULT_AES_KEY_SIZE = 128; // in bits
public static final int GCM_NONCE_LENGTH = 12; // in bytes
public static final int GCM_TAG_LENGTH = 16; // in bytes
public static AESMessage encrypt(String inputString, String key) throws Exception {
return encrypt(inputString, key, DEFAULT_AES_KEY_SIZE);
}
public static AESMessage encrypt(String inputString, String keyString, int keySize) throws Exception {
byte[] input = inputString.getBytes("UTF-8");
final byte[] nonce = new byte[GCM_NONCE_LENGTH];
Random random = new Random();
random.nextBytes(nonce);
byte[] encrypted = operate(Cipher.ENCRYPT_MODE, input, keyString, keySize, nonce);
return new AESMessage(encrypted, nonce);
}
public static String decrypt(AESMessage message, String keyString) throws Exception {
return decrypt(message, keyString, DEFAULT_AES_KEY_SIZE);
}
public static String decrypt(AESMessage message, String keyString, int keySize) throws Exception {
byte[] decrypted = operate(Cipher.DECRYPT_MODE, message.content, keyString, keySize, message.nonce);
return new String(decrypted, "UTF-8");
}
private static byte[] operate(int mode, byte[] input, String keyString, int keySize, byte[] nonce)
throws Exception {
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(keySize);
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding", "BC");
byte[] key = keyString.getBytes("UTF-8");
MessageDigest sha = MessageDigest.getInstance("SHA-1");
key = sha.digest(key);
key = Arrays.copyOf(key, 16); // use only first 128 bit
Key AESkey = new SecretKeySpec(key, "AES");
cipher.init(mode, AESkey, new IvParameterSpec(nonce));
/*
Todo: add any additional authenticated data
byte[] aad = "Whatever I like".getBytes("UTF-8");
cipher.updateAAD(aad);
*/
return cipher.doFinal(input);
}
// Example implementation
private static void example() throws Exception {
AESMessage encrypted = AESPlatform.encrypt("We Ichi!", ":3");
System.out.println(encrypted.toString());
String decrypted = AESPlatform.decrypt(encrypted, ":3");
System.out.println(decrypted);
}
}
class AESMessage {
byte[] content;
byte[] nonce;
public AESMessage(byte[] in_content, byte[] in_nonce) {
content = in_content;
nonce = in_nonce;
}
public AESMessage(String input) throws UnsupportedEncodingException {
String[] parts = input.split(":");
content = parts[0].getBytes("UTF-8");
nonce = parts[1].getBytes("UTF-8");
}
@Override
public String toString() {
return new String(Base64.encode(content, Base64.DEFAULT)) + ":"
+ new String(Base64.encode(nonce, Base64.DEFAULT));
}
} |
package org.commcare.entity;
import java.util.Vector;
import org.commcare.suite.model.Detail;
import org.commcare.suite.model.Entry;
import org.commcare.suite.model.Text;
import org.javarosa.core.model.instance.FormInstance;
import org.javarosa.core.services.locale.Localization;
import org.javarosa.core.services.storage.EntityFilter;
import org.javarosa.core.services.storage.Persistable;
import org.javarosa.entity.model.Entity;
import org.javarosa.entity.util.StackedEntityFilter;
/**
* @author ctsims
*
*/
public class CommCareEntity<E extends Persistable> extends Entity<E> {
Entry e;
Detail shortDetail;
Detail longDetail;
FormInstanceLoader<E> loader;
String[] shortText;
public CommCareEntity(Entry e, Detail shortDetail, Detail longDetail, FormInstanceLoader<E> loader) {
this.e = e;
this.shortDetail = shortDetail;
this.longDetail = longDetail;
this.loader = loader;
}
/* (non-Javadoc)
* @see org.javarosa.entity.model.Entity#entityType()
*/
public String entityType() {
return shortDetail.getTitle().evaluate();
}
/* (non-Javadoc)
* @see org.javarosa.entity.model.Entity#factory()
*/
public Entity<E> factory() {
return new CommCareEntity<E>(e,shortDetail,longDetail, loader);
}
/* (non-Javadoc)
* @see org.javarosa.entity.model.Entity#getHeaders(boolean)
*/
public String[] getHeaders(boolean detailed) {
Text[] text;
if(!detailed) {
text = shortDetail.getHeaders();
} else{
text = longDetail.getHeaders();
}
String[] output = new String[text.length];
for(int i = 0 ; i < output.length ; ++i) {
output[i] = text[i].evaluate();
}
return output;
}
/* (non-Javadoc)
* @see org.javarosa.patient.select.activity.IEntity#matchID(java.lang.String)
*/
public boolean match (String key) {
key = key.toLowerCase();
String[] fields = this.getShortFields();
for(int i = 0; i < fields.length; ++i) {
//Skip sorting by this key if it's not a normal string
if("image".equals(shortDetail.getTemplateForms()[i])) {
continue;
}
if(fields[i].toLowerCase().startsWith(key)) {
return true;
}
}
return false;
}
/*
* (non-Javadoc)
* @see org.javarosa.entity.model.Entity#getForms(boolean)
*/
public String[] getForms(boolean header) {
return header ? shortDetail.getHeaderForms() : shortDetail.getTemplateForms();
}
/* (non-Javadoc)
* @see org.javarosa.entity.model.Entity#getLongFields(org.javarosa.core.services.storage.Persistable)
*/
public String[] getLongFields(E e) {
loader.prepare(e);
FormInstance specificInstance = loader.loadInstance(longDetail.getInstance());
Text[] text = longDetail.getTemplates();
String[] output = new String[text.length];
for(int i = 0 ; i < output.length ; ++i) {
output[i] = text[i].evaluate(specificInstance, null);
}
return output;
}
/* (non-Javadoc)
* @see org.javarosa.entity.model.Entity#getShortFields()
*/
public String[] getShortFields() {
return shortText;
}
public int[] getStyleHints (boolean header) {
if(header) {
return shortDetail.getHeaderSizeHints();
} else {
return shortDetail.getTemplateSizeHints();
}
}
/* (non-Javadoc)
* @see org.javarosa.entity.model.Entity#loadEntity(org.javarosa.core.services.storage.Persistable)
*/
protected void loadEntity(E entity) {
loader.prepare(entity);
FormInstance instance = loader.loadInstance(shortDetail.getInstance());
loadShortText(instance);
}
public EntityFilter<? super E> getFilter () {
return new StackedEntityFilter<E>(loader.resolveFilter(shortDetail.getFilter(), shortDetail.getInstance()), new InstanceEntityFilter<E>(loader, shortDetail.getFilter(), shortDetail.getInstance()));
}
private void loadShortText(FormInstance instance) {
Text[] text = shortDetail.getTemplates();
shortText = new String[text.length];
for(int i = 0 ; i < shortText.length ; ++i) {
shortText[i] = text[i].evaluate(instance, null);
}
}
/*
* (non-Javadoc)
* @see org.javarosa.entity.model.Entity#getSortFields()
*/
public String[] getSortFields () {
String[] names = getSortFieldNames();
String[] ret = new String[names.length];
ret[0] = "DEFAULT";
for(int i = 1 ; i < ret.length ; ++i ) {
ret[i] = String.valueOf(i);
}
return ret;
}
/*
* (non-Javadoc)
* @see org.javarosa.entity.model.Entity#getSortFieldNames()
*/
public String[] getSortFieldNames () {
Vector<String> fields = new Vector<String>();
fields.addElement(Localization.get("case.id"));
for(String s : getHeaders(false)) {
if(s == null || "".equals(s)) {
continue;
}
fields.addElement(s);
}
String[] ret = new String[fields.size()];
for(int i = 0 ; i < ret.length ; ++i) {
ret[i] = fields.elementAt(i);
}
return ret;
}
/*
* (non-Javadoc)
* @see org.javarosa.entity.model.Entity#getSortKey(java.lang.String)
*/
public Object getSortKey (String fieldKey) {
if (fieldKey.equals("DEFAULT")) {
return new Integer(this.getRecordID());
} else {
try{
return getShortFields()[Integer.valueOf(fieldKey).intValue() - 1];
} catch(NumberFormatException nfe) {
nfe.printStackTrace();
throw new RuntimeException("Invalid sort key in CommCare Entity: " + fieldKey);
}
}
}
} |
package verification.platu.logicAnalysis;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.Stack;
import javax.swing.JOptionPane;
import lpn.parser.Abstraction;
import lpn.parser.ExprTree;
import lpn.parser.LhpnFile;
import lpn.parser.Place;
import lpn.parser.Transition;
import lpn.parser.LpnDecomposition.LpnProcess;
import main.Gui;
import verification.platu.MDD.MDT;
import verification.platu.MDD.Mdd;
import verification.platu.MDD.mddNode;
import verification.platu.common.IndexObjMap;
import verification.platu.lpn.LPNTranRelation;
import verification.platu.lpn.LpnTranList;
import verification.platu.main.Options;
import verification.platu.partialOrders.DependentSet;
import verification.platu.partialOrders.DependentSetComparator;
import verification.platu.partialOrders.LpnTransitionPair;
import verification.platu.partialOrders.StaticSets;
import verification.platu.project.PrjState;
import verification.platu.stategraph.State;
import verification.platu.stategraph.StateGraph;
import verification.timed_state_exploration.zoneProject.EventSet;
import verification.timed_state_exploration.zoneProject.TimedPrjState;
import verification.timed_state_exploration.zoneProject.StateSet;
public class Analysis {
private LinkedList<Transition> traceCex;
protected Mdd mddMgr = null;
private HashMap<LpnTransitionPair, HashSet<LpnTransitionPair>> cachedNecessarySets = new HashMap<LpnTransitionPair, HashSet<LpnTransitionPair>>();
private String PORdebugFileName;
private FileWriter PORdebugFileStream;
private BufferedWriter PORdebugBufferedWriter;
public Analysis(StateGraph[] lpnList, State[] initStateArray, LPNTranRelation lpnTranRelation, String method) {
traceCex = new LinkedList<Transition>();
mddMgr = new Mdd(lpnList.length);
if (method.equals("dfs")) {
//if (Options.getPOR().equals("off")) {
//this.search_dfs(lpnList, initStateArray);
//this.search_dfs_mdd_1(lpnList, initStateArray);
//this.search_dfs_mdd_2(lpnList, initStateArray);
//else
// this.search_dfs_por(lpnList, initStateArray, lpnTranRelation, "state");
}
else if (method.equals("bfs")==true)
this.search_bfs(lpnList, initStateArray);
else if (method == "dfs_noDisabling")
//this.search_dfs_noDisabling(lpnList, initStateArray);
this.search_dfs_noDisabling_fireOrder(lpnList, initStateArray);
}
/**
* This constructor performs dfs.
* @param lpnList
*/
public Analysis(StateGraph[] lpnList){
traceCex = new LinkedList<Transition>();
mddMgr = new Mdd(lpnList.length);
if (Options.getDebugMode()) {
PORdebugFileName = Options.getPrjSgPath() + Options.getLogName() + "_" + Options.getPOR() + "_"
+ Options.getCycleClosingMthd() + "_" + Options.getCycleClosingAmpleMethd() + ".dbg";
try {
PORdebugFileStream = new FileWriter(PORdebugFileName);
} catch (IOException e) {
e.printStackTrace();
}
PORdebugBufferedWriter = new BufferedWriter(PORdebugFileStream);
}
// if (method.equals("dfs")) {
// //if (Options.getPOR().equals("off")) {
// this.search_dfs(lpnList, initStateArray, applyPOR);
// //this.search_dfs_mdd_1(lpnList, initStateArray);
// //this.search_dfs_mdd_2(lpnList, initStateArray);
// //else
// // this.search_dfs_por(lpnList, initStateArray, lpnTranRelation, "state");
// else if (method.equals("bfs")==true)
// this.search_bfs(lpnList, initStateArray);
// else if (method == "dfs_noDisabling")
// //this.search_dfs_noDisabling(lpnList, initStateArray);
// this.search_dfs_noDisabling_fireOrder(lpnList, initStateArray);
}
/**
* Recursively find all reachable project states.
*/
int iterations = 0;
int stack_depth = 0;
int max_stack_depth = 0;
public void search_recursive(final StateGraph[] lpnList,
final State[] curPrjState,
final ArrayList<LinkedList<Transition>> enabledList,
HashSet<PrjState> stateTrace) {
int lpnCnt = lpnList.length;
HashSet<PrjState> prjStateSet = new HashSet<PrjState>();
stack_depth++;
if (stack_depth > max_stack_depth)
max_stack_depth = stack_depth;
iterations++;
if (iterations % 50000 == 0)
System.out.println("iterations: " + iterations
+ ", # of prjStates found: " + prjStateSet.size()
+ ", max_stack_depth: " + max_stack_depth);
for (int index = 0; index < lpnCnt; index++) {
LinkedList<Transition> curEnabledSet = enabledList.get(index);
if (curEnabledSet == null)
continue;
for (Transition firedTran : curEnabledSet) {
// while(curEnabledSet.size() != 0) {
// LPNTran firedTran = curEnabledSet.removeFirst();
// TODO: (check) Not sure if lpnList[index] is correct
State[] nextStateArray = lpnList[index].fire(lpnList, curPrjState, firedTran);
// Add nextPrjState into prjStateSet
// If nextPrjState has been traversed before, skip to the next
// enabled transition.
PrjState nextPrjState = new PrjState(nextStateArray);
if (stateTrace.contains(nextPrjState) == true)
;// System.out.println("found a cycle");
if (prjStateSet.add(nextPrjState) == false) {
continue;
}
// Get the list of enabled transition sets, and call
// findsg_recursive.
ArrayList<LinkedList<Transition>> nextEnabledList = new ArrayList<LinkedList<Transition>>();
for (int i = 0; i < lpnCnt; i++) {
if (curPrjState[i] != nextStateArray[i]) {
StateGraph Lpn_tmp = lpnList[i];
nextEnabledList.add(i, Lpn_tmp.getEnabled(nextStateArray[i]));// firedTran,
// enabledList.get(i),
// false));
} else {
nextEnabledList.add(i, enabledList.get(i));
}
}
stateTrace.add(nextPrjState);
search_recursive(lpnList, nextStateArray, nextEnabledList,
stateTrace);
stateTrace.remove(nextPrjState);
}
}
}
/**
* An iterative implement of findsg_recursive().
*
* @param sgList
* @param start
* @param curLocalStateArray
* @param enabledArray
*/
public StateGraph[] search_dfs(final StateGraph[] sgList, final State[] initStateArray) {
System.out.println("---> calling function search_dfs");
double peakUsedMem = 0;
double peakTotalMem = 0;
boolean failure = false;
int tranFiringCnt = 0;
int totalStates = 1;
int numLpns = sgList.length;
//Stack<State[]> stateStack = new Stack<State[]>();
HashSet<PrjState> stateStack = new HashSet<PrjState>();
Stack<LinkedList<Transition>> lpnTranStack = new Stack<LinkedList<Transition>>();
Stack<Integer> curIndexStack = new Stack<Integer>();
//HashSet<PrjState> prjStateSet = new HashSet<PrjState>();
// Set of PrjStates that have been seen before. Set class documentation
// for how it behaves. Timing Change.
StateSet prjStateSet = new StateSet();
PrjState initPrjState;
// Create the appropriate type for the PrjState depending on whether timing is
// being used or not. Timing Change.
if(!Options.getTimingAnalysisFlag()){
// If not doing timing.
initPrjState = new PrjState(initStateArray);
}
else{
// If timing is enabled.
initPrjState = new TimedPrjState(initStateArray);
// Set the initial values of the inequality variables.
//((TimedPrjState) initPrjState).updateInequalityVariables();
}
prjStateSet.add(initPrjState);
PrjState stateStackTop = initPrjState;
if (Options.getDebugMode()) {
// System.out.println("%%%%%%% stateStackTop %%%%%%%%");
// printStateArray(stateStackTop.toStateArray());
}
stateStack.add(stateStackTop);
constructDstLpnList(sgList);
if (Options.getDebugMode()) {
// printDstLpnList(sgList);
}
boolean init = true;
LpnTranList initEnabled;
if(!Options.getTimingAnalysisFlag()){ // Timing Change.
initEnabled = sgList[0].getEnabled(initStateArray[0], init);
}
else
{
// When timing is enabled, it is the project state that will determine
// what is enabled since it contains the zone. This indicates the zeroth zone
// contained in the project and the zeroth LPN to get the transitions from.
initEnabled = ((TimedPrjState) stateStackTop).getPossibleEvents(0, 0);
}
lpnTranStack.push(initEnabled.clone());
curIndexStack.push(0);
init = false;
if (Options.getDebugMode()) {
// System.out.println("call getEnabled on initStateArray at 0: ");
// System.out.println("+++++++ Push trans onto lpnTranStack ++++++++");
// printTransitionSet(initEnabled, "");
}
boolean memExceedsLimit = false;
main_while_loop: while (failure == false && stateStack.size() != 0) {
if (Options.getDebugMode()) {
// System.out.println("$$$$$$$$$$$ loop begins $$$$$$$$$$");
}
long curTotalMem = Runtime.getRuntime().totalMemory();
long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
if (curTotalMem > peakTotalMem)
peakTotalMem = curTotalMem;
if (curUsedMem > peakUsedMem)
peakUsedMem = curUsedMem;
if (stateStack.size() > max_stack_depth)
max_stack_depth = stateStack.size();
iterations++;
if (iterations % 100000 == 0) {
System.out.println("---> #iteration " + iterations
+ "> # LPN transition firings: " + tranFiringCnt
+ ", # of prjStates found: " + totalStates
+ ", stack_depth: " + stateStack.size()
+ " used memory: " + (float) curUsedMem / 1000000
+ " free memory: "
+ (float) Runtime.getRuntime().freeMemory() / 1000000);
}
if (!memExceedsLimit && Options.getMemUpperBoundFlag() && iterations % 100 == 0) {
if (curUsedMem > Options.getMemUpperBound()) {
System.out.println("******* Used memory exceeds memory upper bound (" + (float)Options.getMemUpperBound()/1000000 + "MB) *******");
System.out.println("******* Used memory = " + (float)curUsedMem/1000000 + "MB *******");
memExceedsLimit = true;
}
}
State[] curStateArray = stateStackTop.toStateArray(); //stateStack.peek();
int curIndex = curIndexStack.peek();
LinkedList<Transition> curEnabled = lpnTranStack.peek();
if (failureTranIsEnabled(curEnabled)) {
return null;
}
if (Options.getDebugMode()) {
// printStateArray(curStateArray);
// System.out.println("+++++++ curEnabled trans ++++++++");
// printTransLinkedList(curEnabled);
}
// If all enabled transitions of the current LPN are considered,
// then consider the next LPN
// by increasing the curIndex.
// Otherwise, if all enabled transitions of all LPNs are considered,
// then pop the stacks.
if (curEnabled.size() == 0) {
lpnTranStack.pop();
if (Options.getDebugMode()) {
// System.out.println("+++++++ Pop trans off lpnTranStack ++++++++");
// System.out.println("
// printLpnTranStack(lpnTranStack);
}
curIndexStack.pop();
curIndex++;
while (curIndex < numLpns) {
// System.out.println("call getEnabled on curStateArray at 1: ");
if(!Options.getTimingAnalysisFlag()){ // Timing Change
curEnabled = (sgList[curIndex].getEnabled(curStateArray[curIndex], init)).clone();
}
else{
// Get the enabled transitions from the zone that are associated with
// the current LPN.
curEnabled = ((TimedPrjState) stateStackTop).getPossibleEvents(0, curIndex);
}
if (curEnabled.size() > 0) {
if (Options.getDebugMode()) {
// System.out.println("+++++++ Push trans onto lpnTranStack ++++++++");
// printTransLinkedList(curEnabled);
}
lpnTranStack.push(curEnabled);
curIndexStack.push(curIndex);
if (Options.getDebugMode()) {
//printIntegerStack("curIndexStack after push 1", curIndexStack);
}
break;
}
curIndex++;
}
}
if (curIndex == numLpns) {
// prjStateSet.add(stateStackTop);
if (Options.getDebugMode()) {
// System.out.println("%%%%%%% Remove stateStackTop from stateStack %%%%%%%%");
// printStateArray(stateStackTop.toStateArray());
}
stateStack.remove(stateStackTop);
stateStackTop = stateStackTop.getFather();
continue;
}
Transition firedTran = curEnabled.removeLast();
if (Options.getDebugMode()) {
// System.out.println("
// System.out.println("Fired transition: " + firedTran.getLpn().getLabel() + "(" + firedTran.getName() + ")");
// System.out.println("
}
State[] nextStateArray;
PrjState nextPrjState; // Moved this definition up. Timing Change.
// The next state depends on whether timing is in use or not.
// Timing Change.
if(!Options.getTimingAnalysisFlag()){
// Get the next states from the fire method and define the next project state.
nextStateArray = sgList[curIndex].fire(sgList, curStateArray, firedTran);
nextPrjState = new PrjState(nextStateArray);
}
else{
// Get the next timed state and extract the next un-timed states.
nextPrjState = sgList[curIndex].fire(sgList, stateStackTop,
(EventSet) firedTran);
nextStateArray = nextPrjState.toStateArray();
}
tranFiringCnt++;
// Check if the firedTran causes disabling error or deadlock.
@SuppressWarnings("unchecked")
LinkedList<Transition>[] curEnabledArray = new LinkedList[numLpns];
@SuppressWarnings("unchecked")
LinkedList<Transition>[] nextEnabledArray = new LinkedList[numLpns];
for (int i = 0; i < numLpns; i++) {
StateGraph sg = sgList[i];
LinkedList<Transition> enabledList;
if(!Options.getTimingAnalysisFlag()){ // Timing Change.
enabledList = sg.getEnabled(curStateArray[i], init);
}
else{
// Get the enabled transitions from the Zone for the appropriate
// LPN.
//enabledList = ((TimedPrjState) stateStackTop).getEnabled(i);
enabledList = ((TimedPrjState) stateStackTop).getPossibleEvents(0, i);
}
curEnabledArray[i] = enabledList;
if(!Options.getTimingAnalysisFlag()){ // Timing Change.
enabledList = sg.getEnabled(nextStateArray[i], init);
}
else{
//enabledList = ((TimedPrjState) nextPrjState).getEnabled(i);
enabledList = ((TimedPrjState) nextPrjState).getPossibleEvents(0, i);
}
nextEnabledArray[i] = enabledList;
if (Options.getReportDisablingError()) {
Transition disabledTran = firedTran.disablingError(
curEnabledArray[i], nextEnabledArray[i]);
if (disabledTran != null) {
System.err.println("Disabling Error: "
+ disabledTran.getFullLabel() + " is disabled by "
+ firedTran.getFullLabel());
failure = true;
break main_while_loop;
}
}
}
if(!Options.getTimingAnalysisFlag()){
if (Analysis.deadLock(sgList, nextStateArray) == true) {
System.out.println("*** Verification failed: deadlock.");
failure = true;
break main_while_loop;
}
}
//PrjState nextPrjState = new PrjState(nextStateArray); // Moved earlier. Timing Change.
Boolean existingState = prjStateSet.contains(nextPrjState); //|| stateStack.contains(nextPrjState);
if (existingState == false) {
prjStateSet.add(nextPrjState);
stateStackTop.setChild(nextPrjState);
nextPrjState.setFather(stateStackTop);
if (Options.getOutputSgFlag()) {
if (Options.getDebugMode()) {
// printStateArray(curStateArray);
// printStateArray(nextStateArray);
// System.out.println("stateStackTop: ");
// printStateArray(stateStackTop.toStateArray());
// System.out.println("firedTran = " + firedTran.getName());
// printNextStateMap(stateStackTop.getNextStateMap());
}
stateStackTop.setTranOut(firedTran, nextPrjState);
if (Options.getDebugMode()) {
// printNextStateMap(stateStackTop.getNextStateMap());
}
for (PrjState prjState : prjStateSet) {
if (prjState.equals(stateStackTop)) {
prjState.setTranOut(firedTran, nextPrjState);
if (Options.getDebugMode()) {
System.out.println("***nextStateMap for prjState: ");
printNextStateMap(prjState.getNextStateMap());
}
}
}
}
stateStackTop = nextPrjState;
if (Options.getDebugMode()) {
// System.out.println("%%%%%%% Add global state to stateStack %%%%%%%%");
// printStateArray(stateStackTop.toStateArray());
}
stateStack.add(stateStackTop);
if (Options.getDebugMode()) {
// System.out.println("+++++++ Push trans onto lpnTranStack ++++++++");
// printTransitionSet((LpnTranList) nextEnabledArray[0], "");
}
lpnTranStack.push((LpnTranList) nextEnabledArray[0].clone());
if (Options.getDebugMode()) {
// printLpnTranStack(lpnTranStack);
}
curIndexStack.push(0);
totalStates++;
}
else {
if (Options.getOutputSgFlag()) {
if (Options.getDebugMode()) {
// printStateArray(curStateArray);
// printStateArray(nextStateArray);
}
for (PrjState prjState : prjStateSet) {
if (prjState.equals(nextPrjState)) {
nextPrjState.setNextStateMap((HashMap<Transition, PrjState>) prjState.getNextStateMap().clone());
}
}
if (Options.getDebugMode()) {
// System.out.println("stateStackTop: ");
// printStateArray(stateStackTop.toStateArray());
// System.out.println("firedTran = " + firedTran.getName());
// System.out.println("nextStateMap for stateStackTop before firedTran being added: ");
// printNextStateMap(stateStackTop.getNextStateMap());
}
stateStackTop.setTranOut(firedTran, nextPrjState);
if (Options.getDebugMode()) {
// printNextStateMap(stateStackTop.getNextStateMap());
}
for (PrjState prjState : prjStateSet) {
if (prjState == stateStackTop) {
prjState.setNextStateMap((HashMap<Transition, PrjState>) stateStackTop.getNextStateMap().clone());
if (Options.getDebugMode()) {
// printNextStateMap(prjState.getNextStateMap());
}
}
}
}
}
}
double totalStateCnt = prjStateSet.size();
System.out.println("---> final numbers: # LPN transition firings: " + tranFiringCnt
//+ ", # of prjStates found: " + totalStateCnt
+ ", " + prjStateSet.stateString()
+ ", max_stack_depth: " + max_stack_depth
+ ", peak total memory: " + peakTotalMem / 1000000 + " MB"
+ ", peak used memory: " + peakUsedMem / 1000000 + " MB");
if (Options.getOutputLogFlag())
writePerformanceResultsToLogFile(false, tranFiringCnt, totalStateCnt, peakTotalMem / 1000000, peakUsedMem / 1000000);
if (Options.getOutputSgFlag())
drawGlobalStateGraph(sgList, prjStateSet.toHashSet(), true);
return sgList;
}
private boolean failureTranIsEnabled(LinkedList<Transition> curEnabled) {
boolean failureTranIsEnabled = false;
for (Transition tran : curEnabled) {
if (tran.isFail()) {
JOptionPane.showMessageDialog(Gui.frame,
"Failure transition " + tran.getName() + " is enabled.", "Error",
JOptionPane.ERROR_MESSAGE);
failureTranIsEnabled = true;
break;
}
}
return failureTranIsEnabled;
}
private void drawGlobalStateGraph(StateGraph[] sgList, HashSet<PrjState> prjStateSet, boolean fullSG) {
try {
String fileName = null;
if (fullSG) {
fileName = Options.getPrjSgPath() + "full_sg.dot";
}
else {
fileName = Options.getPrjSgPath() + Options.getPOR().toLowerCase() + "_"
+ Options.getCycleClosingMthd().toLowerCase() + "_"
+ Options.getCycleClosingAmpleMethd().toLowerCase() + "_sg.dot";
}
BufferedWriter out = new BufferedWriter(new FileWriter(fileName));
out.write("digraph G {\n");
for (PrjState curGlobalState : prjStateSet) {
// Build composite current global state.
String curVarNames = "";
String curVarValues = "";
String curMarkings = "";
String curEnabledTrans = "";
String curGlobalStateIndex = "";
HashMap<String, Integer> vars = new HashMap<String, Integer>();
for (State curLocalState : curGlobalState.toStateArray()) {
LhpnFile curLpn = curLocalState.getLpn();
for(int i = 0; i < curLpn.getVarIndexMap().size(); i++) {
//System.out.println(curLpn.getVarIndexMap().getKey(i) + " = " + curLocalState.getVector()[i]);
vars.put(curLpn.getVarIndexMap().getKey(i), curLocalState.getVector()[i]);
}
curMarkings = curMarkings + "," + intArrayToString("markings", curLocalState);
if (!boolArrayToString("enabled trans", curLocalState).equals(""))
curEnabledTrans = curEnabledTrans + "," + boolArrayToString("enabled trans", curLocalState);
curGlobalStateIndex = curGlobalStateIndex + "_" + "S" + curLocalState.getIndex();
}
for (String vName : vars.keySet()) {
Integer vValue = vars.get(vName);
curVarValues = curVarValues + vValue + ", ";
curVarNames = curVarNames + vName + ", ";
}
curVarNames = curVarNames.substring(0, curVarNames.lastIndexOf(","));
curVarValues = curVarValues.substring(0, curVarValues.lastIndexOf(","));
curMarkings = curMarkings.substring(curMarkings.indexOf(",")+1, curMarkings.length());
curEnabledTrans = curEnabledTrans.substring(curEnabledTrans.indexOf(",")+1, curEnabledTrans.length());
curGlobalStateIndex = curGlobalStateIndex.substring(curGlobalStateIndex.indexOf("_")+1, curGlobalStateIndex.length());
out.write("Inits[shape=plaintext, label=\"<" + curVarNames + ">\"]\n");
out.write(curGlobalStateIndex + "[shape=\"ellipse\",label=\"" + curGlobalStateIndex + "\\n<"+curVarValues+">" + "\\n<"+curEnabledTrans+">" + "\\n<"+curMarkings+">" + "\"]\n");
// // Build composite next global states.
HashMap<Transition, PrjState> nextStateMap = curGlobalState.getNextStateMap();
for (Transition outTran : nextStateMap.keySet()) {
PrjState nextGlobalState = nextStateMap.get(outTran);
String nextVarNames = "";
String nextVarValues = "";
String nextMarkings = "";
String nextEnabledTrans = "";
String nextGlobalStateIndex = "";
for (State nextLocalState : nextGlobalState.toStateArray()) {
LhpnFile nextLpn = nextLocalState.getLpn();
for(int i = 0; i < nextLpn.getVarIndexMap().size(); i++) {
vars.put(nextLpn.getVarIndexMap().getKey(i), nextLocalState.getVector()[i]);
}
nextMarkings = nextMarkings + "," + intArrayToString("markings", nextLocalState);
if (!boolArrayToString("enabled trans", nextLocalState).equals(""))
nextEnabledTrans = nextEnabledTrans + "," + boolArrayToString("enabled trans", nextLocalState);
nextGlobalStateIndex = nextGlobalStateIndex + "_" + "S" + nextLocalState.getIndex();
}
for (String vName : vars.keySet()) {
Integer vValue = vars.get(vName);
nextVarValues = nextVarValues + vValue + ", ";
nextVarNames = nextVarNames + vName + ", ";
}
nextVarNames = nextVarNames.substring(0, nextVarNames.lastIndexOf(","));
nextVarValues = nextVarValues.substring(0, nextVarValues.lastIndexOf(","));
nextMarkings = nextMarkings.substring(nextMarkings.indexOf(",")+1, nextMarkings.length());
nextEnabledTrans = nextEnabledTrans.substring(nextEnabledTrans.indexOf(",")+1, nextEnabledTrans.length());
nextGlobalStateIndex = nextGlobalStateIndex.substring(nextGlobalStateIndex.indexOf("_")+1, nextGlobalStateIndex.length());
out.write("Inits[shape=plaintext, label=\"<" + nextVarNames + ">\"]\n");
out.write(nextGlobalStateIndex + "[shape=\"ellipse\",label=\"" + nextGlobalStateIndex + "\\n<"+nextVarValues+">" + "\\n<"+nextEnabledTrans+">" + "\\n<"+nextMarkings+">" + "\"]\n");
String outTranName = outTran.getName();
if (outTran.isFail() && !outTran.isPersistent())
out.write(curGlobalStateIndex + "->" + nextGlobalStateIndex + "[label=\"" + outTranName + "\", fontcolor=red]\n");
else if (!outTran.isFail() && outTran.isPersistent())
out.write(curGlobalStateIndex + "->" + nextGlobalStateIndex + "[label=\"" + outTranName + "\", fontcolor=blue]\n");
else if (outTran.isFail() && outTran.isPersistent())
out.write(curGlobalStateIndex + "->" + nextGlobalStateIndex + "[label=\"" + outTranName + "\", fontcolor=purple]\n");
else
out.write(curGlobalStateIndex + "->" + nextGlobalStateIndex + "[label=\"" + outTranName + "\"]\n");
}
}
out.write("}");
out.close();
}
catch (Exception e) {
e.printStackTrace();
System.err.println("Error producing local state graph as dot file.");
}
}
private void drawDependencyGraphs(LhpnFile[] lpnList,
HashMap<LpnTransitionPair, StaticSets> staticSetsMap) {
String fileName = Options.getPrjSgPath() + "dependencyGraph.dot";
BufferedWriter out;
try {
out = new BufferedWriter(new FileWriter(fileName));
out.write("digraph G {\n");
for (LpnTransitionPair curTran : staticSetsMap.keySet()) {
String curTranStr = lpnList[curTran.getLpnIndex()].getLabel()
+ "_" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()).getName();
out.write(curTranStr + "[shape=\"box\"];");
out.newLine();
}
for (LpnTransitionPair curTran : staticSetsMap.keySet()) {
StaticSets curStaticSets = staticSetsMap.get(curTran);
String curTranStr = lpnList[curTran.getLpnIndex()].getLabel()
+ "_" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()).getName();
for (LpnTransitionPair curTranInDisable : curStaticSets.getOtherTransDisableCurTranSet()) {
String curTranInDisableStr = lpnList[curTranInDisable.getLpnIndex()].getLabel()
+ "_" + lpnList[curTranInDisable.getLpnIndex()].getTransition(curTranInDisable.getTranIndex()).getName();
out.write(curTranInDisableStr + "->" + curTranStr + "[color=\"chocolate\"];");
out.newLine();
}
// for (LpnTransitionPair curTranInDisable : curStaticSets.getCurTranDisableOtherTransSet()) {
// String curTranInDisableStr = lpnList[curTranInDisable.getLpnIndex()].getLabel()
// + "_" + lpnList[curTranInDisable.getLpnIndex()].getTransition(curTranInDisable.getTranIndex()).getName();
// out.write(curTranStr + "->" + curTranInDisableStr + "[color=\"chocolate\"];");
// out.newLine();
// for (LpnTransitionPair curTranInDisable : curStaticSets.getDisableSet()) {
// String curTranInDisableStr = lpnList[curTranInDisable.getLpnIndex()].getLabel()
// + "_" + lpnList[curTranInDisable.getLpnIndex()].getTransition(curTranInDisable.getTranIndex()).getName();
// out.write(curTranStr + "->" + curTranInDisableStr + "[color=\"blue\"];");
// out.newLine();
HashSet<LpnTransitionPair> enableByBringingToken = new HashSet<LpnTransitionPair>();
Transition curTransition = lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex());
for (Place p : curTransition.getPreset()) {
for (Transition presetTran : p.getPreset()) {
int lpnIndex = presetTran.getLpn().getLpnIndex();
enableByBringingToken.add(new LpnTransitionPair(lpnIndex, presetTran.getIndex()));
}
}
for (LpnTransitionPair curTranInCanEnable : enableByBringingToken) {
String curTranInCanEnableStr = lpnList[curTranInCanEnable.getLpnIndex()].getLabel()
+ "_" + lpnList[curTranInCanEnable.getLpnIndex()].getTransition(curTranInCanEnable.getTranIndex()).getName();
//out.write(curTranInCanEnableStr + "->" + curTranStr + "[color=\"mediumaquamarine\"];");
out.write(curTranStr + "->" + curTranInCanEnableStr + "[color=\"mediumaquamarine\"];");
out.newLine();
}
for (HashSet<LpnTransitionPair> canEnableOneConjunctSet : curStaticSets.getOtherTransSetCurTranEnablingTrue()) {
for (LpnTransitionPair curTranInCanEnable : canEnableOneConjunctSet) {
String curTranInCanEnableStr = lpnList[curTranInCanEnable.getLpnIndex()].getLabel()
+ "_" + lpnList[curTranInCanEnable.getLpnIndex()].getTransition(curTranInCanEnable.getTranIndex()).getName();
//out.write(curTranInCanEnableStr + "->" + curTranStr + "[color=\"deepskyblue\"];");
out.write(curTranStr + "->" + curTranInCanEnableStr + "[color=\"deepskyblue\"];");
out.newLine();
}
}
}
out.write("}");
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private String intArrayToString(String type, State curState) {
String arrayStr = "";
if (type.equals("markings")) {
for (int i=0; i< curState.getMarking().length; i++) {
if (curState.getMarking()[i] == 1) {
arrayStr = arrayStr + curState.getLpn().getPlaceList()[i] + ",";
}
// String tranName = curState.getLpn().getAllTransitions()[i].getName();
// if (curState.getTranVector()[i])
// System.out.println(tranName + " " + "Enabled");
// else
// System.out.println(tranName + " " + "Not Enabled");
}
arrayStr = arrayStr.substring(0, arrayStr.lastIndexOf(","));
}
else if (type.equals("vars")) {
for (int i=0; i< curState.getVector().length; i++) {
arrayStr = arrayStr + curState.getVector()[i] + ",";
}
if (arrayStr.contains(","))
arrayStr = arrayStr.substring(0, arrayStr.lastIndexOf(","));
}
return arrayStr;
}
private String boolArrayToString(String type, State curState) {
String arrayStr = "";
if (type.equals("enabled trans")) {
for (int i=0; i< curState.getTranVector().length; i++) {
if (curState.getTranVector()[i]) {
arrayStr = arrayStr + curState.getLpn().getAllTransitions()[i].getName() + ",";
}
}
if (arrayStr != "")
arrayStr = arrayStr.substring(0, arrayStr.lastIndexOf(","));
}
return arrayStr;
}
private void printStateArray(State[] stateArray) {
for (int i=0; i<stateArray.length; i++) {
System.out.print("S" + stateArray[i].getIndex() + "(" + stateArray[i].getLpn().getLabel() +") -> ");
System.out.print("markings: " + intArrayToString("markings", stateArray[i]) + " / ");
System.out.print("enabled trans: " + boolArrayToString("enabled trans", stateArray[i]) + " / ");
System.out.print("var values: " + intArrayToString("vars", stateArray[i]) + " / ");
System.out.print("\n");
}
}
private void printTransLinkedList(LinkedList<Transition> curPop) {
for (int i=0; i< curPop.size(); i++) {
System.out.print(curPop.get(i).getName() + " ");
}
System.out.println("");
}
private void printIntegerStack(String stackName, Stack<Integer> curIndexStack) {
System.out.println("+++++++++" + stackName + "+++++++++");
for (int i=0; i < curIndexStack.size(); i++) {
System.out.println(stackName + "[" + i + "]" + curIndexStack.get(i));
}
System.out.println("
}
private void printDstLpnList(StateGraph[] lpnList) {
System.out.println("++++++ dstLpnList ++++++");
for (int i=0; i<lpnList.length; i++) {
LhpnFile curLPN = lpnList[i].getLpn();
System.out.println("LPN: " + curLPN.getLabel());
Transition[] allTrans = curLPN.getAllTransitions();
for (int j=0; j< allTrans.length; j++) {
System.out.print(allTrans[j].getName() + ": ");
for (int k=0; k< allTrans[j].getDstLpnList().size(); k++) {
System.out.print(allTrans[j].getDstLpnList().get(k).getLabel() + ",");
}
System.out.print("\n");
}
System.out.println("
}
System.out.println("++++++++++++++++++++");
}
private void constructDstLpnList(StateGraph[] lpnList) {
for (int i=0; i<lpnList.length; i++) {
LhpnFile curLPN = lpnList[i].getLpn();
Transition[] allTrans = curLPN.getAllTransitions();
for (int j=0; j<allTrans.length; j++) {
Transition curTran = allTrans[j];
for (int k=0; k<lpnList.length; k++) {
curTran.setDstLpnList(lpnList[k].getLpn());
}
}
}
}
/**
* This method performs first-depth search on an array of LPNs and applies partial order reduction technique with the traceback.
* @param sgList
* @param initStateArray
* @param cycleClosingMthdIndex
* @return
*/
@SuppressWarnings("unchecked")
public StateGraph[] search_dfsPOR(final StateGraph[] sgList, final State[] initStateArray) {
System.out.println("---> calling function search_dfsPOR");
System.out.println("---> " + Options.getPOR());
System.out.println("---> " + Options.getCycleClosingMthd());
System.out.println("---> " + Options.getCycleClosingAmpleMethd());
double peakUsedMem = 0;
double peakTotalMem = 0;
boolean failure = false;
int tranFiringCnt = 0;
int totalStates = 1;
int numLpns = sgList.length;
LhpnFile[] lpnList = new LhpnFile[numLpns];
for (int i=0; i<numLpns; i++) {
lpnList[i] = sgList[i].getLpn();
}
HashSet<PrjState> stateStack = new HashSet<PrjState>();
Stack<LinkedList<Transition>> lpnTranStack = new Stack<LinkedList<Transition>>();
HashSet<PrjState> prjStateSet = new HashSet<PrjState>();
PrjState initPrjState = new PrjState(initStateArray);
prjStateSet.add(initPrjState);
PrjState stateStackTop = initPrjState;
if (Options.getDebugMode()) {
// System.out.println("%%%%%%% stateStackTop %%%%%%%%");
// printStateArray(stateStackTop.toStateArray());
}
stateStack.add(stateStackTop);
constructDstLpnList(sgList);
if (Options.getDebugMode()) {
// printDstLpnList(sgList);
createPORDebugFile();
}
// Find static pieces for POR.
HashMap<Integer, Transition[]> allTransitions = new HashMap<Integer, Transition[]>(lpnList.length);
HashMap<LpnTransitionPair, StaticSets> staticSetsMap = new HashMap<LpnTransitionPair, StaticSets>();
HashMap<Transition, Integer> allProcessTransInOneLpn = new HashMap<Transition, Integer>();
HashMap<Transition, LpnProcess> allTransitionsToLpnProcesses = new HashMap<Transition, LpnProcess>();
for (int lpnIndex=0; lpnIndex<lpnList.length; lpnIndex++) {
allTransitions.put(lpnIndex, lpnList[lpnIndex].getAllTransitions());
Abstraction abs = new Abstraction(lpnList[lpnIndex]);
abs.decomposeLpnIntoProcesses();
allProcessTransInOneLpn = (HashMap<Transition, Integer>)abs.getTransWithProcIDs();
HashMap<Integer, LpnProcess> processMapForOneLpn = new HashMap<Integer, LpnProcess>();
for (Transition curTran: allProcessTransInOneLpn.keySet()) {
Integer procId = allProcessTransInOneLpn.get(curTran);
if (!processMapForOneLpn.containsKey(procId)) {
LpnProcess newProcess = new LpnProcess(procId);
newProcess.addTranToProcess(curTran);
if (curTran.getPreset() != null) {
if (newProcess.getStateMachineFlag()
&& ((curTran.getPreset().length > 1)
|| (curTran.getPostset().length > 1))) {
newProcess.setStateMachineFlag(false);
}
Place[] preset = curTran.getPreset();
for (Place p : preset) {
newProcess.addPlaceToProcess(p);
}
}
processMapForOneLpn.put(procId, newProcess);
allTransitionsToLpnProcesses.put(curTran, newProcess);
}
else {
LpnProcess curProcess = processMapForOneLpn.get(procId);
curProcess.addTranToProcess(curTran);
if (curTran.getPreset() != null) {
if (curProcess.getStateMachineFlag()
&& (curTran.getPreset().length > 1
|| curTran.getPostset().length > 1)) {
curProcess.setStateMachineFlag(false);
}
Place[] preset = curTran.getPreset();
for (Place p : preset) {
curProcess.addPlaceToProcess(p);
}
}
allTransitionsToLpnProcesses.put(curTran, curProcess);
}
}
}
HashMap<LpnTransitionPair, Integer> tranFiringFreq = null;
if (Options.getUseDependentQueue())
tranFiringFreq = new HashMap<LpnTransitionPair, Integer>(allTransitions.keySet().size());
for (int lpnIndex=0; lpnIndex<lpnList.length; lpnIndex++) {
if (Options.getDebugMode()) {
writeStringWithEndOfLineToPORDebugFile("=======LPN = " + lpnList[lpnIndex].getLabel() + "=======");
}
for (Transition curTran: allTransitions.get(lpnIndex)) {
StaticSets curStatic = new StaticSets(curTran, allTransitionsToLpnProcesses);
curStatic.buildCurTranDisableOtherTransSet();
if (Options.getPORdeadlockPreserve())
curStatic.buildOtherTransDisableCurTranSet();
else
curStatic.buildModifyAssignSet();
curStatic.buildOtherTransSetCurTranEnablingTrue();
LpnTransitionPair lpnTranPair = new LpnTransitionPair(lpnIndex,curTran.getIndex());
staticSetsMap.put(lpnTranPair, curStatic);
if (Options.getUseDependentQueue())
tranFiringFreq.put(lpnTranPair, 0);
}
}
if (Options.getDebugMode()) {
writeStaticSetsMapToPORDebugFile(lpnList, staticSetsMap);
}
boolean init = true;
LpnTranList initAmpleTrans = new LpnTranList();
initAmpleTrans = getAmple(initStateArray, null, staticSetsMap, init, tranFiringFreq, sgList, lpnList, stateStack, stateStackTop);
lpnTranStack.push(initAmpleTrans);
init = false;
if (Options.getDebugMode()) {
// System.out.println("+++++++ Push trans onto lpnTranStack @ 1++++++++");
// printTransitionSet(initAmpleTrans, "");
drawDependencyGraphs(lpnList, staticSetsMap);
}
HashSet<LpnTransitionPair> initAmple = new HashSet<LpnTransitionPair>();
for (Transition t: initAmpleTrans) {
initAmple.add(new LpnTransitionPair(t.getLpn().getLpnIndex(), t.getIndex()));
}
updateLocalAmpleTbl(initAmple, sgList, initStateArray);
boolean memExceedsLimit = false;
main_while_loop: while (failure == false && stateStack.size() != 0) {
if (Options.getDebugMode()) {
writeStringWithEndOfLineToPORDebugFile("~~~~~~~~~~~ loop begins ~~~~~~~~~~~");
}
long curTotalMem = Runtime.getRuntime().totalMemory();
long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
if (curTotalMem > peakTotalMem)
peakTotalMem = curTotalMem;
if (curUsedMem > peakUsedMem)
peakUsedMem = curUsedMem;
if (stateStack.size() > max_stack_depth)
max_stack_depth = stateStack.size();
iterations++;
if (iterations % 100000 == 0) {
System.out.println("---> #iteration " + iterations
+ "> # LPN transition firings: " + tranFiringCnt
+ ", # of prjStates found: " + totalStates
+ ", stack_depth: " + stateStack.size()
+ " used memory: " + (float) curUsedMem / 1000000
+ " free memory: "
+ (float) Runtime.getRuntime().freeMemory() / 1000000);
}
if (!memExceedsLimit && Options.getMemUpperBoundFlag() && iterations % 100 == 0) {
if (curUsedMem > Options.getMemUpperBound()) {
System.out.println("******* Used memory exceeds memory upper bound (" + (float)Options.getMemUpperBound()/1000000 + "MB) *******");
System.out.println("******* Used memory = " + (float)curUsedMem/1000000 + "MB *******");
memExceedsLimit = true;
}
}
State[] curStateArray = stateStackTop.toStateArray(); //stateStack.peek();
LinkedList<Transition> curAmpleTrans = lpnTranStack.peek();
if (failureTranIsEnabled(curAmpleTrans)) {
return null;
}
if (curAmpleTrans.size() == 0) {
lpnTranStack.pop();
prjStateSet.add(stateStackTop);
if (Options.getDebugMode()) {
// System.out.println("+++++++ Pop trans off lpnTranStack ++++++++");
// System.out.println("
// printLpnTranStack(lpnTranStack);
//// System.out.println("
//// printStateStack(stateStack);
// System.out.println("
// printPrjStateSet(prjStateSet);
// System.out.println("%%%%%%% Remove stateStackTop from stateStack %%%%%%%%");
}
stateStack.remove(stateStackTop);
stateStackTop = stateStackTop.getFather();
continue;
}
Transition firedTran = curAmpleTrans.removeLast();
if (Options.getDebugMode()) {
writeStringWithEndOfLineToPORDebugFile("
writeStringWithEndOfLineToPORDebugFile("Fired Transition: " + firedTran.getLpn().getLabel() + "(" + firedTran.getName() + ")");
writeStringWithEndOfLineToPORDebugFile("
}
LpnTransitionPair firedLpnTranPair = new LpnTransitionPair(firedTran.getLpn().getLpnIndex(), firedTran.getIndex());
if (Options.getUseDependentQueue()) {
Integer freq = tranFiringFreq.get(firedLpnTranPair) + 1;
tranFiringFreq.put(firedLpnTranPair, freq);
if (Options.getDebugMode()) {
// System.out.println("~~~~~~tranFiringFreq~~~~~~~");
// printHashMap(tranFiringFreq, sgList);
}
}
State[] nextStateArray = sgList[firedLpnTranPair.getLpnIndex()].fire(sgList, curStateArray, firedTran);
tranFiringCnt++;
// Check if the firedTran causes disabling error or deadlock.
if (Options.getReportDisablingError()) {
for (int i=0; i<numLpns; i++) {
Transition disabledTran = firedTran.disablingError(curStateArray[i].getEnabledTransitions(), nextStateArray[i].getEnabledTransitions());
if (disabledTran != null) {
System.err.println("Disabling Error: "
+ disabledTran.getFullLabel() + " is disabled by "
+ firedTran.getFullLabel());
failure = true;
break main_while_loop;
}
}
}
LpnTranList nextAmpleTrans = new LpnTranList();
nextAmpleTrans = getAmple(curStateArray, nextStateArray, staticSetsMap, init, tranFiringFreq, sgList, lpnList, prjStateSet, stateStackTop);
// check for possible deadlock
if (nextAmpleTrans.size() == 0) {
System.out.println("*** Verification failed: deadlock.");
failure = true;
break main_while_loop;
}
HashSet<LpnTransitionPair> nextAmple = getLpnTransitionPair(nextAmpleTrans);
PrjState nextPrjState = new PrjState(nextStateArray);
Boolean existingState = prjStateSet.contains(nextPrjState) || stateStack.contains(nextPrjState);
if (existingState == false) {
if (Options.getDebugMode()) {
// System.out.println("%%%%%%% existingSate == false %%%%%%%%");
}
if (Options.getOutputSgFlag()) {
if (Options.getDebugMode()) {
// printStateArray(curStateArray);
// printStateArray(nextStateArray);
// System.out.println("stateStackTop: ");
// printStateArray(stateStackTop.toStateArray());
// System.out.println("firedTran = " + firedTran.getName());
// printNextStateMap(stateStackTop.getNextStateMap());
}
stateStackTop.setTranOut(firedTran, nextPrjState);
if (Options.getDebugMode()) {
// printNextStateMap(stateStackTop.getNextStateMap());
}
for (PrjState prjState : prjStateSet) {
if (prjState.equals(stateStackTop)) {
prjState.setTranOut(firedTran, nextPrjState);
if (Options.getDebugMode()) {
// printNextStateMap(prjState.getNextStateMap());
}
}
}
}
updateLocalAmpleTbl(nextAmple, sgList, nextStateArray);
stateStackTop.setChild(nextPrjState);
nextPrjState.setFather(stateStackTop);
stateStackTop = nextPrjState;
stateStack.add(stateStackTop);
if (Options.getDebugMode()) {
// System.out.println("%%%%%%% Add global state to stateStack %%%%%%%%");
// printStateArray(stateStackTop.toStateArray());
// System.out.println("+++++++ Push trans onto lpnTranStack @ 2++++++++");
// printTransitionSet((LpnTranList) nextAmpleTrans, "");
}
lpnTranStack.push((LpnTranList) nextAmpleTrans.clone());
totalStates++;
}
else {
if (Options.getOutputSgFlag()) {
if (Options.getDebugMode()) {
// printStateArray(curStateArray);
// printStateArray(nextStateArray);
}
for (PrjState prjState : prjStateSet) {
if (prjState.equals(nextPrjState)) {
nextPrjState.setNextStateMap((HashMap<Transition, PrjState>) prjState.getNextStateMap().clone());
}
}
if (Options.getDebugMode()) {
// System.out.println("stateStackTop: ");
// printStateArray(stateStackTop.toStateArray());
// System.out.println("firedTran = " + firedTran.getName());
// System.out.println("nextStateMap for stateStackTop before firedTran being added: ");
// printNextStateMap(stateStackTop.getNextStateMap());
}
stateStackTop.setTranOut(firedTran, nextPrjState);
if (Options.getDebugMode()) {
// printNextStateMap(stateStackTop.getNextStateMap());
}
for (PrjState prjState : prjStateSet) {
if (prjState == stateStackTop) {
prjState.setNextStateMap((HashMap<Transition, PrjState>) stateStackTop.getNextStateMap().clone());
if (Options.getDebugMode()) {
// printNextStateMap(prjState.getNextStateMap());
}
}
}
}
if (!Options.getCycleClosingMthd().toLowerCase().equals("no_cycleclosing")) {
// Cycle closing check
if (prjStateSet.contains(nextPrjState) && stateStack.contains(nextPrjState)) {
if (Options.getDebugMode()) {
// System.out.println("%%%%%%% Cycle Closing %%%%%%%%");
}
HashSet<LpnTransitionPair> nextAmpleSet = new HashSet<LpnTransitionPair>();
HashSet<LpnTransitionPair> curAmpleSet = new HashSet<LpnTransitionPair>();
for (Transition t : nextAmpleTrans) {
nextAmpleSet.add(new LpnTransitionPair(t.getLpn().getLpnIndex(), t.getIndex()));
}
for (Transition t: curAmpleTrans) {
curAmpleSet.add(new LpnTransitionPair(t.getLpn().getLpnIndex(), t.getIndex()));
}
curAmpleSet.add(new LpnTransitionPair(firedTran.getLpn().getLpnIndex(), firedTran.getIndex()));
HashSet<LpnTransitionPair> newNextAmple = new HashSet<LpnTransitionPair>();
// if (Options.getNecessaryUsingDependencyGraphs())
// newNextAmple = computeCycleClosingTrans(curStateArray, nextStateArray, staticSetsMap,
// null, sgList, prjStateSet, nextPrjState, nextAmpleSet, curAmpleSet, stateStack);
// else
newNextAmple = computeCycleClosingTrans(curStateArray, nextStateArray, staticSetsMap,
tranFiringFreq, sgList, prjStateSet, nextPrjState, nextAmpleSet, curAmpleSet, stateStack);
if (newNextAmple != null && !newNextAmple.isEmpty()) {
LpnTranList newNextAmpleTrans = getLpnTranList(newNextAmple, sgList);
stateStackTop.setChild(nextPrjState);
nextPrjState.setFather(stateStackTop);
if (Options.getDebugMode()) {
// System.out.println("nextPrjState: ");
// printStateArray(nextPrjState.toStateArray());
// System.out.println("nextStateMap for nextPrjState: ");
// printNextStateMap(nextPrjState.getNextStateMap());
}
stateStackTop = nextPrjState;
stateStack.add(stateStackTop);
if (Options.getDebugMode()) {
// System.out.println("%%%%%%% Add state to stateStack %%%%%%%%");
// printStateArray(stateStackTop.toStateArray());
// System.out.println("stateStackTop: ");
// printStateArray(stateStackTop.toStateArray());
// System.out.println("nextStateMap for stateStackTop: ");
// printNextStateMap(nextPrjState.getNextStateMap());
}
lpnTranStack.push(newNextAmpleTrans.clone());
if (Options.getDebugMode()) {
// System.out.println("+++++++ Push these trans onto lpnTranStack @ Cycle Closing ++++++++");
// printTransitionSet((LpnTranList) newNextAmpleTrans, "");
// printLpnTranStack(lpnTranStack);
}
}
}
}
updateLocalAmpleTbl(nextAmple, sgList, nextStateArray);
}
}
if (Options.getDebugMode()) {
try {
PORdebugBufferedWriter.close();
PORdebugFileStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
double totalStateCnt = prjStateSet.size();
System.out.println("---> final numbers: # LPN transition firings: " + tranFiringCnt
+ ", # of prjStates found: " + totalStateCnt
+ ", max_stack_depth: " + max_stack_depth
+ ", peak total memory: " + peakTotalMem / 1000000 + " MB"
+ ", peak used memory: " + peakUsedMem / 1000000 + " MB");
if (Options.getOutputLogFlag())
writePerformanceResultsToLogFile(true, tranFiringCnt, totalStateCnt, peakTotalMem / 1000000, peakUsedMem / 1000000);
if (Options.getOutputSgFlag()) {
drawGlobalStateGraph(sgList, prjStateSet, false);
}
return sgList;
}
private void createPORDebugFile() {
try {
PORdebugFileName = Options.getPrjSgPath() + Options.getLogName() + "_" + Options.getPOR() + "_"
+ Options.getCycleClosingMthd() + "_" + Options.getCycleClosingAmpleMethd() + ".dbg";
PORdebugFileStream = new FileWriter(PORdebugFileName, true);
PORdebugBufferedWriter = new BufferedWriter(PORdebugFileStream);
}
catch (Exception e) {
e.printStackTrace();
System.err.println("Error producing the debugging file for partial order reduction.");
}
}
private void writeStringWithEndOfLineToPORDebugFile(String string) {
try {
PORdebugBufferedWriter.append(string);
PORdebugBufferedWriter.newLine();
PORdebugBufferedWriter.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
private void writeStringToPORDebugFile(String string) {
try {
PORdebugBufferedWriter.append(string);
//PORdebugBufferedWriter.newLine();
PORdebugBufferedWriter.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
private void writePerformanceResultsToLogFile(boolean isPOR, int tranFiringCnt, double totalStateCnt,
double peakTotalMem, double peakUsedMem) {
try {
String fileName = null;
if (isPOR) {
fileName = Options.getPrjSgPath() + Options.getLogName() + "_" + Options.getPOR() + "_"
+ Options.getCycleClosingMthd() + "_" + Options.getCycleClosingAmpleMethd() + ".log";
}
else
fileName = Options.getPrjSgPath() + Options.getLogName() + "_full" + ".log";
BufferedWriter out = new BufferedWriter(new FileWriter(fileName));
out.write("tranFiringCnt" + "\t" + "prjStateCnt" + "\t" + "maxStackDepth" + "\t" + "peakTotalMem(MB)" + "\t" + "peakUsedMem(MB)\n");
out.write(tranFiringCnt + "\t" + totalStateCnt + "\t" + max_stack_depth + "\t" + peakTotalMem + "\t"
+ peakUsedMem + "\n");
out.close();
}
catch (Exception e) {
e.printStackTrace();
System.err.println("Error producing local state graph as dot file.");
}
}
private void printLpnTranStack(Stack<LinkedList<Transition>> lpnTranStack) {
for (int i=0; i<lpnTranStack.size(); i++) {
LinkedList<Transition> tranList = lpnTranStack.get(i);
for (int j=0; j<tranList.size(); j++) {
System.out.println(tranList.get(j).getName());
}
System.out.println("
}
}
private void printNextStateMap(HashMap<Transition, PrjState> nextStateMap) {
for (Transition t: nextStateMap.keySet()) {
System.out.print(t.getName() + " -> ");
State[] stateArray = nextStateMap.get(t).getStateArray();
for (int i=0; i<stateArray.length; i++) {
System.out.print("S" + stateArray[i].getIndex() + ", ");
}
System.out.print("\n");
}
}
private HashSet<LpnTransitionPair> getLpnTransitionPair(LpnTranList ampleTrans) {
HashSet<LpnTransitionPair> ample = new HashSet<LpnTransitionPair>();
for (Transition tran : ampleTrans) {
ample.add(new LpnTransitionPair(tran.getLpn().getLpnIndex(), tran.getIndex()));
}
return ample;
}
private LpnTranList getLpnTranList(HashSet<LpnTransitionPair> newNextAmple,
StateGraph[] sgList) {
LpnTranList newNextAmpleTrans = new LpnTranList();
for (LpnTransitionPair lpnTran : newNextAmple) {
Transition tran = sgList[lpnTran.getLpnIndex()].getLpn().getTransition(lpnTran.getTranIndex());
newNextAmpleTrans.add(tran);
}
return newNextAmpleTrans;
}
private HashSet<LpnTransitionPair> computeCycleClosingTrans(State[] curStateArray,
State[] nextStateArray,
HashMap<LpnTransitionPair, StaticSets> staticSetsMap,
HashMap<LpnTransitionPair, Integer> tranFiringFreq, StateGraph[] sgList, HashSet<PrjState> prjStateSet,
PrjState nextPrjState, HashSet<LpnTransitionPair> nextAmple,
HashSet<LpnTransitionPair> curAmple, HashSet<PrjState> stateStack) {
for (State s : nextStateArray)
if (s == null)
throw new NullPointerException();
String cycleClosingMthd = Options.getCycleClosingMthd();
HashSet<LpnTransitionPair> newNextAmple = new HashSet<LpnTransitionPair>();
HashSet<LpnTransitionPair> nextEnabled = new HashSet<LpnTransitionPair>();
HashSet<LpnTransitionPair> curEnabled = new HashSet<LpnTransitionPair>();
LhpnFile[] lpnList = new LhpnFile[sgList.length];
for (int i=0; i<sgList.length; i++)
lpnList[i] = sgList[i].getLpn();
for (int lpnIndex=0; lpnIndex<nextStateArray.length; lpnIndex++) {
LhpnFile curLpn = sgList[lpnIndex].getLpn();
for (int i=0; i < curLpn.getAllTransitions().length; i++) {
Transition tran = curLpn.getAllTransitions()[i];
if (nextStateArray[lpnIndex].getTranVector()[i])
nextEnabled.add(new LpnTransitionPair(curLpn.getLpnIndex(), tran.getIndex()));
if (curStateArray[lpnIndex].getTranVector()[i])
curEnabled.add(new LpnTransitionPair(curLpn.getLpnIndex(), tran.getIndex()));
}
}
// Cycle closing on global state graph
if (Options.getDebugMode()) {
//System.out.println("~~~~~~~ existing global state ~~~~~~~~");
}
if (cycleClosingMthd.equals("strong")) {
newNextAmple.addAll(getIntSetSubstraction(curEnabled, nextAmple));
updateLocalAmpleTbl(newNextAmple, sgList, nextStateArray);
}
else if (cycleClosingMthd.equals("behavioral")) {
if (Options.getDebugMode()) {
}
HashSet<LpnTransitionPair> curReduced = getIntSetSubstraction(curEnabled, curAmple);
HashSet<LpnTransitionPair> oldNextAmple = new HashSet<LpnTransitionPair>();
DependentSetComparator depComp = new DependentSetComparator(tranFiringFreq);
PriorityQueue<DependentSet> dependentSetQueue = new PriorityQueue<DependentSet>(nextEnabled.size(), depComp);
// TODO: Is oldNextAmple correctly obtained below?
if (Options.getDebugMode()) {
// printStateArray(nextStateArray);
}
for (int lpnIndex=0; lpnIndex < sgList.length; lpnIndex++) {
if (sgList[lpnIndex].getEnabledSetTbl().get(nextStateArray[lpnIndex]) != null) {
LpnTranList oldLocalNextAmpleTrans = sgList[lpnIndex].getEnabledSetTbl().get(nextStateArray[lpnIndex]);
if (Options.getDebugMode()) {
// printTransitionSet(oldLocalNextAmpleTrans, "oldLocalNextAmpleTrans");
}
for (Transition oldLocalTran : oldLocalNextAmpleTrans)
oldNextAmple.add(new LpnTransitionPair(lpnIndex, oldLocalTran.getIndex()));
}
}
HashSet<LpnTransitionPair> ignored = getIntSetSubstraction(curReduced, oldNextAmple);
boolean isCycleClosingAmpleComputation = true;
for (LpnTransitionPair seed : ignored) {
HashSet<LpnTransitionPair> dependent = new HashSet<LpnTransitionPair>();
dependent = computeDependent(nextStateArray,seed,dependent,nextEnabled,staticSetsMap, lpnList, isCycleClosingAmpleComputation);
if (Options.getDebugMode()) {
// printIntegerSet(dependent, sgList, "dependent set for ignored transition " + sgList[seed.getLpnIndex()].getLpn().getLabel()
// + "(" + sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName() + ")");
}
// TODO: Is this still necessary?
// boolean dependentOnlyHasDummyTrans = true;
// for (LpnTransitionPair dependentTran : dependent) {
// dependentOnlyHasDummyTrans = dependentOnlyHasDummyTrans
// && isDummyTran(sgList[dependentTran.getLpnIndex()].getLpn().getTransition(dependentTran.getTranIndex()).getName());
// if ((newNextAmple.size() == 0 || dependent.size() < newNextAmple.size()) && !dependentOnlyHasDummyTrans)
// newNextAmple = (HashSet<LpnTransitionPair>) dependent.clone();
// DependentSet dependentSet = new DependentSet(newNextAmple, seed,
// isDummyTran(sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName()));
DependentSet dependentSet = new DependentSet(dependent, seed,
isDummyTran(sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName()));
dependentSetQueue.add(dependentSet);
}
cachedNecessarySets.clear();
if (!dependentSetQueue.isEmpty()) {
// System.out.println("depdentSetQueue is NOT empty.");
// newNextAmple = dependentSetQueue.poll().getDependent();
// TODO: Will newNextAmpleTmp - oldNextAmple be safe?
HashSet<LpnTransitionPair> newNextAmpleTmp = dependentSetQueue.poll().getDependent();
newNextAmple = getIntSetSubstraction(newNextAmpleTmp, oldNextAmple);
updateLocalAmpleTbl(newNextAmple, sgList, nextStateArray);
}
if (Options.getDebugMode()) {
// printIntegerSet(newNextAmple, sgList, "newNextAmple");
}
}
else if (cycleClosingMthd.equals("state_search")) {
// TODO: complete cycle closing check for state search.
}
return newNextAmple;
}
private void updateLocalAmpleTbl(HashSet<LpnTransitionPair> newNextAmple,
StateGraph[] sgList, State[] nextStateArray) {
// Ample set at each state is stored in the enabledSetTbl in each state graph.
for (LpnTransitionPair lpnTran : newNextAmple) {
State nextState = nextStateArray[lpnTran.getLpnIndex()];
Transition tran = sgList[lpnTran.getLpnIndex()].getLpn().getTransition(lpnTran.getTranIndex());
if (sgList[lpnTran.getLpnIndex()].getEnabledSetTbl().get(nextState) != null) {
if (!sgList[lpnTran.getLpnIndex()].getEnabledSetTbl().get(nextState).contains(tran))
sgList[lpnTran.getLpnIndex()].getEnabledSetTbl().get(nextState).add(tran);
}
else {
LpnTranList newLpnTranList = new LpnTranList();
newLpnTranList.add(tran);
sgList[lpnTran.getLpnIndex()].getEnabledSetTbl().put(nextStateArray[lpnTran.getLpnIndex()], newLpnTranList);
if (Options.getDebugMode()) {
// System.out.println("@ updateLocalAmpleTbl: ");
// System.out.println("Add S" + nextStateArray[lpnTran.getLpnIndex()].getIndex() + " to the enabledSetTbl of "
// + sgList[lpnTran.getLpnIndex()].getLpn().getLabel() + ".");
}
}
}
if (Options.getDebugMode()) {
// printEnabledSetTbl(sgList);
}
}
private void printPrjStateSet(HashSet<PrjState> prjStateSet) {
for (PrjState curGlobal : prjStateSet) {
State[] curStateArray = curGlobal.toStateArray();
printStateArray(curStateArray);
System.out.println("
}
}
// /**
// * This method performs first-depth search on multiple LPNs and applies partial order reduction technique with the trace-back.
// * @param sgList
// * @param initStateArray
// * @param cycleClosingMthdIndex
// * @return
// */
// public StateGraph[] search_dfsPORrefinedCycleRule(final StateGraph[] sgList, final State[] initStateArray, int cycleClosingMthdIndex) {
// if (cycleClosingMthdIndex == 1)
// else if (cycleClosingMthdIndex == 2)
// else if (cycleClosingMthdIndex == 4)
// double peakUsedMem = 0;
// double peakTotalMem = 0;
// boolean failure = false;
// int tranFiringCnt = 0;
// int totalStates = 1;
// int numLpns = sgList.length;
// HashSet<PrjState> stateStack = new HashSet<PrjState>();
// Stack<LinkedList<Transition>> lpnTranStack = new Stack<LinkedList<Transition>>();
// Stack<Integer> curIndexStack = new Stack<Integer>();
// HashSet<PrjState> prjStateSet = new HashSet<PrjState>();
// PrjState initPrjState = new PrjState(initStateArray);
// prjStateSet.add(initPrjState);
// PrjState stateStackTop = initPrjState;
// System.out.println("%%%%%%% Add states to stateStack %%%%%%%%");
// printStateArray(stateStackTop.toStateArray());
// stateStack.add(stateStackTop);
// // Prepare static pieces for POR
// HashMap<Integer, HashMap<Integer, StaticSets>> staticSetsMap = new HashMap<Integer, HashMap<Integer, StaticSets>>();
// Transition[] allTransitions = sgList[0].getLpn().getAllTransitions();
// HashMap<Integer, StaticSets> tmpMap = new HashMap<Integer, StaticSets>();
// HashMap<Integer, Integer> tranFiringFreq = new HashMap<Integer, Integer>(allTransitions.length);
// for (Transition curTran: allTransitions) {
// StaticSets curStatic = new StaticSets(sgList[0].getLpn(), curTran, allTransitions);
// curStatic.buildDisableSet();
// curStatic.buildEnableSet();
// curStatic.buildModifyAssignSet();
// tmpMap.put(curTran.getIndex(), curStatic);
// tranFiringFreq.put(curTran.getIndex(), 0);
// staticSetsMap.put(sgList[0].getLpn().getLpnIndex(), tmpMap);
// printStaticSetMap(staticSetsMap);
// System.out.println("call getAmple on initStateArray at 0: ");
// boolean init = true;
// AmpleSet initAmple = new AmpleSet();
// initAmple = sgList[0].getAmple(initStateArray[0], staticSetsMap, init, tranFiringFreq);
// HashMap<State, LpnTranList> initEnabledSetTbl = (HashMap<State, LpnTranList>) sgList[0].copyEnabledSetTbl();
// lpnTranStack.push(initAmple.getAmpleSet());
// curIndexStack.push(0);
// System.out.println("+++++++ Push trans onto lpnTranStack ++++++++");
// printTransitionSet((LpnTranList) initAmple.getAmpleSet(), "");
// main_while_loop: while (failure == false && stateStack.size() != 0) {
// System.out.println("$$$$$$$$$$$ loop begins $$$$$$$$$$");
// long curTotalMem = Runtime.getRuntime().totalMemory();
// long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
// if (curTotalMem > peakTotalMem)
// peakTotalMem = curTotalMem;
// if (curUsedMem > peakUsedMem)
// peakUsedMem = curUsedMem;
// if (stateStack.size() > max_stack_depth)
// max_stack_depth = stateStack.size();
// iterations++;
// if (iterations % 100000 == 0) {
// System.out.println("---> #iteration " + iterations
// + "> # LPN transition firings: " + tranFiringCnt
// + ", # of prjStates found: " + totalStates
// + ", stack_depth: " + stateStack.size()
// + " used memory: " + (float) curUsedMem / 1000000
// + " free memory: "
// + (float) Runtime.getRuntime().freeMemory() / 1000000);
// State[] curStateArray = stateStackTop.toStateArray(); //stateStack.peek();
// int curIndex = curIndexStack.peek();
//// System.out.println("curIndex = " + curIndex);
// //AmpleSet curAmple = new AmpleSet();
// //LinkedList<Transition> curAmpleTrans = curAmple.getAmpleSet();
// LinkedList<Transition> curAmpleTrans = lpnTranStack.peek();
//// printStateArray(curStateArray);
//// System.out.println("+++++++ curAmple trans ++++++++");
//// printTransLinkedList(curAmpleTrans);
// // If all enabled transitions of the current LPN are considered,
// // then consider the next LPN
// // by increasing the curIndex.
// // Otherwise, if all enabled transitions of all LPNs are considered,
// // then pop the stacks.
// if (curAmpleTrans.size() == 0) {
// lpnTranStack.pop();
//// System.out.println("+++++++ Pop trans off lpnTranStack ++++++++");
// curIndexStack.pop();
//// System.out.println("+++++++ Pop index off curIndexStack ++++++++");
// curIndex++;
//// System.out.println("curIndex = " + curIndex);
// while (curIndex < numLpns) {
// System.out.println("call getEnabled on curStateArray at 1: ");
// LpnTranList tmpAmpleTrans = (LpnTranList) (sgList[curIndex].getAmple(curStateArray[curIndex], staticSetsMap, init, tranFiringFreq)).getAmpleSet();
// curAmpleTrans = tmpAmpleTrans.clone();
// //printTransitionSet(curEnabled, "curEnabled set");
// if (curAmpleTrans.size() > 0) {
// System.out.println("+++++++ Push trans onto lpnTranStack ++++++++");
// printTransLinkedList(curAmpleTrans);
// lpnTranStack.push(curAmpleTrans);
// curIndexStack.push(curIndex);
// printIntegerStack("curIndexStack after push 1", curIndexStack);
// break;
// curIndex++;
// if (curIndex == numLpns) {
// prjStateSet.add(stateStackTop);
// System.out.println("%%%%%%% Remove stateStackTop from stateStack %%%%%%%%");
// printStateArray(stateStackTop.toStateArray());
// stateStack.remove(stateStackTop);
// stateStackTop = stateStackTop.getFather();
// continue;
// Transition firedTran = curAmpleTrans.removeLast();
// System.out.println("
// System.out.println("Fired transition: " + firedTran.getName());
// System.out.println("
// Integer freq = tranFiringFreq.get(firedTran.getIndex()) + 1;
// tranFiringFreq.put(firedTran.getIndex(), freq);
// System.out.println("~~~~~~tranFiringFreq~~~~~~~");
// printHashMap(tranFiringFreq, allTransitions);
// State[] nextStateArray = sgList[curIndex].fire(sgList, curStateArray, firedTran);
// tranFiringCnt++;
// Check if the firedTran causes disabling error or deadlock.
// @SuppressWarnings("unchecked")
// LinkedList<Transition>[] curAmpleArray = new LinkedList[numLpns];
// @SuppressWarnings("unchecked")
// LinkedList<Transition>[] nextAmpleArray = new LinkedList[numLpns];
// boolean updatedAmpleDueToCycleRule = false;
// for (int i = 0; i < numLpns; i++) {
// StateGraph sg_tmp = sgList[i];
// System.out.println("call getAmple on curStateArray at 2: i = " + i);
// AmpleSet ampleList = new AmpleSet();
// if (init) {
// ampleList = initAmple;
// sg_tmp.setEnabledSetTbl(initEnabledSetTbl);
// init = false;
// else
// ampleList = sg_tmp.getAmple(curStateArray[i], staticSetsMap, init, tranFiringFreq);
// curAmpleArray[i] = ampleList.getAmpleSet();
// System.out.println("call getAmpleRefinedCycleRule on nextStateArray at 3: i = " + i);
// ampleList = sg_tmp.getAmpleRefinedCycleRule(curStateArray[i], nextStateArray[i], staticSetsMap, stateStack, stateStackTop, init, cycleClosingMthdIndex, i, tranFiringFreq);
// nextAmpleArray[i] = ampleList.getAmpleSet();
// if (!updatedAmpleDueToCycleRule && ampleList.getAmpleChanged()) {
// updatedAmpleDueToCycleRule = true;
// for (LinkedList<Transition> tranList : curAmpleArray) {
// printTransLinkedList(tranList);
//// for (LinkedList<Transition> tranList : curAmpleArray) {
//// printTransLinkedList(tranList);
//// for (LinkedList<Transition> tranList : nextAmpleArray) {
//// printTransLinkedList(tranList);
// Transition disabledTran = firedTran.disablingError(
// curStateArray[i].getEnabledTransitions(), nextStateArray[i].getEnabledTransitions());
// if (disabledTran != null) {
// System.err.println("Disabling Error: "
// + disabledTran.getFullLabel() + " is disabled by "
// + firedTran.getFullLabel());
// failure = true;
// break main_while_loop;
// if (Analysis.deadLock(sgList, nextStateArray, staticSetsMap, init, tranFiringFreq) == true) {
// failure = true;
// break main_while_loop;
// PrjState nextPrjState = new PrjState(nextStateArray);
// Boolean existingState = prjStateSet.contains(nextPrjState) || stateStack.contains(nextPrjState);
// if (existingState == true && updatedAmpleDueToCycleRule) {
// // cycle closing
// System.out.println("%%%%%%% existingSate == true %%%%%%%%");
// stateStackTop.setChild(nextPrjState);
// nextPrjState.setFather(stateStackTop);
// stateStackTop = nextPrjState;
// stateStack.add(stateStackTop);
// System.out.println("%%%%%%% Add state to stateStack %%%%%%%%");
// printStateArray(stateStackTop.toStateArray());
// System.out.println("+++++++ Push trans onto lpnTranStack ++++++++");
// printTransitionSet((LpnTranList) nextAmpleArray[0], "");
// lpnTranStack.push((LpnTranList) nextAmpleArray[0].clone());
// curIndexStack.push(0);
// if (existingState == false) {
// System.out.println("%%%%%%% existingSate == false %%%%%%%%");
// stateStackTop.setChild(nextPrjState);
// nextPrjState.setFather(stateStackTop);
// stateStackTop = nextPrjState;
// stateStack.add(stateStackTop);
// System.out.println("%%%%%%% Add state to stateStack %%%%%%%%");
// printStateArray(stateStackTop.toStateArray());
// System.out.println("+++++++ Push trans onto lpnTranStack ++++++++");
// printTransitionSet((LpnTranList) nextAmpleArray[0], "");
// lpnTranStack.push((LpnTranList) nextAmpleArray[0].clone());
// curIndexStack.push(0);
// totalStates++;
// // end of main_while_loop
// double totalStateCnt = prjStateSet.size();
// System.out.println("---> final numbers: # LPN transition firings: " + tranFiringCnt
// + ", # of prjStates found: " + totalStateCnt
// + ", max_stack_depth: " + max_stack_depth
// + ", peak total memory: " + peakTotalMem / 1000000 + " MB"
// + ", peak used memory: " + peakUsedMem / 1000000 + " MB");
// // This currently works for a single LPN.
// return sgList;
// return null;
private void printHashMap(HashMap<LpnTransitionPair, Integer> tranFiringFreq, StateGraph[] sgList) {
for (LpnTransitionPair curIndex : tranFiringFreq.keySet()) {
LhpnFile curLpn = sgList[curIndex.getLpnIndex()].getLpn();
Transition curTran = curLpn.getTransition(curIndex.getTranIndex());
System.out.println(curLpn.getLabel() + "(" + curTran.getName() + ")" + " -> " + tranFiringFreq.get(curIndex));
}
}
private void writeStaticSetsMapToPORDebugFile(
LhpnFile[] lpnList, HashMap<LpnTransitionPair,StaticSets> staticSetsMap) {
try {
PORdebugBufferedWriter.write("
PORdebugBufferedWriter.newLine();
for (LpnTransitionPair lpnTranPair : staticSetsMap.keySet()) {
StaticSets statSets = staticSetsMap.get(lpnTranPair);
writeLpnTranPairToPORDebugFile(lpnList, statSets.getTran(), statSets.getDisableSet(), "disableSet");
for (HashSet<LpnTransitionPair> setOneConjunctTrue : statSets.getOtherTransSetCurTranEnablingTrue()) {
writeLpnTranPairToPORDebugFile(lpnList, statSets.getTran(), setOneConjunctTrue, "enableBySetingEnablingTrue for one conjunct");
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
// private Transition[] assignStickyTransitions(LhpnFile lpn) {
// // allProcessTrans is a hashmap from a transition to its process color (integer).
// HashMap<Transition, Integer> allProcessTrans = new HashMap<Transition, Integer>();
// // create an Abstraction object to call the divideProcesses method.
// Abstraction abs = new Abstraction(lpn);
// abs.decomposeLpnIntoProcesses();
// allProcessTrans.putAll(
// (HashMap<Transition, Integer>)abs.getTransWithProcIDs().clone());
// HashMap<Integer, LpnProcess> processMap = new HashMap<Integer, LpnProcess>();
// for (Iterator<Transition> tranIter = allProcessTrans.keySet().iterator(); tranIter.hasNext();) {
// Transition curTran = tranIter.next();
// Integer procId = allProcessTrans.get(curTran);
// if (!processMap.containsKey(procId)) {
// LpnProcess newProcess = new LpnProcess(procId);
// newProcess.addTranToProcess(curTran);
// if (curTran.getPreset() != null) {
// Place[] preset = curTran.getPreset();
// for (Place p : preset) {
// newProcess.addPlaceToProcess(p);
// processMap.put(procId, newProcess);
// else {
// LpnProcess curProcess = processMap.get(procId);
// curProcess.addTranToProcess(curTran);
// if (curTran.getPreset() != null) {
// Place[] preset = curTran.getPreset();
// for (Place p : preset) {
// curProcess.addPlaceToProcess(p);
// for(Iterator<Integer> processMapIter = processMap.keySet().iterator(); processMapIter.hasNext();) {
// LpnProcess curProc = processMap.get(processMapIter.next());
// curProc.assignStickyTransitions();
// curProc.printProcWithStickyTrans();
// return lpn.getAllTransitions();
private void printLpnTranPair(LhpnFile[] lpnList, Transition curTran,
HashSet<LpnTransitionPair> curDisable, String setName) {
System.out.print(setName + " for " + curTran.getName() + "(" + curTran.getIndex() + ")" + " is: ");
if (curDisable.isEmpty()) {
System.out.println("empty");
}
else {
for (LpnTransitionPair lpnTranPair: curDisable) {
System.out.print("(" + lpnList[lpnTranPair.getLpnIndex()].getLabel()
+ ", " + lpnList[lpnTranPair.getLpnIndex()].getAllTransitions()[lpnTranPair.getTranIndex()].getName() + ")," + "\t");
}
System.out.print("\n");
}
}
private void writeLpnTranPairToPORDebugFile(LhpnFile[] lpnList, Transition curTran,
HashSet<LpnTransitionPair> lpnTransitionPairSet, String setName) {
try {
//PORdebugBufferedWriter.write(setName + " for " + curTran.getName() + "(" + curTran.getIndex() + ")" + " is: ");
PORdebugBufferedWriter.write(setName + " for (" + curTran.getLpn().getLabel() + " , " + curTran.getName() + ") is: ");
if (lpnTransitionPairSet.isEmpty()) {
PORdebugBufferedWriter.write("empty");
PORdebugBufferedWriter.newLine();
}
else {
for (LpnTransitionPair lpnTranPair: lpnTransitionPairSet) {
PORdebugBufferedWriter.append("(" + lpnList[lpnTranPair.getLpnIndex()].getLabel()
+ ", " + lpnList[lpnTranPair.getLpnIndex()].getAllTransitions()[lpnTranPair.getTranIndex()].getName() + ")," + " ");
}
PORdebugBufferedWriter.newLine();
}
PORdebugBufferedWriter.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
private void printTransitionSet(LpnTranList transitionSet, String setName) {
if (!setName.isEmpty())
System.out.print(setName + " is: ");
if (transitionSet.isEmpty()) {
System.out.println("empty");
}
else {
for (Iterator<Transition> curTranIter = transitionSet.iterator(); curTranIter.hasNext();) {
Transition tranInDisable = curTranIter.next();
System.out.print(tranInDisable.getName() + " ");
}
System.out.print("\n");
}
}
// private void printTransitionSet(LinkedList<Transition> transitionSet, String setName) {
// System.out.print(setName + " is: ");
// if (transitionSet.isEmpty()) {
// System.out.println("empty");
// else {
// for (Iterator<Transition> curTranIter = transitionSet.iterator(); curTranIter.hasNext();) {
// Transition tranInDisable = curTranIter.next();
// System.out.print(tranInDisable.getIndex() + " ");
// System.out.print("\n");
/**
* Return the set of all LPN transitions that are enabled in 'state'. The "init" flag indicates whether a transition
* needs to be evaluated. The enabledSetTbl (for each StateGraph obj) stores the AMPLE set for each state of each LPN.
* @param stateArray
* @param stateStack
* @param enable
* @param disableByStealingToken
* @param disable
* @param init
* @param tranFiringFreq
* @param sgList
* @return
*/
public LpnTranList getAmple(State[] curStateArray, State[] nextStateArray, HashMap<LpnTransitionPair,StaticSets> staticSetsMap,
boolean init, HashMap<LpnTransitionPair, Integer> tranFiringFreq, StateGraph[] sgList, LhpnFile[] lpnList,
HashSet<PrjState> stateStack, PrjState stateStackTop) {
State[] stateArray = null;
if (nextStateArray == null)
stateArray = curStateArray;
else
stateArray = nextStateArray;
for (State s : stateArray)
if (s == null)
throw new NullPointerException();
LpnTranList ample = new LpnTranList();
HashSet<LpnTransitionPair> curEnabled = new HashSet<LpnTransitionPair>();
for (int lpnIndex=0; lpnIndex<stateArray.length; lpnIndex++) {
State state = stateArray[lpnIndex];
if (init) {
LhpnFile curLpn = sgList[lpnIndex].getLpn();
for (int i=0; i < curLpn.getAllTransitions().length; i++) {
Transition tran = curLpn.getAllTransitions()[i];
if (sgList[lpnIndex].isEnabled(tran,state)){
curEnabled.add(new LpnTransitionPair(curLpn.getLpnIndex(), i));
}
}
}
else {
LhpnFile curLpn = sgList[lpnIndex].getLpn();
for (int i=0; i < curLpn.getAllTransitions().length; i++) {
if (stateArray[lpnIndex].getTranVector()[i]) {
curEnabled.add(new LpnTransitionPair(curLpn.getLpnIndex(), i));
}
}
}
}
HashSet<LpnTransitionPair> ready = new HashSet<LpnTransitionPair>();
if (Options.getDebugMode()) {
// printIntegerSet(curEnabled, sgList, "Enabled set");
writeStringWithEndOfLineToPORDebugFile("******* Partial Order Reduction *******");
writeIntegerSetToPORDebugFile(curEnabled, sgList, "Enabled set");
writeStringWithEndOfLineToPORDebugFile("******* Begin POR *******");
}
if (curEnabled.isEmpty()) {
return ample;
}
ready = partialOrderReduction(stateArray, curEnabled, staticSetsMap, tranFiringFreq, sgList, lpnList);
if (Options.getDebugMode()) {
writeStringWithEndOfLineToPORDebugFile("******* End POR *******");
writeIntegerSetToPORDebugFile(ready, sgList, "Ready set");
writeStringWithEndOfLineToPORDebugFile("********************");
}
if (tranFiringFreq != null) {
LinkedList<LpnTransitionPair> readyList = new LinkedList<LpnTransitionPair>();
for (LpnTransitionPair inReady : ready) {
readyList.add(inReady);
}
mergeSort(readyList, tranFiringFreq);
for (LpnTransitionPair inReady : readyList) {
LhpnFile lpn = sgList[inReady.getLpnIndex()].getLpn();
Transition tran = lpn.getTransition(inReady.getTranIndex());
ample.addFirst(tran);
}
}
else {
for (LpnTransitionPair inReady : ready) {
LhpnFile lpn = sgList[inReady.getLpnIndex()].getLpn();
Transition tran = lpn.getTransition(inReady.getTranIndex());
ample.add(tran);
}
}
return ample;
}
private LinkedList<LpnTransitionPair> mergeSort(LinkedList<LpnTransitionPair> array, HashMap<LpnTransitionPair, Integer> tranFiringFreq) {
if (array.size() == 1)
return array;
int middle = array.size() / 2;
LinkedList<LpnTransitionPair> left = new LinkedList<LpnTransitionPair>();
LinkedList<LpnTransitionPair> right = new LinkedList<LpnTransitionPair>();
for (int i=0; i<middle; i++) {
left.add(i, array.get(i));
}
for (int i=middle; i<array.size();i++) {
right.add(i-middle, array.get(i));
}
left = mergeSort(left, tranFiringFreq);
right = mergeSort(right, tranFiringFreq);
return merge(left, right, tranFiringFreq);
}
private LinkedList<LpnTransitionPair> merge(LinkedList<LpnTransitionPair> left,
LinkedList<LpnTransitionPair> right, HashMap<LpnTransitionPair, Integer> tranFiringFreq) {
LinkedList<LpnTransitionPair> result = new LinkedList<LpnTransitionPair>();
while (left.size() > 0 || right.size() > 0) {
if (left.size() > 0 && right.size() > 0) {
if (tranFiringFreq.get(left.peek()) <= tranFiringFreq.get(right.peek())) {
result.addLast(left.poll());
}
else {
result.addLast(right.poll());
}
}
else if (left.size()>0) {
result.addLast(left.poll());
}
else if (right.size()>0) {
result.addLast(right.poll());
}
}
return result;
}
/**
* Return the set of all LPN transitions that are enabled in 'state'. The "init" flag indicates whether a transition
* needs to be evaluated.
* @param nextState
* @param stateStackTop
* @param enable
* @param disableByStealingToken
* @param disable
* @param init
* @param cycleClosingMthdIndex
* @param lpnIndex
* @param isNextState
* @return
*/
public LpnTranList getAmpleRefinedCycleRule(State[] curStateArray, State[] nextStateArray, HashMap<LpnTransitionPair,StaticSets> staticSetsMap,
boolean init, HashMap<LpnTransitionPair,Integer> tranFiringFreq, StateGraph[] sgList,
HashSet<PrjState> stateStack, PrjState stateStackTop) {
// AmpleSet nextAmple = new AmpleSet();
// if (nextState == null) {
// throw new NullPointerException();
// if(ampleSetTbl.containsKey(nextState) == true && stateOnStack(nextState, stateStack)) {
// System.out.println("~~~~~~~ existing state in enabledSetTbl and on stateStack: S" + nextState.getIndex() + "~~~~~~~~");
// printTransitionSet((LpnTranList)ampleSetTbl.get(nextState), "Old ample at this state: ");
// // Cycle closing check
// LpnTranList nextAmpleTransOld = (LpnTranList) nextAmple.getAmpleSet();
// nextAmpleTransOld = ampleSetTbl.get(nextState);
// LpnTranList curAmpleTrans = ampleSetTbl.get(curState);
// LpnTranList curReduced = new LpnTranList();
// LpnTranList curEnabled = curState.getEnabledTransitions();
// for (int i=0; i<curEnabled.size(); i++) {
// if (!curAmpleTrans.contains(curEnabled.get(i))) {
// curReduced.add(curEnabled.get(i));
// if (!nextAmpleTransOld.containsAll(curReduced)) {
// System.out.println("((((((((((((((((((((()))))))))))))))))))))");
// printTransitionSet(curEnabled, "curEnabled:");
// printTransitionSet(curAmpleTrans, "curAmpleTrans:");
// printTransitionSet(curReduced, "curReduced:");
// printTransitionSet(nextState.getEnabledTransitions(), "nextEnabled:");
// printTransitionSet(nextAmpleTransOld, "nextAmpleTransOld:");
// nextAmple.setAmpleChanged();
// HashSet<LpnTransitionPair> curEnabledIndicies = new HashSet<LpnTransitionPair>();
// for (int i=0; i<curEnabled.size(); i++) {
// curEnabledIndicies.add(curEnabled.get(i).getIndex());
// // transToAdd = curReduced - nextAmpleOld
// LpnTranList overlyReducedTrans = getSetSubtraction(curReduced, nextAmpleTransOld);
// HashSet<Integer> transToAddIndices = new HashSet<Integer>();
// for (int i=0; i<overlyReducedTrans.size(); i++) {
// transToAddIndices.add(overlyReducedTrans.get(i).getIndex());
// HashSet<Integer> nextAmpleNewIndices = (HashSet<Integer>) curEnabledIndicies.clone();
// for (Integer tranToAdd : transToAddIndices) {
// HashSet<LpnTransitionPair> dependent = new HashSet<LpnTransitionPair>();
// //Transition enabledTransition = this.lpn.getAllTransitions()[tranToAdd];
// dependent = getDependentSet(curState,tranToAdd,dependent,curEnabledIndicies,staticMap);
// // printIntegerSet(dependent, "dependent set for enabled transition " + this.lpn.getAllTransitions()[enabledTran]);
// boolean dependentOnlyHasDummyTrans = true;
// for (Integer curTranIndex : dependent) {
// Transition curTran = this.lpn.getAllTransitions()[curTranIndex];
// dependentOnlyHasDummyTrans = dependentOnlyHasDummyTrans && isDummyTran(curTran.getName());
// if (dependent.size() < nextAmpleNewIndices.size() && !dependentOnlyHasDummyTrans)
// nextAmpleNewIndices = (HashSet<Integer>) dependent.clone();
// if (nextAmpleNewIndices.size() == 1)
// break;
// LpnTranList nextAmpleNew = new LpnTranList();
// for (Integer nextAmpleNewIndex : nextAmpleNewIndices) {
// nextAmpleNew.add(this.getLpn().getTransition(nextAmpleNewIndex));
// LpnTranList transToAdd = getSetSubtraction(nextAmpleNew, nextAmpleTransOld);
// boolean allTransToAddFired = false;
// if (cycleClosingMthdIndex == 2) {
// // For every transition t in transToAdd, if t was fired in the any state on stateStack, there is no need to put it to the new ample of nextState.
// if (transToAdd != null) {
// LpnTranList transToAddCopy = transToAdd.copy();
// HashSet<Integer> stateVisited = new HashSet<Integer>();
// stateVisited.add(nextState.getIndex());
// allTransToAddFired = allTransToAddFired(transToAddCopy,
// allTransToAddFired, stateVisited, stateStackTop, lpnIndex);
// // Update the old ample of the next state
// if (!allTransToAddFired || cycleClosingMthdIndex == 1) {
// nextAmple.getAmpleSet().clear();
// nextAmple.getAmpleSet().addAll(transToAdd);
// ampleSetTbl.get(nextState).addAll(transToAdd);
// printTransitionSet(nextAmpleNew, "nextAmpleNew:");
// printTransitionSet(transToAdd, "transToAdd:");
// System.out.println("((((((((((((((((((((()))))))))))))))))))))");
// if (cycleClosingMthdIndex == 4) {
// nextAmple.getAmpleSet().clear();
// nextAmple.getAmpleSet().addAll(overlyReducedTrans);
// ampleSetTbl.get(nextState).addAll(overlyReducedTrans);
// printTransitionSet(nextAmpleNew, "nextAmpleNew:");
// printTransitionSet(transToAdd, "transToAdd:");
// System.out.println("((((((((((((((((((((()))))))))))))))))))))");
// // enabledSetTble stores the ample set at curState.
// // The fully enabled set at each state is stored in the tranVector in each state.
// return (AmpleSet) nextAmple;
// for (State s : nextStateArray)
// if (s == null)
// throw new NullPointerException();
// cachedNecessarySets.clear();
// String cycleClosingMthd = Options.getCycleClosingMthd();
// AmpleSet nextAmple = new AmpleSet();
// HashSet<LpnTransitionPair> nextEnabled = new HashSet<LpnTransitionPair>();
//// boolean allEnabledAreSticky = false;
// for (int lpnIndex=0; lpnIndex<nextStateArray.length; lpnIndex++) {
// State nextState = nextStateArray[lpnIndex];
// if (init) {
// LhpnFile curLpn = sgList[lpnIndex].getLpn();
// //allEnabledAreSticky = true;
// for (int i=0; i < curLpn.getAllTransitions().length; i++) {
// Transition tran = curLpn.getAllTransitions()[i];
// if (sgList[lpnIndex].isEnabled(tran,nextState)){
// nextEnabled.add(new LpnTransitionPair(curLpn.getLpnIndex(), i));
// //allEnabledAreSticky = allEnabledAreSticky && tran.isSticky();
// //sgList[lpnIndex].getEnabledSetTbl().put(nextStateArray[lpnIndex], new LpnTranList());
// else {
// LhpnFile curLpn = sgList[lpnIndex].getLpn();
// for (int i=0; i < curLpn.getAllTransitions().length; i++) {
// Transition tran = curLpn.getAllTransitions()[i];
// if (nextStateArray[lpnIndex].getTranVector()[i]) {
// nextEnabled.add(new LpnTransitionPair(curLpn.getLpnIndex(), i));
// //allEnabledAreSticky = allEnabledAreSticky && tran.isSticky();
// //sgList[lpnIndex].getEnabledSetTbl().put(nextStateArray[lpnIndex], new LpnTranList());
// DependentSetComparator depComp = new DependentSetComparator(tranFiringFreq);
// PriorityQueue<DependentSet> dependentSetQueue = new PriorityQueue<DependentSet>(nextEnabled.size(), depComp);
// LhpnFile[] lpnList = new LhpnFile[sgList.length];
// for (int i=0; i<sgList.length; i++)
// lpnList[i] = sgList[i].getLpn();
// HashMap<LpnTransitionPair, LpnTranList> transToAddMap = new HashMap<LpnTransitionPair, LpnTranList>();
// Integer cycleClosingLpnIndex = -1;
// for (int lpnIndex=0; lpnIndex<nextStateArray.length; lpnIndex++) {
// State curState = curStateArray[lpnIndex];
// State nextState = nextStateArray[lpnIndex];
// if(sgList[lpnIndex].getEnabledSetTbl().containsKey(nextState) == true
// && !sgList[lpnIndex].getEnabledSetTbl().get(nextState).isEmpty()
// && stateOnStack(lpnIndex, nextState, stateStack)
// && nextState.getIndex() != curState.getIndex()) {
// cycleClosingLpnIndex = lpnIndex;
// System.out.println("~~~~~~~ existing state in enabledSetTbl for LPN " + sgList[lpnIndex].getLpn().getLabel() +": S" + nextState.getIndex() + "~~~~~~~~");
// printAmpleSet((LpnTranList)sgList[lpnIndex].getEnabledSetTbl().get(nextState), "Old ample at this state: ");
// LpnTranList oldLocalNextAmpleTrans = sgList[lpnIndex].getEnabledSetTbl().get(nextState);
// LpnTranList curLocalAmpleTrans = sgList[lpnIndex].getEnabledSetTbl().get(curState);
// LpnTranList reducedLocalTrans = new LpnTranList();
// LpnTranList curLocalEnabledTrans = curState.getEnabledTransitions();
// System.out.println("The firedTran is a cycle closing transition.");
// if (cycleClosingMthd.toLowerCase().equals("behavioral") || cycleClosingMthd.toLowerCase().equals("state_search")) {
// // firedTran is a cycle closing transition.
// for (int i=0; i<curLocalEnabledTrans.size(); i++) {
// if (!curLocalAmpleTrans.contains(curLocalEnabledTrans.get(i))) {
// reducedLocalTrans.add(curLocalEnabledTrans.get(i));
// if (!oldLocalNextAmpleTrans.containsAll(reducedLocalTrans)) {
// printTransitionSet(curLocalEnabledTrans, "curLocalEnabled:");
// printTransitionSet(curLocalAmpleTrans, "curAmpleTrans:");
// printTransitionSet(reducedLocalTrans, "reducedLocalTrans:");
// printTransitionSet(nextState.getEnabledTransitions(), "nextLocalEnabled:");
// printTransitionSet(oldLocalNextAmpleTrans, "nextAmpleTransOld:");
// // nextAmple.setAmpleChanged();
// // ignoredTrans should not be empty here.
// LpnTranList ignoredTrans = getSetSubtraction(reducedLocalTrans, oldLocalNextAmpleTrans);
// HashSet<LpnTransitionPair> ignored = new HashSet<LpnTransitionPair>();
// for (int i=0; i<ignoredTrans.size(); i++) {
// ignored.add(new LpnTransitionPair(lpnIndex, ignoredTrans.get(i).getIndex()));
// HashSet<LpnTransitionPair> newNextAmple = (HashSet<LpnTransitionPair>) nextEnabled.clone();
// if (cycleClosingMthd.toLowerCase().equals("behavioral")) {
// for (LpnTransitionPair seed : ignored) {
// HashSet<LpnTransitionPair> dependent = new HashSet<LpnTransitionPair>();
// dependent = computeDependent(nextStateArray,seed,dependent,nextEnabled,staticSetsMap, lpnList);
// printIntegerSet(dependent, sgList, "dependent set for ignored transition " + sgList[seed.getLpnIndex()].getLpn().getLabel()
// + "(" + sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName() + ")");
// boolean dependentOnlyHasDummyTrans = true;
// for (LpnTransitionPair dependentTran : dependent) {
// dependentOnlyHasDummyTrans = dependentOnlyHasDummyTrans
// && isDummyTran(sgList[dependentTran.getLpnIndex()].getLpn().getTransition(dependentTran.getTranIndex()).getName());
// if (dependent.size() < newNextAmple.size() && !dependentOnlyHasDummyTrans)
// newNextAmple = (HashSet<LpnTransitionPair>) dependent.clone();
//// if (nextAmpleNewIndices.size() == 1)
//// break;
// DependentSet dependentSet = new DependentSet(newNextAmple, seed,
// isDummyTran(sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName()));
// dependentSetQueue.add(dependentSet);
// LpnTranList newLocalNextAmpleTrans = new LpnTranList();
// for (LpnTransitionPair tran : newNextAmple) {
// if (tran.getLpnIndex() == lpnIndex)
// newLocalNextAmpleTrans.add(sgList[lpnIndex].getLpn().getTransition(tran.getTranIndex()));
// LpnTranList transToAdd = getSetSubtraction(newLocalNextAmpleTrans, oldLocalNextAmpleTrans);
// transToAddMap.put(seed, transToAdd);
// else if (cycleClosingMthd.toLowerCase().equals("state_search")) {
// // For every transition t in ignored, if t was fired in any state on stateStack, there is no need to put it to the new ample of nextState.
// HashSet<Integer> stateVisited = new HashSet<Integer>();
// stateVisited.add(nextState.getIndex());
// LpnTranList trulyIgnoredTrans = ignoredTrans.copy();
// trulyIgnoredTrans = allIgnoredTransFired(trulyIgnoredTrans, stateVisited, stateStackTop, lpnIndex, sgList[lpnIndex]);
// if (!trulyIgnoredTrans.isEmpty()) {
// HashSet<LpnTransitionPair> trulyIgnored = new HashSet<LpnTransitionPair>();
// for (Transition tran : trulyIgnoredTrans) {
// trulyIgnored.add(new LpnTransitionPair(tran.getLpn().getLpnIndex(), tran.getIndex()));
// for (LpnTransitionPair seed : trulyIgnored) {
// HashSet<LpnTransitionPair> dependent = new HashSet<LpnTransitionPair>();
// dependent = computeDependent(nextStateArray,seed,dependent,nextEnabled,staticSetsMap, lpnList);
// printIntegerSet(dependent, sgList, "dependent set for trulyIgnored transition " + sgList[seed.getLpnIndex()].getLpn().getLabel()
// + "(" + sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName() + ")");
// boolean dependentOnlyHasDummyTrans = true;
// for (LpnTransitionPair dependentTran : dependent) {
// dependentOnlyHasDummyTrans = dependentOnlyHasDummyTrans
// && isDummyTran(sgList[dependentTran.getLpnIndex()].getLpn().getTransition(dependentTran.getTranIndex()).getName());
// if (dependent.size() < newNextAmple.size() && !dependentOnlyHasDummyTrans)
// newNextAmple = (HashSet<LpnTransitionPair>) dependent.clone();
// DependentSet dependentSet = new DependentSet(newNextAmple, seed,
// isDummyTran(sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName()));
// dependentSetQueue.add(dependentSet);
// LpnTranList newLocalNextAmpleTrans = new LpnTranList();
// for (LpnTransitionPair tran : newNextAmple) {
// if (tran.getLpnIndex() == lpnIndex)
// newLocalNextAmpleTrans.add(sgList[lpnIndex].getLpn().getTransition(tran.getTranIndex()));
// LpnTranList transToAdd = getSetSubtraction(newLocalNextAmpleTrans, oldLocalNextAmpleTrans);
// transToAddMap.put(seed, transToAdd);
// else { // All ignored transitions were fired before. It is safe to close the current cycle.
// HashSet<LpnTransitionPair> oldLocalNextAmple = new HashSet<LpnTransitionPair>();
// for (Transition tran : oldLocalNextAmpleTrans)
// oldLocalNextAmple.add(new LpnTransitionPair(tran.getLpn().getLpnIndex(), tran.getIndex()));
// for (LpnTransitionPair seed : oldLocalNextAmple) {
// HashSet<LpnTransitionPair> dependent = new HashSet<LpnTransitionPair>();
// dependent = computeDependent(nextStateArray,seed,dependent,nextEnabled,staticSetsMap, lpnList);
// printIntegerSet(dependent, sgList, "dependent set for transition in oldNextAmple is " + sgList[seed.getLpnIndex()].getLpn().getLabel()
// + "(" + sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName() + ")");
// boolean dependentOnlyHasDummyTrans = true;
// for (LpnTransitionPair dependentTran : dependent) {
// dependentOnlyHasDummyTrans = dependentOnlyHasDummyTrans
// && isDummyTran(sgList[dependentTran.getLpnIndex()].getLpn().getTransition(dependentTran.getTranIndex()).getName());
// if (dependent.size() < newNextAmple.size() && !dependentOnlyHasDummyTrans)
// newNextAmple = (HashSet<LpnTransitionPair>) dependent.clone();
// DependentSet dependentSet = new DependentSet(newNextAmple, seed,
// isDummyTran(sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName()));
// dependentSetQueue.add(dependentSet);
// else {
// // oldNextAmpleTrans.containsAll(curReducedTrans) == true (safe to close the current cycle)
// HashSet<LpnTransitionPair> newNextAmple = (HashSet<LpnTransitionPair>) nextEnabled.clone();
// HashSet<LpnTransitionPair> oldLocalNextAmple = new HashSet<LpnTransitionPair>();
// for (Transition tran : oldLocalNextAmpleTrans)
// oldLocalNextAmple.add(new LpnTransitionPair(tran.getLpn().getLpnIndex(), tran.getIndex()));
// for (LpnTransitionPair seed : oldLocalNextAmple) {
// HashSet<LpnTransitionPair> dependent = new HashSet<LpnTransitionPair>();
// dependent = computeDependent(nextStateArray,seed,dependent,nextEnabled,staticSetsMap, lpnList);
// printIntegerSet(dependent, sgList, "dependent set for transition in oldNextAmple is " + sgList[seed.getLpnIndex()].getLpn().getLabel()
// + "(" + sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName() + ")");
// boolean dependentOnlyHasDummyTrans = true;
// for (LpnTransitionPair dependentTran : dependent) {
// dependentOnlyHasDummyTrans = dependentOnlyHasDummyTrans
// && isDummyTran(sgList[dependentTran.getLpnIndex()].getLpn().getTransition(dependentTran.getTranIndex()).getName());
// if (dependent.size() < newNextAmple.size() && !dependentOnlyHasDummyTrans)
// newNextAmple = (HashSet<LpnTransitionPair>) dependent.clone();
// DependentSet dependentSet = new DependentSet(newNextAmple, seed,
// isDummyTran(sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName()));
// dependentSetQueue.add(dependentSet);
// else if (cycleClosingMthd.toLowerCase().equals("strong")) {
// LpnTranList ignoredTrans = getSetSubtraction(reducedLocalTrans, oldLocalNextAmpleTrans);
// HashSet<LpnTransitionPair> ignored = new HashSet<LpnTransitionPair>();
// for (int i=0; i<ignoredTrans.size(); i++) {
// ignored.add(new LpnTransitionPair(lpnIndex, ignoredTrans.get(i).getIndex()));
// HashSet<LpnTransitionPair> allNewNextAmple = new HashSet<LpnTransitionPair>();
// for (LpnTransitionPair seed : ignored) {
// HashSet<LpnTransitionPair> newNextAmple = (HashSet<LpnTransitionPair>) nextEnabled.clone();
// HashSet<LpnTransitionPair> dependent = new HashSet<LpnTransitionPair>();
// dependent = computeDependent(nextStateArray,seed,dependent,nextEnabled,staticSetsMap, lpnList);
// printIntegerSet(dependent, sgList, "dependent set for transition in curLocalEnabled is " + sgList[seed.getLpnIndex()].getLpn().getLabel()
// + "(" + sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName() + ")");
// boolean dependentOnlyHasDummyTrans = true;
// for (LpnTransitionPair dependentTran : dependent) {
// dependentOnlyHasDummyTrans = dependentOnlyHasDummyTrans
// && isDummyTran(sgList[dependentTran.getLpnIndex()].getLpn().getTransition(dependentTran.getTranIndex()).getName());
// if (dependent.size() < newNextAmple.size() && !dependentOnlyHasDummyTrans)
// newNextAmple = (HashSet<LpnTransitionPair>) dependent.clone();
// allNewNextAmple.addAll(newNextAmple);
// // The strong cycle condition requires all seeds in ignored to be included in the allNewNextAmple, as well as dependent set for each seed.
// // So each seed should have the same new ample set.
// for (LpnTransitionPair seed : ignored) {
// DependentSet dependentSet = new DependentSet(allNewNextAmple, seed,
// isDummyTran(sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName()));
// dependentSetQueue.add(dependentSet);
// else { // firedTran is not a cycle closing transition. Compute next ample.
//// if (nextEnabled.size() == 1)
//// return nextEnabled;
// System.out.println("The firedTran is NOT a cycle closing transition.");
// HashSet<LpnTransitionPair> ready = null;
// for (LpnTransitionPair seed : nextEnabled) {
// System.out.println("@ partialOrderReduction, consider transition " + sgList[seed.getLpnIndex()].getLpn().getLabel()
// + "("+ sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()) + ")");
// HashSet<LpnTransitionPair> dependent = new HashSet<LpnTransitionPair>();
// Transition enabledTransition = sgList[seed.getLpnIndex()].getLpn().getAllTransitions()[seed.getTranIndex()];
// boolean enabledIsDummy = false;
//// if (enabledTransition.isSticky()) {
//// dependent = (HashSet<LpnTransitionPair>) nextEnabled.clone();
//// else {
//// dependent = computeDependent(curStateArray,seed,dependent,nextEnabled,staticMap, lpnList);
// dependent = computeDependent(curStateArray,seed,dependent,nextEnabled,staticSetsMap,lpnList);
// printIntegerSet(dependent, sgList, "dependent set for enabled transition " + sgList[seed.getLpnIndex()].getLpn().getLabel()
// + "(" + enabledTransition.getName() + ")");
// if (isDummyTran(enabledTransition.getName()))
// enabledIsDummy = true;
// for (LpnTransitionPair inDependent : dependent) {
// if(inDependent.getLpnIndex() == cycleClosingLpnIndex) {
// // check cycle closing condition
// break;
// DependentSet dependentSet = new DependentSet(dependent, seed, enabledIsDummy);
// dependentSetQueue.add(dependentSet);
// ready = dependentSetQueue.poll().getDependent();
//// // Update the old ample of the next state
//// boolean allTransToAddFired = false;
//// if (cycleClosingMthdIndex == 2) {
//// // For every transition t in transToAdd, if t was fired in the any state on stateStack, there is no need to put it to the new ample of nextState.
//// if (transToAdd != null) {
//// LpnTranList transToAddCopy = transToAdd.copy();
//// HashSet<Integer> stateVisited = new HashSet<Integer>();
//// stateVisited.add(nextState.getIndex());
//// allTransToAddFired = allTransToAddFired(transToAddCopy,
//// allTransToAddFired, stateVisited, stateStackTop, lpnIndex);
//// // Update the old ample of the next state
//// if (!allTransToAddFired || cycleClosingMthdIndex == 1) {
//// nextAmple.getAmpleSet().clear();
//// nextAmple.getAmpleSet().addAll(transToAdd);
//// ampleSetTbl.get(nextState).addAll(transToAdd);
//// printTransitionSet(nextAmpleNew, "nextAmpleNew:");
//// printTransitionSet(transToAdd, "transToAdd:");
//// System.out.println("((((((((((((((((((((()))))))))))))))))))))");
//// if (cycleClosingMthdIndex == 4) {
//// nextAmple.getAmpleSet().clear();
//// nextAmple.getAmpleSet().addAll(ignoredTrans);
//// ampleSetTbl.get(nextState).addAll(ignoredTrans);
//// printTransitionSet(nextAmpleNew, "nextAmpleNew:");
//// printTransitionSet(transToAdd, "transToAdd:");
//// System.out.println("((((((((((((((((((((()))))))))))))))))))))");
//// // enabledSetTble stores the ample set at curState.
//// // The fully enabled set at each state is stored in the tranVector in each state.
//// return (AmpleSet) nextAmple;
return null;
}
private LpnTranList allIgnoredTransFired(LpnTranList ignoredTrans,
HashSet<Integer> stateVisited, PrjState stateStackEntry, int lpnIndex, StateGraph sg) {
State state = stateStackEntry.get(lpnIndex);
System.out.println("state = " + state.getIndex());
State predecessor = stateStackEntry.getFather().get(lpnIndex);
if (predecessor != null)
System.out.println("predecessor = " + predecessor.getIndex());
if (predecessor == null || stateVisited.contains(predecessor.getIndex())) {
return ignoredTrans;
}
else
stateVisited.add(predecessor.getIndex());
LpnTranList predecessorOldAmple = sg.getEnabledSetTbl().get(predecessor);//enabledSetTbl.get(predecessor);
for (Transition oldAmpleTran : predecessorOldAmple) {
State tmpState = sg.getNextStateMap().get(predecessor).get(oldAmpleTran);
if (tmpState.getIndex() == state.getIndex()) {
ignoredTrans.remove(oldAmpleTran);
break;
}
}
if (ignoredTrans.size()==0) {
return ignoredTrans;
}
else {
ignoredTrans = allIgnoredTransFired(ignoredTrans, stateVisited, stateStackEntry.getFather(), lpnIndex, sg);
}
return ignoredTrans;
}
// for (Transition oldAmpleTran : oldAmple) {
// State successor = nextStateMap.get(nextState).get(oldAmpleTran);
// if (stateVisited.contains(successor.getIndex())) {
// break;
// else
// stateVisited.add(successor.getIndex());
// LpnTranList successorOldAmple = enabledSetTbl.get(successor);
// // Either successor or sucessorOldAmple should not be null for a nonterminal state graph.
// HashSet<Transition> transToAddFired = new HashSet<Transition>();
// for (Transition tran : transToAddCopy) {
// if (successorOldAmple.contains(tran))
// transToAddFired.add(tran);
// transToAddCopy.removeAll(transToAddFired);
// if (transToAddCopy.size() == 0) {
// allTransFired = true;
// break;
// else {
// allTransFired = allTransToAddFired(successorOldAmple, nextState, successor,
// transToAddCopy, allTransFired, stateVisited, stateStackEntry, lpnIndex);
// return allTransFired;
/**
* An iterative implement of findsg_recursive().
* @param lpnList
* @param curLocalStateArray
* @param enabledArray
*/
/**
* An iterative implement of findsg_recursive().
* @param lpnList
* @param curLocalStateArray
* @param enabledArray
*/
public Stack<State[]> search_dfs_noDisabling_fireOrder(final StateGraph[] lpnList, final State[] initStateArray) {
boolean firingOrder = false;
long peakUsedMem = 0;
long peakTotalMem = 0;
boolean failure = false;
int tranFiringCnt = 0;
int arraySize = lpnList.length;
HashSet<PrjLpnState> globalStateTbl = new HashSet<PrjLpnState>();
@SuppressWarnings("unchecked")
IndexObjMap<LpnState>[] lpnStateCache = new IndexObjMap[arraySize];
//HashMap<LpnState, LpnState>[] lpnStateCache1 = new HashMap[arraySize];
Stack<LpnState[]> stateStack = new Stack<LpnState[]>();
Stack<LpnTranList[]> lpnTranStack = new Stack<LpnTranList[]>();
//get initial enable transition set
LpnTranList initEnabled = new LpnTranList();
LpnTranList initFireFirst = new LpnTranList();
LpnState[] initLpnStateArray = new LpnState[arraySize];
for (int i = 0; i < arraySize; i++)
{
lpnStateCache[i] = new IndexObjMap<LpnState>();
LinkedList<Transition> enabledTrans = lpnList[i].getEnabled(initStateArray[i]);
HashSet<Transition> enabledSet = new HashSet<Transition>();
if(!enabledTrans.isEmpty())
{
for(Transition tran : enabledTrans) {
enabledSet.add(tran);
initEnabled.add(tran);
}
}
LpnState curLpnState = new LpnState(lpnList[i].getLpn(), initStateArray[i], enabledSet);
lpnStateCache[i].add(curLpnState);
initLpnStateArray[i] = curLpnState;
}
LpnTranList[] initEnabledSet = new LpnTranList[2];
initEnabledSet[0] = initFireFirst;
initEnabledSet[1] = initEnabled;
lpnTranStack.push(initEnabledSet);
stateStack.push(initLpnStateArray);
globalStateTbl.add(new PrjLpnState(initLpnStateArray));
main_while_loop: while (failure == false && stateStack.empty() == false) {
long curTotalMem = Runtime.getRuntime().totalMemory();
long curUsedMem = Runtime.getRuntime().totalMemory()
- Runtime.getRuntime().freeMemory();
if (curTotalMem > peakTotalMem)
peakTotalMem = curTotalMem;
if (curUsedMem > peakUsedMem)
peakUsedMem = curUsedMem;
if (stateStack.size() > max_stack_depth)
max_stack_depth = stateStack.size();
iterations++;
//if(iterations>2)break;
if (iterations % 100000 == 0)
System.out.println("---> #iteration " + iterations
+ "> # LPN transition firings: " + tranFiringCnt
+ ", # of prjStates found: " + globalStateTbl.size()
+ ", current_stack_depth: " + stateStack.size()
+ ", total MDD nodes: " + mddMgr.nodeCnt()
+ " used memory: " + (float) curUsedMem / 1000000
+ " free memory: "
+ (float) Runtime.getRuntime().freeMemory() / 1000000);
LpnTranList[] curEnabled = lpnTranStack.peek();
LpnState[] curLpnStateArray = stateStack.peek();
// If all enabled transitions of the current LPN are considered,
// then consider the next LPN
// by increasing the curIndex.
// Otherwise, if all enabled transitions of all LPNs are considered,
// then pop the stacks.
if(curEnabled[0].size()==0 && curEnabled[1].size()==0){
lpnTranStack.pop();
stateStack.pop();
continue;
}
Transition firedTran = null;
if(curEnabled[0].size() != 0)
firedTran = curEnabled[0].removeFirst();
else
firedTran = curEnabled[1].removeFirst();
traceCex.addLast(firedTran);
State[] curStateArray = new State[arraySize];
for( int i = 0; i < arraySize; i++)
curStateArray[i] = curLpnStateArray[i].getState();
StateGraph sg = null;
for (int i=0; i<lpnList.length; i++) {
if (lpnList[i].getLpn().equals(firedTran.getLpn())) {
sg = lpnList[i];
}
}
State[] nextStateArray = sg.fire(lpnList, curStateArray, firedTran);
// Check if the firedTran causes disabling error or deadlock.
@SuppressWarnings("unchecked")
HashSet<Transition>[] extendedNextEnabledArray = new HashSet[arraySize];
for (int i = 0; i < arraySize; i++) {
HashSet<Transition> curEnabledSet = curLpnStateArray[i].getEnabled();
LpnTranList nextEnabledList = lpnList[i].getEnabled(nextStateArray[i]);
HashSet<Transition> nextEnabledSet = new HashSet<Transition>();
for(Transition tran : nextEnabledList) {
nextEnabledSet.add(tran);
}
extendedNextEnabledArray[i] = nextEnabledSet;
//non_disabling
for(Transition curTran : curEnabledSet) {
if(curTran == firedTran)
continue;
if(nextEnabledSet.contains(curTran) == false) {
int[] nextMarking = nextStateArray[i].getMarking();
// Not sure if the code below is correct.
int[] preset = lpnList[i].getLpn().getPresetIndex(curTran.getName());
boolean included = true;
if (preset != null && preset.length > 0) {
for (int pp : preset) {
boolean temp = false;
for (int mi = 0; mi < nextMarking.length; mi++) {
if (nextMarking[mi] == pp) {
temp = true;
break;
}
}
if (temp == false)
{
included = false;
break;
}
}
}
if(preset==null || preset.length==0 || included==true) {
extendedNextEnabledArray[i].add(curTran);
}
}
}
}
boolean deadlock=true;
for(int i = 0; i < arraySize; i++) {
if(extendedNextEnabledArray[i].size() != 0){
deadlock = false;
break;
}
}
if(deadlock==true) {
failure = true;
break main_while_loop;
}
// Add nextPrjState into prjStateSet
// If nextPrjState has been traversed before, skip to the next
// enabled transition.
LpnState[] nextLpnStateArray = new LpnState[arraySize];
for(int i = 0; i < arraySize; i++) {
HashSet<Transition> lpnEnabledSet = new HashSet<Transition>();
for(Transition tran : extendedNextEnabledArray[i]) {
lpnEnabledSet.add(tran);
}
LpnState tmp = new LpnState(lpnList[i].getLpn(), nextStateArray[i], lpnEnabledSet);
LpnState tmpCached = (LpnState)(lpnStateCache[i].add(tmp));
nextLpnStateArray[i] = tmpCached;
}
boolean newState = globalStateTbl.add(new PrjLpnState(nextLpnStateArray));
if(newState == false) {
traceCex.removeLast();
continue;
}
stateStack.push(nextLpnStateArray);
LpnTranList[] nextEnabledSet = new LpnTranList[2];
LpnTranList fireFirstTrans = new LpnTranList();
LpnTranList otherTrans = new LpnTranList();
for(int i = 0; i < arraySize; i++)
{
for(Transition tran : nextLpnStateArray[i].getEnabled())
{
if(firingOrder == true)
if(curLpnStateArray[i].getEnabled().contains(tran))
otherTrans.add(tran);
else
fireFirstTrans.add(tran);
else
fireFirstTrans.add(tran);
}
}
nextEnabledSet[0] = fireFirstTrans;
nextEnabledSet[1] = otherTrans;
lpnTranStack.push(nextEnabledSet);
}// END while (stateStack.empty() == false)
// graph.write(String.format("graph_%s_%s-tran_%s-state.gv",mode,tranFiringCnt,
// prjStateSet.size()));
System.out.println("SUMMARY: # LPN transition firings: "
+ tranFiringCnt + ", # of prjStates found: "
+ globalStateTbl.size() + ", max_stack_depth: " + max_stack_depth);
/*
* by looking at stateStack, generate the trace showing the counter-example.
*/
if (failure == true) {
System.out.println("
System.out.println("the deadlock trace:");
//update traceCex from stateStack
// LpnState[] cur = null;
// LpnState[] next = null;
for(Transition tran : traceCex)
System.out.println(tran.getFullLabel());
}
System.out.println("Modules' local states: ");
for (int i = 0; i < arraySize; i++) {
System.out.println("module " + lpnList[i].getLpn().getLabel() + ": "
+ lpnList[i].reachSize());
}
return null;
}
/**
* findsg using iterative approach based on DFS search. The states found are
* stored in MDD.
*
* When a state is considered during DFS, only one enabled transition is
* selected to fire in an iteration.
*
* @param lpnList
* @param curLocalStateArray
* @param enabledArray
* @return a linked list of a sequence of LPN transitions leading to the
* failure if it is not empty.
*/
public Stack<State[]> search_dfs_mdd_1(final StateGraph[] lpnList, final State[] initStateArray) {
System.out.println("---> calling function search_dfs_mdd_1");
long peakUsedMem = 0;
long peakTotalMem = 0;
long peakMddNodeCnt = 0;
int memUpBound = 500; // Set an upper bound of memory in MB usage to
// trigger MDD compression.
boolean compressed = false;
boolean failure = false;
int tranFiringCnt = 0;
int totalStates = 1;
int arraySize = lpnList.length;
int newStateCnt = 0;
Stack<State[]> stateStack = new Stack<State[]>();
Stack<LinkedList<Transition>> lpnTranStack = new Stack<LinkedList<Transition>>();
Stack<Integer> curIndexStack = new Stack<Integer>();
mddNode reachAll = null;
mddNode reach = mddMgr.newNode();
int[] localIdxArray = Analysis.getLocalStateIdxArray(lpnList, initStateArray, true);
mddMgr.add(reach, localIdxArray, compressed);
stateStack.push(initStateArray);
LpnTranList initEnabled = lpnList[0].getEnabled(initStateArray[0]);
lpnTranStack.push(initEnabled.clone());
curIndexStack.push(0);
int numMddCompression = 0;
main_while_loop: while (failure == false && stateStack.empty() == false) {
long curTotalMem = Runtime.getRuntime().totalMemory();
long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
if (curTotalMem > peakTotalMem)
peakTotalMem = curTotalMem;
if (curUsedMem > peakUsedMem)
peakUsedMem = curUsedMem;
if (stateStack.size() > max_stack_depth)
max_stack_depth = stateStack.size();
iterations++;
if (iterations % 100000 == 0) {
long curMddNodeCnt = mddMgr.nodeCnt();
peakMddNodeCnt = peakMddNodeCnt > curMddNodeCnt ? peakMddNodeCnt : curMddNodeCnt;
System.out.println("---> #iteration " + iterations
+ "> # LPN transition firings: " + tranFiringCnt
+ ", # of prjStates found: " + totalStates
+ ", stack depth: " + stateStack.size()
+ ", total MDD nodes: " + curMddNodeCnt
+ " used memory: " + (float) curUsedMem / 1000000
+ " free memory: "
+ (float) Runtime.getRuntime().freeMemory() / 1000000);
if (curUsedMem >= memUpBound * 1000000) {
mddMgr.compress(reach);
numMddCompression++;
if (reachAll == null)
reachAll = reach;
else {
mddNode newReachAll = mddMgr.union(reachAll, reach);
if (newReachAll != reachAll) {
mddMgr.remove(reachAll);
reachAll = newReachAll;
}
}
mddMgr.remove(reach);
reach = mddMgr.newNode();
if(memUpBound < 1500)
memUpBound *= numMddCompression;
}
}
State[] curStateArray = stateStack.peek();
int curIndex = curIndexStack.peek();
LinkedList<Transition> curEnabled = lpnTranStack.peek();
// If all enabled transitions of the current LPN are considered,
// then consider the next LPN
// by increasing the curIndex.
// Otherwise, if all enabled transitions of all LPNs are considered,
// then pop the stacks.
if (curEnabled.size() == 0) {
lpnTranStack.pop();
curIndexStack.pop();
curIndex++;
while (curIndex < arraySize) {
LpnTranList enabledCached = (lpnList[curIndex].getEnabled(curStateArray[curIndex]));
if (enabledCached.size() > 0) {
curEnabled = enabledCached.clone();
lpnTranStack.push(curEnabled);
curIndexStack.push(curIndex);
break;
} else
curIndex++;
}
}
if (curIndex == arraySize) {
stateStack.pop();
continue;
}
Transition firedTran = curEnabled.removeLast();
State[] nextStateArray = lpnList[curIndex].fire(lpnList, curStateArray,firedTran);
tranFiringCnt++;
// Check if the firedTran causes disabling error or deadlock.
LinkedList<Transition>[] curEnabledArray = new LinkedList[arraySize];
LinkedList<Transition>[] nextEnabledArray = new LinkedList[arraySize];
for (int i = 0; i < arraySize; i++) {
StateGraph lpn_tmp = lpnList[i];
LinkedList<Transition> enabledList = lpn_tmp.getEnabled(curStateArray[i]);
curEnabledArray[i] = enabledList;
enabledList = lpn_tmp.getEnabled(nextStateArray[i]);
nextEnabledArray[i] = enabledList;
Transition disabledTran = firedTran.disablingError(
curEnabledArray[i], nextEnabledArray[i]);
if (disabledTran != null) {
System.err.println("Disabling Error: "
+ disabledTran.getFullLabel() + " is disabled by "
+ firedTran.getFullLabel());
failure = true;
break main_while_loop;
}
}
if (Analysis.deadLock(lpnList, nextStateArray) == true) {
failure = true;
break main_while_loop;
}
/*
* Check if the local indices of nextStateArray already exist.
* if not, add it into reachable set, and push it onto stack.
*/
localIdxArray = Analysis.getLocalStateIdxArray(lpnList, nextStateArray, true);
Boolean existingState = false;
if (reachAll != null && mddMgr.contains(reachAll, localIdxArray) == true)
existingState = true;
else if (mddMgr.contains(reach, localIdxArray) == true)
existingState = true;
if (existingState == false) {
mddMgr.add(reach, localIdxArray, compressed);
newStateCnt++;
stateStack.push(nextStateArray);
lpnTranStack.push((LpnTranList) nextEnabledArray[0].clone());
curIndexStack.push(0);
totalStates++;
}
}
double totalStateCnt = mddMgr.numberOfStates(reach);
System.out.println("---> run statistics: \n"
+ "# LPN transition firings: " + tranFiringCnt + "\n"
+ "# of prjStates found: " + totalStateCnt + "\n"
+ "max_stack_depth: " + max_stack_depth + "\n"
+ "peak MDD nodes: " + peakMddNodeCnt + "\n"
+ "peak used memory: " + peakUsedMem / 1000000 + " MB\n"
+ "peak total memory: " + peakTotalMem / 1000000 + " MB\n");
return null;
}
/**
* findsg using iterative approach based on DFS search. The states found are
* stored in MDD.
*
* It is similar to findsg_dfs_mdd_1 except that when a state is considered
* during DFS, all enabled transition are fired, and all its successor
* states are found in an iteration.
*
* @param lpnList
* @param curLocalStateArray
* @param enabledArray
* @return a linked list of a sequence of LPN transitions leading to the
* failure if it is not empty.
*/
public Stack<State[]> search_dfs_mdd_2(final StateGraph[] lpnList, final State[] initStateArray) {
System.out.println("---> calling function search_dfs_mdd_2");
int tranFiringCnt = 0;
int totalStates = 0;
int arraySize = lpnList.length;
long peakUsedMem = 0;
long peakTotalMem = 0;
long peakMddNodeCnt = 0;
int memUpBound = 1000; // Set an upper bound of memory in MB usage to
// trigger MDD compression.
boolean failure = false;
MDT state2Explore = new MDT(arraySize);
state2Explore.push(initStateArray);
totalStates++;
long peakState2Explore = 0;
Stack<Integer> searchDepth = new Stack<Integer>();
searchDepth.push(1);
boolean compressed = false;
mddNode reachAll = null;
mddNode reach = mddMgr.newNode();
main_while_loop:
while (failure == false && state2Explore.empty() == false) {
long curTotalMem = Runtime.getRuntime().totalMemory();
long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
if (curTotalMem > peakTotalMem)
peakTotalMem = curTotalMem;
if (curUsedMem > peakUsedMem)
peakUsedMem = curUsedMem;
iterations++;
if (iterations % 100000 == 0) {
int mddNodeCnt = mddMgr.nodeCnt();
peakMddNodeCnt = peakMddNodeCnt > mddNodeCnt ? peakMddNodeCnt : mddNodeCnt;
int state2ExploreSize = state2Explore.size();
peakState2Explore = peakState2Explore > state2ExploreSize ? peakState2Explore : state2ExploreSize;
System.out.println("---> #iteration " + iterations
+ "> # LPN transition firings: " + tranFiringCnt
+ ", # of prjStates found: " + totalStates
+ ", # states to explore: " + state2ExploreSize
+ ", # MDT nodes: " + state2Explore.nodeCnt()
+ ", total MDD nodes: " + mddNodeCnt
+ " used memory: " + (float) curUsedMem / 1000000
+ " free memory: "
+ (float) Runtime.getRuntime().freeMemory() / 1000000);
if (curUsedMem >= memUpBound * 1000000) {
mddMgr.compress(reach);
if (reachAll == null)
reachAll = reach;
else {
mddNode newReachAll = mddMgr.union(reachAll, reach);
if (newReachAll != reachAll) {
mddMgr.remove(reachAll);
reachAll = newReachAll;
}
}
mddMgr.remove(reach);
reach = mddMgr.newNode();
}
}
State[] curStateArray = state2Explore.pop();
State[] nextStateArray = null;
int states2ExploreCurLevel = searchDepth.pop();
if(states2ExploreCurLevel > 1)
searchDepth.push(states2ExploreCurLevel-1);
int[] localIdxArray = Analysis.getLocalStateIdxArray(lpnList, curStateArray, false);
mddMgr.add(reach, localIdxArray, compressed);
int nextStates2Explore = 0;
for (int index = arraySize - 1; index >= 0; index
StateGraph curLpn = lpnList[index];
State curState = curStateArray[index];
LinkedList<Transition> curEnabledSet = curLpn.getEnabled(curState);
LpnTranList curEnabled = (LpnTranList) curEnabledSet.clone();
while (curEnabled.size() > 0) {
Transition firedTran = curEnabled.removeLast();
// TODO: (check) Not sure if curLpn.fire is correct.
nextStateArray = curLpn.fire(lpnList, curStateArray, firedTran);
tranFiringCnt++;
for (int i = 0; i < arraySize; i++) {
StateGraph lpn_tmp = lpnList[i];
if (curStateArray[i] == nextStateArray[i])
continue;
LinkedList<Transition> curEnabled_l = lpn_tmp.getEnabled(curStateArray[i]);
LinkedList<Transition> nextEnabled = lpn_tmp.getEnabled(nextStateArray[i]);
Transition disabledTran = firedTran.disablingError(curEnabled_l, nextEnabled);
if (disabledTran != null) {
System.err.println("Verification failed: disabling error: "
+ disabledTran.getFullLabel()
+ " disabled by "
+ firedTran.getFullLabel() + "!!!");
failure = true;
break main_while_loop;
}
}
if (Analysis.deadLock(lpnList, nextStateArray) == true) {
System.err.println("Verification failed: deadlock.");
failure = true;
break main_while_loop;
}
/*
* Check if the local indices of nextStateArray already exist.
*/
localIdxArray = Analysis.getLocalStateIdxArray(lpnList, nextStateArray, false);
Boolean existingState = false;
if (reachAll != null && mddMgr.contains(reachAll, localIdxArray) == true)
existingState = true;
else if (mddMgr.contains(reach, localIdxArray) == true)
existingState = true;
else if(state2Explore.contains(nextStateArray)==true)
existingState = true;
if (existingState == false) {
totalStates++;
//mddMgr.add(reach, localIdxArray, compressed);
state2Explore.push(nextStateArray);
nextStates2Explore++;
}
}
}
if(nextStates2Explore > 0)
searchDepth.push(nextStates2Explore);
}
endoffunction: System.out.println("
+ "---> run statistics: \n"
+ " # Depth of search (Length of Cex): " + searchDepth.size() + "\n"
+ " # LPN transition firings: " + (double)tranFiringCnt/1000000 + " M\n"
+ " # of prjStates found: " + (double)totalStates / 1000000 + " M\n"
+ " peak states to explore : " + (double) peakState2Explore / 1000000 + " M\n"
+ " peak MDD nodes: " + peakMddNodeCnt + "\n"
+ " peak used memory: " + peakUsedMem / 1000000 + " MB\n"
+ " peak total memory: " + peakTotalMem /1000000 + " MB\n"
+ "_____________________________________");
return null;
}
public LinkedList<Transition> search_bfs(final StateGraph[] sgList, final State[] initStateArray) {
System.out.println("---> starting search_bfs");
long peakUsedMem = 0;
long peakTotalMem = 0;
long peakMddNodeCnt = 0;
int memUpBound = 1000; // Set an upper bound of memory in MB usage to
// trigger MDD compression.
int arraySize = sgList.length;
for (int i = 0; i < arraySize; i++)
sgList[i].addState(initStateArray[i]);
mddNode reachSet = null;
mddNode reach = mddMgr.newNode();
MDT frontier = new MDT(arraySize);
MDT image = new MDT(arraySize);
frontier.push(initStateArray);
State[] curStateArray = null;
int tranFiringCnt = 0;
int totalStates = 0;
int imageSize = 0;
boolean verifyError = false;
bfsWhileLoop: while (true) {
if (verifyError == true)
break;
long curTotalMem = Runtime.getRuntime().totalMemory();
long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
if (curTotalMem > peakTotalMem)
peakTotalMem = curTotalMem;
if (curUsedMem > peakUsedMem)
peakUsedMem = curUsedMem;
long curMddNodeCnt = mddMgr.nodeCnt();
peakMddNodeCnt = peakMddNodeCnt > curMddNodeCnt ? peakMddNodeCnt : curMddNodeCnt;
iterations++;
System.out.println("iteration " + iterations
+ "> # LPN transition firings: " + tranFiringCnt
+ ", # of prjStates found: " + totalStates
+ ", total MDD nodes: " + curMddNodeCnt
+ " used memory: " + (float) curUsedMem / 1000000
+ " free memory: "
+ (float) Runtime.getRuntime().freeMemory() / 1000000);
if (curUsedMem >= memUpBound * 1000000) {
mddMgr.compress(reach);
if (reachSet == null)
reachSet = reach;
else {
mddNode newReachSet = mddMgr.union(reachSet, reach);
if (newReachSet != reachSet) {
mddMgr.remove(reachSet);
reachSet = newReachSet;
}
}
mddMgr.remove(reach);
reach = mddMgr.newNode();
}
while(frontier.empty() == false) {
boolean deadlock = true;
// Stack<State[]> curStateArrayList = frontier.pop();
// while(curStateArrayList.empty() == false) {
// curStateArray = curStateArrayList.pop();
{
curStateArray = frontier.pop();
int[] localIdxArray = Analysis.getLocalStateIdxArray(sgList, curStateArray, false);
mddMgr.add(reach, localIdxArray, false);
totalStates++;
for (int i = 0; i < arraySize; i++) {
LinkedList<Transition> curEnabled = sgList[i].getEnabled(curStateArray[i]);
if (curEnabled.size() > 0)
deadlock = false;
for (Transition firedTran : curEnabled) {
// TODO: (check) Not sure if sgList[i].fire is correct.
State[] nextStateArray = sgList[i].fire(sgList, curStateArray, firedTran);
tranFiringCnt++;
/*
* Check if any transitions can be disabled by fireTran.
*/
LinkedList<Transition> nextEnabled = sgList[i].getEnabled(nextStateArray[i]);
Transition disabledTran = firedTran.disablingError(curEnabled, nextEnabled);
if (disabledTran != null) {
System.err.println("*** Verification failed: disabling error: "
+ disabledTran.getFullLabel()
+ " disabled by "
+ firedTran.getFullLabel() + "!!!");
verifyError = true;
break bfsWhileLoop;
}
localIdxArray = Analysis.getLocalStateIdxArray(sgList, nextStateArray, false);
if (mddMgr.contains(reachSet, localIdxArray) == false && mddMgr.contains(reach, localIdxArray) == false && frontier.contains(nextStateArray) == false) {
if(image.contains(nextStateArray)==false) {
image.push(nextStateArray);
imageSize++;
}
}
}
}
}
/*
* If curStateArray deadlocks (no enabled transitions), terminate.
*/
if (deadlock == true) {
System.err.println("*** Verification failed: deadlock.");
verifyError = true;
break bfsWhileLoop;
}
}
if(image.empty()==true) break;
System.out.println("---> size of image: " + imageSize);
frontier = image;
image = new MDT(arraySize);
imageSize = 0;
}
System.out.println("---> final numbers: # LPN transition firings: " + tranFiringCnt / 1000000 + "M\n"
+ "---> # of prjStates found: " + (double) totalStates / 1000000 + "M\n"
+ "---> peak total memory: " + peakTotalMem / 1000000F + " MB\n"
+ "---> peak used memory: " + peakUsedMem / 1000000F + " MB\n"
+ "---> peak MDD nodes: " + peakMddNodeCnt);
return null;
}
/**
* BFS findsg using iterative approach. THe states found are stored in MDD.
*
* @param lpnList
* @param curLocalStateArray
* @param enabledArray
* @return a linked list of a sequence of LPN transitions leading to the
* failure if it is not empty.
*/
public LinkedList<Transition> search_bfs_mdd_localFirings(final StateGraph[] lpnList, final State[] initStateArray) {
System.out.println("---> starting search_bfs");
long peakUsedMem = 0;
long peakTotalMem = 0;
int arraySize = lpnList.length;
for (int i = 0; i < arraySize; i++)
lpnList[i].addState(initStateArray[i]);
// mddNode reachSet = mddMgr.newNode();
// mddMgr.add(reachSet, curLocalStateArray);
mddNode reachSet = null;
mddNode exploredSet = null;
LinkedList<State>[] nextSetArray = (LinkedList<State>[]) (new LinkedList[arraySize]);
for (int i = 0; i < arraySize; i++)
nextSetArray[i] = new LinkedList<State>();
mddNode initMdd = mddMgr.doLocalFirings(lpnList, initStateArray, null);
mddNode curMdd = initMdd;
reachSet = curMdd;
mddNode nextMdd = null;
int[] curStateArray = null;
int tranFiringCnt = 0;
boolean verifyError = false;
bfsWhileLoop: while (true) {
if (verifyError == true)
break;
long curTotalMem = Runtime.getRuntime().totalMemory();
long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
if (curTotalMem > peakTotalMem)
peakTotalMem = curTotalMem;
if (curUsedMem > peakUsedMem)
peakUsedMem = curUsedMem;
curStateArray = mddMgr.next(curMdd, curStateArray);
if (curStateArray == null) {
// Break the loop if no new next states are found.
// System.out.println("nextSet size " + nextSet.size());
if (nextMdd == null)
break bfsWhileLoop;
if (exploredSet == null)
exploredSet = curMdd;
else {
mddNode newExplored = mddMgr.union(exploredSet, curMdd);
if (newExplored != exploredSet)
mddMgr.remove(exploredSet);
exploredSet = newExplored;
}
mddMgr.remove(curMdd);
curMdd = nextMdd;
nextMdd = null;
iterations++;
System.out.println("iteration " + iterations
+ "> # LPN transition firings: " + tranFiringCnt
+ ", # of union calls: " + mddNode.numCalls
+ ", # of union cache nodes: " + mddNode.cacheNodes
+ ", total MDD nodes: " + mddMgr.nodeCnt()
+ " used memory: " + (float) curUsedMem / 1000000
+ " free memory: "
+ (float) Runtime.getRuntime().freeMemory() / 1000000);
System.out.println("---> # of prjStates found: " + mddMgr.numberOfStates(reachSet)
+ ", CurSet.Size = " + mddMgr.numberOfStates(curMdd));
continue;
}
if (exploredSet != null && mddMgr.contains(exploredSet, curStateArray) == true)
continue;
// If curStateArray deadlocks (no enabled transitions), terminate.
if (Analysis.deadLock(lpnList, curStateArray) == true) {
System.err.println("*** Verification failed: deadlock.");
verifyError = true;
break bfsWhileLoop;
}
// Do firings of non-local LPN transitions.
for (int index = arraySize - 1; index >= 0; index
StateGraph curLpn = lpnList[index];
LinkedList<Transition> curLocalEnabled = curLpn.getEnabled(curStateArray[index]);
if (curLocalEnabled.size() == 0 || curLocalEnabled.getFirst().isLocal() == true)
continue;
for (Transition firedTran : curLocalEnabled) {
if (firedTran.isLocal() == true)
continue;
// TODO: (check) Not sure if curLpn.fire is correct.
State[] nextStateArray = curLpn.fire(lpnList, curStateArray, firedTran);
tranFiringCnt++;
@SuppressWarnings("unused")
ArrayList<LinkedList<Transition>> nextEnabledArray = new ArrayList<LinkedList<Transition>>(1);
for (int i = 0; i < arraySize; i++) {
if (curStateArray[i] == nextStateArray[i].getIndex())
continue;
StateGraph lpn_tmp = lpnList[i];
LinkedList<Transition> curEnabledList = lpn_tmp.getEnabled(curStateArray[i]);
LinkedList<Transition> nextEnabledList = lpn_tmp.getEnabled(nextStateArray[i].getIndex());
Transition disabledTran = firedTran.disablingError(curEnabledList, nextEnabledList);
if (disabledTran != null) {
System.err.println("Verification failed: disabling error: "
+ disabledTran.getFullLabel()
+ ": is disabled by "
+ firedTran.getFullLabel() + "!!!");
verifyError = true;
break bfsWhileLoop;
}
}
if (Analysis.deadLock(lpnList, nextStateArray) == true) {
verifyError = true;
break bfsWhileLoop;
}
// Add nextPrjState into prjStateSet
// If nextPrjState has been traversed before, skip to the
// next
// enabled transition.
int[] nextIdxArray = Analysis.getIdxArray(nextStateArray);
if (reachSet != null && mddMgr.contains(reachSet, nextIdxArray) == true)
continue;
mddNode newNextMdd = mddMgr.doLocalFirings(lpnList, nextStateArray, reachSet);
mddNode newReachSet = mddMgr.union(reachSet, newNextMdd);
if (newReachSet != reachSet)
mddMgr.remove(reachSet);
reachSet = newReachSet;
if (nextMdd == null)
nextMdd = newNextMdd;
else {
mddNode tmpNextMdd = mddMgr.union(nextMdd, newNextMdd);
if (tmpNextMdd != nextMdd)
mddMgr.remove(nextMdd);
nextMdd = tmpNextMdd;
mddMgr.remove(newNextMdd);
}
}
}
}
System.out.println("---> final numbers: # LPN transition firings: "
+ tranFiringCnt + "\n" + "---> # of prjStates found: "
+ (mddMgr.numberOfStates(reachSet)) + "\n"
+ "---> peak total memory: " + peakTotalMem / 1000000F
+ " MB\n" + "---> peak used memory: " + peakUsedMem / 1000000F
+ " MB\n" + "---> peak MMD nodes: " + mddMgr.peakNodeCnt());
return null;
}
/**
* partial order reduction
*
* @param lpnList
* @param curLocalStateArray
* @param enabledArray
*/
public Stack<State[]> search_dfs_por(final StateGraph[] lpnList, final State[] initStateArray, LPNTranRelation lpnTranRelation, String approach) {
System.out.println("---> Calling search_dfs with partial order reduction");
long peakUsedMem = 0;
long peakTotalMem = 0;
double stateCount = 1;
int max_stack_depth = 0;
int iterations = 0;
boolean useMdd = true;
mddNode reach = mddMgr.newNode();
//init por
verification.platu.por1.AmpleSet ampleClass = new verification.platu.por1.AmpleSet();
//AmpleSubset ampleClass = new AmpleSubset();
HashMap<Transition,HashSet<Transition>> indepTranSet = new HashMap<Transition,HashSet<Transition>>();
if(approach == "state")
indepTranSet = ampleClass.getIndepTranSet_FromState(lpnList, lpnTranRelation);
else if (approach == "lpn")
indepTranSet = ampleClass.getIndepTranSet_FromLPN(lpnList);
System.out.println("finish get independent set!!!!");
boolean failure = false;
int tranFiringCnt = 0;
int arraySize = lpnList.length;;
HashSet<PrjState> stateStack = new HashSet<PrjState>();
Stack<LpnTranList> lpnTranStack = new Stack<LpnTranList>();
Stack<HashSet<Transition>> firedTranStack = new Stack<HashSet<Transition>>();
//get initial enable transition set
@SuppressWarnings("unchecked")
LinkedList<Transition>[] initEnabledArray = new LinkedList[arraySize];
for (int i = 0; i < arraySize; i++) {
lpnList[i].getLpn().setLpnIndex(i);
initEnabledArray[i] = lpnList[i].getEnabled(initStateArray[i]);
}
//set initEnableSubset
//LPNTranSet initEnableSubset = ampleClass.generateAmpleList(false, approach,initEnabledArray, indepTranSet);
LpnTranList initEnableSubset = ampleClass.generateAmpleTranSet(initEnabledArray, indepTranSet);
/*
* Initialize the reach state set with the initial state.
*/
HashSet<PrjState> prjStateSet = new HashSet<PrjState>();
PrjState initPrjState = new PrjState(initStateArray);
if (useMdd) {
int[] initIdxArray = Analysis.getIdxArray(initStateArray);
mddMgr.add(reach, initIdxArray, true);
}
else
prjStateSet.add(initPrjState);
stateStack.add(initPrjState);
PrjState stateStackTop = initPrjState;
lpnTranStack.push(initEnableSubset);
firedTranStack.push(new HashSet<Transition>());
/*
* Start the main search loop.
*/
main_while_loop:
while(failure == false && stateStack.size() != 0) {
long curTotalMem = Runtime.getRuntime().totalMemory();
long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
if (curTotalMem > peakTotalMem)
peakTotalMem = curTotalMem;
if (curUsedMem > peakUsedMem)
peakUsedMem = curUsedMem;
if (stateStack.size() > max_stack_depth)
max_stack_depth = stateStack.size();
iterations++;
if (iterations % 500000 == 0) {
if (useMdd==true)
stateCount = mddMgr.numberOfStates(reach);
else
stateCount = prjStateSet.size();
System.out.println("---> #iteration " + iterations
+ "> # LPN transition firings: " + tranFiringCnt
+ ", # of prjStates found: " + stateCount
+ ", max_stack_depth: " + max_stack_depth
+ ", total MDD nodes: " + mddMgr.nodeCnt()
+ " used memory: " + (float) curUsedMem / 1000000
+ " free memory: "
+ (float) Runtime.getRuntime().freeMemory() / 1000000);
}
State[] curStateArray = stateStackTop.toStateArray();
LpnTranList curEnabled = lpnTranStack.peek();
// for (LPNTran tran : curEnabled)
// for (int i = 0; i < arraySize; i++)
// if (lpnList[i] == tran.getLpn())
// if (tran.isEnabled(curStateArray[i]) == false) {
// System.out.println("transition " + tran.getFullLabel() + " not enabled in the current state");
// System.exit(0);
// If all enabled transitions of the current LPN are considered, then consider the next LPN
// by increasing the curIndex.
// Otherwise, if all enabled transitions of all LPNs are considered, then pop the stacks.
if(curEnabled.size() == 0) {
lpnTranStack.pop();
firedTranStack.pop();
stateStack.remove(stateStackTop);
stateStackTop = stateStackTop.getFather();
if (stateStack.size() > 0)
traceCex.removeLast();
continue;
}
Transition firedTran = curEnabled.removeFirst();
firedTranStack.peek().add(firedTran);
traceCex.addLast(firedTran);
//System.out.println(tranFiringCnt + ": firedTran: "+ firedTran.getFullLabel());
// TODO: (??) Not sure if the state graph sg below is correct.
StateGraph sg = null;
for (int i=0; i<lpnList.length; i++) {
if (lpnList[i].getLpn().equals(firedTran.getLpn())) {
sg = lpnList[i];
}
}
State[] nextStateArray = sg.fire(lpnList, curStateArray, firedTran);
tranFiringCnt++;
// Check if the firedTran causes disabling error or deadlock.
@SuppressWarnings("unchecked")
LinkedList<Transition>[] curEnabledArray = new LinkedList[arraySize];
@SuppressWarnings("unchecked")
LinkedList<Transition>[] nextEnabledArray = new LinkedList[arraySize];
for (int i = 0; i < arraySize; i++) {
lpnList[i].getLpn().setLpnIndex(i);
StateGraph lpn_tmp = lpnList[i];
LinkedList<Transition> enabledList = lpn_tmp.getEnabled(curStateArray[i]);
curEnabledArray[i] = enabledList;
enabledList = lpn_tmp.getEnabled(nextStateArray[i]);
nextEnabledArray[i] = enabledList;
Transition disabledTran = firedTran.disablingError(curEnabledArray[i], nextEnabledArray[i]);
if(disabledTran != null) {
System.out.println("---> Disabling Error: " + disabledTran.getFullLabel() + " is disabled by " + firedTran.getFullLabel());
System.out.println("Current state:");
for(int ii = 0; ii < arraySize; ii++) {
System.out.println("module " + lpnList[ii].getLpn().getLabel());
System.out.println(curStateArray[ii]);
System.out.println("Enabled set: " + curEnabledArray[ii]);
}
System.out.println("======================\nNext state:");
for(int ii = 0; ii < arraySize; ii++) {
System.out.println("module " + lpnList[ii].getLpn().getLabel());
System.out.println(nextStateArray[ii]);
System.out.println("Enabled set: " + nextEnabledArray[ii]);
}
System.out.println();
failure = true;
break main_while_loop;
}
}
if (Analysis.deadLock(lpnList, nextStateArray) == true) {
System.out.println("---> Deadlock.");
// System.out.println("Deadlock state:");
// for(int ii = 0; ii < arraySize; ii++) {
// System.out.println("module " + lpnList[ii].getLabel());
// System.out.println(nextStateArray[ii]);
// System.out.println("Enabled set: " + nextEnabledArray[ii]);
failure = true;
break main_while_loop;
}
/*
// Add nextPrjState into prjStateSet
// If nextPrjState has been traversed before, skip to the next
// enabled transition.
//exist cycle
*/
PrjState nextPrjState = new PrjState(nextStateArray);
boolean isExisting = false;
int[] nextIdxArray = null;
if(useMdd==true)
nextIdxArray = Analysis.getIdxArray(nextStateArray);
if (useMdd == true)
isExisting = mddMgr.contains(reach, nextIdxArray);
else
isExisting = prjStateSet.contains(nextPrjState);
if (isExisting == false) {
if (useMdd == true) {
mddMgr.add(reach, nextIdxArray, true);
}
else
prjStateSet.add(nextPrjState);
//get next enable transition set
//LPNTranSet nextEnableSubset = ampleClass.generateAmpleList(false, approach, nextEnabledArray, indepTranSet);
LpnTranList nextEnableSubset = ampleClass.generateAmpleTranSet(nextEnabledArray, indepTranSet);
// LPNTranSet nextEnableSubset = new LPNTranSet();
// for (int i = 0; i < arraySize; i++)
// for (LPNTran tran : nextEnabledArray[i])
// nextEnableSubset.addLast(tran);
stateStack.add(nextPrjState);
stateStackTop.setChild(nextPrjState);
nextPrjState.setFather(stateStackTop);
stateStackTop = nextPrjState;
lpnTranStack.push(nextEnableSubset);
firedTranStack.push(new HashSet<Transition>());
// for (int i = 0; i < arraySize; i++)
// for (LPNTran tran : nextEnabledArray[i])
// System.out.print(tran.getFullLabel() + ", ");
// System.out.println("\n");
// for (LPNTran tran : nextEnableSubset)
// System.out.print(tran.getFullLabel() + ", ");
// HashSet<LPNTran> allEnabledSet = new HashSet<LPNTran>();
// for (int i = 0; i < arraySize; i++) {
// for (LPNTran tran : nextEnabledArray[i]) {
// allEnabledSet.add(tran);
// System.out.print(tran.getFullLabel() + ", ");
// System.out.println("\n");
// if(nextEnableSubset.size() > 0) {
// for (LPNTran tran : nextEnableSubset) {
// if (allEnabledSet.contains(tran) == false) {
// System.out.println("\n\n" + tran.getFullLabel() + " in reduced set but not enabled\n");
// System.exit(0);
// System.out.print(tran.getFullLabel() + ", ");
// System.out.println("\n
continue;
}
/*
* Remove firedTran from traceCex if its successor state already exists.
*/
traceCex.removeLast();
/*
* When firedTran forms a cycle in the state graph, consider all enabled transitions except those
* 1. already fired in the current state,
* 2. in the ample set of the next state.
*/
if(stateStack.contains(nextPrjState)==true && curEnabled.size()==0) {
//System.out.println("formed a cycle......");
LpnTranList original = new LpnTranList();
LpnTranList reduced = new LpnTranList();
//LPNTranSet nextStateAmpleSet = ampleClass.generateAmpleList(false, approach, nextEnabledArray, indepTranSet);
LpnTranList nextStateAmpleSet = ampleClass.generateAmpleTranSet(nextEnabledArray, indepTranSet);
// System.out.println("Back state's ample set:");
// for(LPNTran tran : nextStateAmpleSet)
// System.out.print(tran.getFullLabel() + ", ");
// System.out.println("\n");
int enabledTranCnt = 0;
LpnTranList[] tmp = new LpnTranList[arraySize];
for (int i = 0; i < arraySize; i++) {
tmp[i] = new LpnTranList();
for (Transition tran : curEnabledArray[i]) {
original.addLast(tran);
if (firedTranStack.peek().contains(tran)==false && nextStateAmpleSet.contains(tran)==false) {
tmp[i].addLast(tran);
reduced.addLast(tran);
enabledTranCnt++;
}
}
}
LpnTranList ampleSet = new LpnTranList();
if(enabledTranCnt > 0)
//ampleSet = ampleClass.generateAmpleList(false, approach, tmp, indepTranSet);
ampleSet = ampleClass.generateAmpleTranSet(tmp, indepTranSet);
LpnTranList sortedAmpleSet = ampleSet;
/*
* Sort transitions in ampleSet for better performance for MDD.
* Not needed for hash table.
*/
if (useMdd == true) {
LpnTranList[] newCurEnabledArray = new LpnTranList[arraySize];
for (int i = 0; i < arraySize; i++)
newCurEnabledArray[i] = new LpnTranList();
for (Transition tran : ampleSet)
newCurEnabledArray[tran.getLpn().getLpnIndex()].addLast(tran);
sortedAmpleSet = new LpnTranList();
for (int i = 0; i < arraySize; i++) {
LpnTranList localEnabledSet = newCurEnabledArray[i];
for (Transition tran : localEnabledSet)
sortedAmpleSet.addLast(tran);
}
}
// for(LPNTran tran : original)
// System.out.print(tran.getFullLabel() + ", ");
// System.out.println("\n");
// for(LPNTran tran : ampleSet)
// System.out.print(tran.getFullLabel() + ", ");
// System.out.println("\n");
// for(LPNTran tran : firedTranStack.peek())
// allCurEnabled.remove(tran);
lpnTranStack.pop();
lpnTranStack.push(sortedAmpleSet);
// for (int i = 0; i < arraySize; i++) {
// for (LPNTran tran : curEnabledArray[i]) {
// System.out.print(tran.getFullLabel() + ", ");
// System.out.println("\n");
// for(LPNTran tran : allCurEnabled)
// System.out.print(tran.getFullLabel() + ", ");
}
//System.out.println("Backtrack........\n");
}//END while (stateStack.empty() == false)
if (useMdd==true)
stateCount = mddMgr.numberOfStates(reach);
else
stateCount = prjStateSet.size();
//long curTotalMem = Runtime.getRuntime().totalMemory();
long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
System.out.println("SUMMARY: # LPN transition firings: " + tranFiringCnt
+ ", # of prjStates found: " + stateCount
+ ", max_stack_depth: " + max_stack_depth
+ ", used memory: " + (float) curUsedMem / 1000000
+ ", free memory: "
+ (float) Runtime.getRuntime().freeMemory() / 1000000);
return null;
}
// /**
// * Check if this project deadlocks in the current state 'stateArray'.
// * @param sgList
// * @param stateArray
// * @param staticSetsMap
// * @param enableSet
// * @param disableByStealingToken
// * @param disableSet
// * @param init
// * @return
// */
// // Called by search search_dfsPOR
// public boolean deadLock(StateGraph[] sgList, State[] stateArray, HashMap<LpnTransitionPair,StaticSets> staticSetsMap,
// boolean init, HashMap<LpnTransitionPair, Integer> tranFiringFreq, HashSet<PrjState> stateStack, PrjState stateStackTop, int cycleClosingMethdIndex) {
// boolean deadlock = true;
// System.out.println("@ deadlock:");
//// for (int i = 0; i < stateArray.length; i++) {
//// LinkedList<Transition> tmp = getAmple(stateArray, null, staticSetsMap, init, tranFiringFreq, sgList, stateStack, stateStackTop, cycleClosingMethdIndex).getAmpleSet();
//// if (tmp.size() > 0) {
//// deadlock = false;
//// break;
// LinkedList<Transition> tmp = getAmple(stateArray, null, staticSetsMap, init, tranFiringFreq, sgList, stateStack, stateStackTop, cycleClosingMethdIndex).getAmpleSet();
// if (tmp.size() > 0) {
// deadlock = false;
// System.out.println("@ end of deadlock");
// return deadlock;
public static boolean deadLock(StateGraph[] lpnArray, State[] stateArray) {
boolean deadlock = true;
for (int i = 0; i < stateArray.length; i++) {
LinkedList<Transition> tmp = lpnArray[i].getEnabled(stateArray[i]);
if (tmp.size() > 0) {
deadlock = false;
break;
}
}
return deadlock;
}
public static boolean deadLock(StateGraph[] lpnArray, int[] stateIdxArray) {
boolean deadlock = true;
for (int i = 0; i < stateIdxArray.length; i++) {
LinkedList<Transition> tmp = lpnArray[i].getEnabled(stateIdxArray[i]);
if (tmp.size() > 0) {
deadlock = false;
break;
}
}
return deadlock;
}
// /*
// * Scan enabledArray, identify all sticky transitions other the firedTran, and return them.
// *
// * Arguments remain constant.
// */
// public static LpnTranList[] getStickyTrans(LpnTranList[] enabledArray, Transition firedTran) {
// int arraySize = enabledArray.length;
// LpnTranList[] stickyTranArray = new LpnTranList[arraySize];
// for (int i = 0; i < arraySize; i++) {
// stickyTranArray[i] = new LpnTranList();
// for (Transition tran : enabledArray[i]) {
// if (tran != firedTran)
// stickyTranArray[i].add(tran);
// if(stickyTranArray[i].size()==0)
// stickyTranArray[i] = null;
// return stickyTranArray;
/**
* Identify if any sticky transitions in currentStickyTransArray can existing in the nextState. If so, add them to
* nextStickyTransArray.
*
* Arguments: curStickyTransArray and nextState are constant, nextStickyTransArray may be added with sticky transitions
* from curStickyTransArray.
*
* Return: sticky transitions from curStickyTransArray that are not marking disabled in nextState.
*/
public static LpnTranList[] checkStickyTrans(
LpnTranList[] curStickyTransArray, LpnTranList[] nextEnabledArray,
LpnTranList[] nextStickyTransArray, State nextState, LhpnFile LPN) {
int arraySize = curStickyTransArray.length;
LpnTranList[] stickyTransArray = new LpnTranList[arraySize];
boolean[] hasStickyTrans = new boolean[arraySize];
for (int i = 0; i < arraySize; i++) {
HashSet<Transition> tmp = new HashSet<Transition>();
if(nextStickyTransArray[i] != null)
for(Transition tran : nextStickyTransArray[i])
tmp.add(tran);
stickyTransArray[i] = new LpnTranList();
hasStickyTrans[i] = false;
for (Transition tran : curStickyTransArray[i]) {
if (tran.isPersistent() == true && tmp.contains(tran)==false) {
int[] nextMarking = nextState.getMarking();
int[] preset = LPN.getPresetIndex(tran.getName());//tran.getPreSet();
boolean included = false;
if (preset != null && preset.length > 0) {
for (int pp : preset) {
for (int mi = 0; i < nextMarking.length; i++) {
if (nextMarking[mi] == pp) {
included = true;
break;
}
}
if (included == false)
break;
}
}
if(preset==null || preset.length==0 || included==true) {
stickyTransArray[i].add(tran);
hasStickyTrans[i] = true;
}
}
}
if(stickyTransArray[i].size()==0)
stickyTransArray[i] = null;
}
return stickyTransArray;
}
/*
* Return an array of indices for the given stateArray.
*/
private static int[] getIdxArray(State[] stateArray) {
int[] idxArray = new int[stateArray.length];
for(int i = 0; i < stateArray.length; i++) {
idxArray[i] = stateArray[i].getIndex();
}
return idxArray;
}
private static int[] getLocalStateIdxArray(StateGraph[] sgList, State[] stateArray, boolean reverse) {
int arraySize = sgList.length;
int[] localIdxArray = new int[arraySize];
for(int i = 0; i < arraySize; i++) {
if(reverse == false)
localIdxArray[i] = sgList[i].getLocalState(stateArray[i]).getIndex();
else
localIdxArray[arraySize - i - 1] = sgList[i].getLocalState(stateArray[i]).getIndex();
//System.out.print(localIdxArray[i] + " ");
}
//System.out.println();
return localIdxArray;
}
private void printEnabledSetTbl(StateGraph[] sgList) {
for (int i=0; i<sgList.length; i++) {
System.out.println("******* enabledSetTbl for " + sgList[i].getLpn().getLabel() + " **********");
for (State s : sgList[i].getEnabledSetTbl().keySet()) {
System.out.print("S" + s.getIndex() + " -> ");
printTransitionSet(sgList[i].getEnabledSetTbl().get(s), "");
}
}
}
private HashSet<LpnTransitionPair> partialOrderReduction(State[] curStateArray,
HashSet<LpnTransitionPair> curEnabled, HashMap<LpnTransitionPair, StaticSets> staticMap,
HashMap<LpnTransitionPair,Integer> tranFiringFreqMap, StateGraph[] sgList, LhpnFile[] lpnList) {
if (curEnabled.size() == 1)
return curEnabled;
HashSet<LpnTransitionPair> ready = new HashSet<LpnTransitionPair>();
for (LpnTransitionPair enabledTran : curEnabled) {
if (staticMap.get(enabledTran).getOtherTransDisableCurTranSet().isEmpty()) {
ready.add(enabledTran);
return ready;
}
}
if (Options.getUseDependentQueue()) {
DependentSetComparator depComp = new DependentSetComparator(tranFiringFreqMap);
PriorityQueue<DependentSet> dependentSetQueue = new PriorityQueue<DependentSet>(curEnabled.size(), depComp);
for (LpnTransitionPair enabledTran : curEnabled) {
if (Options.getDebugMode()){
writeStringWithEndOfLineToPORDebugFile("@ beginning of partialOrderReduction, consider seed transition " + getNamesOfLPNandTrans(lpnList, enabledTran));
}
HashSet<LpnTransitionPair> dependent = new HashSet<LpnTransitionPair>();
Transition enabledTransition = sgList[enabledTran.getLpnIndex()].getLpn().getAllTransitions()[enabledTran.getTranIndex()];
boolean enabledIsDummy = false;
boolean isCycleClosingAmpleComputation = false;
dependent = computeDependent(curStateArray,enabledTran,dependent,curEnabled,staticMap, lpnList, isCycleClosingAmpleComputation);
if (Options.getDebugMode()) {
writeIntegerSetToPORDebugFile(dependent, sgList, "@ end of partialOrderReduction, dependent set for enabled transition "
+ getNamesOfLPNandTrans(lpnList, enabledTran));
}
// TODO: temporarily dealing with dummy transitions (This requires the dummy transitions to have "_dummy" in their names.)
if(isDummyTran(enabledTransition.getName()))
enabledIsDummy = true;
DependentSet dependentSet = new DependentSet(dependent, enabledTran, enabledIsDummy);
dependentSetQueue.add(dependentSet);
}
//cachedNecessarySets.clear();
ready = dependentSetQueue.poll().getDependent();
//return ready;
}
else {
for (LpnTransitionPair enabledTran : curEnabled) {
if (Options.getDebugMode()){
writeStringWithEndOfLineToPORDebugFile("@ beginning of partialOrderReduction, consider seed transition " + getNamesOfLPNandTrans(lpnList, enabledTran));
}
HashSet<LpnTransitionPair> dependent = new HashSet<LpnTransitionPair>();
boolean isCycleClosingAmpleComputation = false;
dependent = computeDependent(curStateArray,enabledTran,dependent,curEnabled,staticMap, lpnList, isCycleClosingAmpleComputation);
if (Options.getDebugMode()) {
writeIntegerSetToPORDebugFile(dependent, sgList, "@ end of partialOrderReduction, dependent set for enabled transition "
+ getNamesOfLPNandTrans(lpnList, enabledTran));
}
if (ready.isEmpty() || dependent.size() < ready.size())
ready = (HashSet<LpnTransitionPair>) dependent.clone();
if (ready.size() == 1) {
cachedNecessarySets.clear();
return ready;
}
}
}
cachedNecessarySets.clear();
return ready;
}
private boolean isDummyTran(String tranName) {
if (tranName.contains("_dummy"))
return true;
else
return false;
}
private HashSet<LpnTransitionPair> computeDependent(State[] curStateArray,
LpnTransitionPair seedTran, HashSet<LpnTransitionPair> dependent, HashSet<LpnTransitionPair> curEnabled,
HashMap<LpnTransitionPair, StaticSets> staticMap, LhpnFile[] lpnList, boolean isCycleClosingAmpleComputation) {
// disableSet is the set of transitions that can be disabled by firing enabledLpnTran, or can disable enabledLpnTran.
HashSet<LpnTransitionPair> disableSet = staticMap.get(seedTran).getDisableSet();
HashSet<LpnTransitionPair> otherTransDisableEnabledTran = staticMap.get(seedTran).getOtherTransDisableCurTranSet();
if (Options.getDebugMode()) {
writeStringWithEndOfLineToPORDebugFile("@ beginning of computeDependent, consider transition " + getNamesOfLPNandTrans(lpnList, seedTran));
writeIntegerSetToPORDebugFile(disableSet, lpnList, "Disable set for " + getNamesOfLPNandTrans(lpnList, seedTran));
}
dependent.add(seedTran);
// for (LpnTransitionPair lpnTranPair : canModifyAssign) {
// if (curEnabled.contains(lpnTranPair))
// dependent.add(lpnTranPair);
if (Options.getDebugMode()) {
writeIntegerSetToPORDebugFile(dependent, lpnList, "@ getDependentSet at 0, dependent set for " + getNamesOfLPNandTrans(lpnList, seedTran));
}
// dependent is equal to enabled. Terminate.
if (dependent.size() == curEnabled.size()) {
if (Options.getDebugMode()) {
writeStringWithEndOfLineToPORDebugFile("Check 0: Size of dependent is equal to enabled. Return dependent.");
}
return dependent;
}
for (LpnTransitionPair tranInDisableSet : disableSet) {
if (Options.getDebugMode()) {
writeStringWithEndOfLineToPORDebugFile("Consider transition in the disable set of "
+ getNamesOfLPNandTrans(lpnList, seedTran) + ": "
+ getNamesOfLPNandTrans(lpnList, tranInDisableSet));
}
boolean tranInDisableSetIsPersistent = lpnList[tranInDisableSet.getLpnIndex()].getTransition(tranInDisableSet.getTranIndex()).isPersistent();
if (curEnabled.contains(tranInDisableSet) && !dependent.contains(tranInDisableSet)
&& (!tranInDisableSetIsPersistent || otherTransDisableEnabledTran.contains(tranInDisableSet))) {
dependent.addAll(computeDependent(curStateArray,tranInDisableSet,dependent,curEnabled,staticMap, lpnList, isCycleClosingAmpleComputation));
if (Options.getDebugMode()) {
writeIntegerSetToPORDebugFile(dependent, lpnList, "@ getDependentSet at 1 for transition " + getNamesOfLPNandTrans(lpnList, seedTran));
}
}
else if (!curEnabled.contains(tranInDisableSet)) {
if(Options.getPOR().toLowerCase().equals("tboff") // no trace-back
|| (Options.getCycleClosingAmpleMethd().toLowerCase().equals("cctboff") && isCycleClosingAmpleComputation)) {
dependent.addAll(curEnabled);
break;
}
LpnTransitionPair seedTranInDisableSet = new LpnTransitionPair(tranInDisableSet.getLpnIndex(), tranInDisableSet.getTranIndex());
HashSet<LpnTransitionPair> necessary = null;
if (Options.getDebugMode()) {
writeCachedNecessarySetsToPORDebugFile(lpnList);
}
if (cachedNecessarySets.containsKey(tranInDisableSet)) {
if (Options.getDebugMode()) {
writeStringWithEndOfLineToPORDebugFile("Found transition " + getNamesOfLPNandTrans(lpnList, tranInDisableSet) + "in the cached necessary sets.");
}
necessary = cachedNecessarySets.get(tranInDisableSet);
}
else {
if (Options.getDebugMode()) {
writeStringWithEndOfLineToPORDebugFile("==== Compute necessary using DFS ====");
}
necessary = computeNecessary(curStateArray,tranInDisableSet,dependent,curEnabled, staticMap, lpnList, seedTranInDisableSet);
}
if (necessary != null && !necessary.isEmpty()) {
cachedNecessarySets.put(tranInDisableSet, necessary);
if (Options.getDebugMode()) {
writeIntegerSetToPORDebugFile(necessary, lpnList, "necessary set for transition " + getNamesOfLPNandTrans(lpnList, tranInDisableSet));
}
for (LpnTransitionPair tranNecessary : necessary) {
if (!dependent.contains(tranNecessary)) {
if (Options.getDebugMode()) {
writeIntegerSetToPORDebugFile(dependent, lpnList, "Check if the newly found necessary transition is in the dependent set of " + getNamesOfLPNandTrans(lpnList, seedTran));
writeStringWithEndOfLineToPORDebugFile("It does not contain this transition found by computeNecessary: "
+ getNamesOfLPNandTrans(lpnList, tranNecessary) + ". Compute its dependent set.");
}
dependent.addAll(computeDependent(curStateArray,tranNecessary,dependent,curEnabled,staticMap, lpnList, isCycleClosingAmpleComputation));
}
else {
if (Options.getDebugMode()) {
writeIntegerSetToPORDebugFile(dependent, lpnList, "Check if the newly found necessary transition is in the dependent set. Dependent set for " + getNamesOfLPNandTrans(lpnList, seedTran));
writeStringWithEndOfLineToPORDebugFile("It already contains this transition found by computeNecessary: "
+ getNamesOfLPNandTrans(lpnList, tranNecessary) + ".");
}
}
}
}
else {
if (Options.getDebugMode()) {
if (necessary == null) {
writeStringWithEndOfLineToPORDebugFile("necessary set for transition " + getNamesOfLPNandTrans(lpnList, seedTran) + " is null.");
}
else {
writeStringWithEndOfLineToPORDebugFile("necessary set for transition " + getNamesOfLPNandTrans(lpnList, seedTran) + " is empty.");
}
}
dependent.addAll(curEnabled);
}
if (Options.getDebugMode()) {
writeIntegerSetToPORDebugFile(dependent, lpnList, "@ getDependentSet at 2, dependent set for transition " + getNamesOfLPNandTrans(lpnList, seedTran));
}
}
else if (dependent.contains(tranInDisableSet)) {
if (Options.getDebugMode()) {
writeIntegerSetToPORDebugFile(dependent, lpnList, "@ getDependentSet at 3 for transition " + getNamesOfLPNandTrans(lpnList, seedTran));
writeStringWithEndOfLineToPORDebugFile("Transition " + getNamesOfLPNandTrans(lpnList, tranInDisableSet) + " is already in the dependent set of "
+ getNamesOfLPNandTrans(lpnList, seedTran) + ".");
}
}
}
return dependent;
}
private String getNamesOfLPNandTrans(LhpnFile[] lpnList, LpnTransitionPair tran) {
return lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(tran.getTranIndex()).getName() + ")";
}
@SuppressWarnings("unchecked")
private HashSet<LpnTransitionPair> computeNecessary(State[] curStateArray,
LpnTransitionPair tran, HashSet<LpnTransitionPair> dependent,
HashSet<LpnTransitionPair> curEnabledIndices, HashMap<LpnTransitionPair, StaticSets> staticMap,
LhpnFile[] lpnList, LpnTransitionPair seedTranInDisableSet) { //, LpnTransitionPair seedTran) {
if (Options.getDebugMode()) {
writeStringWithEndOfLineToPORDebugFile("@ getNecessary, consider transition: " + getNamesOfLPNandTrans(lpnList, tran));
}
if (cachedNecessarySets.containsKey(tran)) {
if (Options.getDebugMode()) {
writeStringWithEndOfLineToPORDebugFile("Found transition " + getNamesOfLPNandTrans(lpnList, tran)
+ "'s necessary set in the cached necessary sets. ");
}
return cachedNecessarySets.get(tran);
}
// Search for transition(s) that can help to bring the marking(s).
HashSet<LpnTransitionPair> nMarking = null;
Transition transition = lpnList[tran.getLpnIndex()].getTransition(tran.getTranIndex());
int[] presetPlaces = lpnList[tran.getLpnIndex()].getPresetIndex(transition.getName());
for (int i=0; i < presetPlaces.length; i++) {
int place = presetPlaces[i];
if (curStateArray[tran.getLpnIndex()].getMarking()[place]==0) {
if (Options.getDebugMode()) {
writeStringWithEndOfLineToPORDebugFile("
}
HashSet<LpnTransitionPair> nMarkingTemp = new HashSet<LpnTransitionPair>();
String placeName = lpnList[tran.getLpnIndex()].getAllPlaces().get(place);
if (Options.getDebugMode()) {
writeStringWithEndOfLineToPORDebugFile("preset place of " + getNamesOfLPNandTrans(lpnList, tran) + " is " + placeName);
}
int[] presetTrans = lpnList[tran.getLpnIndex()].getPresetIndex(placeName);
for (int j=0; j < presetTrans.length; j++) {
LpnTransitionPair presetTran = new LpnTransitionPair(tran.getLpnIndex(), presetTrans[j]);
if (Options.getDebugMode()) {
writeStringWithEndOfLineToPORDebugFile("preset transition of " + placeName + " is " + getNamesOfLPNandTrans(lpnList, presetTran));
}
if (seedTranInDisableSet.getVisitedTrans().contains(presetTran)) {
if (Options.getDebugMode()) {
writeStringWithEndOfLineToPORDebugFile("Transition " + getNamesOfLPNandTrans(lpnList, presetTran) + " is visted before by "
+ getNamesOfLPNandTrans(lpnList, seedTranInDisableSet));
}
if (cachedNecessarySets.containsKey(presetTran)) {
if (Options.getDebugMode()) {
writeStringWithEndOfLineToPORDebugFile("Found transition " + getNamesOfLPNandTrans(lpnList, presetTran)
+ "'s necessary set in the cached necessary sets. Add it to nMarkingTemp.");
}
nMarkingTemp = cachedNecessarySets.get(presetTran);
}
if (curEnabledIndices.contains(presetTran)) {
if (Options.getDebugMode()) {
writeStringWithEndOfLineToPORDebugFile("@ nMarking: curEnabled contains transition "
+ getNamesOfLPNandTrans(lpnList, presetTran) + "). Add to nMarkingTmp.");
}
nMarkingTemp.add(presetTran);;
}
continue;
}
else
seedTranInDisableSet.addVisitedTran(presetTran);
if (Options.getDebugMode()) {
writeStringWithEndOfLineToPORDebugFile("~~~~~~~~~ transVisited for transition "
+ getNamesOfLPNandTrans(lpnList, seedTranInDisableSet) + ")~~~~~~~~~");
for (LpnTransitionPair visitedTran : seedTranInDisableSet.getVisitedTrans()) {
writeStringWithEndOfLineToPORDebugFile(getNamesOfLPNandTrans(lpnList, visitedTran));
}
writeStringWithEndOfLineToPORDebugFile("@ getNecessary, consider transition: "
+ getNamesOfLPNandTrans(lpnList, tran));
}
if (curEnabledIndices.contains(presetTran)) {
if (Options.getDebugMode()) {
writeStringWithEndOfLineToPORDebugFile("@ nMarking: curEnabled contains transition "
+ getNamesOfLPNandTrans(lpnList, presetTran) + "). Add to nMarkingTmp.");
}
nMarkingTemp.add(presetTran);
}
else {
if (Options.getDebugMode()) {
writeStringWithEndOfLineToPORDebugFile("@ nMarking: transition " + getNamesOfLPNandTrans(lpnList, presetTran) + " is not enabled. Compute its necessary set.");
}
HashSet<LpnTransitionPair> tmp = null;
tmp = computeNecessary(curStateArray, presetTran, dependent,
curEnabledIndices, staticMap, lpnList, seedTranInDisableSet);
if (tmp != null)
nMarkingTemp.addAll(tmp);
else
if (Options.getDebugMode()) {
writeStringWithEndOfLineToPORDebugFile("@ nMarking: necessary set for transition "
+ getNamesOfLPNandTrans(lpnList, presetTran) + " is null.");
}
}
}
if (nMarkingTemp != null)
if (nMarking == null || nMarkingTemp.size() < nMarking.size())
nMarking = (HashSet<LpnTransitionPair>) nMarkingTemp.clone();
}
else
if (Options.getDebugMode()) {
writeStringWithEndOfLineToPORDebugFile("Place " + lpnList[tran.getLpnIndex()].getLabel()
+ "(" + lpnList[tran.getLpnIndex()].getAllPlaces().get(place) + ") is marked.");
}
}
if (nMarking != null && nMarking.size() ==1) {
cachedNecessarySets.put(tran, nMarking);
if (Options.getDebugMode()) {
writeStringWithEndOfLineToPORDebugFile("size of nMarking == 1. Return nMarking as necessary set.");
writeCachedNecessarySetsToPORDebugFile(lpnList);
}
return nMarking;
}
// Search for transition(s) that can help to enable the current transition.
HashSet<LpnTransitionPair> nEnable = null;
int[] varValueVector = curStateArray[tran.getLpnIndex()].getVector();
//HashSet<LpnTransitionPair> canEnable = staticMap.get(tran).getEnableBySettingEnablingTrue();
ArrayList<HashSet<LpnTransitionPair>> canEnable = staticMap.get(tran).getOtherTransSetCurTranEnablingTrue();
if (Options.getDebugMode()) {
writeStringWithEndOfLineToPORDebugFile("
writeIntegerSetToPORDebugFile(canEnable, lpnList, getNamesOfLPNandTrans(lpnList, tran) + " can be enabled by");
}
if (transition.getEnablingTree() != null
&& transition.getEnablingTree().evaluateExpr(lpnList[tran.getLpnIndex()].getAllVarsWithValuesAsString(varValueVector)) == 0.0
&& !canEnable.isEmpty()) {
nEnable = new HashSet<LpnTransitionPair>();
for(int index=0; index < staticMap.get(tran).getConjunctsOfEnabling().size(); index++) {
ExprTree conjunctExprTree = staticMap.get(tran).getConjunctsOfEnabling().get(index);
HashSet<LpnTransitionPair> nEnableOfOneConjunct = null;
if (conjunctExprTree.evaluateExpr(lpnList[tran.getLpnIndex()].getAllVarsWithValuesAsString(varValueVector)) == 0.0) {
HashSet<LpnTransitionPair> canEnableOneConjunctSet = staticMap.get(tran).getOtherTransSetCurTranEnablingTrue().get(index);
nEnableOfOneConjunct = new HashSet<LpnTransitionPair>();
for (LpnTransitionPair tranCanEnable : canEnableOneConjunctSet) {
if (curEnabledIndices.contains(tranCanEnable)) {
nEnableOfOneConjunct.add(tranCanEnable);
if (Options.getDebugMode()) {
writeStringWithEndOfLineToPORDebugFile("@ nEnable: curEnabled contains transition " + getNamesOfLPNandTrans(lpnList, tranCanEnable) + ". Add to nEnableOfOneConjunct.");
}
}
else {
if (seedTranInDisableSet.getVisitedTrans().contains(tranCanEnable)) {
if (Options.getDebugMode()) {
writeStringWithEndOfLineToPORDebugFile("Transition " + getNamesOfLPNandTrans(lpnList, tranCanEnable) + " is visted before by "
+ getNamesOfLPNandTrans(lpnList, seedTranInDisableSet)+".");
}
if (cachedNecessarySets.containsKey(tranCanEnable)) {
if (Options.getDebugMode()) {
writeStringWithEndOfLineToPORDebugFile("Found transition " + getNamesOfLPNandTrans(lpnList, tranCanEnable)
+ "'s necessary set in the cached necessary sets. Add it to nEnableOfOneConjunct.");
}
nEnableOfOneConjunct.addAll(cachedNecessarySets.get(tranCanEnable));
}
continue;
}
else {
seedTranInDisableSet.addVisitedTran(tranCanEnable);
}
if (Options.getDebugMode()) {
writeStringWithEndOfLineToPORDebugFile("@ nEnable: transition " + getNamesOfLPNandTrans(lpnList, tranCanEnable)
+ " is not enabled. Compute its necessary set.");
}
HashSet<LpnTransitionPair> tmp = computeNecessary(curStateArray, tranCanEnable, dependent,
curEnabledIndices, staticMap, lpnList, seedTranInDisableSet);
if (tmp != null)
nEnableOfOneConjunct.addAll(tmp);
else
if (Options.getDebugMode()) {
writeStringWithEndOfLineToPORDebugFile("@ nEnable: necessary set for transition "
+ getNamesOfLPNandTrans(lpnList, tranCanEnable) + " is null.");
}
}
}
}
if (nEnableOfOneConjunct != null) {
if (nEnable.isEmpty())
nEnable = (HashSet<LpnTransitionPair>) nEnableOfOneConjunct.clone();
else {
if (nEnableOfOneConjunct.size() < nEnable.size())
nEnable = (HashSet<LpnTransitionPair>) nEnableOfOneConjunct.clone();
}
}
}
}
if (Options.getDebugMode()) {
if (transition.getEnablingTree() == null) {
writeStringWithEndOfLineToPORDebugFile("@ nEnable: transition " + getNamesOfLPNandTrans(lpnList, tran) + " has no enabling condition.");
}
else if (transition.getEnablingTree().evaluateExpr(lpnList[tran.getLpnIndex()].getAllVarsWithValuesAsString(varValueVector)) !=0.0) {
writeStringWithEndOfLineToPORDebugFile("@ nEnable: transition " + getNamesOfLPNandTrans(lpnList, tran) + "'s enabling condition is true.");
}
else if (transition.getEnablingTree() != null
&& transition.getEnablingTree().evaluateExpr(lpnList[tran.getLpnIndex()].getAllVarsWithValuesAsString(varValueVector)) == 0.0
&& canEnable.isEmpty()) {
writeStringWithEndOfLineToPORDebugFile("@ nEnable: transition " + getNamesOfLPNandTrans(lpnList, tran)
+ "'s enabling condition is false, but no other transitions that can help to enable it were found .");
}
writeIntegerSetToPORDebugFile(nMarking, lpnList, "nMarking for transition " + getNamesOfLPNandTrans(lpnList, tran));
writeIntegerSetToPORDebugFile(nEnable, lpnList, "nEnable for transition " + getNamesOfLPNandTrans(lpnList, tran));
}
if (nEnable == null && nMarking != null) {
if (!nMarking.isEmpty())
cachedNecessarySets.put(tran, nMarking);
if (Options.getDebugMode()) {
writeCachedNecessarySetsToPORDebugFile(lpnList);
}
return nMarking;
}
else if (nMarking == null && nEnable != null) {
if (!nEnable.isEmpty())
cachedNecessarySets.put(tran, nEnable);
if (Options.getDebugMode()) {
writeCachedNecessarySetsToPORDebugFile(lpnList);
}
return nEnable;
}
// else if (nMarking == null && nEnable == null) {
// return null;
else {
if (!nMarking.isEmpty() && !nEnable.isEmpty()) {
if (getIntSetSubstraction(nMarking, dependent).size() < getIntSetSubstraction(nEnable, dependent).size()) {
cachedNecessarySets.put(tran, nMarking);
if (Options.getDebugMode()) {
writeCachedNecessarySetsToPORDebugFile(lpnList);
}
return nMarking;
}
else {
cachedNecessarySets.put(tran, nEnable);
if (Options.getDebugMode()) {
writeCachedNecessarySetsToPORDebugFile(lpnList);
}
return nEnable;
}
}
else if (nMarking.isEmpty() && !nEnable.isEmpty()) {
cachedNecessarySets.put(tran, nEnable);
if (Options.getDebugMode()) {
writeCachedNecessarySetsToPORDebugFile(lpnList);
}
return nEnable;
}
else {
cachedNecessarySets.put(tran, nMarking);
if (Options.getDebugMode()) {
writeCachedNecessarySetsToPORDebugFile(lpnList);
}
return nMarking;
}
}
}
// private HashSet<LpnTransitionPair> computeNecessaryUsingDependencyGraphs(State[] curStateArray,
// LpnTransitionPair tran, HashSet<LpnTransitionPair> curEnabled,
// HashMap<LpnTransitionPair, StaticSets> staticMap,
// LhpnFile[] lpnList, LpnTransitionPair seedTran) {
// if (Options.getDebugMode()) {
//// System.out.println("@ getNecessary, consider transition: " + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(tran.getTranIndex()).getName() + ")");
// writeStringWithEndOfLineToPORDebugFile("@ getNecessary, consider transition: " + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(tran.getTranIndex()).getName() + ")");
// // Use breadth-first search to find the shorted path from the seed transition to an enabled transition.
// LinkedList<LpnTransitionPair> exploredTransQueue = new LinkedList<LpnTransitionPair>();
// HashSet<LpnTransitionPair> allExploredTrans = new HashSet<LpnTransitionPair>();
// exploredTransQueue.add(tran);
// //boolean foundEnabledTran = false;
// HashSet<LpnTransitionPair> canEnable = new HashSet<LpnTransitionPair>();
// while(!exploredTransQueue.isEmpty()){
// LpnTransitionPair curTran = exploredTransQueue.poll();
// allExploredTrans.add(curTran);
// if (cachedNecessarySets.containsKey(curTran)) {
// if (Options.getDebugMode()) {
// writeStringWithEndOfLineToPORDebugFile("Found transition " + lpnList[curTran.getLpnIndex()].getLabel() + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()).getName() + ")"
// + "'s necessary set in the cached necessary sets. Terminate BFS.");
// return cachedNecessarySets.get(curTran);
// canEnable = buildCanBringTokenSet(curTran,lpnList, curStateArray);
// if (Options.getDebugMode()) {
//// printIntegerSet(canEnable, lpnList, "Neighbors that can help to bring tokens to transition " + lpnList[curTran.getLpnIndex()].getLabel() + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()) + ") ");
// writeIntegerSetToPORDebugFile(canEnable, lpnList, "Neighbors that can help to bring tokens to transition " + lpnList[curTran.getLpnIndex()].getLabel() + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()) + ") ");
// // Decide if canSetEnablingTrue set can help to enable curTran.
// Transition curTransition = lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex());
// int[] varValueVector = curStateArray[curTran.getLpnIndex()].getVector();
// if (curTransition.getEnablingTree() != null
// && curTransition.getEnablingTree().evaluateExpr(lpnList[curTran.getLpnIndex()].getAllVarsWithValuesAsString(varValueVector)) == 0.0) {
// canEnable.addAll(staticMap.get(curTran).getEnableBySettingEnablingTrue());
// if (Options.getDebugMode()) {
//// printIntegerSet(canEnable, lpnList, "Neighbors that can help to set the enabling of transition " + lpnList[curTran.getLpnIndex()].getLabel() + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()) + ") ");
// writeIntegerSetToPORDebugFile(staticMap.get(curTran).getEnableBySettingEnablingTrue(), lpnList, "Neighbors that can help to set the enabling transition " + lpnList[curTran.getLpnIndex()].getLabel() + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()) + ") ");
// if (Options.getDebugMode()) {
//// printIntegerSet(canEnable, lpnList, "Neighbors that can help to enable transition " + lpnList[curTran.getLpnIndex()].getLabel() + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()) + ") ");
// writeIntegerSetToPORDebugFile(canEnable, lpnList, "Neighbors that can help to enable transition " + lpnList[curTran.getLpnIndex()].getLabel() + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()) + ") ");
// for (LpnTransitionPair neighborTran : canEnable) {
// if (curEnabled.contains(neighborTran)) {
// if (!neighborTran.equals(seedTran)) {
// HashSet<LpnTransitionPair> necessarySet = new HashSet<LpnTransitionPair>();
// necessarySet.add(neighborTran);
// // TODO: Is it true that the necessary set for a disabled transition only contains a single element before the dependent set of the element is computed?
// cachedNecessarySets.put(tran, necessarySet);
// if (Options.getDebugMode()) {
//// System.out.println("Enabled neighbor that can help to enable transition " + lpnList[curTran.getLpnIndex()].getLabel()
//// + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()) + "): " + lpnList[neighborTran.getLpnIndex()].getLabel()
//// + "(" + lpnList[neighborTran.getLpnIndex()].getTransition(neighborTran.getTranIndex()) + ").");
// writeStringWithEndOfLineToPORDebugFile("Enabled neighbor that can help to enable transition " + lpnList[curTran.getLpnIndex()].getLabel()
// + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()) + "): " + lpnList[neighborTran.getLpnIndex()].getLabel()
// + "(" + lpnList[neighborTran.getLpnIndex()].getTransition(neighborTran.getTranIndex()) + ").");
// return necessarySet;
// else if (neighborTran.equals(seedTran) && canEnable.size()==1) {
// if (Options.getDebugMode()) {
//// System.out.println("Enabled neighbor that can help to enable transition " + lpnList[curTran.getLpnIndex()].getLabel()
//// + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()) + "): " + lpnList[neighborTran.getLpnIndex()].getLabel()
//// + "(" + lpnList[neighborTran.getLpnIndex()].getTransition(neighborTran.getTranIndex()) + "). But " + lpnList[neighborTran.getLpnIndex()].getLabel()
//// + "(" + lpnList[neighborTran.getLpnIndex()].getTransition(neighborTran.getTranIndex()) + ") is the seed transition. Return null necessary set.");
// writeStringWithEndOfLineToPORDebugFile("Enabled neighbor that can help to enable transition " + lpnList[curTran.getLpnIndex()].getLabel()
// + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()) + "): " + lpnList[neighborTran.getLpnIndex()].getLabel()
// + "(" + lpnList[neighborTran.getLpnIndex()].getTransition(neighborTran.getTranIndex()) + "). But " + lpnList[neighborTran.getLpnIndex()].getLabel()
// + "(" + lpnList[neighborTran.getLpnIndex()].getTransition(neighborTran.getTranIndex()) + ") is the seed transition. Return null necessary set.");
// return null;
//// if (exploredTransQueue.isEmpty()) {
//// System.out.println("exploredTransQueue is empty. Return null necessary set.");
//// writeStringWithNewLineToPORDebugFile("exploredTransQueue is empty. Return null necessary set.");
//// return null;
// if (!allExploredTrans.contains(neighborTran)) {
// allExploredTrans.add(neighborTran);
// exploredTransQueue.add(neighborTran);
// canEnable.clear();
// return null;
private void printCachedNecessarySets(LhpnFile[] lpnList) {
System.out.println("================ cachedNecessarySets =================");
for (LpnTransitionPair key : cachedNecessarySets.keySet()) {
System.out.print(lpnList[key.getLpnIndex()].getLabel() + "(" + lpnList[key.getLpnIndex()].getTransition(key.getTranIndex()).getName() + ") => ");
HashSet<LpnTransitionPair> necessarySet = cachedNecessarySets.get(key);
for (LpnTransitionPair necessary : necessarySet) {
System.out.print(lpnList[necessary.getLpnIndex()].getLabel() + "(" + lpnList[necessary.getLpnIndex()].getTransition(necessary.getTranIndex()).getName() + ") ");
}
System.out.print("\n");
}
}
private void writeCachedNecessarySetsToPORDebugFile(LhpnFile[] lpnList) {
writeStringWithEndOfLineToPORDebugFile("================ cached necessary sets =================");
for (LpnTransitionPair key : cachedNecessarySets.keySet()) {
writeStringToPORDebugFile(lpnList[key.getLpnIndex()].getLabel() + "(" + lpnList[key.getLpnIndex()].getTransition(key.getTranIndex()).getName() + ") => ");
for (LpnTransitionPair necessary : cachedNecessarySets.get(key)) {
writeStringToPORDebugFile(lpnList[necessary.getLpnIndex()].getLabel() + "(" + lpnList[necessary.getLpnIndex()].getTransition(necessary.getTranIndex()).getName() + ") ");
}
writeStringWithEndOfLineToPORDebugFile("");
}
}
private HashSet<LpnTransitionPair> getIntSetSubstraction(
HashSet<LpnTransitionPair> left, HashSet<LpnTransitionPair> right) {
HashSet<LpnTransitionPair> sub = new HashSet<LpnTransitionPair>();
for (LpnTransitionPair lpnTranPair : left) {
if (!right.contains(lpnTranPair))
sub.add(lpnTranPair);
}
return sub;
}
// private LpnTranList getSetSubtraction(LpnTranList left, LpnTranList right) {
// LpnTranList sub = new LpnTranList();
// for (Transition lpnTran : left) {
// if (!right.contains(lpnTran))
// sub.add(lpnTran);
// return sub;
public boolean stateOnStack(int lpnIndex, State curState, HashSet<PrjState> stateStack) {
boolean isStateOnStack = false;
for (PrjState prjState : stateStack) {
State[] stateArray = prjState.toStateArray();
if (stateArray[lpnIndex] == curState) {
isStateOnStack = true;
break;
}
}
return isStateOnStack;
}
private void printIntegerSet(HashSet<LpnTransitionPair> indicies, StateGraph[] sgList, String setName) {
if (!setName.isEmpty())
System.out.print(setName + ": ");
if (indicies == null) {
System.out.println("null");
}
else if (indicies.isEmpty()) {
System.out.println("empty");
}
else {
for (LpnTransitionPair lpnTranPair : indicies) {
System.out.print("\t" + sgList[lpnTranPair.getLpnIndex()].getLpn().getLabel() + "("
+ sgList[lpnTranPair.getLpnIndex()].getLpn().getAllTransitions()[lpnTranPair.getTranIndex()].getName() + ") \t");
}
System.out.print("\n");
}
}
private void writeIntegerSetToPORDebugFile(HashSet<LpnTransitionPair> indicies, StateGraph[] sgList, String setName) {
if (!setName.isEmpty())
writeStringToPORDebugFile(setName + ": ");
if (indicies == null) {
writeStringWithEndOfLineToPORDebugFile("null");
}
else if (indicies.isEmpty()) {
writeStringWithEndOfLineToPORDebugFile("empty");
}
else {
for (LpnTransitionPair lpnTranPair : indicies) {
writeStringToPORDebugFile(sgList[lpnTranPair.getLpnIndex()].getLpn().getLabel() + "("
+ sgList[lpnTranPair.getLpnIndex()].getLpn().getAllTransitions()[lpnTranPair.getTranIndex()].getName() + "),");
}
writeStringWithEndOfLineToPORDebugFile("");
}
}
private void printIntegerSet(HashSet<LpnTransitionPair> indicies,
LhpnFile[] lpnList, String setName) {
if (!setName.isEmpty())
System.out.print(setName + ": ");
if (indicies == null) {
System.out.println("null");
}
else if (indicies.isEmpty()) {
System.out.println("empty");
}
else {
for (LpnTransitionPair lpnTranPair : indicies) {
System.out.print(lpnList[lpnTranPair.getLpnIndex()].getLabel() + "("
+ lpnList[lpnTranPair.getLpnIndex()].getAllTransitions()[lpnTranPair.getTranIndex()].getName() + ") \t");
}
System.out.print("\n");
}
}
private void writeIntegerSetToPORDebugFile(HashSet<LpnTransitionPair> indicies,
LhpnFile[] lpnList, String setName) {
if (!setName.isEmpty())
writeStringToPORDebugFile(setName + ": ");
if (indicies == null) {
writeStringWithEndOfLineToPORDebugFile("null");
}
else if (indicies.isEmpty()) {
writeStringWithEndOfLineToPORDebugFile("empty");
}
else {
for (LpnTransitionPair lpnTranPair : indicies) {
writeStringToPORDebugFile(lpnList[lpnTranPair.getLpnIndex()].getLabel() + "("
+ lpnList[lpnTranPair.getLpnIndex()].getAllTransitions()[lpnTranPair.getTranIndex()].getName() + "),");
}
writeStringWithEndOfLineToPORDebugFile("");
}
}
private void writeIntegerSetToPORDebugFile(ArrayList<HashSet<LpnTransitionPair>> indexSet,
LhpnFile[] lpnList, String setName) {
if (!setName.isEmpty())
writeStringToPORDebugFile(setName + ": ");
if (indexSet == null) {
writeStringWithEndOfLineToPORDebugFile("null");
}
else if (indexSet.isEmpty()) {
writeStringWithEndOfLineToPORDebugFile("empty");
}
else {
for (HashSet<LpnTransitionPair> lpnTranPairSet : indexSet) {
for (LpnTransitionPair lpnTranPair : lpnTranPairSet)
writeStringToPORDebugFile(lpnList[lpnTranPair.getLpnIndex()].getLabel() + "("
+ lpnList[lpnTranPair.getLpnIndex()].getAllTransitions()[lpnTranPair.getTranIndex()].getName() + "),");
}
writeStringWithEndOfLineToPORDebugFile("");
}
}
} |
package cc.arduino.utils;
import cc.arduino.os.FileNativeUtils;
import org.apache.commons.compress.archivers.ArchiveEntry;
import org.apache.commons.compress.archivers.ArchiveInputStream;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream;
import org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream;
import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream;
import processing.app.I18n;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import static processing.app.I18n._;
public class ArchiveExtractor {
/**
* Extract <b>source</b> into <b>destFolder</b>. <b>source</b> file archive
* format is autodetected from file extension.
*
* @param archiveFile
* @param destFolder
* @throws IOException
*/
public static void extract(File archiveFile, File destFolder) throws IOException {
extract(archiveFile, destFolder, 0);
}
/**
* Extract <b>source</b> into <b>destFolder</b>. <b>source</b> file archive
* format is autodetected from file extension.
*
* @param archiveFile Archive file to extract
* @param destFolder Destination folder
* @param stripPath Number of path elements to strip from the paths contained in the
* archived files
* @throws IOException
*/
public static void extract(File archiveFile, File destFolder, int stripPath) throws IOException {
// Folders timestamps must be set at the end of archive extraction
// (because creating a file in a folder alters the folder's timestamp)
Map<File, Long> foldersTimestamps = new HashMap<File, Long>();
ArchiveInputStream in = null;
try {
// Create an ArchiveInputStream with the correct archiving algorithm
if (archiveFile.getName().endsWith("tar.bz2")) {
InputStream fin = new FileInputStream(archiveFile);
fin = new BZip2CompressorInputStream(fin);
in = new TarArchiveInputStream(fin);
} else if (archiveFile.getName().endsWith("zip")) {
InputStream fin = new FileInputStream(archiveFile);
in = new ZipArchiveInputStream(fin);
} else if (archiveFile.getName().endsWith("tar.gz")) {
InputStream fin = new FileInputStream(archiveFile);
fin = new GzipCompressorInputStream(fin);
in = new TarArchiveInputStream(fin);
} else if (archiveFile.getName().endsWith("tar")) {
InputStream fin = new FileInputStream(archiveFile);
in = new TarArchiveInputStream(fin);
} else {
throw new IOException("Archive format not supported.");
}
String pathPrefix = "";
Map<File, File> hardLinks = new HashMap<File, File>();
Map<File, Integer> hardLinksMode = new HashMap<File, Integer>();
Map<File, File> symLinks = new HashMap<File, File>();
Map<File, Long> symLinksModifiedTimes = new HashMap<File, Long>();
// Cycle through all the archive entries
while (true) {
ArchiveEntry entry = in.getNextEntry();
if (entry == null) {
break;
}
// Extract entry info
long size = entry.getSize();
String name = entry.getName();
boolean isDirectory = entry.isDirectory();
boolean isLink = false;
boolean isSymLink = false;
String linkName = null;
Integer mode = null;
long modifiedTime = entry.getLastModifiedDate().getTime();
{
// Skip MacOSX metadata
int slash = name.lastIndexOf('/');
if (slash == -1) {
if (name.startsWith("._")) {
continue;
}
} else {
if (name.substring(slash + 1).startsWith("._")) {
continue;
}
}
}
// Skip git metadata
if (name.contains("pax_global_header")) {
continue;
}
if (entry instanceof TarArchiveEntry) {
TarArchiveEntry tarEntry = (TarArchiveEntry) entry;
mode = tarEntry.getMode();
isLink = tarEntry.isLink();
isSymLink = tarEntry.isSymbolicLink();
linkName = tarEntry.getLinkName();
}
// On the first archive entry, if requested, detect the common path
// prefix to be stripped from filenames
if (stripPath > 0 && pathPrefix.isEmpty()) {
int slash = 0;
while (stripPath > 0) {
slash = name.indexOf("/", slash);
if (slash == -1) {
throw new IOException("Invalid archive: it must contains a single root folder");
}
slash++;
stripPath
}
pathPrefix = name.substring(0, slash);
}
// Strip the common path prefix when requested
if (!name.startsWith(pathPrefix)) {
throw new IOException("Invalid archive: it must contains a single root folder while file " + name + " is outside " + pathPrefix);
}
name = name.substring(pathPrefix.length());
if (name.isEmpty()) {
continue;
}
File outputFile = new File(destFolder, name);
File outputLinkedFile = null;
if (isLink) {
if (!linkName.startsWith(pathPrefix)) {
throw new IOException("Invalid archive: it must contains a single root folder while file " + linkName + " is outside " + pathPrefix);
}
linkName = linkName.substring(pathPrefix.length());
outputLinkedFile = new File(destFolder, linkName);
}
if (isSymLink) {
// Symbolic links are referenced with relative paths
outputLinkedFile = new File(linkName);
if (outputLinkedFile.isAbsolute()) {
System.err.println(I18n.format(_("Warning: file {0} links to an absolute path {1}"), outputFile, outputLinkedFile));
System.err.println();
}
}
// Safety check
if (isDirectory) {
if (outputFile.isFile()) {
throw new IOException("Can't create folder " + outputFile + ", a file with the same name exists!");
}
} else {
// - isLink
// - isSymLink
// - anything else
if (outputFile.exists()) {
throw new IOException("Can't extract file " + outputFile + ", file already exists!");
}
}
// Extract the entry
if (isDirectory) {
if (!outputFile.exists() && !outputFile.mkdirs()) {
throw new IOException("Could not create folder: " + outputFile);
}
foldersTimestamps.put(outputFile, modifiedTime);
} else if (isLink) {
hardLinks.put(outputFile, outputLinkedFile);
hardLinksMode.put(outputFile, mode);
} else if (isSymLink) {
symLinks.put(outputFile, outputLinkedFile);
symLinksModifiedTimes.put(outputFile, modifiedTime);
} else {
// Create the containing folder if not exists
if (!outputFile.getParentFile().isDirectory()) {
outputFile.getParentFile().mkdirs();
}
copyStreamToFile(in, size, outputFile);
outputFile.setLastModified(modifiedTime);
}
if (mode != null && !isSymLink && outputFile.exists()) {
FileNativeUtils.chmod(outputFile, mode);
}
}
for (Map.Entry<File, File> entry : hardLinks.entrySet()) {
FileNativeUtils.link(entry.getValue(), entry.getKey());
Integer mode = hardLinksMode.get(entry.getKey());
if (mode != null) {
FileNativeUtils.chmod(entry.getKey(), mode);
}
}
for (Map.Entry<File, File> entry : symLinks.entrySet()) {
FileNativeUtils.symlink(entry.getValue(), entry.getKey());
entry.getKey().setLastModified(symLinksModifiedTimes.get(entry.getKey()));
}
} finally {
if (in != null) {
in.close();
}
}
// Set folders timestamps
for (File folder : foldersTimestamps.keySet()) {
folder.setLastModified(foldersTimestamps.get(folder));
}
}
private static void copyStreamToFile(InputStream in, long size, File outputFile) throws IOException {
FileOutputStream fos = new FileOutputStream(outputFile);
try {
// if size is not available, copy until EOF...
if (size == -1) {
byte buffer[] = new byte[4096];
int length;
while ((length = in.read(buffer)) != -1) {
fos.write(buffer, 0, length);
}
return;
}
// ...else copy just the needed amount of bytes
byte buffer[] = new byte[4096];
while (size > 0) {
int length = in.read(buffer);
if (length <= 0) {
throw new IOException("Error while extracting file " + outputFile.getAbsolutePath());
}
fos.write(buffer, 0, length);
size -= length;
}
} finally {
fos.close();
}
}
} |
package org.sagebionetworks.bridge.validators;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.fail;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import org.junit.Before;
import org.junit.Test;
import org.sagebionetworks.bridge.TestUtils;
import org.sagebionetworks.bridge.dynamodb.DynamoStudy;
import org.sagebionetworks.bridge.exceptions.InvalidEntityException;
import org.sagebionetworks.bridge.models.studies.EmailTemplate;
import org.sagebionetworks.bridge.models.studies.MimeType;
import org.sagebionetworks.bridge.models.studies.PasswordPolicy;
import org.sagebionetworks.bridge.models.studies.Study;
import com.google.common.collect.Sets;
public class StudyValidatorTest {
private DynamoStudy study;
@Before
public void createValidStudy() {
study = TestUtils.getValidStudy(StudyValidatorTest.class);
}
public void assertCorrectMessage(Study study, String fieldName, String message) {
try {
Validate.entityThrowingException(StudyValidator.INSTANCE, study);
fail("should have thrown an exception");
} catch(InvalidEntityException e) {
List<String> errors = e.getErrors().get(fieldName);
assertFalse(errors == null || errors.isEmpty());
String error = errors.get(0);
assertEquals(error, message);
}
}
@Test
public void acceptsValidStudy() {
Validate.entityThrowingException(StudyValidator.INSTANCE, study);
}
// While 2 is not a good length, we must allow it for legacy reasons.
@Test
public void minLengthCannotBeLessThan2() {
study.setPasswordPolicy(new PasswordPolicy(1, false, false, false, false));
assertCorrectMessage(study, "passwordPolicy.minLength", "passwordPolicy.minLength must be 2-999 characters");
}
@Test
public void sponsorNameRequired() {
study.setSponsorName("");
assertCorrectMessage(study, "sponsorName", "sponsorName is required");
}
@Test
public void minLengthCannotBeMoreThan999() {
study.setPasswordPolicy(new PasswordPolicy(1000, false, false, false, false));
assertCorrectMessage(study, "passwordPolicy.minLength", "passwordPolicy.minLength must be 2-999 characters");
}
@Test
public void resetPasswordMustHaveUrlVariable() {
study.setResetPasswordTemplate(new EmailTemplate("subject", "no url variable", MimeType.TEXT));
assertCorrectMessage(study, "resetPasswordTemplate.body", "resetPasswordTemplate.body must contain the ${url} template variable");
}
@Test
public void verifyEmailMustHaveUrlVariable() {
study.setVerifyEmailTemplate(new EmailTemplate("subject", "no url variable", MimeType.TEXT));
assertCorrectMessage(study, "verifyEmailTemplate.body", "verifyEmailTemplate.body must contain the ${url} template variable");
}
@Test
public void cannotCreateIdentifierWithUppercase() {
study.setIdentifier("Test");
assertCorrectMessage(study, "identifier", "identifier must contain only lower-case letters and/or numbers with optional dashes");
}
@Test
public void cannotCreateInvalidIdentifierWithSpaces() {
study.setIdentifier("test test");
assertCorrectMessage(study, "identifier", "identifier must contain only lower-case letters and/or numbers with optional dashes");
}
@Test
public void identifierCanContainDashes() {
study.setIdentifier("sage-pd");
Validate.entityThrowingException(StudyValidator.INSTANCE, study);
}
@Test
public void acceptsMultipleValidSupportEmailAddresses() {
study.setSupportEmail("test@test.com,test2@test.com");
Validate.entityThrowingException(StudyValidator.INSTANCE, study);
}
@Test
public void rejectsInvalidSupportEmailAddresses() {
study.setSupportEmail("test@test.com,asdf,test2@test.com");
assertCorrectMessage(study, "supportEmail", "supportEmail 'asdf' is not a valid email address");
}
@Test
public void rejectsInvalidSupportEmailAddresses2() {
study.setSupportEmail("test@test.com,,,test2@test.com");
assertCorrectMessage(study, "supportEmail", "supportEmail '' is not a valid email address");
}
@Test
public void requiresMissingSupportEmail() {
study.setSupportEmail(null);
assertCorrectMessage(study, "supportEmail", "supportEmail is required");
}
@Test
public void acceptsMultipleValidTechnicalEmailAddresses() {
study.setTechnicalEmail("test@test.com,test2@test.com");
Validate.entityThrowingException(StudyValidator.INSTANCE, study);
}
@Test
public void rejectsInvalidTechnicalEmailAddresses() {
study.setTechnicalEmail("test@test.com,asdf,test2@test.com");
assertCorrectMessage(study, "technicalEmail", "technicalEmail 'asdf' is not a valid email address");
}
@Test
public void rejectsInvalidTechnicalEmailAddresses2() {
study.setTechnicalEmail("test@test.com,,,test2@test.com");
assertCorrectMessage(study, "technicalEmail", "technicalEmail '' is not a valid email address");
}
@Test
public void requiresMissingTechnicalEmail() {
study.setTechnicalEmail(null);
assertCorrectMessage(study, "technicalEmail", "technicalEmail is required");
}
@Test
public void rejectsInvalidConsentEmailAddresses() {
study.setConsentNotificationEmail("test@test.com,asdf,test2@test.com");
assertCorrectMessage(study, "consentNotificationEmail", "consentNotificationEmail 'asdf' is not a valid email address");
}
@Test
public void cannotAddConflictingUserProfileAttribute() {
study.getUserProfileAttributes().add("username");
assertCorrectMessage(study, "userProfileAttributes", "userProfileAttributes 'username' conflicts with existing user profile property");
}
@Test
public void requiresMissingConsentNotificationEmail() {
study.setConsentNotificationEmail(null);
assertCorrectMessage(study, "consentNotificationEmail", "consentNotificationEmail is required");
}
@Test
public void requiresPasswordPolicy() {
study.setPasswordPolicy(null);
assertCorrectMessage(study, "passwordPolicy", "passwordPolicy is required");
}
@Test
public void requiresVerifyEmailTemplate() {
study.setVerifyEmailTemplate(null);
assertCorrectMessage(study, "verifyEmailTemplate", "verifyEmailTemplate is required");
}
@Test
public void requiresVerifyEmailTemplateWithSubject() {
study.setVerifyEmailTemplate(new EmailTemplate(" ", "body", MimeType.HTML));
assertCorrectMessage(study, "verifyEmailTemplate.subject", "verifyEmailTemplate.subject is required");
}
@Test
public void requiresVerifyEmailTemplateWithBody() {
study.setVerifyEmailTemplate(new EmailTemplate("subject", null, MimeType.HTML));
assertCorrectMessage(study, "verifyEmailTemplate.body", "verifyEmailTemplate.body is required");
}
@Test
public void requiresResetPasswordTemplate() {
study.setResetPasswordTemplate(null);
assertCorrectMessage(study, "resetPasswordTemplate", "resetPasswordTemplate is required");
}
@Test
public void requiresResetPasswordTemplateWithSubject() {
study.setResetPasswordTemplate(new EmailTemplate(" ", "body", MimeType.TEXT));
assertCorrectMessage(study, "resetPasswordTemplate.subject", "resetPasswordTemplate.subject is required");
}
@Test
public void requiresResetPasswordTemplateWithBody() {
study.setResetPasswordTemplate(new EmailTemplate("subject", null, MimeType.TEXT));
assertCorrectMessage(study, "resetPasswordTemplate.body", "resetPasswordTemplate.body is required");
}
@Test
public void cannotSetMinAgeOfConsentLessThanZero() {
study.setMinAgeOfConsent(-100);
assertCorrectMessage(study, "minAgeOfConsent", "minAgeOfConsent must be zero (no minimum age of consent) or higher");
}
@Test
public void cannotSetMaxNumOfParticipantsLessThanZero() {
study.setMaxNumOfParticipants(-100);
assertCorrectMessage(study, "maxNumOfParticipants", "maxNumOfParticipants must be zero (no limit on enrollees) or higher");
}
@Test
public void shorterLisOfDataGroupsOK() {
study.setDataGroups(Sets.newHashSet("beta_users", "production_users", "testers", "internal"));
Validate.entityThrowingException(StudyValidator.INSTANCE, study);
}
@Test
public void dataGroupCharactersRestricted() {
study.setDataGroups(Sets.newHashSet("Liège"));
assertCorrectMessage(study, "dataGroups", "dataGroups contains invalid tag 'Liège' (only letters, numbers, underscore and dash allowed)");
}
@Test
public void cannotExportVeryLongListOfDataGroups() {
study.setDataGroups(newLinkedHashSet("Antwerp", "Ghent", "Charleroi", "Liege", "Brussels-City", "Bruges", "Schaerbeek", "Anderlecht", "Namur", "Leuven", "Mons", "Molenbeek-Saint-Jean"));
assertCorrectMessage(study, "dataGroups", "dataGroups will not export to Synapse (string is over 100 characters: 'Antwerp, Ghent, Charleroi, Liege, Brussels-City, Bruges, Schaerbeek, Anderlecht, Namur, Leuven, Mons, Molenbeek-Saint-Jean')");
}
private Set<String> newLinkedHashSet(String... list) {
Set<String> set = new LinkedHashSet<>();
for (String element : list) {
set.add(element);
}
return set;
}
} |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.venky.swf.db;
import java.io.InputStream;
import java.io.Reader;
import java.math.BigDecimal;
import java.sql.Date;
import java.sql.SQLException;
import java.sql.Time;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.List;
import java.util.TimeZone;
import com.venky.core.date.DateUtils;
import com.venky.core.util.Bucket;
import com.venky.swf.db.model.Count;
import com.venky.swf.db.model.Model;
import com.venky.swf.db.table.Table;
import com.venky.swf.exceptions.SWFTimeoutException;
import com.venky.swf.sql.DataManupulationStatement;
import com.venky.swf.sql.Select;
/**
*
* @author venky
*/
public class MySqlHelper extends JdbcTypeHelper{
@Override
public String getAutoIncrementInstruction() {
return (" BIGINT NOT NULL AUTO_INCREMENT ");
}
@Override
public String getCurrentTimeStampKW(){
return "CURRENT_TIMESTAMP";
}
@Override
public String getCurrentDateKW(){
return "CURRENT_DATE" ;
}
public boolean isQueryTimeoutException(SQLException ex){
if (!super.isQueryTimeoutException(ex)){
return ex.getClass().getName().endsWith("TimeoutException");
}
return false;
}
public boolean hasTransactionRolledBack(Throwable ex){
if (super.hasTransactionRolledBack(ex) || ex instanceof SWFTimeoutException){
return true;
}
return false;
}
@Override
public String getDefaultKW(TypeRef<?> ref,Object value) {
if (Boolean.class.isAssignableFrom(ref.getJavaClass()) || boolean.class.isAssignableFrom(ref.getJavaClass())) {
if ((Boolean)value){
return "b'1'";
}else {
return "b'0'";
}
}
return super.getDefaultKW(ref, value);
}
protected MySqlHelper() {
/**
* Specify size and scale for a data type only if the database accepts
* them during table creation
*/
registerjdbcSQLType(Boolean.class, new TypeRef<Boolean>(
java.sql.Types.BIT, "BIT", 0, 0,false,false,
new BooleanConverter()));
registerjdbcSQLType(boolean.class, new TypeRef<Boolean>(
java.sql.Types.BIT, "BIT", 0, 0,false,false,
new BooleanConverter()));
registerjdbcSQLType(Byte.class, new TypeRef<Byte>(java.sql.Types.TINYINT,
"TINYINT", 0, 0, false,false,new ByteConverter()));
registerjdbcSQLType(byte.class, new TypeRef<Byte>(java.sql.Types.TINYINT,
"TINYINT", 0, 0, false,false,new ByteConverter()));
registerjdbcSQLType(Short.class,
new TypeRef<Short>(java.sql.Types.SMALLINT, "SMALLINT", 0, 0,false,false,
new ShortConverter()));
registerjdbcSQLType(short.class,
new TypeRef<Short>(java.sql.Types.SMALLINT, "SMALLINT", 0, 0,false,false,
new ShortConverter()));
registerjdbcSQLType(Integer.class,
new TypeRef<Integer>(java.sql.Types.INTEGER, "INTEGER", 0, 0,false,false,
new IntegerConverter()));
registerjdbcSQLType(int.class, new TypeRef<Integer>(java.sql.Types.INTEGER,
"INTEGER", 0, 0, false,false, new IntegerConverter()));
registerjdbcSQLType(Long.class, new TypeRef<Long>(java.sql.Types.BIGINT,
"BIGINT", 0, 0,false,false, new LongConverter()));
registerjdbcSQLType(long.class, new TypeRef<Long>(java.sql.Types.BIGINT,
"BIGINT", 0, 0,false,false, new LongConverter()));
registerjdbcSQLType(BigDecimal.class, new TypeRef<BigDecimal>(
java.sql.Types.DECIMAL, "DECIMAL", 15, 10,false,false,
new BigDecimalConverter()));// also NUMERIC
registerjdbcSQLType(Float.class, new TypeRef<Float>(java.sql.Types.REAL,
"FLOAT", 10, 7,false,false, new FloatConverter()));
registerjdbcSQLType(float.class, new TypeRef<Float>(java.sql.Types.REAL,
"FLOAT", 10, 7, false,false,new FloatConverter()));
registerjdbcSQLType(Double.class, new TypeRef<Double>(
java.sql.Types.DOUBLE, "DOUBLE", 0, 0, false,false,new DoubleConverter())); // ALSO
// FLOAT
registerjdbcSQLType(double.class, new TypeRef<Double>(
java.sql.Types.DOUBLE, "DOUBLE", 0, 0, false,false,new DoubleConverter())); // ALSO
registerjdbcSQLType(Bucket.class, new TypeRef<Bucket>(
java.sql.Types.DOUBLE, "DOUBLE", 0, 0, false,false,new BucketConverter())); // ALSO
// FLOAT
registerjdbcSQLType(Date.class, new TypeRef<Date>(java.sql.Types.DATE,
"DATE", 0, 0, true, true, new DateConverter(DateUtils.ISO_DATE_FORMAT_STR, TimeZone.getDefault())));
registerjdbcSQLType(Time.class, new TypeRef<Time>(
java.sql.Types.TIME, "TIME", 0, 0, true, true ,new TimeConverter(DateUtils.ISO_TIME_FORMAT_STR,TimeZone.getDefault())));
registerjdbcSQLType(java.sql.Timestamp.class, new TypeRef<Timestamp>(
java.sql.Types.TIMESTAMP, "DATETIME", 0, 0, true, false,
new TimestampConverter()));
registerjdbcSQLType(String.class, new TypeRef<String>(
java.sql.Types.VARCHAR, "VARCHAR", 128, 0, true, true,
new StringConverter())); // ALSO CHAR, LONG VARCHAR
registerjdbcSQLType(String.class, new TypeRef<String>(
java.sql.Types.CHAR, "VARCHAR", 128, 0, true, true,
new StringConverter())); // ALSO CHAR, LONG VARCHAR
registerjdbcSQLType(Reader.class, new TypeRef<Reader>(java.sql.Types.CLOB,
"LONGTEXT", 0, 0, true, true, new ReaderConverter()));
registerjdbcSQLType(Reader.class, new TypeRef<Reader>(java.sql.Types.LONGVARCHAR,
"LONGTEXT", 0, 0, true, true, new ReaderConverter()));
registerjdbcSQLType(InputStream.class, new TypeRef<InputStream>(java.sql.Types.LONGVARBINARY,
"LONGBLOB", 0, 0, true, true, new InputStreamConverter()));
registerjdbcSQLType(String[].class, new TypeRef<>(Types.VARCHAR,
"VARCHAR",128,0,true,true,new StringArrayConverter()));
}
@Override
protected <M extends Model> void updateSequence(Table<M> table){
List<Count> counts = new Select("MAX(id) AS COUNT").from(table.getModelClass()).execute(Count.class);
Count count = counts.get(0);
DataManupulationStatement ddl = new DataManupulationStatement(table.getPool());
if (count.getCount() < getPrimaryKeyOffset() ){
count.setCount(getPrimaryKeyOffset()- 1L);
}
ddl.add("ALTER TABLE ").add(table.getRealTableName()).add(" AUTO_INCREMENT = ").add( String.valueOf( count.getCount() + 1L) );
ddl.executeUpdate();
}
} |
package org.swows.xmlinrdf;
import java.io.IOException;
import java.io.StringReader;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Random;
import java.util.Vector;
import java.util.concurrent.ConcurrentHashMap;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.swows.vocabulary.xml;
import org.swows.vocabulary.xmlInstance;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import com.hp.hpl.jena.graph.BulkUpdateHandler;
import com.hp.hpl.jena.graph.Capabilities;
import com.hp.hpl.jena.graph.Graph;
import com.hp.hpl.jena.graph.GraphEventManager;
import com.hp.hpl.jena.graph.GraphStatisticsHandler;
import com.hp.hpl.jena.graph.Node;
import com.hp.hpl.jena.graph.Reifier;
import com.hp.hpl.jena.graph.TransactionHandler;
import com.hp.hpl.jena.graph.Triple;
import com.hp.hpl.jena.graph.TripleMatch;
import com.hp.hpl.jena.graph.impl.SimpleEventManager;
import com.hp.hpl.jena.graph.impl.SimpleTransactionHandler;
import com.hp.hpl.jena.graph.query.QueryHandler;
import com.hp.hpl.jena.graph.query.SimpleQueryHandler;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.rdf.model.ResourceFactory;
import com.hp.hpl.jena.rdf.model.StmtIterator;
import com.hp.hpl.jena.shared.AddDeniedException;
import com.hp.hpl.jena.shared.DeleteDeniedException;
import com.hp.hpl.jena.shared.PrefixMapping;
import com.hp.hpl.jena.shared.impl.PrefixMappingImpl;
import com.hp.hpl.jena.sparql.graph.Reifier2;
import com.hp.hpl.jena.util.iterator.ExtendedIterator;
import com.hp.hpl.jena.util.iterator.Filter;
import com.hp.hpl.jena.util.iterator.Map1;
import com.hp.hpl.jena.util.iterator.NiceIterator;
import com.hp.hpl.jena.util.iterator.NullIterator;
import com.hp.hpl.jena.util.iterator.SingletonIterator;
import com.hp.hpl.jena.vocabulary.RDF;
// TODO: Auto-generated Javadoc
/**
* The Class DomEncoder.
*/
public class DomEncoder {
/*
private static interface NodeReference {
public abstract org.w3c.dom.Node getNode();
}
*/
static class EncodedDocument implements Graph {
private static final NullIterator<Triple> emptyTripleIterator = new NullIterator<Triple>();
private static final NullIterator<org.w3c.dom.Node> emptyNodeIterator = new NullIterator<org.w3c.dom.Node>();
private Document document;
private Node rootNode = null;
private boolean closed = false;
/*
private Map<AnonId, Element> mapBlankId2Element = new ConcurrentHashMap<AnonId, Element>();
private Map<Element, AnonId> mapElement2BlankId = new ConcurrentHashMap<Element, AnonId>();
private Map<AnonId, Element> mapBlankId2Attr = new ConcurrentHashMap<AnonId, Element>();
private Map<Element, AnonId> mapAttr2BlankId = new ConcurrentHashMap<Element, AnonId>();
*/
private Map<Node, org.w3c.dom.Node> mapBlankId2XmlNode = new ConcurrentHashMap<Node, org.w3c.dom.Node>();
private Map<org.w3c.dom.Node, Node> mapXmlNode2BlankId = new ConcurrentHashMap<org.w3c.dom.Node, Node>();
public EncodedDocument(Document document) {
this.document = document;
}
public EncodedDocument(Document document, String rootUri) {
this.document = document;
rootNode = Node.createURI(rootUri);
}
private Node mapXmlNode2GraphNode(org.w3c.dom.Node node) {
Node graphNode = mapXmlNode2BlankId.get(node);
if (graphNode != null)
return graphNode;
if (node.getNodeType() == org.w3c.dom.Node.DOCUMENT_NODE && rootNode != null)
graphNode = rootNode;
if (node.getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) {
Attr idAttr = ((Element) node).getAttributeNode("id");
if (idAttr != null)
graphNode = Node.createURI(xmlInstance.getURI() + idAttr.getValue());
else {
Attr xmlIdAttr = ((Element) node).getAttributeNodeNS("http:
if (xmlIdAttr != null)
graphNode = Node.createURI(xmlInstance.getURI() + xmlIdAttr.getValue());
else {
Attr svgIdAttr = ((Element) node).getAttributeNodeNS("http:
if (svgIdAttr != null)
graphNode = Node.createURI(xmlInstance.getURI() + svgIdAttr.getValue());
}
}
}
if (graphNode == null)
graphNode = Node.createAnon();
mapXmlNode2BlankId.put(node, graphNode);
mapBlankId2XmlNode.put(graphNode, node);
return graphNode;
}
private org.w3c.dom.Node mapGraphNode2XmlNode(Node node) {
// if (node.isURI()) {
// if (rootNode != null && rootNode.equals(node))
// return document;
// return document.getElementById(node.getURI());
// if (node.isBlank())
return mapBlankId2XmlNode.get(node);
// return null;
}
private Iterator<org.w3c.dom.Node> listNodesExceptDocument() {
return Utils.listSubtreeNodes(document.getDocumentElement());
}
private Iterator<org.w3c.dom.Node> listNodes() {
return new NullIterator<org.w3c.dom.Node>()
.andThen(new SingletonIterator<org.w3c.dom.Node>(document))
.andThen(listNodesExceptDocument());
}
@Override
public void close() {
closed = true;
}
@Override
public boolean contains(Triple t) {
return contains(t.getSubject(), t.getPredicate(), t.getObject());
}
@Override
public boolean contains(Node s, Node p, Node o) {
if (s == null || !s.isConcrete()) {
if (p == null || !p.isConcrete()) {
if (o == null || !o.isConcrete()) {
// Schema: * * *
return true;
} else {
// Schema: * * o
return // namescape
( o.isURI() && ( xml.getURI().equals(o.getURI()) || document.getElementsByTagNameNS(o.getURI(), "*").getLength() > 0 ) )
|| // nodeName
( document.getElementsByTagNameNS("*", o.getLiteralLexicalForm()).getLength() > 0 )
|| // nodeVallue
Utils.containsNodeValue(document, o.getLiteralLexicalForm())
|| // nodeType
( o.isURI() && Utils.containsNodeType( document, Utils.mapResource2nodeType( ResourceFactory.createResource( o.getURI() ) ) ) )
|| mapGraphNode2XmlNode(o) != null;
}
} else {
if (o == null || !o.isConcrete()) {
// Schema: * p *
if ( p.equals(xml.namespace.asNode()) )
return true;
if ( p.equals(xml.nodeName.asNode()) )
return true;
if ( p.equals(xml.nodeValue.asNode()) )
return Utils.containsNodeValue(document);
if ( p.equals(xml.nodeType.asNode()) )
return true;
if (p.equals(xml.hasChild.asNode()))
return true;
if (p.equals(xml.firstChild.asNode()))
return true;
if (p.equals(xml.lastChild.asNode()))
return true;
if (p.equals(xml.previousSibling.asNode()))
return Utils.containsSiblings(document);
if (p.equals(xml.nextSibling.asNode()))
return Utils.containsSiblings(document);
if (p.equals(xml.parentNode.asNode()))
return true;
if (p.equals(xml.hasAttribute.asNode()))
return Utils.containsAttributes(document);
if (p.equals(xml.ownerDocument.asNode()))
return true;
return false;
} else {
// Schema: * p o
if ( p.equals(xml.namespace.asNode()) )
return o.isURI()
&& ( xml.getURI().equals(o.getURI()) || document.getElementsByTagNameNS(o.getURI(), "*").getLength() > 0 );
if ( p.equals(xml.nodeName.asNode()) )
return (document.getElementsByTagNameNS("*", o.getLiteralLexicalForm()).getLength() > 0 );
if ( p.equals(xml.nodeValue.asNode()) )
return Utils.containsNodeValue(document, o.getLiteralLexicalForm());
if ( p.equals(xml.nodeType.asNode()) )
return o.isURI() && Utils.containsNodeType(document, Utils.mapResource2nodeType(ResourceFactory.createResource(o.getURI())));
// Part in which object must represent an xml node
org.w3c.dom.Node objXmlNode = mapGraphNode2XmlNode(o);
if (objXmlNode == null)
return false;
if (p.equals(xml.hasChild.asNode()))
return objXmlNode.getParentNode() != null;
if (p.equals(xml.firstChild.asNode()))
return objXmlNode.getParentNode() != null
&& objXmlNode.getPreviousSibling() == null;
if (p.equals(xml.lastChild.asNode()))
return objXmlNode.getParentNode() != null
&& objXmlNode.getNextSibling() == null;
if (p.equals(xml.previousSibling.asNode()))
return objXmlNode.getNextSibling() != null;
if (p.equals(xml.nextSibling.asNode()))
return objXmlNode.getPreviousSibling() != null;
if (p.equals(xml.parentNode.asNode()))
return objXmlNode.hasChildNodes();
if (p.equals(xml.hasAttribute.asNode()))
return (objXmlNode.getNodeType() == org.w3c.dom.Node.ATTRIBUTE_NODE);
if (p.equals(xml.ownerDocument.asNode()))
return objXmlNode.getNodeType() == org.w3c.dom.Node.DOCUMENT_NODE;
return false;
}
}
} else {
if (p == null || !p.isConcrete()) {
if (o == null || !o.isConcrete()) {
// Schema: s * *
return mapGraphNode2XmlNode(s) != null;
} else {
// Schema: s * o
org.w3c.dom.Node subjXmlNode = mapGraphNode2XmlNode(s);
if (subjXmlNode == null)
return false;
if ( // namespace
//o.hasURI(subjXmlNode.lookupNamespaceURI(subjXmlNode.getPrefix()))
o.hasURI(subjXmlNode.getNamespaceURI())
// nodeName
|| o.getLiteralLexicalForm().equals(subjXmlNode.getNodeName())
// nodeValue
|| subjXmlNode.getNodeValue() != null && o.getLiteralLexicalForm().equals(subjXmlNode.getNodeValue())
// nodeType
|| o.equals(Utils.mapNodeType2resource(subjXmlNode.getNodeType()).asNode())
) return true;
// Part in which object must represent an xml node
org.w3c.dom.Node objXmlNode = mapGraphNode2XmlNode(o);
if (objXmlNode == null)
return false;
return // hasChild
objXmlNode.getParentNode().equals(subjXmlNode)
// firstChild
|| subjXmlNode.getFirstChild().equals(objXmlNode)
// lastChild
|| subjXmlNode.getLastChild().equals(objXmlNode)
// previousSibling
|| subjXmlNode.getPreviousSibling().equals(objXmlNode)
// nextSibling
|| subjXmlNode.getNextSibling().equals(objXmlNode)
// parentNode
|| subjXmlNode.getParentNode().equals(objXmlNode)
// hasAttribute
|| ( objXmlNode.getNodeType() == org.w3c.dom.Node.ATTRIBUTE_NODE
&& subjXmlNode
.getAttributes()
.getNamedItemNS(
//objXmlNode.lookupNamespaceURI(objXmlNode.getPrefix()),
objXmlNode.getNamespaceURI(),
objXmlNode.getLocalName() ) != null )
// ownerDocument
|| subjXmlNode.getOwnerDocument().equals(objXmlNode);
}
} else {
if (o == null || !o.isConcrete()) {
// Schema: s p *
return ( mapGraphNode2XmlNode(s) == null )
? false
: xml.isNodeProperty(p);
} else {
// Schema: s p o
org.w3c.dom.Node subjXmlNode = mapGraphNode2XmlNode(s);
if (subjXmlNode == null)
return false;
if ( p.equals(xml.namespace.asNode()) )
//return o.hasURI(subjXmlNode.lookupNamespaceURI(subjXmlNode.getPrefix()));
return o.hasURI(subjXmlNode.getNamespaceURI());
if ( p.equals(xml.nodeName.asNode()) )
return o.getLiteralLexicalForm().equals(subjXmlNode.getNodeName());
if ( p.equals(xml.nodeValue.asNode()) )
return subjXmlNode.getNodeValue() != null && o.getLiteralLexicalForm().equals(subjXmlNode.getNodeValue());
if ( p.equals(xml.nodeType.asNode()) )
return o.equals(Utils.mapNodeType2resource(subjXmlNode.getNodeType()).asNode());
// Part in which object must represent an xml node
org.w3c.dom.Node objXmlNode = mapGraphNode2XmlNode(o);
if (objXmlNode == null)
return false;
if (p.equals(xml.hasChild.asNode())) {
org.w3c.dom.Node parentNode = objXmlNode.getParentNode();
return (parentNode != null && parentNode.equals(subjXmlNode));
}
if (p.equals(xml.firstChild.asNode()))
return subjXmlNode.getFirstChild().equals(objXmlNode);
if (p.equals(xml.lastChild.asNode()))
return subjXmlNode.getLastChild().equals(objXmlNode);
if (p.equals(xml.previousSibling.asNode())) {
org.w3c.dom.Node previousSiblingNode = objXmlNode.getParentNode();
return (previousSiblingNode != null && previousSiblingNode.equals(subjXmlNode));
}
if (p.equals(xml.nextSibling.asNode()))
return subjXmlNode.getNextSibling().equals(objXmlNode);
if (p.equals(xml.parentNode.asNode()))
return subjXmlNode.getParentNode().equals(objXmlNode);
if (p.equals(xml.hasAttribute.asNode()))
return (objXmlNode.getNodeType() == org.w3c.dom.Node.ATTRIBUTE_NODE
&& subjXmlNode.getAttributes().getNamedItemNS(
objXmlNode.lookupNamespaceURI(objXmlNode.getPrefix()),
objXmlNode.getLocalName()) != null);
if (p.equals(xml.ownerDocument.asNode()))
return subjXmlNode.getOwnerDocument().equals(objXmlNode);
return false;
}
}
}
}
@Override
public void delete(Triple t) throws DeleteDeniedException {
throw new DeleteDeniedException("XML DOM derived read only graph");
}
@Override
public boolean dependsOn(Graph other) {
return false;
}
@Override
public ExtendedIterator<Triple> find(TripleMatch m) {
Triple triple = m.asTriple();
return find( triple.getSubject(), triple.getPredicate(), triple.getObject() );
}
@Override
public ExtendedIterator<Triple> find(final Node s, final Node p, final Node o) {
if (s == null || !s.isConcrete()) {
if (p == null || !p.isConcrete()) {
if (o == null || !o.isConcrete()) {
// Schema: * * *
Iterator<org.w3c.dom.Node> documentNodes = listNodes();
ExtendedIterator<Triple> resultIterator = new NullIterator<Triple>();
while ( documentNodes.hasNext() ) {
resultIterator =
resultIterator.andThen( find( mapXmlNode2GraphNode( documentNodes.next() ), p, o ) );
}
return resultIterator;
} else {
// Schema: * * o
ExtendedIterator<Triple> resultIterator = new NullIterator<Triple>();
Iterator<Node> availableProps = xml.nodeProperties();
while (availableProps.hasNext()) {
resultIterator = resultIterator.andThen( find( s, availableProps.next(), o ) );
}
return resultIterator;
}
} else {
if (o == null || !o.isConcrete()) {
// Schema: * p *
Iterator<org.w3c.dom.Node> documentNodes = listNodes();
ExtendedIterator<Triple> resultIterator = new NullIterator<Triple>();
while ( documentNodes.hasNext() ) {
resultIterator =
resultIterator.andThen( find( mapXmlNode2GraphNode( documentNodes.next() ), p, o ) );
}
return resultIterator;
} else {
// Schema: * p o
ExtendedIterator<org.w3c.dom.Node> subjIterator = null;
if ( p.equals(xml.namespace.asNode()) && o.isURI())
subjIterator =
o.isLiteral()
? Utils.listSubtreeNodes( document, null, null, o.getURI(), null )
: emptyNodeIterator;
else if ( p.equals(xml.nodeName.asNode()) )
subjIterator =
o.isLiteral()
? Utils.listSubtreeNodes( document, null, o.getLiteralLexicalForm(), null, null )
: emptyNodeIterator;
else if ( p.equals(xml.nodeValue.asNode()) )
subjIterator =
o.isLiteral()
? Utils.listSubtreeNodes( document, null, null, null, o.getLiteralLexicalForm() )
: emptyNodeIterator;
else if ( p.equals(xml.nodeType.asNode()) ) {
if (o.isURI()) {
short nodeType = Utils.mapResource2nodeType( ResourceFactory.createResource(o.getURI()) );
if (nodeType != -1)
subjIterator = Utils.listSubtreeNodes( document, new Short(nodeType), null, null, null );
else
subjIterator = emptyNodeIterator;
} else
subjIterator = emptyNodeIterator;
}
if (subjIterator != null) {
return subjIterator.mapWith(new Map1<org.w3c.dom.Node, Triple>() {
@Override
public Triple map1(org.w3c.dom.Node currNode) {
return new Triple( mapXmlNode2GraphNode(currNode), p, o );
}
});
}
org.w3c.dom.Node objXmlNode = mapGraphNode2XmlNode(o);
if ( objXmlNode == null )
return emptyTripleIterator;
final NodeList subjList = xml.getRevNodeListProperty(objXmlNode, p);
return new NiceIterator<Triple>() {
private int subjectIndex = 0;
@Override
public boolean hasNext() {
return subjectIndex < subjList.getLength();
}
@Override
public Triple next() {
return new Triple(s,p,mapXmlNode2GraphNode(subjList.item(subjectIndex++)));
}
};
}
}
} else {
if (p == null || !p.isConcrete()) {
// Schema: s * X
org.w3c.dom.Node subjXmlNode = mapGraphNode2XmlNode(s);
if ( subjXmlNode == null )
return emptyTripleIterator;
ExtendedIterator<Triple> resultIterator = new NullIterator<Triple>();
Iterator<Node> availableProps = xml.nodeProperties();
while (availableProps.hasNext()) {
resultIterator = resultIterator.andThen( find( s, availableProps.next(), o ) );
}
return resultIterator;
} else {
if (o == null || !o.isConcrete()) {
// Schema: s p *
org.w3c.dom.Node subjXmlNode = mapGraphNode2XmlNode(s);
if (subjXmlNode == null)
return emptyTripleIterator;
Node singleObjectNode = null;
String singleObjectString = null;
if ( p.equals(xml.nodeName.asNode()) )
singleObjectString = subjXmlNode.getNodeName();
else if ( p.equals(xml.nodeValue.asNode()) )
singleObjectString = subjXmlNode.getNodeValue();
if (singleObjectString != null)
singleObjectNode = Node.createLiteral(singleObjectString);
else {
if ( p.equals(xml.namespace.asNode()) ) {
singleObjectNode =
subjXmlNode.getNamespaceURI() == null
? null
: Node.createURI(subjXmlNode.getNamespaceURI());
}
else if ( p.equals(xml.nodeType.asNode()) ) {
singleObjectNode = Utils.mapNodeType2resource(subjXmlNode.getNodeType()).asNode();
if (singleObjectNode == null)
return emptyTripleIterator;
}
}
if (singleObjectNode != null)
return new SingletonIterator<Triple>(new Triple(s, p, singleObjectNode));
else {
final NodeList objList = xml.getNodeListProperty(subjXmlNode, p);
return new NiceIterator<Triple>() {
private int objectIndex = 0;
@Override
public boolean hasNext() {
return objectIndex < objList.getLength();
}
@Override
public Triple next() {
if (!hasNext())
throw new NoSuchElementException();
return new Triple(s,p,mapXmlNode2GraphNode(objList.item(objectIndex++)));
}
};
}
} else {
// Schema: s p o
if ( contains(s, p, o) )
return new SingletonIterator<Triple>(new Triple(s, p, o));
else
return emptyTripleIterator;
}
}
}
}
@Override
public BulkUpdateHandler getBulkUpdateHandler() {
// Should be ok to return null for a readonly graph
return null;
}
@Override
public Capabilities getCapabilities() {
return new Capabilities() {
@Override
public boolean sizeAccurate() {
return false;
}
@Override
public boolean iteratorRemoveAllowed() {
return false;
}
@Override
public boolean handlesLiteralTyping() {
return true;
}
@Override
public boolean findContractSafe() {
return false;
}
@Override
public boolean deleteAllowed(boolean everyTriple) {
return false;
}
@Override
public boolean deleteAllowed() {
return false;
}
@Override
public boolean canBeEmpty() {
// there should be at least the root xml element
return false;
}
@Override
public boolean addAllowed(boolean everyTriple) {
return false;
}
@Override
public boolean addAllowed() {
return false;
}
};
}
private GraphEventManager eventManager = new SimpleEventManager(this);
@Override
public GraphEventManager getEventManager() {
return eventManager;
}
private PrefixMapping prefixMapping = new PrefixMappingImpl();
@Override
public PrefixMapping getPrefixMapping() {
return prefixMapping;
}
Reifier reifier = new Reifier2(this);
@Override
public Reifier getReifier() {
return reifier;
}
GraphStatisticsHandler graphStatisticsHandler =
new GraphStatisticsHandler() {
@Override
public long getStatistic(Node S, Node P, Node O) {
return -1;
}
};
@Override
public GraphStatisticsHandler getStatisticsHandler() {
return graphStatisticsHandler;
}
TransactionHandler transactionHandler = new SimpleTransactionHandler();
@Override
public TransactionHandler getTransactionHandler() {
return transactionHandler;
}
@Override
public boolean isClosed() {
return closed;
}
@Override
public boolean isEmpty() {
return false;
}
@Override
public boolean isIsomorphicWith(Graph g) {
if (g == this)
return true;
if (g instanceof EncodedDocument)
return document.equals(((EncodedDocument) g).document);
ExtendedIterator<Triple> extTriples = g.find(null, null, null);
while (extTriples.hasNext())
if (!contains(extTriples.next()))
return false;
ExtendedIterator<Triple> intTriples = find(null, null, null);
while (intTriples.hasNext())
if (!g.contains(intTriples.next()))
return false;
return true;
}
QueryHandler queryHandler = new SimpleQueryHandler(this);
@Override
public QueryHandler queryHandler() {
return queryHandler;
}
@Override
public int size() {
/* By graph interface contract, implementors are
* forced just to give a lower bound, we return
* 0 for simplicity.
*/
return 0;
}
@Override
public void add(Triple t) throws AddDeniedException {
throw new AddDeniedException("XML DOM derived read only graph");
}
};
/**
* Encode.
*
* @param document the document
* @return the graph
*/
public static Graph encode(Document document) {
return new EncodedDocument(document);
}
public static Graph encode(Document document, String rootUri) {
return new EncodedDocument(document, rootUri);
}
public static void developInRDF(Graph graph) {
Model model = ModelFactory.createModelForGraph(graph);
Iterator<Resource> xmlResources =
model.listResourcesWithProperty(RDF.type, xml.Document)
.filterKeep( new Filter<Resource>() {
@Override
public boolean accept(Resource res) {
StmtIterator stmtIterator = res.listProperties();
boolean textProp = false;
while (stmtIterator.hasNext()) {
Property prop = stmtIterator.next().getPredicate();
if (prop.equals(xml.text)) {
// TODO: check for single literal string value of xml.text
textProp = true;
}
else if (!prop.equals(RDF.type))
return false;
}
return textProp;
}
});
//if (!xmlResources.hasNext())
// System.out.println("Empty Iterator!");
List<Resource> xmlResourcesList = new Vector<Resource>();
while (xmlResources.hasNext())
xmlResourcesList.add(xmlResources.next());
xmlResources = xmlResourcesList.iterator();
while (xmlResources.hasNext()) {
Resource xmlRes = xmlResources.next();
String xmlString = xmlRes.getRequiredProperty(xml.text).getString();
InputSource xmlInputSource = new InputSource(new StringReader(xmlString));
String rootUri = null;
Node rootNode = null;
while (rootUri == null || graph.contains(rootNode, Node.ANY, Node.ANY) || graph.contains(Node.ANY, Node.ANY, rootNode) ) {
rootUri = getRandomString();
rootNode = Node.createURI(rootUri);
}
Document newDoc;
try {
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
docBuilderFactory.setCoalescing(true);
//docBuilderFactory.setFeature("XML 2.0", true);
docBuilderFactory.setNamespaceAware(true);
newDoc = docBuilderFactory.newDocumentBuilder().parse(xmlInputSource);
Graph newGraph = encode(newDoc, rootUri);
graph.getBulkUpdateHandler().add(newGraph);
Iterator<Triple> tripleIterator =
graph.find(rootNode, null, null).andThen(graph.find(null, null, rootNode));
List<Triple> tripleList = new Vector<Triple>();
while (tripleIterator.hasNext()) {
Triple triple = tripleIterator.next();
tripleList.add(triple);
}
tripleIterator = tripleList.iterator();
while (tripleIterator.hasNext()) {
Triple triple = tripleIterator.next();
graph.add(
new Triple(
triple.getSubject().equals(rootNode) ? xmlRes.asNode() : triple.getSubject(),
triple.getPredicate(),
triple.getObject().equals(rootNode) ? xmlRes.asNode() : triple.getObject()
));
graph.delete(triple);
}
//SparqlJenaQuery query = new SparqlJenaQuery(queryString);
//query.addRootedGraph(graph, xmlRes.asNode());
} catch (SAXException e) {
} catch (IOException e) {
} catch (ParserConfigurationException e) {
}
}
}
public static final int RANDOM_HEX_SIZE = 8;
private static final Random random = new Random();
private static char nibble2hexDigit(byte input) {
input |= 15;
switch(input) {
case 10:
return 'a';
case 11:
return 'b';
case 12:
return 'c';
case 13:
return 'd';
case 14:
return 'e';
case 15:
return 'f';
default:
return Byte.toString(input).charAt(0);
}
}
private static String getRandomString() {
byte randomBytes[] = new byte[RANDOM_HEX_SIZE * 2];
random.nextBytes(randomBytes);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < RANDOM_HEX_SIZE * 2; i++) {
sb.append( nibble2hexDigit( (byte) (randomBytes[i] >>> 8) ) );
sb.append( nibble2hexDigit( randomBytes[i] ) );
}
return sb.toString();
}
} |
package org.jgroups.blocks;
import static org.jgroups.blocks.BasicConnectionTable.getNumberOfConnectionCreations;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.jgroups.Address;
import org.jgroups.stack.IpAddress;
import org.jgroups.util.Util;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.concurrent.*;
/**
* Tests ConnectionTable
* @author Bela Ban
* @version $Id: ConnectionTableTest.java,v 1.3 2007/09/19 10:14:48 belaban Exp $
*/
public class ConnectionTableTest extends TestCase {
private BasicConnectionTable ct1, ct2;
static InetAddress loopback_addr=null;
static byte[] data=new byte[]{'b', 'e', 'l', 'a'};
Address addr1, addr2;
int active_threads=0;
final static int PORT1=7521, PORT2=8931;
static {
try {
loopback_addr=InetAddress.getByName("127.0.0.1");
}
catch(UnknownHostException e) {
e.printStackTrace();
}
}
public ConnectionTableTest(String testName) {
super(testName);
}
protected void setUp() throws Exception {
super.setUp();
active_threads=Thread.activeCount();
System.out.println("active threads before (" + active_threads + "):\n" + Util.activeThreads());
addr1=new IpAddress(loopback_addr, PORT1);
addr2=new IpAddress(loopback_addr, PORT2);
}
protected void tearDown() throws Exception {
if(ct2 != null) {
ct2.stop();
ct2=null;
}
if(ct1 != null) {
ct1.stop();
ct1=null;
}
super.tearDown();
}
public void testConcurrentConnect() throws Exception {
Sender sender1, sender2;
CyclicBarrier barrier=new CyclicBarrier(3);
ct1=new ConnectionTable(loopback_addr, PORT1);
ct2=new ConnectionTable(loopback_addr, PORT2);
BasicConnectionTable.Receiver dummy=new BasicConnectionTable.Receiver() {
public void receive(Address sender, byte[] data, int offset, int length) {}
};
ct1.setReceiver(dummy);
ct2.setReceiver(dummy);
sender1=new Sender((ConnectionTable)ct1, barrier, addr2, 0);
sender2=new Sender((ConnectionTable)ct2, barrier, addr1, 0);
sender1.start(); sender2.start();
Util.sleep(100);
int num_conns;
System.out.println("ct1: " + ct1 + "\nct2: " + ct2);
num_conns=ct1.getNumConnections();
assertEquals(0, num_conns);
num_conns=ct2.getNumConnections();
assertEquals(0, num_conns);
barrier.await(10000, TimeUnit.MILLISECONDS);
sender1.join();
sender2.join();
System.out.println("ct1: " + ct1 + "\nct2: " + ct2);
num_conns=ct1.getNumConnections();
assertEquals(1, num_conns);
num_conns=ct2.getNumConnections();
assertEquals(1, num_conns);
int num_creations=BasicConnectionTable.getNumberOfConnectionCreations();
System.out.println("Number of connection creations=" + num_creations);
assertEquals("2 connections should have been created only, but we have " + num_creations, 2, num_creations);
}
private static class Sender extends Thread {
final ConnectionTable conn_table;
final CyclicBarrier barrier;
final Address dest;
final long sleep_time;
public Sender(ConnectionTable conn_table, CyclicBarrier barrier, Address dest, long sleep_time) {
this.conn_table=conn_table;
this.barrier=barrier;
this.dest=dest;
this.sleep_time=sleep_time;
}
public void run() {
try {
barrier.await(10000, TimeUnit.MILLISECONDS);
if(sleep_time > 0)
Util.sleep(sleep_time);
conn_table.send(dest, data, 0, data.length);
}
catch(Exception e) {
}
}
}
public void testBlockingQueue() {
final BlockingQueue queue=new LinkedBlockingQueue();
Thread taker=new Thread() {
public void run() {
try {
System.out.println("taking an element from the queue");
queue.take();
System.out.println("clear");
}
catch(InterruptedException e) {
}
}
};
taker.start();
Util.sleep(500);
queue.clear(); // does this release the taker thread ?
Util.interruptAndWaitToDie(taker);
assertFalse("taker: " + taker, taker.isAlive());
}
public void testStopConnectionTableNoSendQueues() throws Exception {
ct1=new ConnectionTable(new DummyReceiver(), loopback_addr, null, PORT1, PORT1, 60000, 120000);
ct1.setUseSendQueues(false);
ct2=new ConnectionTable(new DummyReceiver(), loopback_addr, null, PORT2, PORT2, 60000, 120000);
ct2.setUseSendQueues(false);
_testStop(ct1, ct2);
}
public void testStopConnectionTableWithSendQueues() throws Exception {
ct1=new ConnectionTable(new DummyReceiver(), loopback_addr, null, PORT1, PORT1, 60000, 120000);
ct2=new ConnectionTable(new DummyReceiver(), loopback_addr, null, PORT2, PORT2, 60000, 120000);
_testStop(ct1, ct2);
}
public void testStopConnectionTableNIONoSendQueues() throws Exception {
ct1=new ConnectionTableNIO(new DummyReceiver(), loopback_addr, null, PORT1, PORT1, 60000, 120000, false);
ct1.setUseSendQueues(false);
ct2=new ConnectionTableNIO(new DummyReceiver(), loopback_addr, null, PORT2, PORT2, 60000, 120000, false);
ct2.setUseSendQueues(false);
ct1.start();
ct2.start();
_testStop(ct1, ct2);
}
public void testStopConnectionTableNIOWithSendQueues() throws Exception {
ct1=new ConnectionTableNIO(new DummyReceiver(), loopback_addr, null, PORT1, PORT1, 60000, 120000, false);
ct2=new ConnectionTableNIO(new DummyReceiver(), loopback_addr, null, PORT2, PORT2, 60000, 120000, false);
ct1.start();
ct2.start();
_testStop(ct1, ct2);
}
private void _testStop(BasicConnectionTable table1, BasicConnectionTable table2) throws Exception {
table1.send(addr1, data, 0, data.length); // send to self
assertEquals(0, table1.getNumConnections()); // sending to self should not create a connection
table1.send(addr2, data, 0, data.length); // send to other
table2.send(addr2, data, 0, data.length); // send to self
table2.send(addr1, data, 0, data.length); // send to other
System.out.println("table1:\n" + table1 + "\ntable2:\n" + table2);
assertEquals(1, table1.getNumConnections());
assertEquals(1, table2.getNumConnections());
table2.stop();
table1.stop();
assertEquals(0, table1.getNumConnections());
assertEquals(0, table2.getNumConnections());
int current_active_threads=Thread.activeCount();
System.out.println("active threads after (" + current_active_threads + "):\n" + Util.activeThreads());
assertEquals("threads:\n" + Util.dumpThreads(), active_threads, current_active_threads);
}
public static Test suite() {
return new TestSuite(ConnectionTableTest.class);
}
public static void main(String[] args) {
junit.textui.TestRunner.run(ConnectionTableTest.suite());
}
static class DummyReceiver implements ConnectionTable.Receiver {
public void receive(Address sender, byte[] data, int offset, int length) {
System.out.println("-- received " + length + " bytes from " + sender);
}
}
static class DummyReceiverNIO implements ConnectionTableNIO.Receiver {
public void receive(Address sender, byte[] data, int offset, int length) {
System.out.println("-- received " + length + " bytes from " + sender);
}
}
} |
package app.hongs.action;
import app.hongs.Cnst;
import app.hongs.Core;
import app.hongs.CoreLocale;
import app.hongs.CoreSerial;
import app.hongs.HongsException;
import app.hongs.util.Data;
import app.hongs.util.Synt;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.regex.Pattern;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
/**
* .
*
* <p>
* , ;
* ,
* .
* </p>
*
* <h3>:</h3>
* <pre>
forms = {
"form_name" : {
"field_name" : {
__text__ : "Label",
__type__ : "string|number|date|file|enum|form",
__rule__ : "rule.class.Name",
__required__ : "yes|no",
__repeated__ : "yes|no",
"param_name" : "Value"
}
}
}
enums = {
"enum_name" : {
"value_code" : "Label"
}
}
* </pre>
*
* <h3>:</h3>
* <pre>
* : 0x10e8~0x10ef
* 0x10e8
* 0x10e9
* </pre>
*
* @author Hongs
*/
public class FormSet
extends CoreSerial
{
private final String name;
public Map<String, Map> forms;
public Map<String, Map> enums;
public FormSet(String name)
throws HongsException
{
this.name = name;
this.init(name + Cnst.FORM_EXT);
}
@Override
protected boolean expired(long time)
{
File xmlFile = new File(Core.CONF_PATH
+ File.separator + name + Cnst.FORM_EXT + ".xml");
File serFile = new File(Core.DATA_PATH
+ File.separator + "serial"
+ File.separator + name + Cnst.FORM_EXT + ".ser");
return xmlFile.exists() && xmlFile.lastModified() > serFile.lastModified();
}
@Override
protected void imports()
throws HongsException
{
InputStream is;
String fn;
try
{
fn = Core.CONF_PATH + File.separator + name + Cnst.FORM_EXT + ".xml";
is = new FileInputStream(fn);
}
catch (FileNotFoundException ex)
{
fn = name.contains(".")
|| name.contains("/") ? name + Cnst.FORM_EXT + ".xml"
: "app/hongs/conf/" + name + Cnst.FORM_EXT + ".xml";
is = this.getClass().getClassLoader().getResourceAsStream(fn);
if ( null == is )
{
throw new app.hongs.HongsException(0x10e8,
"Can not find the config file '" + name + Cnst.FORM_EXT + ".xml'.");
}
}
Element root;
try
{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder dbn = dbf.newDocumentBuilder();
Document doc = dbn.parse( is );
root = doc.getDocumentElement();
}
catch ( IOException ex)
{
throw new HongsException(0x10e9, "Read '" +name+Cnst.FORM_EXT+".xml error'", ex);
}
catch (SAXException ex)
{
throw new HongsException(0x10e9, "Parse '"+name+Cnst.FORM_EXT+".xml error'", ex);
}
catch (ParserConfigurationException ex)
{
throw new HongsException(0x10e9, "Parse '"+name+Cnst.FORM_EXT+".xml error'", ex);
}
this.forms = new HashMap();
this.enums = new HashMap();
this.parse(root, this.forms, this.enums);
}
private void parse(Element element, Map forms, Map enums)
throws HongsException
{
if (!element.hasChildNodes())
{
return;
}
NodeList nodes = element.getChildNodes();
for (int i = 0; i < nodes.getLength(); i ++)
{
Node node = nodes.item(i);
if (node.getNodeType() != Node.ELEMENT_NODE)
{
continue;
}
Element element2 = (Element)node;
String tagName2 = element2.getTagName();
if ("form".equals(tagName2))
{
String namz = element2.getAttribute("name");
if (namz == null) namz = "";
Map items = new LinkedHashMap();
this.parse(element2, items, null);
forms.put(namz, items);
}
if ("enum".equals(tagName2))
{
String namz = element2.getAttribute("name");
if (namz == null) namz = "";
Map items = new LinkedHashMap();
this.parse(element2, null, items);
enums.put(namz, items);
}
if ("field".equals(tagName2))
{
String namz = element2.getAttribute("name");
if (namz == null) namz = "";
Map items = new LinkedHashMap();
this.parse(element2, items, null);
forms.put(namz, items);
items.put("__name__", namz);
namz = element2.getAttribute("text");
items.put("__text__", namz);
namz = element2.getAttribute("hint");
items.put("__hint__", namz);
namz = element2.getAttribute("type");
items.put("__type__", namz);
namz = element2.getAttribute("rule");
items.put("__rule__", namz);
if (element2.hasAttribute("required")) {
namz = element2.getAttribute("required");
items.put("__required__", namz );
} else {
items.put("__required__", "false");
}
if (element2.hasAttribute("repeated")) {
namz = element2.getAttribute("repeated");
items.put("__repeated__", namz );
} else {
items.put("__repeated__", "false");
}
}
else
if ("param".equals(tagName2))
{
String namz = element2.getAttribute("name");
String typz = element2.getAttribute("type");
String text = element2.getTextContent();
forms.put(namz, parse(typz, text));
}
else
if ("value".equals(tagName2))
{
String namz = element2.getAttribute("code");
String typz = element2.getAttribute("type");
String text = element2.getTextContent();
enums.put(namz, parse(typz, text));
}
}
}
private Object parse(String type, String text) throws HongsException {
if (null == type || "".equals(type)) {
return text ;
}
text = text.trim();
if ( "int".equals(type)) {
return Synt.defoult(Synt.asInt (text), false);
}
if ( "long".equals(type)) {
return Synt.defoult(Synt.asLong (text), false);
}
if ( "float".equals(type)) {
return Synt.defoult(Synt.asFloat (text), false);
}
if ("double".equals(type)) {
return Synt.defoult(Synt.asDouble(text), false);
}
if ( "short".equals(type)) {
return Synt.defoult(Synt.asShort (text), false);
}
if ( "byte".equals(type)) {
return Synt.defoult(Synt.asByte (text), false);
}
if ( "bool".equals(type)) {
return Synt.defoult(Synt.asBool (text), false);
}
if ("list".equals(type)) {
if (text.startsWith("[") && text.endsWith("]")) {
return ( List) Data.toObject(text);
} else {
return new ArrayList (
Arrays.asList(SEXP.split(text))
);
}
}
if ( "set".equals(type)) {
if (text.startsWith("[") && text.endsWith("]")) {
return new LinkedHashSet(
( List) Data.toObject(text)
);
} else {
return new LinkedHashSet(
Arrays.asList(SEXP.split(text))
);
}
}
if ( "map".equals(type)) {
if (text.startsWith("{") && text.endsWith("}")) {
return ( Map ) Data.toObject(text);
} else {
Map m = new LinkedHashMap();
for(String s : SEXP.split (text)) {
String[] a = MEXP.split (s, 2);
if ( 2 > a.length ) {
m.put( a[0], a[0] );
} else {
m.put( a[0], a[1] );
}
}
return m;
}
}
throw new HongsException.Common("Unrecognized type '"+type+"'");
}
private static final Pattern SEXP = Pattern.compile ( "\\s*,\\s*" );
private static final Pattern MEXP = Pattern.compile ( "\\s*:\\s*" );
public String getName() {
return this.name;
}
public Map getEnum(String name) throws HongsException {
if (!enums.containsKey(name)) {
throw new HongsException(0x10eb, "Enum "+name+" in "+this.name+" is not exists");
}
return enums.get(name);
}
public Map getForm(String name) throws HongsException {
if (!forms.containsKey(name)) {
throw new HongsException(0x10ea, "Form "+name+" in "+this.name+" is not exists");
}
return forms.get(name);
}
public CoreLocale getCurrTranslator() {
try {
return CoreLocale.getInstance(name);
}
catch (app.hongs.HongsError e) {
if ( e.getErrno() != 0x2a) {
throw e;
}
return CoreLocale.getInstance("default");
}
}
public Map getEnumTranslated(String namc) {
Map items = enums.get(namc);
Map itemz = new LinkedHashMap();
if (items == null) return itemz;
CoreLocale lang = getCurrTranslator();
itemz.putAll(items);
for(Object o : itemz.entrySet()) {
Map.Entry e = (Map.Entry) o ;
String k = (String) e.getKey( );
String n = (String) e.getValue();
if (n == null || "".equals(n)) {
n = "fore.enum."+name+"."+namc+"."+k;
}
e.setValue( lang.translate(n));
}
return itemz;
}
public Map getFormTranslated(String namc)
throws HongsException
{
Map items = getForm(namc);
Map itemz = new LinkedHashMap();
if (items == null) return itemz;
CoreLocale lang = getCurrTranslator();
for(Object o : items.entrySet()) {
Map.Entry e = (Map.Entry) o;
Map m = (Map ) e.getValue();
String k = (String) e.getKey();
String n = (String) m.get("__text__");
String h = (String) m.get("__hint__");
Map u = new LinkedHashMap();
u.putAll( m );
if (n == null || "".equals(n)) {
n = "fore.form."+name+"."+namc+"."+k;
} u.put("__text__", lang.translate(n));
if (h != null &&!"".equals(n)) {
u.put("__hint__", lang.translate(h));
}
itemz.put(k, u);
}
return itemz;
}
/
public static boolean hasConfFile(String name) {
String fn;
fn = Core.DATA_PATH
+ File.separator + "serial"
+ File.separator + name + Cnst.FORM_EXT + ".ser";
if (new File(fn).exists()) {
return true;
}
fn = Core.CONF_PATH
+ File.separator + name + Cnst.FORM_EXT + ".xml";
if (new File(fn).exists()) {
return true;
}
fn = name.contains(".")
|| name.contains("/") ? name + Cnst.FORM_EXT + ".xml"
: "app/hongs/conf/" + name + Cnst.FORM_EXT + ".xml";
return null != FormSet.class.getClassLoader().getResourceAsStream(fn);
}
public static FormSet getInstance(String name) throws HongsException {
String key = FormSet.class.getName() + ":" + name;
Core core = Core.getInstance();
FormSet inst;
if (core.containsKey(key)) {
inst = (FormSet)core.get(key);
}
else {
inst = new FormSet(name);
core.put( key, inst );
}
return inst;
}
public static FormSet getInstance() throws HongsException {
return getInstance("default");
}
} |
package com.helger.as4.client;
import java.io.File;
import javax.mail.internet.MimeMessage;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import com.helger.as4.attachment.WSS4JAttachment;
import com.helger.as4.crypto.ECryptoAlgorithmSign;
import com.helger.as4.crypto.ECryptoAlgorithmSignDigest;
import com.helger.as4.messaging.domain.AS4UserMessage;
import com.helger.as4.messaging.domain.CreateUserMessage;
import com.helger.as4.messaging.encrypt.EncryptionCreator;
import com.helger.as4.messaging.mime.MimeMessageCreator;
import com.helger.as4.messaging.sign.SignedMessageCreator;
import com.helger.as4.soap.ESOAPVersion;
import com.helger.as4.util.AS4ResourceManager;
import com.helger.as4lib.ebms3header.Ebms3CollaborationInfo;
import com.helger.as4lib.ebms3header.Ebms3MessageInfo;
import com.helger.as4lib.ebms3header.Ebms3MessageProperties;
import com.helger.as4lib.ebms3header.Ebms3PartyInfo;
import com.helger.as4lib.ebms3header.Ebms3PayloadInfo;
import com.helger.as4lib.ebms3header.Ebms3Property;
import com.helger.commons.annotation.WorkInProgress;
import com.helger.commons.collection.ext.CommonsArrayList;
import com.helger.commons.collection.ext.ICommonsList;
import com.helger.commons.string.StringHelper;
/**
* AS4 standalone client invoker.
*
* @author Philip Helger
*/
@WorkInProgress
public class AS4Client
{
private final AS4ResourceManager aResMgr = new AS4ResourceManager ();
private ICommonsList <WSS4JAttachment> aAttachments = new CommonsArrayList <> ();
private Node aPayload;
private ESOAPVersion eSOAPVersion;
// Keystore attributes
// TODO look at AS2 Client / ClientSettinggs /ClientRequest
private File m_aKeyStoreFile;
private String m_sKeyStoreAlias;
private String m_sKeyStorePassword;
// org.apache.wss4j.common.crypto.Merlin is the default value
private String m_sKeyStoreProvider = "org.apache.wss4j.common.crypto.Merlin";
// Document related attributes
private Document aDoc;
private MimeMessage aMsg;
private ICommonsList <Ebms3Property> aEbms3Properties = new CommonsArrayList <> ();
// For Message Info
private String sMessageIDPrefix;
// CollaborationInfo
// TODO group accordingly if more then 1 parameter z.b group ServiceType and
// Value in one setter
private String sAction;
private String sServiceType;
private String sServiceValue;
private String sConversationID;
private String sAgreementRefPMode;
private String sAgreementRefValue;
private String sFromRole;
private String sFromPartyID;
private String sToRole;
private String sToPartyID;
// Signing additional attributes
private ECryptoAlgorithmSign eECryptoAlgorithmSign = ECryptoAlgorithmSign.SIGN_ALGORITHM_DEFAULT;
private ECryptoAlgorithmSignDigest eECryptoAlgorithmSignDigest = ECryptoAlgorithmSignDigest.SIGN_DIGEST_ALGORITHM_DEFAULT;
/**
* This method encrypts the current Document and is producing a encrypted
* Document or a MimeMessage. Encrypted Document if only a SOAP BodyPaylod is
* present MimeMessage if Attachments are present
*
* @throws Exception
* if something goes wrong in the encryption process
*/
public void encryptDocument () throws Exception
{
if (aDoc == null)
{
throw new IllegalStateException ("No Document is set.");
}
else
{
_checkKeystoreAttributes ();
final EncryptionCreator aEncCreator = new EncryptionCreator ();
// MustUnderstand always set to true
if (aAttachments.isNotEmpty ())
{
aMsg = aEncCreator.encryptMimeMessage (eSOAPVersion, aDoc, true, aAttachments, aResMgr);
}
else
{
aDoc = aEncCreator.encryptSoapBodyPayload (eSOAPVersion, aDoc, true);
}
}
}
public void signDocument () throws Exception
{
if (aDoc == null)
{
throw new IllegalStateException ("No Document is set.");
}
else
{
_checkKeystoreAttributes ();
aDoc = new SignedMessageCreator ().createSignedMessage (aDoc,
eSOAPVersion,
aAttachments,
aResMgr,
true,
eECryptoAlgorithmSign,
eECryptoAlgorithmSignDigest);
if (aAttachments.isNotEmpty ())
{
aMsg = new MimeMessageCreator (eSOAPVersion).generateMimeMessage (aDoc, aAttachments);
}
}
}
private void _checkKeystoreAttributes ()
{
if (StringHelper.hasNoText (m_sKeyStoreAlias) ||
StringHelper.hasNoText (m_sKeyStorePassword) ||
!m_aKeyStoreFile.exists ())
{
throw new IllegalStateException ("At least one of the following Alias: " +
m_sKeyStoreAlias +
", Password: " +
m_sKeyStorePassword +
" or the KeyStoreFile:(rue if the file exists) " +
m_aKeyStoreFile.exists () +
"are not set.");
}
}
/**
* Only returns something appropriate if the attributes got set before. Not
* every attribute needs to be set.
*
* @return Document that is produced with the current settings.
*/
public Document buildMessage ()
{
final Ebms3MessageInfo aEbms3MessageInfo = CreateUserMessage.createEbms3MessageInfo (sMessageIDPrefix);
final Ebms3PayloadInfo aEbms3PayloadInfo = CreateUserMessage.createEbms3PayloadInfo (aPayload, aAttachments);
final Ebms3CollaborationInfo aEbms3CollaborationInfo = CreateUserMessage.createEbms3CollaborationInfo (sAction,
sServiceType,
sServiceValue,
sConversationID,
sAgreementRefPMode,
sAgreementRefValue);
final Ebms3PartyInfo aEbms3PartyInfo = CreateUserMessage.createEbms3PartyInfo (sFromRole,
sFromPartyID,
sToRole,
sToPartyID);
final Ebms3MessageProperties aEbms3MessageProperties = CreateUserMessage.createEbms3MessageProperties (aEbms3Properties);
final AS4UserMessage aDoc = CreateUserMessage.createUserMessage (aEbms3MessageInfo,
aEbms3PayloadInfo,
aEbms3CollaborationInfo,
aEbms3PartyInfo,
aEbms3MessageProperties,
eSOAPVersion)
.setMustUnderstand (true);
return aDoc.getAsSOAPDocument (aPayload);
}
public ICommonsList <WSS4JAttachment> getAttachments ()
{
return aAttachments;
}
public void setAttachments (final ICommonsList <WSS4JAttachment> aAttachments)
{
this.aAttachments = aAttachments;
}
public Node getPayload ()
{
return aPayload;
}
public void setPayload (final Node aPayload)
{
this.aPayload = aPayload;
}
public ESOAPVersion geteSOAPVersion ()
{
return eSOAPVersion;
}
public void seteSOAPVersion (final ESOAPVersion eSOAPVersion)
{
this.eSOAPVersion = eSOAPVersion;
}
public File getKeyStoreFile ()
{
return m_aKeyStoreFile;
}
public void setKeyStoreFile (final File m_aKeyStoreFile)
{
this.m_aKeyStoreFile = m_aKeyStoreFile;
}
public String getKeyStoreAlias ()
{
return m_sKeyStoreAlias;
}
public void setKeyStoreAlias (final String m_sKeyStoreAlias)
{
this.m_sKeyStoreAlias = m_sKeyStoreAlias;
}
public String getKeyStorePassword ()
{
return m_sKeyStorePassword;
}
public void setKeyStorePassword (final String m_sKeyStorePassword)
{
this.m_sKeyStorePassword = m_sKeyStorePassword;
}
public String getKeyStoreProvider ()
{
return m_sKeyStoreProvider;
}
public void setKeyStoreProvider (final String m_sKeyStoreAlias)
{
this.m_sKeyStoreProvider = m_sKeyStoreAlias;
}
public Document getDoc ()
{
return aDoc;
}
public void setDoc (final Document aDoc)
{
this.aDoc = aDoc;
}
public ICommonsList <Ebms3Property> getEbms3Properties ()
{
return aEbms3Properties;
}
public void setEbms3Properties (final ICommonsList <Ebms3Property> aEbms3Properties)
{
this.aEbms3Properties = aEbms3Properties;
}
public String getMessageIDPrefix ()
{
return sMessageIDPrefix;
}
public void setMessageIDPrefix (final String sMessageIDPrefix)
{
this.sMessageIDPrefix = sMessageIDPrefix;
}
public String getction ()
{
return sAction;
}
public void setction (final String sAction)
{
this.sAction = sAction;
}
public String getServiceType ()
{
return sServiceType;
}
public void setServiceType (final String sServiceType)
{
this.sServiceType = sServiceType;
}
public String getServiceValue ()
{
return sServiceValue;
}
public void setServiceValue (final String sServiceValue)
{
this.sServiceValue = sServiceValue;
}
public String getConversationID ()
{
return sConversationID;
}
public void setConversationID (final String sConversationID)
{
this.sConversationID = sConversationID;
}
public String getgreementRefPMode ()
{
return sAgreementRefPMode;
}
public void setgreementRefPMode (final String sAgreementRefPMode)
{
this.sAgreementRefPMode = sAgreementRefPMode;
}
public String getgreementRefValue ()
{
return sAgreementRefValue;
}
public void setgreementRefValue (final String sAgreementRefValue)
{
this.sAgreementRefValue = sAgreementRefValue;
}
public String getFromRole ()
{
return sFromRole;
}
public void setFromRole (final String sFromRole)
{
this.sFromRole = sFromRole;
}
public String getFromPartyID ()
{
return sFromPartyID;
}
public void setFromPartyID (final String sFromPartyID)
{
this.sFromPartyID = sFromPartyID;
}
public String getToRole ()
{
return sToRole;
}
public void setToRole (final String sToRole)
{
this.sToRole = sToRole;
}
public String getToPartyID ()
{
return sToPartyID;
}
public void setToPartyID (final String sToPartyID)
{
this.sToPartyID = sToPartyID;
}
public ECryptoAlgorithmSign getECryptoAlgorithmSign ()
{
return eECryptoAlgorithmSign;
}
public void setECryptoAlgorithmSign (final ECryptoAlgorithmSign eECryptoAlgorithmSign)
{
this.eECryptoAlgorithmSign = eECryptoAlgorithmSign;
}
public ECryptoAlgorithmSignDigest getECryptoAlgorithmSignDigest ()
{
return eECryptoAlgorithmSignDigest;
}
public void seeECryptoAlgorithmSignDigest (final ECryptoAlgorithmSignDigest eECryptoAlgorithmSignDigest)
{
this.eECryptoAlgorithmSignDigest = eECryptoAlgorithmSignDigest;
}
} |
package com.google.sps.agents;
// Imports the Google Cloud client library
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.users.UserService;
import com.google.gson.Gson;
import com.google.protobuf.Value;
import com.google.sps.data.Book;
import com.google.sps.data.BookQuery;
import com.google.sps.utils.BookUtils;
import com.google.sps.utils.BooksMemoryUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;
/**
* Books Agent handles user's requests for books from Google Books API. It determines appropriate
* outputs and display information to send to the user interface based on Dialogflow's detected Book
* intent.
*/
public class BooksAgent implements Agent {
private final String intentName;
private final String userInput;
private String output;
private String display;
private String redirect;
private int displayNum;
private String sessionID;
private String queryID;
private DatastoreService datastore;
private UserService userService;
private BookQuery query;
private ArrayList<Book> bookResults;
private int startIndex;
private int totalResults;
private int resultsReturned;
private int prevStartIndex;
private int resultsStored;
/**
* BooksAgent constructor without queryID sets queryID property to the most recent queryID for the
* specified sessionID
*
* @param intentName String containing the specific intent within memory agent that user is
* requesting.
* @param userInput String containing user's request input
* @param parameters Map containing the detected entities in the user's intent.
* @param sessionID String containing the unique sessionID for user's session
* @param userService UserService instance to access userID and other user info.
* @param datastore DatastoreService instance used to access Book info from database
*/
public BooksAgent(
String intentName,
String userInput,
Map<String, Value> parameters,
String sessionID,
UserService userService,
DatastoreService datastore)
throws IOException, IllegalArgumentException {
this(intentName, userInput, parameters, sessionID, userService, datastore, null);
}
/**
* BooksAgent constructor with queryID
*
* @param intentName String containing the specific intent within memory agent that user is
* requesting.
* @param userInput String containing user's request input
* @param parameters Map containing the detected entities in the user's intent.
* @param sessionID String containing the unique sessionID for user's session
* @param userService UserService instance to access userID and other user info.
* @param datastore DatastoreService instance used to access book info grom database.
* @param queryID String containing the unique ID for the BookQuery the user is requesting, If
* request comes from Book Display interface, then queryID is retrieved from Book Display
* Otherwise, queryID is set to the most recent query that the user (sessionID) made.
*/
public BooksAgent(
String intentName,
String userInput,
Map<String, Value> parameters,
String sessionID,
UserService userService,
DatastoreService datastore,
String queryID)
throws IOException, IllegalArgumentException {
this.displayNum = 5;
this.intentName = intentName;
this.userInput = userInput;
this.sessionID = sessionID;
this.userService = userService;
this.datastore = datastore;
this.queryID = queryID;
if (queryID == null) {
this.queryID = getMostRecentQueryID(sessionID);
}
setParameters(parameters);
}
@Override
public void setParameters(Map<String, Value> parameters)
throws IOException, IllegalArgumentException {
// Intents that do not require user to be authenticated
if (intentName.equals("search")) {
this.query = BookQuery.createBookQuery(this.userInput, parameters);
this.startIndex = 0;
// Retrieve books from BookQuery
this.bookResults = BookUtils.getRequestedBooks(query, startIndex);
this.totalResults = BookUtils.getTotalVolumesFound(query, startIndex);
this.resultsReturned = bookResults.size();
if (resultsReturned > 0) {
handleNewQuerySuccess();
this.output = "Here's what I found.";
} else {
this.output = "I couldn't find any results. Can you try again?";
}
} else if (intentName.equals("more")) {
// Load BookQuery, totalResults, resultsStored and increment startIndex
loadBookQueryInfo(sessionID, queryID);
this.startIndex = getNextStartIndex(prevStartIndex, totalResults);
if (startIndex == -1) {
this.output = "I'm sorry, this is the last page of results.";
this.startIndex = prevStartIndex;
} else if (startIndex + displayNum <= resultsStored) {
replaceIndices(sessionID, queryID);
this.output = "Here's the next page of results.";
} else {
// Retrieve books from stored query at startIndex
this.bookResults = BookUtils.getRequestedBooks(query, startIndex);
int resultsReturned = bookResults.size();
int newResultsStored = resultsReturned + resultsStored;
this.resultsStored = newResultsStored;
if (resultsReturned == 0) {
this.output = "I'm sorry, this is the last page of results.";
this.startIndex = prevStartIndex;
} else {
// Store Book results and new indices
BooksMemoryUtils.storeBooks(bookResults, startIndex, sessionID, queryID, datastore);
replaceIndices(sessionID, queryID);
this.output = "Here's the next page of results.";
}
}
setBookListDisplay();
this.redirect = queryID;
} else if (intentName.equals("previous")) {
loadBookQueryInfo(sessionID, queryID);
this.startIndex = prevStartIndex - displayNum;
if (startIndex <= -1) {
this.output = "This is the first page of results.";
startIndex = 0;
} else {
replaceIndices(sessionID, queryID);
this.output = "Here's the previous page of results.";
}
setBookListDisplay();
this.redirect = queryID;
} else if (intentName.equals("description") || intentName.equals("preview")) {
int bookNumber = (int) parameters.get("number").getNumberValue();
this.prevStartIndex =
BooksMemoryUtils.getStoredIndices("startIndex", sessionID, queryID, datastore);
Book requestedBook =
BooksMemoryUtils.getBookFromOrderNum(
bookNumber, prevStartIndex, sessionID, queryID, datastore);
this.display = bookToString(requestedBook);
this.redirect = queryID;
this.output = "Here's a " + intentName + " of " + requestedBook.getTitle() + ".";
} else if (intentName.equals("results")) {
loadBookQueryInfo(sessionID, queryID);
this.startIndex = prevStartIndex;
setBookListDisplay();
this.output = "Here are the results.";
this.redirect = queryID;
}
}
@Override
public String getOutput() {
return this.output;
}
@Override
public String getDisplay() {
return this.display;
}
@Override
public String getRedirect() {
return this.redirect;
}
/**
* Upon a successful new book query request, triggered by books.search and books.library intents,
* this function does the following:
*
* <p>Retrieves the next unique queryID, stores BookQuery, Book results, and Indices for the
* corresponding sessionID and queryID of the new query. Retrieves the list of books to display.
* Sets the display and queryID redirect.
*/
private void handleNewQuerySuccess() {
this.queryID = getNextQueryID(sessionID);
// Store BookQuery, Book results, totalResults, resultsReturned
BooksMemoryUtils.storeBooks(bookResults, startIndex, sessionID, queryID, datastore);
BooksMemoryUtils.storeBookQuery(query, sessionID, queryID, datastore);
BooksMemoryUtils.storeIndices(
startIndex, totalResults, resultsReturned, displayNum, sessionID, queryID, datastore);
setBookListDisplay();
this.redirect = queryID;
}
/**
* Loads previous BookQuery and Indices information from the BookQuery matching the request's
* sessionID and queryID and sets query, prevStartIndex, resultsStored, totalResults based on
* stored information
*
* @param sessionID ID of current user / session
* @param queryID ID of query requested
*/
private void loadBookQueryInfo(String sessionID, String queryID) {
this.query = BooksMemoryUtils.getStoredBookQuery(sessionID, queryID, datastore);
this.prevStartIndex =
BooksMemoryUtils.getStoredIndices("startIndex", sessionID, queryID, datastore);
this.resultsStored =
BooksMemoryUtils.getStoredIndices("resultsStored", sessionID, queryID, datastore);
this.totalResults =
BooksMemoryUtils.getStoredIndices("totalResults", sessionID, queryID, datastore);
}
/** Sets display to an ArrayList<Book> to display on user interface */
private void setBookListDisplay() {
ArrayList<Book> booksToDisplay =
BooksMemoryUtils.getStoredBooksToDisplay(
displayNum, startIndex, sessionID, queryID, datastore);
this.display = bookListToString(booksToDisplay);
}
/**
* Replaces previous Indices Entity stored in Datastore with the new startIndex, totalResults,
* resultsSTored, displayNum for the Indices Entity that matches the current sessionID and queryID
* for the request
*
* @param sessionID ID of current user / session
* @param queryID ID of query requested
*/
private void replaceIndices(String sessionID, String queryID) {
BooksMemoryUtils.deleteStoredEntities("Indices", sessionID, queryID, datastore);
BooksMemoryUtils.storeIndices(
startIndex, totalResults, resultsStored, displayNum, sessionID, queryID, datastore);
}
private int getNextStartIndex(int prevIndex, int total) {
int nextIndex = prevIndex + displayNum;
if (nextIndex < total) {
return nextIndex;
}
return -1;
}
public static String bookToString(Book book) {
Gson gson = new Gson();
return gson.toJson(book);
}
public static String bookListToString(ArrayList<Book> books) {
Gson gson = new Gson();
return gson.toJson(books);
}
private String getMostRecentQueryID(String sessionID) {
int queryNum = BooksMemoryUtils.getNumQueryStored(sessionID, datastore);
String queryID = "query-" + Integer.toString(queryNum);
return queryID;
}
private String getNextQueryID(String sessionID) {
int queryNum = BooksMemoryUtils.getNumQueryStored(sessionID, datastore) + 1;
String queryID = "query-" + Integer.toString(queryNum);
return queryID;
}
} |
import java.util.ArrayList;
public class Map{
public ArrayList< ArrayList<Site> > contents;
public int map_width, map_height;
public Map() {
map_width = 0;
map_height = 0;
contents = new ArrayList< ArrayList<Site> >(0);
}
public Map(int map_width_, int map_height_) {
map_width = map_width_;
map_height = map_height_;
contents = new ArrayList< ArrayList<Site> >(0);
for(int y = 0; y < map_height; y++) {
ArrayList<Site> row = new ArrayList<Site>();
for(int x = 0; x < map_width; x++) {
row.add(new Site());
}
contents.add(row);
}
}
public boolean inBounds(Location loc) {
return loc.x < width && loc.x >= 0 && loc.y < height && loc.y >= 0;
}
public double getDistance(Location loc1, Location loc2) {
int dx = Math.abs(loc1.x - loc2.x);
int dy = Math.abs(loc1.y - loc2.y);
if(dx > width / 2.0) dx = width - dx;
if(dy > height / 2.0) dy = height - dy;
return Math.sqrt(Math.pow(dx, 2) + Math.pow(dy, 2));
}
public double getAngle(Location loc1, Location loc2) {
int dx = loc1.x - loc2.x;
int dy = loc1.y - loc2.y;
if(dx > width - dx) dx -= width;
if(-dx > width + dx) dx += width;
if(dy > height - dy) dy -= height;
if(-dy > height + dy) dy += height;
return Math.atan2(dy, dx);
}
public Location getLocation(Location loc, Direction dir) {
Location l = new Location(loc);
if(dir != Direction.STILL) {
if(dir == Direction.NORTH) {
if(l.y == 0) l.y = map_height - 1;
else l.y
}
else if(dir == Direction.EAST) {
if(l.x == map_width - 1) l.x = 0;
else l.x++;
}
else if(dir == Direction.SOUTH) {
if(l.y == map_height - 1) l.y = 0;
else l.y++;
}
else if(dir == Direction.WEST) {
if(l.x == 0) l.x = map_width - 1;
else l.x
}
}
return l;
}
public Site getSite(Location loc, Direction dir) {
Location l = getLocation(loc, dir);
return contents.get(l.y).get(l.x);
}
public Site getSite(Location loc) {
return contents.get(loc.y).get(loc.x);
}
} |
package config;
import pathfinding.astar.arcs.ClothoidesComputer;
import robot.RobotColor;
public enum ConfigInfo {
/**
* Infos sur le robot
*/
DILATATION_ROBOT_DSTARLITE(60), // dilatation des obstacles dans le D* Lite. Comme c'est une heuristique, on peut prendre plus petit que la vraie valeur
CENTRE_ROTATION_ROUE_X(204),
CENTRE_ROTATION_ROUE_Y(64),
DEMI_LONGUEUR_NON_DEPLOYE_ARRIERE(80),
DEMI_LONGUEUR_NON_DEPLOYE_AVANT(332-80),
LARGEUR_NON_DEPLOYE(228),
DILATATION_OBSTACLE_ROBOT(30),
RAYON_CERCLE_ARRIVEE(200),
VITESSE_ROBOT_TEST(300), // vitesse de test en mm/s
VITESSE_ROBOT_STANDARD(500), // vitesse standard en mm/s
VITESSE_ROBOT_BASCULE(300), // vitesse pour passer la bascule en mm/s
VITESSE_ROBOT_REPLANIF(200), // vitesse en replanification en mm/s
FAST_LOG(false), // affichage plus rapide des logs
SAUVEGARDE_LOG(false), // sauvegarde les logs dans un fichier externe
AFFICHE_CONFIG(false),
COLORED_LOG(false), // de la couleur dans les sauvegardes de logs !
/**
* Infos sur l'ennemi
*/
LARGEUR_OBSTACLE_ENNEMI(100), // largeur du robot vu
LONGUEUR_OBSTACLE_ENNEMI(200), // longueur / profondeur du robot vu
COURBURE_MAX(3), // quelle courbure maximale la trajectoire du robot peut-elle avoir
TEMPS_ARRET(800),
PF_MARGE_NECESSAIRE((int)(150/ClothoidesComputer.PRECISION_TRACE_MM)), // combien de points de pathfinding le bas niveau doit-il toujours avoir
PF_MARGE_INITIALE((int)(250/ClothoidesComputer.PRECISION_TRACE_MM)),
DUREE_MAX_RECHERCHE_PF(3000),
TAILLE_FAISCEAU_PF(10),
NB_ESSAIS_PF(3), // nombre d'essais du pathfinding
SERIAL_TIMEOUT(30),
BAUDRATE(115200),
SERIAL_PORT("/dev/ttyS0"),
SLEEP_ENTRE_TRAMES(0),
SIMULE_SERIE(false),
SENSORS_SEND_PERIOD(20),
SENSORS_PRESCALER(5), // sur combien de trames a-t-on les infos des capteurs
DUREE_PEREMPTION_OBSTACLES(1000),
DISTANCE_MAX_ENTRE_MESURE_ET_OBJET(50),
DISTANCE_BETWEEN_PROXIMITY_OBSTACLES(5),
IMPRECISION_MAX_POSITION(20.), // quelle imprecision maximale sur la position du robot peut-on attendre (en mm)
IMPRECISION_MAX_ORIENTATION(0.1), // quelle imprecision maximale sur l'angle du robot peut-on attendre (en radians)
TAILLE_BUFFER_RECALAGE(5),
PEREMPTION_CORRECTION(100),
ENABLE_CORRECTION(true),
NB_INSTANCES_NODE(2000),
NB_INSTANCES_OBSTACLES(5000), // nombre d'instances pour les obstacles rectangulaires
/**
* Verbose
*/
DEBUG_SERIE_TRAME(false), // debug verbeux sur le contenu des trames
DEBUG_SERIE(false),
DEBUG_CAPTEURS(false), // debug verbeux sur les capteurs
DEBUG_REPLANIF(false), // debug verbeux sur la replanif
DEBUG_ACTIONNEURS(false), // debug verbeux sur les actionneurs
DEBUG_CACHE(false), // debug du cache de chemins
DEBUG_PF(false), // affichage de plein d'infos
DEBUG_DEBUG(false), // affichage des messages "debug"
GENERATE_DEPENDENCY_GRAPH(false),
/**
* Interface graphique
*/
GRAPHIC_HEURISTIQUE(false),
GRAPHIC_ENABLE(false),
GRAPHIC_D_STAR_LITE(false), // affiche les calculs du D* Lite
GRAPHIC_D_STAR_LITE_FINAL(false),
GRAPHIC_PROXIMITY_OBSTACLES(true),
GRAPHIC_TRAJECTORY(false), // affiche les trajectoires temporaires
GRAPHIC_TRAJECTORY_ALL(false), // affiche TOUTES les trajectoires temporaires
GRAPHIC_TRAJECTORY_FINAL(true), // affiche les trajectoires
GRAPHIC_FIXED_OBSTACLES(true), // affiche les obstacles fixes
GRAPHIC_GAME_ELEMENTS(true),
GRAPHIC_ROBOT_COLLISION(false),
GRAPHIC_BACKGROUND_PATH("img/background-2017-color.png"), // affiche d'image de la table
GRAPHIC_ROBOT_PATH("img/robot_sans_roues.png"), // image du robot sans les roues
GRAPHIC_ROBOT_ROUE_GAUCHE_PATH("img/robot_roue_gauche.png"), // image de la roue gauche
GRAPHIC_ROBOT_ROUE_DROITE_PATH("img/robot_roue_droite.png"), // image de la roue droite
GRAPHIC_PRODUCE_GIF(false), // produit un gif ?
GRAPHIC_BACKGROUND(true), // affiche d'image de la table
GRAPHIC_SIZE_X(1000),
GRAPHIC_ALL_OBSTACLES(false),
GRAPHIC_ROBOT_AND_SENSORS(true), // affiche le robot et ses capteurs
GRAPHIC_CERCLE_ARRIVEE(false),
GRAPHIC_TIME(false),
GRAPHIC_TRACE_ROBOT(true), // affiche la trace du robot
GRAPHIC_EXTERNAL(true),
GRAPHIC_DIFFERENTIAL(true),
/**
* Config dynamique
*/
COULEUR(RobotColor.getCouleurSansSymetrie(), false), // quelle est la couleur du robot
MATCH_DEMARRE(false, false),
DATE_DEBUT_MATCH(0, false);
private Object defaultValue;
public boolean overridden = false;
public final boolean constant;
private ConfigInfo(Object defaultValue)
{
this(defaultValue, true);
}
private ConfigInfo(Object defaultValue, boolean constant)
{
this.defaultValue = defaultValue;
this.constant = constant;
}
Object getDefaultValue()
{
return defaultValue;
}
public void setDefaultValue(Object o)
{
defaultValue = o;
overridden = true;
}
} |
package Authentication;
import java.lang.reflect.Field;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.UUID;
import DatabaseModel.DatabaseConnection;
import DatabaseModel.SQLExpressions.SQLExpression;
import DatabaseModel.Tables.User;
public class Login {
public static HashMap<Integer, String> authenticationMap = new HashMap<Integer, String>();
public static String login(String login, String password) throws NoSuchFieldException, SecurityException, SQLException {
DatabaseConnection db = new DatabaseConnection();
User filterUser = new User();
filterUser.login = login;
filterUser.password = password;
SQLExpression<User> filterExpression = new SQLExpression<User>(User.class).where(filterUser, new Field[] {
User.class.getField("login"),
User.class.getField("password")
});
if (db.exists(filterExpression)) {
String randomToken = UUID.randomUUID().toString();
authenticationMap.put(db.select(filterExpression).get(0).id, randomToken);
return randomToken;
}
return "";
}
} |
package com.gandalf1209.yge2.graphics;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyListener;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.JComponent;
import com.gandalf1209.yge2.engine.Game;
import com.gandalf1209.yge2.engine.Mesh;
import com.gandalf1209.yge2.engine.Scene;
import com.gandalf1209.yge2.engine.Vector2;
@SuppressWarnings("serial")
public class Display extends JComponent {
private Window frame;
private Game game;
private Scene s;
private GraphicsX g;
private boolean running = false;
public Display(String title, int x, int y, Game game) {
this.game = game;
this.frame = new Window(title, x, y, this);
}
/**
* Returns the Window the Display is attached to
* @return
*/
public Window getWindow() {
return frame;
}
/**
* Starts the loop with a specified delay between frames.
* @param time
*/
public void start(final int fps) {
Thread disp = new Thread("Display Thread") {
public void run() {
while (running) {
repaint();
game.update();
try {
Thread.sleep(1000/fps);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
running = true;
disp.start();
}
/**
* Pauses the loop
*/
public void pause() {
running = false;
}
/**
* Adds a KeyListener to the Window
* @param kl
*/
public void keyListener(KeyListener kl) {
frame.addKeyListener(kl);
}
/**
* Adds a MouseListener to the Window
* @param ml
*/
public void mouseListener(MouseListener ml) {
frame.addMouseListener(ml);
}
/**
* Adds a MouseMotionListener to the Window
* @param mml
*/
public void mouseMotionListener(MouseMotionListener mml) {
frame.addMouseMotionListener(mml);
}
/**
* Sets the scene to be displayed in Window
* @param s
*/
public void loadScene(Scene s) {
this.s = s;
}
/**
* Draws everything it needs to
*/
protected void paintComponent(Graphics g) {
Vector2.verteces.clear();
GraphicsX gx = new GraphicsX(g, frame);
this.g = gx;
gx.setColor(Color.black);
gx.fillRect(0, 0, frame.getWidth(), frame.getHeight());
if (s != null) {
renderMesh(gx);
}
game.render(gx);
}
private void renderMesh(GraphicsX g) {
for (int i = 0; i < s.meshes.size(); i++) {
Mesh m = s.meshes.get(i);
g.setColor(m.getColor());
g.fillRect(m.getX(), m.getY(), m.getW(), m.getH());
if (m.getMaterial() != null) {
g.addImage(m.getMaterial(), m.getX(), m.getY(), m.getW(), m.getH());
}
}
}
public GraphicsX getGraphics() {
return g;
}
} |
package net.jspiner.cachebank;
import android.support.v4.util.LruCache;
import com.jakewharton.disklrucache.DiskLruCache;
import java.io.IOException;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.ObservableSource;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Function;
public final class Bank {
private static int memCacheSize;
private static int diskCacheSize;
private static boolean isInitialized = false;
private static LruCache lruMemCache;
private static DiskLruCache lruDiskCache;
private static CacheMode cacheMode;
private Bank(Builder builder){
this.memCacheSize = builder.memCacheSize;
this.diskCacheSize = builder.diskCacheSize;
this.cacheMode = builder.cacheMode;
this.isInitialized = true;
this.lruMemCache = new LruCache<String, CacheObject>(memCacheSize);
}
public static boolean isInitialized(){
return isInitialized;
}
public static <T extends ProviderInterface> Observable<T> get(String key, Class<T> targetClass){
checkInitAndThrow();
Observable returnObservable = Observable.create(emmiter -> {
CacheObject<T> cachedObject = getCacheObject(key, targetClass);
emmiter.onNext(cachedObject);
emmiter.onComplete();
});
returnObservable.flatMap(new Function<CacheObject, ObservableSource<?>>() {
@Override
public ObservableSource<?> apply(@NonNull CacheObject cacheObject) throws Exception {
if(cacheObject.isObservable()){
return cacheObject.getValueObservable();
}
return Observable.just(cacheObject.getValue());
}
});
return returnObservable;
}
public static <T extends ProviderInterface> T getNow(String key, Class<T> targetClass){
checkInitAndThrow();
CacheObject<T> cachedObject = getCacheObject(key, targetClass);
if(cachedObject.isObservable()){
return (T)cachedObject.getValueObservable().blockingFirst();
}
else{
return cachedObject.getValue();
}
}
private static <T extends ProviderInterface> CacheObject getCacheObject(String key, Class<T> targetClass){
CacheObject<T> cachedObject = getCacheObjectInCache(key, targetClass);
boolean isExpired = isExpired(cachedObject);
if(isExpired){
cachedObject.update(key);
}
return cachedObject;
}
private static <T extends ProviderInterface> CacheObject getCacheObjectInCache(String key, Class<T> targetClass){
CacheObject cachedObject = findInMemory(key, targetClass);
if(cachedObject == null){
cachedObject = findInDisk(key, targetClass);
if(cachedObject != null){
registerInMemory(key, cachedObject);
}
}
if(cachedObject == null){
cachedObject = CacheObject.newInstance(key, targetClass);
}
return cachedObject;
}
private static <T extends ProviderInterface> CacheObject findInMemory(String key, Class<T> targetClass){
CacheObject<T> cachedObject = (CacheObject<T>) lruMemCache.get(key);
if(cachedObject == null){
return null;
}
if(!cachedObject.getValue().getClass().equals(targetClass)){
throw new ClassCastException();
}
return cachedObject;
}
// TODO : disk cache
private static <T extends ProviderInterface> CacheObject findInDisk(String key, Class<T> targetClass){
return null;
}
private static void registerInMemory(String key, CacheObject cacheObject){
lruMemCache.put(key, cacheObject);
}
public static <T extends ProviderInterface> void put(String key, T value){
checkInitAndThrow();
CacheObject<T> cacheObject = new CacheObject<>(
key,
value,
System.currentTimeMillis() + value.getCacheTime()
);
lruMemCache.put(key, cacheObject);
}
private static boolean isExpired(CacheObject cacheObject){
long currentTime = System.currentTimeMillis();
if(cacheObject.getExpireTime() < currentTime){
return true;
}
return false;
}
private static void checkInitAndThrow(){
if(isInitialized() == false){
throw new RuntimeException("You need to start it through the Bank.Builder");
}
}
public static int getMemCacheSize() {
checkInitAndThrow();
return memCacheSize;
}
public static int getDiskCacheSize() {
checkInitAndThrow();
return diskCacheSize;
}
public static CacheMode getCacheMode() {
checkInitAndThrow();
return cacheMode;
}
public static void clear(){
checkInitAndThrow();
clearDiskCache();
clearMemoryCache();
}
private static void clearMemoryCache(){
lruMemCache.evictAll();
}
private static void clearDiskCache(){
try {
if(lruDiskCache != null) {
lruDiskCache.delete();
}
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("IOException", e);
}
}
public static void terminate(){
checkInitAndThrow();
clear();
isInitialized = false;
lruMemCache = null;
}
public final static class Builder {
private int memCacheSize;
private int diskCacheSize;
private CacheMode cacheMode;
public Builder(){
memCacheSize = BankConstant.DEFAULT_MEM_CACHE_SIZE;
diskCacheSize = BankConstant.DEFAULT_DISK_CACHE_SIZE;
cacheMode = BankConstant.DEFAULT_CACHE_MODE;
}
public Bank init(){
return new Bank(this);
}
public Builder setMemCacheSize(int memCacheSize) {
this.memCacheSize = memCacheSize;
return this;
}
public Builder setDiskCacheSize(int diskCacheSize) {
this.diskCacheSize = diskCacheSize;
return this;
}
public Builder setCacheMode(CacheMode cacheMode){
this.cacheMode = cacheMode;
return this;
}
}
} |
package net.formula97.andorid.car_kei_bo;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
/**
* @author kazutoshi
*
*/
public class DbManager extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "fuel_mileage.db";
private static final int DB_VERSION = 1;
private static final String LUB_MASTER = "LUB_MASTER";
private static final String COSTS_MASTER = "COSTS_MASTER";
private static final String CAR_MASTER = "CAR_MASTER";
public DbManager(Context context) {
super(context, DATABASE_NAME, null, DB_VERSION);
// TODO
}
/* ( Javadoc)
* @see android.database.sqlite.SQLiteOpenHelper#onCreate(android.database.sqlite.SQLiteDatabase)
*/
@Override
public void onCreate(SQLiteDatabase db) {
// LUB_MASTER
String create_lub_master = "CREATE TABLE IF NOT EXIST LUB_MASTER ";
create_lub_master += "(RECORD_ID INTEGER PRIMARY KEY AUTOINCREMENT, ";
create_lub_master += "DATE TEXT, CAR_ID INTEGER, ";
create_lub_master += "LUB_AMOUNT REAL, ";
create_lub_master += "UNIT_PRICE REAL, ";
create_lub_master += "ODOMETER REAL, ";
create_lub_master += "COMMENTS TEXT);";
db.execSQL(create_lub_master);
// COSTS_MASTER
String create_costs_master = "CREATE TABLE IF NOT EXIST COSTS_MASTER ";
create_costs_master += "(RECORD_ID INTEGER PRIMARY KEY AUTOINCREMENT, ";
create_costs_master += "DATE TEXT, ";
create_costs_master += "RUNNING_COST REAL);";
db.execSQL(create_costs_master);
// CAR_MASTER
String create_car_master = "CREATE TABLE IF NOT EXIST CAR_MASTER ";
create_car_master += "(CAR_ID INTEGER PRIMARY KEY AUTOINCREMENT, ";
create_car_master += "CAR_NAME TEXT, ";
create_car_master += "DEFAULT INTEGER);";
db.execSQL(create_car_master);
}
/* ( Javadoc)
* @see android.database.sqlite.SQLiteOpenHelper#onUpgrade(android.database.sqlite.SQLiteDatabase, int, int)
*/
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO
// ALTER TABLE
Log.w("Car-Kei-Bo", "Updating database, which will destroy all old data.(for testing)");
db.execSQL("DROP TABLE IF EXIST LUB_MASTER;");
db.execSQL("DROP TABLE IF EXIST COSTS_MASTER;");
db.execSQL("DROP TABLE IF EXIST CAR_MASTER;");
// onCreate()
onCreate(db);
}
public int addNewCar(SQLiteDatabase db, String carName, boolean isDefaultCar) {
// insert()0
int resultInsert = 0;
ContentValues value = new ContentValues();
value.put("CAR_NAME", carName);
value.put("DEFAULT", isDefaultCar);
db.insert(CAR_MASTER, null, value);
return resultInsert;
}
/*
*
*
* truefalse
* SQL
* SELECT CAR_NAME FROM CAR_MASTER WHERE CAR_NAME = '$carName';
*/
protected boolean isExistSameNameCar(SQLiteDatabase db, String carName) {
Cursor q;
String[] columns = {"CAR_NAME"};
String where = "CAR_NAME = ?";
String[] args = {carName};
q = db.query(CAR_MASTER, columns, where, args, null, null, null);
int count = q.getCount();
// 0falsetrue
if (count == 0) {
return false;
} else {
return true;
}
}
/*
*
*
* truefalse
*
*/
protected boolean isExistDefaultCarFlag(SQLiteDatabase db, String carName) {
Cursor q;
String[] columns = {"DEFAULT"};
String where = "CAR_NAME = ?";
String[] args = {carName};
q = db.query(CAR_MASTER, columns, where, args, null, null, null);
int defaultFlag = q.getInt(0);
if (defaultFlag == 0) {
return false;
} else {
return true;
}
}
} |
package de.danielnaber.languagetool;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;
import de.danielnaber.languagetool.rules.Rule;
import de.danielnaber.languagetool.tools.StringTools;
import de.danielnaber.languagetool.tools.Tools;
/**
* The command line tool to check plain text files.
*
* @author Daniel Naber
*/
class Main {
private JLanguageTool lt = null;
private boolean verbose = false;
private boolean apiFormat = false;
/* maximum file size to read in a single read */
private final static int MAXFILESIZE = 64000;
Main(boolean verbose, Language language, Language motherTongue) throws IOException,
ParserConfigurationException, SAXException {
this(verbose, language, motherTongue, new String[0], new String[0]);
}
Main(boolean verbose, Language language, Language motherTongue, String[] disabledRules,
String[] enabledRules) throws IOException, SAXException, ParserConfigurationException {
this(verbose, language, motherTongue, disabledRules, enabledRules, false);
}
Main(boolean verbose, Language language, Language motherTongue, String[] disabledRules,
String[] enabledRules, boolean apiFormat) throws IOException,
SAXException, ParserConfigurationException {
this.verbose = verbose;
this.apiFormat = apiFormat;
lt = new JLanguageTool(language, motherTongue);
lt.activateDefaultPatternRules();
lt.activateDefaultFalseFriendRules();
// disable rules that are disabled explicitly:
for (int i = 0; i < disabledRules.length; i++) {
lt.disableRule(disabledRules[i]);
}
// disable all rules except those enabled explicitly, if any:
if (enabledRules.length > 0) {
Set<String> enabledRuleIDs = new HashSet<String>(Arrays.asList(enabledRules));
for (Rule rule : lt.getAllRules()) {
if (!enabledRuleIDs.contains(rule.getId())) {
lt.disableRule(rule.getId());
}
}
}
}
private void setListUnknownWords(boolean listUnknownWords) {
lt.setListUnknownWords(listUnknownWords);
}
JLanguageTool getJLanguageTool() {
return lt;
}
private void runOnFile(final String filename, final String encoding) throws IOException {
final File file = new File(filename);
if (file.length() < MAXFILESIZE) {
final String text =
getFilteredText(filename, encoding);
Tools.checkText(text, lt);
} else {
if (verbose)
lt.setOutput(System.err);
if (!apiFormat)
System.out.println("Working on "
+ filename + "... in a line by line mode");
//TODO: change LT default statistics mode to summarize at the end
//of processing
InputStreamReader isr = null;
BufferedReader br = null;
try {
if (encoding != null) {
isr = new InputStreamReader(
new FileInputStream(file.getAbsolutePath()), encoding);
} else {
isr = new InputStreamReader(
new FileInputStream(file.getAbsolutePath()));
}
br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
line += "\n";
Tools.checkText(filterXML(line), lt);
}
} finally {
if (br != null) {
br.close();
}
if (isr != null) {
isr.close();
}
}
}
}
private void runRecursive(final String filename, final String encoding) throws IOException,
ParserConfigurationException, SAXException {
final File dir = new File(filename);
if (!dir.isDirectory()) {
throw new IllegalArgumentException(dir.getAbsolutePath() + " is not a directory, cannot use recursion");
}
final File[] files = dir.listFiles();
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
runRecursive(files[i].getAbsolutePath(), encoding);
} else {
runOnFile(files[i].getAbsolutePath(), encoding);
}
}
}
/**
* Loads filename, filter out XML and check the result. Note that the XML filtering
* can lead to incorrect positions in the list of matching rules.
*
* @param filename
* @throws IOException
*/
private String getFilteredText(final String filename, final String encoding) throws IOException {
if (verbose)
lt.setOutput(System.err);
if (!apiFormat)
System.out.println("Working on " + filename + "...");
String fileContents = StringTools.readFile(new FileInputStream(filename), encoding);
return filterXML(fileContents);
}
private String filterXML(String s) {
Pattern pattern = Pattern.compile("", Pattern.DOTALL);
Matcher matcher = pattern.matcher(s);
s = matcher.replaceAll(" ");
pattern = Pattern.compile("<.*?>", Pattern.DOTALL);
matcher = pattern.matcher(s);
s = matcher.replaceAll(" ");
return s;
}
private static void exitWithUsageMessage() {
System.out.println("Usage: java de.danielnaber.languagetool.Main " +
"[-r|--recursive] [-v|--verbose] [-l|--language LANG] [-m|--mothertongue LANG] [-d|--disable RULES] " +
"[-e|--enable RULES] [-c|--encoding] [-u|--list-unknown] [-b] <file>");
System.exit(1);
}
/**
* Command line tool to check plain text files.
*/
public static void main(String[] args) throws IOException, ParserConfigurationException, SAXException {
if (args.length < 1 || args.length > 9) {
exitWithUsageMessage();
}
boolean verbose = false;
boolean recursive = false;
boolean singleLineBreakMarksParagraph = false;
boolean apiFormat = false;
boolean listUnknown = false;
Language language = null;
Language motherTongue = null;
String encoding = null;
String filename = null;
String[] disabledRules = new String[0];
String[] enabledRules = new String[0];
for (int i = 0; i < args.length; i++) {
if (args[i].equals("-h") || args[i].equals("-help") || args[i].equals("--help")) {
exitWithUsageMessage();
} else if (args[i].equals("-v") || args[i].equals("--verbose")) {
verbose = true;
} else if (args[i].equals("-r") || args[i].equals("--recursive")) {
recursive = true;
} else if (args[i].equals("-d") || args[i].equals("--disable")) {
if (enabledRules.length > 0)
throw new IllegalArgumentException("You cannot specifiy both enabled and disabled rules");
String rules = args[++i];
disabledRules = rules.split(",");
} else if (args[i].equals("-e") || args[i].equals("--enable")) {
if (disabledRules.length > 0)
throw new IllegalArgumentException("You cannot specifiy both enabled and disabled rules");
String rules = args[++i];
enabledRules = rules.split(",");
} else if (args[i].equals("-l") || args[i].equals("--language")) {
language = getLanguageOrExit(args[++i]);
} else if (args[i].equals("-m") || args[i].equals("--mothertongue")) {
motherTongue = getLanguageOrExit(args[++i]);
} else if (args[i].equals("-c") || args[i].equals("--encoding")) {
encoding = args[++i];
} else if (args[i].equals("-u") || args[i].equals("--list-unknown")) {
listUnknown = true;
} else if (args[i].equals("-b")) {
singleLineBreakMarksParagraph = true;
} else if (i == args.length - 1) {
filename = args[i];
} else if (args[i].equals("--api")) {
apiFormat = true;
} else {
System.err.println("Unknown option: " + args[i]);
exitWithUsageMessage();
}
}
if (filename == null) {
exitWithUsageMessage();
}
if (language == null) {
if (!apiFormat)
System.err.println("No language specified, using English");
language = Language.ENGLISH;
} else if (!apiFormat) {
System.out.println("Expected text language: " + language.getName());
}
language.getSentenceTokenizer().setSingleLineBreaksMarksParagraph(singleLineBreakMarksParagraph);
Main prg = new Main(verbose, language, motherTongue, disabledRules, enabledRules, apiFormat);
prg.setListUnknownWords(listUnknown);
if (recursive) {
prg.runRecursive(filename, encoding);
} else {
/* String text = prg.getFilteredText(filename, encoding);
Tools.checkText(text, prg.getJLanguageTool(), apiFormat);
*/
prg.runOnFile(filename, encoding);
if (listUnknown) {
System.out.println("Unknown words: " + prg.getJLanguageTool().getUnknownWords());
}
}
}
private static Language getLanguageOrExit(String lang) {
Language language = null;
boolean foundLanguage = false;
List<String> supportedLanguages = new ArrayList<String>();
for (int j = 0; j < Language.LANGUAGES.length; j++) {
Language tmpLang = Language.LANGUAGES[j];
supportedLanguages.add(tmpLang.getShortName());
if (lang.equals(tmpLang.getShortName())) {
language = tmpLang;
foundLanguage = true;
break;
}
}
if (!foundLanguage) {
System.out.println("Unknown language '" + lang + "'. Supported languages are: " + supportedLanguages);
exitWithUsageMessage();
}
return language;
}
} |
package de.SweetCode.e.utils;
import de.SweetCode.e.utils.ToString.ToStringBuilder;
public class Version implements Comparable<Version> {
private final String readable;
private final ReleaseTag releaseTag;
private final int major;
private final int minor;
private final int patch;
private final int build;
public Version(int major, int minor, int patch, int build, ReleaseTag releaseTag) {
if((major < 0) ||(minor < 0) || (patch < 0) || (build < 0)) {
throw new IllegalArgumentException("No part of the version can be negative.");
}
if(releaseTag == null) {
throw new IllegalArgumentException("The release tag cannot be null.");
}
this.major = major;
this.minor = minor;
this.patch = patch;
this.build = build;
this.releaseTag = releaseTag;
if(this.build == 0) {
this.readable = String.format("%d.%d.%d%s", this.major, this.minor, this.patch, this.releaseTag.getTag());
} else {
this.readable = String.format("%d.%d.%d-%d%s", this.major, this.minor, this.patch, this.build, this.releaseTag.getTag());
}
}
public int getMajor() {
return this.major;
}
public int getMinor() {
return this.minor;
}
public int getPatch() {
return this.patch;
}
public int getBuild() {
return this.build;
}
/**
* <p>
* Gives a human readable string of the version.
* </p>
* @return
*/
public String getVersion() {
return this.readable;
}
/**
* <p>
* Lets you created a customized version string. You can simply provide an format with placeholders.
* </p>
* <ul>
* <li>%major% -> Major Version Number</li>
* <li>%minor% -> Minor Version Number</li>
* <li>%patch% -> Patch Version Number</li>
* <li>%build% -> Build Number</li>
* </ul>
* @param format The format for the version string.
*
* @return Returns the format string with replaced placeholders.
*/
public String getVersion(String format) {
Assert.assertNotNull("The format cannot be null.", format);
return format.replaceAll("%major%", String.valueOf(this.major))
.replaceAll("%minor%", String.valueOf(this.minor))
.replaceAll("%patch%", String.valueOf(this.patch))
.replaceAll("%build%", String.valueOf(this.build));
}
public ReleaseTag getReleaseTag() {
return this.releaseTag;
}
@Override
public String toString() {
return ToStringBuilder.create(this)
.build();
}
@Override
public int compareTo(Version v) {
int releaseTagDiff = this.releaseTag.getIndex() - v.getReleaseTag().getIndex();
if(!(releaseTagDiff == 0)) {
return (releaseTagDiff > 0 ? 1 : -1);
}
if(!(this.major == v.getMajor())) {
return (this.major > v.getMajor() ? 1 : -1);
}
if(!(this.minor == v.getMinor())) {
return (this.minor > v.getMinor() ? 1 : -1);
}
if(!(this.patch == v.getPatch())) {
return (this.patch > v.getPatch() ? 1 : -1);
}
if(!(this.build == v.getBuild())) {
return (this.build > v.getBuild() ? 1 : -1);
}
return 0;
}
public enum ReleaseTag {
ALPHA("a", 0),
BETA("b", 1),
NIGHTLY("n", 2),
STABLE("", 3);
private final String tag;
private final int index;
ReleaseTag(String tag, int index) {
this.tag = tag;
this.index = index;
}
public String getTag() {
return this.tag;
}
public int getIndex() {
return this.index;
}
}
} |
package net.sf.mzmine.data.impl;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Vector;
import net.sf.mzmine.data.Parameter;
import net.sf.mzmine.data.ParameterType;
import net.sf.mzmine.data.StorableParameterSet;
import net.sf.mzmine.util.Range;
import org.dom4j.Element;
/**
* Simple storage for the parameters and their values. Typical module will
* inherit this class and define the parameters for the constructor.
*/
public class SimpleParameterSet implements StorableParameterSet {
public static final String PARAMETER_ELEMENT_NAME = "parameter";
public static final String PARAMETER_NAME_ATTRIBUTE = "name";
public static final String PARAMETER_TYPE_ATTRIBUTE = "type";
// Parameters
private Parameter parameters[];
// Parameter -> value
private Hashtable<Parameter, Object> values;
/*
* Multiple selection parameter -> multiple values (array of possible values
*/
private Hashtable<Parameter, Object[]> multipleSelectionValues;
/**
* This constructor is used for cloning
*/
public SimpleParameterSet() {
this(new Parameter[0]);
}
/**
* Checks if project contains current value for some of the parameters, and
* initializes this object using those values if present.
*
*/
public SimpleParameterSet(Parameter[] initParameters) {
this.parameters = initParameters;
values = new Hashtable<Parameter, Object>();
multipleSelectionValues = new Hashtable<Parameter, Object[]>();
}
/**
* @see net.sf.mzmine.data.ParameterSet#getAllParameters()
*/
public Parameter[] getParameters() {
return parameters;
}
/**
* @see net.sf.mzmine.data.ParameterSet#getParameter(java.lang.String)
*/
public Parameter getParameter(String name) {
for (Parameter p : parameters) {
if (p.getName().equals(name))
return p;
}
return null;
}
/**
* @see net.sf.mzmine.data.ParameterSet#getParameterValue(net.sf.mzmine.data.Parameter)
*/
public Object getParameterValue(Parameter parameter) {
Object value = values.get(parameter);
if (value == null)
value = parameter.getDefaultValue();
if (value == null) {
if (parameter.getType() == ParameterType.MULTIPLE_SELECTION)
return new Object[0];
}
return value;
}
public void setMultipleSelection(Parameter parameter,
Object[] selectionArray) {
assert parameter.getType() == ParameterType.MULTIPLE_SELECTION;
if (selectionArray == null)
selectionArray = new Object[0];
multipleSelectionValues.put(parameter, selectionArray);
}
public Object[] getMultipleSelection(Parameter parameter) {
return multipleSelectionValues.get(parameter);
}
public void setParameterValue(Parameter parameter, Object value)
throws IllegalArgumentException {
Object possibleValues[] = parameter.getPossibleValues();
if ((possibleValues != null)
&& (parameter.getType() != ParameterType.MULTIPLE_SELECTION)
&& (parameter.getType() != ParameterType.ORDERED_LIST)) {
for (Object possibleValue : possibleValues) {
// We compare String version of the values, in case some values
// were specified as Enum constants
if (possibleValue.toString().equals(value.toString())) {
values.put(parameter, possibleValue);
return;
}
}
// Value not found
throw (new IllegalArgumentException("Invalid value " + value
+ " for parameter " + parameter));
}
switch (parameter.getType()) {
case BOOLEAN:
if (!(value instanceof Boolean))
throw (new IllegalArgumentException("Value type mismatch"));
break;
case INTEGER:
if (!(value instanceof Integer))
throw (new IllegalArgumentException("Value type mismatch"));
int intValue = (Integer) value;
Integer minIValue = (Integer) parameter.getMinimumValue();
if ((minIValue != null) && (intValue < minIValue))
throw (new IllegalArgumentException(
"Minimum value of parameter " + parameter + " is "
+ minIValue));
Integer maxIValue = (Integer) parameter.getMaximumValue();
if ((maxIValue != null) && (intValue > maxIValue))
throw (new IllegalArgumentException(
"Maximum value of parameter " + parameter + " is "
+ maxIValue));
break;
case DOUBLE:
if (!(value instanceof Double))
throw (new IllegalArgumentException("Value type mismatch"));
double doubleValue = (Double) value;
Double minFValue = (Double) parameter.getMinimumValue();
if ((minFValue != null) && (doubleValue < minFValue))
throw (new IllegalArgumentException(
"Minimum value of parameter " + parameter + " is "
+ minFValue));
Double maxFValue = (Double) parameter.getMaximumValue();
if ((maxFValue != null) && (doubleValue > maxFValue))
throw (new IllegalArgumentException(
"Maximum value of parameter " + parameter + " is "
+ maxFValue));
break;
case RANGE:
if (!(value instanceof Range))
throw (new IllegalArgumentException("Value type mismatch"));
Range rangeValue = (Range) value;
Double minRValue = (Double) parameter.getMinimumValue();
if ((minRValue != null) && (rangeValue.getMin() < minRValue))
throw (new IllegalArgumentException(
"Minimum value of parameter " + parameter + " is "
+ minRValue));
Double maxRValue = (Double) parameter.getMaximumValue();
if ((maxRValue != null) && (rangeValue.getMax() > maxRValue))
throw (new IllegalArgumentException(
"Maximum value of parameter " + parameter + " is "
+ maxRValue));
break;
case STRING:
if (!(value instanceof String))
throw (new IllegalArgumentException("Value type mismatch"));
break;
case MULTIPLE_SELECTION:
if (!value.getClass().isArray())
throw (new IllegalArgumentException("Value type mismatch"));
Object valueArray[] = (Object[]) value;
if (parameter.getMinimumValue() != null) {
int min = (Integer) parameter.getMinimumValue();
if (valueArray.length < min)
throw (new IllegalArgumentException(
"Please select minimum " + min
+ " values for parameter " + parameter));
}
if (parameter.getMaximumValue() != null) {
int max = (Integer) parameter.getMaximumValue();
if (valueArray.length > max)
throw (new IllegalArgumentException(
"Please select maximum " + max
+ " values for parameter " + parameter));
}
break;
case FILE_NAME:
if (!(value instanceof String))
throw (new IllegalArgumentException("Value type mismatch"));
break;
case ORDERED_LIST:
if (!value.getClass().isArray())
throw (new IllegalArgumentException("Value type mismatch"));
break;
}
values.put(parameter, value);
}
/**
* @see net.sf.mzmine.data.ParameterSet#exportValuesToXML(org.w3c.dom.Element)
*/
public void exportValuesToXML(Element element) {
for (Parameter p : parameters) {
Element newElement = element.addElement(PARAMETER_ELEMENT_NAME);
newElement.addAttribute(PARAMETER_NAME_ATTRIBUTE, p.getName());
newElement.addAttribute(PARAMETER_TYPE_ATTRIBUTE, p.getType()
.toString());
if ((p.getType() == ParameterType.MULTIPLE_SELECTION)
|| (p.getType() == ParameterType.ORDERED_LIST)) {
Object[] values = (Object[]) getParameterValue(p);
if (values != null) {
String valueAsString = "";
for (int i = 0; i < values.length; i++) {
if (i == values.length - 1) {
valueAsString += String.valueOf(values[i]);
} else {
valueAsString += String.valueOf(values[i]) + ",";
}
}
newElement.addText(valueAsString);
}
} else {
Object value = getParameterValue(p);
if (value != null) {
String valueAsString;
if (value instanceof Range) {
Range rangeValue = (Range) value;
valueAsString = String.valueOf(rangeValue.getMin())
+ "-" + String.valueOf(rangeValue.getMax());
} else {
valueAsString = value.toString();
}
newElement.addText(valueAsString);
}
}
}
}
/**
* @see net.sf.mzmine.data.ParameterSet#importValuesFromXML(org.w3c.dom.Element)
*/
public void importValuesFromXML(Element element) {
Iterator paramIter = element.elementIterator(PARAMETER_ELEMENT_NAME);
while (paramIter.hasNext()) {
Element paramElem = (Element) paramIter.next();
Parameter param = getParameter(paramElem
.attributeValue(PARAMETER_NAME_ATTRIBUTE));
if (param == null)
continue;
ParameterType paramType = ParameterType.valueOf(paramElem
.attributeValue(PARAMETER_TYPE_ATTRIBUTE));
String valueText = paramElem.getText();
if ((valueText == null) || (valueText.length() == 0))
continue;
Object value = null;
switch (paramType) {
case BOOLEAN:
value = Boolean.parseBoolean(valueText);
break;
case INTEGER:
value = Integer.parseInt(valueText);
break;
case DOUBLE:
value = Double.parseDouble(valueText);
break;
case RANGE:
value = new Range(valueText);
break;
case STRING:
value = valueText;
break;
case MULTIPLE_SELECTION:
String stringMultipleValues[] = valueText.split(",");
Object possibleMultipleValues[] = param.getPossibleValues();
if (possibleMultipleValues == null)
continue;
Vector<Object> multipleValues = new Vector<Object>();
for (int i = 0; i < stringMultipleValues.length; i++) {
for (int j = 0; j < possibleMultipleValues.length; j++)
if (stringMultipleValues[i].equals(String
.valueOf(possibleMultipleValues[j])))
multipleValues.add(possibleMultipleValues[j]);
}
value = multipleValues.toArray();
break;
case FILE_NAME:
value = valueText;
break;
case ORDERED_LIST:
String stringValues[] = valueText.split(",");
Object possibleValues[] = param.getPossibleValues();
Object orderedValues[] = new Object[stringValues.length];
for (int i = 0; i < stringValues.length; i++) {
for (int j = 0; j < possibleValues.length; j++) {
if (stringValues[i].equals(String
.valueOf(possibleValues[j])))
orderedValues[i] = possibleValues[j];
}
}
value = orderedValues;
break;
}
try {
setParameterValue(param, value);
} catch (IllegalArgumentException e) {
// ignore
}
}
}
public void importValuesFrom(SimpleParameterSet valueSet) {
for (Parameter p : parameters) {
Object value = valueSet.getParameterValue(p);
if (value != null)
this.setParameterValue(p, value);
}
}
public SimpleParameterSet clone() {
try {
// do not make a new instance of SimpleParameterSet, but instead
// clone the runtime class of this instance - runtime type may be
// inherited class
SimpleParameterSet newSet = this.getClass().newInstance();
newSet.parameters = this.parameters;
for (Parameter p : parameters) {
Object v = values.get(p);
if (v != null)
newSet.setParameterValue(p, v);
}
return newSet;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* Represent method's parameters and their values in human-readable format
*/
public String toString() {
StringBuffer s = new StringBuffer();
for (Parameter p : getParameters()) {
s = s.append(p.getName() + ": " + values.get(p) + ", ");
}
return s.toString();
}
} |
package net.sf.mzmine.data.impl;
import java.util.Hashtable;
import java.util.Iterator;
import net.sf.mzmine.data.Parameter;
import net.sf.mzmine.data.ParameterType;
import net.sf.mzmine.data.StorableParameterSet;
import net.sf.mzmine.util.Range;
import org.dom4j.Element;
/**
* Simple storage for the parameters and their values. Typical module will
* inherit this class and define the parameters for the constructor.
*/
public class SimpleParameterSet implements StorableParameterSet {
public static final String PARAMETER_ELEMENT_NAME = "parameter";
public static final String PARAMETER_NAME_ATTRIBUTE = "name";
public static final String PARAMETER_TYPE_ATTRIBUTE = "type";
// Parameters
private Parameter parameters[];
// Parameter -> value
private Hashtable<Parameter, Object> values;
/*
* Multiple selection parameter -> multiple values (array of possible values
*/
private Hashtable<Parameter, Object[]> multipleSelectionValues;
/**
* This constructor is used for cloning
*/
public SimpleParameterSet() {
this(new Parameter[0]);
}
/**
* Checks if project contains current value for some of the parameters, and
* initializes this object using those values if present.
*
*/
public SimpleParameterSet(Parameter[] initParameters) {
this.parameters = initParameters;
values = new Hashtable<Parameter, Object>();
multipleSelectionValues = new Hashtable<Parameter, Object[]>();
}
/**
* @see net.sf.mzmine.data.ParameterSet#getAllParameters()
*/
public Parameter[] getParameters() {
return parameters;
}
/**
* @see net.sf.mzmine.data.ParameterSet#getParameter(java.lang.String)
*/
public Parameter getParameter(String name) {
for (Parameter p : parameters) {
if (p.getName().equals(name))
return p;
}
return null;
}
/**
* @see net.sf.mzmine.data.ParameterSet#getParameterValue(net.sf.mzmine.data.Parameter)
*/
public Object getParameterValue(Parameter parameter) {
Object value = values.get(parameter);
if (value == null)
value = parameter.getDefaultValue();
if (value == null) {
if (parameter.getType() == ParameterType.MULTIPLE_SELECTION)
return new Object[0];
}
return value;
}
public void setMultipleSelection(Parameter parameter,
Object[] selectionArray) {
assert parameter.getType() == ParameterType.MULTIPLE_SELECTION;
if (selectionArray == null)
selectionArray = new Object[0];
multipleSelectionValues.put(parameter, selectionArray);
}
public Object[] getMultipleSelection(Parameter parameter) {
return multipleSelectionValues.get(parameter);
}
public void setParameterValue(Parameter parameter, Object value)
throws IllegalArgumentException {
Object possibleValues[] = parameter.getPossibleValues();
if ((possibleValues != null)
&& (parameter.getType() != ParameterType.MULTIPLE_SELECTION)
&& (parameter.getType() != ParameterType.ORDERED_LIST)) {
for (Object possibleValue : possibleValues) {
// We compare String version of the values, in case some values
// were specified as Enum constants
if (possibleValue.toString().equals(value.toString())) {
values.put(parameter, possibleValue);
return;
}
}
// Value not found
throw (new IllegalArgumentException("Invalid value " + value
+ " for parameter " + parameter));
}
switch (parameter.getType()) {
case BOOLEAN:
if (!(value instanceof Boolean))
throw (new IllegalArgumentException("Value type mismatch"));
break;
case INTEGER:
if (!(value instanceof Integer))
throw (new IllegalArgumentException("Value type mismatch"));
int intValue = (Integer) value;
Integer minIValue = (Integer) parameter.getMinimumValue();
if ((minIValue != null) && (intValue < minIValue))
throw (new IllegalArgumentException(
"Minimum value of parameter " + parameter + " is "
+ minIValue));
Integer maxIValue = (Integer) parameter.getMaximumValue();
if ((maxIValue != null) && (intValue > maxIValue))
throw (new IllegalArgumentException(
"Maximum value of parameter " + parameter + " is "
+ maxIValue));
break;
case DOUBLE:
if (!(value instanceof Double))
throw (new IllegalArgumentException("Value type mismatch"));
double doubleValue = (Double) value;
Double minFValue = (Double) parameter.getMinimumValue();
if ((minFValue != null) && (doubleValue < minFValue))
throw (new IllegalArgumentException(
"Minimum value of parameter " + parameter + " is "
+ minFValue));
Double maxFValue = (Double) parameter.getMaximumValue();
if ((maxFValue != null) && (doubleValue > maxFValue))
throw (new IllegalArgumentException(
"Maximum value of parameter " + parameter + " is "
+ maxFValue));
break;
case RANGE:
if (!(value instanceof Range))
throw (new IllegalArgumentException("Value type mismatch"));
Range rangeValue = (Range) value;
Double minRValue = (Double) parameter.getMinimumValue();
if ((minRValue != null) && (rangeValue.getMin() < minRValue))
throw (new IllegalArgumentException(
"Minimum value of parameter " + parameter + " is "
+ minRValue));
Double maxRValue = (Double) parameter.getMaximumValue();
if ((maxRValue != null) && (rangeValue.getMax() > maxRValue))
throw (new IllegalArgumentException(
"Maximum value of parameter " + parameter + " is "
+ maxRValue));
break;
case STRING:
if (!(value instanceof String))
throw (new IllegalArgumentException("Value type mismatch"));
break;
case MULTIPLE_SELECTION:
if (!value.getClass().isArray())
throw (new IllegalArgumentException("Value type mismatch"));
Object valueArray[] = (Object[]) value;
if (parameter.getMinimumValue() != null) {
int min = (Integer) parameter.getMinimumValue();
if (valueArray.length < min)
throw (new IllegalArgumentException(
"Please select minimum " + min
+ " values for parameter " + parameter));
}
if (parameter.getMaximumValue() != null) {
int max = (Integer) parameter.getMaximumValue();
if (valueArray.length > max)
throw (new IllegalArgumentException(
"Please select maximum " + max
+ " values for parameter " + parameter));
}
break;
case FILE_NAME:
if (!(value instanceof String))
throw (new IllegalArgumentException("Value type mismatch"));
break;
case ORDERED_LIST:
if (!value.getClass().isArray())
throw (new IllegalArgumentException("Value type mismatch"));
break;
}
values.put(parameter, value);
}
/**
* @see net.sf.mzmine.data.ParameterSet#exportValuesToXML(org.w3c.dom.Element)
*/
public void exportValuesToXML(Element element) {
for (Parameter p : parameters) {
Element newElement = element.addElement(PARAMETER_ELEMENT_NAME);
newElement.addAttribute(PARAMETER_NAME_ATTRIBUTE, p.getName());
newElement.addAttribute(PARAMETER_TYPE_ATTRIBUTE, p.getType()
.toString());
if ((p.getType() == ParameterType.MULTIPLE_SELECTION)
|| (p.getType() == ParameterType.ORDERED_LIST)) {
Object[] values = (Object[]) getParameterValue(p);
if (values != null) {
String valueAsString = "";
for (int i = 0; i < values.length; i++) {
if (i == values.length - 1) {
valueAsString += String.valueOf(values[i])
.replaceAll(",", ",");
} else {
valueAsString += String.valueOf(values[i])
.replaceAll(",", ",") + ",";
}
}
newElement.addText(valueAsString);
}
} else {
Object value = getParameterValue(p);
if (value != null) {
String valueAsString;
if (value instanceof Range) {
Range rangeValue = (Range) value;
valueAsString = String.valueOf(rangeValue.getMin())
+ "-" + String.valueOf(rangeValue.getMax());
} else {
valueAsString = value.toString();
}
newElement.addText(valueAsString);
}
}
}
}
/**
* @see net.sf.mzmine.data.ParameterSet#importValuesFromXML(org.w3c.dom.Element)
*/
public void importValuesFromXML(Element element) {
Iterator paramIter = element.elementIterator(PARAMETER_ELEMENT_NAME);
while (paramIter.hasNext()) {
Element paramElem = (Element) paramIter.next();
Parameter param = getParameter(paramElem
.attributeValue(PARAMETER_NAME_ATTRIBUTE));
if (param == null)
continue;
ParameterType paramType = ParameterType.valueOf(paramElem
.attributeValue(PARAMETER_TYPE_ATTRIBUTE));
String valueText = paramElem.getText();
if ((valueText == null) || (valueText.length() == 0))
continue;
Object value = null;
switch (paramType) {
case BOOLEAN:
value = Boolean.parseBoolean(valueText);
break;
case INTEGER:
value = Integer.parseInt(valueText);
break;
case DOUBLE:
value = Double.parseDouble(valueText);
break;
case RANGE:
value = new Range(valueText);
break;
case STRING:
value = valueText;
break;
case MULTIPLE_SELECTION:
String array[] = valueText.split(",");
for (int i = 0; i < array.length; i++) {
array[i] = array[i].replaceAll(",", ",");
}
value = array;
break;
case FILE_NAME:
value = valueText;
break;
case ORDERED_LIST:
String stringValues[] = valueText.split(",");
Object possibleValues[] = param.getPossibleValues();
Object orderedValues[] = new Object[stringValues.length];
for (int i = 0; i < stringValues.length; i++) {
for (int j = 0; j < possibleValues.length; j++) {
if (stringValues[i].equals(String
.valueOf(possibleValues[j])))
orderedValues[i] = possibleValues[j];
}
}
value = orderedValues;
break;
}
try {
setParameterValue(param, value);
} catch (IllegalArgumentException e) {
// ignore
}
}
}
public void importValuesFrom(SimpleParameterSet valueSet) {
for (Parameter p : parameters) {
Object value = valueSet.getParameterValue(p);
if (value != null)
this.setParameterValue(p, value);
}
}
public SimpleParameterSet clone() {
try {
// do not make a new instance of SimpleParameterSet, but instead
// clone the runtime class of this instance - runtime type may be
// inherited class
SimpleParameterSet newSet = this.getClass().newInstance();
newSet.parameters = this.parameters;
for (Parameter p : parameters) {
Object v = values.get(p);
if (v != null)
newSet.setParameterValue(p, v);
}
return newSet;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* Represent method's parameters and their values in human-readable format
*/
public String toString() {
StringBuffer s = new StringBuffer();
for (Parameter p : getParameters()) {
s = s.append(p.getName() + ": " + values.get(p) + ", ");
}
return s.toString();
}
} |
package com.cebedo.pmsys.model;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
@Entity
@Table(name = Expense.TABLE_NAME)
public class Expense implements Serializable {
public static final String TABLE_NAME = "expenses";
public static final String OBJECT_NAME = "expense";
public static final String COLUMN_PRIMARY_KEY = OBJECT_NAME + "_id";
private static final long serialVersionUID = 1L;
private long id;
private String name;
private String description;
private double value;
private Date date;
/**
* Any of the following can have expenses.<br>
* Relationship is 1 of any below, to Many expenses.
*/
private Task task;
private Project project;
private Company company;
private Staff staff;
private Team team;
private Delivery delivery;
private Material material;
private Milestone milestone;
private Reminder reminder;
private Storage storage;
private Supplier supplier;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = COLUMN_PRIMARY_KEY, unique = true, nullable = false)
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
@Column(name = "name", nullable = false, length = 32)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Column(name = "description")
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Column(name = "value", nullable = false)
public double getValue() {
return value;
}
public void setValue(double value) {
this.value = value;
}
@Column(name = "date", nullable = false)
@Temporal(TemporalType.DATE)
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
@ManyToOne
@JoinColumn(name = Task.COLUMN_PRIMARY_KEY)
public Task getTask() {
return task;
}
public void setTask(Task task) {
this.task = task;
}
@ManyToOne
@JoinColumn(name = Project.COLUMN_PRIMARY_KEY)
public Project getProject() {
return project;
}
public void setProject(Project project) {
this.project = project;
}
@ManyToOne
@JoinColumn(name = Company.COLUMN_PRIMARY_KEY)
public Company getCompany() {
return company;
}
public void setCompany(Company company) {
this.company = company;
}
@ManyToOne
@JoinColumn(name = Staff.COLUMN_PRIMARY_KEY)
public Staff getStaff() {
return staff;
}
public void setStaff(Staff staff) {
this.staff = staff;
}
@ManyToOne
@JoinColumn(name = Team.COLUMN_PRIMARY_KEY)
public Team getTeam() {
return team;
}
public void setTeam(Team team) {
this.team = team;
}
@ManyToOne
@JoinColumn(name = Delivery.COLUMN_PRIMARY_KEY)
public Delivery getDelivery() {
return delivery;
}
public void setDelivery(Delivery delivery) {
this.delivery = delivery;
}
@ManyToOne
@JoinColumn(name = Material.COLUMN_PRIMARY_KEY)
public Material getMaterial() {
return material;
}
public void setMaterial(Material material) {
this.material = material;
}
@ManyToOne
@JoinColumn(name = Milestone.COLUMN_PRIMARY_KEY)
public Milestone getMilestone() {
return milestone;
}
public void setMilestone(Milestone milestone) {
this.milestone = milestone;
}
@ManyToOne
@JoinColumn(name = Reminder.COLUMN_PRIMARY_KEY)
public Reminder getReminder() {
return reminder;
}
public void setReminder(Reminder reminder) {
this.reminder = reminder;
}
@ManyToOne
@JoinColumn(name = Storage.COLUMN_PRIMARY_KEY)
public Storage getStorage() {
return storage;
}
public void setStorage(Storage storage) {
this.storage = storage;
}
@ManyToOne
@JoinColumn(name = Supplier.COLUMN_PRIMARY_KEY)
public Supplier getSupplier() {
return supplier;
}
public void setSupplier(Supplier supplier) {
this.supplier = supplier;
}
} |
package com.github.twitch4j;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.philippheuer.credentialmanager.domain.OAuth2Credential;
import com.github.philippheuer.events4j.core.domain.Event;
import com.github.twitch4j.chat.events.channel.FollowEvent;
import com.github.twitch4j.common.events.channel.ChannelChangeGameEvent;
import com.github.twitch4j.common.events.channel.ChannelChangeTitleEvent;
import com.github.twitch4j.common.events.channel.ChannelGoLiveEvent;
import com.github.twitch4j.common.events.channel.ChannelGoOfflineEvent;
import com.github.twitch4j.common.events.domain.EventChannel;
import com.github.twitch4j.common.events.domain.EventUser;
import com.github.twitch4j.common.util.CollectionUtils;
import com.github.twitch4j.domain.ChannelCache;
import com.github.twitch4j.helix.domain.*;
import com.netflix.hystrix.HystrixCommand;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
/**
* A helper class that covers a few basic use cases of most library users
*/
@Slf4j
public class TwitchClientHelper implements AutoCloseable {
/**
* The greatest number of streams or followers that can be requested in a single API call
*/
private static final int MAX_LIMIT = 100;
/**
* Holds the channels that are checked for live/offline state changes
*/
private final Set<String> listenForGoLive = ConcurrentHashMap.newKeySet();
/**
* Holds the channels that are checked for new followers
*/
private final Set<String> listenForFollow = ConcurrentHashMap.newKeySet();
/**
* TwitchClient
*/
private final TwitchClient twitchClient;
/**
* Event Task - Stream Status
*/
private final Runnable streamStatusEventTask;
/**
* The {@link ScheduledFuture} associated with streamStatusEventTask, in an atomic wrapper
*/
private final AtomicReference<ScheduledFuture<?>> streamStatusEventFuture = new AtomicReference<>();
/**
* Event Task - Followers
*/
private final Runnable followerEventTask;
/**
* The {@link ScheduledFuture} associated with followerEventTask, in an atomic wrapper
*/
private final AtomicReference<ScheduledFuture<?>> followerEventFuture = new AtomicReference<>();
/**
* Default Auth Token for Twitch API Requests
*/
@Setter
private OAuth2Credential defaultAuthToken = null;
/**
* Channel Information Cache
*/
private final Cache<String, ChannelCache> channelInformation = Caffeine.newBuilder()
.expireAfterAccess(10, TimeUnit.MINUTES)
.maximumSize(10_000)
.build();
/**
* Scheduled Thread Pool Executor
*/
private final ScheduledThreadPoolExecutor executor;
/**
* Thread Rate
*/
@Setter
private long threadRate;
/**
* Constructor
*
* @param twitchClient TwitchClient
* @param executor ScheduledThreadPoolExecutor
*/
public TwitchClientHelper(TwitchClient twitchClient, ScheduledThreadPoolExecutor executor) {
this.twitchClient = twitchClient;
this.executor = executor;
// Threads
this.streamStatusEventTask = () -> {
// check go live / stream events
CollectionUtils.chunked(listenForGoLive, MAX_LIMIT).forEach(channels -> {
HystrixCommand<StreamList> hystrixGetAllStreams = twitchClient.getHelix().getStreams(defaultAuthToken.getAccessToken(), null, null, channels.size(), null, null, null, channels, null);
try {
Map<String, Stream> streams = new HashMap<>();
channels.forEach(id -> streams.put(id, null));
hystrixGetAllStreams.execute().getStreams().forEach(s -> streams.put(s.getUserId(), s));
streams.forEach((userId, stream) -> {
// Check if the channel's live status is still desired to be tracked
if (!listenForGoLive.contains(userId))
return;
ChannelCache currentChannelCache = channelInformation.get(userId, s -> new ChannelCache(null, null, null, null, null));
if (stream != null)
currentChannelCache.setUserName(stream.getUserName());
final EventChannel channel = new EventChannel(userId, currentChannelCache.getUserName());
boolean dispatchGoLiveEvent = false;
boolean dispatchGoOfflineEvent = false;
boolean dispatchTitleChangedEvent = false;
boolean dispatchGameChangedEvent = false;
if (stream != null && stream.getType().equalsIgnoreCase("live")) {
// is live
// - live status
if (currentChannelCache.getIsLive() != null && currentChannelCache.getIsLive() == false) {
dispatchGoLiveEvent = true;
}
currentChannelCache.setIsLive(true);
boolean wasAlreadyLive = dispatchGoLiveEvent != true && currentChannelCache.getIsLive() == true;
// - change stream title event
if (wasAlreadyLive && currentChannelCache.getTitle() != null && !currentChannelCache.getTitle().equalsIgnoreCase(stream.getTitle())) {
dispatchTitleChangedEvent = true;
}
currentChannelCache.setTitle(stream.getTitle());
// - change game event
if (wasAlreadyLive && currentChannelCache.getGameId() != null && !currentChannelCache.getGameId().equals(stream.getGameId())) {
dispatchGameChangedEvent = true;
}
currentChannelCache.setGameId(stream.getGameId());
} else {
// was online previously?
if (currentChannelCache.getIsLive() != null && currentChannelCache.getIsLive() == true) {
dispatchGoOfflineEvent = true;
}
// is offline
currentChannelCache.setIsLive(false);
currentChannelCache.setTitle(null);
currentChannelCache.setGameId(null);
}
// dispatch events
// - go live event
if (dispatchGoLiveEvent) {
Event event = new ChannelGoLiveEvent(channel, currentChannelCache.getTitle(), currentChannelCache.getGameId());
twitchClient.getEventManager().publish(event);
}
// - go offline event
if (dispatchGoOfflineEvent) {
Event event = new ChannelGoOfflineEvent(channel);
twitchClient.getEventManager().publish(event);
}
// - title changed event
if (dispatchTitleChangedEvent) {
Event event = new ChannelChangeTitleEvent(channel, currentChannelCache.getTitle());
twitchClient.getEventManager().publish(event);
}
// - game changed event
if (dispatchGameChangedEvent) {
Event event = new ChannelChangeGameEvent(channel, currentChannelCache.getGameId());
twitchClient.getEventManager().publish(event);
}
});
} catch (Exception ex) {
if (hystrixGetAllStreams != null && hystrixGetAllStreams.isFailedExecution()) {
log.trace(hystrixGetAllStreams.getFailedExecutionException().getMessage(), hystrixGetAllStreams.getFailedExecutionException());
}
log.error("Failed to check for Stream Events (Live/Offline/...): " + ex.getMessage());
}
});
};
this.followerEventTask = () -> {
// check follow events
for (String channelId : listenForFollow) {
HystrixCommand<FollowList> commandGetFollowers = twitchClient.getHelix().getFollowers(defaultAuthToken.getAccessToken(), null, channelId, null, MAX_LIMIT);
try {
ChannelCache currentChannelCache = channelInformation.get(channelId, s -> new ChannelCache(null, null, null, null, null));
LocalDateTime lastFollowDate = null;
if (currentChannelCache.getLastFollowCheck() != null) {
List<Follow> followList = commandGetFollowers.execute().getFollows();
EventChannel channel = null;
if (!followList.isEmpty())
channel = new EventChannel(channelId, followList.get(0).getToName());
for (Follow follow : followList) {
// update lastFollowDate
if (lastFollowDate == null || follow.getFollowedAt().compareTo(lastFollowDate) > 0) {
lastFollowDate = follow.getFollowedAt();
}
// is new follower?
if (follow.getFollowedAt().compareTo(currentChannelCache.getLastFollowCheck()) > 0) {
// dispatch event
FollowEvent event = new FollowEvent(channel, new EventUser(follow.getFromId(), follow.getFromName()));
twitchClient.getEventManager().publish(event);
}
}
}
if (currentChannelCache.getLastFollowCheck() == null) {
// only happens if the user doesn't have any followers at all
currentChannelCache.setLastFollowCheck(LocalDateTime.now(ZoneId.of("UTC")));
} else {
// tracks the date of the latest follow to identify new ones later on
currentChannelCache.setLastFollowCheck(lastFollowDate);
}
} catch (Exception ex) {
if (commandGetFollowers != null && commandGetFollowers.isFailedExecution()) {
log.trace(ex.getMessage(), ex);
}
log.error("Failed to check for Follow Events: " + ex.getMessage());
}
}
};
}
/**
* Enable StreamEvent Listener
*
* @param channelName Channel Name
*/
public void enableStreamEventListener(String channelName) {
UserList users = twitchClient.getHelix().getUsers(defaultAuthToken.getAccessToken(), null, Collections.singletonList(channelName)).execute();
if (users.getUsers().size() == 1) {
users.getUsers().forEach(user -> enableStreamEventListener(user.getId(), user.getLogin()));
startOrStopEventGenerationThread();
} else {
log.error("Failed to add channel {} to stream event listener!", channelName);
}
}
/**
* Enable StreamEvent Listener, without invoking a Helix API call
*
* @param channelId Channel Id
* @param channelName Channel Name
* @return true if the channel was added, false otherwise
*/
public boolean enableStreamEventListener(String channelId, String channelName) {
// add to set
final boolean add = listenForGoLive.add(channelId);
if (!add) {
log.info("Channel {} already added for Stream Events", channelName);
} else {
// initialize cache
channelInformation.get(channelId, s -> new ChannelCache(channelName, null, null, null, null));
}
return add;
}
/**
* Disable StreamEvent Listener
*
* @param channelName Channel Name
*/
public void disableStreamEventListener(String channelName) {
UserList users = twitchClient.getHelix().getUsers(defaultAuthToken.getAccessToken(), null, Collections.singletonList(channelName)).execute();
if (users.getUsers().size() == 1) {
users.getUsers().forEach(user -> disableStreamEventListenerForId(user.getId()));
startOrStopEventGenerationThread();
} else {
log.error("Failed to remove channel " + channelName + " from stream event listener!");
}
}
/**
* Disable StreamEventListener, without invoking a Helix API call
*
* @param channelId Channel Id
* @return true if the channel was removed
*/
public boolean disableStreamEventListenerForId(String channelId) {
// invalidate cache
channelInformation.invalidate(channelId);
// remove from set
return listenForGoLive.remove(channelId);
}
/**
* Follow Listener
*
* @param channelName Channel Name
*/
public void enableFollowEventListener(String channelName) {
UserList users = twitchClient.getHelix().getUsers(defaultAuthToken.getAccessToken(), null, Collections.singletonList(channelName)).execute();
if (users.getUsers().size() == 1) {
users.getUsers().forEach(user -> enableFollowEventListener(user.getId(), user.getLogin()));
startOrStopEventGenerationThread();
} else {
log.error("Failed to add channel " + channelName + " to Follow Listener, maybe it doesn't exist!");
}
}
/**
* Enable Follow Listener, without invoking a Helix API call
*
* @param channelId Channel Id
* @param channelName Channel Name
* @return true if the channel was added, false otherwise
*/
public boolean enableFollowEventListener(String channelId, String channelName) {
// add to list
final boolean add = listenForFollow.add(channelId);
if (!add) {
log.info("Channel {} already added for Follow Events", channelName);
} else {
// initialize cache
channelInformation.get(channelId, s -> new ChannelCache(channelName, null, null, null, null));
}
return add;
}
/**
* Disable Follow Listener
*
* @param channelName Channel Name
*/
public void disableFollowEventListener(String channelName) {
UserList users = twitchClient.getHelix().getUsers(defaultAuthToken.getAccessToken(), null, Collections.singletonList(channelName)).execute();
if (users.getUsers().size() == 1) {
users.getUsers().forEach(user -> disableFollowEventListenerForId(user.getId()));
startOrStopEventGenerationThread();
} else {
log.error("Failed to remove channel " + channelName + " from follow listener!");
}
}
/**
* Disable Follow Listener, without invoking a Helix API call
*
* @param channelId Channel Id
* @return true when a previously-tracked channel was removed, false otherwise
*/
public boolean disableFollowEventListenerForId(String channelId) {
// invalidate cache
channelInformation.invalidate(channelId);
// remove from set
return listenForFollow.remove(channelId);
}
/**
* Start or quit the thread, depending on usage
*/
private void startOrStopEventGenerationThread() {
// stream status event thread
streamStatusEventFuture.updateAndGet(scheduledFuture -> {
if (listenForGoLive.size() > 0) {
if (scheduledFuture == null)
return executor.scheduleAtFixedRate(this.streamStatusEventTask, 1, threadRate,
TimeUnit.MILLISECONDS);
return scheduledFuture;
} else {
if (scheduledFuture != null) {
scheduledFuture.cancel(false);
}
return null;
}
});
// follower event thread
followerEventFuture.updateAndGet(scheduledFuture -> {
if (listenForFollow.size() > 0) {
if (scheduledFuture == null)
return executor.scheduleAtFixedRate(this.followerEventTask, 1, threadRate, TimeUnit.MILLISECONDS);
return scheduledFuture;
} else {
if (scheduledFuture != null)
scheduledFuture.cancel(false);
return null;
}
});
}
/**
* Close
*/
public void close() {
final ScheduledFuture<?> streamStatusFuture = this.streamStatusEventFuture.get();
if (streamStatusFuture != null)
streamStatusFuture.cancel(false);
final ScheduledFuture<?> followerFuture = this.followerEventFuture.get();
if (followerFuture != null)
followerFuture.cancel(false);
}
} |
package opendap.bes.dap2Responders;
import opendap.bes.Version;
import opendap.bes.dap4Responders.Dap4Responder;
import opendap.bes.dap4Responders.MediaType;
import opendap.coreServlet.OPeNDAPException;
import opendap.coreServlet.ReqInfo;
import opendap.coreServlet.RequestCache;
import opendap.http.mediaTypes.TextHtml;
import org.slf4j.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
public class DatasetHtmlForm extends Dap4Responder {
private Logger log;
private static String _defaultRequestSuffix = ".html";
public DatasetHtmlForm(String sysPath, BesApi besApi) {
this(sysPath,null, _defaultRequestSuffix,besApi);
}
public DatasetHtmlForm(String sysPath, String pathPrefix, BesApi besApi) {
this(sysPath,pathPrefix, _defaultRequestSuffix,besApi);
}
public DatasetHtmlForm(String sysPath, String pathPrefix, String requestSuffixRegex, BesApi besApi) {
super(sysPath, pathPrefix, requestSuffixRegex, besApi);
log = org.slf4j.LoggerFactory.getLogger(this.getClass());
setServiceRoleId("http://services.opendap.org/dap2/data_request_form");
setServiceTitle("DAP2 Dataset Form");
setServiceDescription("DAP2 Data Request Form (HTML).");
setServiceDescriptionLink("http://docs.opendap.org/index.php/DAP4:_Specification_Volume_2#DAP2:_HTML_DATA_Request_Form_Service");
setNormativeMediaType(new TextHtml(getRequestSuffix()));
log.debug("Using RequestSuffix: '{}'", getRequestSuffix());
log.debug("Using CombinedRequestSuffixRegex: '{}'", getCombinedRequestSuffixRegex());
}
public boolean isDataResponder(){ return false; }
public boolean isMetadataResponder(){ return true; }
public void sendNormativeRepresentation(HttpServletRequest request, HttpServletResponse response) throws Exception {
String relativeUrl = ReqInfo.getLocalUrl(request);
String resourceID = getResourceId(relativeUrl, false);
String xmlBase = getXmlBase(request);
BesApi besApi = getBesApi();
log.debug("Sending DAP2 Dataset HTML Form for dataset: " + resourceID);
MediaType responseMediaType = getNormativeMediaType();
// Stash the Media type in case there's an error. That way the error handler will know how to encode the error.
RequestCache.put(OPeNDAPException.ERROR_RESPONSE_MEDIA_TYPE_KEY, responseMediaType);
response.setContentType(responseMediaType.getMimeType());
Version.setOpendapMimeHeaders(request,response,besApi);
response.setHeader("Content-Description", "DAP2 Data Request Form");
response.setStatus(HttpServletResponse.SC_OK);
String xdap_accept = request.getHeader("XDAP-Accept");
OutputStream os = response.getOutputStream();
besApi.writeDap2DataRequestForm(resourceID, xdap_accept, xmlBase, os);
os.flush();
log.info("Sent DAP2 Dataset HTML Form page.");
}
} |
package com.angcyo.uiview.container;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.view.ViewCompat;
import android.support.v4.widget.ViewDragHelper;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowInsets;
import android.view.animation.Animation;
import android.view.inputmethod.InputMethodManager;
import com.angcyo.library.utils.L;
import com.angcyo.uiview.R;
import com.angcyo.uiview.RApplication;
import com.angcyo.uiview.RCrashHandler;
import com.angcyo.uiview.Root;
import com.angcyo.uiview.base.UILayoutActivity;
import com.angcyo.uiview.model.ViewPattern;
import com.angcyo.uiview.resources.AnimUtil;
import com.angcyo.uiview.rsen.RGestureDetector;
import com.angcyo.uiview.skin.ISkin;
import com.angcyo.uiview.view.ILifecycle;
import com.angcyo.uiview.view.IView;
import com.angcyo.uiview.view.UIIViewImpl;
import com.angcyo.uiview.widget.viewpager.UIViewPager;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.Stack;
import static com.angcyo.uiview.view.UIIViewImpl.DEFAULT_ANIM_TIME;
public class UILayoutImpl extends SwipeBackLayout implements ILayout<UIParam>, UIViewPager.OnPagerShowListener {
private static final String TAG = "UILayoutImpl";
public static String LAYOUT_INFO = "";
/**
* View
*/
protected Stack<ViewPattern> mAttachViews = new Stack<>();
/**
* View
*/
protected ViewPattern mLastShowViewPattern;
protected boolean isAttachedToWindow = false;
protected UILayoutActivity mLayoutActivity;
private boolean isFinishing = false;
private boolean isStarting = false;
Application.ActivityLifecycleCallbacks mCallbacks = new Application.ActivityLifecycleCallbacks() {
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
L.w("call: onActivityCreated([activity, savedInstanceState])-> " + activity.getClass().getSimpleName());
}
@Override
public void onActivityStarted(Activity activity) {
L.w("call: onActivityStarted([activity])-> " + activity.getClass().getSimpleName());
if (activity == mLayoutActivity) {
if (mLastShowViewPattern != null &&
!mLastShowViewPattern.mIView.haveParentILayout() /*&&
mLastShowViewPattern.mView.getVisibility() != VISIBLE*/) {
viewShow(mLastShowViewPattern, null);
}
}
}
@Override
public void onActivityResumed(Activity activity) {
L.w("call: onActivityResumed([activity])-> " + activity.getClass().getSimpleName());
// if (activity == mLayoutActivity) {
// viewShow(mLastShowViewPattern, null);
}
@Override
public void onActivityPaused(Activity activity) {
L.w("call: onActivityPaused([activity])-> " + activity.getClass().getSimpleName());
// if (activity == mLayoutActivity) {
// viewHide(mLastShowViewPattern);
}
@Override
public void onActivityStopped(Activity activity) {
L.w("call: onActivityStopped([activity])-> " + activity.getClass().getSimpleName());
if (activity == mLayoutActivity) {
if (mLastShowViewPattern != null &&
!mLastShowViewPattern.mIView.haveParentILayout() /*&&
mLastShowViewPattern.mView.getVisibility() == VISIBLE*/) {
viewHide(mLastShowViewPattern);
}
}
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
}
@Override
public void onActivityDestroyed(Activity activity) {
if (activity == mLayoutActivity) {
while (!mAttachViews.empty()) {
try {
ViewPattern pattern = mAttachViews.pop();
pattern.interrupt = true;
pattern.isAnimToEnd = true;
pattern.mIView.onViewHide();
pattern.mIView.onViewUnload();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
};
private boolean isBackPress = false;
private ArrayList<IWindowInsetsListener> mIWindowInsetsListeners;
private ArrayList<OnIViewChangedListener> mOnIViewChangedListeners = new ArrayList<>();
private int[] mInsets = new int[4];
/**
* , , size
*/
private boolean lockHeight = false;
private float mTranslationOffsetX;
/**
* Runnable
*/
private int runnableCount = 0;
/**
* View,
*/
private boolean enableRootSwipe = false;
private boolean isSwipeDrag = false;
/**
* , ,onLayout
*/
private boolean isWantSwipeBack = false;
/**
* IView
*/
private Set<IView> interruptSet;
private boolean needDragClose = false;
/**
* ILayout, IView
*/
private ILayout mChildILayout;
public UILayoutImpl(Context context) {
super(context);
initLayout();
}
public UILayoutImpl(Context context, IView iView) {
super(context);
initLayout();
UIParam uiParam = new UIParam(false, false);
final ViewPattern newViewPattern = startIViewInternal(iView, uiParam);
startIViewAnim(mLastShowViewPattern, newViewPattern, uiParam, false);
}
public UILayoutImpl(Context context, AttributeSet attrs) {
super(context, attrs);
initLayout();
}
public UILayoutImpl(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initLayout();
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public UILayoutImpl(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
initLayout();
}
/**
* inflate, , , RootView.
*/
public static View safeAssignView(final View parentView, final View childView) {
if (parentView == childView) {
if (parentView instanceof ViewGroup) {
final ViewGroup viewGroup = (ViewGroup) parentView;
return viewGroup.getChildAt(viewGroup.getChildCount() - 1);
}
return childView;
} else {
return childView;
}
}
public static void saveToSDCard(String data) {
try {
String saveFolder = Environment.getExternalStorageDirectory().getAbsoluteFile() +
File.separator + Root.APP_FOLDER + File.separator + "log";
File folder = new File(saveFolder);
if (!folder.exists()) {
if (!folder.mkdirs()) {
return;
}
}
String dataTime = RCrashHandler.getDataTime("yyyy-MM-dd_HH-mm-ss-SSS");
File file = new File(saveFolder, /*dataTime + */"ILayout.log");
boolean append = true;
if (file.length() > 1024 * 1024 * 10 /*10MB*/) {
append = false;
}
PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(file, append)));
pw.println(dataTime);
pw.println(data);
pw.println();
pw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static List<Class<? extends IView>> getIViewList(Class<? extends IView>... iViews) {
return Arrays.asList(iViews);
}
@Override
public void onLastViewReShow(Bundle bundle) {
if (mLastShowViewPattern != null) {
mLastShowViewPattern.mView.setVisibility(VISIBLE);
mLastShowViewPattern.mIView.onViewReShow(bundle);
}
}
@Override
public void onLastViewShow(Bundle bundle) {
viewShow(mLastShowViewPattern, bundle);
}
@Override
public void onLastViewHide() {
viewHide(mLastShowViewPattern, false);
}
@Override
protected boolean canTryCaptureView(View child) {
if (isBackPress || mLastShowViewPattern == null ||
mLastShowViewPattern.isAnimToStart || isFinishing ||
mViewDragState != ViewDragHelper.STATE_IDLE ||
needDragClose) {
return false;
}
if (getAttachViewSize() > 1) {
if (/*!mLastShowViewPattern.mIView.isDialog()//
&&*/ mLastShowViewPattern.mIView.canTryCaptureView()//
&& mLastShowViewPattern.mView == child) {
hideSoftInput();
return true;
} else {
return false;
}
} else if (enableRootSwipe) {
hideSoftInput();
return true;
}
return false;
}
public void setEnableRootSwipe(boolean enableRootSwipe) {
this.enableRootSwipe = enableRootSwipe;
}
private void initLayout() {
if (!isInEditMode()) {
mLayoutActivity = (UILayoutActivity) getContext();
}
interruptSet = new HashSet<>();
setTag(TAG);
//setPadding(-2, 0, -2, 0);
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
if (!isInEditMode()) {
mLayoutActivity.getApplication().registerActivityLifecycleCallbacks(mCallbacks);
}
setFocusable(true);
setFocusableInTouchMode(true);
post(new Runnable() {
@Override
public void run() {
isAttachedToWindow = true;
loadViewInternal();
}
});
}
@Override
protected void
onDetachedFromWindow() {
super.onDetachedFromWindow();
mLayoutActivity.getApplication().unregisterActivityLifecycleCallbacks(mCallbacks);
isAttachedToWindow = false;
unloadViewInternal();
/* if (mIWindowInsetsListeners != null) {
mIWindowInsetsListeners.clear();
}*/
//mOnIViewChangedListeners.clear();
//interruptSet.clear();
//mChildILayout = null;
//mLayoutActivity = null;
}
/**
* IView
*/
protected void unloadViewInternal() {
for (; !mAttachViews.isEmpty(); ) {
final ViewPattern viewPattern = mAttachViews.pop();
viewHide(viewPattern);
viewPattern.mIView.onViewUnload();
try {
removeView(viewPattern.mView);
} catch (Exception e) {
e.printStackTrace();
} finally {
viewPattern.mIView.release();
viewPattern.clear();
}
}
}
@Override
public void startIView(final IView iView, final UIParam param) {
String log = this.getClass().getSimpleName() + " :" + iView.getClass().getSimpleName();
L.i(log);
saveToSDCard(log);
iView.onAttachedToILayout(this);
if (checkInterruptAndRemove(iView)) return;
runnableCount++;
final Runnable endRunnable = new Runnable() {
@Override
public void run() {
startInner(iView, param);
runnableCount
}
};
if (isFinishing || (mLastShowViewPattern != null
&& mLastShowViewPattern.mIView.isDialog()
&& !iView.showOnDialog())) {
//,IView, iView
runnableCount
postDelayed(new Runnable() {
@Override
public void run() {
isFinishing = false;
startIView(iView, param);
}
}, UIIViewImpl.DEFAULT_ANIM_TIME);
} else {
if (param.mAsync) {
post(endRunnable);
} else {
endRunnable.run();
}
}
}
private boolean checkInterrupt(IView iView) {
if (interruptSet.contains(iView)) {
//interruptSet.remove(iView);
L.i(":" + iView.getClass().getSimpleName() + "
return true;
}
return false;
}
private boolean checkInterruptAndRemove(IView iView) {
if (interruptSet.contains(iView)) {
interruptSet.remove(iView);
L.i(":" + iView.getClass().getSimpleName() + "
return true;
}
return false;
}
private void startInner(final IView iView, final UIParam param) {
if (!isAttachedToWindow) {
post(new Runnable() {
@Override
public void run() {
startInner(iView, param);
}
});
return;
}
if (isSwipeDrag()) {
restoreCaptureView();
}
if (checkInterruptAndRemove(iView)) return;
final ViewPattern oldViewPattern = getLastViewPattern();
isStarting = true;
if (param.start_mode == UIParam.SINGLE_TOP) {
if (oldViewPattern != null && oldViewPattern.mIView == iView) {
//, onViewShow
oldViewPattern.mIView.onViewShow(param.getBundle());
isStarting = false;
} else {
ViewPattern viewPatternByIView = findViewPatternByClass(iView.getClass());
if (viewPatternByIView == null) {
//IView
final ViewPattern newViewPattern = startIViewInternal(iView, param);
// startIViewAnim(oldViewPattern, newViewPattern, param);
viewPatternByIView = newViewPattern;
startIViewAnim(oldViewPattern, viewPatternByIView, param, false);
} else {
//IView ,
// bottomViewFinish(oldViewPattern, viewPatternByIView, param);
// topViewStart(viewPatternByIView, param);
mAttachViews.remove(viewPatternByIView);
mAttachViews.push(viewPatternByIView);
startIViewAnim(oldViewPattern, viewPatternByIView, param, true);
}
}
} else {
final ViewPattern newViewPattern = startIViewInternal(iView, param);
startIViewAnim(oldViewPattern, newViewPattern, param, false);
}
}
@Override
public void startIView(IView iView) {
startIView(iView, new UIParam());
}
private ViewPattern startIViewInternal(final IView iView, UIParam param) {
hideSoftInput();
iView.onAttachedToILayout(this);
//1:inflateContentView, IViewRootLayout
View rawView = loadViewInternal(iView, param);
//2:loadContentView
iView.loadContentView(rawView);
final ViewPattern newViewPattern = new ViewPattern(iView, rawView);
mAttachViews.push(newViewPattern);
for (OnIViewChangedListener listener : mOnIViewChangedListeners) {
listener.onIViewAdd(this, newViewPattern);
}
return newViewPattern;
}
/**
* [add] 2017-1-11
*/
private ViewPattern startIViewInternal(final ViewPattern viewPattern) {
hideSoftInput();
IView iView = viewPattern.mIView;
iView.onAttachedToILayout(this);
//1:inflateContentView, IViewRootLayout
View rawView = loadViewInternal(iView, null);
//2:loadContentView
iView.loadContentView(rawView);
viewPattern.setView(rawView);
mAttachViews.push(viewPattern);
for (OnIViewChangedListener listener : mOnIViewChangedListeners) {
listener.onIViewAdd(this, viewPattern);
}
return viewPattern;
}
/**
* IView
*/
protected void loadViewInternal() {
ViewPattern lastViewPattern = null;
for (ViewPattern viewPattern : mAttachViews) {
if (lastViewPattern != null) {
viewHide(lastViewPattern);
}
lastViewPattern = viewPattern;
lastViewPattern.mIView.onViewLoad();
}
if (lastViewPattern != null) {
viewShow(lastViewPattern, null);
}
mLastShowViewPattern = lastViewPattern;
}
/**
* IView
*/
private View loadViewInternal(IView iView, UIParam uiParam) {
//IViewinflateContentView,(inflateContentViewView)
//loadContentView,View.(, ButterKnife)
final View view = iView.inflateContentView(mLayoutActivity, this, this, LayoutInflater.from(mLayoutActivity));
View rawView;
//RootView, 2IView, id
if (this == view) {
rawView = getChildAt(getChildCount() - 1);
} else {
rawView = view;
}
iView.onViewCreate(rawView);
iView.onViewCreate(rawView, uiParam);
L.e("call: loadViewInternal()-> :" + iView.getClass().getSimpleName());
return rawView;
}
@Override
public void finishIView(final View view, final boolean needAnim) {
if (view == null) {
return;
}
final ViewPattern viewPatternByView = findViewPatternByView(view);
if (viewPatternByView == null) {
// post(new Runnable() {
// @Override
// public void run() {
// finishIView(view, needAnim);
return;
}
finishIView(viewPatternByView.mIView, new UIParam(needAnim, false, false));
}
/**
* @param param isQuiet true, , {@link IView#onViewShow()}
*/
private void finishIViewInner(final ViewPattern viewPattern, final UIParam param) {
isFinishing = true;
if (viewPattern == null || viewPattern.isAnimToEnd) {
finishEnd();
return;
}
if (isSwipeDrag()) {
restoreCaptureView();
}
viewPattern.mView.setEnabled(false);
String log = this.getClass().getSimpleName() + " 2:" + viewPattern.toString() + " isFinishing:" + isFinishing;
L.i(log);
saveToSDCard(log);
ViewPattern lastViewPattern = findLastShowViewPattern(viewPattern);
if (!viewPattern.interrupt) {
if (viewPattern.isAnimToStart || isFinishing) {
post(new Runnable() {
@Override
public void run() {
finishIViewInner(viewPattern, param);
}
});
return;
}
}
if (param.isSwipeBack) {
} else {
if (viewPattern.mIView.isDialog() &&
!viewPattern.mIView.canCancel()) {
finishEnd();
return;
}
}
boolean isOnTop = viewPattern == mLastShowViewPattern;
// if (!param.isSwipeBack && !viewPattern.mIView.onBackPressed()) {
// isFinishing = false;
// return;
topViewFinish(lastViewPattern, viewPattern, param);
if (isOnTop) {
bottomViewStart(lastViewPattern, viewPattern, param.mAnim, param.isQuiet);
} else {
//IView,
}
// if (param.mAnim) {
// viewPattern.isAnimToEnd = true;
// //startViewPatternAnim(viewPattern, lastViewPattern, true, true);
// //startViewPatternAnim(viewPattern, lastViewPattern, false, false);
// topViewFinish(viewPattern, true);
// bottomViewStart(lastViewPattern, viewPattern, param.mAnim, param.isQuiet);
// } else {
// if (lastViewPattern != null) {
// if (!param.isQuiet) {
// viewShow(lastViewPattern, null);
// if (lastViewPattern.mView instanceof ILifecycle) {
// ((ILifecycle) lastViewPattern.mView).onLifeViewShow();
// removeViewPattern(viewPattern);
//mLastShowViewPattern = lastViewPattern;//top view remove ,
}
@Override
public void finishIView(Class<?> clz) {
ViewPattern pattern = findViewPatternByClass(clz);
if (pattern != null) {
pattern.interrupt = true;
finishIViewInner(pattern, new UIParam(false, true, true));
}
}
@Override
public void finishIView(View view) {
finishIView(view, true);
}
@Override
public void finishIView(IView iview) {
finishIView(iview, true);
}
@Override
public void finishIView(IView iview, boolean needAnim) {
finishIView(iview, needAnim, false);
}
@Override
public void finishIView(IView iview, boolean needAnim, boolean quiet) {
finishIView(iview, new UIParam(needAnim, false, quiet));
}
@Override
public void finishIView(final IView iview, final UIParam param) {
finishIView(iview, param, true);
}
protected void finishIView(final IView iview, final UIParam param, boolean checkInterrupt) {
if (iview == null) {
finishEnd();
return;
}
final ViewPattern viewPattern = findViewPatternByIView(iview);
if (viewPattern == null) {
interruptSet.add(iview);
}
if (viewPattern == null || viewPattern.mIView == null) {
finishEnd();
return;
}
viewPattern.mView.setEnabled(false);
viewPattern.interrupt = true;
if (checkInterrupt && checkInterrupt(iview)) {
String log = this.getClass().getSimpleName() + " :" + iview.getClass().getSimpleName();
L.i(log);
saveToSDCard(log);
return;
} else {
String log = this.getClass().getSimpleName() + " /:" + iview.getClass().getSimpleName();
L.i(log);
saveToSDCard(log);
if (mLastShowViewPattern != null &&
mLastShowViewPattern != viewPattern &&
mLastShowViewPattern.mIView.isDialog()) {
L.i(":" + mLastShowViewPattern.mIView.getClass().getSimpleName() + " ");
postDelayed(new Runnable() {
@Override
public void run() {
finishIView(iview, param, false);
}
}, DEFAULT_ANIM_TIME);
return;
}
final Runnable endRunnable = new Runnable() {
@Override
public void run() {
interruptSet.add(iview);
finishIViewInner(viewPattern, param);
}
};
if (param.mAsync) {
post(endRunnable);
return;
}
endRunnable.run();
}
}
void finishEnd() {
needDragClose = false;
isBackPress = false;
isFinishing = false;
isSwipeDrag = false;
isStarting = false;
}
@Override
public void showIView(View view) {
showIView(view, true);
}
@Override
public void showIView(final View view, final boolean needAnim) {
showIView(view, new UIParam(needAnim));
}
@Override
public void showIView(final View view, final UIParam param) {
if (view == null) {
return;
}
post(new Runnable() {
@Override
public void run() {
final ViewPattern viewPattern = findViewPatternByView(view);
showIViewInternal(viewPattern, param);
}
});
}
@Override
public void showIView(IView iview, boolean needAnim) {
showIView(iview, new UIParam(needAnim));
}
@Override
public void showIView(IView iview) {
showIView(iview, true);
}
@Override
public void showIView(final IView iview, final UIParam param) {
post(new Runnable() {
@Override
public void run() {
final ViewPattern viewPattern = findViewPatternByIView(iview);
showIViewInternal(viewPattern, param);
}
});
}
private void showIViewInternal(final ViewPattern viewPattern, final UIParam param) {
if (viewPattern == null) {
return;
}
if (isFinishing || !isAttachedToWindow) {
post(new Runnable() {
@Override
public void run() {
showIViewInternal(viewPattern, param);
}
});
return;
}
viewPattern.mView.setVisibility(VISIBLE);
viewPattern.mView.bringToFront();
if (viewPattern == mLastShowViewPattern) {
viewReShow(viewPattern, param == null ? null : param.getBundle());
return;
}
final ViewPattern lastShowViewPattern = mLastShowViewPattern;
mLastShowViewPattern = viewPattern;
mAttachViews.remove(viewPattern);
mAttachViews.push(viewPattern);
final Runnable endRunnable = new Runnable() {
@Override
public void run() {
viewShow(mLastShowViewPattern, param == null ? null : param.getBundle());
printLog();
}
};
isStarting = true;
if (mLastShowViewPattern.mIView.isDialog()) {
startDialogAnim(mLastShowViewPattern, param.mAnim ? mLastShowViewPattern.mIView.loadShowAnimation() : null, endRunnable);
} else {
if (lastShowViewPattern != null) {
safeStartAnim(lastShowViewPattern.mView, needAnim(param, false) ?
mLastShowViewPattern.mIView.loadOtherHideAnimation() : null, new Runnable() {
@Override
public void run() {
viewHide(lastShowViewPattern);
}
});
}
safeStartAnim(mLastShowViewPattern.mView, (param.needTransitionStartAnim ||
mLastShowViewPattern.mIView.needTransitionStartAnim() ||
needAnim(param, false)) ?
mLastShowViewPattern.mIView.loadShowAnimation() : null, endRunnable);
}
}
@Override
public void hideIView(final View view, final boolean needAnim) {
if (isFinishing) {
post(new Runnable() {
@Override
public void run() {
hideIView(view, needAnim);
}
});
return;
}
post(new Runnable() {
@Override
public void run() {
final ViewPattern viewPattern = findViewPatternByView(view);
final Runnable endRunnable = new Runnable() {
@Override
public void run() {
viewHide(viewPattern);
}
};
if (viewPattern.mIView.isDialog()) {
finishDialogAnim(viewPattern, needAnim ? viewPattern.mIView.loadHideAnimation() : null, endRunnable);
} else {
//, !!! View, ...
safeStartAnim(view, needAnim ? viewPattern.mIView.loadHideAnimation() : null, endRunnable);
}
}
});
}
@Override
public void hideIView(View view) {
hideIView(view, true);
}
@Override
public View getLayout() {
return this;
}
@Override
public boolean requestBackPressed() {
return requestBackPressed(new UIParam());
}
@Override
public boolean requestBackPressed(final UIParam param) {
if (isSwipeDrag) {
return false;
}
if (isBackPress) {
return false;
}
if (getAttachViewSize() <= 0) {
return true;
}
if (getAttachViewSize() == 1) {
if (mLastShowViewPattern == null) {
return true;
} else {
return mLastShowViewPattern.mIView.onBackPressed();
}
}
if (param.isSwipeBack) {
if (!mLastShowViewPattern.mIView.canSwipeBackPressed()) {
return false;
}
} else {
if (!mLastShowViewPattern.mIView.onBackPressed()) {
return false;
}
}
isBackPress = true;
finishIView(mLastShowViewPattern.mIView, param);
return false;
}
/**
* iView
*/
public int getAttachViewSize() {
return mAttachViews.size();
}
@Override
public void replaceIView(final IView iView, final UIParam param) {
if (iView == null) {
return;
}
iView.onAttachedToILayout(this);
if (isFinishing) {
post(new Runnable() {
@Override
public void run() {
replaceIView(iView, param);
}
});
return;
}
if (mLastShowViewPattern != null && mLastShowViewPattern.mIView.isDialog() &&
(!iView.isDialog() || !iView.showOnDialog())) {
L.i(":" + mLastShowViewPattern.mIView.getClass().getSimpleName() + " ");
postDelayed(new Runnable() {
@Override
public void run() {
replaceIView(iView, param);
}
}, DEFAULT_ANIM_TIME);
return;
}
runnableCount++;
final Runnable runnable = new Runnable() {
@Override
public void run() {
final ViewPattern oldViewPattern = getLastViewPattern();
final ViewPattern newViewPattern = startIViewInternal(iView, param);
newViewPattern.mIView.onViewLoad();
topViewStart(newViewPattern, param);
if (param.isReplaceIViewEmpty() || oldViewPattern.mIView == param.replaceIView) {
final Runnable endRunnable = new Runnable() {
@Override
public void run() {
removeViewPattern(oldViewPattern, param, null);
param.clear();
}
};
viewHide(oldViewPattern);
bottomViewRemove(oldViewPattern, newViewPattern, endRunnable, true, param);
}
mLastShowViewPattern = newViewPattern;
runnableCount
}
};
isStarting = true;
if (param.mAsync) {
post(runnable);
} else {
runnable.run();
}
}
@Override
public void replaceIView(IView iView) {
replaceIView(iView, new UIParam());
}
public ViewPattern getLastViewPattern() {
// if (mAttachViews.isEmpty()) {
// return null;
// return mAttachViews.lastElement();
return mLastShowViewPattern;
}
private void startIViewAnim(final ViewPattern oldViewPattern, final ViewPattern newViewPattern,
final UIParam param, boolean reLoad) {
// if (isAttachedToWindow) {
mLastShowViewPattern = newViewPattern;
if (!reLoad) {
newViewPattern.mIView.onViewLoad();
}
clearOldViewFocus(oldViewPattern);
//startViewPatternAnim(newViewPattern, oldViewPattern, false, true);
//startViewPatternAnim(newViewPattern, oldViewPattern, true, false);
bottomViewFinish(oldViewPattern, newViewPattern, param);//Bottom
topViewStart(newViewPattern, param);//Top
// } else {
// for (ViewPattern viewPattern : mAttachViews) {
// viewPattern.mView.setVisibility(INVISIBLE);
}
private void clearOldViewFocus(ViewPattern oldViewPattern) {
if (oldViewPattern != null) {
oldViewPattern.mView.clearFocus();
View focus = oldViewPattern.mView.findFocus();
if (focus != null) {
focus.clearFocus();
}
}
}
private void topViewStart(final ViewPattern topViewPattern, final UIParam param) {
final Animation animation = topViewPattern.mIView.loadStartAnimation();
if (animation != null) {
animation.setFillAfter(false);
}
final Runnable endRunnable = new Runnable() {
@Override
public void run() {
L.i(topViewPattern.mIView.getClass().getSimpleName() + " .");
viewShow(topViewPattern, param.getBundle());
topViewPattern.isAnimToStart = false;
isStarting = false;
printLog();
}
};
if (topViewPattern.mView instanceof ILifecycle) {
((ILifecycle) topViewPattern.mView).onLifeViewShow();
}
setIViewNeedLayout(topViewPattern.mView, true);
topViewPattern.mView.bringToFront();
topViewPattern.isAnimToStart = true;
topViewPattern.isAnimToEnd = false;
if (param.needTransitionStartAnim ||
topViewPattern.mIView.needTransitionStartAnim() ||
needAnim(param, topViewPattern.mIView.isDialog())) {
if (topViewPattern.mIView.isDialog()) {
//,View
startDialogAnim(topViewPattern, animation, endRunnable);
} else {
safeStartAnim(topViewPattern.mIView.getAnimView(), animation, endRunnable);
}
} else {
if (param.mAsync) {
post(endRunnable);
} else {
endRunnable.run();
}
}
}
private void topViewFinish(final ViewPattern bottomViewPattern, final ViewPattern topViewPattern, final UIParam param) {
final Animation animation = topViewPattern.mIView.loadFinishAnimation();
if (animation != null) {
animation.setFillAfter(true);//2017-9-1
}
final Runnable endRunnable = new Runnable() {
@Override
public void run() {
L.i(topViewPattern.mIView.getClass().getSimpleName() + " .");
topViewPattern.isAnimToEnd = false;
viewHide(topViewPattern);
removeViewPattern(topViewPattern, param, new Runnable() {
@Override
public void run() {
mLastShowViewPattern = bottomViewPattern;// 2017-1-16
}
});
finishEnd();
printLog();
}
};
if (topViewPattern.mView instanceof ILifecycle) {
((ILifecycle) topViewPattern.mView).onLifeViewHide();
}
if (!param.needTransitionExitAnim && !needAnim(param, topViewPattern.mIView.isDialog())) {
endRunnable.run();
return;
}
isFinishing = true;
topViewPattern.isAnimToEnd = true;
topViewPattern.isAnimToStart = false;
if (topViewPattern.mIView.isDialog()) {
//,View
finishDialogAnim(topViewPattern, animation, endRunnable);
} else {
safeStartAnim(topViewPattern.mIView.getAnimView(), animation, endRunnable, true);
}
}
private boolean needAnim(final UIParam param, boolean isDialog) {
if (isDialog) {
return param.mAnim;
}
return (!RApplication.isLowDevice && param.mAnim);
}
@Deprecated
private boolean needTransitionAnim(ViewPattern viewPattern, boolean isSwipeBack, boolean isExit) {
if (isSwipeBack) {
return false;
}
if (isExit) {
return viewPattern.mIView.needTransitionExitAnim();
} else {
return viewPattern.mIView.needTransitionStartAnim();
}
}
private void printLog() {
postDelayed(new Runnable() {
@Override
public void run() {
logLayoutInfo();
}
}, 16);
}
private void bottomViewStart(final ViewPattern bottomViewPattern, final ViewPattern topViewPattern,
boolean anim, final boolean quiet) {
if (bottomViewPattern == null) {
return;
}
final Runnable endRunnable = new Runnable() {
@Override
public void run() {
if (!quiet) {
viewShow(bottomViewPattern, null);
}
bottomViewPattern.mIView.onViewReShow(null);
finishEnd();
}
};
setIViewNeedLayout(bottomViewPattern.mView, true);
bottomViewPattern.mView.setVisibility(VISIBLE);
showChildLayoutLastView();
if (bottomViewPattern.mView instanceof ILifecycle) {
((ILifecycle) bottomViewPattern.mView).onLifeViewShow();
}
if (topViewPattern.mIView.isDialog()) {
} else {
if (RApplication.isLowDevice || !anim || quiet) {
endRunnable.run();
} else {
final Animation animation = topViewPattern.mIView.loadOtherEnterAnimation();
if (animation != null) {
animation.setFillAfter(false);
}
safeStartAnim(bottomViewPattern.mIView.getAnimView(), animation, endRunnable);
}
}
}
private void bottomViewFinish(final ViewPattern bottomViewPattern,
final ViewPattern topViewPattern,
final UIParam param) {
final Runnable endRunnable = new Runnable() {
@Override
public void run() {
viewHide(bottomViewPattern, param.hideLastIView);
finishEnd();
}
};
bottomViewRemove(bottomViewPattern, topViewPattern, endRunnable, false, param);
}
private void bottomViewRemove(final ViewPattern bottomViewPattern,
final ViewPattern topViewPattern,
final Runnable endRunnable,
boolean isRemove,/*bottomViewPattern*/
final UIParam param) {
if (bottomViewPattern == null) {
return;
}
bottomViewPattern.isAnimToStart = false;
if (bottomViewPattern.mView instanceof ILifecycle) {
((ILifecycle) bottomViewPattern.mView).onLifeViewHide();
}
if (topViewPattern.mIView.isDialog() && !isRemove) {
//, IView
} else {
if (!RApplication.isLowDevice || param.mAnim) {
final Animation animation = topViewPattern.mIView.loadOtherExitAnimation();
if (animation != null) {
animation.setFillAfter(false);
}
safeStartAnim(bottomViewPattern.mIView.getAnimView(), animation, endRunnable, true);
} else {
endRunnable.run();
}
}
}
/**
* IViewonViewHide
*/
private void viewHide(final ViewPattern viewPattern, boolean hide) {
if (viewPattern == null ||
viewPattern.mIView.getIViewShowState() == IView.IViewShowState.STATE_VIEW_HIDE) {
return;
}
saveToSDCard(viewPattern.mIView.getClass().getSimpleName() + " onViewHide()");
viewPattern.mIView.onViewHide();
if (hide && !viewPattern.mIView.isDialog()) {
viewPattern.mView.setVisibility(GONE);
}
}
private void viewHide(final ViewPattern viewPattern) {
viewHide(viewPattern, false);
}
/**
* IViewonViewShow
*/
private void viewShow(final ViewPattern viewPattern, final Bundle bundle) {
isStarting = false;
if (viewPattern == null ||
viewPattern.mIView.getIViewShowState() == IView.IViewShowState.STATE_VIEW_SHOW) {
return;
}
saveToSDCard(viewPattern.mIView.getClass().getSimpleName() + " onViewShow()" + bundle);
// viewPattern.mView.setVisibility(VISIBLE);
// viewPattern.mView.bringToFront();
viewPattern.mIView.onViewShow(bundle);
}
/**
* IViewonViewReShow
*/
private void viewReShow(final ViewPattern viewPattern, final Bundle bundle) {
isStarting = false;
saveToSDCard(viewPattern.mIView.getClass().getSimpleName() + " onViewReShow()" + bundle);
viewPattern.mIView.onViewReShow(bundle);
}
/**
* , View
* , ;
* ,
* 2016-12-2 , 4
*/
@Deprecated
private void startViewPatternAnim(final ViewPattern newViewPattern, final ViewPattern lastViewPattern, boolean isStart, boolean withOther) {
if (newViewPattern == null) {
return;
}
if (withOther) {
if (newViewPattern.mIView.isDialog()) {
if (isStart) {
if (lastViewPattern != null) {
lastViewPattern.mIView.onViewShow(null);
}
} else {
if (lastViewPattern != null) {
lastViewPattern.mIView.onViewHide();
}
}
} else {
if (isStart) {
//View, View
final Animation animation = newViewPattern.mIView.loadOtherEnterAnimation();
safeStartAnim(lastViewPattern.mView, animation, new Runnable() {
@Override
public void run() {
lastViewPattern.mIView.onViewShow(null);
if (lastViewPattern.mView instanceof ILifecycle) {
((ILifecycle) lastViewPattern.mView).onLifeViewShow();
}
}
});
} else if (lastViewPattern != null) {
//View, View
final Animation animation = newViewPattern.mIView.loadOtherExitAnimation();
safeStartAnim(lastViewPattern.mView, animation, new Runnable() {
@Override
public void run() {
lastViewPattern.mIView.onViewHide();
if (lastViewPattern.mView instanceof ILifecycle) {
((ILifecycle) lastViewPattern.mView).onLifeViewHide();
}
}
});
}
}
} else {
if (newViewPattern.mIView.isDialog()) {
if (isStart) {
//,View
startDialogAnim(newViewPattern, newViewPattern.mIView.loadStartAnimation(), new Runnable() {
@Override
public void run() {
newViewPattern.mIView.onViewShow(null);
}
});
} else {
//finish View
finishDialogAnim(newViewPattern, newViewPattern.mIView.loadFinishAnimation(), new Runnable() {
@Override
public void run() {
removeViewPattern(newViewPattern, null, null);
}
});
}
} else {
if (isStart) {
//View
final Animation animation = newViewPattern.mIView.loadStartAnimation();
safeStartAnim(newViewPattern.mView, animation, new Runnable() {
@Override
public void run() {
newViewPattern.mIView.onViewShow(null);
}
});
} else {
//finish View
final Animation animation = newViewPattern.mIView.loadFinishAnimation();
safeStartAnim(newViewPattern.mView, animation, new Runnable() {
@Override
public void run() {
removeViewPattern(newViewPattern, null, null);
}
});
}
}
}
}
private void startDialogAnim(final ViewPattern dialogPattern, final Animation animation, final Runnable endRunnable) {
//,View
if (dialogPattern.mIView.isDimBehind()) {
AnimUtil.startArgb(dialogPattern.mIView.getDialogDimView(),
Color.TRANSPARENT, dialogPattern.mIView.getDimColor(), DEFAULT_ANIM_TIME);
}
if (dialogPattern.mIView.canTouchOnOutside()) {
dialogPattern.mView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
L.i("-> " + dialogPattern.mIView.getClass().getSimpleName());
if (dialogPattern.mIView.canCanceledOnOutside()) {
finishIView(dialogPattern.mView);
}
}
});
}
if (dialogPattern.mIView.canDoubleCancel()) {
RGestureDetector.onDoubleTap(dialogPattern.mView, new RGestureDetector.OnDoubleTapListener() {
@Override
public void onDoubleTap() {
L.i("-> " + dialogPattern.mIView.getClass().getSimpleName());
if (dialogPattern.mIView.canCanceledOnOutside()) {
finishIView(dialogPattern.mView);
}
}
});
}
safeStartAnim(dialogPattern.mIView.getAnimView(), animation, endRunnable);
}
private void finishDialogAnim(final ViewPattern dialogPattern, final Animation animation, final Runnable end) {
if (dialogPattern.mIView.isDimBehind()) {
AnimUtil.startArgb(dialogPattern.mIView.getDialogDimView(),
dialogPattern.mIView.getDimColor(), Color.TRANSPARENT, DEFAULT_ANIM_TIME);
}
final View animView = dialogPattern.mIView.getAnimView();
final Runnable endRunnable = new Runnable() {
@Override
public void run() {
dialogPattern.mView.setAlpha(0);
dialogPattern.mView.setVisibility(INVISIBLE);
end.run();
}
};
safeStartAnim(animView, animation, endRunnable, true);
}
private boolean safeStartAnim(final View view, final Animation animation,
final Runnable endRunnable) {
return safeStartAnim(view, animation, endRunnable, false);
}
private boolean safeStartAnim(final View view, final Animation animation,
final Runnable endRunnable, boolean isFinish) {
if (view == null) {
if (endRunnable != null) {
endRunnable.run();
}
return false;
}
if (animation == null) {
if (endRunnable != null) {
endRunnable.run();
}
return false;
}
animation.setAnimationListener(new AnimRunnable(view, endRunnable, isFinish));
view.startAnimation(animation);
return true;
}
public ViewPattern findViewPatternByView(View view) {
for (ViewPattern viewPattern : mAttachViews) {
if (viewPattern.mView == view) {
return viewPattern;
}
}
return null;
}
public ViewPattern findViewPatternByIView(IView iview) {
for (ViewPattern viewPattern : mAttachViews) {
// if (TextUtils.equals(viewPattern.mIView.getClass().getSimpleName(), iview.getClass().getSimpleName())) {
// return viewPattern;
if (viewPattern.mIView == iview) {
return viewPattern;
}
}
return null;
}
public ViewPattern findViewPatternByClass(Class<?> clz) {
for (ViewPattern viewPattern : mAttachViews) {
if (isViewPatternEquals(clz, viewPattern)) {
return viewPattern;
}
}
return null;
}
/**
* ViewPattern
*/
private boolean isViewPatternEquals(Class<?> clz, ViewPattern viewPattern) {
return TextUtils.equals(viewPattern.mIView.getClass().getSimpleName(), clz.getSimpleName());
}
public ViewPattern findLastShowViewPattern() {
return findViewPattern(getAttachViewSize() - 2);
}
public ViewPattern findLastShowViewPattern(final ViewPattern anchor) {
if (anchor == mLastShowViewPattern) {
return findViewPattern(getAttachViewSize() - 2);
} else {
return mLastShowViewPattern;
}
}
public ViewPattern findLastViewPattern() {
return findViewPattern(getAttachViewSize() - 1);
}
public ViewPattern findViewPattern(int position) {
if (getAttachViewSize() > position && position >= 0) {
return mAttachViews.get(position);
}
return null;
}
public void removeViewPattern(final ViewPattern viewPattern, final UIParam param, final Runnable runnable) {
hideSoftInput();
final View view = viewPattern.mView;
//ViewCompat.setAlpha(view, 0);
viewPattern.mIView.onViewUnload();
view.setEnabled(false);
ViewCompat.setAlpha(view, 0);
//view.setVisibility(GONE);
post(new Runnable() {
@Override
public void run() {
try {
//UI.setView(view, 0, 0);
mAttachViews.remove(viewPattern);
try {
removeView(view);
} catch (Exception e) {
}
isFinishing = false;
isBackPress = false;
viewPattern.mIView.release();
interruptSet.remove(viewPattern.mIView);
if (runnable != null) {
runnable.run();
}
L.e("call: removeViewPattern()-> :" + viewPattern.mIView.getClass().getSimpleName());
} catch (Exception e) {
e.printStackTrace();
}
if (param != null && param.getUnloadRunnable() != null) {
if (param.mAsync) {
post(param.getUnloadRunnable());
} else {
param.getUnloadRunnable().run();
}
param.clear();
}
}
});
for (OnIViewChangedListener listener : mOnIViewChangedListeners) {
listener.onIViewRemove(this, viewPattern);
}
}
@Override
public void onShowInPager(final UIViewPager viewPager) {
if (mLastShowViewPattern == null) {
return;
}
if (runnableCount > 0) {
post(new Runnable() {
@Override
public void run() {
onShowInPager(viewPager);
}
});
return;
}
mLastShowViewPattern.mIView.onShowInPager(viewPager);
}
@Override
public void onHideInPager(final UIViewPager viewPager) {
if (mLastShowViewPattern == null) {
return;
}
if (runnableCount > 0) {
post(new Runnable() {
@Override
public void run() {
onShowInPager(viewPager);
}
});
return;
}
mLastShowViewPattern.mIView.onHideInPager(viewPager);
}
private boolean needDelay() {
if (!isAttachedToWindow) {
return true;
}
if (getAttachViewSize() > 0 && mLastShowViewPattern == null) {
return true;
}
return false;
}
@Override
public WindowInsets onApplyWindowInsets(WindowInsets insets) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
mInsets[0] = insets.getSystemWindowInsetLeft();
mInsets[1] = insets.getSystemWindowInsetTop();
mInsets[2] = insets.getSystemWindowInsetRight();
mInsets[3] = insets.getSystemWindowInsetBottom();
post(new Runnable() {
@Override
public void run() {
notifyListener();
}
});
return super.onApplyWindowInsets(insets.replaceSystemWindowInsets(insets.getSystemWindowInsetLeft(), 0,
insets.getSystemWindowInsetRight(), lockHeight ? 0 : insets.getSystemWindowInsetBottom()));
} else {
return super.onApplyWindowInsets(insets);
}
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
return super.dispatchTouchEvent(ev);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
int l = 0;
if (isWantSwipeBack /*&& !requestLayout*/) {
if (getChildCount() > 0) {
View childAt = getChildAt(getChildCount() - 1);
l = childAt.getLeft();
}
}
// super.onLayout(changed, left, top, right, bottom);
int count = getChildCount();
for (int i = 0; i < count; i++) {
View childAt = getChildAt(i);
// if (i == count - 1 || i == count - 2) {
childAt.layout(0, 0, right, bottom);
if (childAt.getMeasuredHeight() == getMeasuredHeight() &&
childAt.getMeasuredWidth() == getMeasuredWidth()) {
setIViewNeedLayout(childAt, true);
} else {
setIViewNeedLayout(childAt, false);
}
// } else {
// childAt.setTag(R.id.tag_layout, "false");
}
// for (int i = 0; i < getChildCount(); i++) {
// View childAt = getChildAt(i);
// childAt.layout(0, 0, getMeasuredWidth(), getMeasuredHeight());
if (isWantSwipeBack /*&& !requestLayout*/) {
if (getChildCount() > 0) {
View childAt = getChildAt(getChildCount() - 1);
if (childAt.getVisibility() == VISIBLE && childAt.getAlpha() == 1) {
childAt.layout(l, childAt.getTop(),
l + childAt.getMeasuredWidth(), childAt.getTop() + childAt.getMeasuredHeight());
}
}
}
}
/**
* flag
*/
public void setIViewNeedLayout(View view, boolean layout) {
view.setTag(R.id.tag_layout, layout ? "false" : "true");
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//of java
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
// int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
// int heightMode = MeasureSpec.getMode(heightMeasureSpec);
//of kotlin
// var widthSize = MeasureSpec.getSize(widthMeasureSpec)
// val widthMode = MeasureSpec.getMode(widthMeasureSpec)
// var heightSize = MeasureSpec.getSize(heightMeasureSpec)
// val heightMode = MeasureSpec.getMode(heightMeasureSpec)
int count = getChildCount();
for (int i = 0; i < count; i++) {
View childAt = getChildAt(i);
ViewPattern viewPatternByView = findViewPatternByView(childAt);
int iViewSize = getIViewSize();
if (viewPatternByView == null) {
continue;
}
int indexFromIViews = getIndexFromIViews(viewPatternByView);
boolean needMeasure = false;
if (!"true".equalsIgnoreCase(String.valueOf(childAt.getTag(R.id.tag_layout)))) {
//layout
needMeasure = true;
} else if (viewPatternByView == mLastShowViewPattern) {
needMeasure = true;
} else if (i == count - 1 /*|| i == count - 2*/) {
//, view
needMeasure = true;
} else if (indexFromIViews >= 0 && (indexFromIViews == iViewSize - 1 /*|| indexFromIViews == iViewSize - 2*/)) {
//, iview
needMeasure = true;
} else {
if (viewPatternByView.mIView.needForceMeasure() ||
viewPatternByView.mIView.haveParentILayout() ||
viewPatternByView.mIView.haveChildILayout()) {
needMeasure = true;
} else {
IView iView = viewPatternByView.mIView;
for (int j = mAttachViews.size() - 1; j >= 0; j
ViewPattern viewPattern = mAttachViews.get(j);
if (viewPattern.mIView.isDialog() || viewPattern.mIView.showOnDialog()) {
needMeasure = true;
if (viewPattern.mIView == iView) {
break;
}
} else if (viewPattern.mIView == iView) {
break;
} else {
needMeasure = false;
break;
}
}
}
// if (!"true".equalsIgnoreCase(String.valueOf(childAt.getTag(R.id.tag_layout)))) {
//childAt.measure(exactlyMeasure(widthSize), exactlyMeasure(heightSize));
// } else {
// ViewPattern viewPatternByView = findViewPatternByView(childAt);
// if (viewPatternByView != null) {
// IView iView = viewPatternByView.mIView;
// if (iView != null && iView.haveChildILayout()) {
// childAt.measure(exactlyMeasure(widthSize), exactlyMeasure(heightSize));
}
//needMeasure = true;
if (needMeasure) {
childAt.measure(exactlyMeasure(widthSize), exactlyMeasure(heightSize));
}
// if (i == count - 1 || i == count - 2) {
// childAt.measure(exactlyMeasure(widthSize), exactlyMeasure(heightSize));
// if (i == count - 2) {
//// if (mAttachViews.get(i).mIView.showOnDialog() || mAttachViews.get(i).mIView.isDialog()) {
//// childAt.measure(MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY),
//// MeasureSpec.makeMeasureSpec(heightSize, MeasureSpec.EXACTLY));
//// } else
// if (childNeedMeasure(mAttachViews.get(i).mIView) || childNeedMeasure(childAt, widthSize, heightSize)) {
// childAt.measure(exactlyMeasure(widthSize), exactlyMeasure(heightSize));
}
setMeasuredDimension(widthSize, heightSize);
}
private int getIndexFromIViews(ViewPattern viewPattern) {
int result = -1;
for (int i = 0; i < mAttachViews.size(); i++) {
ViewPattern pattern = mAttachViews.get(i);
if (pattern == viewPattern) {
result = i;
break;
}
}
return result;
}
private boolean lastIsDialog() {
if (mLastShowViewPattern != null) {
if (mLastShowViewPattern.mIView.isDialog() ||
mLastShowViewPattern.mIView.showOnDialog()) {
return true;
}
}
return false;
}
private int exactlyMeasure(int size) {
return MeasureSpec.makeMeasureSpec(size, MeasureSpec.EXACTLY);
}
private boolean childNeedMeasure(IView iView) {
if (iView.getIViewShowState() == IView.IViewShowState.STATE_NORMAL ||
iView.getIViewShowState() == IView.IViewShowState.STATE_VIEW_SHOW) {
return true;
}
return false;
}
private boolean childNeedMeasure(View child, int viewWidth, int viewHeight) {
if (child == null) {
return false;
}
return child.getMeasuredHeight() != viewHeight || child.getMeasuredWidth() != viewWidth;
}
private void notifyListener() {
if (mIWindowInsetsListeners != null) {
for (IWindowInsetsListener listener : mIWindowInsetsListeners) {
listener.onWindowInsets(mInsets[0], mInsets[1], mInsets[2], mInsets[3]);
}
}
}
public UILayoutImpl addIWindowInsetsListener(IWindowInsetsListener listener) {
if (listener == null) {
return this;
}
if (mIWindowInsetsListeners == null) {
mIWindowInsetsListeners = new ArrayList<>();
}
this.mIWindowInsetsListeners.add(listener);
return this;
}
public UILayoutImpl removeIWindowInsetsListener(IWindowInsetsListener listener) {
if (listener == null || mIWindowInsetsListeners == null) {
return this;
}
this.mIWindowInsetsListeners.remove(listener);
return this;
}
public UILayoutImpl addOnIViewChangeListener(OnIViewChangedListener listener) {
if (listener == null) {
return this;
}
this.mOnIViewChangedListeners.add(listener);
return this;
}
public UILayoutImpl removeOnIViewChangeListener(OnIViewChangedListener listener) {
if (listener == null || mOnIViewChangedListeners == null) {
return this;
}
this.mOnIViewChangedListeners.remove(listener);
return this;
}
public void setLockHeight(boolean lockHeight) {
this.lockHeight = lockHeight;
}
public int getInsersBottom() {
return mInsets[3];
}
public void hideSoftInput() {
if (isSoftKeyboardShow()) {
InputMethodManager manager = (InputMethodManager) getContext()
.getSystemService(Context.INPUT_METHOD_SERVICE);
manager.hideSoftInputFromWindow(getWindowToken(), 0);
}
}
private boolean isSoftKeyboardShow() {
int screenHeight = getResources().getDisplayMetrics().heightPixels;
int keyboardHeight = getSoftKeyboardHeight();
return screenHeight != keyboardHeight && keyboardHeight > 100;
}
private int getSoftKeyboardHeight() {
int screenHeight = getResources().getDisplayMetrics().heightPixels;
Rect rect = new Rect();
getWindowVisibleDisplayFrame(rect);
int visibleBottom = rect.bottom;
return screenHeight - visibleBottom;
}
public void showSoftInput() {
InputMethodManager manager = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
manager.showSoftInputFromInputMethod(getWindowToken(), 0);
}
public void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
if (mLastShowViewPattern != null) {
if (mLastShowViewPattern.isAnimToEnd) {
post(new Runnable() {
@Override
public void run() {
onActivityResult(requestCode, resultCode, data);
}
});
} else {
mLastShowViewPattern.mIView.onActivityResult(requestCode, resultCode, data);
}
}
}
/**
* , IView
*/
public ViewPattern getViewPattern(int position) {
if (position < 0 || position >= getAttachViewSize()) {
return null;
}
return mAttachViews.get(position);
}
@Override
public ViewPattern getViewPatternAtLast(int lastCount) {
return getViewPattern(getAttachViewSize() - 1 - lastCount);
}
/**
* , IView
*/
public ViewPattern getViewPatternWithClass(Class<?> cls) {
for (ViewPattern pattern : mAttachViews) {
if (pattern.mIView.getClass().getSimpleName().equalsIgnoreCase(cls.getSimpleName())) {
return pattern;
}
}
return null;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
super.onTouchEvent(event);
return true;
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
if (isFinishing || isStarting) {
return true;
}
return super.onInterceptTouchEvent(ev);
}
@Override
public <IV extends IView> IV getIViewWith(Class<IV> cls) {
IView result = null;
for (ViewPattern pattern : mAttachViews) {
if (isViewPatternEquals(cls, pattern)) {
result = pattern.mIView;
break;
}
}
return (IV) result;
}
@Override
public void finishAll() {
finishAll(false);
}
@Override
public void finishAllWithKeep(List<Class<? extends IView>> keepList, boolean keepLast, final UIParam lastFinishParam) {
List<ViewPattern> needFinishPattern = new ArrayList<>();
//finishIView
for (ViewPattern pattern : mAttachViews) {
boolean keep = false;
for (Class cls : keepList) {
if (isViewPatternEquals(cls, pattern)) {
keep = true;
break;
}
}
if (!keep) {
if (keepLast && pattern == getLastViewPattern()) {
} else {
needFinishPattern.add(pattern);
}
}
}
for (ViewPattern pattern : needFinishPattern) {
if (pattern == getLastViewPattern() && lastFinishParam != null) {
//finishIViewInner(pattern, lastFinishParam);
finishIView(pattern.mIView, lastFinishParam);
} else {
finishIViewInner(pattern, new UIParam(false, false, true));
}
}
}
@Override
public void finishAll(boolean keepLast) {
while (!mAttachViews.empty()) {
ViewPattern pattern = mAttachViews.pop();
if (keepLast && pattern == getLastViewPattern()) {
return;
} else {
pattern.interrupt = true;
finishIViewInner(pattern, new UIParam(false, false, true));
}
}
}
@Override
public void finish() {
finishAll();
mLayoutActivity.onBackPressed();
}
@Override
public void onSkinChanged(ISkin skin) {
for (ViewPattern pattern : mAttachViews) {
pattern.mIView.onSkinChanged(skin);
}
}
@Override
protected void onRequestClose() {
super.onRequestClose();
translation(0);
if (enableRootSwipe && getIViewSize() == 1) {
mLayoutActivity.finish();
mLayoutActivity.overridePendingTransition(0, 0);
} else {
needDragClose = true;
mLastShowViewPattern.mView.setVisibility(GONE);
mLastShowViewPattern.mView.setAlpha(0f);
finishIView(mLastShowViewPattern.mIView, new UIParam(false, true, false));
}
printLog();
}
@Override
protected void onRequestOpened() {
super.onRequestOpened();
isSwipeDrag = false;
needDragClose = false;
translation(0);
// final ViewPattern viewPattern = findLastShowViewPattern(mLastShowViewPattern);
// if (viewPattern != null) {
// viewPattern.mView.setVisibility(GONE);
//hideChildLayoutLastView();
printLog();
}
@Override
protected void onSlideChange(float percent) {
super.onSlideChange(percent);
isSwipeDrag = true;
translation(percent);
}
@Override
protected void onStateIdle() {
super.onStateIdle();
isWantSwipeBack = false;
}
@Override
protected void onStateDragging() {
super.onStateDragging();
isWantSwipeBack = true;
isSwipeDrag = true;
final ViewPattern viewPattern = findLastShowViewPattern(mLastShowViewPattern);
if (viewPattern != null && !viewPattern.mIView.isDialog()) {
mTranslationOffsetX = getMeasuredWidth() * 0.3f;
viewPattern.mView.setVisibility(VISIBLE);
viewPattern.mView.setTranslationX(-mTranslationOffsetX);
}
showChildLayoutLastView();
}
/**
* child layout
*/
private void showChildLayoutLastView() {
if (!isChildILayoutEmpty()) {
ViewPattern patternAtLast = mChildILayout.getViewPatternAtLast(0);
if (patternAtLast != null) {
patternAtLast.mView.setVisibility(VISIBLE);
}
}
}
private boolean isChildILayoutEmpty() {
return mChildILayout == null || mChildILayout == this;
}
private void hideChildLayoutLastView() {
if (!isChildILayoutEmpty()) {
ViewPattern patternAtLast = mChildILayout.getViewPatternAtLast(0);
if (patternAtLast != null) {
patternAtLast.mView.setVisibility(GONE);
}
}
}
private void translation(float percent) {
final ViewPattern viewPattern = findLastShowViewPattern(mLastShowViewPattern);
if (viewPattern != null && !viewPattern.mIView.isDialog()) {
float tx = -mTranslationOffsetX * percent;
if (viewPattern.mView.getTranslationX() != tx) {
viewPattern.mView.setTranslationX(tx);
}
}
}
public void translationLastView(int x) {
if (mLastShowViewPattern != null) {
mLastShowViewPattern.mView.setTranslationX(x);
}
}
@Override
protected void dispatchDraw(Canvas canvas) {
try {
super.dispatchDraw(canvas);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* IView
*/
public int getIViewSize() {
if (mAttachViews == null || mAttachViews.isEmpty()) {
return 0;
}
return getAttachViewSize();
}
public boolean isSwipeDrag() {
return isSwipeDrag;
}
@Override
public void setChildILayout(ILayout childILayout) {
mChildILayout = childILayout;
}
public String logLayoutInfo() {
StringBuilder stringBuilder = new StringBuilder(this.getClass().getSimpleName() + " IViews:\n");
for (int i = 0; i < getAttachViewSize(); i++) {
ViewPattern viewPattern = mAttachViews.get(i);
stringBuilder.append(i);
stringBuilder.append("
stringBuilder.append(viewPattern.mIView.getClass().getSimpleName());
stringBuilder.append("");
int visibility = viewPattern.mView.getVisibility();
String vis;
if (visibility == View.GONE) {
vis = "GONE";
} else if (visibility == View.VISIBLE) {
vis = "VISIBLE";
} else if (visibility == View.INVISIBLE) {
vis = "INVISIBLE";
} else {
vis = "NONE";
}
stringBuilder.append(" visibility
stringBuilder.append(vis);
stringBuilder.append(" alpha
stringBuilder.append(viewPattern.mView.getAlpha());
stringBuilder.append(" W:");
stringBuilder.append(this.getMeasuredWidth());
stringBuilder.append("-");
stringBuilder.append(viewPattern.mView.getMeasuredWidth());
stringBuilder.append(" H:");
stringBuilder.append(this.getMeasuredHeight());
stringBuilder.append("-");
stringBuilder.append(viewPattern.mView.getMeasuredHeight());
stringBuilder.append(" R:");
stringBuilder.append(viewPattern.mView.getRight());
stringBuilder.append(" B:");
stringBuilder.append(viewPattern.mView.getBottom());
stringBuilder.append(" layout:");
stringBuilder.append(viewPattern.mView.getTag(R.id.tag_layout));
stringBuilder.append("\n");
}
LAYOUT_INFO = stringBuilder.toString();
L.e(LAYOUT_INFO);
saveToSDCard(LAYOUT_INFO);
return LAYOUT_INFO;
}
/**
* IView ,
*/
public interface OnIViewChangedListener {
void onIViewAdd(final UILayoutImpl uiLayout, final ViewPattern viewPattern);
void onIViewRemove(final UILayoutImpl uiLayout, final ViewPattern viewPattern);
}
static class AnimRunnable implements Animation.AnimationListener {
private Runnable mRunnable;
private View mView;
private boolean isFinish;
public AnimRunnable(View view, Runnable runnable, boolean isFinish) {
mRunnable = runnable;
mView = view;
this.isFinish = isFinish;
}
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
if (mRunnable != null) {
if (mView != null && !isFinish) {
mView.post(mRunnable);
} else {
mRunnable.run();
}
mRunnable = null;
}
if (mView != null) {
mView.clearAnimation();
mView = null;
}
}
@Override
public void onAnimationRepeat(Animation animation) {
}
}
} |
package org.adligo.aws_client;
import java.util.ArrayList;
import java.util.List;
import org.adligo.i.log.client.Log;
import org.adligo.i.log.client.LogFactory;
public class DefaultPollingDaemon implements Runnable, I_PollingDaemon {
private static final Log log = LogFactory.getLog(DefaultPollingDaemon.class);
private volatile List<I_PolledItem> items = new ArrayList<I_PolledItem>();
protected void start() {
Thread daemonThread = new Thread(this);
daemonThread.start();
}
@Override
public void run() {
while (items.size() >= 1) {
//prevent concurrent modification by making a copy
List<I_PolledItem> new_items = new ArrayList<I_PolledItem>();
new_items.addAll(items);
for (I_PolledItem item : new_items) {
item.poll();
}
try {
Thread.yield();
Thread.sleep(200);
} catch (InterruptedException e) {
log.error(e.getMessage(), e);
return;
}
}
}
@Override
public void addItem(I_PolledItem item) {
items.add(item);
}
@Override
public void removeItem(I_PolledItem item) {
items.remove(item);
}
} |
package org.broadinstitute.sting.utils;
import com.google.java.contract.Ensures;
import com.google.java.contract.Requires;
import net.sf.samtools.SAMRecord;
import org.broadinstitute.sting.gatk.GenomeAnalysisEngine;
import org.broadinstitute.sting.utils.exceptions.UserException;
import java.math.BigDecimal;
import java.util.*;
/**
* MathUtils is a static class (no instantiation allowed!) with some useful math methods.
*
* @author Kiran Garimella
*/
public class MathUtils {
/** Public constants - used for the Lanczos approximation to the factorial function
* (for the calculation of the binomial/multinomial probability in logspace)
* @param LANC_SEQ[] - an array holding the constants which correspond to the product
* of Chebyshev Polynomial coefficients, and points on the Gamma function (for interpolation)
* [see A Precision Approximation of the Gamma Function J. SIAM Numer. Anal. Ser. B, Vol. 1 1964. pp. 86-96]
* @param LANC_G - a value for the Lanczos approximation to the gamma function that works to
* high precision
*/
/**
* Private constructor. No instantiating this class!
*/
private MathUtils() {
}
// A fast implementation of the Math.round() method. This method does not perform
// under/overflow checking, so this shouldn't be used in the general case (but is fine
// if one is already make those checks before calling in to the rounding).
public static int fastRound(double d) {
return (d > 0) ? (int)(d + 0.5d) : (int)(d - 0.5d);
}
public static double approximateLog10SumLog10(double[] vals) {
final int maxElementIndex = MathUtils.maxElementIndex(vals);
double approxSum = vals[maxElementIndex];
if ( approxSum == Double.NEGATIVE_INFINITY )
return approxSum;
for ( int i = 0; i < vals.length; i++ ) {
if ( i == maxElementIndex || vals[i] == Double.NEGATIVE_INFINITY )
continue;
final double diff = approxSum - vals[i];
if ( diff < MathUtils.MAX_JACOBIAN_TOLERANCE ) {
// See notes from the 2-inout implementation below
final int ind = fastRound(diff / MathUtils.JACOBIAN_LOG_TABLE_STEP); // hard rounding
approxSum += MathUtils.jacobianLogTable[ind];
}
}
return approxSum;
}
public static double approximateLog10SumLog10(double small, double big) {
// make sure small is really the smaller value
if ( small > big ) {
final double t = big;
big = small;
small = t;
}
if ( small == Double.NEGATIVE_INFINITY || big == Double.NEGATIVE_INFINITY )
return big;
final double diff = big - small;
if ( diff >= MathUtils.MAX_JACOBIAN_TOLERANCE )
return big;
// OK, so |y-x| < tol: we use the following identity then:
// we need to compute log10(10^x + 10^y)
// By Jacobian logarithm identity, this is equal to
// max(x,y) + log10(1+10^-abs(x-y))
// we compute the second term as a table lookup with integer quantization
// we have pre-stored correction for 0,0.1,0.2,... 10.0
final int ind = fastRound(diff / MathUtils.JACOBIAN_LOG_TABLE_STEP); // hard rounding
return big + MathUtils.jacobianLogTable[ind];
}
public static double sum(Collection<Number> numbers) {
return sum(numbers, false);
}
public static double sum(Collection<Number> numbers, boolean ignoreNan) {
double sum = 0;
for (Number n : numbers) {
if (!ignoreNan || !Double.isNaN(n.doubleValue())) {
sum += n.doubleValue();
}
}
return sum;
}
public static int nonNanSize(Collection<Number> numbers) {
int size = 0;
for (Number n : numbers) {
size += Double.isNaN(n.doubleValue()) ? 0 : 1;
}
return size;
}
public static double average(Collection<Number> numbers, boolean ignoreNan) {
if (ignoreNan) {
return sum(numbers, true) / nonNanSize(numbers);
} else {
return sum(numbers, false) / nonNanSize(numbers);
}
}
public static double variance(Collection<Number> numbers, Number mean, boolean ignoreNan) {
double mn = mean.doubleValue();
double var = 0;
for (Number n : numbers) {
var += (!ignoreNan || !Double.isNaN(n.doubleValue())) ? (n.doubleValue() - mn) * (n.doubleValue() - mn) : 0;
}
if (ignoreNan) {
return var / (nonNanSize(numbers) - 1);
}
return var / (numbers.size() - 1);
}
public static double variance(Collection<Number> numbers, Number mean) {
return variance(numbers, mean, false);
}
public static double variance(Collection<Number> numbers, boolean ignoreNan) {
return variance(numbers, average(numbers, ignoreNan), ignoreNan);
}
public static double variance(Collection<Number> numbers) {
return variance(numbers, average(numbers, false), false);
}
public static double sum(double[] values) {
double s = 0.0;
for (double v : values) s += v;
return s;
}
/**
* Calculates the log10 cumulative sum of an array with log10 probabilities
*
* @param log10p the array with log10 probabilites
* @param upTo index in the array to calculate the cumsum up to
* @return the log10 of the cumulative sum
*/
public static double log10CumulativeSumLog10(double[] log10p, int upTo) {
return log10sumLog10(log10p, 0, upTo);
}
/**
* Converts a real space array of probabilities into a log10 array
*
* @param prRealSpace
* @return
*/
public static double[] toLog10(double[] prRealSpace) {
double[] log10s = new double[prRealSpace.length];
for (int i = 0; i < prRealSpace.length; i++)
log10s[i] = Math.log10(prRealSpace[i]);
return log10s;
}
public static double log10sumLog10(double[] log10p, int start) {
return log10sumLog10(log10p, start, log10p.length);
}
public static double log10sumLog10(double[] log10p, int start, int finish) {
double sum = 0.0;
double maxValue = Utils.findMaxEntry(log10p);
for (int i = start; i < finish; i++) {
sum += Math.pow(10.0, log10p[i] - maxValue);
}
return Math.log10(sum) + maxValue;
}
public static double sumDoubles(List<Double> values) {
double s = 0.0;
for (double v : values) s += v;
return s;
}
public static int sumIntegers(List<Integer> values) {
int s = 0;
for (int v : values) s += v;
return s;
}
public static double sumLog10(double[] log10values) {
return Math.pow(10.0, log10sumLog10(log10values));
// double s = 0.0;
// for ( double v : log10values) s += Math.pow(10.0, v);
// return s;
}
public static double log10sumLog10(double[] log10values) {
return log10sumLog10(log10values, 0);
}
public static boolean wellFormedDouble(double val) {
return !Double.isInfinite(val) && !Double.isNaN(val);
}
public static double bound(double value, double minBoundary, double maxBoundary) {
return Math.max(Math.min(value, maxBoundary), minBoundary);
}
public static boolean isBounded(double val, double lower, double upper) {
return val >= lower && val <= upper;
}
public static boolean isPositive(double val) {
return !isNegativeOrZero(val);
}
public static boolean isPositiveOrZero(double val) {
return isBounded(val, 0.0, Double.POSITIVE_INFINITY);
}
public static boolean isNegativeOrZero(double val) {
return isBounded(val, Double.NEGATIVE_INFINITY, 0.0);
}
public static boolean isNegative(double val) {
return !isPositiveOrZero(val);
}
/**
* Compares double values for equality (within 1e-6), or inequality.
*
* @param a the first double value
* @param b the second double value
* @return -1 if a is greater than b, 0 if a is equal to be within 1e-6, 1 if b is greater than a.
*/
public static byte compareDoubles(double a, double b) {
return compareDoubles(a, b, 1e-6);
}
/**
* Compares double values for equality (within epsilon), or inequality.
*
* @param a the first double value
* @param b the second double value
* @param epsilon the precision within which two double values will be considered equal
* @return -1 if a is greater than b, 0 if a is equal to be within epsilon, 1 if b is greater than a.
*/
public static byte compareDoubles(double a, double b, double epsilon) {
if (Math.abs(a - b) < epsilon) {
return 0;
}
if (a > b) {
return -1;
}
return 1;
}
/**
* Compares float values for equality (within 1e-6), or inequality.
*
* @param a the first float value
* @param b the second float value
* @return -1 if a is greater than b, 0 if a is equal to be within 1e-6, 1 if b is greater than a.
*/
public static byte compareFloats(float a, float b) {
return compareFloats(a, b, 1e-6f);
}
/**
* Compares float values for equality (within epsilon), or inequality.
*
* @param a the first float value
* @param b the second float value
* @param epsilon the precision within which two float values will be considered equal
* @return -1 if a is greater than b, 0 if a is equal to be within epsilon, 1 if b is greater than a.
*/
public static byte compareFloats(float a, float b, float epsilon) {
if (Math.abs(a - b) < epsilon) {
return 0;
}
if (a > b) {
return -1;
}
return 1;
}
public static double NormalDistribution(double mean, double sd, double x) {
double a = 1.0 / (sd * Math.sqrt(2.0 * Math.PI));
double b = Math.exp(-1.0 * (Math.pow(x - mean, 2.0) / (2.0 * sd * sd)));
return a * b;
}
public static double binomialCoefficient(int n, int k) {
return Math.pow(10, log10BinomialCoefficient(n, k));
}
/**
* Computes a binomial probability. This is computed using the formula
* <p/>
* B(k; n; p) = [ n! / ( k! (n - k)! ) ] (p^k)( (1-p)^k )
* <p/>
* where n is the number of trials, k is the number of successes, and p is the probability of success
*
* @param n number of Bernoulli trials
* @param k number of successes
* @param p probability of success
* @return the binomial probability of the specified configuration. Computes values down to about 1e-237.
*/
public static double binomialProbability(int n, int k, double p) {
return Math.pow(10, log10BinomialProbability(n, k, Math.log10(p)));
}
/**
* Performs the cumulative sum of binomial probabilities, where the probability calculation is done in log space.
*
* @param start - start of the cumulant sum (over hits)
* @param end - end of the cumulant sum (over hits)
* @param total - number of attempts for the number of hits
* @param probHit - probability of a successful hit
* @return - returns the cumulative probability
*/
public static double binomialCumulativeProbability(int start, int end, int total, double probHit) {
double cumProb = 0.0;
double prevProb;
BigDecimal probCache = BigDecimal.ZERO;
for (int hits = start; hits < end; hits++) {
prevProb = cumProb;
double probability = binomialProbability(total, hits, probHit);
cumProb += probability;
if (probability > 0 && cumProb - prevProb < probability / 2) { // loss of precision
probCache = probCache.add(new BigDecimal(prevProb));
cumProb = 0.0;
hits--; // repeat loop
// prevProb changes at start of loop
}
}
return probCache.add(new BigDecimal(cumProb)).doubleValue();
}
/**
* Computes a multinomial coefficient efficiently avoiding overflow even for large numbers.
* This is computed using the formula:
* <p/>
* M(x1,x2,...,xk; n) = [ n! / (x1! x2! ... xk!) ]
* <p/>
* where xi represents the number of times outcome i was observed, n is the number of total observations.
* In this implementation, the value of n is inferred as the sum over i of xi.
*
* @param k an int[] of counts, where each element represents the number of times a certain outcome was observed
* @return the multinomial of the specified configuration.
*/
public static double multinomialCoefficient(int[] k) {
int n = 0;
for (int xi : k) {
n += xi;
}
return Math.pow(10, log10MultinomialCoefficient(n, k));
}
/**
* Computes a multinomial probability efficiently avoiding overflow even for large numbers.
* This is computed using the formula:
* <p/>
* M(x1,x2,...,xk; n; p1,p2,...,pk) = [ n! / (x1! x2! ... xk!) ] (p1^x1)(p2^x2)(...)(pk^xk)
* <p/>
* where xi represents the number of times outcome i was observed, n is the number of total observations, and
* pi represents the probability of the i-th outcome to occur. In this implementation, the value of n is
* inferred as the sum over i of xi.
*
* @param k an int[] of counts, where each element represents the number of times a certain outcome was observed
* @param p a double[] of probabilities, where each element represents the probability a given outcome can occur
* @return the multinomial probability of the specified configuration.
*/
public static double multinomialProbability(int[] k, double[] p) {
if (p.length != k.length)
throw new UserException.BadArgumentValue("p and k", "Array of log10 probabilities must have the same size as the array of number of sucesses: " + p.length + ", " + k.length);
int n = 0;
double[] log10P = new double[p.length];
for (int i = 0; i < p.length; i++) {
log10P[i] = Math.log10(p[i]);
n += k[i];
}
return Math.pow(10, log10MultinomialProbability(n, k, log10P));
}
/**
* calculate the Root Mean Square of an array of integers
*
* @param x an byte[] of numbers
* @return the RMS of the specified numbers.
*/
public static double rms(byte[] x) {
if (x.length == 0)
return 0.0;
double rms = 0.0;
for (int i : x)
rms += i * i;
rms /= x.length;
return Math.sqrt(rms);
}
/**
* calculate the Root Mean Square of an array of integers
*
* @param x an int[] of numbers
* @return the RMS of the specified numbers.
*/
public static double rms(int[] x) {
if (x.length == 0)
return 0.0;
double rms = 0.0;
for (int i : x)
rms += i * i;
rms /= x.length;
return Math.sqrt(rms);
}
/**
* calculate the Root Mean Square of an array of doubles
*
* @param x a double[] of numbers
* @return the RMS of the specified numbers.
*/
public static double rms(Double[] x) {
if (x.length == 0)
return 0.0;
double rms = 0.0;
for (Double i : x)
rms += i * i;
rms /= x.length;
return Math.sqrt(rms);
}
public static double rms(Collection<Integer> l) {
if (l.size() == 0)
return 0.0;
double rms = 0.0;
for (int i : l)
rms += i * i;
rms /= l.size();
return Math.sqrt(rms);
}
public static double distanceSquared(final double[] x, final double[] y) {
double dist = 0.0;
for (int iii = 0; iii < x.length; iii++) {
dist += (x[iii] - y[iii]) * (x[iii] - y[iii]);
}
return dist;
}
public static double round(double num, int digits) {
double result = num * Math.pow(10.0, (double) digits);
result = Math.round(result);
result = result / Math.pow(10.0, (double) digits);
return result;
}
/**
* normalizes the log10-based array. ASSUMES THAT ALL ARRAY ENTRIES ARE <= 0 (<= 1 IN REAL-SPACE).
*
* @param array the array to be normalized
* @param takeLog10OfOutput if true, the output will be transformed back into log10 units
* @return a newly allocated array corresponding the normalized values in array, maybe log10 transformed
*/
public static double[] normalizeFromLog10(double[] array, boolean takeLog10OfOutput) {
return normalizeFromLog10(array, takeLog10OfOutput, false);
}
public static double[] normalizeFromLog10(double[] array, boolean takeLog10OfOutput, boolean keepInLogSpace) {
// for precision purposes, we need to add (or really subtract, since they're
// all negative) the largest value; also, we need to convert to normal-space.
double maxValue = Utils.findMaxEntry(array);
// we may decide to just normalize in log space with converting to linear space
if (keepInLogSpace) {
for (int i = 0; i < array.length; i++)
array[i] -= maxValue;
return array;
}
// default case: go to linear space
double[] normalized = new double[array.length];
for (int i = 0; i < array.length; i++)
normalized[i] = Math.pow(10, array[i] - maxValue);
// normalize
double sum = 0.0;
for (int i = 0; i < array.length; i++)
sum += normalized[i];
for (int i = 0; i < array.length; i++) {
double x = normalized[i] / sum;
if (takeLog10OfOutput) x = Math.log10(x);
normalized[i] = x;
}
return normalized;
}
public static double[] normalizeFromLog10(List<Double> array, boolean takeLog10OfOutput) {
double[] normalized = new double[array.size()];
// for precision purposes, we need to add (or really subtract, since they're
// all negative) the largest value; also, we need to convert to normal-space.
double maxValue = MathUtils.arrayMaxDouble(array);
for (int i = 0; i < array.size(); i++)
normalized[i] = Math.pow(10, array.get(i) - maxValue);
// normalize
double sum = 0.0;
for (int i = 0; i < array.size(); i++)
sum += normalized[i];
for (int i = 0; i < array.size(); i++) {
double x = normalized[i] / sum;
if (takeLog10OfOutput) x = Math.log10(x);
normalized[i] = x;
}
return normalized;
}
/**
* normalizes the log10-based array. ASSUMES THAT ALL ARRAY ENTRIES ARE <= 0 (<= 1 IN REAL-SPACE).
*
* @param array the array to be normalized
* @return a newly allocated array corresponding the normalized values in array
*/
public static double[] normalizeFromLog10(double[] array) {
return normalizeFromLog10(array, false);
}
public static double[] normalizeFromLog10(List<Double> array) {
return normalizeFromLog10(array, false);
}
public static int maxElementIndex(double[] array) {
if (array == null) throw new IllegalArgumentException("Array cannot be null!");
int maxI = -1;
for (int i = 0; i < array.length; i++) {
if (maxI == -1 || array[i] > array[maxI])
maxI = i;
}
return maxI;
}
public static int maxElementIndex(int[] array) {
if (array == null) throw new IllegalArgumentException("Array cannot be null!");
int maxI = -1;
for (int i = 0; i < array.length; i++) {
if (maxI == -1 || array[i] > array[maxI])
maxI = i;
}
return maxI;
}
public static double arrayMax(double[] array) {
return array[maxElementIndex(array)];
}
public static double arrayMin(double[] array) {
return array[minElementIndex(array)];
}
public static int arrayMin(int[] array) {
return array[minElementIndex(array)];
}
public static byte arrayMin(byte[] array) {
return array[minElementIndex(array)];
}
public static int minElementIndex(double[] array) {
if (array == null) throw new IllegalArgumentException("Array cannot be null!");
int minI = -1;
for (int i = 0; i < array.length; i++) {
if (minI == -1 || array[i] < array[minI])
minI = i;
}
return minI;
}
public static int minElementIndex(byte[] array) {
if (array == null) throw new IllegalArgumentException("Array cannot be null!");
int minI = -1;
for (int i = 0; i < array.length; i++) {
if (minI == -1 || array[i] < array[minI])
minI = i;
}
return minI;
}
public static int minElementIndex(int[] array) {
if (array == null) throw new IllegalArgumentException("Array cannot be null!");
int minI = -1;
for (int i = 0; i < array.length; i++) {
if (minI == -1 || array[i] < array[minI])
minI = i;
}
return minI;
}
public static int arrayMaxInt(List<Integer> array) {
if (array == null) throw new IllegalArgumentException("Array cannot be null!");
if (array.size() == 0) throw new IllegalArgumentException("Array size cannot be 0!");
int m = array.get(0);
for (int e : array) m = Math.max(m, e);
return m;
}
public static double arrayMaxDouble(List<Double> array) {
if (array == null) throw new IllegalArgumentException("Array cannot be null!");
if (array.size() == 0) throw new IllegalArgumentException("Array size cannot be 0!");
double m = array.get(0);
for (double e : array) m = Math.max(m, e);
return m;
}
public static double average(List<Long> vals, int maxI) {
long sum = 0L;
int i = 0;
for (long x : vals) {
if (i > maxI)
break;
sum += x;
i++;
//System.out.printf(" %d/%d", sum, i);
}
//System.out.printf("Sum = %d, n = %d, maxI = %d, avg = %f%n", sum, i, maxI, (1.0 * sum) / i);
return (1.0 * sum) / i;
}
public static double averageDouble(List<Double> vals, int maxI) {
double sum = 0.0;
int i = 0;
for (double x : vals) {
if (i > maxI)
break;
sum += x;
i++;
}
return (1.0 * sum) / i;
}
public static double average(List<Long> vals) {
return average(vals, vals.size());
}
public static byte average(byte[] vals) {
int sum = 0;
for (byte v : vals) {
sum += v;
}
return (byte) Math.floor(sum / vals.length);
}
public static double averageDouble(List<Double> vals) {
return averageDouble(vals, vals.size());
}
// Java Generics can't do primitive types, so I had to do this the simplistic way
public static Integer[] sortPermutation(final int[] A) {
class comparator implements Comparator<Integer> {
public int compare(Integer a, Integer b) {
if (A[a.intValue()] < A[b.intValue()]) {
return -1;
}
if (A[a.intValue()] == A[b.intValue()]) {
return 0;
}
if (A[a.intValue()] > A[b.intValue()]) {
return 1;
}
return 0;
}
}
Integer[] permutation = new Integer[A.length];
for (int i = 0; i < A.length; i++) {
permutation[i] = i;
}
Arrays.sort(permutation, new comparator());
return permutation;
}
public static Integer[] sortPermutation(final double[] A) {
class comparator implements Comparator<Integer> {
public int compare(Integer a, Integer b) {
if (A[a.intValue()] < A[b.intValue()]) {
return -1;
}
if (A[a.intValue()] == A[b.intValue()]) {
return 0;
}
if (A[a.intValue()] > A[b.intValue()]) {
return 1;
}
return 0;
}
}
Integer[] permutation = new Integer[A.length];
for (int i = 0; i < A.length; i++) {
permutation[i] = i;
}
Arrays.sort(permutation, new comparator());
return permutation;
}
public static <T extends Comparable> Integer[] sortPermutation(List<T> A) {
final Object[] data = A.toArray();
class comparator implements Comparator<Integer> {
public int compare(Integer a, Integer b) {
return ((T) data[a]).compareTo(data[b]);
}
}
Integer[] permutation = new Integer[A.size()];
for (int i = 0; i < A.size(); i++) {
permutation[i] = i;
}
Arrays.sort(permutation, new comparator());
return permutation;
}
public static int[] permuteArray(int[] array, Integer[] permutation) {
int[] output = new int[array.length];
for (int i = 0; i < output.length; i++) {
output[i] = array[permutation[i]];
}
return output;
}
public static double[] permuteArray(double[] array, Integer[] permutation) {
double[] output = new double[array.length];
for (int i = 0; i < output.length; i++) {
output[i] = array[permutation[i]];
}
return output;
}
public static Object[] permuteArray(Object[] array, Integer[] permutation) {
Object[] output = new Object[array.length];
for (int i = 0; i < output.length; i++) {
output[i] = array[permutation[i]];
}
return output;
}
public static String[] permuteArray(String[] array, Integer[] permutation) {
String[] output = new String[array.length];
for (int i = 0; i < output.length; i++) {
output[i] = array[permutation[i]];
}
return output;
}
public static <T> List<T> permuteList(List<T> list, Integer[] permutation) {
List<T> output = new ArrayList<T>();
for (int i = 0; i < permutation.length; i++) {
output.add(list.get(permutation[i]));
}
return output;
}
/**
* Draw N random elements from list.
*/
public static <T> List<T> randomSubset(List<T> list, int N) {
if (list.size() <= N) {
return list;
}
int idx[] = new int[list.size()];
for (int i = 0; i < list.size(); i++) {
idx[i] = GenomeAnalysisEngine.getRandomGenerator().nextInt();
}
Integer[] perm = sortPermutation(idx);
List<T> ans = new ArrayList<T>();
for (int i = 0; i < N; i++) {
ans.add(list.get(perm[i]));
}
return ans;
}
/**
* Draw N random elements from an array.
*
* @param array your objects
* @param n number of elements to select at random from the list
* @return a new list with the N randomly chosen elements from list
*/
@Requires({"array != null", "n>=0"})
@Ensures({"result != null", "result.length == Math.min(n, array.length)"})
public static Object[] randomSubset(final Object[] array, final int n) {
if (array.length <= n)
return array.clone();
Object[] shuffledArray = arrayShuffle(array);
Object[] result = new Object[n];
System.arraycopy(shuffledArray, 0, result, 0, n);
return result;
}
public static double percentage(double x, double base) {
return (base > 0 ? (x / base) * 100.0 : 0);
}
public static double percentage(int x, int base) {
return (base > 0 ? ((double) x / (double) base) * 100.0 : 0);
}
public static double percentage(long x, long base) {
return (base > 0 ? ((double) x / (double) base) * 100.0 : 0);
}
public static int countOccurrences(char c, String s) {
int count = 0;
for (int i = 0; i < s.length(); i++) {
count += s.charAt(i) == c ? 1 : 0;
}
return count;
}
public static <T> int countOccurrences(T x, List<T> l) {
int count = 0;
for (T y : l) {
if (x.equals(y)) count++;
}
return count;
}
public static int countOccurrences(byte element, byte[] array) {
int count = 0;
for (byte y : array) {
if (element == y)
count++;
}
return count;
}
/**
* Returns the top (larger) N elements of the array. Naive n^2 implementation (Selection Sort).
* Better than sorting if N (number of elements to return) is small
*
* @param array the array
* @param n number of top elements to return
* @return the n larger elements of the array
*/
public static Collection<Double> getNMaxElements(double[] array, int n) {
ArrayList<Double> maxN = new ArrayList<Double>(n);
double lastMax = Double.MAX_VALUE;
for (int i = 0; i < n; i++) {
double max = Double.MIN_VALUE;
for (double x : array) {
max = Math.min(lastMax, Math.max(x, max));
}
maxN.add(max);
lastMax = max;
}
return maxN;
}
/**
* Returns n random indices drawn with replacement from the range 0..(k-1)
*
* @param n the total number of indices sampled from
* @param k the number of random indices to draw (with replacement)
* @return a list of k random indices ranging from 0 to (n-1) with possible duplicates
*/
static public ArrayList<Integer> sampleIndicesWithReplacement(int n, int k) {
ArrayList<Integer> chosen_balls = new ArrayList<Integer>(k);
for (int i = 0; i < k; i++) {
//Integer chosen_ball = balls[rand.nextInt(k)];
chosen_balls.add(GenomeAnalysisEngine.getRandomGenerator().nextInt(n));
//balls.remove(chosen_ball);
}
return chosen_balls;
}
/**
* Returns n random indices drawn without replacement from the range 0..(k-1)
*
* @param n the total number of indices sampled from
* @param k the number of random indices to draw (without replacement)
* @return a list of k random indices ranging from 0 to (n-1) without duplicates
*/
static public ArrayList<Integer> sampleIndicesWithoutReplacement(int n, int k) {
ArrayList<Integer> chosen_balls = new ArrayList<Integer>(k);
for (int i = 0; i < n; i++) {
chosen_balls.add(i);
}
Collections.shuffle(chosen_balls, GenomeAnalysisEngine.getRandomGenerator());
//return (ArrayList<Integer>) chosen_balls.subList(0, k);
return new ArrayList<Integer>(chosen_balls.subList(0, k));
}
/**
* Given a list of indices into a list, return those elements of the list with the possibility of drawing list elements multiple times
*
* @param indices the list of indices for elements to extract
* @param list the list from which the elements should be extracted
* @param <T> the template type of the ArrayList
* @return a new ArrayList consisting of the elements at the specified indices
*/
static public <T> ArrayList<T> sliceListByIndices(List<Integer> indices, List<T> list) {
ArrayList<T> subset = new ArrayList<T>();
for (int i : indices) {
subset.add(list.get(i));
}
return subset;
}
public static Comparable orderStatisticSearch(int orderStat, List<Comparable> list) {
// this finds the order statistic of the list (kth largest element)
// the list is assumed *not* to be sorted
final Comparable x = list.get(orderStat);
ListIterator iterator = list.listIterator();
ArrayList lessThanX = new ArrayList();
ArrayList equalToX = new ArrayList();
ArrayList greaterThanX = new ArrayList();
for (Comparable y : list) {
if (x.compareTo(y) > 0) {
lessThanX.add(y);
} else if (x.compareTo(y) < 0) {
greaterThanX.add(y);
} else
equalToX.add(y);
}
if (lessThanX.size() > orderStat)
return orderStatisticSearch(orderStat, lessThanX);
else if (lessThanX.size() + equalToX.size() >= orderStat)
return orderStat;
else
return orderStatisticSearch(orderStat - lessThanX.size() - equalToX.size(), greaterThanX);
}
public static Object getMedian(List<Comparable> list) {
return orderStatisticSearch((int) Math.ceil(list.size() / 2), list);
}
public static byte getQScoreOrderStatistic(List<SAMRecord> reads, List<Integer> offsets, int k) {
// version of the order statistic calculator for SAMRecord/Integer lists, where the
// list index maps to a q-score only through the offset index
// returns the kth-largest q-score.
if (reads.size() == 0) {
return 0;
}
ArrayList lessThanQReads = new ArrayList();
ArrayList equalToQReads = new ArrayList();
ArrayList greaterThanQReads = new ArrayList();
ArrayList lessThanQOffsets = new ArrayList();
ArrayList greaterThanQOffsets = new ArrayList();
final byte qk = reads.get(k).getBaseQualities()[offsets.get(k)];
for (int iter = 0; iter < reads.size(); iter++) {
SAMRecord read = reads.get(iter);
int offset = offsets.get(iter);
byte quality = read.getBaseQualities()[offset];
if (quality < qk) {
lessThanQReads.add(read);
lessThanQOffsets.add(offset);
} else if (quality > qk) {
greaterThanQReads.add(read);
greaterThanQOffsets.add(offset);
} else {
equalToQReads.add(reads.get(iter));
}
}
if (lessThanQReads.size() > k)
return getQScoreOrderStatistic(lessThanQReads, lessThanQOffsets, k);
else if (equalToQReads.size() + lessThanQReads.size() >= k)
return qk;
else
return getQScoreOrderStatistic(greaterThanQReads, greaterThanQOffsets, k - lessThanQReads.size() - equalToQReads.size());
}
public static byte getQScoreMedian(List<SAMRecord> reads, List<Integer> offsets) {
return getQScoreOrderStatistic(reads, offsets, (int) Math.floor(reads.size() / 2.));
}
public static class RunningAverage {
private double mean = 0.0;
private double s = 0.0;
private long obs_count = 0;
public void add(double obs) {
obs_count++;
double oldMean = mean;
mean += (obs - mean) / obs_count; // update mean
s += (obs - oldMean) * (obs - mean);
}
public void addAll(Collection<Number> col) {
for (Number o : col) {
add(o.doubleValue());
}
}
public double mean() {
return mean;
}
public double stddev() {
return Math.sqrt(s / (obs_count - 1));
}
public double var() {
return s / (obs_count - 1);
}
public long observationCount() {
return obs_count;
}
public RunningAverage clone() {
RunningAverage ra = new RunningAverage();
ra.mean = this.mean;
ra.s = this.s;
ra.obs_count = this.obs_count;
return ra;
}
public void merge(RunningAverage other) {
if (this.obs_count > 0 || other.obs_count > 0) { // if we have any observations at all
this.mean = (this.mean * this.obs_count + other.mean * other.obs_count) / (this.obs_count + other.obs_count);
this.s += other.s;
}
this.obs_count += other.obs_count;
}
}
// useful common utility routines
public static double rate(long n, long d) {
return n / (1.0 * Math.max(d, 1));
}
public static double rate(int n, int d) {
return n / (1.0 * Math.max(d, 1));
}
public static long inverseRate(long n, long d) {
return n == 0 ? 0 : d / Math.max(n, 1);
}
public static long inverseRate(int n, int d) {
return n == 0 ? 0 : d / Math.max(n, 1);
}
public static double ratio(int num, int denom) {
return ((double) num) / (Math.max(denom, 1));
}
public static double ratio(long num, long denom) {
return ((double) num) / (Math.max(denom, 1));
}
public static final double[] log10Cache;
public static final double[] jacobianLogTable;
public static final int JACOBIAN_LOG_TABLE_SIZE = 101;
public static final double JACOBIAN_LOG_TABLE_STEP = 0.1;
public static final double INV_JACOBIAN_LOG_TABLE_STEP = 1.0 / JACOBIAN_LOG_TABLE_STEP;
public static final double MAX_JACOBIAN_TOLERANCE = 10.0;
private static final int MAXN = 11000;
private static final int LOG10_CACHE_SIZE = 4 * MAXN; // we need to be able to go up to 2*(2N) when calculating some of the coefficients
static {
log10Cache = new double[LOG10_CACHE_SIZE];
jacobianLogTable = new double[JACOBIAN_LOG_TABLE_SIZE];
log10Cache[0] = Double.NEGATIVE_INFINITY;
for (int k = 1; k < LOG10_CACHE_SIZE; k++)
log10Cache[k] = Math.log10(k);
for (int k = 0; k < JACOBIAN_LOG_TABLE_SIZE; k++) {
jacobianLogTable[k] = Math.log10(1.0 + Math.pow(10.0, -((double) k)
* JACOBIAN_LOG_TABLE_STEP));
}
}
static public double softMax(final double[] vec) {
double acc = vec[0];
for (int k = 1; k < vec.length; k++)
acc = softMax(acc, vec[k]);
return acc;
}
static public double max(double x0, double x1, double x2) {
double a = Math.max(x0, x1);
return Math.max(a, x2);
}
static public double softMax(final double x0, final double x1, final double x2) {
// compute naively log10(10^x[0] + 10^x[1]+...)
// return Math.log10(MathUtils.sumLog10(vec));
// better approximation: do Jacobian logarithm function on data pairs
double a = softMax(x0, x1);
return softMax(a, x2);
}
static public double softMax(final double x, final double y) {
// we need to compute log10(10^x + 10^y)
// By Jacobian logarithm identity, this is equal to
// max(x,y) + log10(1+10^-abs(x-y))
// we compute the second term as a table lookup
// with integer quantization
// return Math.log10(Math.pow(10.0,x) + Math.pow(10.0,y));
double diff = x - y;
if (diff > MAX_JACOBIAN_TOLERANCE)
return x;
else if (diff < -MAX_JACOBIAN_TOLERANCE)
return y;
else if (diff >= 0) {
int ind = (int) (diff * INV_JACOBIAN_LOG_TABLE_STEP + 0.5);
return x + jacobianLogTable[ind];
} else {
int ind = (int) (-diff * INV_JACOBIAN_LOG_TABLE_STEP + 0.5);
return y + jacobianLogTable[ind];
}
}
public static double phredScaleToProbability(byte q) {
return Math.pow(10, (-q) / 10.0);
}
public static double phredScaleToLog10Probability(byte q) {
return ((-q) / 10.0);
}
/**
* Returns the phred scaled value of probability p
*
* @param p probability (between 0 and 1).
* @return phred scaled probability of p
*/
public static byte probabilityToPhredScale(double p) {
return (byte) ((-10) * Math.log10(p));
}
public static double log10ProbabilityToPhredScale(double log10p) {
return (-10) * log10p;
}
/**
* Converts LN to LOG10
*
* @param ln log(x)
* @return log10(x)
*/
public static double lnToLog10(double ln) {
return ln * Math.log10(Math.exp(1));
}
/**
* Constants to simplify the log gamma function calculation.
*/
private static final double
zero = 0.0,
one = 1.0,
half = .5,
a0 = 7.72156649015328655494e-02,
a1 = 3.22467033424113591611e-01,
a2 = 6.73523010531292681824e-02,
a3 = 2.05808084325167332806e-02,
a4 = 7.38555086081402883957e-03,
a5 = 2.89051383673415629091e-03,
a6 = 1.19270763183362067845e-03,
a7 = 5.10069792153511336608e-04,
a8 = 2.20862790713908385557e-04,
a9 = 1.08011567247583939954e-04,
a10 = 2.52144565451257326939e-05,
a11 = 4.48640949618915160150e-05,
tc = 1.46163214496836224576e+00,
tf = -1.21486290535849611461e-01,
tt = -3.63867699703950536541e-18,
t0 = 4.83836122723810047042e-01,
t1 = -1.47587722994593911752e-01,
t2 = 6.46249402391333854778e-02,
t3 = -3.27885410759859649565e-02,
t4 = 1.79706750811820387126e-02,
t5 = -1.03142241298341437450e-02,
t6 = 6.10053870246291332635e-03,
t7 = -3.68452016781138256760e-03,
t8 = 2.25964780900612472250e-03,
t9 = -1.40346469989232843813e-03,
t10 = 8.81081882437654011382e-04,
t11 = -5.38595305356740546715e-04,
t12 = 3.15632070903625950361e-04,
t13 = -3.12754168375120860518e-04,
t14 = 3.35529192635519073543e-04,
u0 = -7.72156649015328655494e-02,
u1 = 6.32827064025093366517e-01,
u2 = 1.45492250137234768737e+00,
u3 = 9.77717527963372745603e-01,
u4 = 2.28963728064692451092e-01,
u5 = 1.33810918536787660377e-02,
v1 = 2.45597793713041134822e+00,
v2 = 2.12848976379893395361e+00,
v3 = 7.69285150456672783825e-01,
v4 = 1.04222645593369134254e-01,
v5 = 3.21709242282423911810e-03,
s0 = -7.72156649015328655494e-02,
s1 = 2.14982415960608852501e-01,
s2 = 3.25778796408930981787e-01,
s3 = 1.46350472652464452805e-01,
s4 = 2.66422703033638609560e-02,
s5 = 1.84028451407337715652e-03,
s6 = 3.19475326584100867617e-05,
r1 = 1.39200533467621045958e+00,
r2 = 7.21935547567138069525e-01,
r3 = 1.71933865632803078993e-01,
r4 = 1.86459191715652901344e-02,
r5 = 7.77942496381893596434e-04,
r6 = 7.32668430744625636189e-06,
w0 = 4.18938533204672725052e-01,
w1 = 8.33333333333329678849e-02,
w2 = -2.77777777728775536470e-03,
w3 = 7.93650558643019558500e-04,
w4 = -5.95187557450339963135e-04,
w5 = 8.36339918996282139126e-04,
w6 = -1.63092934096575273989e-03;
/**
* Efficient rounding functions to simplify the log gamma function calculation
* double to long with 32 bit shift
*/
private static final int HI(double x) {
return (int) (Double.doubleToLongBits(x) >> 32);
}
/**
* Efficient rounding functions to simplify the log gamma function calculation
* double to long without shift
*/
private static final int LO(double x) {
return (int) Double.doubleToLongBits(x);
}
/**
* Most efficent implementation of the lnGamma (FDLIBM)
* Use via the log10Gamma wrapper method.
*/
private static double lnGamma(double x) {
double t, y, z, p, p1, p2, p3, q, r, w;
int i;
int hx = HI(x);
int lx = LO(x);
/* purge off +-inf, NaN, +-0, and negative arguments */
int ix = hx & 0x7fffffff;
if (ix >= 0x7ff00000) return Double.POSITIVE_INFINITY;
if ((ix | lx) == 0 || hx < 0) return Double.NaN;
if (ix < 0x3b900000) { /* |x|<2**-70, return -log(|x|) */
return -Math.log(x);
}
/* purge off 1 and 2 */
if ((((ix - 0x3ff00000) | lx) == 0) || (((ix - 0x40000000) | lx) == 0)) r = 0;
/* for x < 2.0 */
else if (ix < 0x40000000) {
if (ix <= 0x3feccccc) { /* lgamma(x) = lgamma(x+1)-log(x) */
r = -Math.log(x);
if (ix >= 0x3FE76944) {
y = one - x;
i = 0;
} else if (ix >= 0x3FCDA661) {
y = x - (tc - one);
i = 1;
} else {
y = x;
i = 2;
}
} else {
r = zero;
if (ix >= 0x3FFBB4C3) {
y = 2.0 - x;
i = 0;
} /* [1.7316,2] */ else if (ix >= 0x3FF3B4C4) {
y = x - tc;
i = 1;
} /* [1.23,1.73] */ else {
y = x - one;
i = 2;
}
}
switch (i) {
case 0:
z = y * y;
p1 = a0 + z * (a2 + z * (a4 + z * (a6 + z * (a8 + z * a10))));
p2 = z * (a1 + z * (a3 + z * (a5 + z * (a7 + z * (a9 + z * a11)))));
p = y * p1 + p2;
r += (p - 0.5 * y);
break;
case 1:
z = y * y;
w = z * y;
p1 = t0 + w * (t3 + w * (t6 + w * (t9 + w * t12))); /* parallel comp */
p2 = t1 + w * (t4 + w * (t7 + w * (t10 + w * t13)));
p3 = t2 + w * (t5 + w * (t8 + w * (t11 + w * t14)));
p = z * p1 - (tt - w * (p2 + y * p3));
r += (tf + p);
break;
case 2:
p1 = y * (u0 + y * (u1 + y * (u2 + y * (u3 + y * (u4 + y * u5)))));
p2 = one + y * (v1 + y * (v2 + y * (v3 + y * (v4 + y * v5))));
r += (-0.5 * y + p1 / p2);
}
} else if (ix < 0x40200000) { /* x < 8.0 */
i = (int) x;
t = zero;
y = x - (double) i;
p = y * (s0 + y * (s1 + y * (s2 + y * (s3 + y * (s4 + y * (s5 + y * s6))))));
q = one + y * (r1 + y * (r2 + y * (r3 + y * (r4 + y * (r5 + y * r6)))));
r = half * y + p / q;
z = one; /* lgamma(1+s) = log(s) + lgamma(s) */
switch (i) {
case 7:
z *= (y + 6.0); /* FALLTHRU */
case 6:
z *= (y + 5.0); /* FALLTHRU */
case 5:
z *= (y + 4.0); /* FALLTHRU */
case 4:
z *= (y + 3.0); /* FALLTHRU */
case 3:
z *= (y + 2.0); /* FALLTHRU */
r += Math.log(z);
break;
}
/* 8.0 <= x < 2**58 */
} else if (ix < 0x43900000) {
t = Math.log(x);
z = one / x;
y = z * z;
w = w0 + z * (w1 + y * (w2 + y * (w3 + y * (w4 + y * (w5 + y * w6)))));
r = (x - half) * (t - one) + w;
} else
/* 2**58 <= x <= inf */
r = x * (Math.log(x) - one);
return r;
}
/**
* Calculates the log10 of the gamma function for x using the efficient FDLIBM
* implementation to avoid overflows and guarantees high accuracy even for large
* numbers.
*
* @param x the x parameter
* @return the log10 of the gamma function at x.
*/
public static double log10Gamma(double x) {
return lnToLog10(lnGamma(x));
}
/**
* Calculates the log10 of the binomial coefficient. Designed to prevent
* overflows even with very large numbers.
*
* @param n total number of trials
* @param k number of successes
* @return the log10 of the binomial coefficient
*/
public static double log10BinomialCoefficient(int n, int k) {
return log10Gamma(n + 1) - log10Gamma(k + 1) - log10Gamma(n - k + 1);
}
public static double log10BinomialProbability(int n, int k, double log10p) {
double log10OneMinusP = Math.log10(1 - Math.pow(10, log10p));
return log10BinomialCoefficient(n, k) + log10p * k + log10OneMinusP * (n - k);
}
/**
* Calculates the log10 of the multinomial coefficient. Designed to prevent
* overflows even with very large numbers.
*
* @param n total number of trials
* @param k array of any size with the number of successes for each grouping (k1, k2, k3, ..., km)
* @return
*/
public static double log10MultinomialCoefficient(int n, int[] k) {
double denominator = 0.0;
for (int x : k) {
denominator += log10Gamma(x + 1);
}
return log10Gamma(n + 1) - denominator;
}
/**
* Computes the log10 of the multinomial distribution probability given a vector
* of log10 probabilities. Designed to prevent overflows even with very large numbers.
*
* @param n number of trials
* @param k array of number of successes for each possibility
* @param log10p array of log10 probabilities
* @return
*/
public static double log10MultinomialProbability(int n, int[] k, double[] log10p) {
if (log10p.length != k.length)
throw new UserException.BadArgumentValue("p and k", "Array of log10 probabilities must have the same size as the array of number of sucesses: " + log10p.length + ", " + k.length);
double log10Prod = 0.0;
for (int i = 0; i < log10p.length; i++) {
log10Prod += log10p[i] * k[i];
}
return log10MultinomialCoefficient(n, k) + log10Prod;
}
public static double factorial(int x) {
return Math.pow(10, log10Gamma(x + 1));
}
public static double log10Factorial(int x) {
return log10Gamma(x + 1);
}
/**
* Adds two arrays together and returns a new array with the sum.
*
* @param a one array
* @param b another array
* @return a new array with the sum of a and b
*/
@Requires("a.length == b.length")
@Ensures("result.length == a.length")
public static int[] addArrays(int[] a, int[] b) {
int[] c = new int[a.length];
for (int i = 0; i < a.length; i++)
c[i] = a[i] + b[i];
return c;
}
/**
* Quick implementation of the Knuth-shuffle algorithm to generate a random
* permutation of the given array.
*
* @param array the original array
* @return a new array with the elements shuffled
*/
public static Object[] arrayShuffle(Object[] array) {
int n = array.length;
Object[] shuffled = array.clone();
for (int i = 0; i < n; i++) {
int j = i + GenomeAnalysisEngine.getRandomGenerator().nextInt(n - i);
Object tmp = shuffled[i];
shuffled[i] = shuffled[j];
shuffled[j] = tmp;
}
return shuffled;
}
/**
* Vector operations
*/
public static double[] vectorSum(double v1[], double v2[]) {
if (v1.length != v2.length)
throw new UserException("BUG: vectors v1, v2 of different size in vectorSum()");
double result[] = new double[v1.length];
for (int k=0; k < v1.length; k++)
result[k] = v1[k]+v2[k];
return result;
}
public static double[] scalarTimesIntVector(double a, int[] v1) {
double result[] = new double[v1.length];
for (int k=0; k < v1.length; k++)
result[k] = a*v1[k];
return result;
}
public static double dotProduct(double v1[], double v2[]) {
if (v1.length != v2.length)
throw new UserException("BUG: vectors v1, v2 of different size in vectorSum()");
double result = 0.0;
for (int k=0; k < v1.length; k++)
result += v1[k]*v2[k];
return result;
}
public static double[] vectorLog10(double v1[]) {
double result[] = new double[v1.length];
for (int k=0; k < v1.length; k++)
result[k] = Math.log10(v1[k]);
return result;
}
} |
package li.mvc;
import java.io.IOException;
import java.util.Locale;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import li.dao.Record;
import li.model.Action;
import li.model.Field;
import li.util.Convert;
import li.util.Files;
import li.util.Log;
import li.util.Page;
import li.util.Reflect;
import li.util.Verify;
/**
* MVCFilter,HTTP
*
* @author li (limw@w.cn)
* @version 0.1.3 (2012-05-08)
*/
public class ActionFilter implements Filter {
private static final Log log = Log.init();
private static final String ENCODING = Files.load("config.properties").getProperty("servlet.encoding", "UTF-8");// Servlet,
private static final String USE_I18N = Files.load("config.properties").getProperty("servlet.i18n", "false");
/**
* Filter,,
*/
public void init(FilterConfig config) throws ServletException {
config.getServletContext().setAttribute("root", config.getServletContext().getContextPath() + "/");
if ("true".equals(USE_I18N.trim().toLowerCase())) {
config.getServletContext().setAttribute("lang", Files.load(Locale.getDefault().toString()));// Locale.getDefault(),servletContext
log.info("Setting default language as " + Locale.getDefault());
}
}
/**
* ActionContextAction,chain.doFilter()
*
* @see li.util.Reflect#invoke(Object, String, Object...)
*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
request.setCharacterEncoding(ENCODING);
response.setCharacterEncoding(ENCODING);
if ("true".equals(USE_I18N.trim().toLowerCase())) {
String lang = request.getParameter("lang");// Parameter,session
if (!Verify.isEmpty(lang)) {
((HttpServletRequest) request).getSession().setAttribute("lang", Files.load(lang));
log.info("Setting language for " + lang);
}
}
Action action = ActionContext.getInstance().getAction(((HttpServletRequest) request).getServletPath(), ((HttpServletRequest) request).getMethod());
if (null != action) {
Context.init(request, response, action);// Context
log.info("ACTION FOUND: path=\"" + Context.getRequest().getServletPath() + "\",method=\"" + Context.getRequest().getMethod() + "\" action=" + action.actionInstance.getClass().getName() + "." + action.actionMethod.getName() + "()");
Object[] args = new Object[action.argTypes.length]; // Action
for (int i = 0; i < action.argTypes.length; i++) {// Action
String key = (null == action.argAnnotations[i]) ? action.argNames[i] : action.argAnnotations[i].value();// ParameterKey
if (Verify.basicType(action.argTypes[i]) && !action.argTypes[i].isArray()) {
args[i] = Convert.toType(action.argTypes[i], Context.getParameter(key));
} else if (Verify.basicType(action.argTypes[i]) && action.argTypes[i].isArray()) {
args[i] = Context.getArray(action.argTypes[i].getComponentType(), key);
} else if (ServletRequest.class.isAssignableFrom(action.argTypes[i])) { // Request
args[i] = Context.getRequest();
} else if (ServletResponse.class.isAssignableFrom(action.argTypes[i])) { // Response
args[i] = Context.getResponse();
} else if (Page.class.isAssignableFrom(action.argTypes[i])) { // Page
args[i] = Context.getPage(key);
} else if (Field.list(action.argTypes[i], false).size() > 0 || Record.class.isAssignableFrom(action.argTypes[i])) {
key = (null == action.argAnnotations[i]) ? action.argNames[i] + "." : action.argAnnotations[i].value();
args[i] = Context.get(action.argTypes[i], key);// ,POJO,@Arg,key+"."
}
}
Object result = Reflect.invoke(action.actionInstance, action.actionMethod, args);// Action
if (result instanceof String && !result.equals("~!@#DONE")) {// String
Context.view(result.toString());// Context.view
}
} else {
log.info("ACTION NOT FOUND: path=\"" + ((HttpServletRequest) request).getServletPath() + "\",method=\"" + ((HttpServletRequest) request).getMethod() + "\"");
chain.doFilter(request, response);
}
}
/**
* Filter
*/
public void destroy() {
log.debug("li.mvc.ActionFilter.destroy()");
}
} |
package org.cmcg.webcrawler.search;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.awt.image.PixelGrabber;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import org.cmcg.logger.Log;
/**
* A search object that searches for 'img' tags and compares the image to local images.
*/
public abstract class HTMLImageSearch extends XMLTagSearch {
private String homePage;
private boolean preloadImages;
private boolean resizeImages;
private ArrayList<SearchImage> imagesToFind;
private HashMap<URL, Integer[]> checkedImages;
/**
*
* @param homePage The homepage for the hosted images. Skips URLs that don't contain this string.
* @param preloadImages True if local images should be loaded before processing. False if each local image should be loaded every time it's checked (Easier on memory).
* @param resizeImages True if site images should be resized before comparison
* @param imagesToFind The paths for the local images. Directories are searched recursively for images.
*/
public HTMLImageSearch(String homePage, boolean preloadImages, boolean resizeImages, String... imagesToFind) {
super("img");
this.homePage = homePage;
this.preloadImages = preloadImages;
this.imagesToFind = new ArrayList<SearchImage>();
this.checkedImages = new HashMap<URL, Integer[]>();
ArrayList<String> pathsToFind = new ArrayList<String>();
for (String s : imagesToFind) {
pathsToFind.add(s);
}
String s;
while (!pathsToFind.isEmpty()) {
addPath(pathsToFind.remove(0));
}
}
private void addPath(String s) {
File file = new File(s);
if (file.exists()) {
if (file.isDirectory()) {
for (File f : file.listFiles()) {
if (f.isDirectory() || f.getName().endsWith(".png") || f.getName().endsWith(".jpg")
|| f.getName().endsWith(".jpeg") || f.getName().endsWith(".bmp")) {
addPath(f.getPath());
}
}
return;
}
try {
this.imagesToFind.add(new SearchImage(s, preloadImages));
} catch (IOException e) {
Log.error("Could not load image: " + Arrays.toString(e.getStackTrace()));
}
}
}
/**
* Called when a matching image is found
* @param originalImage The path to the original Image
* @param matchedImage The url to the matched image
* @param pageUrl The url the image was found on
*/
public abstract void onFoundImage(String originalImage, String matchedImage, String pageUrl);
@Override
public void onFoundTag(HashMap<String, String> attributes, String tagContents) {
String src = attributes.get("src");
if (src == null || !src.contains(homePage) || src.endsWith(".gif")) {
return;
}
src = src.trim();
if (src.startsWith("\"") || src.startsWith("'")) {
src = src.substring(1);
}
if (src.endsWith("\"") || src.endsWith("'")) {
src = src.substring(0, src.length() - 1);
}
if (src.startsWith("/")) {
src = "http://" + homePage + src;
}
try {
URL url = new URL(src);
if (checkedImages.containsKey(url)) {
for (Integer i : checkedImages.get(url)) {
onFoundImage(imagesToFind.get(i).path, src, super.pageUrl);
}
return;
}
Image siteImage = ImageIO.read(url);
if (siteImage == null) {
return;
}
int size = imagesToFind.size();
ArrayList<Integer> matchedLocalImages = new ArrayList<Integer>();
ImageIcon icon = new ImageIcon(siteImage);
int h1 = icon.getIconHeight();
int w1 = icon.getIconWidth();
Log.log("Testing against " + size + " " + (preloadImages ? "" : "non-") + "preloaded images: " + src);
local_image_loop: for (int i = 0; i < size; i++) {
SearchImage searchImage = imagesToFind.get(i);
int[] pixelData = searchImage.getPixelData();
if (pixelData == null) {
Log.error("Pixel data was null for image: " + searchImage.path);
continue;
}
int h2 = searchImage.height;
int w2 = searchImage.width;
if (w1 != w2 || h1 != h2) {
if (resizeImages) {
siteImage = siteImage.getScaledInstance(w1, h1, Image.SCALE_SMOOTH);
} else {
continue;//TODO if an image gets skipped it won't get another change to retry atm
}
}
int[] pixelData2 = new int[w1 * h1];
PixelGrabber pxGrabber = new PixelGrabber(siteImage, 0, 0, w1, h1, pixelData2, 0, w1);
try {
pxGrabber.grabPixels();
} catch (InterruptedException e) {
e.printStackTrace();
continue;//TODO here too
}
for (int j = 0; j < pixelData.length; j++) {
if (pixelData[j] != pixelData2[j]) {
continue local_image_loop;
}
}
matchedLocalImages.add(i);
onFoundImage(searchImage.path, src, super.pageUrl);
}
checkedImages.put(url, matchedLocalImages.toArray(new Integer[matchedLocalImages.size()]));
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void reset() {
super.reset();
}
private class SearchImage {
private static final int NUM_RETRIES = 5;
int width, height;
String path;
private BufferedImage image;
private int[] pixelData;
private int loadRetries;
SearchImage(String path, boolean preload) throws IOException {
this.path = path;
BufferedImage image = null;
image = ImageIO.read(new File(path));
ImageIcon icon = new ImageIcon(image);
this.width = icon.getIconWidth();
this.height = icon.getIconHeight();
if (preload) {
this.image = image;
pixelData = new int[width * height];
PixelGrabber pxGrabber = new PixelGrabber(image, 0, 0, width, height, pixelData, 0, width);
try {
pxGrabber.grabPixels();
} catch (InterruptedException e) {
Log.error("Could not grab pixels from image \"" + this.path + "\"" + Arrays.toString(e.getStackTrace()));
}
}
}
private BufferedImage getImage() {
if (image == null && loadRetries < NUM_RETRIES) {
try {
return ImageIO.read(new File(path));
} catch (IOException e) {
loadRetries++;
Log.log("Could not load image file \"" + this.path + "\"\nRetry count: " + loadRetries);
e.printStackTrace();
}
}
return image;
}
int[] getPixelData() {
if (pixelData == null) {
pixelData = new int[width * height];
Image image = getImage();
if (image != null) {
PixelGrabber pxGrabber = new PixelGrabber(image, 0, 0, width, height, pixelData, 0, width);
try {
pxGrabber.grabPixels();
} catch (InterruptedException e) {
Log.error("Could not grab pixels from image \"" + this.path + "\"" + Arrays.toString(e.getStackTrace()));
}
}
}
return pixelData;
}
}
} |
package com.zakgof.db.velvet.join;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import com.zakgof.db.velvet.IVelvet;
import com.zakgof.db.velvet.entity.IEntityDef;
import com.zakgof.db.velvet.link.IBiManyToManyLinkDef;
import com.zakgof.db.velvet.link.ILinkDef;
import com.zakgof.db.velvet.link.IMultiGetter;
import com.zakgof.db.velvet.link.IMultiLinkDef;
import com.zakgof.db.velvet.link.ISingleGetter;
import com.zakgof.db.velvet.link.ISingleLinkDef;
import com.zakgof.db.velvet.link.Links;
/**
* Query for multiple linked entities.
*
* @param <MK> main entity key type
* @param <MV> main entity value type
*/
public class JoinDef<MK, MV> {
private final Map<IEntityDef<?, ?>, FetcherEntity<?, ?>> entities;
private final IEntityDef<MK, MV> mainEntity;
private JoinDef(IEntityDef<MK, MV> mainEntity, Map<IEntityDef<?, ?>, FetcherEntity<?, ?>> entities) {
this.mainEntity = mainEntity;
this.entities = entities;
}
/**
* Create a QueryDef builder.
*
* @param mainEntity main entity definition
* @param <MK> main entity key class
* @param <MV> main entity value class
* @return builder
*/
public static <MK, MV> Builder<MK, MV>.QueryEntityBuilder<MK, MV> builderFor(IEntityDef<MK, MV> mainEntity) {
return new Builder<>(mainEntity).entity(mainEntity);
}
/**
* QueryDef builder.
*
* @param <MK> main entity key type
* @param <MV> main entity value type
*/
public static class Builder<MK, MV> {
private final Map<IEntityDef<?, ?>, FetcherEntity<?, ?>> entities = new LinkedHashMap<>();
private final IEntityDef<MK, MV> mainEntity;
private Builder(IEntityDef<MK, MV> mainEntity) {
this.mainEntity = mainEntity;
}
/**
* Registers a linked entity definition.
*
* @param entityDef entity definition
* @param <K> entity key class
* @param <V> entity value class
* @return QueryEntityBuilder for this entity
*/
public <K, V> QueryEntityBuilder<K, V> entity(IEntityDef<K, V> entityDef) {
return new QueryEntityBuilder<>(entityDef);
}
/**
* Linked entity definition builder.
*
* @param <K> entity key type
* @param <V> entity value type
*/
public class QueryEntityBuilder<K, V> {
private final IEntityDef<K, V> entityDef;
private final Map<String, ISingleGetter<K, V, ?, ?>> singles = new HashMap<>();
private final Set<ILinkDef<K, V, ?, ?>> detaches = new HashSet<>();
private final Map<String, IMultiGetter<K, V, ?, ?>> multis = new HashMap<>();
private final Map<String, IContextSingleGetter<K, V, ?>> attrs = new HashMap<>();
private final Map<String, Function<DataWrap<K, V>, ?>> postattrs = new HashMap<>();
private Comparator<DataWrap<K, V>> sort = null;
private QueryEntityBuilder(IEntityDef<K, V> entityDef) {
this.entityDef = entityDef;
}
/**
* Registers a IMultiGetter to be fetched with this entity as child data.
*
* The child data will be available from the resulting DataWrap via {@link DataWrap#multi(String)}
*
* @param name name for child data.
* @param multigetter IMultiGetter for child data
* @param <CK> child entity key type
* @param <CV> child entity value type
* @return this entity builder
*/
public <CK, CV> QueryEntityBuilder<K, V> include(String name, IMultiGetter<K, V, CK, CV> multigetter) {
multis.put(name, multigetter);
return this;
}
/**
* Registers a one-to-many link to be fetched with this entity as child data.
*
* The child data will be available as a List from the resulting DataWrap via {@link DataWrap#multiLink(IMultiLinkDef)}
*
* @param linkDef child link definition
* @param <CK> child entity key type
* @param <CV> child entity value type
* @return this entity builder
*/
public <CK, CV> QueryEntityBuilder<K, V> include(IMultiLinkDef<K, V, CK, CV> linkDef) {
return include(linkDef.getKind(), linkDef);
}
/**
* Registers a ISingleGetter to be fetched with this entity as child data.
*
* The child data will be available from the resulting DataWrap via {@code DataWrap#singleLink(ISingleGetter)}
*
* @param name name for child data.
* @param <CK> child entity key type
* @param <CV> child entity value type
* @param getter ISingleGetter for child dat
* @return this entity builder
*/
public <CK, CV> QueryEntityBuilder<K, V> include(String name, ISingleGetter<K, V, CK, CV> getter) {
singles.put(name, getter);
return this;
}
/**
* Registers a one-to-one link to be fetched with this entity as child data.
*
* The child data will be available from the resulting DataWrap via {@code DataWrap#multiLink(ISingleLinkDef)}
*
* @param linkDef child link definition
* @param <L> child entity value type
* @return this entity builder
*/
public <L> QueryEntityBuilder<K, V> include(ISingleLinkDef<K, V, ?, L> linkDef) {
return include(linkDef.getKind(), linkDef);
}
/**
* Registers a link to be detached from when deleting the entity.
*
* @param parentLink link to this entity to be disconnected when removing this entity
* @param <CK> child entity key type
* @param <CV> child entity value type
* @return this entity builder
*/
public <CK, CV> QueryEntityBuilder<K, V> detach(ISingleLinkDef<K, V, CK, CV> parentLink) {
detaches.add(parentLink);
return this;
}
/**
* Registers a link to be detached from when deleting the entity.
*
* @param parentLink link to this entity to be disconnected when removing this entity
* @param <CK> child entity key type
* @param <CV> child entity value type
* @return this entity builder
*/
public <CK, CV> QueryEntityBuilder<K, V> detach(IBiManyToManyLinkDef<K, V, CK, CV> parentLink) {
detaches.add(parentLink);
return this;
}
/**
* Registers an attribute to be added to entity's DataWrap when fetching.
*
* @param name attribute name
* @param <CV> attribute type
* @param contextSingleGetter IContextSingleGetter that returns attribute value from context
* @return this entity builder
*/
public <CV> QueryEntityBuilder<K, V> attribute(String name, IContextSingleGetter<K, V, CV> contextSingleGetter) {
attrs.put(name, contextSingleGetter);
return this;
}
/**
* Registers an attribute to be added to entity's DataWrap when fetching.
*
* @param name attribute name
* @param function function that returns attribute value from DataWrap
* @param <CV> attribute type
* @return this entity builder
*/
public <CV> QueryEntityBuilder<K, V> attribute(String name, Function<DataWrap<K, V>, CV> function) {
postattrs.put(name, function);
return this;
}
/**
* Registers sort comparator for this entity.
* DataWraps will be sorted using this comparator.
*
* @param comparator comparator
* @return this entity builder
*/
public QueryEntityBuilder<K, V> sort(Comparator<V> comparator) {
return sortWraps(Comparator.comparing(DataWrap::getNode, comparator));
}
/**
* Registers DataWrap sort comparator for this entity.
* DataWraps will be sorted using this comparator.
*
* @param comparator comparator
* @return this entity builder
*/
public QueryEntityBuilder<K, V> sortWraps(Comparator<DataWrap<K, V>> comparator) {
sort = comparator;
return this;
}
/**
* Finish building entity and continue with query builder.
*
* @return query definition builder
*/
public Builder<MK, MV> done() {
Builder.this.addEntity(new FetcherEntity<>(entityDef, multis, singles, detaches, attrs, postattrs, sort));
return Builder.this;
}
}
private <K, V> void addEntity(FetcherEntity<K, V> entity) {
entities.put(entity.entityDef, entity);
}
/**
* Build query definition.
* @return query definition
*/
public JoinDef<MK, MV> build() {
return new JoinDef<>(mainEntity, entities);
}
}
private static class FetcherEntity<K, V> {
private final IEntityDef<K, V> entityDef;
private final Map<String, IMultiGetter<K, V, ?, ?>> multis;
private final Map<String, ISingleGetter<K, V, ?, ?>> singles;
private final Set<ILinkDef<K, V, ?, ?>> detaches;
private final Comparator<DataWrap<K, V>> sort;
private final Map<String, IContextSingleGetter<K, V, ?>> attrs;
private final Map<String, Function<DataWrap<K, V>, ?>> postattrs;
private FetcherEntity(IEntityDef<K, V> entityDef,
Map<String, IMultiGetter<K, V, ?, ?>> multis,
Map<String, ISingleGetter<K, V, ?, ?>> singles,
Set<ILinkDef<K, V, ?, ?>> detaches,
Map<String, IContextSingleGetter<K, V, ?>> attrs,
Map<String, Function<DataWrap<K, V>, ?>> postattrs,
Comparator<DataWrap<K, V>> sort) {
this.entityDef = entityDef;
this.multis = multis;
this.singles = singles;
this.detaches = detaches;
this.attrs = attrs;
this.postattrs = postattrs;
this.sort = sort;
}
}
/**
* Get entity with all the linked data by its key.
*
* @param velvet velvet handle
* @param key entity key
* @return DataWrap for entity value with all the linked data, or null if no entity exists for the key.
*/
public DataWrap<MK, MV> get(IVelvet velvet, MK key) {
MV node = mainEntity.get(velvet, key);
DataWrap<MK, MV> wrap = new BatchBuilder<>(velvet, mainEntity).make(node);
return wrap;
}
/**
* Gets multiple entities with all the linked data by their keys.
*
* When no entity exists for a key, the corresponding DataWrap will be silently missing from the resulting list.
*
* @param velvet velvet handle
* @param keys entity keys
* @return DataWrap for entity value with all the linked data
*/
public List<DataWrap<MK, MV>> batchGet(IVelvet velvet, List<MK> keys) {
List<MV> nodes = mainEntity.batchGetList(velvet, keys);
return wrapNodes(velvet, mainEntity, nodes);
}
/**
* Gets all the entities of this kind with all the linked data.
*
* @param velvet velvet handle
* @return list of DataWraps
*/
public List<DataWrap<MK, MV>> batchGetAll(IVelvet velvet) {
List<MV> nodes = mainEntity.batchGetAllList(velvet);
return wrapNodes(velvet, mainEntity, nodes);
}
/**
* Deletes an entity by a key, removing or detaching the linked data.
*
* @param velvet velvet handle
* @param key entity key
*/
public void deleteKey(IVelvet velvet, MK key) {
delete(velvet, mainEntity, key);
}
/**
* Deletes an entity by a value, removing or detaching the linked data.
*
* @param velvet velvet handle
* @param value entity value
*/
public void deleteValue(IVelvet velvet, MV value) {
delete(velvet, mainEntity, mainEntity.keyOf(value));
}
private <K, V> void delete(IVelvet velvet, IEntityDef<K, V> entityDef, K key) {
@SuppressWarnings("unchecked")
FetcherEntity<K, V> entity = (FetcherEntity<K, V>) entities.get(entityDef);
if (entity != null) {
for (Entry<String, IMultiGetter<K, V, ?, ?>> entry : entity.multis.entrySet()) {
killChildren(velvet, entry.getValue(), key);
}
for (Entry<String, ISingleGetter<K, V, ?, ?>> entry : entity.singles.entrySet()) {
killChild(velvet, entry.getValue(), key);
}
for (ILinkDef<K, V, ?, ?> parent : entity.detaches) {
detachParent(velvet, parent, key);
}
}
entityDef.deleteKey(velvet, key);
}
/**
* Wrap an entity value into a DataWrap
* @param velvet velvet handle
* @param node entity value
* @return DataWrap
*/
public DataWrap<MK, MV> wrap(IVelvet velvet, MV node) {
return wrap(velvet, mainEntity, node);
}
private <K, V> DataWrap<K, V> wrap(IVelvet velvet, IEntityDef<K, V> entityDef, V node) {
DataWrap<K, V> wrap = new BatchBuilder<>(velvet, entityDef).make(node);
return wrap;
}
/**
* Wrap multiple entities into DataWraps
* @param velvet velvet handle
* @param nodes entity values
* @return DataWrap list
*/
public List<DataWrap<MK, MV>> wrapNodes(IVelvet velvet, List<MV> nodes) {
return wrapNodes(velvet, mainEntity, nodes);
}
private <K, V> List<DataWrap<K, V>> wrapNodes(IVelvet velvet, IEntityDef<K, V> entityDef, List<V> nodes) {
List<DataWrap<K, V>> wrapList = new BatchBuilder<>(velvet, entityDef).make(nodes);
return wrapList;
}
private <K, V, CK, CV> void killChild(IVelvet velvet, ISingleGetter<K, V, CK, CV> singleGetter, K key) {
if (singleGetter instanceof ISingleLinkDef<?, ?, ?, ?>) {
ISingleLinkDef<K, V, CK, CV> singleLinkDef = (ISingleLinkDef<K, V, CK, CV>) singleGetter;
CK childKey = singleLinkDef.key(velvet, key);
if (childKey != null) {
singleLinkDef.disconnectKeys(velvet, key, childKey);
delete(velvet, singleLinkDef.getChildEntity(), childKey);
}
}
}
private <K, V, CK, CV> void killChildren(IVelvet velvet, IMultiGetter<K, V, CK, CV> multiGetter, K key) {
if (multiGetter instanceof IMultiLinkDef<?, ?, ?, ?>) {
IMultiLinkDef<K, V, CK, CV> multiLinkDef = (IMultiLinkDef<K, V, CK, CV>) multiGetter;
List<CK> childKeys = multiLinkDef.keys(velvet, key);
for (CK childKey : childKeys) {
multiLinkDef.disconnectKeys(velvet, key, childKey);
}
for (CK childKey : childKeys) {
delete(velvet, multiLinkDef.getChildEntity(), childKey);
}
}
}
private <K, V, CK, CV> void detachParent(IVelvet velvet, ILinkDef<K, V, CK, CV> parentLinkDef, K key) {
IMultiGetter<K, V, CK, CV> multiGetter = Links.toMultiGetter(parentLinkDef);
List<CK> keys = multiGetter.keys(velvet, key);
for (CK parentKey : keys) {
parentLinkDef.disconnectKeys(velvet, key, parentKey);
}
}
private <K, V> Stream<DataWrap<K, V>> sortWraps(IEntityDef<K, V> entityDef, Stream<DataWrap<K, V>> stream) {
@SuppressWarnings("unchecked")
FetcherEntity<K, V> fetcher = (FetcherEntity<K, V>) entities.get(entityDef);
Comparator<DataWrap<K, V>> comparator = (fetcher == null) ? null : fetcher.sort;
if (comparator != null) {
stream = stream.sorted(comparator);
}
return stream;
}
public interface IIslandContext<K, V> {
V current();
K currentKey();
<CK, CV> CV node(IEntityDef<CK, CV> def);
<CK, CV> DataWrap<CK, CV> wrap(IEntityDef<CK, CV> def);
}
// TODO: refactor, add parents and make immutable
private static class Context<K, V> implements IIslandContext<K, V> {
private final IEntityDef<K, V> entityDef;
private final V current;
private final Map<IEntityDef<?, ?>, Object> nodes = new HashMap<>();
private final Map<IEntityDef<?, ?>, DataWrap<?, ?>> wraps = new HashMap<>();
private K currentKey;
private Context(Context<?, ?> parentContext, IEntityDef<K, V> entityDef, V node) {
this.current = node;
this.entityDef = entityDef;
nodes.put(entityDef, node);
}
private void setKey(K key) {
this.currentKey = key;
}
private void addWrap(DataWrap<K, V> wrap) {
wraps.put(entityDef, wrap);
}
@Override
public <CK, CV> CV node(IEntityDef<CK, CV> def) {
return def.getValueClass().cast(nodes.get(def));
}
@SuppressWarnings("unchecked")
@Override
public <CK, CV> DataWrap<CK, CV> wrap(IEntityDef<CK, CV> def) {
return (DataWrap<CK, CV>) wraps.get(def);
}
@Override
public V current() {
return current;
}
@Override
public K currentKey() {
return currentKey;
}
}
private class BatchBuilder<KK, VV> {
private IVelvet velvet;
private IEntityDef<KK, VV> startEntity;
private Map<ISingleGetter<?, ?, ?, ?>, Map<?, ?>> singles = new HashMap<>();
private Map<IMultiGetter<?, ?, ?, ?>, Map<?, List<?>>> multis = new HashMap<>();
private BatchBuilder(IVelvet velvet, IEntityDef<KK, VV> startEntity) {
this.velvet = velvet;
this.startEntity = startEntity;
}
private DataWrap<KK, VV> make(VV node) {
if (node == null) {
return null;
}
preFetch(startEntity, Arrays.asList(node));
DataWrap<KK, VV> wrap = wrap(startEntity, node, null);
return wrap;
}
private List<DataWrap<KK, VV>> make(List<VV> startNodes) {
preFetch(startEntity, startNodes);
Stream<DataWrap<KK, VV>> wrapstream = startNodes.stream().map(node -> wrap(startEntity, node, null));
wrapstream = sortWraps(startEntity, wrapstream);
return wrapstream.collect(Collectors.toList());
}
private <K, V> void preFetch(IEntityDef<K, V> entity, List<V> nodes) {
@SuppressWarnings("unchecked")
FetcherEntity<K, V> fentity = (FetcherEntity<K, V>) entities.get(entity);
if (fentity == null) {
return;
}
for (Entry<String, ? extends IMultiGetter<K, V, ?, ?>> entry : fentity.multis.entrySet()) {
IMultiGetter<K, V, ?, ?> multi = entry.getValue();
preFetchMulti(multi, nodes);
}
for (Entry<String, ? extends ISingleGetter<K, V, ?, ?>> entry : fentity.singles.entrySet()) {
ISingleGetter<K, V, ?, ?> single = entry.getValue();
preFetchSingle(single, nodes);
}
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private <K, V, CK, CV> void preFetchSingle(ISingleGetter<K, V, CK, CV> single, List<V> nodes) {
Map<K, CV> children = single.batchGet(velvet, nodes);
singles.computeIfAbsent(single, s -> new LinkedHashMap<>()).putAll((Map) children);
List<CV> childnodes = children.values().stream().filter(v -> v != null).collect(Collectors.toList());
preFetch(single.getChildEntity(), childnodes);
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private <K, V, CK, CV> void preFetchMulti(IMultiGetter<K, V, CK, CV> multi, List<V> nodes) {
Map<K, List<CV>> children = multi.batchGet(velvet, nodes);
multis.computeIfAbsent(multi, m -> new LinkedHashMap<>()).putAll((Map) children);
List<CV> childnodes = children.values().stream().flatMap(List::stream).collect(Collectors.toList());
preFetch(multi.getChildEntity(), childnodes);
}
private <K, V> DataWrap<K, V> wrap(IEntityDef<K, V> entityDef, V node, Context<?, ?> parentContext) {
Context<K, V> context = new Context<>(parentContext, entityDef, node);
K key = entityDef.keyOf(node);
DataWrap.Builder<K, V> wrapBuilder = new DataWrap.Builder<K, V>(node).key(key);
context.setKey(key);
@SuppressWarnings("unchecked")
FetcherEntity<K, V> entity = (FetcherEntity<K, V>) entities.get(entityDef);
if (entity == null) {
return wrapBuilder.build();
}
if (entity != null) {
for (Entry<String, ? extends IMultiGetter<K, V, ?, ?>> entry : entity.multis.entrySet()) {
IMultiGetter<K, V, ?, ?> multiLinkDef = entry.getValue();
List<? extends DataWrap<?, ?>> wrappedLinks = wrapChildren(context, key, multiLinkDef);
wrapBuilder.addList(entry.getKey(), wrappedLinks);
}
for (Entry<String, ? extends ISingleGetter<K, V, ?, ?>> entry : entity.singles.entrySet()) {
ISingleGetter<K, V, ?, ?> singleConn = entry.getValue();
DataWrap<?, ?> wrappedLink = wrapChild(context, key, singleConn);
if (wrappedLink != null)
wrapBuilder.add(entry.getKey(), wrappedLink);
}
for (Entry<String, IContextSingleGetter<K, V, ?>> entry : entity.attrs.entrySet()) {
Object link = entry.getValue().single(velvet, context);
if (link != null) {
wrapBuilder.attr(entry.getKey(), link);
}
}
DataWrap<K, V> wrap = wrapBuilder.build();
wrapBuilder = new DataWrap.Builder<>(wrap);
for (Entry<String, Function<DataWrap<K, V>, ?>> entry : entity.postattrs.entrySet()) {
wrapBuilder.attr(entry.getKey(), entry.getValue().apply(wrap));
}
}
DataWrap<K, V> wrap = wrapBuilder.build();
context.addWrap(wrap);
return wrap;
}
private <K, V, CK, CV> DataWrap<CK, CV> wrapChild(Context<K, V> context, K key, ISingleGetter<K, V, CK, CV> single) {
@SuppressWarnings("unchecked")
CV childValue = (CV) singles.get(single).get(key);
if (childValue == null)
return null;
return wrap(single.getChildEntity(), childValue, context);
}
private <K, V, CK, CV> List<DataWrap<CK, CV>> wrapChildren(Context<K, V> context, K key, IMultiGetter<K, V, CK, CV> multi) {
@SuppressWarnings("unchecked")
FetcherEntity<CK, CV> childFetcher = (FetcherEntity<CK, CV>) entities.get(multi.getChildEntity());
Comparator<DataWrap<CK, CV>> comparator = (childFetcher == null) ? null : childFetcher.sort;
@SuppressWarnings("unchecked")
List<CV> cvs = (List<CV>) multis.get(multi).get(key);
Stream<DataWrap<CK, CV>> stream = cvs.stream().map(o -> wrap(multi.getChildEntity(), o, context));
if (comparator != null) {
stream = stream.sorted(comparator);
}
return stream.collect(Collectors.toList());
}
}
} |
package org.concord.framework.otrunk.otcore;
public interface OTEnum extends OTType {
public Object getValue(int valueOrdinal);
public Object getValue(String valueName);
} |
package org.eclipse.imp.pdb.facts.type;
/*package*/ final class IntegerType extends NumberType {
private static final class InstanceKeeper {
public final static IntegerType sInstance= new IntegerType();
}
public static IntegerType getInstance() {
return InstanceKeeper.sInstance;
}
private IntegerType() {
super();
}
/**
* Should never need to be called; there should be only one instance of IntegerType
*/
@Override
public boolean equals(Object obj) {
return obj == IntegerType.getInstance();
}
@Override
public int hashCode() {
return 74843;
}
@Override
public String toString() {
return "int";
}
@Override
public <T,E extends Throwable> T accept(ITypeVisitor<T,E> visitor) throws E {
return visitor.visitInteger(this);
}
@Override
protected boolean isSupertypeOf(Type type) {
return type.isSubtypeOfInteger(this);
}
@Override
public Type lub(Type other) {
return other.lubWithInteger(this);
}
@Override
protected boolean isSubtypeOfInteger(Type type) {
return true;
}
@Override
protected Type lubWithInteger(Type type) {
return this;
}
} |
/*
* @author <a href="mailto:novotny@aei.mpg.de">Jason Novotny</a>
* @version $Id$
*/
package org.gridlab.gridsphere.layout;
import org.gridlab.gridsphere.portlet.*;
import org.gridlab.gridsphere.portlet.impl.SportletWindow;
import org.gridlab.gridsphere.portlet.impl.SportletURI;
import org.gridlab.gridsphere.portlet.service.PortletServiceException;
import org.gridlab.gridsphere.portletcontainer.ConcretePortlet;
import org.gridlab.gridsphere.portletcontainer.GridSphereProperties;
import org.gridlab.gridsphere.services.container.registry.PortletRegistryService;
import org.gridlab.gridsphere.services.container.registry.PortletRegistryServiceException;
import org.gridlab.gridsphere.services.container.registry.impl.PortletRegistryServiceImpl;
//import org.gridlab.gridsphere.services.container.caching.CachingService;
//import org.gridlab.gridsphere.services.container.caching.impl.PortletCachingServiceImpl;
import org.gridlab.gridsphere.event.ActionEvent;
import java.io.IOException;
import java.io.PrintWriter;
public class PortletFrame extends BasePortletComponent {
private static PortletLog log = org.gridlab.gridsphere.portlet.impl.SportletLog.getInstance(PortletFrame.class);
private String portletClass;
private String windowState = SportletWindow.NORMAL.toString();
private String portletMode = Portlet.Mode.VIEW.toString();
public PortletFrame() {
}
public void setConcretePortletClass(String portletClass) {
this.portletClass = portletClass;
}
public String getConcretePortletClass() {
return portletClass;
}
public void setWindowState(String windowState) {
this.windowState = windowState;
}
public String getWindowState() {
return windowState;
}
public void setPortletMode(String portletMode) {
this.portletMode = portletMode;
}
public String getPortletMode() {
return portletMode;
}
public void doRender(PortletContext ctx, PortletRequest req, PortletResponse res) throws PortletLayoutException, IOException {
super.doRender(ctx, req, res);
log.debug("in doRender()");
PortletRegistryService registryService = null;
//CachingService cachingService = null;
try {
//cachingService = PortletCachingServiceImpl.getInstance();
registryService = PortletRegistryServiceImpl.getInstance();
} catch (PortletRegistryServiceException e) {
log.error("Failed to get registry instance in PortletFrame: ", e);
throw new PortletLayoutException("Unable to get portlet instance");
}
if (border == null) border = new PortletBorder();
System.err.println("contacting registry for portlet: " + portletClass);
ConcretePortlet concretePortlet = registryService.getConcretePortlet(portletClass);
AbstractPortlet abstractPortlet = concretePortlet.getAbstractPortlet();
PortletSettings settings = concretePortlet.getSportletSettings();
// Set the portlet ID
req.setAttribute(GridSphereProperties.PORTLETID, settings.getConcretePortletID());
System.err.println("concrete " + settings.getConcretePortletID());
// Set the portlet window
PortletWindow p = SportletWindow.getInstance(windowState);
req.setAttribute(GridSphereProperties.PORTLETWINDOW, p);
// Set the portlet mode
String prevMode = req.getParameter(GridSphereProperties.PORTLETMODE);
if (prevMode == null) prevMode = Portlet.Mode.VIEW.toString();
req.getPortletSession().setAttribute(GridSphereProperties.PREVIOUSMODE, prevMode);
req.getPortletSession().setAttribute(GridSphereProperties.PORTLETMODE, portletMode);
// Create URI tags that can be used
PortletURI minimizedModeURI = res.createURI(PortletWindow.State.MINIMIZED);
PortletURI maximizedModeURI = res.createURI(PortletWindow.State.MAXIMIZED);
PortletURI closedModeURI = res.createURI(PortletWindow.State.CLOSED);
PortletURI restoreModeURI = res.createURI(PortletWindow.State.RESIZING);
PortletURI modeURI = res.createURI();
DefaultPortletAction dpa = new DefaultPortletAction(PortletAction.MODE);
modeURI.addAction(dpa);
modeURI.addParameter(GridSphereProperties.PORTLETMODE, Portlet.Mode.EDIT.toString());
String edit = modeURI.toString();
req.setAttribute(LayoutProperties.EDITURI, edit);
modeURI.addParameter(GridSphereProperties.PORTLETMODE, Portlet.Mode.HELP.toString());
String help = modeURI.toString();
req.setAttribute(LayoutProperties.HELPURI, help);
modeURI.addParameter(GridSphereProperties.PORTLETMODE, Portlet.Mode.CONFIGURE.toString());
String configure = modeURI.toString();
req.setAttribute(LayoutProperties.CONFIGUREURI, configure);
// set the portlet frame title
String title = settings.getTitle(req.getLocale(), req.getClient());
border.setTitle(title);
// render portlet frame
///// begin portlet frame
PrintWriter out = res.getWriter();
out.println("<table width=\"" + width + "%\" border=\"0\" cellspacing=\"2\" cellpadding=\"0\" bgcolor=\"#FFFFFF\"><tr><td>");
out.println("<table width=\"100%\" border=\"0\" cellspacing=\"2\" cellpadding=\"0\" bgcolor=\"#999999\">");
out.println("<tr><td width=\"100%\">");
border.doRender(ctx, req, res);
out.println("</td></tr>");
out.println("<tr><td valign=\"top\" align=\"left\"><table width=\"100%\" border=\"0\" cellspacing=\"1\" cellpadding=\"1\" bgcolor=");
out.println("\"" + bgColor + "\"<tr><td width=\"25%\" valign=\"center\">");
try {
if (abstractPortlet != null) {
abstractPortlet.service(req, res);
}
} catch (PortletException e) {
log.error("Failed invoking portlet service method: ", e);
throw new PortletLayoutException("Failed invoking portlet service method");
}
out.println("</tr></table></td></tr></table></td></tr></table>");
///// end portlet frame
}
public void doRenderFirst(PortletContext ctx, PortletRequest req, PortletResponse res) throws PortletLayoutException, IOException {
doRender(ctx, req, res);
}
public void doRenderLast(PortletContext ctx, PortletRequest req, PortletResponse res) throws PortletLayoutException, IOException {}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.