lang
stringclasses
1 value
license
stringclasses
13 values
stderr
stringlengths
0
350
commit
stringlengths
40
40
returncode
int64
0
128
repos
stringlengths
7
45.1k
new_contents
stringlengths
0
1.87M
new_file
stringlengths
6
292
old_contents
stringlengths
0
1.87M
message
stringlengths
6
9.26k
old_file
stringlengths
6
292
subject
stringlengths
0
4.45k
Java
apache-2.0
7799793881b259779155ce08175c71adcc890f2f
0
openbaton/generic-vnfm,openbaton/generic-vnfm
package org.openbaton.vnfm.generic; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonObject; import org.apache.commons.codec.binary.Base64; import org.openbaton.catalogue.mano.common.Event; import org.openbaton.catalogue.mano.common.Ip; import org.openbaton.catalogue.mano.common.LifecycleEvent; import org.openbaton.catalogue.mano.descriptor.VirtualDeploymentUnit; import org.openbaton.catalogue.mano.record.VNFCInstance; import org.openbaton.catalogue.mano.record.VNFRecordDependency; import org.openbaton.catalogue.mano.record.VirtualNetworkFunctionRecord; import org.openbaton.catalogue.nfvo.Action; import org.openbaton.catalogue.nfvo.ConfigurationParameter; import org.openbaton.catalogue.nfvo.DependencyParameters; import org.openbaton.catalogue.nfvo.Script; import org.openbaton.common.vnfm_sdk.amqp.AbstractVnfmSpringAmqp; import org.openbaton.common.vnfm_sdk.exception.VnfmSdkException; import org.openbaton.common.vnfm_sdk.utils.VnfmUtils; import org.openbaton.vnfm.generic.utils.EmsRegistrator; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import java.util.*; /** * Created by mob on 16.07.15. */ public class GenericVNFM extends AbstractVnfmSpringAmqp { @Autowired private EmsRegistrator emsRegistrator; private Gson parser = new GsonBuilder().setPrettyPrinting().create(); private String scriptPath; public static void main(String[] args) { SpringApplication.run(GenericVNFM.class); } @Override public VirtualNetworkFunctionRecord instantiate(VirtualNetworkFunctionRecord virtualNetworkFunctionRecord, Object scripts) throws Exception { log.info("Instantiation of VirtualNetworkFunctionRecord " + virtualNetworkFunctionRecord.getName()); if (scripts != null) this.saveScriptOnEms(virtualNetworkFunctionRecord, scripts); for (VirtualDeploymentUnit virtualDeploymentUnit : virtualNetworkFunctionRecord.getVdu()) for (VNFCInstance vnfcInstance : virtualDeploymentUnit.getVnfc_instance()) log.debug("VNFCInstance: " + vnfcInstance); log.info("Executed script for INSTANTIATE: \n" + "\n" + this.executeScriptsForEvent(virtualNetworkFunctionRecord, Event.INSTANTIATE)); log.debug("added parameter to config"); log.debug("CONFIGURATION: " + virtualNetworkFunctionRecord.getConfigurations()); ConfigurationParameter cp = new ConfigurationParameter(); cp.setConfKey("new_key"); cp.setValue("new_value"); virtualNetworkFunctionRecord.getConfigurations().getConfigurationParameters().add(cp); return virtualNetworkFunctionRecord; } @Override public void query() { } @Override public VirtualNetworkFunctionRecord scale(Action scaleInOrOut, VirtualNetworkFunctionRecord virtualNetworkFunctionRecord, VNFCInstance component, Object scripts, VNFRecordDependency dependency) throws Exception { if (scaleInOrOut.ordinal() == Action.SCALE_OUT.ordinal()) { log.info("Created VNFComponent"); saveScriptOnEms(component, scripts); log.debug("Executed scripts for event INSTANTIATE " + this.executeScriptsForEvent(virtualNetworkFunctionRecord, component, Event.INSTANTIATE)); if (dependency != null) log.debug("Executed scripts for event CONFIGURE " + this.executeScriptsForEvent(virtualNetworkFunctionRecord, component, Event.CONFIGURE, dependency)); if (VnfmUtils.getLifecycleEvent(virtualNetworkFunctionRecord.getLifecycle_event(), Event.START) != null) log.debug("Executed scripts for event START " + this.executeScriptsForEvent(virtualNetworkFunctionRecord, component, Event.START)); log.trace("HB_VERSION == " + virtualNetworkFunctionRecord.getHb_version()); return virtualNetworkFunctionRecord; } else {// log.debug("Executed scripts for event SCALE_IN " + this.executeScriptsForEvent(virtualNetworkFunctionRecord, component, Event.SCALE_IN)); return virtualNetworkFunctionRecord; } } private List<String> executeScriptsForEvent(VirtualNetworkFunctionRecord virtualNetworkFunctionRecord, VNFCInstance vnfcInstance, Event event) throws Exception { Map<String, String> env = getMap(virtualNetworkFunctionRecord); List<String> res = new ArrayList<>(); LifecycleEvent le = VnfmUtils.getLifecycleEvent(virtualNetworkFunctionRecord.getLifecycle_event(), event); if (le != null) { log.trace("The number of scripts for " + virtualNetworkFunctionRecord.getName() + " are: " + le.getLifecycle_events()); for (String script : le.getLifecycle_events()) { log.info("Sending script: " + script + " to VirtualNetworkFunctionRecord: " + virtualNetworkFunctionRecord.getName()); Map<String, String> tempEnv = new HashMap<>(); for (Ip ip : vnfcInstance.getIps()) { log.debug("Adding net: " + ip.getNetName() + " with value: " + ip.getIp()); tempEnv.put(ip.getNetName(), ip.getIp()); } log.debug("adding floatingIp: " + vnfcInstance.getFloatingIps()); for (Ip fip : vnfcInstance.getFloatingIps()) { tempEnv.put(fip.getNetName() + "_floatingIp", fip.getIp()); } tempEnv.put("hostname", vnfcInstance.getHostname()); env.putAll(tempEnv); log.info("Environment Variables are: " + env); String command = getJsonObject("EXECUTE", script, env).toString(); res.add(executeActionOnEMS(vnfcInstance.getHostname(), command)); for (String key : tempEnv.keySet()) { env.remove(key); } } } return res; } private List<String> executeScriptsForEvent(VirtualNetworkFunctionRecord virtualNetworkFunctionRecord, VNFCInstance vnfcInstance, Event event, String cause) throws Exception { Map<String, String> env = getMap(virtualNetworkFunctionRecord); List<String> res = new LinkedList<>(); LifecycleEvent le = VnfmUtils.getLifecycleEvent(virtualNetworkFunctionRecord.getLifecycle_event(), event); if (le != null) { log.trace("The number of scripts for " + virtualNetworkFunctionRecord.getName() + " are: " + le.getLifecycle_events()); for (String script : le.getLifecycle_events()) { log.info("Sending script: " + script + " to VirtualNetworkFunctionRecord: " + virtualNetworkFunctionRecord.getName()); Map<String, String> tempEnv = new HashMap<>(); for (Ip ip : vnfcInstance.getIps()) { log.debug("Adding net: " + ip.getNetName() + " with value: " + ip.getIp()); tempEnv.put(ip.getNetName(), ip.getIp()); } log.debug("adding floatingIp: " + vnfcInstance.getFloatingIps()); for (Ip fip : vnfcInstance.getFloatingIps()) { tempEnv.put(fip.getNetName() + "_floatingIp", fip.getIp()); } tempEnv.put("hostname", vnfcInstance.getHostname()); //Add cause to the environment variables tempEnv.put("cause", cause); env.putAll(tempEnv); log.info("Environment Variables are: " + env); String command = getJsonObject("EXECUTE", script, env).toString(); res.add(executeActionOnEMS(vnfcInstance.getHostname(), command)); for (String key : tempEnv.keySet()) { env.remove(key); } } } return res; } private List<String> executeScriptsForEvent(VirtualNetworkFunctionRecord virtualNetworkFunctionRecord, VNFCInstance vnfcInstance, Event event, VNFRecordDependency dependency) throws Exception { Map<String, String> env = getMap(virtualNetworkFunctionRecord); List<String> res = new ArrayList<>(); LifecycleEvent le = VnfmUtils.getLifecycleEvent(virtualNetworkFunctionRecord.getLifecycle_event(), event); log.trace("The number of scripts for " + virtualNetworkFunctionRecord.getName() + " are: " + le.getLifecycle_events()); log.debug("DEPENDENCY IS: " + dependency); if (le != null) { for (String script : le.getLifecycle_events()) { String type = script.substring(0, script.indexOf("_")); log.debug("There are " + dependency.getVnfcParameters().get(type).getParameters().size() + " VNFCInstanceForeign"); for (String vnfcForeignId : dependency.getVnfcParameters().get(type).getParameters().keySet()) { log.info("Running script: " + script + " for VNFCInstance foreign id " + vnfcForeignId); log.info("Sending command: " + script + " to adding relation with type: " + type + " from VirtualNetworkFunctionRecord " + virtualNetworkFunctionRecord.getName()); Map<String, String> tempEnv = new HashMap<>(); //Adding own ips for (Ip ip : vnfcInstance.getIps()) { log.debug("Adding net: " + ip.getNetName() + " with value: " + ip.getIp()); tempEnv.put(ip.getNetName(), ip.getIp()); } //Adding own floating ip log.debug("adding floatingIp: " + vnfcInstance.getFloatingIps()); for (Ip fip : vnfcInstance.getFloatingIps()) { tempEnv.put(fip.getNetName() + "_floatingIp", fip.getIp()); } //Adding foreign parameters such as ip if (script.contains("_")) { //Adding foreign parameters such as ip Map<String, String> parameters = dependency.getParameters().get(type).getParameters(); for (Map.Entry<String, String> param : parameters.entrySet()) tempEnv.put(type + "_" + param.getKey(), param.getValue()); Map<String, String> parametersVNFC = dependency.getVnfcParameters().get(type).getParameters().get(vnfcForeignId).getParameters(); for (Map.Entry<String, String> param : parametersVNFC.entrySet()) tempEnv.put(type + "_" + param.getKey(), param.getValue()); } tempEnv.put("hostname", vnfcInstance.getHostname()); env.putAll(tempEnv); log.info("Environment Variables are: " + env); String command = getJsonObject("EXECUTE", script, tempEnv).toString(); res.add(executeActionOnEMS(vnfcInstance.getHostname(), command)); for (String key : tempEnv.keySet()) { env.remove(key); } } } } return res; } @Override public void checkInstantiationFeasibility() { } @Override public VirtualNetworkFunctionRecord heal(VirtualNetworkFunctionRecord virtualNetworkFunctionRecord, VNFCInstance component, String cause) throws Exception { if (VnfmUtils.getLifecycleEvent(virtualNetworkFunctionRecord.getLifecycle_event(), Event.HEAL) != null) { if (VnfmUtils.getLifecycleEvent(virtualNetworkFunctionRecord.getLifecycle_event(), Event.HEAL).getLifecycle_events() != null) { log.debug("Heal method started"); log.info("-----------------------------------------------------------------------"); log.debug("Executed scripts for event HEAL: " + this.executeScriptsForEvent(virtualNetworkFunctionRecord, component, Event.HEAL, cause)); log.info("-----------------------------------------------------------------------"); } } return virtualNetworkFunctionRecord; } @Override public void updateSoftware() { } @Override public void upgradeSoftware() { } @Override public VirtualNetworkFunctionRecord modify(VirtualNetworkFunctionRecord virtualNetworkFunctionRecord, VNFRecordDependency dependency) throws Exception { log.trace("VirtualNetworkFunctionRecord VERSION is: " + virtualNetworkFunctionRecord.getHb_version()); log.info("executing modify for VNFR: " + virtualNetworkFunctionRecord.getName()); log.debug("Got dependency: " + dependency); log.debug("Parameters are: "); for (Map.Entry<String, DependencyParameters> entry : dependency.getParameters().entrySet()) { log.debug("Source type: " + entry.getKey()); log.debug("Parameters: " + entry.getValue().getParameters()); } if (VnfmUtils.getLifecycleEvent(virtualNetworkFunctionRecord.getLifecycle_event(), Event.CONFIGURE) != null) { log.debug("LifeCycle events: " + VnfmUtils.getLifecycleEvent(virtualNetworkFunctionRecord.getLifecycle_event(), Event.CONFIGURE).getLifecycle_events()); log.info("-----------------------------------------------------------------------"); log.info("Result script for CONFIGURE: \n\n" + this.executeScriptsForEvent(virtualNetworkFunctionRecord, Event.CONFIGURE, dependency)); log.info("-----------------------------------------------------------------------"); } else { log.debug("No LifeCycle events for Event.CONFIGURE"); } return virtualNetworkFunctionRecord; } //When the EMS reveive a script which terminate the vnf, the EMS is still running. //Once the vnf is terminated NFVO requests deletion of resources (MANO B.5) and the EMS will be terminated. @Override public VirtualNetworkFunctionRecord terminate(VirtualNetworkFunctionRecord virtualNetworkFunctionRecord) throws Exception { log.debug("Termination of VNF: " + virtualNetworkFunctionRecord.getName()); if (VnfmUtils.getLifecycleEvent(virtualNetworkFunctionRecord.getLifecycle_event(), Event.TERMINATE) != null) { log.info("Executed script: " + this.executeScriptsForEvent(virtualNetworkFunctionRecord, Event.TERMINATE)); } return virtualNetworkFunctionRecord; } @Override public void handleError(VirtualNetworkFunctionRecord virtualNetworkFunctionRecord) { log.error("Received Error for VNFR " + virtualNetworkFunctionRecord.getName()); } @Override protected void fillSpecificProvides(VirtualNetworkFunctionRecord virtualNetworkFunctionRecord) { for (ConfigurationParameter configurationParameter : virtualNetworkFunctionRecord.getProvides().getConfigurationParameters()) { if (!configurationParameter.getConfKey().startsWith("#nfvo:")) { configurationParameter.setValue("" + ((int) (Math.random() * 100))); log.debug("Setting: " + configurationParameter.getConfKey() + " with value: " + configurationParameter.getValue()); } } } @Override public VirtualNetworkFunctionRecord start(VirtualNetworkFunctionRecord virtualNetworkFunctionRecord) throws Exception { log.debug("Starting vnfr: " + virtualNetworkFunctionRecord.getName()); if (VnfmUtils.getLifecycleEvent(virtualNetworkFunctionRecord.getLifecycle_event(), Event.START) != null) { if (VnfmUtils.getLifecycleEvent(virtualNetworkFunctionRecord.getLifecycle_event(), Event.START).getLifecycle_events() != null) log.info("Executed script: " + this.executeScriptsForEvent(virtualNetworkFunctionRecord, Event.START)); } return virtualNetworkFunctionRecord; } @Override public VirtualNetworkFunctionRecord configure(VirtualNetworkFunctionRecord virtualNetworkFunctionRecord) throws Exception { return virtualNetworkFunctionRecord; } @Override public void NotifyChange() { } @Override protected void checkEmsStarted(String hostname) { if (!emsRegistrator.getHostnames().contains(hostname)) throw new RuntimeException("no ems for hostame: " + hostname); } private String executeActionOnEMS(String vduHostname, String command) throws Exception { log.trace("Sending message and waiting: " + command + " to " + vduHostname); log.info("Waiting answer from EMS - " + vduHostname); String response = vnfmHelper.sendAndReceive(command, "vnfm." + vduHostname + ".actions"); log.debug("Received from EMS (" + vduHostname + "): " + response); if (response == null) { throw new NullPointerException("Response from EMS is null"); } JsonObject jsonObject = parser.fromJson(response, JsonObject.class); if (jsonObject.get("status").getAsInt() == 0) { try { log.debug("Output from EMS (" + vduHostname + ") is: " + jsonObject.get("output")); } catch (Exception e) { e.printStackTrace(); throw e; } } else { log.error(jsonObject.get("err").getAsString()); throw new VnfmSdkException("EMS (" + vduHostname + ") had the following error: " + jsonObject.get("err").getAsString()); } return response; } public Iterable<String> executeScriptsForEvent(VirtualNetworkFunctionRecord virtualNetworkFunctionRecord, Event event) throws Exception {//TODO make it parallel Map<String, String> env = getMap(virtualNetworkFunctionRecord); List<String> res = new ArrayList<>(); LifecycleEvent le = VnfmUtils.getLifecycleEvent(virtualNetworkFunctionRecord.getLifecycle_event(), event); if (le != null) { log.trace("The number of scripts for " + virtualNetworkFunctionRecord.getName() + " are: " + le.getLifecycle_events()); for (String script : le.getLifecycle_events()) { log.info("Sending script: " + script + " to VirtualNetworkFunctionRecord: " + virtualNetworkFunctionRecord.getName()); for (VirtualDeploymentUnit vdu : virtualNetworkFunctionRecord.getVdu()) { for (VNFCInstance vnfcInstance : vdu.getVnfc_instance()) { Map<String, String> tempEnv = new HashMap<>(); for (Ip ip : vnfcInstance.getIps()) { log.debug("Adding net: " + ip.getNetName() + " with value: " + ip.getIp()); tempEnv.put(ip.getNetName(), ip.getIp()); } log.debug("adding floatingIp: " + vnfcInstance.getFloatingIps()); for (Ip fip : vnfcInstance.getFloatingIps()) { tempEnv.put(fip.getNetName() + "_floatingIp", fip.getIp()); } tempEnv.put("hostname", vnfcInstance.getHostname()); env.putAll(tempEnv); log.info("Environment Variables are: " + env); String command = getJsonObject("EXECUTE", script, env).toString(); res.add(executeActionOnEMS(vnfcInstance.getHostname(), command)); for (String key : tempEnv.keySet()) { env.remove(key); } } } } } return res; } public List<String> executeScriptsForEvent(VirtualNetworkFunctionRecord virtualNetworkFunctionRecord, Event event, VNFRecordDependency dependency) throws Exception { Map<String, String> env = getMap(virtualNetworkFunctionRecord); LifecycleEvent le = VnfmUtils.getLifecycleEvent(virtualNetworkFunctionRecord.getLifecycle_event(), event); List<String> res = new ArrayList<>(); if (le != null) { for (String script : le.getLifecycle_events()) { String type = null; if (script.contains("_")) { type = script.substring(0, script.indexOf("_")); log.info("Sending command: " + script + " to adding relation with type: " + type + " from VirtualNetworkFunctionRecord " + virtualNetworkFunctionRecord.getName()); } for (VirtualDeploymentUnit vdu : virtualNetworkFunctionRecord.getVdu()) { for (VNFCInstance vnfcInstance : vdu.getVnfc_instance()) { log.debug("VNFCParameters are: " + dependency.getVnfcParameters()); if (dependency.getVnfcParameters().get(type) != null) for (String vnfcId : dependency.getVnfcParameters().get(type).getParameters().keySet()) { Map<String, String> tempEnv = new HashMap<>(); //Adding own ips for (Ip ip : vnfcInstance.getIps()) { log.debug("Adding net: " + ip.getNetName() + " with value: " + ip.getIp()); tempEnv.put(ip.getNetName(), ip.getIp()); } //Adding own floating ip log.debug("adding floatingIp: " + vnfcInstance.getFloatingIps()); for (Ip fip : vnfcInstance.getFloatingIps()) { tempEnv.put(fip.getNetName() + "_floatingIp", fip.getIp()); } if (script.contains("_")) { //Adding foreign parameters such as ip Map<String, String> parameters = dependency.getParameters().get(type).getParameters(); for (Map.Entry<String, String> param : parameters.entrySet()) tempEnv.put(type + "_" + param.getKey(), param.getValue()); Map<String, String> parametersVNFC = dependency.getVnfcParameters().get(type).getParameters().get(vnfcId).getParameters(); for (Map.Entry<String, String> param : parametersVNFC.entrySet()) tempEnv.put(type + "_" + param.getKey(), param.getValue()); } tempEnv.put("hostname", vnfcInstance.getHostname()); env.putAll(tempEnv); log.info("Environment Variables are: " + env); String command = getJsonObject("EXECUTE", script, env).toString(); res.add(executeActionOnEMS(vnfcInstance.getHostname(), command)); for (String key : tempEnv.keySet()) { env.remove(key); } } } } } } return res; } public void saveScriptOnEms(VirtualNetworkFunctionRecord virtualNetworkFunctionRecord, Object scripts) throws Exception { log.debug("Scripts are: " + scripts.getClass().getName()); if (scripts instanceof String) { String scriptLink = (String) scripts; log.debug("Scripts are: " + scriptLink); JsonObject jsonMessage = getJsonObject("CLONE_SCRIPTS", scriptLink, scriptPath); for (VirtualDeploymentUnit virtualDeploymentUnit : virtualNetworkFunctionRecord.getVdu()) { for (VNFCInstance vnfcInstance : virtualDeploymentUnit.getVnfc_instance()) { executeActionOnEMS(vnfcInstance.getHostname(), jsonMessage.toString()); } } } else if (scripts instanceof Set) { Set<Script> scriptSet = (Set<Script>) scripts; for (Script script : scriptSet) { log.debug("Sending script encoded base64 "); String base64String = Base64.encodeBase64String(script.getPayload()); log.trace("The base64 string is: " + base64String); JsonObject jsonMessage = getJsonObjectForScript("SAVE_SCRIPTS", base64String, script.getName(), scriptPath); for (VirtualDeploymentUnit virtualDeploymentUnit : virtualNetworkFunctionRecord.getVdu()) { for (VNFCInstance vnfcInstance : virtualDeploymentUnit.getVnfc_instance()) { executeActionOnEMS(vnfcInstance.getHostname(), jsonMessage.toString()); } } } } } public void saveScriptOnEms(VNFCInstance component, Object scripts) throws Exception { log.debug("Scripts are: " + scripts.getClass().getName()); if (scripts instanceof String) { String scriptLink = (String) scripts; log.debug("Scripts are: " + scriptLink); JsonObject jsonMessage = getJsonObject("CLONE_SCRIPTS", scriptLink, scriptPath); executeActionOnEMS(component.getHostname(), jsonMessage.toString()); } else if (scripts instanceof Set) { Set<Script> scriptSet = (Set<Script>) scripts; for (Script script : scriptSet) { log.debug("Sending script encoded base64 "); String base64String = Base64.encodeBase64String(script.getPayload()); log.trace("The base64 string is: " + base64String); JsonObject jsonMessage = getJsonObjectForScript("SAVE_SCRIPTS", base64String, script.getName(), scriptPath); executeActionOnEMS(component.getHostname(), jsonMessage.toString()); } } } private JsonObject getJsonObject(String action, String payload, String scriptPath) { JsonObject jsonMessage = new JsonObject(); jsonMessage.addProperty("action", action); jsonMessage.addProperty("payload", payload); jsonMessage.addProperty("script-path", scriptPath); return jsonMessage; } private JsonObject getJsonObject(String action, String payload, Map<String, String> dependencyParameters) { JsonObject jsonMessage = new JsonObject(); jsonMessage.addProperty("action", action); jsonMessage.addProperty("payload", payload); jsonMessage.add("env", parser.fromJson(parser.toJson(dependencyParameters), JsonObject.class)); return jsonMessage; } private JsonObject getJsonObjectForScript(String save_scripts, String payload, String name, String scriptPath) { JsonObject jsonMessage = new JsonObject(); jsonMessage.addProperty("action", save_scripts); jsonMessage.addProperty("payload", payload); jsonMessage.addProperty("name", name); jsonMessage.addProperty("script-path", scriptPath); return jsonMessage; } private Map<String, String> getMap(VirtualNetworkFunctionRecord virtualNetworkFunctionRecord) { Map<String, String> res = new HashMap<>(); for (ConfigurationParameter configurationParameter : virtualNetworkFunctionRecord.getProvides().getConfigurationParameters()) res.put(configurationParameter.getConfKey(), configurationParameter.getValue()); for (ConfigurationParameter configurationParameter : virtualNetworkFunctionRecord.getConfigurations().getConfigurationParameters()) { res.put(configurationParameter.getConfKey(), configurationParameter.getValue()); } return res; } @Override protected void setup() { super.setup(); this.scriptPath = properties.getProperty("script-path", "/opt/openbaton/scripts"); } }
src/main/java/org/openbaton/vnfm/generic/GenericVNFM.java
package org.openbaton.vnfm.generic; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonObject; import org.apache.commons.codec.binary.Base64; import org.openbaton.catalogue.mano.common.Event; import org.openbaton.catalogue.mano.common.Ip; import org.openbaton.catalogue.mano.common.LifecycleEvent; import org.openbaton.catalogue.mano.descriptor.VirtualDeploymentUnit; import org.openbaton.catalogue.mano.record.VNFCInstance; import org.openbaton.catalogue.mano.record.VNFRecordDependency; import org.openbaton.catalogue.mano.record.VirtualNetworkFunctionRecord; import org.openbaton.catalogue.nfvo.Action; import org.openbaton.catalogue.nfvo.ConfigurationParameter; import org.openbaton.catalogue.nfvo.DependencyParameters; import org.openbaton.catalogue.nfvo.Script; import org.openbaton.common.vnfm_sdk.amqp.AbstractVnfmSpringAmqp; import org.openbaton.common.vnfm_sdk.exception.VnfmSdkException; import org.openbaton.common.vnfm_sdk.utils.VnfmUtils; import org.openbaton.vnfm.generic.utils.EmsRegistrator; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import java.util.*; /** * Created by mob on 16.07.15. */ public class GenericVNFM extends AbstractVnfmSpringAmqp { @Autowired private EmsRegistrator emsRegistrator; private Gson parser = new GsonBuilder().setPrettyPrinting().create(); private String scriptPath; public static void main(String[] args) { SpringApplication.run(GenericVNFM.class); } @Override public VirtualNetworkFunctionRecord instantiate(VirtualNetworkFunctionRecord virtualNetworkFunctionRecord, Object scripts) throws Exception { log.info("Instantiation of VirtualNetworkFunctionRecord " + virtualNetworkFunctionRecord.getName()); if (scripts != null) this.saveScriptOnEms(virtualNetworkFunctionRecord, scripts); for (VirtualDeploymentUnit virtualDeploymentUnit : virtualNetworkFunctionRecord.getVdu()) for (VNFCInstance vnfcInstance : virtualDeploymentUnit.getVnfc_instance()) log.debug("VNFCInstance: " + vnfcInstance); log.info("Executed script for INSTANTIATE: \n" + "\n" + this.executeScriptsForEvent(virtualNetworkFunctionRecord, Event.INSTANTIATE)); log.debug("added parameter to config"); log.debug("CONFIGURATION: " + virtualNetworkFunctionRecord.getConfigurations()); ConfigurationParameter cp = new ConfigurationParameter(); cp.setConfKey("new_key"); cp.setValue("new_value"); virtualNetworkFunctionRecord.getConfigurations().getConfigurationParameters().add(cp); return virtualNetworkFunctionRecord; } @Override public void query() { } @Override public VirtualNetworkFunctionRecord scale(Action scaleInOrOut, VirtualNetworkFunctionRecord virtualNetworkFunctionRecord, VNFCInstance component, Object scripts, VNFRecordDependency dependency) throws Exception { if (scaleInOrOut.ordinal() == Action.SCALE_OUT.ordinal()) { log.info("Created VNFComponent"); saveScriptOnEms(component, scripts); log.debug("Executed scripts for event INSTANTIATE " + this.executeScriptsForEvent(virtualNetworkFunctionRecord, component, Event.INSTANTIATE)); if (dependency != null) log.debug("Executed scripts for event CONFIGURE " + this.executeScriptsForEvent(virtualNetworkFunctionRecord, component, Event.CONFIGURE, dependency)); if (VnfmUtils.getLifecycleEvent(virtualNetworkFunctionRecord.getLifecycle_event(), Event.START) != null) log.debug("Executed scripts for event START " + this.executeScriptsForEvent(virtualNetworkFunctionRecord, component, Event.START)); log.trace("HB_VERSION == " + virtualNetworkFunctionRecord.getHb_version()); return virtualNetworkFunctionRecord; } else {// log.debug("Executed scripts for event SCALE_IN " + this.executeScriptsForEvent(virtualNetworkFunctionRecord, component, Event.SCALE_IN)); return virtualNetworkFunctionRecord; } } private List<String> executeScriptsForEvent(VirtualNetworkFunctionRecord virtualNetworkFunctionRecord, VNFCInstance vnfcInstance, Event event) throws Exception { Map<String, String> env = getMap(virtualNetworkFunctionRecord); List<String> res = new ArrayList<>(); LifecycleEvent le = VnfmUtils.getLifecycleEvent(virtualNetworkFunctionRecord.getLifecycle_event(), event); if (le != null) { log.trace("The number of scripts for " + virtualNetworkFunctionRecord.getName() + " are: " + le.getLifecycle_events()); for (String script : le.getLifecycle_events()) { log.info("Sending script: " + script + " to VirtualNetworkFunctionRecord: " + virtualNetworkFunctionRecord.getName()); Map<String, String> tempEnv = new HashMap<>(); for (Ip ip : vnfcInstance.getIps()) { log.debug("Adding net: " + ip.getNetName() + " with value: " + ip.getIp()); tempEnv.put(ip.getNetName(), ip.getIp()); } log.debug("adding floatingIp: " + vnfcInstance.getFloatingIps()); for (Ip fip : vnfcInstance.getFloatingIps()) { tempEnv.put(fip.getNetName() + "_floatingIp", fip.getIp()); } tempEnv.put("hostname", vnfcInstance.getHostname()); env.putAll(tempEnv); log.info("Environment Variables are: " + env); String command = getJsonObject("EXECUTE", script, env).toString(); res.add(executeActionOnEMS(vnfcInstance.getHostname(), command)); for (String key : tempEnv.keySet()) { env.remove(key); } } } return res; } private List<String> executeScriptsForEvent(VirtualNetworkFunctionRecord virtualNetworkFunctionRecord, VNFCInstance vnfcInstance, Event event,String cause) throws Exception { Map<String, String> env = getMap(virtualNetworkFunctionRecord); List<String> res = new LinkedList<>(); LifecycleEvent le = VnfmUtils.getLifecycleEvent(virtualNetworkFunctionRecord.getLifecycle_event(), event); if (le != null) { log.trace("The number of scripts for " + virtualNetworkFunctionRecord.getName() + " are: " + le.getLifecycle_events()); for (String script : le.getLifecycle_events()) { log.info("Sending script: " + script + " to VirtualNetworkFunctionRecord: " + virtualNetworkFunctionRecord.getName()); Map<String, String> tempEnv = new HashMap<>(); for (Ip ip : vnfcInstance.getIps()) { log.debug("Adding net: " + ip.getNetName() + " with value: " + ip.getIp()); tempEnv.put(ip.getNetName(), ip.getIp()); } log.debug("adding floatingIp: " + vnfcInstance.getFloatingIps()); for (Ip fip : vnfcInstance.getFloatingIps()) { tempEnv.put(fip.getNetName() + "_floatingIp", fip.getIp()); } tempEnv.put("hostname", vnfcInstance.getHostname()); //Add cause to the environment variables tempEnv.put("cause",cause); env.putAll(tempEnv); log.info("Environment Variables are: " + env); String command = getJsonObject("EXECUTE", script, env).toString(); res.add(executeActionOnEMS(vnfcInstance.getHostname(), command)); for (String key : tempEnv.keySet()) { env.remove(key); } } } return res; } private List<String> executeScriptsForEvent(VirtualNetworkFunctionRecord virtualNetworkFunctionRecord, VNFCInstance vnfcInstance, Event event, VNFRecordDependency dependency) throws Exception { Map<String, String> env = getMap(virtualNetworkFunctionRecord); List<String> res = new ArrayList<>(); LifecycleEvent le = VnfmUtils.getLifecycleEvent(virtualNetworkFunctionRecord.getLifecycle_event(), event); log.trace("The number of scripts for " + virtualNetworkFunctionRecord.getName() + " are: " + le.getLifecycle_events()); log.debug("DEPENDENCY IS: " + dependency); if (le != null) { for (String script : le.getLifecycle_events()) { String type = script.substring(0, script.indexOf("_")); log.debug("There are " + dependency.getVnfcParameters().get(type).getParameters().size() + " VNFCInstanceForeign"); for (String vnfcForeignId : dependency.getVnfcParameters().get(type).getParameters().keySet()) { log.info("Running script: " + script + " for VNFCInstance foreign id " + vnfcForeignId); log.info("Sending command: " + script + " to adding relation with type: " + type + " from VirtualNetworkFunctionRecord " + virtualNetworkFunctionRecord.getName()); Map<String, String> tempEnv = new HashMap<>(); //Adding own ips for (Ip ip : vnfcInstance.getIps()) { log.debug("Adding net: " + ip.getNetName() + " with value: " + ip.getIp()); tempEnv.put(ip.getNetName(), ip.getIp()); } //Adding own floating ip log.debug("adding floatingIp: " + vnfcInstance.getFloatingIps()); for (Ip fip : vnfcInstance.getFloatingIps()) { tempEnv.put(fip.getNetName() + "_floatingIp", fip.getIp()); } //Adding foreign parameters such as ip if (script.contains("_")) { //Adding foreign parameters such as ip Map<String, String> parameters = dependency.getParameters().get(type).getParameters(); for (Map.Entry<String, String> param : parameters.entrySet()) tempEnv.put(type + "_" + param.getKey(), param.getValue()); Map<String, String> parametersVNFC = dependency.getVnfcParameters().get(type).getParameters().get(vnfcForeignId).getParameters(); for (Map.Entry<String, String> param : parametersVNFC.entrySet()) tempEnv.put(type + "_" + param.getKey(), param.getValue()); } tempEnv.put("hostname", vnfcInstance.getHostname()); env.putAll(tempEnv); log.info("Environment Variables are: " + env); String command = getJsonObject("EXECUTE", script, tempEnv).toString(); res.add(executeActionOnEMS(vnfcInstance.getHostname(), command)); for (String key : tempEnv.keySet()) { env.remove(key); } } } } return res; } @Override public void checkInstantiationFeasibility() { } @Override public VirtualNetworkFunctionRecord heal(VirtualNetworkFunctionRecord virtualNetworkFunctionRecord, VNFCInstance component, String cause) throws Exception { if (VnfmUtils.getLifecycleEvent(virtualNetworkFunctionRecord.getLifecycle_event(), Event.HEAL) != null) { if (VnfmUtils.getLifecycleEvent(virtualNetworkFunctionRecord.getLifecycle_event(), Event.HEAL).getLifecycle_events() != null) { log.debug("Heal method started"); log.info("-----------------------------------------------------------------------"); log.debug("Executed scripts for event HEAL: " + this.executeScriptsForEvent(virtualNetworkFunctionRecord, component, Event.HEAL,cause)); log.info("-----------------------------------------------------------------------"); } } return virtualNetworkFunctionRecord; } @Override public void updateSoftware() { } @Override public void upgradeSoftware() { } @Override public VirtualNetworkFunctionRecord modify(VirtualNetworkFunctionRecord virtualNetworkFunctionRecord, VNFRecordDependency dependency) throws Exception { log.debug("VirtualNetworkFunctionRecord VERSION is: " + virtualNetworkFunctionRecord.getHb_version()); log.debug("VirtualNetworkFunctionRecord NAME is: " + virtualNetworkFunctionRecord.getName()); log.debug("Got dependency: " + dependency); log.debug("Parameters are: "); for (Map.Entry<String, DependencyParameters> entry : dependency.getParameters().entrySet()) { log.debug("Source type: " + entry.getKey()); log.debug("Parameters: " + entry.getValue().getParameters()); } if (VnfmUtils.getLifecycleEvent(virtualNetworkFunctionRecord.getLifecycle_event(), Event.CONFIGURE) != null) { log.debug("LifeCycle events: " + VnfmUtils.getLifecycleEvent(virtualNetworkFunctionRecord.getLifecycle_event(), Event.CONFIGURE).getLifecycle_events()); log.info("-----------------------------------------------------------------------"); log.info("Result script for CONFIGURE: \n\n" + this.executeScriptsForEvent(virtualNetworkFunctionRecord, Event.CONFIGURE, dependency)); log.info("-----------------------------------------------------------------------"); } else { log.debug("No LifeCycle events for Event.CONFIGURE"); } return virtualNetworkFunctionRecord; } //When the EMS reveive a script which terminate the vnf, the EMS is still running. //Once the vnf is terminated NFVO requests deletion of resources (MANO B.5) and the EMS will be terminated. @Override public VirtualNetworkFunctionRecord terminate(VirtualNetworkFunctionRecord virtualNetworkFunctionRecord) throws Exception { log.debug("Termination of VNF: " + virtualNetworkFunctionRecord.getName()); if (VnfmUtils.getLifecycleEvent(virtualNetworkFunctionRecord.getLifecycle_event(), Event.TERMINATE) != null) { log.info("Executed script: " + this.executeScriptsForEvent(virtualNetworkFunctionRecord, Event.TERMINATE)); } return virtualNetworkFunctionRecord; } @Override public void handleError(VirtualNetworkFunctionRecord virtualNetworkFunctionRecord) { log.error("Received Error for VNFR " + virtualNetworkFunctionRecord.getName()); } @Override protected void fillSpecificProvides(VirtualNetworkFunctionRecord virtualNetworkFunctionRecord) { for (ConfigurationParameter configurationParameter : virtualNetworkFunctionRecord.getProvides().getConfigurationParameters()) { if (!configurationParameter.getConfKey().startsWith("#nfvo:")) { configurationParameter.setValue("" + ((int) (Math.random() * 100))); log.debug("Setting: " + configurationParameter.getConfKey() + " with value: " + configurationParameter.getValue()); } } } @Override public VirtualNetworkFunctionRecord start(VirtualNetworkFunctionRecord virtualNetworkFunctionRecord) throws Exception { log.debug("Starting vnfr: " + virtualNetworkFunctionRecord.getName()); if (VnfmUtils.getLifecycleEvent(virtualNetworkFunctionRecord.getLifecycle_event(), Event.START) != null) { if (VnfmUtils.getLifecycleEvent(virtualNetworkFunctionRecord.getLifecycle_event(), Event.START).getLifecycle_events() != null) log.info("Executed script: " + this.executeScriptsForEvent(virtualNetworkFunctionRecord, Event.START)); } return virtualNetworkFunctionRecord; } @Override public VirtualNetworkFunctionRecord configure(VirtualNetworkFunctionRecord virtualNetworkFunctionRecord) throws Exception { return virtualNetworkFunctionRecord; } @Override public void NotifyChange() { } @Override protected void checkEmsStarted(String hostname) { if (!emsRegistrator.getHostnames().contains(hostname)) throw new RuntimeException("no ems for hostame: " + hostname); } private String executeActionOnEMS(String vduHostname, String command) throws Exception { log.trace("Sending message and waiting: " + command + " to " + vduHostname); log.info("Waiting answer from EMS - " + vduHostname); String response = vnfmHelper.sendAndReceive(command, "vnfm."+ vduHostname + ".actions"); log.debug("Received from EMS (" + vduHostname + "): " + response); if (response == null) { throw new NullPointerException("Response from EMS is null"); } JsonObject jsonObject = parser.fromJson(response, JsonObject.class); if (jsonObject.get("status").getAsInt() == 0) { try { log.debug("Output from EMS (" + vduHostname + ") is: " + jsonObject.get("output")); } catch (Exception e) { e.printStackTrace(); throw e; } } else { log.error(jsonObject.get("err").getAsString()); throw new VnfmSdkException("EMS (" + vduHostname + ") had the following error: " + jsonObject.get("err").getAsString()); } return response; } public Iterable<String> executeScriptsForEvent(VirtualNetworkFunctionRecord virtualNetworkFunctionRecord, Event event) throws Exception {//TODO make it parallel Map<String, String> env = getMap(virtualNetworkFunctionRecord); List<String> res = new ArrayList<>(); LifecycleEvent le = VnfmUtils.getLifecycleEvent(virtualNetworkFunctionRecord.getLifecycle_event(), event); if (le != null) { log.trace("The number of scripts for " + virtualNetworkFunctionRecord.getName() + " are: " + le.getLifecycle_events()); for (String script : le.getLifecycle_events()) { log.info("Sending script: " + script + " to VirtualNetworkFunctionRecord: " + virtualNetworkFunctionRecord.getName()); for (VirtualDeploymentUnit vdu : virtualNetworkFunctionRecord.getVdu()) { for (VNFCInstance vnfcInstance : vdu.getVnfc_instance()) { Map<String, String> tempEnv = new HashMap<>(); for (Ip ip : vnfcInstance.getIps()) { log.debug("Adding net: " + ip.getNetName() + " with value: " + ip.getIp()); tempEnv.put(ip.getNetName(), ip.getIp()); } log.debug("adding floatingIp: " + vnfcInstance.getFloatingIps()); for (Ip fip : vnfcInstance.getFloatingIps()) { tempEnv.put(fip.getNetName() + "_floatingIp", fip.getIp()); } tempEnv.put("hostname", vnfcInstance.getHostname()); env.putAll(tempEnv); log.info("Environment Variables are: " + env); String command = getJsonObject("EXECUTE", script, env).toString(); res.add(executeActionOnEMS(vnfcInstance.getHostname(), command)); for (String key : tempEnv.keySet()) { env.remove(key); } } } } } return res; } public List<String> executeScriptsForEvent(VirtualNetworkFunctionRecord virtualNetworkFunctionRecord, Event event, VNFRecordDependency dependency) throws Exception { Map<String, String> env = getMap(virtualNetworkFunctionRecord); LifecycleEvent le = VnfmUtils.getLifecycleEvent(virtualNetworkFunctionRecord.getLifecycle_event(), event); List<String> res = new ArrayList<>(); if (le != null) { for (String script : le.getLifecycle_events()) { String type = null; if (script.contains("_")) { type = script.substring(0, script.indexOf("_")); log.info("Sending command: " + script + " to adding relation with type: " + type + " from VirtualNetworkFunctionRecord " + virtualNetworkFunctionRecord.getName()); } for (VirtualDeploymentUnit vdu : virtualNetworkFunctionRecord.getVdu()) { for (VNFCInstance vnfcInstance : vdu.getVnfc_instance()) { log.debug("VNFCParameters are: " + dependency.getVnfcParameters()); if (dependency.getVnfcParameters().get(type) != null) for (String vnfcId : dependency.getVnfcParameters().get(type).getParameters().keySet()) { Map<String, String> tempEnv = new HashMap<>(); //Adding own ips for (Ip ip : vnfcInstance.getIps()) { log.debug("Adding net: " + ip.getNetName() + " with value: " + ip.getIp()); tempEnv.put(ip.getNetName(), ip.getIp()); } //Adding own floating ip log.debug("adding floatingIp: " + vnfcInstance.getFloatingIps()); for (Ip fip : vnfcInstance.getFloatingIps()) { tempEnv.put(fip.getNetName() + "_floatingIp", fip.getIp()); } if (script.contains("_")) { //Adding foreign parameters such as ip Map<String, String> parameters = dependency.getParameters().get(type).getParameters(); for (Map.Entry<String, String> param : parameters.entrySet()) tempEnv.put(type + "_" + param.getKey(), param.getValue()); Map<String, String> parametersVNFC = dependency.getVnfcParameters().get(type).getParameters().get(vnfcId).getParameters(); for (Map.Entry<String, String> param : parametersVNFC.entrySet()) tempEnv.put(type + "_" + param.getKey(), param.getValue()); } tempEnv.put("hostname", vnfcInstance.getHostname()); env.putAll(tempEnv); log.info("Environment Variables are: " + env); String command = getJsonObject("EXECUTE", script, env).toString(); res.add(executeActionOnEMS(vnfcInstance.getHostname(), command)); for (String key : tempEnv.keySet()) { env.remove(key); } } } } } } return res; } public void saveScriptOnEms(VirtualNetworkFunctionRecord virtualNetworkFunctionRecord, Object scripts) throws Exception { log.debug("Scripts are: " + scripts.getClass().getName()); if (scripts instanceof String) { String scriptLink = (String) scripts; log.debug("Scripts are: " + scriptLink); JsonObject jsonMessage = getJsonObject("CLONE_SCRIPTS", scriptLink, scriptPath); for (VirtualDeploymentUnit virtualDeploymentUnit : virtualNetworkFunctionRecord.getVdu()) { for (VNFCInstance vnfcInstance : virtualDeploymentUnit.getVnfc_instance()) { executeActionOnEMS(vnfcInstance.getHostname(), jsonMessage.toString()); } } } else if (scripts instanceof Set) { Set<Script> scriptSet = (Set<Script>) scripts; for (Script script : scriptSet) { log.debug("Sending script encoded base64 "); String base64String = Base64.encodeBase64String(script.getPayload()); log.trace("The base64 string is: " + base64String); JsonObject jsonMessage = getJsonObjectForScript("SAVE_SCRIPTS", base64String, script.getName(), scriptPath); for (VirtualDeploymentUnit virtualDeploymentUnit : virtualNetworkFunctionRecord.getVdu()) { for (VNFCInstance vnfcInstance : virtualDeploymentUnit.getVnfc_instance()) { executeActionOnEMS(vnfcInstance.getHostname(), jsonMessage.toString()); } } } } } public void saveScriptOnEms(VNFCInstance component, Object scripts) throws Exception { log.debug("Scripts are: " + scripts.getClass().getName()); if (scripts instanceof String) { String scriptLink = (String) scripts; log.debug("Scripts are: " + scriptLink); JsonObject jsonMessage = getJsonObject("CLONE_SCRIPTS", scriptLink, scriptPath); executeActionOnEMS(component.getHostname(), jsonMessage.toString()); } else if (scripts instanceof Set) { Set<Script> scriptSet = (Set<Script>) scripts; for (Script script : scriptSet) { log.debug("Sending script encoded base64 "); String base64String = Base64.encodeBase64String(script.getPayload()); log.trace("The base64 string is: " + base64String); JsonObject jsonMessage = getJsonObjectForScript("SAVE_SCRIPTS", base64String, script.getName(), scriptPath); executeActionOnEMS(component.getHostname(), jsonMessage.toString()); } } } private JsonObject getJsonObject(String action, String payload, String scriptPath) { JsonObject jsonMessage = new JsonObject(); jsonMessage.addProperty("action", action); jsonMessage.addProperty("payload", payload); jsonMessage.addProperty("script-path", scriptPath); return jsonMessage; } private JsonObject getJsonObject(String action, String payload, Map<String, String> dependencyParameters) { JsonObject jsonMessage = new JsonObject(); jsonMessage.addProperty("action", action); jsonMessage.addProperty("payload", payload); jsonMessage.add("env", parser.fromJson(parser.toJson(dependencyParameters), JsonObject.class)); return jsonMessage; } private JsonObject getJsonObjectForScript(String save_scripts, String payload, String name, String scriptPath) { JsonObject jsonMessage = new JsonObject(); jsonMessage.addProperty("action", save_scripts); jsonMessage.addProperty("payload", payload); jsonMessage.addProperty("name", name); jsonMessage.addProperty("script-path", scriptPath); return jsonMessage; } private Map<String, String> getMap(VirtualNetworkFunctionRecord virtualNetworkFunctionRecord) { Map<String, String> res = new HashMap<>(); for (ConfigurationParameter configurationParameter : virtualNetworkFunctionRecord.getProvides().getConfigurationParameters()) res.put(configurationParameter.getConfKey(), configurationParameter.getValue()); for (ConfigurationParameter configurationParameter : virtualNetworkFunctionRecord.getConfigurations().getConfigurationParameters()) { res.put(configurationParameter.getConfKey(), configurationParameter.getValue()); } return res; } @Override protected void setup() { super.setup(); this.scriptPath = properties.getProperty("script-path", "/opt/openbaton/scripts"); } }
added some spaces
src/main/java/org/openbaton/vnfm/generic/GenericVNFM.java
added some spaces
Java
apache-2.0
2cec9982b5d63f3e7dd7b975af093bf5e31bb689
0
JamesTPF/spring-hateoas
/* * Copyright 2013-2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.hateoas; import org.springframework.http.MediaType; /** * Constants for well-known hypermedia types. * * @author Oliver Gierke * @author Przemek Nowak */ public class MediaTypes { /** * A String equivalent of {@link MediaTypes#HAL_JSON}. */ public static final String HAL_JSON_VALUE = "application/hal+json"; /** * Public constant media type for {@code application/hal+json}. */ public static final MediaType HAL_JSON = MediaType.valueOf(HAL_JSON_VALUE); }
src/main/java/org/springframework/hateoas/MediaTypes.java
/* * Copyright 2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.hateoas; import org.springframework.http.MediaType; /** * Constants for well-known hypermedia types. * * @author Oliver Gierke */ public class MediaTypes { public static final MediaType HAL_JSON = MediaType.valueOf("application/hal+json"); }
#247 - Added HAL_JSON_VALUE in MediaTypes. Original pull request: #329.
src/main/java/org/springframework/hateoas/MediaTypes.java
#247 - Added HAL_JSON_VALUE in MediaTypes.
Java
apache-2.0
af259469e4684e0955ef59cea867914cd01fef5f
0
uzh/katts,uzh/katts,uzh/katts,uzh/katts
package ch.uzh.ddis.katts.bolts.join; import java.lang.reflect.Constructor; import java.util.Date; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import backtype.storm.task.OutputCollector; import backtype.storm.task.TopologyContext; import ch.uzh.ddis.katts.bolts.AbstractSynchronizedBolt; import ch.uzh.ddis.katts.bolts.Event; import ch.uzh.ddis.katts.bolts.VariableBindings; import ch.uzh.ddis.katts.query.processor.join.JoinConditionConfiguration; import ch.uzh.ddis.katts.query.processor.join.TemporalJoinConfiguration; import ch.uzh.ddis.katts.query.stream.Stream; import ch.uzh.ddis.katts.query.stream.StreamConsumer; import ch.uzh.ddis.katts.query.stream.Variable; /** * The temporal join basically happens in two steps. First, all events arrive over the input streams are kept in the * join cache. The semantic join operation that checks for the actual join conditions is then executed over the data in * this cache. Events that do not satisfy the temporal conditions anymore are evicted from the join cache. * * There are three steps that are being executed on the arrival of each new element in the cache. First, a configurable * set of eviction rules will be applied to the cache, in order to remove all data entries that have to be removed from * the cache <i>before</i> the join conditions are checked. Second, the actual join operation is executed, which will * emit all variable bindings that satisfy all join conditions. Lastly, there is a second set of eviction rules that can * be configured to be executed <i>after</i> the join has been executed. * * @author lfischer */ public class TemporalJoinBolt extends AbstractSynchronizedBolt { // TODO lorenz: use global storage facility private static final long serialVersionUID = 1L; /** This object holds the configuration details for this bolt. */ private final TemporalJoinConfiguration configuration; /** A set containing all ids of all incoming streams. */ private Set<String> incomingStreamIds; /** The join condition this bolt uses. */ private JoinCondition joinCondition; /** * This manager manages the eviction indices and provides methods for invoking the eviction rules. */ private EvictionRuleManager evictionRuleManager; /** We store all of our state variables into this object. */ // private Storage<Object, Map<StreamConsumer, PriorityQueue<Event>>> // queues; // private Logger logger = LoggerFactory.getLogger(TemporalJoinBolt.class); private Date lastEventDate; private Boolean monitor = new Boolean(true); private Logger logger = LoggerFactory.getLogger(TemporalJoinBolt.class); /** * Creates a new instance of this bolt type using the configuration provided. * * @param configuration * the jaxb configuration object. */ public TemporalJoinBolt(TemporalJoinConfiguration configuration) { this.configuration = configuration; } @Override public void prepare(@SuppressWarnings("rawtypes") Map stormConf, TopologyContext context, OutputCollector collector) { super.prepare(stormConf, context, collector); // Create a set containing the identifiers of all incoming streams. this.incomingStreamIds = new HashSet<String>(); for (StreamConsumer consumer : this.configuration.getConsumers()) { this.incomingStreamIds.add(consumer.getStream().getId()); } // Create and configure the join condition JoinConditionConfiguration config; Constructor<? extends JoinCondition> constructor; // there is always exactly one condition! config = this.configuration.getJoinCondition(); try { constructor = config.getImplementingClass().getConstructor(); this.joinCondition = constructor.newInstance(); } catch (Exception e) { throw new RuntimeException("Could not instantiate the configured join condition.", e); } this.joinCondition.prepare(config, this.incomingStreamIds); // Create and configure the eviction rules this.evictionRuleManager = new EvictionRuleManager(this.configuration.getBeforeEvictionRules(), this.configuration.getAfterEvictionRules(), this.joinCondition, this.incomingStreamIds); } @Override public void execute(Event event) { // Check the constrain that all event, must be in order for processing. synchronized (monitor) { if (lastEventDate != null && lastEventDate.after(event.getEndDate())) { // throw new RuntimeException("An event was out of order."); logger.error(String.format("An event was out of order. Component Id: %1s -- Source Stream ID: %2s", this.getId(), event.getTuple().getSourceStreamId())); } lastEventDate = event.getEndDate(); } // // TODO: Workaround to send the shutdown signal to depending tasks: // if (event.getEndDate().after(new Date())) { // setLastDateProcessed(event.getEndDate()); // return; // } Set<SimpleVariableBindings> joinResults; SimpleVariableBindings newBindings = new SimpleVariableBindings(event.getTuple()); String streamId = event.getEmittedOn().getStream().getId(); this.evictionRuleManager.addBindingsToIndices(newBindings, streamId); this.evictionRuleManager.executeBeforeEvictionRules(newBindings, streamId); joinResults = this.joinCondition.join(newBindings, streamId); this.evictionRuleManager.executeAfterEvictionRules(newBindings, streamId); /* * Emit the joined results by creating a variableBindings object for each stream */ for (Stream stream : this.getStreams()) { /* * copy all variable bindings from the result of the join into the new bindings variable which we emit from * this bolt. */ for (SimpleVariableBindings simpleBindings : joinResults) { VariableBindings bindingsToEmit = getEmitter().createVariableBindings(stream, event); for (Variable variable : stream.getVariables()) { if (simpleBindings.get(variable.getReferencesTo()) == null) { throw new NullPointerException(); } bindingsToEmit.add(variable, simpleBindings.get(variable.getReferencesTo())); } bindingsToEmit.setStartDate((Date) simpleBindings.get("startDate")); bindingsToEmit.setEndDate((Date) simpleBindings.get("endDate")); bindingsToEmit.emit(); // TODO: Is this really the last possible occurring date of join? setLastDateProcessed(bindingsToEmit.getEndDate()); } } ack(event); } @Override public synchronized void updateIncomingStreamDate(Date streamDate) { super.updateIncomingStreamDate(streamDate); // TODO: Remove this workaround. This is required to ensure the proper termination of the system. if (streamDate.after(new Date())) { setLastDateProcessed(streamDate); } } @Override public String getId() { return this.configuration.getId(); } }
src/main/java/ch/uzh/ddis/katts/bolts/join/TemporalJoinBolt.java
package ch.uzh.ddis.katts.bolts.join; import java.lang.reflect.Constructor; import java.util.Date; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import backtype.storm.task.OutputCollector; import backtype.storm.task.TopologyContext; import ch.uzh.ddis.katts.bolts.AbstractSynchronizedBolt; import ch.uzh.ddis.katts.bolts.Event; import ch.uzh.ddis.katts.bolts.VariableBindings; import ch.uzh.ddis.katts.query.processor.join.JoinConditionConfiguration; import ch.uzh.ddis.katts.query.processor.join.TemporalJoinConfiguration; import ch.uzh.ddis.katts.query.stream.Stream; import ch.uzh.ddis.katts.query.stream.StreamConsumer; import ch.uzh.ddis.katts.query.stream.Variable; /** * The temporal join basically happens in two steps. First, all events arrive over the input streams are kept in the * join cache. The semantic join operation that checks for the actual join conditions is then executed over the data in * this cache. Events that do not satisfy the temporal conditions anymore are evicted from the join cache. * * There are three steps that are being executed on the arrival of each new element in the cache. First, a configurable * set of eviction rules will be applied to the cache, in order to remove all data entries that have to be removed from * the cache <i>before</i> the join conditions are checked. Second, the actual join operation is executed, which will * emit all variable bindings that satisfy all join conditions. Lastly, there is a second set of eviction rules that can * be configured to be executed <i>after</i> the join has been executed. * * @author lfischer */ public class TemporalJoinBolt extends AbstractSynchronizedBolt { // TODO lorenz: use global storage facility private static final long serialVersionUID = 1L; /** This object holds the configuration details for this bolt. */ private final TemporalJoinConfiguration configuration; /** A set containing all ids of all incoming streams. */ private Set<String> incomingStreamIds; /** The join condition this bolt uses. */ private JoinCondition joinCondition; /** * This manager manages the eviction indices and provides methods for invoking the eviction rules. */ private EvictionRuleManager evictionRuleManager; /** We store all of our state variables into this object. */ // private Storage<Object, Map<StreamConsumer, PriorityQueue<Event>>> // queues; // private Logger logger = LoggerFactory.getLogger(TemporalJoinBolt.class); private Date lastEventDate; private Boolean monitor = new Boolean(true); private Logger logger = LoggerFactory.getLogger(TemporalJoinBolt.class); /** * Creates a new instance of this bolt type using the configuration provided. * * @param configuration * the jaxb configuration object. */ public TemporalJoinBolt(TemporalJoinConfiguration configuration) { this.configuration = configuration; } @Override public void prepare(@SuppressWarnings("rawtypes") Map stormConf, TopologyContext context, OutputCollector collector) { super.prepare(stormConf, context, collector); // Create a set containing the identifiers of all incoming streams. this.incomingStreamIds = new HashSet<String>(); for (StreamConsumer consumer : this.configuration.getConsumers()) { this.incomingStreamIds.add(consumer.getStream().getId()); } // Create and configure the join condition JoinConditionConfiguration config; Constructor<? extends JoinCondition> constructor; // there is always exactly one condition! config = this.configuration.getJoinCondition(); try { constructor = config.getImplementingClass().getConstructor(); this.joinCondition = constructor.newInstance(); } catch (Exception e) { throw new RuntimeException("Could not instantiate the configured join condition.", e); } this.joinCondition.prepare(config, this.incomingStreamIds); // Create and configure the eviction rules this.evictionRuleManager = new EvictionRuleManager(this.configuration.getBeforeEvictionRules(), this.configuration.getAfterEvictionRules(), this.joinCondition, this.incomingStreamIds); } @Override public void execute(Event event) { // Check the constrain that all event, must be in order for processing. synchronized (monitor) { if (lastEventDate != null && lastEventDate.after(event.getEndDate())) { // throw new RuntimeException("An event was out of order."); logger.error(String.format("An event was out of order. Component Id: %1s -- Source Stream ID: %2s", this.getId(), event.getTuple().getSourceStreamId())); } lastEventDate = event.getEndDate(); } // // TODO: Workaround to send the shutdown signal to depending tasks: // if (event.getEndDate().after(new Date())) { // setLastDateProcessed(event.getEndDate()); // return; // } Set<SimpleVariableBindings> joinResults; SimpleVariableBindings newBindings = new SimpleVariableBindings(event.getTuple()); String streamId = event.getEmittedOn().getStream().getId(); this.evictionRuleManager.addBindingsToIndices(newBindings, streamId); this.evictionRuleManager.executeBeforeEvictionRules(newBindings, streamId); joinResults = this.joinCondition.join(newBindings, streamId); this.evictionRuleManager.executeAfterEvictionRules(newBindings, streamId); /* * Emit the joined results by creating a variableBindings object for each stream */ for (Stream stream : this.getStreams()) { /* * copy all variable bindings from the result of the join into the new bindings variable which we emit from * this bolt. */ for (SimpleVariableBindings simpleBindings : joinResults) { VariableBindings bindingsToEmit = getEmitter().createVariableBindings(stream, event); for (Variable variable : stream.getVariables()) { if (simpleBindings.get(variable.getReferencesTo()) == null) { throw new NullPointerException(); } bindingsToEmit.add(variable, simpleBindings.get(variable.getReferencesTo())); } bindingsToEmit.setStartDate((Date) simpleBindings.get("startDate")); bindingsToEmit.setEndDate((Date) simpleBindings.get("endDate")); bindingsToEmit.emit(); // TODO: Is this really the last possible occurring date of join? setLastDateProcessed(bindingsToEmit.getEndDate()); } } ack(event); } @Override public synchronized void updateIncomingStreamDate(Date streamDate) { System.out.println(streamDate); super.updateIncomingStreamDate(streamDate); // TODO: Remove this workaround. This is required to ensure the proper termination of the system. if (streamDate.after(new Date())) { setLastDateProcessed(streamDate); } } @Override public String getId() { return this.configuration.getId(); } }
Remove debug output code.
src/main/java/ch/uzh/ddis/katts/bolts/join/TemporalJoinBolt.java
Remove debug output code.
Java
apache-2.0
4f6aa4391025f84ac6aad3c17549e9575c0c8795
0
mtenrero/vetManager,mtenrero/vetManager,mtenrero/vetManager,mtenrero/vetManager
package es.urjc.etsii.mtenrero; import es.urjc.etsii.mtenrero.ServicioInterno.MailerResponse; import org.springframework.http.ResponseEntity; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.client.RestTemplate; import javax.net.ssl.SSLSocketFactory; import javax.xml.ws.Response; import java.io.*; import java.net.Socket; import java.net.UnknownHostException; import java.util.Date; /** * Created by was12 on 15/03/2017. */ public class Communication { public void main(String email,String subject,String body) throws UnknownHostException, IOException{ RestTemplate restTemplate = new RestTemplate(); MultiValueMap<String, String> map= new LinkedMultiValueMap<String, String>(); map.add("email", email); map.add("subject", subject); map.add("body", body); ResponseEntity<MailerResponse> response = restTemplate.postForEntity("https://100.76.52.160:8083/sendEmail",map,MailerResponse.class); } }
src/main/java/es/urjc/etsii/mtenrero/Communication.java
package es.urjc.etsii.mtenrero; import es.urjc.etsii.mtenrero.ServicioInterno.MailerResponse; import org.springframework.http.ResponseEntity; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.client.RestTemplate; import javax.net.ssl.SSLSocketFactory; import javax.xml.ws.Response; import java.io.*; import java.net.Socket; import java.net.UnknownHostException; import java.util.Date; /** * Created by was12 on 15/03/2017. */ public class Communication { public void main(String email,String subject,String body) throws UnknownHostException, IOException{ RestTemplate restTemplate = new RestTemplate(); MultiValueMap<String, String> map= new LinkedMultiValueMap<String, String>(); map.add("email", email); map.add("subject", subject); map.add("body", body); ResponseEntity<MailerResponse> response = restTemplate.postForEntity("https://localhost:8083/sendEmail",map,MailerResponse.class); } }
Changed Communicator with Mailer Service to Load Balancer IP
src/main/java/es/urjc/etsii/mtenrero/Communication.java
Changed Communicator with Mailer Service to Load Balancer IP
Java
apache-2.0
8d22bd8af543ddcc4f8a1417cd238e7b79bb279e
0
izonder/intellij-community,clumsy/intellij-community,alphafoobar/intellij-community,youdonghai/intellij-community,vladmm/intellij-community,adedayo/intellij-community,nicolargo/intellij-community,xfournet/intellij-community,tmpgit/intellij-community,gnuhub/intellij-community,salguarnieri/intellij-community,ol-loginov/intellij-community,youdonghai/intellij-community,ahb0327/intellij-community,jagguli/intellij-community,da1z/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,samthor/intellij-community,ivan-fedorov/intellij-community,slisson/intellij-community,xfournet/intellij-community,SerCeMan/intellij-community,alphafoobar/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,fnouama/intellij-community,petteyg/intellij-community,vladmm/intellij-community,lucafavatella/intellij-community,jagguli/intellij-community,fengbaicanhe/intellij-community,FHannes/intellij-community,slisson/intellij-community,fnouama/intellij-community,MER-GROUP/intellij-community,blademainer/intellij-community,Lekanich/intellij-community,clumsy/intellij-community,SerCeMan/intellij-community,fitermay/intellij-community,ahb0327/intellij-community,fitermay/intellij-community,samthor/intellij-community,apixandru/intellij-community,slisson/intellij-community,vvv1559/intellij-community,caot/intellij-community,supersven/intellij-community,dslomov/intellij-community,TangHao1987/intellij-community,ivan-fedorov/intellij-community,asedunov/intellij-community,ol-loginov/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,diorcety/intellij-community,diorcety/intellij-community,robovm/robovm-studio,robovm/robovm-studio,amith01994/intellij-community,adedayo/intellij-community,TangHao1987/intellij-community,semonte/intellij-community,pwoodworth/intellij-community,lucafavatella/intellij-community,slisson/intellij-community,michaelgallacher/intellij-community,Distrotech/intellij-community,adedayo/intellij-community,samthor/intellij-community,nicolargo/intellij-community,semonte/intellij-community,salguarnieri/intellij-community,orekyuu/intellij-community,retomerz/intellij-community,ibinti/intellij-community,kool79/intellij-community,wreckJ/intellij-community,samthor/intellij-community,wreckJ/intellij-community,Distrotech/intellij-community,suncycheng/intellij-community,diorcety/intellij-community,michaelgallacher/intellij-community,nicolargo/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,caot/intellij-community,mglukhikh/intellij-community,ivan-fedorov/intellij-community,petteyg/intellij-community,caot/intellij-community,semonte/intellij-community,FHannes/intellij-community,gnuhub/intellij-community,kool79/intellij-community,fnouama/intellij-community,petteyg/intellij-community,Distrotech/intellij-community,dslomov/intellij-community,idea4bsd/idea4bsd,fengbaicanhe/intellij-community,wreckJ/intellij-community,MichaelNedzelsky/intellij-community,diorcety/intellij-community,hurricup/intellij-community,wreckJ/intellij-community,MichaelNedzelsky/intellij-community,tmpgit/intellij-community,fitermay/intellij-community,samthor/intellij-community,wreckJ/intellij-community,gnuhub/intellij-community,salguarnieri/intellij-community,pwoodworth/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,ryano144/intellij-community,holmes/intellij-community,mglukhikh/intellij-community,petteyg/intellij-community,holmes/intellij-community,muntasirsyed/intellij-community,da1z/intellij-community,ibinti/intellij-community,ahb0327/intellij-community,ivan-fedorov/intellij-community,gnuhub/intellij-community,suncycheng/intellij-community,semonte/intellij-community,asedunov/intellij-community,muntasirsyed/intellij-community,muntasirsyed/intellij-community,Distrotech/intellij-community,youdonghai/intellij-community,holmes/intellij-community,da1z/intellij-community,allotria/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,gnuhub/intellij-community,blademainer/intellij-community,FHannes/intellij-community,ol-loginov/intellij-community,holmes/intellij-community,fengbaicanhe/intellij-community,retomerz/intellij-community,holmes/intellij-community,petteyg/intellij-community,signed/intellij-community,hurricup/intellij-community,supersven/intellij-community,salguarnieri/intellij-community,FHannes/intellij-community,pwoodworth/intellij-community,akosyakov/intellij-community,kool79/intellij-community,MichaelNedzelsky/intellij-community,ThiagoGarciaAlves/intellij-community,muntasirsyed/intellij-community,akosyakov/intellij-community,slisson/intellij-community,fitermay/intellij-community,izonder/intellij-community,asedunov/intellij-community,gnuhub/intellij-community,clumsy/intellij-community,caot/intellij-community,retomerz/intellij-community,kdwink/intellij-community,slisson/intellij-community,slisson/intellij-community,MichaelNedzelsky/intellij-community,SerCeMan/intellij-community,alphafoobar/intellij-community,da1z/intellij-community,fengbaicanhe/intellij-community,orekyuu/intellij-community,salguarnieri/intellij-community,kdwink/intellij-community,ftomassetti/intellij-community,youdonghai/intellij-community,Distrotech/intellij-community,akosyakov/intellij-community,muntasirsyed/intellij-community,caot/intellij-community,dslomov/intellij-community,blademainer/intellij-community,alphafoobar/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,akosyakov/intellij-community,ahb0327/intellij-community,signed/intellij-community,Lekanich/intellij-community,supersven/intellij-community,supersven/intellij-community,retomerz/intellij-community,ahb0327/intellij-community,clumsy/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,vladmm/intellij-community,jagguli/intellij-community,Lekanich/intellij-community,robovm/robovm-studio,michaelgallacher/intellij-community,jagguli/intellij-community,MichaelNedzelsky/intellij-community,robovm/robovm-studio,xfournet/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,pwoodworth/intellij-community,slisson/intellij-community,semonte/intellij-community,vladmm/intellij-community,vvv1559/intellij-community,kool79/intellij-community,hurricup/intellij-community,samthor/intellij-community,amith01994/intellij-community,holmes/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,salguarnieri/intellij-community,ThiagoGarciaAlves/intellij-community,supersven/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,fengbaicanhe/intellij-community,youdonghai/intellij-community,ryano144/intellij-community,asedunov/intellij-community,Distrotech/intellij-community,da1z/intellij-community,salguarnieri/intellij-community,apixandru/intellij-community,ivan-fedorov/intellij-community,dslomov/intellij-community,ibinti/intellij-community,ol-loginov/intellij-community,pwoodworth/intellij-community,michaelgallacher/intellij-community,izonder/intellij-community,TangHao1987/intellij-community,ol-loginov/intellij-community,FHannes/intellij-community,hurricup/intellij-community,samthor/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,clumsy/intellij-community,supersven/intellij-community,orekyuu/intellij-community,blademainer/intellij-community,kdwink/intellij-community,allotria/intellij-community,ryano144/intellij-community,nicolargo/intellij-community,lucafavatella/intellij-community,allotria/intellij-community,da1z/intellij-community,xfournet/intellij-community,diorcety/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,SerCeMan/intellij-community,izonder/intellij-community,diorcety/intellij-community,youdonghai/intellij-community,fengbaicanhe/intellij-community,MER-GROUP/intellij-community,ThiagoGarciaAlves/intellij-community,kdwink/intellij-community,TangHao1987/intellij-community,FHannes/intellij-community,adedayo/intellij-community,vladmm/intellij-community,izonder/intellij-community,clumsy/intellij-community,TangHao1987/intellij-community,jagguli/intellij-community,izonder/intellij-community,robovm/robovm-studio,semonte/intellij-community,clumsy/intellij-community,orekyuu/intellij-community,lucafavatella/intellij-community,ol-loginov/intellij-community,akosyakov/intellij-community,alphafoobar/intellij-community,youdonghai/intellij-community,robovm/robovm-studio,retomerz/intellij-community,ThiagoGarciaAlves/intellij-community,kool79/intellij-community,MichaelNedzelsky/intellij-community,caot/intellij-community,adedayo/intellij-community,blademainer/intellij-community,robovm/robovm-studio,ibinti/intellij-community,ol-loginov/intellij-community,signed/intellij-community,pwoodworth/intellij-community,holmes/intellij-community,kool79/intellij-community,michaelgallacher/intellij-community,suncycheng/intellij-community,signed/intellij-community,ryano144/intellij-community,Distrotech/intellij-community,apixandru/intellij-community,hurricup/intellij-community,Lekanich/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,pwoodworth/intellij-community,allotria/intellij-community,semonte/intellij-community,orekyuu/intellij-community,FHannes/intellij-community,slisson/intellij-community,fnouama/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,ahb0327/intellij-community,fnouama/intellij-community,tmpgit/intellij-community,tmpgit/intellij-community,caot/intellij-community,allotria/intellij-community,dslomov/intellij-community,izonder/intellij-community,vvv1559/intellij-community,TangHao1987/intellij-community,supersven/intellij-community,wreckJ/intellij-community,muntasirsyed/intellij-community,TangHao1987/intellij-community,tmpgit/intellij-community,MichaelNedzelsky/intellij-community,hurricup/intellij-community,wreckJ/intellij-community,apixandru/intellij-community,semonte/intellij-community,petteyg/intellij-community,fengbaicanhe/intellij-community,MichaelNedzelsky/intellij-community,xfournet/intellij-community,tmpgit/intellij-community,MER-GROUP/intellij-community,holmes/intellij-community,idea4bsd/idea4bsd,ryano144/intellij-community,fengbaicanhe/intellij-community,holmes/intellij-community,pwoodworth/intellij-community,hurricup/intellij-community,slisson/intellij-community,kool79/intellij-community,diorcety/intellij-community,tmpgit/intellij-community,pwoodworth/intellij-community,xfournet/intellij-community,petteyg/intellij-community,alphafoobar/intellij-community,jagguli/intellij-community,retomerz/intellij-community,caot/intellij-community,FHannes/intellij-community,alphafoobar/intellij-community,kdwink/intellij-community,diorcety/intellij-community,fitermay/intellij-community,tmpgit/intellij-community,blademainer/intellij-community,allotria/intellij-community,semonte/intellij-community,salguarnieri/intellij-community,Lekanich/intellij-community,ahb0327/intellij-community,jagguli/intellij-community,asedunov/intellij-community,dslomov/intellij-community,ahb0327/intellij-community,adedayo/intellij-community,muntasirsyed/intellij-community,gnuhub/intellij-community,asedunov/intellij-community,tmpgit/intellij-community,suncycheng/intellij-community,MER-GROUP/intellij-community,semonte/intellij-community,jagguli/intellij-community,caot/intellij-community,amith01994/intellij-community,ryano144/intellij-community,akosyakov/intellij-community,adedayo/intellij-community,SerCeMan/intellij-community,tmpgit/intellij-community,michaelgallacher/intellij-community,Lekanich/intellij-community,gnuhub/intellij-community,ol-loginov/intellij-community,FHannes/intellij-community,caot/intellij-community,suncycheng/intellij-community,kdwink/intellij-community,idea4bsd/idea4bsd,diorcety/intellij-community,clumsy/intellij-community,apixandru/intellij-community,izonder/intellij-community,vladmm/intellij-community,MichaelNedzelsky/intellij-community,allotria/intellij-community,fitermay/intellij-community,SerCeMan/intellij-community,amith01994/intellij-community,youdonghai/intellij-community,fnouama/intellij-community,blademainer/intellij-community,retomerz/intellij-community,lucafavatella/intellij-community,FHannes/intellij-community,michaelgallacher/intellij-community,blademainer/intellij-community,alphafoobar/intellij-community,supersven/intellij-community,caot/intellij-community,vvv1559/intellij-community,supersven/intellij-community,ibinti/intellij-community,ibinti/intellij-community,xfournet/intellij-community,amith01994/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,samthor/intellij-community,fitermay/intellij-community,slisson/intellij-community,gnuhub/intellij-community,nicolargo/intellij-community,diorcety/intellij-community,ftomassetti/intellij-community,akosyakov/intellij-community,ibinti/intellij-community,apixandru/intellij-community,ol-loginov/intellij-community,lucafavatella/intellij-community,vladmm/intellij-community,Lekanich/intellij-community,idea4bsd/idea4bsd,samthor/intellij-community,dslomov/intellij-community,salguarnieri/intellij-community,SerCeMan/intellij-community,retomerz/intellij-community,allotria/intellij-community,lucafavatella/intellij-community,salguarnieri/intellij-community,muntasirsyed/intellij-community,nicolargo/intellij-community,pwoodworth/intellij-community,da1z/intellij-community,salguarnieri/intellij-community,fnouama/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,wreckJ/intellij-community,FHannes/intellij-community,lucafavatella/intellij-community,ryano144/intellij-community,izonder/intellij-community,TangHao1987/intellij-community,idea4bsd/idea4bsd,MER-GROUP/intellij-community,ftomassetti/intellij-community,mglukhikh/intellij-community,fengbaicanhe/intellij-community,petteyg/intellij-community,orekyuu/intellij-community,kool79/intellij-community,suncycheng/intellij-community,kdwink/intellij-community,fengbaicanhe/intellij-community,TangHao1987/intellij-community,amith01994/intellij-community,nicolargo/intellij-community,adedayo/intellij-community,diorcety/intellij-community,ryano144/intellij-community,mglukhikh/intellij-community,alphafoobar/intellij-community,michaelgallacher/intellij-community,supersven/intellij-community,mglukhikh/intellij-community,fnouama/intellij-community,izonder/intellij-community,ibinti/intellij-community,fitermay/intellij-community,TangHao1987/intellij-community,MER-GROUP/intellij-community,asedunov/intellij-community,fitermay/intellij-community,adedayo/intellij-community,ThiagoGarciaAlves/intellij-community,Lekanich/intellij-community,kdwink/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,adedayo/intellij-community,ftomassetti/intellij-community,ryano144/intellij-community,asedunov/intellij-community,MER-GROUP/intellij-community,apixandru/intellij-community,hurricup/intellij-community,slisson/intellij-community,dslomov/intellij-community,hurricup/intellij-community,ol-loginov/intellij-community,ivan-fedorov/intellij-community,Lekanich/intellij-community,fengbaicanhe/intellij-community,idea4bsd/idea4bsd,nicolargo/intellij-community,da1z/intellij-community,michaelgallacher/intellij-community,ol-loginov/intellij-community,petteyg/intellij-community,apixandru/intellij-community,orekyuu/intellij-community,asedunov/intellij-community,signed/intellij-community,MichaelNedzelsky/intellij-community,orekyuu/intellij-community,samthor/intellij-community,fitermay/intellij-community,ivan-fedorov/intellij-community,kdwink/intellij-community,gnuhub/intellij-community,alphafoobar/intellij-community,suncycheng/intellij-community,gnuhub/intellij-community,Distrotech/intellij-community,ftomassetti/intellij-community,semonte/intellij-community,amith01994/intellij-community,kool79/intellij-community,signed/intellij-community,petteyg/intellij-community,kool79/intellij-community,hurricup/intellij-community,fengbaicanhe/intellij-community,SerCeMan/intellij-community,amith01994/intellij-community,vvv1559/intellij-community,vladmm/intellij-community,ftomassetti/intellij-community,ivan-fedorov/intellij-community,supersven/intellij-community,muntasirsyed/intellij-community,xfournet/intellij-community,semonte/intellij-community,kool79/intellij-community,ThiagoGarciaAlves/intellij-community,lucafavatella/intellij-community,MER-GROUP/intellij-community,holmes/intellij-community,da1z/intellij-community,blademainer/intellij-community,orekyuu/intellij-community,ibinti/intellij-community,kdwink/intellij-community,SerCeMan/intellij-community,Lekanich/intellij-community,tmpgit/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,ftomassetti/intellij-community,ivan-fedorov/intellij-community,robovm/robovm-studio,ahb0327/intellij-community,tmpgit/intellij-community,suncycheng/intellij-community,wreckJ/intellij-community,gnuhub/intellij-community,akosyakov/intellij-community,Lekanich/intellij-community,retomerz/intellij-community,holmes/intellij-community,adedayo/intellij-community,fnouama/intellij-community,FHannes/intellij-community,SerCeMan/intellij-community,signed/intellij-community,ftomassetti/intellij-community,robovm/robovm-studio,alphafoobar/intellij-community,apixandru/intellij-community,Distrotech/intellij-community,vvv1559/intellij-community,jagguli/intellij-community,youdonghai/intellij-community,akosyakov/intellij-community,izonder/intellij-community,jagguli/intellij-community,SerCeMan/intellij-community,ThiagoGarciaAlves/intellij-community,vladmm/intellij-community,samthor/intellij-community,muntasirsyed/intellij-community,semonte/intellij-community,holmes/intellij-community,apixandru/intellij-community,allotria/intellij-community,signed/intellij-community,pwoodworth/intellij-community,clumsy/intellij-community,SerCeMan/intellij-community,diorcety/intellij-community,MichaelNedzelsky/intellij-community,ftomassetti/intellij-community,allotria/intellij-community,allotria/intellij-community,robovm/robovm-studio,hurricup/intellij-community,TangHao1987/intellij-community,dslomov/intellij-community,adedayo/intellij-community,youdonghai/intellij-community,da1z/intellij-community,ahb0327/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,kdwink/intellij-community,ol-loginov/intellij-community,da1z/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,izonder/intellij-community,nicolargo/intellij-community,samthor/intellij-community,vladmm/intellij-community,ftomassetti/intellij-community,Distrotech/intellij-community,lucafavatella/intellij-community,TangHao1987/intellij-community,retomerz/intellij-community,blademainer/intellij-community,dslomov/intellij-community,wreckJ/intellij-community,akosyakov/intellij-community,fnouama/intellij-community,jagguli/intellij-community,fnouama/intellij-community,vvv1559/intellij-community,ivan-fedorov/intellij-community,Distrotech/intellij-community,ftomassetti/intellij-community,amith01994/intellij-community,MER-GROUP/intellij-community,asedunov/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,ivan-fedorov/intellij-community,Lekanich/intellij-community,michaelgallacher/intellij-community,amith01994/intellij-community,pwoodworth/intellij-community,signed/intellij-community,robovm/robovm-studio,jagguli/intellij-community,wreckJ/intellij-community,vladmm/intellij-community,orekyuu/intellij-community,asedunov/intellij-community,ivan-fedorov/intellij-community,dslomov/intellij-community,dslomov/intellij-community,nicolargo/intellij-community,ahb0327/intellij-community,fnouama/intellij-community,orekyuu/intellij-community,akosyakov/intellij-community,ibinti/intellij-community,vladmm/intellij-community,MER-GROUP/intellij-community,allotria/intellij-community,amith01994/intellij-community,ahb0327/intellij-community,petteyg/intellij-community,akosyakov/intellij-community,retomerz/intellij-community,kool79/intellij-community,da1z/intellij-community,fitermay/intellij-community,supersven/intellij-community,MER-GROUP/intellij-community,robovm/robovm-studio,mglukhikh/intellij-community,wreckJ/intellij-community,idea4bsd/idea4bsd,ftomassetti/intellij-community,Distrotech/intellij-community,blademainer/intellij-community,muntasirsyed/intellij-community,blademainer/intellij-community,ryano144/intellij-community,signed/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,alphafoobar/intellij-community,clumsy/intellij-community,amith01994/intellij-community,signed/intellij-community,MichaelNedzelsky/intellij-community,allotria/intellij-community,MER-GROUP/intellij-community,ryano144/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,caot/intellij-community,asedunov/intellij-community,clumsy/intellij-community,ryano144/intellij-community,nicolargo/intellij-community,kdwink/intellij-community,retomerz/intellij-community,hurricup/intellij-community,orekyuu/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,petteyg/intellij-community,muntasirsyed/intellij-community,salguarnieri/intellij-community,nicolargo/intellij-community
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.psi.infos; import com.intellij.openapi.project.Project; import com.intellij.openapi.projectRoots.JavaSdkVersion; import com.intellij.openapi.projectRoots.JavaVersionService; import com.intellij.openapi.util.Computable; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.RecursionGuard; import com.intellij.openapi.util.RecursionManager; import com.intellij.pom.java.LanguageLevel; import com.intellij.psi.*; import com.intellij.psi.impl.source.resolve.DefaultParameterTypeInferencePolicy; import com.intellij.psi.impl.source.resolve.ParameterTypeInferencePolicy; import com.intellij.psi.util.PsiUtil; import com.intellij.util.containers.ConcurrentWeakHashMap; import org.intellij.lang.annotations.MagicConstant; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Map; /** * @author ik, dsl */ public class MethodCandidateInfo extends CandidateInfo{ public static final RecursionGuard ourOverloadGuard = RecursionManager.createGuard("overload.guard"); public static final ThreadLocal<Map<PsiElement, Pair<PsiMethod, PsiSubstitutor>>> CURRENT_CANDIDATE = new ThreadLocal<Map<PsiElement, Pair<PsiMethod, PsiSubstitutor>>>(); @ApplicabilityLevelConstant private int myApplicabilityLevel = 0; private final PsiElement myArgumentList; private final PsiType[] myArgumentTypes; private final PsiType[] myTypeArguments; private PsiSubstitutor myCalcedSubstitutor = null; private final LanguageLevel myLanguageLevel; public MethodCandidateInfo(PsiElement candidate, PsiSubstitutor substitutor, boolean accessProblem, boolean staticsProblem, PsiElement argumentList, PsiElement currFileContext, @Nullable PsiType[] argumentTypes, PsiType[] typeArguments) { this(candidate, substitutor, accessProblem, staticsProblem, argumentList, currFileContext, argumentTypes, typeArguments, PsiUtil.getLanguageLevel(argumentList)); } public MethodCandidateInfo(PsiElement candidate, PsiSubstitutor substitutor, boolean accessProblem, boolean staticsProblem, PsiElement argumentList, PsiElement currFileContext, @Nullable PsiType[] argumentTypes, PsiType[] typeArguments, @NotNull LanguageLevel languageLevel) { super(candidate, substitutor, accessProblem, staticsProblem, currFileContext); myArgumentList = argumentList; myArgumentTypes = argumentTypes; myTypeArguments = typeArguments; myLanguageLevel = languageLevel; } public boolean isApplicable(){ return getApplicabilityLevel() != ApplicabilityLevel.NOT_APPLICABLE; } @ApplicabilityLevelConstant private int getApplicabilityLevelInner() { if (myArgumentTypes == null) return ApplicabilityLevel.NOT_APPLICABLE; int level = PsiUtil.getApplicabilityLevel(getElement(), getSubstitutor(), myArgumentTypes, myLanguageLevel); if (level > ApplicabilityLevel.NOT_APPLICABLE && !isTypeArgumentsApplicable()) level = ApplicabilityLevel.NOT_APPLICABLE; return level; } @ApplicabilityLevelConstant public int getApplicabilityLevel() { if(myApplicabilityLevel == 0){ myApplicabilityLevel = getApplicabilityLevelInner(); } return myApplicabilityLevel; } @ApplicabilityLevelConstant public int getPertinentApplicabilityLevel() { if (myTypeArguments != null) { return getApplicabilityLevel(); } final PsiMethod method = getElement(); if (method != null && method.hasTypeParameters() || myArgumentList == null || !PsiUtil.isLanguageLevel8OrHigher(myArgumentList)) { @ApplicabilityLevelConstant int level; if (myArgumentTypes == null) { return ApplicabilityLevel.NOT_APPLICABLE; } else { final PsiSubstitutor substitutor = getSubstitutor(); Integer boxedLevel = ourOverloadGuard.doPreventingRecursion(myArgumentList, false, new Computable<Integer>() { @Override public Integer compute() { return PsiUtil.getApplicabilityLevel(getElement(), substitutor, myArgumentTypes, myLanguageLevel); } }); level = boxedLevel != null ? boxedLevel : getApplicabilityLevel(); } if (level > ApplicabilityLevel.NOT_APPLICABLE && !isTypeArgumentsApplicable()) level = ApplicabilityLevel.NOT_APPLICABLE; return level; } Integer boxedLevel = ourOverloadGuard.doPreventingRecursion(myArgumentList, false, new Computable<Integer>() { @Override public Integer compute() { return getApplicabilityLevelInner(); } }); return boxedLevel != null ? boxedLevel : getApplicabilityLevel(); } public PsiSubstitutor getSiteSubstitutor() { return super.getSubstitutor(); } @Override public PsiSubstitutor getSubstitutor() { return getSubstitutor(true); } public PsiSubstitutor getSubstitutor(boolean includeReturnConstraint) { if (myCalcedSubstitutor == null || !includeReturnConstraint) { PsiSubstitutor incompleteSubstitutor = super.getSubstitutor(); PsiMethod method = getElement(); if (myTypeArguments == null) { final RecursionGuard.StackStamp stackStamp = PsiDiamondType.ourDiamondGuard.markStack(); final PsiSubstitutor inferredSubstitutor = inferTypeArguments(DefaultParameterTypeInferencePolicy.INSTANCE, includeReturnConstraint); if (!stackStamp.mayCacheNow() || !includeReturnConstraint) { return inferredSubstitutor; } myCalcedSubstitutor = inferredSubstitutor; } else { PsiTypeParameter[] typeParams = method.getTypeParameters(); for (int i = 0; i < myTypeArguments.length && i < typeParams.length; i++) { incompleteSubstitutor = incompleteSubstitutor.put(typeParams[i], myTypeArguments[i]); } myCalcedSubstitutor = incompleteSubstitutor; } } return myCalcedSubstitutor; } public boolean isTypeArgumentsApplicable() { final PsiMethod psiMethod = getElement(); PsiTypeParameter[] typeParams = psiMethod.getTypeParameters(); if (myTypeArguments != null && typeParams.length != myTypeArguments.length && !PsiUtil.isLanguageLevel7OrHigher(psiMethod)){ return typeParams.length == 0 && JavaVersionService.getInstance().isAtLeast(psiMethod, JavaSdkVersion.JDK_1_7); } PsiSubstitutor substitutor = getSubstitutor(); return GenericsUtil.isTypeArgumentsApplicable(typeParams, substitutor, getParent()); } protected PsiElement getParent() { return myArgumentList != null ? myArgumentList.getParent() : myArgumentList; } @Override public boolean isValidResult(){ return super.isValidResult() && isApplicable(); } @Override public PsiMethod getElement(){ return (PsiMethod)super.getElement(); } public PsiSubstitutor inferTypeArguments(@NotNull ParameterTypeInferencePolicy policy, boolean includeReturnConstraint) { return inferTypeArguments(policy, myArgumentList instanceof PsiExpressionList ? ((PsiExpressionList)myArgumentList).getExpressions() : PsiExpression.EMPTY_ARRAY, includeReturnConstraint); } public PsiSubstitutor inferSubstitutorFromArgs(@NotNull ParameterTypeInferencePolicy policy, final PsiExpression[] arguments) { if (myTypeArguments == null) { return inferTypeArguments(policy, arguments, true); } else { PsiSubstitutor incompleteSubstitutor = super.getSubstitutor(); PsiMethod method = getElement(); if (method != null) { PsiTypeParameter[] typeParams = method.getTypeParameters(); for (int i = 0; i < myTypeArguments.length && i < typeParams.length; i++) { incompleteSubstitutor = incompleteSubstitutor.put(typeParams[i], myTypeArguments[i]); } } return incompleteSubstitutor; } } public PsiSubstitutor inferTypeArguments(@NotNull ParameterTypeInferencePolicy policy, @NotNull PsiExpression[] arguments, boolean includeReturnConstraint) { Map<PsiElement, Pair<PsiMethod, PsiSubstitutor>> map = CURRENT_CANDIDATE.get(); if (map == null) { map = new ConcurrentWeakHashMap<PsiElement, Pair<PsiMethod, PsiSubstitutor>>(); CURRENT_CANDIDATE.set(map); } final PsiMethod method = getElement(); final Pair<PsiMethod, PsiSubstitutor> alreadyThere = includeReturnConstraint ? map.put(getMarkerList(), Pair.create(method, super.getSubstitutor())) : null; try { PsiTypeParameter[] typeParameters = method.getTypeParameters(); if (!method.hasModifierProperty(PsiModifier.STATIC)) { final PsiClass containingClass = method.getContainingClass(); if (containingClass != null && PsiUtil.isRawSubstitutor(containingClass, mySubstitutor)) { Project project = containingClass.getProject(); JavaPsiFacade javaPsiFacade = JavaPsiFacade.getInstance(project); return javaPsiFacade.getElementFactory().createRawSubstitutor(mySubstitutor, typeParameters); } } final PsiElement parent = getParent(); if (parent == null) return PsiSubstitutor.EMPTY; Project project = method.getProject(); JavaPsiFacade javaPsiFacade = JavaPsiFacade.getInstance(project); return javaPsiFacade.getResolveHelper() .inferTypeArguments(typeParameters, method.getParameterList().getParameters(), arguments, mySubstitutor, parent, policy, myLanguageLevel); } finally { if (alreadyThere == null) map.remove(getMarkerList()); } } protected PsiElement getMarkerList() { return myArgumentList; } public boolean isInferencePossible() { return myArgumentList != null && myArgumentList.isValid(); } public static Pair<PsiMethod, PsiSubstitutor> getCurrentMethod(PsiElement context) { final Map<PsiElement,Pair<PsiMethod,PsiSubstitutor>> currentMethodCandidates = CURRENT_CANDIDATE.get(); return currentMethodCandidates != null ? currentMethodCandidates.get(context) : null; } public static void updateSubstitutor(PsiElement context, PsiSubstitutor newSubstitutor) { final Map<PsiElement,Pair<PsiMethod,PsiSubstitutor>> currentMethodCandidates = CURRENT_CANDIDATE.get(); if (currentMethodCandidates != null) { final Pair<PsiMethod, PsiSubstitutor> pair = currentMethodCandidates.get(context); if (pair != null) { currentMethodCandidates.put(context, Pair.create(pair.first, newSubstitutor)); } } } public static class ApplicabilityLevel { public static final int NOT_APPLICABLE = 1; public static final int VARARGS = 2; public static final int FIXED_ARITY = 3; } @MagicConstant(intValues = {ApplicabilityLevel.NOT_APPLICABLE, ApplicabilityLevel.VARARGS, ApplicabilityLevel.FIXED_ARITY}) public @interface ApplicabilityLevelConstant { } }
java/java-psi-api/src/com/intellij/psi/infos/MethodCandidateInfo.java
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.psi.infos; import com.intellij.openapi.project.Project; import com.intellij.openapi.projectRoots.JavaSdkVersion; import com.intellij.openapi.projectRoots.JavaVersionService; import com.intellij.openapi.util.Computable; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.RecursionGuard; import com.intellij.openapi.util.RecursionManager; import com.intellij.pom.java.LanguageLevel; import com.intellij.psi.*; import com.intellij.psi.impl.source.resolve.DefaultParameterTypeInferencePolicy; import com.intellij.psi.impl.source.resolve.ParameterTypeInferencePolicy; import com.intellij.psi.util.PsiUtil; import com.intellij.util.containers.ConcurrentWeakHashMap; import org.intellij.lang.annotations.MagicConstant; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Map; /** * @author ik, dsl */ public class MethodCandidateInfo extends CandidateInfo{ public static final RecursionGuard ourOverloadGuard = RecursionManager.createGuard("overload.guard"); public static final ThreadLocal<Map<PsiElement, Pair<PsiMethod, PsiSubstitutor>>> CURRENT_CANDIDATE = new ThreadLocal<Map<PsiElement, Pair<PsiMethod, PsiSubstitutor>>>(); @ApplicabilityLevelConstant private int myApplicabilityLevel = 0; private final PsiElement myArgumentList; private final PsiType[] myArgumentTypes; private final PsiType[] myTypeArguments; private PsiSubstitutor myCalcedSubstitutor = null; private final LanguageLevel myLanguageLevel; public MethodCandidateInfo(PsiElement candidate, PsiSubstitutor substitutor, boolean accessProblem, boolean staticsProblem, PsiElement argumentList, PsiElement currFileContext, @Nullable PsiType[] argumentTypes, PsiType[] typeArguments) { this(candidate, substitutor, accessProblem, staticsProblem, argumentList, currFileContext, argumentTypes, typeArguments, PsiUtil.getLanguageLevel(argumentList)); } public MethodCandidateInfo(PsiElement candidate, PsiSubstitutor substitutor, boolean accessProblem, boolean staticsProblem, PsiElement argumentList, PsiElement currFileContext, @Nullable PsiType[] argumentTypes, PsiType[] typeArguments, @NotNull LanguageLevel languageLevel) { super(candidate, substitutor, accessProblem, staticsProblem, currFileContext); myArgumentList = argumentList; myArgumentTypes = argumentTypes; myTypeArguments = typeArguments; myLanguageLevel = languageLevel; } public boolean isApplicable(){ return getApplicabilityLevel() != ApplicabilityLevel.NOT_APPLICABLE; } @ApplicabilityLevelConstant private int getApplicabilityLevelInner() { if (myArgumentTypes == null) return ApplicabilityLevel.NOT_APPLICABLE; int level = PsiUtil.getApplicabilityLevel(getElement(), getSubstitutor(), myArgumentTypes, myLanguageLevel); if (level > ApplicabilityLevel.NOT_APPLICABLE && !isTypeArgumentsApplicable()) level = ApplicabilityLevel.NOT_APPLICABLE; return level; } @ApplicabilityLevelConstant public int getApplicabilityLevel() { if(myApplicabilityLevel == 0){ myApplicabilityLevel = getApplicabilityLevelInner(); } return myApplicabilityLevel; } @ApplicabilityLevelConstant public int getPertinentApplicabilityLevel() { if (myTypeArguments != null) { return getApplicabilityLevel(); } final PsiMethod method = getElement(); if (method != null && method.hasTypeParameters() || myArgumentList == null || !PsiUtil.isLanguageLevel8OrHigher(myArgumentList)) { @ApplicabilityLevelConstant int level; if (myArgumentTypes == null) { return ApplicabilityLevel.NOT_APPLICABLE; } else { final PsiSubstitutor substitutor = getSubstitutor(); level = ourOverloadGuard.doPreventingRecursion(myArgumentList, false, new Computable<Integer>() { @Override public Integer compute() { return PsiUtil.getApplicabilityLevel(getElement(), substitutor, myArgumentTypes, myLanguageLevel); } }); } if (level > ApplicabilityLevel.NOT_APPLICABLE && !isTypeArgumentsApplicable()) level = ApplicabilityLevel.NOT_APPLICABLE; return level; } return ourOverloadGuard.doPreventingRecursion(myArgumentList, false, new Computable<Integer>() { @Override public Integer compute() { return getApplicabilityLevelInner(); } }); } public PsiSubstitutor getSiteSubstitutor() { return super.getSubstitutor(); } @Override public PsiSubstitutor getSubstitutor() { return getSubstitutor(true); } public PsiSubstitutor getSubstitutor(boolean includeReturnConstraint) { if (myCalcedSubstitutor == null || !includeReturnConstraint) { PsiSubstitutor incompleteSubstitutor = super.getSubstitutor(); PsiMethod method = getElement(); if (myTypeArguments == null) { final RecursionGuard.StackStamp stackStamp = PsiDiamondType.ourDiamondGuard.markStack(); final PsiSubstitutor inferredSubstitutor = inferTypeArguments(DefaultParameterTypeInferencePolicy.INSTANCE, includeReturnConstraint); if (!stackStamp.mayCacheNow() || !includeReturnConstraint) { return inferredSubstitutor; } myCalcedSubstitutor = inferredSubstitutor; } else { PsiTypeParameter[] typeParams = method.getTypeParameters(); for (int i = 0; i < myTypeArguments.length && i < typeParams.length; i++) { incompleteSubstitutor = incompleteSubstitutor.put(typeParams[i], myTypeArguments[i]); } myCalcedSubstitutor = incompleteSubstitutor; } } return myCalcedSubstitutor; } public boolean isTypeArgumentsApplicable() { final PsiMethod psiMethod = getElement(); PsiTypeParameter[] typeParams = psiMethod.getTypeParameters(); if (myTypeArguments != null && typeParams.length != myTypeArguments.length && !PsiUtil.isLanguageLevel7OrHigher(psiMethod)){ return typeParams.length == 0 && JavaVersionService.getInstance().isAtLeast(psiMethod, JavaSdkVersion.JDK_1_7); } PsiSubstitutor substitutor = getSubstitutor(); return GenericsUtil.isTypeArgumentsApplicable(typeParams, substitutor, getParent()); } protected PsiElement getParent() { return myArgumentList != null ? myArgumentList.getParent() : myArgumentList; } @Override public boolean isValidResult(){ return super.isValidResult() && isApplicable(); } @Override public PsiMethod getElement(){ return (PsiMethod)super.getElement(); } public PsiSubstitutor inferTypeArguments(@NotNull ParameterTypeInferencePolicy policy, boolean includeReturnConstraint) { return inferTypeArguments(policy, myArgumentList instanceof PsiExpressionList ? ((PsiExpressionList)myArgumentList).getExpressions() : PsiExpression.EMPTY_ARRAY, includeReturnConstraint); } public PsiSubstitutor inferSubstitutorFromArgs(@NotNull ParameterTypeInferencePolicy policy, final PsiExpression[] arguments) { if (myTypeArguments == null) { return inferTypeArguments(policy, arguments, true); } else { PsiSubstitutor incompleteSubstitutor = super.getSubstitutor(); PsiMethod method = getElement(); if (method != null) { PsiTypeParameter[] typeParams = method.getTypeParameters(); for (int i = 0; i < myTypeArguments.length && i < typeParams.length; i++) { incompleteSubstitutor = incompleteSubstitutor.put(typeParams[i], myTypeArguments[i]); } } return incompleteSubstitutor; } } public PsiSubstitutor inferTypeArguments(@NotNull ParameterTypeInferencePolicy policy, @NotNull PsiExpression[] arguments, boolean includeReturnConstraint) { Map<PsiElement, Pair<PsiMethod, PsiSubstitutor>> map = CURRENT_CANDIDATE.get(); if (map == null) { map = new ConcurrentWeakHashMap<PsiElement, Pair<PsiMethod, PsiSubstitutor>>(); CURRENT_CANDIDATE.set(map); } final PsiMethod method = getElement(); final Pair<PsiMethod, PsiSubstitutor> alreadyThere = includeReturnConstraint ? map.put(getMarkerList(), Pair.create(method, super.getSubstitutor())) : null; try { PsiTypeParameter[] typeParameters = method.getTypeParameters(); if (!method.hasModifierProperty(PsiModifier.STATIC)) { final PsiClass containingClass = method.getContainingClass(); if (containingClass != null && PsiUtil.isRawSubstitutor(containingClass, mySubstitutor)) { Project project = containingClass.getProject(); JavaPsiFacade javaPsiFacade = JavaPsiFacade.getInstance(project); return javaPsiFacade.getElementFactory().createRawSubstitutor(mySubstitutor, typeParameters); } } final PsiElement parent = getParent(); if (parent == null) return PsiSubstitutor.EMPTY; Project project = method.getProject(); JavaPsiFacade javaPsiFacade = JavaPsiFacade.getInstance(project); return javaPsiFacade.getResolveHelper() .inferTypeArguments(typeParameters, method.getParameterList().getParameters(), arguments, mySubstitutor, parent, policy, myLanguageLevel); } finally { if (alreadyThere == null) map.remove(getMarkerList()); } } protected PsiElement getMarkerList() { return myArgumentList; } public boolean isInferencePossible() { return myArgumentList != null && myArgumentList.isValid(); } public static Pair<PsiMethod, PsiSubstitutor> getCurrentMethod(PsiElement context) { final Map<PsiElement,Pair<PsiMethod,PsiSubstitutor>> currentMethodCandidates = CURRENT_CANDIDATE.get(); return currentMethodCandidates != null ? currentMethodCandidates.get(context) : null; } public static void updateSubstitutor(PsiElement context, PsiSubstitutor newSubstitutor) { final Map<PsiElement,Pair<PsiMethod,PsiSubstitutor>> currentMethodCandidates = CURRENT_CANDIDATE.get(); if (currentMethodCandidates != null) { final Pair<PsiMethod, PsiSubstitutor> pair = currentMethodCandidates.get(context); if (pair != null) { currentMethodCandidates.put(context, Pair.create(pair.first, newSubstitutor)); } } } public static class ApplicabilityLevel { public static final int NOT_APPLICABLE = 1; public static final int VARARGS = 2; public static final int FIXED_ARITY = 3; } @MagicConstant(intValues = {ApplicabilityLevel.NOT_APPLICABLE, ApplicabilityLevel.VARARGS, ApplicabilityLevel.FIXED_ARITY}) public @interface ApplicabilityLevelConstant { } }
EA-52505 - NPE: MethodCandidateInfo.getPertinentApplicabilityLevel
java/java-psi-api/src/com/intellij/psi/infos/MethodCandidateInfo.java
EA-52505 - NPE: MethodCandidateInfo.getPertinentApplicabilityLevel
Java
apache-2.0
c6ec523203169152bcece6b4f9684c33c0601ab1
0
alibaba/fastjson,alibaba/fastjson,alibaba/fastjson,alibaba/fastjson
/* * Copyright 1999-2017 Alibaba Group. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.fastjson.parser; /** * @author wenshao[[email protected]] */ public enum Feature { /** * */ AutoCloseSource, /** * */ AllowComment, /** * */ AllowUnQuotedFieldNames, /** * */ AllowSingleQuotes, /** * */ InternFieldNames, /** * */ AllowISO8601DateFormat, /** * {"a":1,,,"b":2} */ AllowArbitraryCommas, /** * */ UseBigDecimal, /** * @since 1.1.2 */ IgnoreNotMatch, /** * @since 1.1.3 */ SortFeidFastMatch, /** * @since 1.1.3 */ DisableASM, /** * @since 1.1.7 */ DisableCircularReferenceDetect, /** * @since 1.1.10 */ InitStringFieldAsEmpty, /** * @since 1.1.35 * */ SupportArrayToBean, /** * @since 1.2.3 * */ OrderedField, /** * @since 1.2.5 * */ DisableSpecialKeyDetect, /** * @since 1.2.9 */ UseObjectArray, /** * @since 1.2.22, 1.1.54.android */ SupportNonPublicField, /** * @since 1.2.29 * * disable autotype key '@type' */ IgnoreAutoType ; Feature(){ mask = (1 << ordinal()); } public final int mask; public final int getMask() { return mask; } public static boolean isEnabled(int features, Feature feature) { return (features & feature.mask) != 0; } public static int config(int features, Feature feature, boolean state) { if (state) { features |= feature.mask; } else { features &= ~feature.mask; } return features; } public static int of(Feature[] features) { if (features == null) { return 0; } int value = 0; for (Feature feature: features) { value |= feature.mask; } return value; } }
src/main/java/com/alibaba/fastjson/parser/Feature.java
/* * Copyright 1999-2017 Alibaba Group. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.fastjson.parser; /** * @author wenshao[[email protected]] */ public enum Feature { /** * */ AutoCloseSource, /** * */ AllowComment, /** * */ AllowUnQuotedFieldNames, /** * */ AllowSingleQuotes, /** * */ InternFieldNames, /** * */ AllowISO8601DateFormat, /** * {"a":1,,,"b":2} */ AllowArbitraryCommas, /** * */ UseBigDecimal, /** * @since 1.1.2 */ IgnoreNotMatch, /** * @since 1.1.3 */ SortFeidFastMatch, /** * @since 1.1.3 */ DisableASM, /** * @since 1.1.7 */ DisableCircularReferenceDetect, /** * @since 1.1.10 */ InitStringFieldAsEmpty, /** * @since 1.1.35 * */ SupportArrayToBean, /** * @since 1.2.3 * */ OrderedField, /** * @since 1.2.5 * */ DisableSpecialKeyDetect, /** * @since 1.2.9 */ UseObjectArray, /** * @since 1.2.22, 1.1.54.android */ SupportNonPublicField, IgnoreType ; Feature(){ mask = (1 << ordinal()); } public final int mask; public final int getMask() { return mask; } public static boolean isEnabled(int features, Feature feature) { return (features & feature.mask) != 0; } public static int config(int features, Feature feature, boolean state) { if (state) { features |= feature.mask; } else { features &= ~feature.mask; } return features; } public static int of(Feature[] features) { if (features == null) { return 0; } int value = 0; for (Feature feature: features) { value |= feature.mask; } return value; } }
rename feature.
src/main/java/com/alibaba/fastjson/parser/Feature.java
rename feature.
Java
apache-2.0
eddc240a37e5c6da04c4039c5795e099f098f37d
0
raphw/byte-buddy,raphw/byte-buddy,DALDEI/byte-buddy,CodingFabian/byte-buddy,vic/byte-buddy,raphw/byte-buddy,mches/byte-buddy
package net.bytebuddy.dynamic.scaffold; import net.bytebuddy.description.method.MethodDescription; import net.bytebuddy.description.type.TypeDescription; import java.util.*; public interface MethodGraph extends MethodLookupEngine.Finding { interface Factory { MethodGraph make(TypeDescription typeDescription); class Default implements Factory { @Override public MethodGraph make(TypeDescription typeDescription) { return null; } protected static class Key { public static Key of(MethodDescription methodDescription) { return new Key(methodDescription.getInternalName(), Collections.singleton(methodDescription.asToken())); } private final String internalName; private final Set<MethodDescription.Token> keys; protected Key(String internalName, Set<MethodDescription.Token> keys) { this.internalName = internalName; this.keys = keys; } protected Key expand(MethodDescription.InDefinedShape methodDescription) { Set<MethodDescription.Token> keys = new HashSet<MethodDescription.Token>(this.keys); keys.add(methodDescription.asToken()); return new Key(internalName, keys); } @Override public boolean equals(Object other) { return other == this || (other instanceof Key && !Collections.disjoint(keys, ((Key) other).keys)); } @Override public int hashCode() { return internalName.hashCode(); } protected static class Store { private final Map<Key, Entry> entries; protected Store() { this(Collections.<Key, Entry>emptyMap()); } private Store(Map<Key, Entry> entries) { this.entries = entries; } protected Store register(MethodDescription methodDescription) { Key key = Key.of(methodDescription); Entry currentEntry = entries.get(key); Entry expandedEntry = (currentEntry == null ? new Entry(key, methodDescription) : currentEntry).expand(methodDescription); Map<Key, Entry> entries = new HashMap<Key, Entry>(this.entries); entries.put(expandedEntry.getKey(), expandedEntry); return new Store(entries); } protected static class Entry { private final Key key; private final MethodDescription methodDescription; protected Entry(Key key, MethodDescription methodDescription) { this.key = key; this.methodDescription = methodDescription; } protected Entry expand(MethodDescription methodDescription) { return new Entry(key.expand(methodDescription.asDefined()), methodDescription); } protected Key getKey() { return key; } } } } } } }
byte-buddy-dep/src/main/java/net/bytebuddy/dynamic/scaffold/MethodGraph.java
package net.bytebuddy.dynamic.scaffold; import net.bytebuddy.description.method.MethodDescription; import net.bytebuddy.description.type.TypeDescription; import net.bytebuddy.description.type.generic.GenericTypeDescription; import java.util.*; public interface MethodGraph { MethodDescription locate(MethodDescription.Token methodToken); interface Factory { MethodGraph make(TypeDescription typeDescription); class Default implements Factory { @Override public MethodGraph make(TypeDescription typeDescription) { return null; } protected static class KeyCollection { private final String internalName; private final Set<MethodDescription.Token> keys; protected KeyCollection(String internalName, Set<MethodDescription.Token> keys) { this.internalName = internalName; this.keys = keys; } @Override public boolean equals(Object other) { return other == this || other instanceof KeyCollection && !Collections.disjoint(keys, ((KeyCollection) other).keys); } @Override public int hashCode() { return internalName.hashCode(); } } } } }
Added registry to method graph.
byte-buddy-dep/src/main/java/net/bytebuddy/dynamic/scaffold/MethodGraph.java
Added registry to method graph.
Java
bsd-2-clause
533c8e7d2f98185aaef0edbe36d86b26a3be4152
0
KnisterPeter/Smaller,KnisterPeter/Smaller,KnisterPeter/Smaller,KnisterPeter/Smaller
package de.matrixweb.smaller.osgi.http; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintStream; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOUtils; import org.codehaus.jackson.map.ObjectMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import de.matrixweb.smaller.common.Manifest; import de.matrixweb.smaller.common.SmallerException; import de.matrixweb.smaller.common.Task; import de.matrixweb.smaller.common.Task.GlobalOptions; import de.matrixweb.smaller.common.Zip; import de.matrixweb.smaller.pipeline.Pipeline; import de.matrixweb.smaller.pipeline.Result; import de.matrixweb.smaller.resource.FileResourceResolver; import de.matrixweb.smaller.resource.ResourceResolver; import de.matrixweb.smaller.resource.Type; /** * @author marwol */ public class Servlet extends HttpServlet { private static final Logger LOGGER = LoggerFactory.getLogger(Servlet.class); private static final long serialVersionUID = -3500628755781284892L; private final Pipeline pipeline; /** * @param pipeline */ public Servlet(final Pipeline pipeline) { super(); this.pipeline = pipeline; } /** * @see javax.servlet.http.HttpServlet#service(javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse) */ @Override protected void service(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { LOGGER.info("Handle smaller request from {} {}", request.getRemoteAddr(), request.getRequestURI()); final OutputStream out = response.getOutputStream(); if ("/".equals(request.getRequestURI())) { executePipeline(request, response, out); } else { final PrintStream print = new PrintStream(out); print.print("hallo welt"); out.close(); } } private void executePipeline(final HttpServletRequest request, final HttpServletResponse response, final OutputStream out) throws IOException { Context context = null; try { context = setUpContext(request.getInputStream()); final ResourceResolver resolver = new FileResourceResolver( context.sourceDir.getAbsolutePath()); Task task = context.manifest.getNext(); while (task != null) { writeResults(this.pipeline.execute(resolver, task), context.targetDir, task); task = context.manifest.getNext(); } Zip.zip(out, context.targetDir); setResponseHeader(response, "OK", null); } catch (final SmallerException e) { LOGGER.error("Error during smaller execution", e); handleSmallerException(response, e); } catch (final InvalidRequestException e) { LOGGER.error(e.toString()); } catch (final IOException e) { LOGGER.error("Error during smaller execution", e); setResponseHeader(response, "ERROR", "Exception during execution"); } finally { if (context != null) { context.inputZip.delete(); FileUtils.deleteDirectory(context.sourceDir); FileUtils.deleteDirectory(context.targetDir); } IOUtils.closeQuietly(out); } } private Context setUpContext(final InputStream is) throws IOException { try { final Context context = unzip(is); final Manifest manifest = new ObjectMapper().readValue( getMainFile(context.sourceDir), Manifest.class); File output = context.sourceDir; if (GlobalOptions.isOutOnly(manifest.getTasks()[0])) { output = File.createTempFile("smaller-output", ".dir"); output.delete(); output.mkdirs(); } context.targetDir = output; context.manifest = manifest; return context; } finally { IOUtils.closeQuietly(is); } } private Context unzip(final InputStream is) throws IOException { final Context context = storeZip(is); final File base = File.createTempFile("smaller-work", ".dir"); try { base.delete(); base.mkdir(); Zip.unzip(context.inputZip, base); } catch (final IOException e) { FileUtils.deleteDirectory(base); if (context.inputZip != null) { context.inputZip.delete(); } throw e; } context.sourceDir = base; return context; } private Context storeZip(final InputStream in) throws IOException { final File temp = File.createTempFile("smaller-input", ".zip"); try { temp.delete(); FileOutputStream out = null; try { if (in.available() <= 0) { throw new InvalidRequestException( "Invalid attachment size; rejecting request"); } else { out = new FileOutputStream(temp); IOUtils.copy(in, out); } } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } } catch (final IOException e) { FileUtils.deleteDirectory(temp); throw e; } final Context context = new Context(); context.inputZip = temp; return context; } private File getMainFile(final File input) { File main = new File(input, "META-INF/MAIN.json"); if (!main.exists()) { // Old behaviour: Search directly in root of zip main = new File(input, "MAIN.json"); if (!main.exists()) { throw new SmallerException( "Missing instructions file 'META-INF/MAIN.json'"); } } return main; } private void writeResults(final Result result, final File outputDir, final Task task) throws IOException { writeResult(outputDir, task, result, Type.JS); writeResult(outputDir, task, result, Type.CSS); } private void writeResult(final File output, final Task task, final Result result, final Type type) throws IOException { final String outputFile = getTargetFile(output, task.getOut(), type); if (outputFile != null) { FileUtils.writeStringToFile(new File(outputFile), result.get(type) .getContents()); } } private String getTargetFile(final File base, final String[] out, final Type type) { String target = null; for (final String s : out) { final String ext = FilenameUtils.getExtension(s); switch (type) { case JS: if (ext.equals("js")) { target = new File(base, s).getAbsolutePath(); } break; case CSS: if (ext.equals("css")) { target = new File(base, s).getAbsolutePath(); } break; default: throw new SmallerException("Invalid resource type " + type); } } return target; } private void handleSmallerException(final HttpServletResponse response, final SmallerException e) { final StringBuilder message = new StringBuilder(e.getMessage()); Throwable t = e.getCause(); while (t != null) { message.append(": ").append(t.getMessage()); t = t.getCause(); } setResponseHeader(response, "ERROR", message.toString().replace("\n", "#@@#")); } private void setResponseHeader(final HttpServletResponse response, final String status, final String message) { response.setHeader("X-Smaller-Status", status); if (message != null) { response.setHeader("X-Smaller-Message", message); } } private static class Context { private File inputZip; private File sourceDir; private File targetDir; private Manifest manifest; } private static class InvalidRequestException extends IOException { private static final long serialVersionUID = 4298402581130531621L; /** * @param message */ public InvalidRequestException(final String message) { super(message); } } }
server/osgi-http/src/main/java/de/matrixweb/smaller/osgi/http/Servlet.java
package de.matrixweb.smaller.osgi.http; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintStream; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOUtils; import org.codehaus.jackson.map.ObjectMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import de.matrixweb.smaller.common.Manifest; import de.matrixweb.smaller.common.SmallerException; import de.matrixweb.smaller.common.Task; import de.matrixweb.smaller.common.Task.GlobalOptions; import de.matrixweb.smaller.common.Zip; import de.matrixweb.smaller.pipeline.Pipeline; import de.matrixweb.smaller.pipeline.Result; import de.matrixweb.smaller.resource.FileResourceResolver; import de.matrixweb.smaller.resource.ResourceResolver; import de.matrixweb.smaller.resource.Type; /** * @author marwol */ public class Servlet extends HttpServlet { private static final Logger LOGGER = LoggerFactory.getLogger(Servlet.class); private static final long serialVersionUID = -3500628755781284892L; private final Pipeline pipeline; /** * @param pipeline */ public Servlet(final Pipeline pipeline) { super(); this.pipeline = pipeline; } /** * @see javax.servlet.http.HttpServlet#service(javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse) */ @Override protected void service(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { LOGGER.info("Handle smaller request from {} {}", request.getRemoteAddr(), request.getRequestURI()); final OutputStream out = response.getOutputStream(); if ("/".equals(request.getRequestURI())) { executePipeline(request, response, out); } else { final PrintStream print = new PrintStream(out); print.print("hallo welt"); out.close(); } } private void executePipeline(final HttpServletRequest request, final HttpServletResponse response, final OutputStream out) throws IOException { Context context = null; try { context = setUpContext(request.getInputStream()); final ResourceResolver resolver = new FileResourceResolver( context.sourceDir.getAbsolutePath()); Task task = context.manifest.getNext(); while (task != null) { writeResults(this.pipeline.execute(resolver, task), context.targetDir, task); task = context.manifest.getNext(); } Zip.zip(out, context.targetDir); setResponseHeader(response, "OK", null); } catch (final SmallerException e) { LOGGER.error("Error during smaller execution", e); handleSmallerException(response, e); } catch (final InvalidRequestException e) { LOGGER.error(e.toString()); } catch (final IOException e) { LOGGER.error("Error during smaller execution", e); setResponseHeader(response, "ERROR", "Exception during execution"); } finally { if (context != null) { context.inputZip.delete(); FileUtils.deleteDirectory(context.sourceDir); FileUtils.deleteDirectory(context.targetDir); } IOUtils.closeQuietly(out); } } private Context setUpContext(final InputStream is) throws IOException { try { final Context context = unzip(is); final Manifest manifest = new ObjectMapper().readValue( getMainFile(context.sourceDir), Manifest.class); File output = context.sourceDir; if (GlobalOptions.isOutOnly(manifest.getTasks()[0])) { output = File.createTempFile("smaller-output", ".dir"); output.delete(); output.mkdirs(); } context.targetDir = output; context.manifest = manifest; return context; } finally { IOUtils.closeQuietly(is); } } private Context unzip(final InputStream is) throws IOException { final Context context = storeZip(is); final File base = File.createTempFile("smaller-work", ".dir"); base.delete(); base.mkdir(); Zip.unzip(context.inputZip, base); context.sourceDir = base; return context; } private Context storeZip(final InputStream in) throws IOException { final File temp = File.createTempFile("smaller-input", ".zip"); temp.delete(); FileOutputStream out = null; try { if (in.available() <= 0) { throw new InvalidRequestException( "Invalid attachment size; rejecting request"); } else { out = new FileOutputStream(temp); IOUtils.copy(in, out); } } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } final Context context = new Context(); context.inputZip = temp; return context; } private File getMainFile(final File input) { File main = new File(input, "META-INF/MAIN.json"); if (!main.exists()) { // Old behaviour: Search directly in root of zip main = new File(input, "MAIN.json"); if (!main.exists()) { throw new SmallerException( "Missing instructions file 'META-INF/MAIN.json'"); } } return main; } private void writeResults(final Result result, final File outputDir, final Task task) throws IOException { writeResult(outputDir, task, result, Type.JS); writeResult(outputDir, task, result, Type.CSS); } private void writeResult(final File output, final Task task, final Result result, final Type type) throws IOException { final String outputFile = getTargetFile(output, task.getOut(), type); if (outputFile != null) { FileUtils.writeStringToFile(new File(outputFile), result.get(type) .getContents()); } } private String getTargetFile(final File base, final String[] out, final Type type) { String target = null; for (final String s : out) { final String ext = FilenameUtils.getExtension(s); switch (type) { case JS: if (ext.equals("js")) { target = new File(base, s).getAbsolutePath(); } break; case CSS: if (ext.equals("css")) { target = new File(base, s).getAbsolutePath(); } break; default: throw new SmallerException("Invalid resource type " + type); } } return target; } private void handleSmallerException(final HttpServletResponse response, final SmallerException e) { final StringBuilder message = new StringBuilder(e.getMessage()); Throwable t = e.getCause(); while (t != null) { message.append(": ").append(t.getMessage()); t = t.getCause(); } setResponseHeader(response, "ERROR", message.toString().replace("\n", "#@@#")); } private void setResponseHeader(final HttpServletResponse response, final String status, final String message) { response.setHeader("X-Smaller-Status", status); if (message != null) { response.setHeader("X-Smaller-Message", message); } } private static class Context { private File inputZip; private File sourceDir; private File targetDir; private Manifest manifest; } private static class InvalidRequestException extends IOException { private static final long serialVersionUID = 4298402581130531621L; /** * @param message */ public InvalidRequestException(final String message) { super(message); } } }
Clean temp resources in case of io error
server/osgi-http/src/main/java/de/matrixweb/smaller/osgi/http/Servlet.java
Clean temp resources in case of io error
Java
bsd-2-clause
0cd5ed802fcbc0d7682186370a96da6f81a2e947
0
Ryszard-Trojnacki/nifty-gui,bgroenks96/nifty-gui,Ryszard-Trojnacki/nifty-gui,void256/nifty-gui,atomixnmc/nifty-gui,gouessej/nifty-gui,atomixnmc/nifty-gui,void256/nifty-gui,Teencrusher/nifty-gui,relu91/nifty-gui,Teencrusher/nifty-gui,bgroenks96/nifty-gui,mkaring/nifty-gui,xranby/nifty-gui
package de.lessvoid.nifty.renderer.lwjgl.input; import java.nio.IntBuffer; import java.util.ArrayList; import java.util.List; import org.lwjgl.BufferUtils; import org.lwjgl.input.Keyboard; import org.lwjgl.input.Mouse; import org.lwjgl.opengl.GL11; import de.lessvoid.nifty.NiftyInputConsumer; import de.lessvoid.nifty.input.keyboard.KeyboardInputEvent; import de.lessvoid.nifty.input.mouse.MouseInputEvent; import de.lessvoid.nifty.spi.input.InputSystem; public class LwjglInputSystem implements InputSystem { private boolean lastLeftMouseDown = false; private LwjglKeyboardInputEventCreator keyboardEventCreator = new LwjglKeyboardInputEventCreator(); private List<KeyboardInputEvent> keyboardEvents = new ArrayList<KeyboardInputEvent>(); private IntBuffer viewportBuffer = BufferUtils.createIntBuffer(4 * 4); public void startup() throws Exception { Mouse.create(); Keyboard.create(); Keyboard.enableRepeatEvents(true); } public void shutdown() { Mouse.destroy(); Keyboard.destroy(); } public void forwardEvents(final NiftyInputConsumer inputEventConsumer) { processMouseEvents(inputEventConsumer); processKeyboardEvents(inputEventConsumer); } private void processMouseEvents(final NiftyInputConsumer inputEventConsumer) { GL11.glGetInteger(GL11.GL_VIEWPORT, viewportBuffer); int viewportHeight = viewportBuffer.get(3); while (Mouse.next()) { int mouseX = Mouse.getEventX(); int mouseY = viewportHeight - Mouse.getEventY(); if (Mouse.getEventButton() == 0) { boolean leftMouseButton = Mouse.getEventButtonState(); if (leftMouseButton != lastLeftMouseDown) { lastLeftMouseDown = leftMouseButton; } } MouseInputEvent inputEvent = new MouseInputEvent(mouseX, mouseY, lastLeftMouseDown); inputEventConsumer.processMouseEvent(inputEvent); } } private void processKeyboardEvents(final NiftyInputConsumer inputEventConsumer) { keyboardEvents.clear(); while (Keyboard.next()) { inputEventConsumer.processKeyboardEvent(keyboardEventCreator.createEvent(Keyboard.getEventKey(), Keyboard.getEventCharacter(), Keyboard.getEventKeyState())); } } }
src/main/java/de/lessvoid/nifty/renderer/lwjgl/input/LwjglInputSystem.java
package de.lessvoid.nifty.renderer.lwjgl.input; import java.util.ArrayList; import java.util.List; import org.lwjgl.input.Keyboard; import org.lwjgl.input.Mouse; import org.lwjgl.opengl.Display; import de.lessvoid.nifty.NiftyInputConsumer; import de.lessvoid.nifty.input.keyboard.KeyboardInputEvent; import de.lessvoid.nifty.input.mouse.MouseInputEvent; import de.lessvoid.nifty.spi.input.InputSystem; public class LwjglInputSystem implements InputSystem { private boolean lastLeftMouseDown = false; private LwjglKeyboardInputEventCreator keyboardEventCreator = new LwjglKeyboardInputEventCreator(); private List<KeyboardInputEvent> keyboardEvents = new ArrayList<KeyboardInputEvent>(); public void startup() throws Exception { Mouse.create(); Keyboard.create(); Keyboard.enableRepeatEvents(true); } public void shutdown() { Mouse.destroy(); Keyboard.destroy(); } public void forwardEvents(final NiftyInputConsumer inputEventConsumer) { processMouseEvents(inputEventConsumer); processKeyboardEvents(inputEventConsumer); } private void processMouseEvents(final NiftyInputConsumer inputEventConsumer) { while (Mouse.next()) { int mouseX = Mouse.getEventX(); int mouseY = Display.getDisplayMode().getHeight() - Mouse.getEventY(); if (Mouse.getEventButton() == 0) { boolean leftMouseButton = Mouse.getEventButtonState(); if (leftMouseButton != lastLeftMouseDown) { lastLeftMouseDown = leftMouseButton; } } MouseInputEvent inputEvent = new MouseInputEvent(mouseX, mouseY, lastLeftMouseDown); inputEventConsumer.processMouseEvent(inputEvent); } } private void processKeyboardEvents(final NiftyInputConsumer inputEventConsumer) { keyboardEvents.clear(); while (Keyboard.next()) { inputEventConsumer.processKeyboardEvent(keyboardEventCreator.createEvent(Keyboard.getEventKey(), Keyboard.getEventCharacter(), Keyboard.getEventKeyState())); } } }
@public added a patch from Hayden to fix mouse coordinates when running LWJGL Nifty in an applet (mouse coordinates where calculated with desktop and not with window/viewport coordinates)
src/main/java/de/lessvoid/nifty/renderer/lwjgl/input/LwjglInputSystem.java
@public added a patch from Hayden to fix mouse coordinates when running LWJGL Nifty in an applet (mouse coordinates where calculated with desktop and not with window/viewport coordinates)
Java
bsd-3-clause
e1bef52e2110e5f7b92d4c0d2780c7d940fa6e42
0
Simsilica/SimEthereal
/* * $Id$ * * Copyright (c) 2015, Simsilica, LLC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.simsilica.ethereal.zone; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.CopyOnWriteArraySet; import java.util.concurrent.atomic.AtomicBoolean; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Uses a background thread to periodically collect the accumulated * state for the zones and send the blocks of state to zone state * listeners. * * @author Paul Speed */ public class StateCollector { static Logger log = LoggerFactory.getLogger(StateCollector.class); private static final long NANOS_PER_SEC = 1000000000L; public static final long DEFAULT_PERIOD = NANOS_PER_SEC / 20; private ZoneManager zones; private long collectionPeriod; private long idleSleepTime = 1; // for our standard 20 FPS that's more than fine private final Runner runner = new Runner(); private final Set<StateListener> listeners = new CopyOnWriteArraySet<>(); private final ConcurrentLinkedQueue<StateListener> removed = new ConcurrentLinkedQueue<>(); /** * This is the actual zone interest management. It's only used by the * background thread which is why it is unsynchronized. All interactio * is done through the listeners set and removed queue. */ private final Map<ZoneKey,List<StateListener>> zoneListeners = new HashMap<>(); public StateCollector( ZoneManager zones ) { this(zones, DEFAULT_PERIOD); } public StateCollector( ZoneManager zones, long collectionPeriod ) { this.zones = zones; this.collectionPeriod = collectionPeriod == 0 ? DEFAULT_PERIOD : collectionPeriod; } public void start() { log.info("Starting state collector."); runner.start(); } public void shutdown() { log.info("Shuttong down state collector."); runner.close(); } /** * Adds a listener that self-indicates which specific zones * it is interested in from one frame to the next. This is necessary * so that it syncs with the background state collection in a way * that does not cause partial state, etc... it's also nicer to * to the background threads and synchronization if zone interest * is synched with updates. */ public void addListener( StateListener l ) { listeners.add(l); } public void removeListener( StateListener l ) { listeners.remove(l); removed.add(l); } /** * Sets the sleep() time for the state collector's idle periods. * This defaults to 1 which keeps the CPU happier while also providing * timely checks against the interval time. However, for higher rates of * state collection (lower collectionPeriods such as 16 ms or 60 FPS) on windows, * sleep(1) may take longer than 1/60th of a second or close enough to still * cause collection frame drops. In that case, it can be configured to 0 which * should provide timelier updates. * Set to -1 to avoid sleeping at all in which case the thread will consume 100% * of a single core in order to busy wait between collection intervals. */ public void setIdleSleepTime( long millis ) { this.idleSleepTime = millis; } public long getIdleSleepTime() { return idleSleepTime; } protected List<StateListener> getListeners( ZoneKey key, boolean create ) { List<StateListener> result = zoneListeners.get(key); if( result == null && create ) { result = new ArrayList<>(); zoneListeners.put(key, result); } return result; } protected void watch( ZoneKey key, StateListener l ) { if( log.isTraceEnabled() ) { log.trace("watch(" + key + ", " + l + ")"); } getListeners(key, true).add(l); } protected void unwatch( ZoneKey key, StateListener l ) { if( log.isTraceEnabled() ) { log.trace("unwatch(" + key + ", " + l + ")" ); } List<StateListener> list = getListeners(key, false); if( list == null ) { return; } list.remove(l); } protected void unwatchAll( StateListener l ) { if( log.isTraceEnabled() ) { log.trace("unwatchAll(" + l + ")" ); } for( List<StateListener> list : zoneListeners.values() ) { list.remove(l); } } /** * Called from the background thread when it first starts up. */ protected void initialize() { // Let the zone manager know that it can start collecting history zones.setCollectHistory(true); } protected void publish( StateBlock b ) { List<StateListener> list = getListeners(b.getZone(), false); if( list == null ) { return; } for( StateListener l : list ) { l.stateChanged(b); } } /** * Adjusts the per-listener zone interest based on latest * listener state, then publishes the state frame to all * interested listeners. */ protected void publishFrame( StateFrame frame ) { log.trace("publishFrame()"); for( StateListener l : listeners ) { if( l.hasChangedZones() ) { List<ZoneKey> exited = l.getExitedZones(); for( ZoneKey k : exited ) { unwatch( k, l ); } List<ZoneKey> entered = l.getEnteredZones(); for( ZoneKey k : entered ) { watch( k, l ); } } l.beginFrame(frame.getTime()); } for( StateBlock b : frame ) { publish( b ); } for( StateListener l : listeners ) { l.endFrame(frame.getTime()); } log.trace("end publishFrame()"); } /** * Called by the background thread to collect all * of the accumulated state since the last collection and * distribute it to the state listeners. This is called * once per "collectionPeriod". */ protected void collect() { log.trace("collect()"); // Purge any pending removals StateListener remove; while( (remove = removed.poll()) != null ) { unwatchAll(remove); } // Collect all state since the last time we asked // long start = System.nanoTime(); StateFrame[] frames = zones.purgeState(); // long end = System.nanoTime(); // System.out.println( "State purged in:" + ((end - start)/1000000.0) + " ms" ); for( StateListener l : listeners ) { l.beginFrameBlock(); } // start = end; for( StateFrame f : frames ) { if( f == null ) { continue; } publishFrame(f); } for( StateListener l : listeners ) { l.endFrameBlock(); } // end = System.nanoTime(); // System.out.println( "State published in:" + ((end - start)/1000000.0) + " ms" ); log.trace("end collect()"); } /** * Called by the background thread when it is shutting down. * Currently does nothing. */ protected void terminate() { // Let the zone manager know that it should stop collecting // history because we won't be purging it anymore. zones.setCollectHistory(false); } protected void collectionError( Exception e ) { log.error("Collection error", e); } private class Runner extends Thread { private final AtomicBoolean go = new AtomicBoolean(true); public Runner() { setName( "StateCollectionThread" ); //setPriority( Thread.MAX_PRIORITY ); } public void close() { go.set(false); try { join(); } catch( InterruptedException e ) { throw new RuntimeException( "Interrupted while waiting for physic thread to complete.", e ); } } @Override public void run() { initialize(); long lastTime = System.nanoTime(); long counter = 0; long nextCountTime = lastTime + 1000000000L; while( go.get() ) { long time = System.nanoTime(); long delta = time - lastTime; if( delta >= collectionPeriod ) { // Time to collect lastTime = time; try { collect(); counter++; //long end = System.nanoTime(); //delta = end - time; } catch( Exception e ) { collectionError(e); } if( lastTime > nextCountTime ) { if( counter < 20 ) { System.out.println("collect underflow FPS:" + counter); } //System.out.println("collect FPS:" + counter); counter = 0; nextCountTime = lastTime + 1000000000L; } // Don't sleep when we've processed in case we need // to process again immediately. continue; } // Wait just a little. This is an important enough thread // that we'll poll instead of smart-sleep. try { if( idleSleepTime > 0 ) { Thread.sleep(idleSleepTime); } } catch( InterruptedException e ) { throw new RuntimeException("Interrupted sleeping", e); } } terminate(); } } }
src/main/java/com/simsilica/ethereal/zone/StateCollector.java
/* * $Id$ * * Copyright (c) 2015, Simsilica, LLC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.simsilica.ethereal.zone; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.CopyOnWriteArraySet; import java.util.concurrent.atomic.AtomicBoolean; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Uses a background thread to periodically collect the accumulated * state for the zones and send the blocks of state to zone state * listeners. * * @author Paul Speed */ public class StateCollector { static Logger log = LoggerFactory.getLogger(StateCollector.class); private static final long NANOS_PER_SEC = 1000000000L; public static final long DEFAULT_PERIOD = NANOS_PER_SEC / 20; private ZoneManager zones; private long collectionPeriod; private long idleSleepTime = 1; // for our standard 20 FPS that's more than fine private final Runner runner = new Runner(); private final Set<StateListener> listeners = new CopyOnWriteArraySet<>(); private final ConcurrentLinkedQueue<StateListener> removed = new ConcurrentLinkedQueue<>(); /** * This is the actual zone interest management. It's only used by the * background thread which is why it is unsynchronized. All interactio * is done through the listeners set and removed queue. */ private final Map<ZoneKey,List<StateListener>> zoneListeners = new HashMap<>(); public StateCollector( ZoneManager zones ) { this(zones, DEFAULT_PERIOD); } public StateCollector( ZoneManager zones, long collectionPeriod ) { this.zones = zones; this.collectionPeriod = collectionPeriod == 0 ? DEFAULT_PERIOD : collectionPeriod; } public void start() { log.info("Starting state collector."); runner.start(); } public void shutdown() { log.info("Shuttong down state collector."); runner.close(); } /** * Adds a listener that self-indicates which specific zones * it is interested in from one frame to the next. This is necessary * so that it syncs with the background state collection in a way * that does not cause partial state, etc... it's also nicer to * to the background threads and synchronization if zone interest * is synched with updates. */ public void addListener( StateListener l ) { listeners.add(l); } public void removeListener( StateListener l ) { listeners.remove(l); removed.add(l); } /** * Sets the sleep() time for the state collector's idle periods. * This defaults to 1 which keeps the CPU happier while also providing * timely checks against the interval time. However, for higher rates of * state collection (lower collectionPeriods such as 16 ms or 60 FPS) on windows, * sleep(1) may take longer than 1/60th of a second or close enough to still * cause collection frame drops. In that case, it can be configured to 0 which * should provide timelier updates. * Set to -1 to avoid sleeping at all in which case the thread will consume 100% * of a single core in order to busy wait between collection intervals. */ public void setIdleSleepTime( long millis ) { this.idleSleepTime = millis; } public long getIdleSleepTime() { return idleSleepTime; } protected List<StateListener> getListeners( ZoneKey key, boolean create ) { List<StateListener> result = zoneListeners.get(key); if( result == null && create ) { result = new ArrayList<>(); zoneListeners.put(key, result); } return result; } protected void watch( ZoneKey key, StateListener l ) { if( log.isTraceEnabled() ) { log.trace("watch(" + key + ", " + l + ")"); } getListeners(key, true).add(l); } protected void unwatch( ZoneKey key, StateListener l ) { if( log.isTraceEnabled() ) { log.trace("unwatch(" + key + ", " + l + ")" ); } List<StateListener> list = getListeners(key, false); if( list == null ) { return; } list.remove(l); } protected void unwatchAll( StateListener l ) { if( log.isTraceEnabled() ) { log.trace("unwatchAll(" + l + ")" ); } for( List<StateListener> list : zoneListeners.values() ) { list.remove(l); } } /** * Called from the background thread when it first starts up. */ protected void initialize() { // Let the zone manager know that it can start collecting history zones.setCollectHistory(true); } protected void publish( StateBlock b ) { List<StateListener> list = getListeners(b.getZone(), false); if( list == null ) return; for( StateListener l : list ) l.stateChanged(b); } /** * Adjusts the per-listener zone interest based on latest * listener state, then publishes the state frame to all * interested listeners. */ protected void publishFrame( StateFrame frame ) { for( StateListener l : listeners ) { if( l.hasChangedZones() ) { List<ZoneKey> exited = l.getExitedZones(); for( ZoneKey k : exited ) { unwatch( k, l ); } List<ZoneKey> entered = l.getEnteredZones(); for( ZoneKey k : entered ) { watch( k, l ); } } l.beginFrame(frame.getTime()); } for( StateBlock b : frame ) { publish( b ); } for( StateListener l : listeners ) { l.endFrame(frame.getTime()); } } /** * Called by the background thread to collect all * of the accumulated state since the last collection and * distribute it to the state listeners. This is called * once per "collectionPeriod". */ protected void collect() { // Purge any pending removals StateListener remove; while( (remove = removed.poll()) != null ) { unwatchAll(remove); } // Collect all state since the last time we asked // long start = System.nanoTime(); StateFrame[] frames = zones.purgeState(); // long end = System.nanoTime(); // System.out.println( "State purged in:" + ((end - start)/1000000.0) + " ms" ); for( StateListener l : listeners ) { l.beginFrameBlock(); } // start = end; for( StateFrame f : frames ) { if( f == null ) { continue; } publishFrame(f); } for( StateListener l : listeners ) { l.endFrameBlock(); } // end = System.nanoTime(); // System.out.println( "State published in:" + ((end - start)/1000000.0) + " ms" ); } /** * Called by the background thread when it is shutting down. * Currently does nothing. */ protected void terminate() { // Let the zone manager know that it should stop collecting // history because we won't be purging it anymore. zones.setCollectHistory(false); } protected void collectionError( Exception e ) { log.error("Collection error", e); } private class Runner extends Thread { private final AtomicBoolean go = new AtomicBoolean(true); public Runner() { setName( "StateCollectionThread" ); //setPriority( Thread.MAX_PRIORITY ); } public void close() { go.set(false); try { join(); } catch( InterruptedException e ) { throw new RuntimeException( "Interrupted while waiting for physic thread to complete.", e ); } } @Override public void run() { initialize(); long lastTime = System.nanoTime(); long counter = 0; long nextCountTime = lastTime + 1000000000L; while( go.get() ) { long time = System.nanoTime(); long delta = time - lastTime; if( delta >= collectionPeriod ) { // Time to collect lastTime = time; try { collect(); counter++; //long end = System.nanoTime(); //delta = end - time; } catch( Exception e ) { collectionError(e); } if( lastTime > nextCountTime ) { if( counter < 20 ) { System.out.println("collect underflow FPS:" + counter); } //System.out.println("collect FPS:" + counter); counter = 0; nextCountTime = lastTime + 1000000000L; } // Don't sleep when we've processed in case we need // to process again immediately. continue; } // Wait just a little. This is an important enough thread // that we'll poll instead of smart-sleep. try { if( idleSleepTime > 0 ) { Thread.sleep(idleSleepTime); } } catch( InterruptedException e ) { throw new RuntimeException("Interrupted sleeping", e); } } terminate(); } } }
Minor formatting changes. Added a couple more trace logs.
src/main/java/com/simsilica/ethereal/zone/StateCollector.java
Minor formatting changes. Added a couple more trace logs.
Java
bsd-3-clause
61808a7e6e20f99e26b33ae637d106e645633dcf
0
giorgos1987/jsonld-java,giorgos1987/jsonld-java,westei/jsonld-java,westei/jsonld-java,dyanarose/jsonld-java,jsonld-java/jsonld-java,dyanarose/jsonld-java
package com.github.jsonldjava.core; import static com.github.jsonldjava.core.JsonLdConsts.RDF_FIRST; import static com.github.jsonldjava.core.JsonLdConsts.RDF_LANGSTRING; import static com.github.jsonldjava.core.JsonLdConsts.RDF_NIL; import static com.github.jsonldjava.core.JsonLdConsts.RDF_REST; import static com.github.jsonldjava.core.JsonLdConsts.RDF_TYPE; import static com.github.jsonldjava.core.JsonLdConsts.XSD_BOOLEAN; import static com.github.jsonldjava.core.JsonLdConsts.XSD_DOUBLE; import static com.github.jsonldjava.core.JsonLdConsts.XSD_INTEGER; import static com.github.jsonldjava.core.JsonLdConsts.XSD_STRING; import static com.github.jsonldjava.core.JsonLdUtils.isKeyword; import static com.github.jsonldjava.core.JsonLdUtils.isList; import static com.github.jsonldjava.core.JsonLdUtils.isObject; import static com.github.jsonldjava.core.JsonLdUtils.isString; import static com.github.jsonldjava.core.JsonLdUtils.isValue; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Pattern; /** * Starting to migrate away from using plain java Maps as the internal RDF * dataset store. Currently each item just wraps a Map based on the old format * so everything doesn't break. Will phase this out once everything is using the * new format. * * @author Tristan * */ public class RDFDataset extends LinkedHashMap<String, Object> { public static class Quad extends LinkedHashMap<String, Object> implements Comparable<Quad> { public Quad(final String subject, final String predicate, final String object, final String graph) { this(subject, predicate, object.startsWith("_:") ? new BlankNode(object) : new IRI( object), graph); }; public Quad(final String subject, final String predicate, final String value, final String datatype, final String language, final String graph) { this(subject, predicate, new Literal(value, datatype, language), graph); }; private Quad(final String subject, final String predicate, final Node object, final String graph) { this(subject.startsWith("_:") ? new BlankNode(subject) : new IRI(subject), new IRI( predicate), object, graph); }; public Quad(final Node subject, final Node predicate, final Node object, final String graph) { super(); put("subject", subject); put("predicate", predicate); put("object", object); if (graph != null && !"@default".equals(graph)) { // TODO: i'm not yet sure if this should be added or if the // graph should only be represented by the keys in the dataset put("name", graph.startsWith("_:") ? new BlankNode(graph) : new IRI(graph)); } } public Node getSubject() { return (Node) get("subject"); } public Node getPredicate() { return (Node) get("predicate"); } public Node getObject() { return (Node) get("object"); } public Node getGraph() { return (Node) get("name"); } @Override public int compareTo(Quad o) { if (o == null) { return 1; } int rval = getGraph().compareTo(o.getGraph()); if (rval != 0) { return rval; } rval = getSubject().compareTo(o.getSubject()); if (rval != 0) { return rval; } rval = getPredicate().compareTo(o.getPredicate()); if (rval != 0) { return rval; } return getObject().compareTo(o.getObject()); } } public static abstract class Node extends LinkedHashMap<String, Object> implements Comparable<Node> { public abstract boolean isLiteral(); public abstract boolean isIRI(); public abstract boolean isBlankNode(); public String getValue() { return (String) get("value"); } public String getDatatype() { return (String) get("datatype"); } public String getLanguage() { return (String) get("language"); } @Override public int compareTo(Node o) { if (this.isIRI()) { if (!o.isIRI()) { // IRIs > everything return 1; } } else if (this.isBlankNode()) { if (o.isIRI()) { // IRI > blank node return -1; } else if (o.isLiteral()) { // blank node > literal return 1; } } return this.getValue().compareTo(o.getValue()); } /** * Converts an RDF triple object to a JSON-LD object. * * @param o * the RDF triple object to convert. * @param useNativeTypes * true to output native types, false not to. * * @return the JSON-LD object. * @throws JsonLdError */ Map<String, Object> toObject(Boolean useNativeTypes) throws JsonLdError { // If value is an an IRI or a blank node identifier, return a new // JSON object consisting // of a single member @id whose value is set to value. if (isIRI() || isBlankNode()) { return new LinkedHashMap<String, Object>() { { put("@id", getValue()); } }; } ; // convert literal object to JSON-LD final Map<String, Object> rval = new LinkedHashMap<String, Object>() { { put("@value", getValue()); } }; // add language if (getLanguage() != null) { rval.put("@language", getLanguage()); } // add datatype else { final String type = getDatatype(); final String value = getValue(); if (useNativeTypes) { // use native datatypes for certain xsd types if (XSD_STRING.equals(type)) { // don't add xsd:string } else if (XSD_BOOLEAN.equals(type)) { if ("true".equals(value)) { rval.put("@value", Boolean.TRUE); } else if ("false".equals(value)) { rval.put("@value", Boolean.FALSE); } } else if ((XSD_INTEGER.equals(type) || XSD_DOUBLE.equals(type)) && Pattern.matches( "^[+-]?[0-9]+((?:\\.?[0-9]+((?:E?[+-]?[0-9]+)|)|))$", value)) { try { final Double d = Double.parseDouble(value); if (!Double.isNaN(d) && !Double.isInfinite(d)) { if (XSD_INTEGER.equals(type)) { final Integer i = d.intValue(); if (i.toString().equals(value)) { rval.put("@value", i); } } else if (XSD_DOUBLE.equals(type)) { rval.put("@value", d); } else { throw new RuntimeException( "This should never happen as we checked the type was either integer or double"); } } } catch (final NumberFormatException e) { // TODO: This should never happen since we match the // value with regex! throw new RuntimeException(e); } } // do not add xsd:string type else { rval.put("@type", type); } } else if (!XSD_STRING.equals(type)) { rval.put("@type", type); } } return rval; } } public static class Literal extends Node { public Literal(String value, String datatype, String language) { super(); put("type", "literal"); put("value", value); put("datatype", datatype != null ? datatype : XSD_STRING); if (language != null) { put("language", language); } } @Override public boolean isLiteral() { return true; } @Override public boolean isIRI() { return false; } @Override public boolean isBlankNode() { return false; } @Override public int compareTo(Node o) { if (o == null) { // valid nodes are > null nodes return 1; } if (o.isIRI()) { // literals < iri return -1; } if (o.isBlankNode()) { // blank node < iri return -1; } if (this.getLanguage() == null && ((Literal) o).getLanguage() != null) { return -1; } else if (this.getLanguage() != null && ((Literal) o).getLanguage() == null) { return 1; } if (this.getDatatype() != null) { return this.getDatatype().compareTo(((Literal) o).getDatatype()); } else if (((Literal) o).getDatatype() != null) { return -1; } return 0; } } public static class IRI extends Node { public IRI(String iri) { super(); put("type", "IRI"); put("value", iri); } @Override public boolean isLiteral() { return false; } @Override public boolean isIRI() { return true; } @Override public boolean isBlankNode() { return false; } } public static class BlankNode extends Node { public BlankNode(String attribute) { super(); put("type", "blank node"); put("value", attribute); } @Override public boolean isLiteral() { return false; } @Override public boolean isIRI() { return false; } @Override public boolean isBlankNode() { return true; } } private static final Node first = new IRI(RDF_FIRST); private static final Node rest = new IRI(RDF_REST); private static final Node nil = new IRI(RDF_NIL); private final Map<String, String> context; // private UniqueNamer namer; private JsonLdApi api; public RDFDataset() { super(); put("@default", new ArrayList<Quad>()); context = new LinkedHashMap<String, String>(); // put("@context", context); } /* * public RDFDataset(String blankNodePrefix) { this(new * UniqueNamer(blankNodePrefix)); } * * public RDFDataset(UniqueNamer namer) { this(); this.namer = namer; } */ public RDFDataset(JsonLdApi jsonLdApi) { this(); this.api = jsonLdApi; } public void setNamespace(String ns, String prefix) { context.put(ns, prefix); } public String getNamespace(String ns) { return context.get(ns); } /** * clears all the namespaces in this dataset */ public void clearNamespaces() { context.clear(); } public Map<String, String> getNamespaces() { return context; } /** * Returns a valid context containing any namespaces set * * @return The context map */ public Map<String, Object> getContext() { final Map<String, Object> rval = new LinkedHashMap<String, Object>(); rval.putAll(context); // replace "" with "@vocab" if (rval.containsKey("")) { rval.put("@vocab", rval.remove("")); } return rval; } /** * parses a context object and sets any namespaces found within it * * @param contextLike * The context to parse * @throws JsonLdError * If the context can't be parsed */ public void parseContext(Object contextLike) throws JsonLdError { Context context; if (api != null) { context = new Context(api.opts); } else { context = new Context(); } // Context will do our recursive parsing and initial IRI resolution context = context.parse(contextLike); // And then leak to us the potential 'prefixes' final Map<String, String> prefixes = context.getPrefixes(true); for (final String key : prefixes.keySet()) { final String val = prefixes.get(key); if ("@vocab".equals(key)) { if (val == null || isString(val)) { setNamespace("", val); } else { } } else if (!isKeyword(key)) { setNamespace(key, val); // TODO: should we make sure val is a valid URI prefix (i.e. it // ends with /# or ?) // or is it ok that full URIs for terms are used? } } } /** * Adds a triple to the @default graph of this dataset * * @param subject * the subject for the triple * @param predicate * the predicate for the triple * @param value * the value of the literal object for the triple * @param datatype * the datatype of the literal object for the triple (null values * will default to xsd:string) * @param language * the language of the literal object for the triple (or null) */ public void addTriple(final String subject, final String predicate, final String value, final String datatype, final String language) { addQuad(subject, predicate, value, datatype, language, "@default"); } /** * Adds a triple to the specified graph of this dataset * * @param s * the subject for the triple * @param p * the predicate for the triple * @param value * the value of the literal object for the triple * @param datatype * the datatype of the literal object for the triple (null values * will default to xsd:string) * @param graph * the graph to add this triple to * @param language * the language of the literal object for the triple (or null) */ public void addQuad(final String s, final String p, final String value, final String datatype, final String language, String graph) { if (graph == null) { graph = "@default"; } if (!containsKey(graph)) { put(graph, new ArrayList<Quad>()); } ((ArrayList<Quad>) get(graph)).add(new Quad(s, p, value, datatype, language, graph)); } /** * Adds a triple to the default graph of this dataset * * @param subject * the subject for the triple * @param predicate * the predicate for the triple * @param object * the object for the triple */ public void addTriple(final String subject, final String predicate, final String object) { addQuad(subject, predicate, object, "@default"); } /** * Adds a triple to the specified graph of this dataset * * @param subject * the subject for the triple * @param predicate * the predicate for the triple * @param object * the object for the triple * @param graph * the graph to add this triple to */ public void addQuad(final String subject, final String predicate, final String object, String graph) { if (graph == null) { graph = "@default"; } if (!containsKey(graph)) { put(graph, new ArrayList<Quad>()); } ((ArrayList<Quad>) get(graph)).add(new Quad(subject, predicate, object, graph)); } /** * Creates an array of RDF triples for the given graph. * * @param graphName * The graph URI * @param graph * the graph to create RDF triples for. */ void graphToRDF(String graphName, Map<String, Object> graph) { // 4.2) final List<Quad> triples = new ArrayList<Quad>(); // 4.3) final List<String> subjects = new ArrayList<String>(graph.keySet()); // Collections.sort(subjects); for (final String id : subjects) { if (JsonLdUtils.isRelativeIri(id)) { continue; } final Map<String, Object> node = (Map<String, Object>) graph.get(id); final List<String> properties = new ArrayList<String>(node.keySet()); Collections.sort(properties); for (String property : properties) { final List<Object> values; // 4.3.2.1) if ("@type".equals(property)) { values = (List<Object>) node.get("@type"); property = RDF_TYPE; } // 4.3.2.2) else if (isKeyword(property)) { continue; } // 4.3.2.3) else if (property.startsWith("_:") && !api.opts.getProduceGeneralizedRdf()) { continue; } // 4.3.2.4) else if (JsonLdUtils.isRelativeIri(property)) { continue; } else { values = (List<Object>) node.get(property); } Node subject; if (id.indexOf("_:") == 0) { // NOTE: don't rename, just set it as a blank node subject = new BlankNode(id); } else { subject = new IRI(id); } // RDF predicates Node predicate; if (property.startsWith("_:")) { predicate = new BlankNode(property); } else { predicate = new IRI(property); } for (final Object item : values) { // convert @list to triples if (isList(item)) { final List<Object> list = (List<Object>) ((Map<String, Object>) item) .get("@list"); Node last = null; Node firstBNode = nil; if (!list.isEmpty()) { last = objectToRDF(list.get(list.size() - 1)); firstBNode = new BlankNode(api.generateBlankNodeIdentifier()); } triples.add(new Quad(subject, predicate, firstBNode, graphName)); for (int i = 0; i < list.size() - 1; i++) { final Node object = objectToRDF(list.get(i)); triples.add(new Quad(firstBNode, first, object, graphName)); final Node restBNode = new BlankNode(api.generateBlankNodeIdentifier()); triples.add(new Quad(firstBNode, rest, restBNode, graphName)); firstBNode = restBNode; } if (last != null) { triples.add(new Quad(firstBNode, first, last, graphName)); triples.add(new Quad(firstBNode, rest, nil, graphName)); } } // convert value or node object to triple else { final Node object = objectToRDF(item); if (object != null) { triples.add(new Quad(subject, predicate, object, graphName)); } } } } } put(graphName, triples); } /** * Converts a JSON-LD value object to an RDF literal or a JSON-LD string or * node object to an RDF resource. * * @param item * the JSON-LD value or node object. * @return the RDF literal or RDF resource. */ private Node objectToRDF(Object item) { // convert value object to RDF if (isValue(item)) { final Object value = ((Map<String, Object>) item).get("@value"); final Object datatype = ((Map<String, Object>) item).get("@type"); // convert to XSD datatypes as appropriate if (value instanceof Boolean || value instanceof Number) { // convert to XSD datatype if (value instanceof Boolean) { return new Literal(value.toString(), datatype == null ? XSD_BOOLEAN : (String) datatype, null); } else if (value instanceof Double || value instanceof Float || XSD_DOUBLE.equals(datatype)) { // canonical double representation final DecimalFormat df = new DecimalFormat("0.0###############E0"); return new Literal(df.format(value), datatype == null ? XSD_DOUBLE : (String) datatype, null); } else { final DecimalFormat df = new DecimalFormat("0"); return new Literal(df.format(value), datatype == null ? XSD_INTEGER : (String) datatype, null); } } else if (((Map<String, Object>) item).containsKey("@language")) { return new Literal((String) value, datatype == null ? RDF_LANGSTRING : (String) datatype, (String) ((Map<String, Object>) item).get("@language")); } else { return new Literal((String) value, datatype == null ? XSD_STRING : (String) datatype, null); } } // convert string/node object to RDF else { final String id; if (isObject(item)) { id = (String) ((Map<String, Object>) item).get("@id"); if (JsonLdUtils.isRelativeIri(id)) { return null; } } else { id = (String) item; } if (id.indexOf("_:") == 0) { // NOTE: once again no need to rename existing blank nodes return new BlankNode(id); } else { return new IRI(id); } } } public Set<String> graphNames() { // TODO Auto-generated method stub return keySet(); } public List<Quad> getQuads(String graphName) { return (List<Quad>) get(graphName); } }
core/src/main/java/com/github/jsonldjava/core/RDFDataset.java
package com.github.jsonldjava.core; import static com.github.jsonldjava.core.JsonLdConsts.RDF_FIRST; import static com.github.jsonldjava.core.JsonLdConsts.RDF_LANGSTRING; import static com.github.jsonldjava.core.JsonLdConsts.RDF_NIL; import static com.github.jsonldjava.core.JsonLdConsts.RDF_REST; import static com.github.jsonldjava.core.JsonLdConsts.RDF_TYPE; import static com.github.jsonldjava.core.JsonLdConsts.XSD_BOOLEAN; import static com.github.jsonldjava.core.JsonLdConsts.XSD_DOUBLE; import static com.github.jsonldjava.core.JsonLdConsts.XSD_INTEGER; import static com.github.jsonldjava.core.JsonLdConsts.XSD_STRING; import static com.github.jsonldjava.core.JsonLdUtils.isKeyword; import static com.github.jsonldjava.core.JsonLdUtils.isList; import static com.github.jsonldjava.core.JsonLdUtils.isObject; import static com.github.jsonldjava.core.JsonLdUtils.isString; import static com.github.jsonldjava.core.JsonLdUtils.isValue; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Pattern; /** * Starting to migrate away from using plain java Maps as the internal RDF * dataset store. Currently each item just wraps a Map based on the old format * so everything doesn't break. Will phase this out once everything is using the * new format. * * @author Tristan * */ public class RDFDataset extends LinkedHashMap<String, Object> { public static class Quad extends LinkedHashMap<String, Object> implements Comparable<Quad> { public Quad(final String subject, final String predicate, final String object, final String graph) { this(subject, predicate, object.startsWith("_:") ? new BlankNode(object) : new IRI( object), graph); }; public Quad(final String subject, final String predicate, final String value, final String datatype, final String language, final String graph) { this(subject, predicate, new Literal(value, datatype, language), graph); }; private Quad(final String subject, final String predicate, final Node object, final String graph) { this(subject.startsWith("_:") ? new BlankNode(subject) : new IRI(subject), new IRI( predicate), object, graph); }; public Quad(final Node subject, final Node predicate, final Node object, final String graph) { super(); put("subject", subject); put("predicate", predicate); put("object", object); if (graph != null && !"@default".equals(graph)) { // TODO: i'm not yet sure if this should be added or if the // graph should only be represented by the keys in the dataset put("name", graph.startsWith("_:") ? new BlankNode(graph) : new IRI(graph)); } } public Node getSubject() { return (Node) get("subject"); } public Node getPredicate() { return (Node) get("predicate"); } public Node getObject() { return (Node) get("object"); } public Node getGraph() { return (Node) get("name"); } @Override public int compareTo(Quad o) { if (o == null) { return 1; } int rval = getGraph().compareTo(o.getGraph()); if (rval != 0) { return rval; } rval = getSubject().compareTo(o.getSubject()); if (rval != 0) { return rval; } rval = getPredicate().compareTo(o.getPredicate()); if (rval != 0) { return rval; } return getObject().compareTo(o.getObject()); } } public static abstract class Node extends LinkedHashMap<String, Object> implements Comparable<Node> { public abstract boolean isLiteral(); public abstract boolean isIRI(); public abstract boolean isBlankNode(); public String getValue() { return (String) get("value"); } public String getDatatype() { return (String) get("datatype"); } public String getLanguage() { return (String) get("language"); } @Override public int compareTo(Node o) { if (this.isIRI()) { if (!o.isIRI()) { // IRIs > everything return 1; } } else if (this.isBlankNode()) { if (o.isIRI()) { // IRI > blank node return -1; } else if (o.isLiteral()) { // blank node > literal return 1; } } return this.getValue().compareTo(o.getValue()); } /** * Converts an RDF triple object to a JSON-LD object. * * @param o * the RDF triple object to convert. * @param useNativeTypes * true to output native types, false not to. * * @return the JSON-LD object. * @throws JsonLdError */ Map<String, Object> toObject(Boolean useNativeTypes) throws JsonLdError { // If value is an an IRI or a blank node identifier, return a new // JSON object consisting // of a single member @id whose value is set to value. if (isIRI() || isBlankNode()) { return new LinkedHashMap<String, Object>() { { put("@id", getValue()); } }; } ; // convert literal object to JSON-LD final Map<String, Object> rval = new LinkedHashMap<String, Object>() { { put("@value", getValue()); } }; // add language if (getLanguage() != null) { rval.put("@language", getLanguage()); } // add datatype else { final String type = getDatatype(); final String value = getValue(); if (useNativeTypes) { // use native datatypes for certain xsd types if (XSD_STRING.equals(type)) { // don't add xsd:string } else if (XSD_BOOLEAN.equals(type)) { if ("true".equals(value)) { rval.put("@value", Boolean.TRUE); } else if ("false".equals(value)) { rval.put("@value", Boolean.FALSE); } } else if (Pattern.matches( "^[+-]?[0-9]+((?:\\.?[0-9]+((?:E?[+-]?[0-9]+)|)|))$", value)) { try { final Double d = Double.parseDouble(value); if (!Double.isNaN(d) && !Double.isInfinite(d)) { if (XSD_INTEGER.equals(type)) { final Integer i = d.intValue(); if (i.toString().equals(value)) { rval.put("@value", i); } } else if (XSD_DOUBLE.equals(type)) { rval.put("@value", d); } else { // we don't know the type, so we should add // it to the JSON-LD rval.put("@type", type); } } } catch (final NumberFormatException e) { // TODO: This should never happen since we match the // value with regex! throw new RuntimeException(e); } } // do not add xsd:string type else { rval.put("@type", type); } } else if (!XSD_STRING.equals(type)) { rval.put("@type", type); } } return rval; } } public static class Literal extends Node { public Literal(String value, String datatype, String language) { super(); put("type", "literal"); put("value", value); put("datatype", datatype != null ? datatype : XSD_STRING); if (language != null) { put("language", language); } } @Override public boolean isLiteral() { return true; } @Override public boolean isIRI() { return false; } @Override public boolean isBlankNode() { return false; } @Override public int compareTo(Node o) { if (o == null) { // valid nodes are > null nodes return 1; } if (o.isIRI()) { // literals < iri return -1; } if (o.isBlankNode()) { // blank node < iri return -1; } if (this.getLanguage() == null && ((Literal) o).getLanguage() != null) { return -1; } else if (this.getLanguage() != null && ((Literal) o).getLanguage() == null) { return 1; } if (this.getDatatype() != null) { return this.getDatatype().compareTo(((Literal) o).getDatatype()); } else if (((Literal) o).getDatatype() != null) { return -1; } return 0; } } public static class IRI extends Node { public IRI(String iri) { super(); put("type", "IRI"); put("value", iri); } @Override public boolean isLiteral() { return false; } @Override public boolean isIRI() { return true; } @Override public boolean isBlankNode() { return false; } } public static class BlankNode extends Node { public BlankNode(String attribute) { super(); put("type", "blank node"); put("value", attribute); } @Override public boolean isLiteral() { return false; } @Override public boolean isIRI() { return false; } @Override public boolean isBlankNode() { return true; } } private static final Node first = new IRI(RDF_FIRST); private static final Node rest = new IRI(RDF_REST); private static final Node nil = new IRI(RDF_NIL); private final Map<String, String> context; // private UniqueNamer namer; private JsonLdApi api; public RDFDataset() { super(); put("@default", new ArrayList<Quad>()); context = new LinkedHashMap<String, String>(); // put("@context", context); } /* * public RDFDataset(String blankNodePrefix) { this(new * UniqueNamer(blankNodePrefix)); } * * public RDFDataset(UniqueNamer namer) { this(); this.namer = namer; } */ public RDFDataset(JsonLdApi jsonLdApi) { this(); this.api = jsonLdApi; } public void setNamespace(String ns, String prefix) { context.put(ns, prefix); } public String getNamespace(String ns) { return context.get(ns); } /** * clears all the namespaces in this dataset */ public void clearNamespaces() { context.clear(); } public Map<String, String> getNamespaces() { return context; } /** * Returns a valid context containing any namespaces set * * @return The context map */ public Map<String, Object> getContext() { final Map<String, Object> rval = new LinkedHashMap<String, Object>(); rval.putAll(context); // replace "" with "@vocab" if (rval.containsKey("")) { rval.put("@vocab", rval.remove("")); } return rval; } /** * parses a context object and sets any namespaces found within it * * @param contextLike * The context to parse * @throws JsonLdError * If the context can't be parsed */ public void parseContext(Object contextLike) throws JsonLdError { Context context; if (api != null) { context = new Context(api.opts); } else { context = new Context(); } // Context will do our recursive parsing and initial IRI resolution context = context.parse(contextLike); // And then leak to us the potential 'prefixes' final Map<String, String> prefixes = context.getPrefixes(true); for (final String key : prefixes.keySet()) { final String val = prefixes.get(key); if ("@vocab".equals(key)) { if (val == null || isString(val)) { setNamespace("", val); } else { } } else if (!isKeyword(key)) { setNamespace(key, val); // TODO: should we make sure val is a valid URI prefix (i.e. it // ends with /# or ?) // or is it ok that full URIs for terms are used? } } } /** * Adds a triple to the @default graph of this dataset * * @param subject * the subject for the triple * @param predicate * the predicate for the triple * @param value * the value of the literal object for the triple * @param datatype * the datatype of the literal object for the triple (null values * will default to xsd:string) * @param language * the language of the literal object for the triple (or null) */ public void addTriple(final String subject, final String predicate, final String value, final String datatype, final String language) { addQuad(subject, predicate, value, datatype, language, "@default"); } /** * Adds a triple to the specified graph of this dataset * * @param s * the subject for the triple * @param p * the predicate for the triple * @param value * the value of the literal object for the triple * @param datatype * the datatype of the literal object for the triple (null values * will default to xsd:string) * @param graph * the graph to add this triple to * @param language * the language of the literal object for the triple (or null) */ public void addQuad(final String s, final String p, final String value, final String datatype, final String language, String graph) { if (graph == null) { graph = "@default"; } if (!containsKey(graph)) { put(graph, new ArrayList<Quad>()); } ((ArrayList<Quad>) get(graph)).add(new Quad(s, p, value, datatype, language, graph)); } /** * Adds a triple to the default graph of this dataset * * @param subject * the subject for the triple * @param predicate * the predicate for the triple * @param object * the object for the triple */ public void addTriple(final String subject, final String predicate, final String object) { addQuad(subject, predicate, object, "@default"); } /** * Adds a triple to the specified graph of this dataset * * @param subject * the subject for the triple * @param predicate * the predicate for the triple * @param object * the object for the triple * @param graph * the graph to add this triple to */ public void addQuad(final String subject, final String predicate, final String object, String graph) { if (graph == null) { graph = "@default"; } if (!containsKey(graph)) { put(graph, new ArrayList<Quad>()); } ((ArrayList<Quad>) get(graph)).add(new Quad(subject, predicate, object, graph)); } /** * Creates an array of RDF triples for the given graph. * * @param graphName * The graph URI * @param graph * the graph to create RDF triples for. */ void graphToRDF(String graphName, Map<String, Object> graph) { // 4.2) final List<Quad> triples = new ArrayList<Quad>(); // 4.3) final List<String> subjects = new ArrayList<String>(graph.keySet()); // Collections.sort(subjects); for (final String id : subjects) { if (JsonLdUtils.isRelativeIri(id)) { continue; } final Map<String, Object> node = (Map<String, Object>) graph.get(id); final List<String> properties = new ArrayList<String>(node.keySet()); Collections.sort(properties); for (String property : properties) { final List<Object> values; // 4.3.2.1) if ("@type".equals(property)) { values = (List<Object>) node.get("@type"); property = RDF_TYPE; } // 4.3.2.2) else if (isKeyword(property)) { continue; } // 4.3.2.3) else if (property.startsWith("_:") && !api.opts.getProduceGeneralizedRdf()) { continue; } // 4.3.2.4) else if (JsonLdUtils.isRelativeIri(property)) { continue; } else { values = (List<Object>) node.get(property); } Node subject; if (id.indexOf("_:") == 0) { // NOTE: don't rename, just set it as a blank node subject = new BlankNode(id); } else { subject = new IRI(id); } // RDF predicates Node predicate; if (property.startsWith("_:")) { predicate = new BlankNode(property); } else { predicate = new IRI(property); } for (final Object item : values) { // convert @list to triples if (isList(item)) { final List<Object> list = (List<Object>) ((Map<String, Object>) item) .get("@list"); Node last = null; Node firstBNode = nil; if (!list.isEmpty()) { last = objectToRDF(list.get(list.size() - 1)); firstBNode = new BlankNode(api.generateBlankNodeIdentifier()); } triples.add(new Quad(subject, predicate, firstBNode, graphName)); for (int i = 0; i < list.size() - 1; i++) { final Node object = objectToRDF(list.get(i)); triples.add(new Quad(firstBNode, first, object, graphName)); final Node restBNode = new BlankNode(api.generateBlankNodeIdentifier()); triples.add(new Quad(firstBNode, rest, restBNode, graphName)); firstBNode = restBNode; } if (last != null) { triples.add(new Quad(firstBNode, first, last, graphName)); triples.add(new Quad(firstBNode, rest, nil, graphName)); } } // convert value or node object to triple else { final Node object = objectToRDF(item); if (object != null) { triples.add(new Quad(subject, predicate, object, graphName)); } } } } } put(graphName, triples); } /** * Converts a JSON-LD value object to an RDF literal or a JSON-LD string or * node object to an RDF resource. * * @param item * the JSON-LD value or node object. * @return the RDF literal or RDF resource. */ private Node objectToRDF(Object item) { // convert value object to RDF if (isValue(item)) { final Object value = ((Map<String, Object>) item).get("@value"); final Object datatype = ((Map<String, Object>) item).get("@type"); // convert to XSD datatypes as appropriate if (value instanceof Boolean || value instanceof Number) { // convert to XSD datatype if (value instanceof Boolean) { return new Literal(value.toString(), datatype == null ? XSD_BOOLEAN : (String) datatype, null); } else if (value instanceof Double || value instanceof Float || XSD_DOUBLE.equals(datatype)) { // canonical double representation final DecimalFormat df = new DecimalFormat("0.0###############E0"); return new Literal(df.format(value), datatype == null ? XSD_DOUBLE : (String) datatype, null); } else { final DecimalFormat df = new DecimalFormat("0"); return new Literal(df.format(value), datatype == null ? XSD_INTEGER : (String) datatype, null); } } else if (((Map<String, Object>) item).containsKey("@language")) { return new Literal((String) value, datatype == null ? RDF_LANGSTRING : (String) datatype, (String) ((Map<String, Object>) item).get("@language")); } else { return new Literal((String) value, datatype == null ? XSD_STRING : (String) datatype, null); } } // convert string/node object to RDF else { final String id; if (isObject(item)) { id = (String) ((Map<String, Object>) item).get("@id"); if (JsonLdUtils.isRelativeIri(id)) { return null; } } else { id = (String) item; } if (id.indexOf("_:") == 0) { // NOTE: once again no need to rename existing blank nodes return new BlankNode(id); } else { return new IRI(id); } } } public Set<String> graphNames() { // TODO Auto-generated method stub return keySet(); } public List<Quad> getQuads(String graphName) { return (List<Quad>) get(graphName); } }
Sanity check only use native type for integer/double and regex
core/src/main/java/com/github/jsonldjava/core/RDFDataset.java
Sanity check only use native type for integer/double and regex
Java
bsd-3-clause
694cafb4ad1d959c192a4b47e413ff830a5fed8a
0
Masterdocs/masterdoc-maven-plugin,Masterdocs/masterdoc-maven-plugin,Masterdocs/masterdoc-maven-plugin
package fr.masterdocs.plugin; import com.github.jknack.handlebars.*; import com.github.jknack.handlebars.io.FileTemplateLoader; import com.google.common.base.Function; import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.Ordering; import com.googlecode.gentyref.GenericTypeReflector; import fr.masterdocs.pojo.*; import fr.masterdocs.pojo.Enumeration; import org.apache.http.client.utils.URIBuilder; import org.apache.maven.artifact.Artifact; import org.apache.maven.project.MavenProject; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jettison.json.JSONArray; import org.codehaus.jettison.json.JSONException; import org.codehaus.jettison.json.JSONObject; import org.codehaus.plexus.logging.console.ConsoleLogger; import org.reflections.Reflections; import javax.ws.rs.*; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlTransient; import java.beans.IntrospectionException; import java.io.*; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; import java.net.URLClassLoader; import java.text.SimpleDateFormat; import java.util.*; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import static com.google.common.base.Defaults.defaultValue; import static java.io.File.separator; import static java.text.MessageFormat.format; import static org.springframework.util.StringUtils.capitalize; public class MasterDocGenerator { // ---------------------------------------------------------------------- // Constants // ---------------------------------------------------------------------- public static final String CLASS = "class "; public static final SimpleDateFormat SDF = new SimpleDateFormat("dd-MM-yyyy HH:mm:sss"); public static final String MASTERDOC_JSON_FILENAME = "masterdocs.json"; public static final String PATH_PARAM = "PathParam"; public static final String QUERY_PARAM = "QueryParam"; public static final String JAVA_UTIL_HASH_MAP = "java.util.HashMap"; public static final String GET = "GET"; public static final String POST = "POST"; public static final String PUT = "PUT"; public static final String DELETE = "DELETE"; public static final String OPTIONS = "OPTIONS"; public static final String NULL = "null"; public static final String VOID = "void"; public static final String IS_PREFIX = "is"; public static final String GET_PREFIX = "get"; public static final String INTERFACE = "interface"; public static final String T = "T"; public static final String JAVA_LANG_OBJECT = "java.lang.Object"; public static final String JAVA = "java"; public static final String BYTE = "B"; public static final String ARRAY = "[]"; public static final String DOT = "."; public static final String COMMA = ","; public static final String MASTERDOCS_DIR = "masterdocs"; private static final String JAVA_UTIL_LIST = "java.util.List"; private static final String JAVA_UTIL_SET = "java.util.Set"; public Integer MAX_DEPTH = 1; // ---------------------------------------------------------------------- // Variables // ---------------------------------------------------------------------- /** * Logger for maven plugin. */ private ConsoleLogger consoleLogger = new ConsoleLogger(); /** * Resources found by MasterDoc. */ private List<Resource> resources; /** * Entities found by MasterDoc. */ private List<AbstractEntity> entities; /** * Metadata found by MasterDoc. */ private MasterDocMetadata metadata; /** * Final MasterDoc. */ private Set<String> entityList; private MavenProject project; private ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader(); private ClassLoader newClassLoader; private String pathToGenerateFile; private HashSet<String> newEntities; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- public MasterDocGenerator() { } public MasterDocGenerator(MavenProject project, String pathToGenerateFile, String[] packageDocumentationResources, boolean generateHTMLSite, Integer maxDepth) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException { long start = System.currentTimeMillis(); consoleLogger.info("MasterDocGenerator started"); resources = new ArrayList<Resource>(); entities = new ArrayList<AbstractEntity>(); entityList = new HashSet<String>(); this.project = project; this.pathToGenerateFile = pathToGenerateFile; if (null != maxDepth) { this.MAX_DEPTH = maxDepth; } // //////////////////// generateProjectClassLoader(project); // //////////////////// for (String packageDocumentationResource : packageDocumentationResources) { consoleLogger.info(format("Generate REST documentation on package {0} ...", packageDocumentationResource)); startGeneration(new String[] { packageDocumentationResource }); } // generateDocumentationFile(generateHTMLSite); // // restore original classloader Thread.currentThread().setContextClassLoader(originalClassLoader); consoleLogger.info(format("Generation ended in {0} ms", (System.currentTimeMillis() - start))); } private static void copy(InputStream in, OutputStream out) throws IOException { byte[] buffer = new byte[1024]; while (true) { int readCount = in.read(buffer); if (readCount < 0) { break; } out.write(buffer, 0, readCount); } } private static void copy(File file, OutputStream out) throws IOException { InputStream in = new FileInputStream(file); try { copy(in, out); } finally { in.close(); } } private static void copy(InputStream in, File file) throws IOException { OutputStream out = new FileOutputStream(file); try { copy(in, out); } finally { out.close(); } } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public void startGeneration(String[] args) { String packageDocumentationResource = args[0]; if (null != packageDocumentationResource && packageDocumentationResource.length() > 0) { try { getMetadata(); getDocResource(packageDocumentationResource); getEntities(entityList); consoleLogger.info(format("Entities : {0}", entityList.size())); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (IntrospectionException e) { e.printStackTrace(); } } else { consoleLogger.error("packageDocumentationResources not defined in plugin configuration"); } } // ---------------------------------------------------------------------- // Private methods // ---------------------------------------------------------------------- private void getEntities(Set list) throws ClassNotFoundException, IntrospectionException { newEntities = new HashSet<String>(); for (Iterator<Serializable> iterator = list.iterator(); iterator .hasNext();) { Serializable entity = iterator.next(); final Class<?> entityClass; String entityToString = entity.toString(); try { if (entityToString.startsWith(JAVA_UTIL_LIST)) { entityToString = entityToString.substring(JAVA_UTIL_LIST.length() + 1, entityToString.length() - 1); } entityClass = Class.forName(entityToString, true, newClassLoader); } catch (Exception e) { consoleLogger.debug(format("{0} is not forNamable", entityToString)); continue; } Entity newEntity = new Entity(); if (!entityToString.startsWith(JAVA)) { newEntity.setName(entityToString.replaceAll("\\$", ".")); if (entityClass.isEnum()) { extractEnumFields(entity); } else { newEntity.setFields(extractFields(entityClass)); final Class<?> superclass = entityClass.getSuperclass(); if (!JAVA_LANG_OBJECT.equals(superclass.getName())) { newEntity.setSuperClass(superclass.getName()); if (!entityList.contains(superclass.getName()) && !newEntities.contains(superclass.getName())) { newEntities.add(superclass.getName()); } } if (newEntity.getFields().isEmpty()) { newEntity.setFields(null); } entities.add(newEntity); } } } if (newEntities.size() > 0) { entityList.addAll(newEntities); getEntities((Set) newEntities.clone()); } } private String extractName(String fqn) { if (null != fqn) { final int indexOfDOT = fqn.lastIndexOf(DOT); if (indexOfDOT > 0 && indexOfDOT < fqn.length() - 1) return fqn.substring(indexOfDOT + 1); } return fqn; } /** * Get all @Path class and export all methods * * @throws NoSuchFieldException * @throws SecurityException */ private void getDocResource(String packageDocumentationResource) { String mediaTypeProduces = null, mediaTypeConsumes = null; Reflections reflections = new Reflections(packageDocumentationResource); Set<Class<?>> reflectionResources = reflections .getTypesAnnotatedWith(Path.class); consoleLogger.info(format("Resources : {0}", reflectionResources)); for (Iterator<Class<?>> iterator = reflectionResources.iterator(); iterator .hasNext();) { Class<?> resource = iterator.next(); if (!resource.isInterface()) { Resource res = new Resource(); Annotation[] annotations = resource.getAnnotations(); Method[] declaredMethods = resource.getDeclaredMethods(); res.setEntryList(new TreeMap<String, List<ResourceEntry>>()); // Annotations for resource for (int i = 0; i < annotations.length; i++) { Annotation annotation = annotations[i]; if (annotation instanceof Path) { String rootPath = ((Path) annotation).value(); if (null != rootPath && !rootPath.endsWith("/")) { rootPath = rootPath + "/"; } res.setRootPath(rootPath); } if (annotation instanceof Produces) { mediaTypeProduces = ((Produces) annotation).value()[0]; } if (annotation instanceof Consumes) { mediaTypeConsumes = ((Consumes) annotation).value()[0]; } } // Check methods Class<?> superclass = resource.getSuperclass(); if (null != superclass && !superclass.getCanonicalName().equals( JAVA_LANG_OBJECT)) { Method[] superclassDeclaredMethods = superclass .getDeclaredMethods(); for (int i = 0; i < superclassDeclaredMethods.length; i++) { Method superclassDeclaredMethod = superclassDeclaredMethods[i]; ResourceEntry resourceEntry = createResourceEntryFromMethod( superclassDeclaredMethod, mediaTypeConsumes, mediaTypeProduces, resource); if (null != resourceEntry) { String path = resourceEntry.getPath(); if (null != path && path.startsWith("/")) { path = path.substring(1); } resourceEntry.setFullPath(res.getRootPath() + path); if (!res.getEntryList().containsKey(resourceEntry.getFullPath())) { res.getEntryList().put(resourceEntry.getFullPath(), new ArrayList<ResourceEntry>()); } List<ResourceEntry> resourceEntries = res.getEntryList().get(resourceEntry.getFullPath()); res.getEntryList().put(resourceEntry.getFullPath(), addResourceEntries(resourceEntries, resourceEntry)); } } } for (int i = 0; i < declaredMethods.length; i++) { Method declaredMethod = declaredMethods[i]; ResourceEntry resourceEntry = createResourceEntryFromMethod( declaredMethod, mediaTypeConsumes, mediaTypeProduces, resource); if (null != resourceEntry) { if (res.getEntryList().containsKey( resourceEntry.calculateUniqKey())) { res.getEntryList().remove( resourceEntry.calculateUniqKey()); } String path = resourceEntry.getPath(); if (null != path && path.startsWith("/")) { path = path.substring(1); } resourceEntry.setFullPath(res.getRootPath() + path); if (!res.getEntryList().containsKey(resourceEntry.getFullPath())) { res.getEntryList().put(resourceEntry.getFullPath(), new ArrayList<ResourceEntry>()); } List<ResourceEntry> resourceEntries = res.getEntryList().get(resourceEntry.getFullPath()); res.getEntryList().put(resourceEntry.getFullPath(), addResourceEntries(resourceEntries, resourceEntry)); } } consoleLogger.debug(">> " + resource.getCanonicalName()); resources.add(res); extractEntityFromResourceEntries(res); } else { consoleLogger.debug(">>skip " + resource.getCanonicalName()); } } } private List<ResourceEntry> addResourceEntries(List<ResourceEntry> resourceEntries, ResourceEntry resourceEntry) { final Iterator<ResourceEntry> iterator = resourceEntries.iterator(); while (iterator.hasNext()) { final ResourceEntry next = iterator.next(); if (next.getVerb().equals(resourceEntry.getVerb())) { iterator.remove(); } } resourceEntries.add(resourceEntry); return resourceEntries; } private void getMetadata() { metadata = new MasterDocMetadata(); metadata.setGenerationDate(SDF.format(new Date())); metadata.setGroupId(project.getGroupId()); metadata.setArtifactId(project.getArtifactId()); metadata.setVersion(project.getVersion()); } /** * Method to extract the class values. * * @param entityClass * @return * @throws ClassNotFoundException * @throws IntrospectionException */ private Map<String, AbstractEntity> extractFields(Class<?> entityClass) throws ClassNotFoundException, IntrospectionException { Map<String, AbstractEntity> fields = new TreeMap<String, AbstractEntity>(); consoleLogger.debug(format(">>Extract fields for class {0} ...", entityClass)); final java.lang.reflect.Field[] declaredFields = entityClass .getDeclaredFields(); for (int i = 0; i < declaredFields.length; i++) { java.lang.reflect.Field declaredField = declaredFields[i]; final Annotation[] declaredAnnotations = declaredField.getDeclaredAnnotations(); boolean bypass = false; String name = null; for (Annotation annotation : declaredAnnotations) { if (annotation.toString().contains("JsonIgnore")) { bypass = true; } if (annotation instanceof XmlTransient) { bypass = true; } if (annotation instanceof XmlElement) { name = ((XmlElement) annotation).name(); } } if (!bypass) { consoleLogger.debug(format(">>Extract fields {0} ...", declaredField.getName())); Type typeOfField = declaredField.getGenericType(); if (!typeOfField.toString().startsWith(CLASS) && !typeOfField.toString().startsWith(INTERFACE) && typeOfField.toString().indexOf(DOT) > -1) { typeOfField = (ParameterizedType) typeOfField; } String type = extractTypeFromType(typeOfField); String typeDisplay = type; if (type.startsWith("[")) { if (type.startsWith("[L") && type.endsWith(";")) { type = type.substring(2, type.length() - 1); } else { type = type.substring(1); if (BYTE.equals(type)) { type = byte.class.getName(); } } typeDisplay = type + ARRAY; } if (type.indexOf("<") > -1) { type = type.substring(type.indexOf("<") + 1, type.indexOf(">")); } String[] types = type.split(COMMA); if (isGetterSetterExist(entityClass, declaredField.getName())) { createEntityFromField(fields, declaredField, typeDisplay, types, null != name ? name : declaredField.getName()); } } } return fields; } private boolean isGetterSetterExist(Class<?> entityClass, String name) { try { entityClass.getDeclaredMethod(GET_PREFIX + capitalize(name)); // GET OR IS return true; } catch (NoSuchMethodException e) { try { entityClass.getDeclaredMethod(IS_PREFIX + capitalize(name)); // GET OR IS return true; } catch (NoSuchMethodException ex) { try { entityClass.getDeclaredMethod(GET_PREFIX + name); // GET OR IS return true; } catch (NoSuchMethodException exe) { try { entityClass.getDeclaredMethod(IS_PREFIX + name); // GET OR IS return true; } catch (NoSuchMethodException exec) { try { entityClass.getDeclaredMethod(name); // just name return true; } catch (NoSuchMethodException nsme) { } } } consoleLogger.debug(format(">>>>Bypass : {0}.{1}", entityClass.toString(), name)); } } return false; } private void createEntityFromField(Map<String, AbstractEntity> fields, Field declaredField, String typeDisplay, String[] types, String name) { Class<?> currEntityClass = null; for (String t : types) { try { t = t.trim(); currEntityClass = Class.forName(t, true, newClassLoader); if (!entityList.contains(t) && !newEntities.contains(t)) { newEntities.add(t); } } catch (Exception e) { consoleLogger.debug(format("{0} is not forNamable", t.toString())); continue; } } AbstractEntity field; if (null != currEntityClass && currEntityClass.isEnum()) { field = new Enumeration(); field.setName(typeDisplay.replaceAll("\\$", ".")); } else { field = new Entity(); field.setName(typeDisplay.replaceAll("\\$", ".")); } fields.put(name, field); } /** * Method to extract the enuration values. * * @param entity * @return * @throws ClassNotFoundException * @throws IntrospectionException */ private Map<String, AbstractEntity> extractEnumFields(Serializable entity) throws ClassNotFoundException, IntrospectionException { Map<String, AbstractEntity> fields = new TreeMap<String, AbstractEntity>(); List<String> values = new ArrayList<String>(); String entityString = entity.toString(); if (entityString.startsWith(CLASS)) { entityString = entityString.substring(entityString.indexOf(CLASS) + CLASS.length()); } consoleLogger.debug(">>>Extract enum " + entityString + " ..."); final Class<?> entityClass = Class.forName(entityString, true, newClassLoader); final Object[] declaredEnumConstants = entityClass.getFields(); // final Object[] declaredEnumConstants = entityClass.getEnumConstants(); Enumeration newEnumeration = new Enumeration(); newEnumeration.setName(entityString.replaceAll("\\$", ".")); for (int i = 0; i < declaredEnumConstants.length; i++) { values.add(extractName(declaredEnumConstants[i].toString())); } newEnumeration.setValues(values); // do not add an enum if its already in the entities list if (!entities.contains(newEnumeration)) { entities.add(newEnumeration); } return fields; } private void extractEntityFromResourceEntries(Resource res) { Map<String, List<ResourceEntry>> entryList = res.getEntryList(); Set<String> set = entryList.keySet(); for (Iterator<String> iterator = set.iterator(); iterator.hasNext();) { String key = iterator.next(); List<ResourceEntry> resourceEntries = entryList.get(key); for (ResourceEntry resourceEntry : resourceEntries) { Serializable requestEntity = resourceEntry.getRequestEntity(); Serializable responseEntity = resourceEntry.getResponseEntity(); if (null != requestEntity && !NULL.equals(requestEntity) && !VOID.equals(requestEntity)) { entityList.add(removeList(requestEntity)); } if (null != responseEntity && !NULL.equals(responseEntity) && !VOID.equals(responseEntity)) { entityList.add(removeList(responseEntity)); } } } } private String removeList(Serializable entity) { String string = String.valueOf(entity); if (string.indexOf("<") > 0) { string = string.substring(string.indexOf("<") + 1, string.length() - 1); } return string; } private ResourceEntry createResourceEntryFromMethod(Method declaredMethod, String mediaTypeConsumes, String mediaTypeProduces, Class childResourceClass) { ResourceEntry resourceEntry = new ResourceEntry(mediaTypeConsumes, mediaTypeProduces); resourceEntry.setPath("/"); Annotation[] declaredAnnotations = declaredMethod .getDeclaredAnnotations(); for (int i = 0; i < declaredAnnotations.length; i++) { Annotation declaredAnnotation = declaredAnnotations[i]; if (declaredAnnotation instanceof Path) { String path = ((Path) declaredAnnotation).value(); if (null != path && !path.startsWith("/")) { path = "/" + path; } resourceEntry.setPath(path); } if (declaredAnnotation instanceof Produces) { resourceEntry .setMediaTypeProduces(((Produces) declaredAnnotation) .value()[0]); } if (declaredAnnotation instanceof Consumes) { resourceEntry .setMediaTypeConsumes(((Consumes) declaredAnnotation) .value()[0]); } if (declaredAnnotation instanceof GET) { resourceEntry.setVerb(GET); } if (declaredAnnotation instanceof POST) { resourceEntry.setVerb(POST); } if (declaredAnnotation instanceof PUT) { resourceEntry.setVerb(PUT); } if (declaredAnnotation instanceof DELETE) { resourceEntry.setVerb(DELETE); } if (declaredAnnotation instanceof OPTIONS) { resourceEntry.setVerb(OPTIONS); } } if (null == resourceEntry.getVerb()) { return null; } Object[] pType; if (null != childResourceClass) { pType = GenericTypeReflector.getExactParameterTypes(declaredMethod, childResourceClass); } else { pType = declaredMethod.getParameterTypes(); } Annotation[][] pAnnot = declaredMethod.getParameterAnnotations(); for (int i = 0; i < pType.length; i++) { String typeName = ""; if (pType[i] instanceof Class) { typeName = ((Class) pType[i]).getName(); } else { typeName = extractTypeFromType(((ParameterizedType) pType[i])); } if (JAVA_UTIL_HASH_MAP.equals(typeName)) { Type[] types = declaredMethod.getGenericParameterTypes(); ParameterizedType paramType = (ParameterizedType) types[i]; typeName = extractTypeFromType(paramType); } boolean isAParam = false; for (int j = 0; j < pAnnot[i].length; j++) { Annotation annotation = pAnnot[i][j]; if (annotation instanceof PathParam) { Param param = new Param(); param.setType(PATH_PARAM); param.setClassName(typeName); param.setName(((PathParam) annotation).value()); resourceEntry.getPathParams().add(param); isAParam = true; } if (annotation instanceof QueryParam) { Param param = new Param(); param.setType(QUERY_PARAM); param.setClassName(typeName); param.setName(((QueryParam) annotation).value()); resourceEntry.getQueryParams().add(param); isAParam = true; } if (annotation instanceof javax.ws.rs.core.Context) { isAParam = true; } } if (!isAParam) { if (typeName.startsWith("[")) { if (typeName.startsWith("[L") && typeName.endsWith(";")) { typeName = typeName.substring(2, typeName.length() - 1); } else { typeName = typeName.substring(1); if (BYTE.equals(typeName)) { typeName = byte.class.getName(); } } typeName = typeName + ARRAY; } resourceEntry.setRequestEntity(typeName); } if (!entityList.contains(typeName)) { entityList.add(typeName); } } if (null != childResourceClass) { Type exactReturnType = GenericTypeReflector.getExactReturnType( declaredMethod, childResourceClass); resourceEntry .setResponseEntity(extractTypeFromType(exactReturnType)); } else { resourceEntry.setResponseEntity(extractTypeFromType(declaredMethod .getGenericReturnType())); } resourceEntry.setMethodName(declaredMethod.getName()); return resourceEntry; } private String extractTypeFromType(Type type) { String returnType = null; if (T.equals(type.toString())) { return JAVA_LANG_OBJECT; } if (type instanceof ParameterizedType) { returnType = type.toString(); if (returnType.startsWith(CLASS)) { returnType = returnType.substring(returnType.indexOf(CLASS)); } } else { returnType = ((Class) type).getName(); } return returnType; } /** * @param project * @throws NoSuchFieldException * @throws IllegalAccessException */ private void generateProjectClassLoader(MavenProject project) throws NoSuchFieldException, IllegalAccessException { List<URL> urls = new ArrayList<URL>(); // get all the dependencies which are hidden in resolvedArtifacts of project object Field dependencies = MavenProject.class. getDeclaredField("resolvedArtifacts"); dependencies.setAccessible(true); LinkedHashSet<Artifact> artifacts = (LinkedHashSet<Artifact>) dependencies.get(project); // noinspection unchecked for (Artifact artifact : artifacts) { try { urls.add(artifact.getFile().toURI().toURL()); } catch (MalformedURLException e) { // logger.error(e); } } try { urls.add(new File(project.getBuild().getOutputDirectory()).toURI().toURL()); } catch (MalformedURLException e) { consoleLogger.error(e.getMessage()); } consoleLogger.debug("urls = \n" + urls.toString().replace(",", "\n")); newClassLoader = new URLClassLoader(urls.toArray(new URL[urls.size()]), originalClassLoader); Thread.currentThread().setContextClassLoader(newClassLoader); } /** * @param generateHTMLSite */ private void generateDocumentationFile(boolean generateHTMLSite) { JacksonJsonProvider jsonProvider = new JacksonJsonProvider(); ObjectMapper mapper = jsonProvider.getObjectMapper(); MasterDoc masterDoc = new MasterDoc(); Function<AbstractEntity, String> getNameFunction = new Function<AbstractEntity, String>() { public String apply(AbstractEntity from) { return extractName(from.getName()); } }; Ordering<AbstractEntity> nameOrdering = Ordering.natural().onResultOf(getNameFunction); ImmutableSortedSet<AbstractEntity> sortedEntities = ImmutableSortedSet.orderedBy( nameOrdering).addAll(entities).build(); masterDoc.setEntities(sortedEntities.asList()); Function<Resource, String> getPathFunction = new Function<Resource, String>() { public String apply(Resource from) { return from.getRootPath(); } }; Ordering<Resource> pathOrdering = Ordering.natural().onResultOf(getPathFunction); ImmutableSortedSet<Resource> sortedResources = ImmutableSortedSet.orderedBy( pathOrdering).addAll(resources).build(); masterDoc.setResources(sortedResources.asList()); masterDoc.setMetadata(metadata); consoleLogger.info(format("Generate files in {0} ...", pathToGenerateFile)); File theDir = new File(pathToGenerateFile); // if the directory does not exist, create it theDir.mkdirs(); try { File fileEntities = new File(pathToGenerateFile + separator + MASTERDOC_JSON_FILENAME); BufferedWriter output = new BufferedWriter(new FileWriter( fileEntities)); output.write(mapper.defaultPrettyPrintingWriter() .writeValueAsString(masterDoc)); output.close(); if (generateHTMLSite) { consoleLogger.debug("Start HTMLSite generation"); final URL location = getClass().getProtectionDomain().getCodeSource().getLocation(); final ZipFile zipFile = new ZipFile(location.getPath()); final java.util.Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); if (entry.getName().startsWith(MASTERDOCS_DIR)) { consoleLogger.debug(format("Copy file : {0}", entry.getName())); File file = new File(pathToGenerateFile + separator, entry.getName()); if (entry.isDirectory()) { file.mkdirs(); } else { file.getParentFile().mkdirs(); InputStream in = zipFile.getInputStream(entry); try { copy(in, file); } finally { in.close(); } } } } String handlebarsTemplate = pathToGenerateFile + separator + MASTERDOCS_DIR + separator; handleBarsApply(masterDoc, handlebarsTemplate); consoleLogger.info(format("HTMLSite generate in {0}", pathToGenerateFile)); } } catch (IOException e) { e.printStackTrace(); } } protected String handleBarsApply(MasterDoc masterDoc, String handlebarsTemplate) throws IOException { final FileTemplateLoader fileTemplateLoader = new FileTemplateLoader(handlebarsTemplate); Handlebars handlebars = new Handlebars(fileTemplateLoader); handlebars.registerHelper("isEnum", new Helper<AbstractEntity>() { @Override public CharSequence apply(AbstractEntity abstractEntity, Options options) throws IOException { if (abstractEntity instanceof Enumeration) return options.fn(); else return options.inverse(); } }); handlebars.registerHelper("getLabelColor", new Helper<ResourceEntry>() { @Override public CharSequence apply(ResourceEntry entry, Options options) throws IOException { if (GET.equals(entry.getVerb())) { return "info"; } if (DELETE.equals(entry.getVerb())) { return "error"; } if (POST.equals(entry.getVerb())) { return "success"; } if (PUT.equals(entry.getVerb())) { return "warning"; } return "info"; } }); handlebars.registerHelper("extractName", new Helper<String>() { @Override public CharSequence apply(String context, Options options) throws IOException { return extractNameFromFQN(context); } }); handlebars.registerHelper("generateResID", new Helper<Resource>() { @Override public CharSequence apply(Resource context, Options options) throws IOException { return context.getRootPath().replaceAll("/", "_").replaceAll("\\{", "").replaceAll("}", ""); } }); handlebars.registerHelper("generateResEntryID", new Helper<ResourceEntry>() { @Override public CharSequence apply(ResourceEntry context, Options options) throws IOException { return context.calculateUniqKey(); } }); handlebars.registerHelper("decorate", new Helper<String>() { @Override public CharSequence apply(String context, Options options) throws IOException { return decorateURL(context); } }); handlebars.registerHelper("generateResEntryID", new Helper<ResourceEntry>() { @Override public CharSequence apply(ResourceEntry context, Options options) throws IOException { return new Handlebars.SafeString((context.getFullPath() + context.calculateUniqKey()).replaceAll("<<", "").replaceAll("/", "").replaceAll("}", "") .replaceAll("\\{", "") .replaceAll(":", "") .replaceAll("\\+", "") .replaceAll("\\{", "").replaceAll("\\\\", "")); } }); handlebars.registerHelper("URL", new Helper<ResourceEntry>() { @Override public CharSequence apply(ResourceEntry context, Options options) throws IOException { URIBuilder uriBuilder = new URIBuilder(); for (Param queryParam : context.getQueryParams()) { uriBuilder.addParameter(queryParam.getName(), "value"); } uriBuilder.setPath(context.getFullPath()); try { return decorateURL(uriBuilder.build().toString().replaceAll("%7B", "{").replaceAll("%7D", "}")); } catch (URISyntaxException e) { return decorateURL(context.getFullPath()); } } }); handlebars.registerHelper("JSON", new Helper<String>() { @Override public CharSequence apply(String context, Options options) throws IOException { try { JSONObject jso = new JSONObject(); JSONArray jsa = null; if (context.startsWith(JAVA_UTIL_HASH_MAP) || context.startsWith(JAVA_UTIL_SET) || context.startsWith(JAVA_UTIL_LIST)) { jsa = new JSONArray(); final int beginIndex = context.indexOf("<") + 1; final int finishIndex = context.indexOf(">"); context = context.substring(beginIndex, finishIndex); } final AbstractEntity entity = extractEntity(context); if (null != entity) { if (entity instanceof Entity) { try { final TreeMap<String, Integer> depthObj = new TreeMap<String, Integer>(); final Object jsonFromEntity = getJSONFromEntity((Entity) entity, depthObj); if (jsonFromEntity instanceof JSONObject) { jso = (JSONObject) jsonFromEntity; } else { jsa = (JSONArray) jsonFromEntity; } } catch (JSONException e) { } if (null != jsa) { jsa.put(jso); return jsa.toString(); } return jso.toString(); } else { return ((Enumeration) entity).getValues().get(0); } } } catch (Exception e) { return context; } return null; } }); handlebars.registerHelper("LINK", new Helper<AbstractEntity>() { @Override public CharSequence apply(AbstractEntity context, Options options) throws IOException { String name = context.getName(); if (name.startsWith(JAVA_UTIL_HASH_MAP) || name.startsWith(JAVA_UTIL_SET) || name.startsWith(JAVA_UTIL_LIST)) { final int beginIndex = name.indexOf("<") + 1; final int finishIndex = name.indexOf(">"); name = name.substring(beginIndex, finishIndex); } return "<a href=\"#" + name + "\">"; } }); Template template = handlebars.compile("index"); Context ctx = Context.newContext(masterDoc); String newIndex = template.apply(ctx); File indexFile = new File(handlebarsTemplate + "index.html"); FileWriter fw = new FileWriter(indexFile.getAbsoluteFile()); BufferedWriter bw = new BufferedWriter(fw); bw.write(newIndex); bw.close(); return newIndex; } private Object getJSONFromEntity(Entity entity, TreeMap<String, Integer> depthObj) throws JSONException { JSONObject jsonObject = new JSONObject(); JSONArray jsa = null; String name = entity.getName(); if (name.startsWith(JAVA_UTIL_HASH_MAP) || name.startsWith(JAVA_UTIL_SET) || name.startsWith(JAVA_UTIL_LIST)) { jsa = new JSONArray(); final int beginIndex = name.indexOf("<") + 1; final int finishIndex = name.indexOf(">"); name = name.substring(beginIndex, finishIndex); } final AbstractEntity extractEntity = extractEntity(name); if (null != extractEntity) { if (!depthObj.containsKey(name)) { depthObj.put(name, 0); } final Integer nbObj = depthObj.get(name) + 1; if (nbObj > MAX_DEPTH) { return new JSONObject(); } depthObj.put(name, nbObj); // SuperClass final Entity myEntity = (Entity) extractEntity; final String superClass = myEntity.getSuperClass(); if (null != superClass) { final AbstractEntity superClassEntity = extractEntity(superClass); if (null != superClassEntity) { jsonObject = enrichWithFields(jsonObject, (Entity) superClassEntity, depthObj); } } // Class jsonObject = enrichWithFields(jsonObject, myEntity, depthObj); } else { // Maybe a JDK type, trying to instanciate Class aClass = null; try { aClass = Class.forName(name); } catch (ClassNotFoundException e) { if ("boolean".equals(name)) { aClass = boolean.class; } else if ("byte".equals(name)) { aClass = byte.class; } else if ("short".equals(name)) { aClass = short.class; } else if ("int".equals(name)) { aClass = int.class; } else if ("long".equals(name)) { aClass = long.class; } else if ("long".equals(name)) { aClass = float.class; } else if ("double".equals(name)) { aClass = double.class; } } try { return aClass.newInstance(); } catch (Exception e) { return defaultValue(aClass); } } if (null != jsa) { jsa.put(jsonObject); return jsa; } return jsonObject; } private AbstractEntity extractEntity(String entityName) { for (AbstractEntity entity : entities) { if (entityName.equals(entity.getName())) { return entity; } } return null; } private JSONObject enrichWithFields(JSONObject parent, Entity entity, TreeMap<String, Integer> depthObj) throws JSONException { final Map<String, AbstractEntity> fields = entity.getFields(); if (fields != null && fields.keySet() != null) { final Iterator<String> iterator = fields.keySet().iterator(); while (iterator.hasNext()) { final String key = iterator.next(); final AbstractEntity abstractEntity = fields.get(key); if (null != abstractEntity) { if (abstractEntity instanceof Entity) { if (depthObj.containsKey(abstractEntity.getName()) && depthObj.get(abstractEntity.getName()) > MAX_DEPTH) { parent.put(key, new JSONObject()); } else { parent.put(key, getJSONFromEntity((Entity) abstractEntity, depthObj)); } } else { final AbstractEntity enumExtracted = extractEntity(abstractEntity.getName()); if (null != enumExtracted) { final List<String> values = ((Enumeration) enumExtracted).getValues(); if (values != null && !values.isEmpty()) { parent.put(key, values.get(0)); } } else { parent.put(key, "{" + abstractEntity.getName() + "}"); } // } } } } } return parent; } private CharSequence decorateURL(String context) { String url = context.replaceAll("\\{", "<span class=\"ink-label success invert\">{") .replaceAll("}", "}</span>") .replaceAll("&", "</span>&<span class=\"ink-label info invert\">") .replaceAll("\\?", "?<span class=\"ink-label info invert\">"); if (url.indexOf("?") > -1) { url = url + "</span>"; } return url; } private CharSequence extractNameFromFQN(String name) { final String[] split = name.split("<"); boolean first = true; StringBuilder sb = new StringBuilder(); for (String part : split) { sb.append(part.substring(part.lastIndexOf(DOT) + 1)); if (first && split.length > 1) { sb.append("<"); } first = false; } return sb.toString(); } }
src/main/java/fr/masterdocs/plugin/MasterDocGenerator.java
package fr.masterdocs.plugin; import com.github.jknack.handlebars.*; import com.github.jknack.handlebars.io.FileTemplateLoader; import com.google.common.base.Function; import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.Ordering; import com.googlecode.gentyref.GenericTypeReflector; import fr.masterdocs.pojo.*; import fr.masterdocs.pojo.Enumeration; import org.apache.http.client.utils.URIBuilder; import org.apache.maven.artifact.Artifact; import org.apache.maven.project.MavenProject; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jettison.json.JSONArray; import org.codehaus.jettison.json.JSONException; import org.codehaus.jettison.json.JSONObject; import org.codehaus.plexus.logging.console.ConsoleLogger; import org.reflections.Reflections; import javax.ws.rs.*; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlTransient; import java.beans.IntrospectionException; import java.io.*; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; import java.net.URLClassLoader; import java.text.SimpleDateFormat; import java.util.*; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import static com.google.common.base.Defaults.defaultValue; import static java.io.File.separator; import static java.text.MessageFormat.format; import static org.springframework.util.StringUtils.capitalize; public class MasterDocGenerator { // ---------------------------------------------------------------------- // Constants // ---------------------------------------------------------------------- public static final String CLASS = "class "; public static final SimpleDateFormat SDF = new SimpleDateFormat("dd-MM-yyyy HH:mm:sss"); public static final String MASTERDOC_JSON_FILENAME = "masterdocs.json"; public static final String PATH_PARAM = "PathParam"; public static final String QUERY_PARAM = "QueryParam"; public static final String JAVA_UTIL_HASH_MAP = "java.util.HashMap"; public static final String GET = "GET"; public static final String POST = "POST"; public static final String PUT = "PUT"; public static final String DELETE = "DELETE"; public static final String OPTIONS = "OPTIONS"; public static final String NULL = "null"; public static final String VOID = "void"; public static final String IS_PREFIX = "is"; public static final String GET_PREFIX = "get"; public static final String INTERFACE = "interface"; public static final String T = "T"; public static final String JAVA_LANG_OBJECT = "java.lang.Object"; public static final String JAVA = "java"; public static final String BYTE = "B"; public static final String ARRAY = "[]"; public static final String DOT = "."; public static final String COMMA = ","; public static final String MASTERDOCS_DIR = "masterdocs"; private static final String JAVA_UTIL_LIST = "java.util.List"; private static final String JAVA_UTIL_SET = "java.util.Set"; public Integer MAX_DEPTH = 1; // ---------------------------------------------------------------------- // Variables // ---------------------------------------------------------------------- /** * Logger for maven plugin. */ private ConsoleLogger consoleLogger = new ConsoleLogger(); /** * Resources found by MasterDoc. */ private List<Resource> resources; /** * Entities found by MasterDoc. */ private List<AbstractEntity> entities; /** * Metadata found by MasterDoc. */ private MasterDocMetadata metadata; /** * Final MasterDoc. */ private Set<String> entityList; private MavenProject project; private ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader(); private ClassLoader newClassLoader; private String pathToGenerateFile; private HashSet<String> newEntities; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- public MasterDocGenerator() { } public MasterDocGenerator(MavenProject project, String pathToGenerateFile, String[] packageDocumentationResources, boolean generateHTMLSite, Integer maxDepth) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException { long start = System.currentTimeMillis(); consoleLogger.info("MasterDocGenerator started"); resources = new ArrayList<Resource>(); entities = new ArrayList<AbstractEntity>(); entityList = new HashSet<String>(); this.project = project; this.pathToGenerateFile = pathToGenerateFile; if (null != maxDepth) { this.MAX_DEPTH = maxDepth; } // //////////////////// generateProjectClassLoader(project); // //////////////////// for (String packageDocumentationResource : packageDocumentationResources) { consoleLogger.info(format("Generate REST documentation on package {0} ...", packageDocumentationResource)); startGeneration(new String[] { packageDocumentationResource }); } // generateDocumentationFile(generateHTMLSite); // // restore original classloader Thread.currentThread().setContextClassLoader(originalClassLoader); consoleLogger.info(format("Generation ended in {0} ms", (System.currentTimeMillis() - start))); } private static void copy(InputStream in, OutputStream out) throws IOException { byte[] buffer = new byte[1024]; while (true) { int readCount = in.read(buffer); if (readCount < 0) { break; } out.write(buffer, 0, readCount); } } private static void copy(File file, OutputStream out) throws IOException { InputStream in = new FileInputStream(file); try { copy(in, out); } finally { in.close(); } } private static void copy(InputStream in, File file) throws IOException { OutputStream out = new FileOutputStream(file); try { copy(in, out); } finally { out.close(); } } // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public void startGeneration(String[] args) { String packageDocumentationResource = args[0]; if (null != packageDocumentationResource && packageDocumentationResource.length() > 0) { try { getMetadata(); getDocResource(packageDocumentationResource); getEntities(entityList); consoleLogger.info(format("Entities : {0}", entityList.size())); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (IntrospectionException e) { e.printStackTrace(); } } else { consoleLogger.error("packageDocumentationResources not defined in plugin configuration"); } } // ---------------------------------------------------------------------- // Private methods // ---------------------------------------------------------------------- private void getEntities(Set list) throws ClassNotFoundException, IntrospectionException { newEntities = new HashSet<String>(); for (Iterator<Serializable> iterator = list.iterator(); iterator .hasNext();) { Serializable entity = iterator.next(); final Class<?> entityClass; String entityToString = entity.toString(); try { if (entityToString.startsWith(JAVA_UTIL_LIST)) { entityToString = entityToString.substring(JAVA_UTIL_LIST.length() + 1, entityToString.length() - 1); } entityClass = Class.forName(entityToString, true, newClassLoader); } catch (Exception e) { consoleLogger.debug(format("{0} is not forNamable", entityToString)); continue; } Entity newEntity = new Entity(); if (!entityToString.startsWith(JAVA)) { newEntity.setName(entityToString.replaceAll("\\$", ".")); if (entityClass.isEnum()) { extractEnumFields(entity); } else { newEntity.setFields(extractFields(entityClass)); final Class<?> superclass = entityClass.getSuperclass(); if (!JAVA_LANG_OBJECT.equals(superclass.getName())) { newEntity.setSuperClass(superclass.getName()); if (!entityList.contains(superclass.getName()) && !newEntities.contains(superclass.getName())) { newEntities.add(superclass.getName()); } } if (newEntity.getFields().isEmpty()) { newEntity.setFields(null); } entities.add(newEntity); } } } if (newEntities.size() > 0) { entityList.addAll(newEntities); getEntities((Set) newEntities.clone()); } } private String extractName(String fqn) { if (null != fqn) { final int indexOfDOT = fqn.lastIndexOf(DOT); if (indexOfDOT > 0 && indexOfDOT < fqn.length() - 1) return fqn.substring(indexOfDOT + 1); } return fqn; } /** * Get all @Path class and export all methods * * @throws NoSuchFieldException * @throws SecurityException */ private void getDocResource(String packageDocumentationResource) { String mediaTypeProduces = null, mediaTypeConsumes = null; Reflections reflections = new Reflections(packageDocumentationResource); Set<Class<?>> reflectionResources = reflections .getTypesAnnotatedWith(Path.class); consoleLogger.info(format("Resources : {0}", reflectionResources)); for (Iterator<Class<?>> iterator = reflectionResources.iterator(); iterator .hasNext();) { Class<?> resource = iterator.next(); if (!resource.isInterface()) { Resource res = new Resource(); Annotation[] annotations = resource.getAnnotations(); Method[] declaredMethods = resource.getDeclaredMethods(); res.setEntryList(new TreeMap<String, List<ResourceEntry>>()); // Annotations for resource for (int i = 0; i < annotations.length; i++) { Annotation annotation = annotations[i]; if (annotation instanceof Path) { String rootPath = ((Path) annotation).value(); if (null != rootPath && !rootPath.endsWith("/")) { rootPath = rootPath + "/"; } res.setRootPath(rootPath); } if (annotation instanceof Produces) { mediaTypeProduces = ((Produces) annotation).value()[0]; } if (annotation instanceof Consumes) { mediaTypeConsumes = ((Consumes) annotation).value()[0]; } } // Check methods Class<?> superclass = resource.getSuperclass(); if (null != superclass && !superclass.getCanonicalName().equals( JAVA_LANG_OBJECT)) { Method[] superclassDeclaredMethods = superclass .getDeclaredMethods(); for (int i = 0; i < superclassDeclaredMethods.length; i++) { Method superclassDeclaredMethod = superclassDeclaredMethods[i]; ResourceEntry resourceEntry = createResourceEntryFromMethod( superclassDeclaredMethod, mediaTypeConsumes, mediaTypeProduces, resource); if (null != resourceEntry) { String path = resourceEntry.getPath(); if (null != path && path.startsWith("/")) { path = path.substring(1); } resourceEntry.setFullPath(res.getRootPath() + path); if (!res.getEntryList().containsKey(resourceEntry.getFullPath())) { res.getEntryList().put(resourceEntry.getFullPath(), new ArrayList<ResourceEntry>()); } List<ResourceEntry> resourceEntries = res.getEntryList().get(resourceEntry.getFullPath()); res.getEntryList().put(resourceEntry.getFullPath(), addResourceEntries(resourceEntries, resourceEntry)); } } } for (int i = 0; i < declaredMethods.length; i++) { Method declaredMethod = declaredMethods[i]; ResourceEntry resourceEntry = createResourceEntryFromMethod( declaredMethod, mediaTypeConsumes, mediaTypeProduces, resource); if (null != resourceEntry) { if (res.getEntryList().containsKey( resourceEntry.calculateUniqKey())) { res.getEntryList().remove( resourceEntry.calculateUniqKey()); } String path = resourceEntry.getPath(); if (null != path && path.startsWith("/")) { path = path.substring(1); } resourceEntry.setFullPath(res.getRootPath() + path); if (!res.getEntryList().containsKey(resourceEntry.getFullPath())) { res.getEntryList().put(resourceEntry.getFullPath(), new ArrayList<ResourceEntry>()); } List<ResourceEntry> resourceEntries = res.getEntryList().get(resourceEntry.getFullPath()); res.getEntryList().put(resourceEntry.getFullPath(), addResourceEntries(resourceEntries, resourceEntry)); } } consoleLogger.debug(">> " + resource.getCanonicalName()); resources.add(res); extractEntityFromResourceEntries(res); } else { consoleLogger.debug(">>skip " + resource.getCanonicalName()); } } } private List<ResourceEntry> addResourceEntries(List<ResourceEntry> resourceEntries, ResourceEntry resourceEntry) { final Iterator<ResourceEntry> iterator = resourceEntries.iterator(); while (iterator.hasNext()) { final ResourceEntry next = iterator.next(); if (next.getVerb().equals(resourceEntry.getVerb())) { iterator.remove(); } } resourceEntries.add(resourceEntry); return resourceEntries; } private void getMetadata() { metadata = new MasterDocMetadata(); metadata.setGenerationDate(SDF.format(new Date())); metadata.setGroupId(project.getGroupId()); metadata.setArtifactId(project.getArtifactId()); metadata.setVersion(project.getVersion()); } /** * Method to extract the class values. * * @param entityClass * @return * @throws ClassNotFoundException * @throws IntrospectionException */ private Map<String, AbstractEntity> extractFields(Class<?> entityClass) throws ClassNotFoundException, IntrospectionException { Map<String, AbstractEntity> fields = new HashMap<String, AbstractEntity>(); consoleLogger.debug(format(">>Extract fields for class {0} ...", entityClass)); final java.lang.reflect.Field[] declaredFields = entityClass .getDeclaredFields(); for (int i = 0; i < declaredFields.length; i++) { java.lang.reflect.Field declaredField = declaredFields[i]; final Annotation[] declaredAnnotations = declaredField.getDeclaredAnnotations(); boolean bypass = false; String name = null; for (Annotation annotation : declaredAnnotations) { if (annotation.toString().contains("JsonIgnore")) { bypass = true; } if (annotation instanceof XmlTransient) { bypass = true; } if (annotation instanceof XmlElement) { name = ((XmlElement) annotation).name(); } } if (!bypass) { consoleLogger.debug(format(">>Extract fields {0} ...", declaredField.getName())); Type typeOfField = declaredField.getGenericType(); if (!typeOfField.toString().startsWith(CLASS) && !typeOfField.toString().startsWith(INTERFACE) && typeOfField.toString().indexOf(DOT) > -1) { typeOfField = (ParameterizedType) typeOfField; } String type = extractTypeFromType(typeOfField); String typeDisplay = type; if (type.startsWith("[")) { if (type.startsWith("[L") && type.endsWith(";")) { type = type.substring(2, type.length() - 1); } else { type = type.substring(1); if (BYTE.equals(type)) { type = byte.class.getName(); } } typeDisplay = type + ARRAY; } if (type.indexOf("<") > -1) { type = type.substring(type.indexOf("<") + 1, type.indexOf(">")); } String[] types = type.split(COMMA); if (isGetterSetterExist(entityClass, declaredField.getName())) { createEntityFromField(fields, declaredField, typeDisplay, types, null != name ? name : declaredField.getName()); } } } return fields; } private boolean isGetterSetterExist(Class<?> entityClass, String name) { try { entityClass.getDeclaredMethod(GET_PREFIX + capitalize(name)); // GET OR IS return true; } catch (NoSuchMethodException e) { try { entityClass.getDeclaredMethod(IS_PREFIX + capitalize(name)); // GET OR IS return true; } catch (NoSuchMethodException ex) { try { entityClass.getDeclaredMethod(GET_PREFIX + name); // GET OR IS return true; } catch (NoSuchMethodException exe) { try { entityClass.getDeclaredMethod(IS_PREFIX + name); // GET OR IS return true; } catch (NoSuchMethodException exec) { try { entityClass.getDeclaredMethod(name); // just name return true; } catch (NoSuchMethodException nsme) { } } } consoleLogger.debug(format(">>>>Bypass : {0}.{1}", entityClass.toString(), name)); } } return false; } private void createEntityFromField(Map<String, AbstractEntity> fields, Field declaredField, String typeDisplay, String[] types, String name) { Class<?> currEntityClass = null; for (String t : types) { try { t = t.trim(); currEntityClass = Class.forName(t, true, newClassLoader); if (!entityList.contains(t) && !newEntities.contains(t)) { newEntities.add(t); } } catch (Exception e) { consoleLogger.debug(format("{0} is not forNamable", t.toString())); continue; } } AbstractEntity field; if (null != currEntityClass && currEntityClass.isEnum()) { field = new Enumeration(); field.setName(typeDisplay.replaceAll("\\$", ".")); } else { field = new Entity(); field.setName(typeDisplay.replaceAll("\\$", ".")); } fields.put(name, field); } /** * Method to extract the enuration values. * * @param entity * @return * @throws ClassNotFoundException * @throws IntrospectionException */ private Map<String, AbstractEntity> extractEnumFields(Serializable entity) throws ClassNotFoundException, IntrospectionException { Map<String, AbstractEntity> fields = new HashMap<String, AbstractEntity>(); List<String> values = new ArrayList<String>(); String entityString = entity.toString(); if (entityString.startsWith(CLASS)) { entityString = entityString.substring(entityString.indexOf(CLASS) + CLASS.length()); } consoleLogger.debug(">>>Extract enum " + entityString + " ..."); final Class<?> entityClass = Class.forName(entityString, true, newClassLoader); final Object[] declaredEnumConstants = entityClass.getFields(); // final Object[] declaredEnumConstants = entityClass.getEnumConstants(); Enumeration newEnumeration = new Enumeration(); newEnumeration.setName(entityString.replaceAll("\\$", ".")); for (int i = 0; i < declaredEnumConstants.length; i++) { values.add(extractName(declaredEnumConstants[i].toString())); } newEnumeration.setValues(values); // do not add an enum if its already in the entities list if (!entities.contains(newEnumeration)) { entities.add(newEnumeration); } return fields; } private void extractEntityFromResourceEntries(Resource res) { Map<String, List<ResourceEntry>> entryList = res.getEntryList(); Set<String> set = entryList.keySet(); for (Iterator<String> iterator = set.iterator(); iterator.hasNext();) { String key = iterator.next(); List<ResourceEntry> resourceEntries = entryList.get(key); for (ResourceEntry resourceEntry : resourceEntries) { Serializable requestEntity = resourceEntry.getRequestEntity(); Serializable responseEntity = resourceEntry.getResponseEntity(); if (null != requestEntity && !NULL.equals(requestEntity) && !VOID.equals(requestEntity)) { entityList.add(removeList(requestEntity)); } if (null != responseEntity && !NULL.equals(responseEntity) && !VOID.equals(responseEntity)) { entityList.add(removeList(responseEntity)); } } } } private String removeList(Serializable entity) { String string = String.valueOf(entity); if (string.indexOf("<") > 0) { string = string.substring(string.indexOf("<") + 1, string.length() - 1); } return string; } private ResourceEntry createResourceEntryFromMethod(Method declaredMethod, String mediaTypeConsumes, String mediaTypeProduces, Class childResourceClass) { ResourceEntry resourceEntry = new ResourceEntry(mediaTypeConsumes, mediaTypeProduces); resourceEntry.setPath("/"); Annotation[] declaredAnnotations = declaredMethod .getDeclaredAnnotations(); for (int i = 0; i < declaredAnnotations.length; i++) { Annotation declaredAnnotation = declaredAnnotations[i]; if (declaredAnnotation instanceof Path) { String path = ((Path) declaredAnnotation).value(); if (null != path && !path.startsWith("/")) { path = "/" + path; } resourceEntry.setPath(path); } if (declaredAnnotation instanceof Produces) { resourceEntry .setMediaTypeProduces(((Produces) declaredAnnotation) .value()[0]); } if (declaredAnnotation instanceof Consumes) { resourceEntry .setMediaTypeConsumes(((Consumes) declaredAnnotation) .value()[0]); } if (declaredAnnotation instanceof GET) { resourceEntry.setVerb(GET); } if (declaredAnnotation instanceof POST) { resourceEntry.setVerb(POST); } if (declaredAnnotation instanceof PUT) { resourceEntry.setVerb(PUT); } if (declaredAnnotation instanceof DELETE) { resourceEntry.setVerb(DELETE); } if (declaredAnnotation instanceof OPTIONS) { resourceEntry.setVerb(OPTIONS); } } if (null == resourceEntry.getVerb()) { return null; } Object[] pType; if (null != childResourceClass) { pType = GenericTypeReflector.getExactParameterTypes(declaredMethod, childResourceClass); } else { pType = declaredMethod.getParameterTypes(); } Annotation[][] pAnnot = declaredMethod.getParameterAnnotations(); for (int i = 0; i < pType.length; i++) { String typeName = ""; if (pType[i] instanceof Class) { typeName = ((Class) pType[i]).getName(); } else { typeName = extractTypeFromType(((ParameterizedType) pType[i])); } if (JAVA_UTIL_HASH_MAP.equals(typeName)) { Type[] types = declaredMethod.getGenericParameterTypes(); ParameterizedType paramType = (ParameterizedType) types[i]; typeName = extractTypeFromType(paramType); } boolean isAParam = false; for (int j = 0; j < pAnnot[i].length; j++) { Annotation annotation = pAnnot[i][j]; if (annotation instanceof PathParam) { Param param = new Param(); param.setType(PATH_PARAM); param.setClassName(typeName); param.setName(((PathParam) annotation).value()); resourceEntry.getPathParams().add(param); isAParam = true; } if (annotation instanceof QueryParam) { Param param = new Param(); param.setType(QUERY_PARAM); param.setClassName(typeName); param.setName(((QueryParam) annotation).value()); resourceEntry.getQueryParams().add(param); isAParam = true; } if (annotation instanceof javax.ws.rs.core.Context) { isAParam = true; } } if (!isAParam) { if (typeName.startsWith("[")) { if (typeName.startsWith("[L") && typeName.endsWith(";")) { typeName = typeName.substring(2, typeName.length() - 1); } else { typeName = typeName.substring(1); if (BYTE.equals(typeName)) { typeName = byte.class.getName(); } } typeName = typeName + ARRAY; } resourceEntry.setRequestEntity(typeName); } if (!entityList.contains(typeName)) { entityList.add(typeName); } } if (null != childResourceClass) { Type exactReturnType = GenericTypeReflector.getExactReturnType( declaredMethod, childResourceClass); resourceEntry .setResponseEntity(extractTypeFromType(exactReturnType)); } else { resourceEntry.setResponseEntity(extractTypeFromType(declaredMethod .getGenericReturnType())); } resourceEntry.setMethodName(declaredMethod.getName()); return resourceEntry; } private String extractTypeFromType(Type type) { String returnType = null; if (T.equals(type.toString())) { return JAVA_LANG_OBJECT; } if (type instanceof ParameterizedType) { returnType = type.toString(); if (returnType.startsWith(CLASS)) { returnType = returnType.substring(returnType.indexOf(CLASS)); } } else { returnType = ((Class) type).getName(); } return returnType; } /** * @param project * @throws NoSuchFieldException * @throws IllegalAccessException */ private void generateProjectClassLoader(MavenProject project) throws NoSuchFieldException, IllegalAccessException { List<URL> urls = new ArrayList<URL>(); // get all the dependencies which are hidden in resolvedArtifacts of project object Field dependencies = MavenProject.class. getDeclaredField("resolvedArtifacts"); dependencies.setAccessible(true); LinkedHashSet<Artifact> artifacts = (LinkedHashSet<Artifact>) dependencies.get(project); // noinspection unchecked for (Artifact artifact : artifacts) { try { urls.add(artifact.getFile().toURI().toURL()); } catch (MalformedURLException e) { // logger.error(e); } } try { urls.add(new File(project.getBuild().getOutputDirectory()).toURI().toURL()); } catch (MalformedURLException e) { consoleLogger.error(e.getMessage()); } consoleLogger.debug("urls = \n" + urls.toString().replace(",", "\n")); newClassLoader = new URLClassLoader(urls.toArray(new URL[urls.size()]), originalClassLoader); Thread.currentThread().setContextClassLoader(newClassLoader); } /** * @param generateHTMLSite */ private void generateDocumentationFile(boolean generateHTMLSite) { JacksonJsonProvider jsonProvider = new JacksonJsonProvider(); ObjectMapper mapper = jsonProvider.getObjectMapper(); MasterDoc masterDoc = new MasterDoc(); Function<AbstractEntity, String> getNameFunction = new Function<AbstractEntity, String>() { public String apply(AbstractEntity from) { return extractName(from.getName()); } }; Ordering<AbstractEntity> nameOrdering = Ordering.natural().onResultOf(getNameFunction); ImmutableSortedSet<AbstractEntity> sortedEntities = ImmutableSortedSet.orderedBy( nameOrdering).addAll(entities).build(); masterDoc.setEntities(sortedEntities.asList()); Function<Resource, String> getPathFunction = new Function<Resource, String>() { public String apply(Resource from) { return from.getRootPath(); } }; Ordering<Resource> pathOrdering = Ordering.natural().onResultOf(getPathFunction); ImmutableSortedSet<Resource> sortedResources = ImmutableSortedSet.orderedBy( pathOrdering).addAll(resources).build(); masterDoc.setResources(sortedResources.asList()); masterDoc.setMetadata(metadata); consoleLogger.info(format("Generate files in {0} ...", pathToGenerateFile)); File theDir = new File(pathToGenerateFile); // if the directory does not exist, create it theDir.mkdirs(); try { File fileEntities = new File(pathToGenerateFile + separator + MASTERDOC_JSON_FILENAME); BufferedWriter output = new BufferedWriter(new FileWriter( fileEntities)); output.write(mapper.defaultPrettyPrintingWriter() .writeValueAsString(masterDoc)); output.close(); if (generateHTMLSite) { consoleLogger.debug("Start HTMLSite generation"); final URL location = getClass().getProtectionDomain().getCodeSource().getLocation(); final ZipFile zipFile = new ZipFile(location.getPath()); final java.util.Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); if (entry.getName().startsWith(MASTERDOCS_DIR)) { consoleLogger.debug(format("Copy file : {0}", entry.getName())); File file = new File(pathToGenerateFile + separator, entry.getName()); if (entry.isDirectory()) { file.mkdirs(); } else { file.getParentFile().mkdirs(); InputStream in = zipFile.getInputStream(entry); try { copy(in, file); } finally { in.close(); } } } } String handlebarsTemplate = pathToGenerateFile + separator + MASTERDOCS_DIR + separator; handleBarsApply(masterDoc, handlebarsTemplate); consoleLogger.info(format("HTMLSite generate in {0}", pathToGenerateFile)); } } catch (IOException e) { e.printStackTrace(); } } protected String handleBarsApply(MasterDoc masterDoc, String handlebarsTemplate) throws IOException { final FileTemplateLoader fileTemplateLoader = new FileTemplateLoader(handlebarsTemplate); Handlebars handlebars = new Handlebars(fileTemplateLoader); handlebars.registerHelper("isEnum", new Helper<AbstractEntity>() { @Override public CharSequence apply(AbstractEntity abstractEntity, Options options) throws IOException { if (abstractEntity instanceof Enumeration) return options.fn(); else return options.inverse(); } }); handlebars.registerHelper("getLabelColor", new Helper<ResourceEntry>() { @Override public CharSequence apply(ResourceEntry entry, Options options) throws IOException { if (GET.equals(entry.getVerb())) { return "info"; } if (DELETE.equals(entry.getVerb())) { return "error"; } if (POST.equals(entry.getVerb())) { return "success"; } if (PUT.equals(entry.getVerb())) { return "warning"; } return "info"; } }); handlebars.registerHelper("extractName", new Helper<String>() { @Override public CharSequence apply(String context, Options options) throws IOException { return extractNameFromFQN(context); } }); handlebars.registerHelper("generateResID", new Helper<Resource>() { @Override public CharSequence apply(Resource context, Options options) throws IOException { return context.getRootPath().replaceAll("/", "_").replaceAll("\\{", "").replaceAll("}", ""); } }); handlebars.registerHelper("generateResEntryID", new Helper<ResourceEntry>() { @Override public CharSequence apply(ResourceEntry context, Options options) throws IOException { return context.calculateUniqKey(); } }); handlebars.registerHelper("decorate", new Helper<String>() { @Override public CharSequence apply(String context, Options options) throws IOException { return decorateURL(context); } }); handlebars.registerHelper("generateResEntryID", new Helper<ResourceEntry>() { @Override public CharSequence apply(ResourceEntry context, Options options) throws IOException { return new Handlebars.SafeString((context.getFullPath() + context.calculateUniqKey()).replaceAll("<<", "").replaceAll("/", "").replaceAll("}", "") .replaceAll("\\{", "") .replaceAll(":", "") .replaceAll("\\+", "") .replaceAll("\\{", "").replaceAll("\\\\", "")); } }); handlebars.registerHelper("URL", new Helper<ResourceEntry>() { @Override public CharSequence apply(ResourceEntry context, Options options) throws IOException { URIBuilder uriBuilder = new URIBuilder(); for (Param queryParam : context.getQueryParams()) { uriBuilder.addParameter(queryParam.getName(), "value"); } uriBuilder.setPath(context.getFullPath()); try { return decorateURL(uriBuilder.build().toString().replaceAll("%7B", "{").replaceAll("%7D", "}")); } catch (URISyntaxException e) { return decorateURL(context.getFullPath()); } } }); handlebars.registerHelper("JSON", new Helper<String>() { @Override public CharSequence apply(String context, Options options) throws IOException { try { JSONObject jso = new JSONObject(); JSONArray jsa = null; if (context.startsWith(JAVA_UTIL_HASH_MAP) || context.startsWith(JAVA_UTIL_SET) || context.startsWith(JAVA_UTIL_LIST)) { jsa = new JSONArray(); final int beginIndex = context.indexOf("<") + 1; final int finishIndex = context.indexOf(">"); context = context.substring(beginIndex, finishIndex); } final AbstractEntity entity = extractEntity(context); if (null != entity) { if (entity instanceof Entity) { try { final HashMap<String, Integer> depthObj = new HashMap<String, Integer>(); final Object jsonFromEntity = getJSONFromEntity((Entity) entity, depthObj); if (jsonFromEntity instanceof JSONObject) { jso = (JSONObject) jsonFromEntity; } else { jsa = (JSONArray) jsonFromEntity; } } catch (JSONException e) { } if (null != jsa) { jsa.put(jso); return jsa.toString(); } return jso.toString(); } else { return ((Enumeration) entity).getValues().get(0); } } } catch (Exception e) { return context; } return null; } }); handlebars.registerHelper("LINK", new Helper<AbstractEntity>() { @Override public CharSequence apply(AbstractEntity context, Options options) throws IOException { String name = context.getName(); if (name.startsWith(JAVA_UTIL_HASH_MAP) || name.startsWith(JAVA_UTIL_SET) || name.startsWith(JAVA_UTIL_LIST)) { final int beginIndex = name.indexOf("<") + 1; final int finishIndex = name.indexOf(">"); name = name.substring(beginIndex, finishIndex); } return "<a href=\"#" + name + "\">"; } }); Template template = handlebars.compile("index"); Context ctx = Context.newContext(masterDoc); String newIndex = template.apply(ctx); File indexFile = new File(handlebarsTemplate + "index.html"); FileWriter fw = new FileWriter(indexFile.getAbsoluteFile()); BufferedWriter bw = new BufferedWriter(fw); bw.write(newIndex); bw.close(); return newIndex; } private Object getJSONFromEntity(Entity entity, HashMap<String, Integer> depthObj) throws JSONException { JSONObject jsonObject = new JSONObject(); JSONArray jsa = null; String name = entity.getName(); if (name.startsWith(JAVA_UTIL_HASH_MAP) || name.startsWith(JAVA_UTIL_SET) || name.startsWith(JAVA_UTIL_LIST)) { jsa = new JSONArray(); final int beginIndex = name.indexOf("<") + 1; final int finishIndex = name.indexOf(">"); name = name.substring(beginIndex, finishIndex); } final AbstractEntity extractEntity = extractEntity(name); if (null != extractEntity) { if (!depthObj.containsKey(name)) { depthObj.put(name, 0); } final Integer nbObj = depthObj.get(name) + 1; if (nbObj > MAX_DEPTH) { return new JSONObject(); } depthObj.put(name, nbObj); // SuperClass final Entity myEntity = (Entity) extractEntity; final String superClass = myEntity.getSuperClass(); if (null != superClass) { final AbstractEntity superClassEntity = extractEntity(superClass); if (null != superClassEntity) { jsonObject = enrichWithFields(jsonObject, (Entity) superClassEntity, depthObj); } } // Class jsonObject = enrichWithFields(jsonObject, myEntity, depthObj); } else { // Maybe a JDK type, trying to instanciate Class aClass = null; try { aClass = Class.forName(name); } catch (ClassNotFoundException e) { if ("boolean".equals(name)) { aClass = boolean.class; } else if ("byte".equals(name)) { aClass = byte.class; } else if ("short".equals(name)) { aClass = short.class; } else if ("int".equals(name)) { aClass = int.class; } else if ("long".equals(name)) { aClass = long.class; } else if ("long".equals(name)) { aClass = float.class; } else if ("double".equals(name)) { aClass = double.class; } } try { return aClass.newInstance(); } catch (Exception e) { return defaultValue(aClass); } } if (null != jsa) { jsa.put(jsonObject); return jsa; } return jsonObject; } private AbstractEntity extractEntity(String entityName) { for (AbstractEntity entity : entities) { if (entityName.equals(entity.getName())) { return entity; } } return null; } private JSONObject enrichWithFields(JSONObject parent, Entity entity, HashMap<String, Integer> depthObj) throws JSONException { final Map<String, AbstractEntity> fields = entity.getFields(); if (fields != null && fields.keySet() != null) { final Iterator<String> iterator = fields.keySet().iterator(); while (iterator.hasNext()) { final String key = iterator.next(); final AbstractEntity abstractEntity = fields.get(key); if (null != abstractEntity) { if (abstractEntity instanceof Entity) { if (depthObj.containsKey(abstractEntity.getName()) && depthObj.get(abstractEntity.getName()) > MAX_DEPTH) { parent.put(key, new JSONObject()); } else { parent.put(key, getJSONFromEntity((Entity) abstractEntity, depthObj)); } } else { final AbstractEntity enumExtracted = extractEntity(abstractEntity.getName()); if (null != enumExtracted) { final List<String> values = ((Enumeration) enumExtracted).getValues(); if (values != null && !values.isEmpty()) { parent.put(key, values.get(0)); } } else { parent.put(key, "{" + abstractEntity.getName() + "}"); } // } } } } } return parent; } private CharSequence decorateURL(String context) { String url = context.replaceAll("\\{", "<span class=\"ink-label success invert\">{") .replaceAll("}", "}</span>") .replaceAll("&", "</span>&<span class=\"ink-label info invert\">") .replaceAll("\\?", "?<span class=\"ink-label info invert\">"); if (url.indexOf("?") > -1) { url = url + "</span>"; } return url; } private CharSequence extractNameFromFQN(String name) { final String[] split = name.split("<"); boolean first = true; StringBuilder sb = new StringBuilder(); for (String part : split) { sb.append(part.substring(part.lastIndexOf(DOT) + 1)); if (first && split.length > 1) { sb.append("<"); } first = false; } return sb.toString(); } }
#2 : Sort fields on entities
src/main/java/fr/masterdocs/plugin/MasterDocGenerator.java
#2 : Sort fields on entities
Java
bsd-3-clause
21ad37528e537a8e0f640b769c6a1804c2c7a272
0
ShiftMediaProject/libilbc,ShiftMediaProject/libilbc,TimothyGu/libilbc,TimothyGu/libilbc,TimothyGu/libilbc,ShiftMediaProject/libilbc,ShiftMediaProject/libilbc,ShiftMediaProject/libilbc,TimothyGu/libilbc,TimothyGu/libilbc
/* * libjingle * Copyright 2014 Google Inc. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.webrtc; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import java.util.ArrayList; import java.util.concurrent.CountDownLatch; import java.util.concurrent.LinkedBlockingQueue; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.opengles.GL10; import android.graphics.SurfaceTexture; import android.opengl.EGL14; import android.opengl.EGLContext; import android.opengl.GLES11Ext; import android.opengl.GLES20; import android.opengl.GLSurfaceView; import android.util.Log; import org.webrtc.VideoRenderer.I420Frame; /** * Efficiently renders YUV frames using the GPU for CSC. * Clients will want first to call setView() to pass GLSurfaceView * and then for each video stream either create instance of VideoRenderer using * createGui() call or VideoRenderer.Callbacks interface using create() call. * Only one instance of the class can be created. */ public class VideoRendererGui implements GLSurfaceView.Renderer { private static VideoRendererGui instance = null; private static Runnable eglContextReady = null; private static final String TAG = "VideoRendererGui"; private GLSurfaceView surface; private static EGLContext eglContext = null; // Indicates if SurfaceView.Renderer.onSurfaceCreated was called. // If true then for every newly created yuv image renderer createTexture() // should be called. The variable is accessed on multiple threads and // all accesses are synchronized on yuvImageRenderers' object lock. private boolean onSurfaceCreatedCalled; private int screenWidth; private int screenHeight; // List of yuv renderers. private ArrayList<YuvImageRenderer> yuvImageRenderers; private int yuvProgram; private int oesProgram; // Types of video scaling: // SCALE_ASPECT_FIT - video frame is scaled to fit the size of the view by // maintaining the aspect ratio (black borders may be displayed). // SCALE_ASPECT_FILL - video frame is scaled to fill the size of the view by // maintaining the aspect ratio. Some portion of the video frame may be // clipped. // SCALE_FILL - video frame is scaled to to fill the size of the view. Video // aspect ratio is changed if necessary. public static enum ScalingType { SCALE_ASPECT_FIT, SCALE_ASPECT_FILL, SCALE_FILL }; private static final int EGL14_SDK_VERSION = android.os.Build.VERSION_CODES.JELLY_BEAN_MR1; // Current SDK version. private static final int CURRENT_SDK_VERSION = android.os.Build.VERSION.SDK_INT; private final String VERTEX_SHADER_STRING = "varying vec2 interp_tc;\n" + "attribute vec4 in_pos;\n" + "attribute vec2 in_tc;\n" + "\n" + "void main() {\n" + " gl_Position = in_pos;\n" + " interp_tc = in_tc;\n" + "}\n"; private final String YUV_FRAGMENT_SHADER_STRING = "precision mediump float;\n" + "varying vec2 interp_tc;\n" + "\n" + "uniform sampler2D y_tex;\n" + "uniform sampler2D u_tex;\n" + "uniform sampler2D v_tex;\n" + "\n" + "void main() {\n" + // CSC according to http://www.fourcc.org/fccyvrgb.php " float y = texture2D(y_tex, interp_tc).r;\n" + " float u = texture2D(u_tex, interp_tc).r - 0.5;\n" + " float v = texture2D(v_tex, interp_tc).r - 0.5;\n" + " gl_FragColor = vec4(y + 1.403 * v, " + " y - 0.344 * u - 0.714 * v, " + " y + 1.77 * u, 1);\n" + "}\n"; private static final String OES_FRAGMENT_SHADER_STRING = "#extension GL_OES_EGL_image_external : require\n" + "precision mediump float;\n" + "varying vec2 interp_tc;\n" + "\n" + "uniform samplerExternalOES oes_tex;\n" + "\n" + "void main() {\n" + " gl_FragColor = texture2D(oes_tex, interp_tc);\n" + "}\n"; private VideoRendererGui(GLSurfaceView surface) { this.surface = surface; // Create an OpenGL ES 2.0 context. surface.setPreserveEGLContextOnPause(true); surface.setEGLContextClientVersion(2); surface.setRenderer(this); surface.setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY); yuvImageRenderers = new ArrayList<YuvImageRenderer>(); } // Poor-man's assert(): die with |msg| unless |condition| is true. private static void abortUnless(boolean condition, String msg) { if (!condition) { throw new RuntimeException(msg); } } // Assert that no OpenGL ES 2.0 error has been raised. private static void checkNoGLES2Error() { int error = GLES20.glGetError(); abortUnless(error == GLES20.GL_NO_ERROR, "GLES20 error: " + error); } // Wrap a float[] in a direct FloatBuffer using native byte order. private static FloatBuffer directNativeFloatBuffer(float[] array) { FloatBuffer buffer = ByteBuffer.allocateDirect(array.length * 4).order( ByteOrder.nativeOrder()).asFloatBuffer(); buffer.put(array); buffer.flip(); return buffer; } private int loadShader(int shaderType, String source) { int[] result = new int[] { GLES20.GL_FALSE }; int shader = GLES20.glCreateShader(shaderType); GLES20.glShaderSource(shader, source); GLES20.glCompileShader(shader); GLES20.glGetShaderiv(shader, GLES20.GL_COMPILE_STATUS, result, 0); if (result[0] != GLES20.GL_TRUE) { Log.e(TAG, "Could not compile shader " + shaderType + ":" + GLES20.glGetShaderInfoLog(shader)); throw new RuntimeException(GLES20.glGetShaderInfoLog(shader)); } checkNoGLES2Error(); return shader; } private int createProgram(String vertexSource, String fragmentSource) { int vertexShader = loadShader(GLES20.GL_VERTEX_SHADER, vertexSource); int fragmentShader = loadShader(GLES20.GL_FRAGMENT_SHADER, fragmentSource); int program = GLES20.glCreateProgram(); if (program == 0) { throw new RuntimeException("Could not create program"); } GLES20.glAttachShader(program, vertexShader); GLES20.glAttachShader(program, fragmentShader); GLES20.glLinkProgram(program); int[] linkStatus = new int[] { GLES20.GL_FALSE }; GLES20.glGetProgramiv(program, GLES20.GL_LINK_STATUS, linkStatus, 0); if (linkStatus[0] != GLES20.GL_TRUE) { Log.e(TAG, "Could not link program: " + GLES20.glGetProgramInfoLog(program)); throw new RuntimeException(GLES20.glGetProgramInfoLog(program)); } checkNoGLES2Error(); return program; } /** * Class used to display stream of YUV420 frames at particular location * on a screen. New video frames are sent to display using renderFrame() * call. */ private static class YuvImageRenderer implements VideoRenderer.Callbacks { private GLSurfaceView surface; private int id; private int yuvProgram; private int oesProgram; private int[] yuvTextures = { -1, -1, -1 }; private int oesTexture = -1; private float[] stMatrix = new float[16]; // Render frame queue - accessed by two threads. renderFrame() call does // an offer (writing I420Frame to render) and early-returns (recording // a dropped frame) if that queue is full. draw() call does a peek(), // copies frame to texture and then removes it from a queue using poll(). LinkedBlockingQueue<I420Frame> frameToRenderQueue; // Local copy of incoming video frame. private I420Frame yuvFrameToRender; private I420Frame textureFrameToRender; // Type of video frame used for recent frame rendering. private static enum RendererType { RENDERER_YUV, RENDERER_TEXTURE }; private RendererType rendererType; private ScalingType scalingType; private boolean mirror; // Flag if renderFrame() was ever called. boolean seenFrame; // Total number of video frames received in renderFrame() call. private int framesReceived; // Number of video frames dropped by renderFrame() because previous // frame has not been rendered yet. private int framesDropped; // Number of rendered video frames. private int framesRendered; // Time in ns when the first video frame was rendered. private long startTimeNs = -1; // Time in ns spent in draw() function. private long drawTimeNs; // Time in ns spent in renderFrame() function - including copying frame // data to rendering planes. private long copyTimeNs; // Texture vertices. private float texLeft; private float texRight; private float texTop; private float texBottom; private FloatBuffer textureVertices; // Texture UV coordinates. private FloatBuffer textureCoords; // Flag if texture vertices or coordinates update is needed. private boolean updateTextureProperties; // Texture properties update lock. private final Object updateTextureLock = new Object(); // Viewport dimensions. private int screenWidth; private int screenHeight; // Video dimension. private int videoWidth; private int videoHeight; private YuvImageRenderer( GLSurfaceView surface, int id, int x, int y, int width, int height, ScalingType scalingType, boolean mirror) { Log.d(TAG, "YuvImageRenderer.Create id: " + id); this.surface = surface; this.id = id; this.scalingType = scalingType; this.mirror = mirror; frameToRenderQueue = new LinkedBlockingQueue<I420Frame>(1); // Create texture vertices. texLeft = (x - 50) / 50.0f; texTop = (50 - y) / 50.0f; texRight = Math.min(1.0f, (x + width - 50) / 50.0f); texBottom = Math.max(-1.0f, (50 - y - height) / 50.0f); float textureVeticesFloat[] = new float[] { texLeft, texTop, texLeft, texBottom, texRight, texTop, texRight, texBottom }; textureVertices = directNativeFloatBuffer(textureVeticesFloat); // Create texture UV coordinates. float textureCoordinatesFloat[] = new float[] { 0, 0, 0, 1, 1, 0, 1, 1 }; textureCoords = directNativeFloatBuffer(textureCoordinatesFloat); updateTextureProperties = false; } private void createTextures(int yuvProgram, int oesProgram) { Log.d(TAG, " YuvImageRenderer.createTextures " + id + " on GL thread:" + Thread.currentThread().getId()); this.yuvProgram = yuvProgram; this.oesProgram = oesProgram; // Generate 3 texture ids for Y/U/V and place them into |yuvTextures|. GLES20.glGenTextures(3, yuvTextures, 0); for (int i = 0; i < 3; i++) { GLES20.glActiveTexture(GLES20.GL_TEXTURE0 + i); GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, yuvTextures[i]); GLES20.glTexImage2D(GLES20.GL_TEXTURE_2D, 0, GLES20.GL_LUMINANCE, 128, 128, 0, GLES20.GL_LUMINANCE, GLES20.GL_UNSIGNED_BYTE, null); GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR); GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR); GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE); GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE); } checkNoGLES2Error(); } private void checkAdjustTextureCoords() { if (!updateTextureProperties || scalingType == ScalingType.SCALE_FILL) { return; } synchronized(updateTextureLock) { // Re - calculate texture vertices to preserve video aspect ratio. float texRight = this.texRight; float texLeft = this.texLeft; float texTop = this.texTop; float texBottom = this.texBottom; float texOffsetU = 0; float texOffsetV = 0; float displayWidth = (texRight - texLeft) * screenWidth / 2; float displayHeight = (texTop - texBottom) * screenHeight / 2; Log.d(TAG, "ID: " + id + ". Display: " + displayWidth + " x " + displayHeight + ". Video: " + videoWidth + " x " + videoHeight); if (displayWidth > 1 && displayHeight > 1 && videoWidth > 1 && videoHeight > 1) { float displayAspectRatio = displayWidth / displayHeight; float videoAspectRatio = (float)videoWidth / videoHeight; if (scalingType == ScalingType.SCALE_ASPECT_FIT) { // Need to re-adjust vertices width or height to match video AR. if (displayAspectRatio > videoAspectRatio) { float deltaX = (displayWidth - videoAspectRatio * displayHeight) / instance.screenWidth; texRight -= deltaX; texLeft += deltaX; } else { float deltaY = (displayHeight - displayWidth / videoAspectRatio) / instance.screenHeight; texTop -= deltaY; texBottom += deltaY; } } if (scalingType == ScalingType.SCALE_ASPECT_FILL) { // Need to re-adjust UV coordinates to match display AR. if (displayAspectRatio > videoAspectRatio) { texOffsetV = (1.0f - videoAspectRatio / displayAspectRatio) / 2.0f; } else { texOffsetU = (1.0f - displayAspectRatio / videoAspectRatio) / 2.0f; } } Log.d(TAG, " Texture vertices: (" + texLeft + "," + texBottom + ") - (" + texRight + "," + texTop + ")"); float textureVeticesFloat[] = new float[] { texLeft, texTop, texLeft, texBottom, texRight, texTop, texRight, texBottom }; textureVertices = directNativeFloatBuffer(textureVeticesFloat); Log.d(TAG, " Texture UV offsets: " + texOffsetU + ", " + texOffsetV); float uLeft = texOffsetU; float uRight = 1.0f - texOffsetU; if (mirror) { // Swap U coordinates for mirror image. uLeft = 1.0f - texOffsetU; uRight = texOffsetU; } float textureCoordinatesFloat[] = new float[] { uLeft, texOffsetV, // left top uLeft, 1.0f - texOffsetV, // left bottom uRight, texOffsetV, // right top uRight, 1.0f - texOffsetV // right bottom }; textureCoords = directNativeFloatBuffer(textureCoordinatesFloat); } updateTextureProperties = false; } } private void draw() { if (!seenFrame) { // No frame received yet - nothing to render. return; } // Check if texture vertices/coordinates adjustment is required when // screen orientation changes or video frame size changes. checkAdjustTextureCoords(); long now = System.nanoTime(); int currentProgram = 0; I420Frame frameFromQueue; synchronized (frameToRenderQueue) { frameFromQueue = frameToRenderQueue.peek(); if (frameFromQueue != null && startTimeNs == -1) { startTimeNs = now; } if (rendererType == RendererType.RENDERER_YUV) { // YUV textures rendering. GLES20.glUseProgram(yuvProgram); currentProgram = yuvProgram; for (int i = 0; i < 3; ++i) { GLES20.glActiveTexture(GLES20.GL_TEXTURE0 + i); GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, yuvTextures[i]); if (frameFromQueue != null) { int w = (i == 0) ? frameFromQueue.width : frameFromQueue.width / 2; int h = (i == 0) ? frameFromQueue.height : frameFromQueue.height / 2; GLES20.glTexImage2D(GLES20.GL_TEXTURE_2D, 0, GLES20.GL_LUMINANCE, w, h, 0, GLES20.GL_LUMINANCE, GLES20.GL_UNSIGNED_BYTE, frameFromQueue.yuvPlanes[i]); } } GLES20.glUniform1i( GLES20.glGetUniformLocation(yuvProgram, "y_tex"), 0); GLES20.glUniform1i( GLES20.glGetUniformLocation(yuvProgram, "u_tex"), 1); GLES20.glUniform1i( GLES20.glGetUniformLocation(yuvProgram, "v_tex"), 2); } else { // External texture rendering. GLES20.glUseProgram(oesProgram); currentProgram = oesProgram; if (frameFromQueue != null) { oesTexture = frameFromQueue.textureId; if (frameFromQueue.textureObject instanceof SurfaceTexture) { SurfaceTexture surfaceTexture = (SurfaceTexture) frameFromQueue.textureObject; surfaceTexture.updateTexImage(); surfaceTexture.getTransformMatrix(stMatrix); } } GLES20.glActiveTexture(GLES20.GL_TEXTURE0); GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, oesTexture); } if (frameFromQueue != null) { frameToRenderQueue.poll(); } } int posLocation = GLES20.glGetAttribLocation(currentProgram, "in_pos"); if (posLocation == -1) { throw new RuntimeException("Could not get attrib location for in_pos"); } GLES20.glEnableVertexAttribArray(posLocation); GLES20.glVertexAttribPointer( posLocation, 2, GLES20.GL_FLOAT, false, 0, textureVertices); int texLocation = GLES20.glGetAttribLocation(currentProgram, "in_tc"); if (texLocation == -1) { throw new RuntimeException("Could not get attrib location for in_tc"); } GLES20.glEnableVertexAttribArray(texLocation); GLES20.glVertexAttribPointer( texLocation, 2, GLES20.GL_FLOAT, false, 0, textureCoords); GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4); GLES20.glDisableVertexAttribArray(posLocation); GLES20.glDisableVertexAttribArray(texLocation); checkNoGLES2Error(); if (frameFromQueue != null) { framesRendered++; drawTimeNs += (System.nanoTime() - now); if ((framesRendered % 150) == 0) { logStatistics(); } } } private void logStatistics() { long timeSinceFirstFrameNs = System.nanoTime() - startTimeNs; Log.d(TAG, "ID: " + id + ". Type: " + rendererType + ". Frames received: " + framesReceived + ". Dropped: " + framesDropped + ". Rendered: " + framesRendered); if (framesReceived > 0 && framesRendered > 0) { Log.d(TAG, "Duration: " + (int)(timeSinceFirstFrameNs / 1e6) + " ms. FPS: " + (float)framesRendered * 1e9 / timeSinceFirstFrameNs); Log.d(TAG, "Draw time: " + (int) (drawTimeNs / (1000 * framesRendered)) + " us. Copy time: " + (int) (copyTimeNs / (1000 * framesReceived)) + " us"); } } public void setScreenSize(final int screenWidth, final int screenHeight) { synchronized(updateTextureLock) { this.screenWidth = screenWidth; this.screenHeight = screenHeight; updateTextureProperties = true; } } public void setPosition(int x, int y, int width, int height, ScalingType scalingType) { synchronized(updateTextureLock) { texLeft = (x - 50) / 50.0f; texTop = (50 - y) / 50.0f; texRight = Math.min(1.0f, (x + width - 50) / 50.0f); texBottom = Math.max(-1.0f, (50 - y - height) / 50.0f); this.scalingType = scalingType; updateTextureProperties = true; } } @Override public void setSize(final int width, final int height) { Log.d(TAG, "ID: " + id + ". YuvImageRenderer.setSize: " + width + " x " + height); videoWidth = width; videoHeight = height; int[] strides = { width, width / 2, width / 2 }; // Frame re-allocation need to be synchronized with copying // frame to textures in draw() function to avoid re-allocating // the frame while it is being copied. synchronized (frameToRenderQueue) { // Clear rendering queue. frameToRenderQueue.poll(); // Re-allocate / allocate the frame. yuvFrameToRender = new I420Frame(width, height, strides, null); textureFrameToRender = new I420Frame(width, height, null, -1); updateTextureProperties = true; } } @Override public synchronized void renderFrame(I420Frame frame) { long now = System.nanoTime(); framesReceived++; // Skip rendering of this frame if setSize() was not called. if (yuvFrameToRender == null || textureFrameToRender == null) { framesDropped++; return; } // Check input frame parameters. if (frame.yuvFrame) { if (frame.yuvStrides[0] < frame.width || frame.yuvStrides[1] < frame.width / 2 || frame.yuvStrides[2] < frame.width / 2) { Log.e(TAG, "Incorrect strides " + frame.yuvStrides[0] + ", " + frame.yuvStrides[1] + ", " + frame.yuvStrides[2]); return; } // Check incoming frame dimensions. if (frame.width != yuvFrameToRender.width || frame.height != yuvFrameToRender.height) { throw new RuntimeException("Wrong frame size " + frame.width + " x " + frame.height); } } if (frameToRenderQueue.size() > 0) { // Skip rendering of this frame if previous frame was not rendered yet. framesDropped++; return; } // Create a local copy of the frame. if (frame.yuvFrame) { yuvFrameToRender.copyFrom(frame); rendererType = RendererType.RENDERER_YUV; frameToRenderQueue.offer(yuvFrameToRender); } else { textureFrameToRender.copyFrom(frame); rendererType = RendererType.RENDERER_TEXTURE; frameToRenderQueue.offer(textureFrameToRender); } copyTimeNs += (System.nanoTime() - now); seenFrame = true; // Request rendering. surface.requestRender(); } } /** Passes GLSurfaceView to video renderer. */ public static void setView(GLSurfaceView surface, Runnable eglContextReadyCallback) { Log.d(TAG, "VideoRendererGui.setView"); instance = new VideoRendererGui(surface); eglContextReady = eglContextReadyCallback; } public static EGLContext getEGLContext() { return eglContext; } /** * Creates VideoRenderer with top left corner at (x, y) and resolution * (width, height). All parameters are in percentage of screen resolution. */ public static VideoRenderer createGui(int x, int y, int width, int height, ScalingType scalingType, boolean mirror) throws Exception { YuvImageRenderer javaGuiRenderer = create( x, y, width, height, scalingType, mirror); return new VideoRenderer(javaGuiRenderer); } public static VideoRenderer.Callbacks createGuiRenderer( int x, int y, int width, int height, ScalingType scalingType, boolean mirror) { return create(x, y, width, height, scalingType, mirror); } /** * Creates VideoRenderer.Callbacks with top left corner at (x, y) and * resolution (width, height). All parameters are in percentage of * screen resolution. */ public static YuvImageRenderer create(int x, int y, int width, int height, ScalingType scalingType, boolean mirror) { // Check display region parameters. if (x < 0 || x > 100 || y < 0 || y > 100 || width < 0 || width > 100 || height < 0 || height > 100 || x + width > 100 || y + height > 100) { throw new RuntimeException("Incorrect window parameters."); } if (instance == null) { throw new RuntimeException( "Attempt to create yuv renderer before setting GLSurfaceView"); } final YuvImageRenderer yuvImageRenderer = new YuvImageRenderer( instance.surface, instance.yuvImageRenderers.size(), x, y, width, height, scalingType, mirror); synchronized (instance.yuvImageRenderers) { if (instance.onSurfaceCreatedCalled) { // onSurfaceCreated has already been called for VideoRendererGui - // need to create texture for new image and add image to the // rendering list. final CountDownLatch countDownLatch = new CountDownLatch(1); instance.surface.queueEvent(new Runnable() { public void run() { yuvImageRenderer.createTextures( instance.yuvProgram, instance.oesProgram); yuvImageRenderer.setScreenSize( instance.screenWidth, instance.screenHeight); countDownLatch.countDown(); } }); // Wait for task completion. try { countDownLatch.await(); } catch (InterruptedException e) { throw new RuntimeException(e); } } // Add yuv renderer to rendering list. instance.yuvImageRenderers.add(yuvImageRenderer); } return yuvImageRenderer; } public static void update( VideoRenderer.Callbacks renderer, int x, int y, int width, int height, ScalingType scalingType) { Log.d(TAG, "VideoRendererGui.update"); if (instance == null) { throw new RuntimeException( "Attempt to update yuv renderer before setting GLSurfaceView"); } synchronized (instance.yuvImageRenderers) { for (YuvImageRenderer yuvImageRenderer : instance.yuvImageRenderers) { if (yuvImageRenderer == renderer) { yuvImageRenderer.setPosition(x, y, width, height, scalingType); } } } } public static void remove(VideoRenderer.Callbacks renderer) { Log.d(TAG, "VideoRendererGui.remove"); if (instance == null) { throw new RuntimeException( "Attempt to remove yuv renderer before setting GLSurfaceView"); } synchronized (instance.yuvImageRenderers) { if (!instance.yuvImageRenderers.remove(renderer)) { Log.w(TAG, "Couldn't remove renderer (not present in current list)"); } } } @Override public void onSurfaceCreated(GL10 unused, EGLConfig config) { Log.d(TAG, "VideoRendererGui.onSurfaceCreated"); // Store render EGL context. if (CURRENT_SDK_VERSION >= EGL14_SDK_VERSION) { eglContext = EGL14.eglGetCurrentContext(); Log.d(TAG, "VideoRendererGui EGL Context: " + eglContext); } // Create YUV and OES programs. yuvProgram = createProgram(VERTEX_SHADER_STRING, YUV_FRAGMENT_SHADER_STRING); oesProgram = createProgram(VERTEX_SHADER_STRING, OES_FRAGMENT_SHADER_STRING); synchronized (yuvImageRenderers) { // Create textures for all images. for (YuvImageRenderer yuvImageRenderer : yuvImageRenderers) { yuvImageRenderer.createTextures(yuvProgram, oesProgram); } onSurfaceCreatedCalled = true; } checkNoGLES2Error(); GLES20.glClearColor(0.15f, 0.15f, 0.15f, 1.0f); // Fire EGL context ready event. if (eglContextReady != null) { eglContextReady.run(); } } @Override public void onSurfaceChanged(GL10 unused, int width, int height) { Log.d(TAG, "VideoRendererGui.onSurfaceChanged: " + width + " x " + height + " "); screenWidth = width; screenHeight = height; GLES20.glViewport(0, 0, width, height); synchronized (yuvImageRenderers) { for (YuvImageRenderer yuvImageRenderer : yuvImageRenderers) { yuvImageRenderer.setScreenSize(screenWidth, screenHeight); } } } @Override public void onDrawFrame(GL10 unused) { GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT); synchronized (yuvImageRenderers) { for (YuvImageRenderer yuvImageRenderer : yuvImageRenderers) { yuvImageRenderer.draw(); } } } }
talk/app/webrtc/java/android/org/webrtc/VideoRendererGui.java
/* * libjingle * Copyright 2014 Google Inc. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.webrtc; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import java.util.ArrayList; import java.util.concurrent.CountDownLatch; import java.util.concurrent.LinkedBlockingQueue; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.opengles.GL10; import android.graphics.SurfaceTexture; import android.opengl.EGL14; import android.opengl.EGLContext; import android.opengl.GLES11Ext; import android.opengl.GLES20; import android.opengl.GLSurfaceView; import android.util.Log; import org.webrtc.VideoRenderer.I420Frame; /** * Efficiently renders YUV frames using the GPU for CSC. * Clients will want first to call setView() to pass GLSurfaceView * and then for each video stream either create instance of VideoRenderer using * createGui() call or VideoRenderer.Callbacks interface using create() call. * Only one instance of the class can be created. */ public class VideoRendererGui implements GLSurfaceView.Renderer { private static VideoRendererGui instance = null; private static Runnable eglContextReady = null; private static final String TAG = "VideoRendererGui"; private GLSurfaceView surface; private static EGLContext eglContext = null; // Indicates if SurfaceView.Renderer.onSurfaceCreated was called. // If true then for every newly created yuv image renderer createTexture() // should be called. The variable is accessed on multiple threads and // all accesses are synchronized on yuvImageRenderers' object lock. private boolean onSurfaceCreatedCalled; private int screenWidth; private int screenHeight; // List of yuv renderers. private ArrayList<YuvImageRenderer> yuvImageRenderers; private int yuvProgram; private int oesProgram; // Types of video scaling: // SCALE_ASPECT_FIT - video frame is scaled to fit the size of the view by // maintaining the aspect ratio (black borders may be displayed). // SCALE_ASPECT_FILL - video frame is scaled to fill the size of the view by // maintaining the aspect ratio. Some portion of the video frame may be // clipped. // SCALE_FILL - video frame is scaled to to fill the size of the view. Video // aspect ratio is changed if necessary. public static enum ScalingType { SCALE_ASPECT_FIT, SCALE_ASPECT_FILL, SCALE_FILL }; private static final int EGL14_SDK_VERSION = android.os.Build.VERSION_CODES.JELLY_BEAN_MR1; // Current SDK version. private static final int CURRENT_SDK_VERSION = android.os.Build.VERSION.SDK_INT; private final String VERTEX_SHADER_STRING = "varying vec2 interp_tc;\n" + "attribute vec4 in_pos;\n" + "attribute vec2 in_tc;\n" + "\n" + "void main() {\n" + " gl_Position = in_pos;\n" + " interp_tc = in_tc;\n" + "}\n"; private final String YUV_FRAGMENT_SHADER_STRING = "precision mediump float;\n" + "varying vec2 interp_tc;\n" + "\n" + "uniform sampler2D y_tex;\n" + "uniform sampler2D u_tex;\n" + "uniform sampler2D v_tex;\n" + "\n" + "void main() {\n" + // CSC according to http://www.fourcc.org/fccyvrgb.php " float y = texture2D(y_tex, interp_tc).r;\n" + " float u = texture2D(u_tex, interp_tc).r - 0.5;\n" + " float v = texture2D(v_tex, interp_tc).r - 0.5;\n" + " gl_FragColor = vec4(y + 1.403 * v, " + " y - 0.344 * u - 0.714 * v, " + " y + 1.77 * u, 1);\n" + "}\n"; private static final String OES_FRAGMENT_SHADER_STRING = "#extension GL_OES_EGL_image_external : require\n" + "precision mediump float;\n" + "varying vec2 interp_tc;\n" + "\n" + "uniform samplerExternalOES oes_tex;\n" + "\n" + "void main() {\n" + " gl_FragColor = texture2D(oes_tex, interp_tc);\n" + "}\n"; private VideoRendererGui(GLSurfaceView surface) { this.surface = surface; // Create an OpenGL ES 2.0 context. surface.setPreserveEGLContextOnPause(true); surface.setEGLContextClientVersion(2); surface.setRenderer(this); surface.setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY); yuvImageRenderers = new ArrayList<YuvImageRenderer>(); } // Poor-man's assert(): die with |msg| unless |condition| is true. private static void abortUnless(boolean condition, String msg) { if (!condition) { throw new RuntimeException(msg); } } // Assert that no OpenGL ES 2.0 error has been raised. private static void checkNoGLES2Error() { int error = GLES20.glGetError(); abortUnless(error == GLES20.GL_NO_ERROR, "GLES20 error: " + error); } // Wrap a float[] in a direct FloatBuffer using native byte order. private static FloatBuffer directNativeFloatBuffer(float[] array) { FloatBuffer buffer = ByteBuffer.allocateDirect(array.length * 4).order( ByteOrder.nativeOrder()).asFloatBuffer(); buffer.put(array); buffer.flip(); return buffer; } private int loadShader(int shaderType, String source) { int[] result = new int[] { GLES20.GL_FALSE }; int shader = GLES20.glCreateShader(shaderType); GLES20.glShaderSource(shader, source); GLES20.glCompileShader(shader); GLES20.glGetShaderiv(shader, GLES20.GL_COMPILE_STATUS, result, 0); if (result[0] != GLES20.GL_TRUE) { Log.e(TAG, "Could not compile shader " + shaderType + ":" + GLES20.glGetShaderInfoLog(shader)); throw new RuntimeException(GLES20.glGetShaderInfoLog(shader)); } checkNoGLES2Error(); return shader; } private int createProgram(String vertexSource, String fragmentSource) { int vertexShader = loadShader(GLES20.GL_VERTEX_SHADER, vertexSource); int fragmentShader = loadShader(GLES20.GL_FRAGMENT_SHADER, fragmentSource); int program = GLES20.glCreateProgram(); if (program == 0) { throw new RuntimeException("Could not create program"); } GLES20.glAttachShader(program, vertexShader); GLES20.glAttachShader(program, fragmentShader); GLES20.glLinkProgram(program); int[] linkStatus = new int[] { GLES20.GL_FALSE }; GLES20.glGetProgramiv(program, GLES20.GL_LINK_STATUS, linkStatus, 0); if (linkStatus[0] != GLES20.GL_TRUE) { Log.e(TAG, "Could not link program: " + GLES20.glGetProgramInfoLog(program)); throw new RuntimeException(GLES20.glGetProgramInfoLog(program)); } checkNoGLES2Error(); return program; } /** * Class used to display stream of YUV420 frames at particular location * on a screen. New video frames are sent to display using renderFrame() * call. */ private static class YuvImageRenderer implements VideoRenderer.Callbacks { private GLSurfaceView surface; private int id; private int yuvProgram; private int oesProgram; private int[] yuvTextures = { -1, -1, -1 }; private int oesTexture = -1; private float[] stMatrix = new float[16]; // Render frame queue - accessed by two threads. renderFrame() call does // an offer (writing I420Frame to render) and early-returns (recording // a dropped frame) if that queue is full. draw() call does a peek(), // copies frame to texture and then removes it from a queue using poll(). LinkedBlockingQueue<I420Frame> frameToRenderQueue; // Local copy of incoming video frame. private I420Frame yuvFrameToRender; private I420Frame textureFrameToRender; // Type of video frame used for recent frame rendering. private static enum RendererType { RENDERER_YUV, RENDERER_TEXTURE }; private RendererType rendererType; private ScalingType scalingType; private boolean mirror; // Flag if renderFrame() was ever called. boolean seenFrame; // Total number of video frames received in renderFrame() call. private int framesReceived; // Number of video frames dropped by renderFrame() because previous // frame has not been rendered yet. private int framesDropped; // Number of rendered video frames. private int framesRendered; // Time in ns when the first video frame was rendered. private long startTimeNs = -1; // Time in ns spent in draw() function. private long drawTimeNs; // Time in ns spent in renderFrame() function - including copying frame // data to rendering planes. private long copyTimeNs; // Texture vertices. private float texLeft; private float texRight; private float texTop; private float texBottom; private FloatBuffer textureVertices; // Texture UV coordinates. private FloatBuffer textureCoords; // Flag if texture vertices or coordinates update is needed. private boolean updateTextureProperties; // Texture properties update lock. private final Object updateTextureLock = new Object(); // Viewport dimensions. private int screenWidth; private int screenHeight; // Video dimension. private int videoWidth; private int videoHeight; private YuvImageRenderer( GLSurfaceView surface, int id, int x, int y, int width, int height, ScalingType scalingType, boolean mirror) { Log.d(TAG, "YuvImageRenderer.Create id: " + id); this.surface = surface; this.id = id; this.scalingType = scalingType; this.mirror = mirror; frameToRenderQueue = new LinkedBlockingQueue<I420Frame>(1); // Create texture vertices. texLeft = (x - 50) / 50.0f; texTop = (50 - y) / 50.0f; texRight = Math.min(1.0f, (x + width - 50) / 50.0f); texBottom = Math.max(-1.0f, (50 - y - height) / 50.0f); float textureVeticesFloat[] = new float[] { texLeft, texTop, texLeft, texBottom, texRight, texTop, texRight, texBottom }; textureVertices = directNativeFloatBuffer(textureVeticesFloat); // Create texture UV coordinates. float textureCoordinatesFloat[] = new float[] { 0, 0, 0, 1, 1, 0, 1, 1 }; textureCoords = directNativeFloatBuffer(textureCoordinatesFloat); updateTextureProperties = false; } private void createTextures(int yuvProgram, int oesProgram) { Log.d(TAG, " YuvImageRenderer.createTextures " + id + " on GL thread:" + Thread.currentThread().getId()); this.yuvProgram = yuvProgram; this.oesProgram = oesProgram; // Generate 3 texture ids for Y/U/V and place them into |yuvTextures|. GLES20.glGenTextures(3, yuvTextures, 0); for (int i = 0; i < 3; i++) { GLES20.glActiveTexture(GLES20.GL_TEXTURE0 + i); GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, yuvTextures[i]); GLES20.glTexImage2D(GLES20.GL_TEXTURE_2D, 0, GLES20.GL_LUMINANCE, 128, 128, 0, GLES20.GL_LUMINANCE, GLES20.GL_UNSIGNED_BYTE, null); GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR); GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR); GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE); GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE); } checkNoGLES2Error(); } private void checkAdjustTextureCoords() { if (!updateTextureProperties || scalingType == ScalingType.SCALE_FILL) { return; } synchronized(updateTextureLock) { // Re - calculate texture vertices to preserve video aspect ratio. float texRight = this.texRight; float texLeft = this.texLeft; float texTop = this.texTop; float texBottom = this.texBottom; float texOffsetU = 0; float texOffsetV = 0; float displayWidth = (texRight - texLeft) * screenWidth / 2; float displayHeight = (texTop - texBottom) * screenHeight / 2; Log.d(TAG, "ID: " + id + ". Display: " + displayWidth + " x " + displayHeight + ". Video: " + videoWidth + " x " + videoHeight); if (displayWidth > 1 && displayHeight > 1 && videoWidth > 1 && videoHeight > 1) { float displayAspectRatio = displayWidth / displayHeight; float videoAspectRatio = (float)videoWidth / videoHeight; if (scalingType == ScalingType.SCALE_ASPECT_FIT) { // Need to re-adjust vertices width or height to match video AR. if (displayAspectRatio > videoAspectRatio) { float deltaX = (displayWidth - videoAspectRatio * displayHeight) / instance.screenWidth; texRight -= deltaX; texLeft += deltaX; } else { float deltaY = (displayHeight - displayWidth / videoAspectRatio) / instance.screenHeight; texTop -= deltaY; texBottom += deltaY; } } if (scalingType == ScalingType.SCALE_ASPECT_FILL) { // Need to re-adjust UV coordinates to match display AR. if (displayAspectRatio > videoAspectRatio) { texOffsetV = (1.0f - videoAspectRatio / displayAspectRatio) / 2.0f; } else { texOffsetU = (1.0f - displayAspectRatio / videoAspectRatio) / 2.0f; } } Log.d(TAG, " Texture vertices: (" + texLeft + "," + texBottom + ") - (" + texRight + "," + texTop + ")"); float textureVeticesFloat[] = new float[] { texLeft, texTop, texLeft, texBottom, texRight, texTop, texRight, texBottom }; textureVertices = directNativeFloatBuffer(textureVeticesFloat); Log.d(TAG, " Texture UV offsets: " + texOffsetU + ", " + texOffsetV); float uLeft = texOffsetU; float uRight = 1.0f - texOffsetU; if (mirror) { // Swap U coordinates for mirror image. uLeft = 1.0f - texOffsetU; uRight = texOffsetU; } float textureCoordinatesFloat[] = new float[] { uLeft, texOffsetV, // left top uLeft, 1.0f - texOffsetV, // left bottom uRight, texOffsetV, // right top uRight, 1.0f - texOffsetV // right bottom }; textureCoords = directNativeFloatBuffer(textureCoordinatesFloat); } updateTextureProperties = false; } } private void draw() { if (!seenFrame) { // No frame received yet - nothing to render. return; } // Check if texture vertices/coordinates adjustment is required when // screen orientation changes or video frame size changes. checkAdjustTextureCoords(); long now = System.nanoTime(); I420Frame frameFromQueue; synchronized (frameToRenderQueue) { frameFromQueue = frameToRenderQueue.peek(); if (frameFromQueue != null && startTimeNs == -1) { startTimeNs = now; } if (rendererType == RendererType.RENDERER_YUV) { // YUV textures rendering. GLES20.glUseProgram(yuvProgram); for (int i = 0; i < 3; ++i) { GLES20.glActiveTexture(GLES20.GL_TEXTURE0 + i); GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, yuvTextures[i]); if (frameFromQueue != null) { int w = (i == 0) ? frameFromQueue.width : frameFromQueue.width / 2; int h = (i == 0) ? frameFromQueue.height : frameFromQueue.height / 2; GLES20.glTexImage2D(GLES20.GL_TEXTURE_2D, 0, GLES20.GL_LUMINANCE, w, h, 0, GLES20.GL_LUMINANCE, GLES20.GL_UNSIGNED_BYTE, frameFromQueue.yuvPlanes[i]); } } } else { // External texture rendering. GLES20.glUseProgram(oesProgram); if (frameFromQueue != null) { oesTexture = frameFromQueue.textureId; if (frameFromQueue.textureObject instanceof SurfaceTexture) { SurfaceTexture surfaceTexture = (SurfaceTexture) frameFromQueue.textureObject; surfaceTexture.updateTexImage(); surfaceTexture.getTransformMatrix(stMatrix); } } GLES20.glActiveTexture(GLES20.GL_TEXTURE0); GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, oesTexture); } if (frameFromQueue != null) { frameToRenderQueue.poll(); } } if (rendererType == RendererType.RENDERER_YUV) { GLES20.glUniform1i(GLES20.glGetUniformLocation(yuvProgram, "y_tex"), 0); GLES20.glUniform1i(GLES20.glGetUniformLocation(yuvProgram, "u_tex"), 1); GLES20.glUniform1i(GLES20.glGetUniformLocation(yuvProgram, "v_tex"), 2); } int posLocation = GLES20.glGetAttribLocation(yuvProgram, "in_pos"); if (posLocation == -1) { throw new RuntimeException("Could not get attrib location for in_pos"); } GLES20.glEnableVertexAttribArray(posLocation); GLES20.glVertexAttribPointer( posLocation, 2, GLES20.GL_FLOAT, false, 0, textureVertices); int texLocation = GLES20.glGetAttribLocation(yuvProgram, "in_tc"); if (texLocation == -1) { throw new RuntimeException("Could not get attrib location for in_tc"); } GLES20.glEnableVertexAttribArray(texLocation); GLES20.glVertexAttribPointer( texLocation, 2, GLES20.GL_FLOAT, false, 0, textureCoords); GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4); GLES20.glDisableVertexAttribArray(posLocation); GLES20.glDisableVertexAttribArray(texLocation); checkNoGLES2Error(); if (frameFromQueue != null) { framesRendered++; drawTimeNs += (System.nanoTime() - now); if ((framesRendered % 150) == 0) { logStatistics(); } } } private void logStatistics() { long timeSinceFirstFrameNs = System.nanoTime() - startTimeNs; Log.d(TAG, "ID: " + id + ". Type: " + rendererType + ". Frames received: " + framesReceived + ". Dropped: " + framesDropped + ". Rendered: " + framesRendered); if (framesReceived > 0 && framesRendered > 0) { Log.d(TAG, "Duration: " + (int)(timeSinceFirstFrameNs / 1e6) + " ms. FPS: " + (float)framesRendered * 1e9 / timeSinceFirstFrameNs); Log.d(TAG, "Draw time: " + (int) (drawTimeNs / (1000 * framesRendered)) + " us. Copy time: " + (int) (copyTimeNs / (1000 * framesReceived)) + " us"); } } public void setScreenSize(final int screenWidth, final int screenHeight) { synchronized(updateTextureLock) { this.screenWidth = screenWidth; this.screenHeight = screenHeight; updateTextureProperties = true; } } public void setPosition(int x, int y, int width, int height, ScalingType scalingType) { synchronized(updateTextureLock) { texLeft = (x - 50) / 50.0f; texTop = (50 - y) / 50.0f; texRight = Math.min(1.0f, (x + width - 50) / 50.0f); texBottom = Math.max(-1.0f, (50 - y - height) / 50.0f); this.scalingType = scalingType; updateTextureProperties = true; } } @Override public void setSize(final int width, final int height) { Log.d(TAG, "ID: " + id + ". YuvImageRenderer.setSize: " + width + " x " + height); videoWidth = width; videoHeight = height; int[] strides = { width, width / 2, width / 2 }; // Frame re-allocation need to be synchronized with copying // frame to textures in draw() function to avoid re-allocating // the frame while it is being copied. synchronized (frameToRenderQueue) { // Clear rendering queue. frameToRenderQueue.poll(); // Re-allocate / allocate the frame. yuvFrameToRender = new I420Frame(width, height, strides, null); textureFrameToRender = new I420Frame(width, height, null, -1); updateTextureProperties = true; } } @Override public synchronized void renderFrame(I420Frame frame) { long now = System.nanoTime(); framesReceived++; // Skip rendering of this frame if setSize() was not called. if (yuvFrameToRender == null || textureFrameToRender == null) { framesDropped++; return; } // Check input frame parameters. if (frame.yuvFrame) { if (frame.yuvStrides[0] < frame.width || frame.yuvStrides[1] < frame.width / 2 || frame.yuvStrides[2] < frame.width / 2) { Log.e(TAG, "Incorrect strides " + frame.yuvStrides[0] + ", " + frame.yuvStrides[1] + ", " + frame.yuvStrides[2]); return; } // Check incoming frame dimensions. if (frame.width != yuvFrameToRender.width || frame.height != yuvFrameToRender.height) { throw new RuntimeException("Wrong frame size " + frame.width + " x " + frame.height); } } if (frameToRenderQueue.size() > 0) { // Skip rendering of this frame if previous frame was not rendered yet. framesDropped++; return; } // Create a local copy of the frame. if (frame.yuvFrame) { yuvFrameToRender.copyFrom(frame); rendererType = RendererType.RENDERER_YUV; frameToRenderQueue.offer(yuvFrameToRender); } else { textureFrameToRender.copyFrom(frame); rendererType = RendererType.RENDERER_TEXTURE; frameToRenderQueue.offer(textureFrameToRender); } copyTimeNs += (System.nanoTime() - now); seenFrame = true; // Request rendering. surface.requestRender(); } } /** Passes GLSurfaceView to video renderer. */ public static void setView(GLSurfaceView surface, Runnable eglContextReadyCallback) { Log.d(TAG, "VideoRendererGui.setView"); instance = new VideoRendererGui(surface); eglContextReady = eglContextReadyCallback; } public static EGLContext getEGLContext() { return eglContext; } /** * Creates VideoRenderer with top left corner at (x, y) and resolution * (width, height). All parameters are in percentage of screen resolution. */ public static VideoRenderer createGui(int x, int y, int width, int height, ScalingType scalingType, boolean mirror) throws Exception { YuvImageRenderer javaGuiRenderer = create( x, y, width, height, scalingType, mirror); return new VideoRenderer(javaGuiRenderer); } public static VideoRenderer.Callbacks createGuiRenderer( int x, int y, int width, int height, ScalingType scalingType, boolean mirror) { return create(x, y, width, height, scalingType, mirror); } /** * Creates VideoRenderer.Callbacks with top left corner at (x, y) and * resolution (width, height). All parameters are in percentage of * screen resolution. */ public static YuvImageRenderer create(int x, int y, int width, int height, ScalingType scalingType, boolean mirror) { // Check display region parameters. if (x < 0 || x > 100 || y < 0 || y > 100 || width < 0 || width > 100 || height < 0 || height > 100 || x + width > 100 || y + height > 100) { throw new RuntimeException("Incorrect window parameters."); } if (instance == null) { throw new RuntimeException( "Attempt to create yuv renderer before setting GLSurfaceView"); } final YuvImageRenderer yuvImageRenderer = new YuvImageRenderer( instance.surface, instance.yuvImageRenderers.size(), x, y, width, height, scalingType, mirror); synchronized (instance.yuvImageRenderers) { if (instance.onSurfaceCreatedCalled) { // onSurfaceCreated has already been called for VideoRendererGui - // need to create texture for new image and add image to the // rendering list. final CountDownLatch countDownLatch = new CountDownLatch(1); instance.surface.queueEvent(new Runnable() { public void run() { yuvImageRenderer.createTextures( instance.yuvProgram, instance.oesProgram); yuvImageRenderer.setScreenSize( instance.screenWidth, instance.screenHeight); countDownLatch.countDown(); } }); // Wait for task completion. try { countDownLatch.await(); } catch (InterruptedException e) { throw new RuntimeException(e); } } // Add yuv renderer to rendering list. instance.yuvImageRenderers.add(yuvImageRenderer); } return yuvImageRenderer; } public static void update( VideoRenderer.Callbacks renderer, int x, int y, int width, int height, ScalingType scalingType) { Log.d(TAG, "VideoRendererGui.update"); if (instance == null) { throw new RuntimeException( "Attempt to update yuv renderer before setting GLSurfaceView"); } synchronized (instance.yuvImageRenderers) { for (YuvImageRenderer yuvImageRenderer : instance.yuvImageRenderers) { if (yuvImageRenderer == renderer) { yuvImageRenderer.setPosition(x, y, width, height, scalingType); } } } } public static void remove(VideoRenderer.Callbacks renderer) { Log.d(TAG, "VideoRendererGui.remove"); if (instance == null) { throw new RuntimeException( "Attempt to remove yuv renderer before setting GLSurfaceView"); } synchronized (instance.yuvImageRenderers) { if (!instance.yuvImageRenderers.remove(renderer)) { Log.w(TAG, "Couldn't remove renderer (not present in current list)"); } } } @Override public void onSurfaceCreated(GL10 unused, EGLConfig config) { Log.d(TAG, "VideoRendererGui.onSurfaceCreated"); // Store render EGL context. if (CURRENT_SDK_VERSION >= EGL14_SDK_VERSION) { eglContext = EGL14.eglGetCurrentContext(); Log.d(TAG, "VideoRendererGui EGL Context: " + eglContext); } // Create YUV and OES programs. yuvProgram = createProgram(VERTEX_SHADER_STRING, YUV_FRAGMENT_SHADER_STRING); oesProgram = createProgram(VERTEX_SHADER_STRING, OES_FRAGMENT_SHADER_STRING); synchronized (yuvImageRenderers) { // Create textures for all images. for (YuvImageRenderer yuvImageRenderer : yuvImageRenderers) { yuvImageRenderer.createTextures(yuvProgram, oesProgram); } onSurfaceCreatedCalled = true; } checkNoGLES2Error(); GLES20.glClearColor(0.15f, 0.15f, 0.15f, 1.0f); // Fire EGL context ready event. if (eglContextReady != null) { eglContextReady.run(); } } @Override public void onSurfaceChanged(GL10 unused, int width, int height) { Log.d(TAG, "VideoRendererGui.onSurfaceChanged: " + width + " x " + height + " "); screenWidth = width; screenHeight = height; GLES20.glViewport(0, 0, width, height); synchronized (yuvImageRenderers) { for (YuvImageRenderer yuvImageRenderer : yuvImageRenderers) { yuvImageRenderer.setScreenSize(screenWidth, screenHeight); } } } @Override public void onDrawFrame(GL10 unused) { GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT); synchronized (yuvImageRenderers) { for (YuvImageRenderer yuvImageRenderer : yuvImageRenderers) { yuvImageRenderer.draw(); } } } }
Ensure we set the right attrib for correct shader When using oesProgram, we still specify the yuvProgram for setting shader attributes. This should be changed to the correct shader program. BUG= [email protected] Review URL: https://webrtc-codereview.appspot.com/45379004 Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#8533} git-svn-id: 917f5d3ca488f358c4d40eaec14422cf392ccec9@8533 4adac7df-926f-26a2-2b94-8c16560cd09d
talk/app/webrtc/java/android/org/webrtc/VideoRendererGui.java
Ensure we set the right attrib for correct shader
Java
mit
a60e6d2b7c41659dc2d9c09a65cd8c7968208bab
0
BridgeAPIs/CrossPermissionsBungee
package net.zyuiop.permissions.bungee; import net.md_5.bungee.api.connection.ProxiedPlayer; import net.md_5.bungee.api.plugin.Plugin; import net.md_5.bungee.config.Configuration; import net.md_5.bungee.config.ConfigurationProvider; import net.md_5.bungee.config.YamlConfiguration; import net.zyuiop.crosspermissions.api.PermissionsAPI; import net.zyuiop.crosspermissions.api.database.JedisDatabase; import net.zyuiop.crosspermissions.api.database.JedisSentinelDatabase; import net.zyuiop.crosspermissions.api.rawtypes.RawPlayer; import net.zyuiop.crosspermissions.api.rawtypes.RawPlugin; import java.io.File; import java.nio.file.Files; import java.util.*; import java.util.concurrent.TimeUnit; /** * This file is licensed under MIT License * A copy of the license is provided with the source * (C) zyuiop 2015 */ public class PermissionBungee extends Plugin implements RawPlugin { public static PermissionsAPI api; public void onEnable() { // Registering listener if (!getDataFolder().exists()) getDataFolder().mkdir(); String defaultGroup = null; try { File file = new File(getDataFolder(), "config.yml"); if (!file.exists()) { Files.copy(getResourceAsStream("config.yml"), file.toPath()); } Configuration config = ConfigurationProvider.getProvider(YamlConfiguration.class).load(file); defaultGroup = config.getString("default-group"); if (config.getBoolean("redis-sentinel.enabled", false)) { logInfo("Trying to load API with database mode : REDIS SENTINEL."); String master = config.getString("redis-sentinel.master", null); String auth = config.getString("redis-sentinel.auth", null); List<String> ips = config.getStringList("redis-sentinel.sentinels"); if (master == null || auth == null || ips == null) { logSevere("Configuration is not complete. Plugin failed to load."); return; } else { try { Set<String> iplist = new HashSet<>(); iplist.addAll(ips); JedisSentinelDatabase database = new JedisSentinelDatabase(iplist, master, auth); api = new PermissionsAPI(this, config.getString("default-group"), database); } catch (Exception e) { logSevere("Configuration is not correct. Plugin failed to load."); e.printStackTrace(); return; } } } else if (config.getBoolean("redis.enabled", false)) { logInfo("Trying to load API with database mode : REDIS."); String address = config.getString("redis.address"); String auth = config.getString("redis.auth"); int port = config.getInt("redis.port", 6379); if (address == null || auth == null) { logSevere("Configuration is not complete. Plugin failed to load."); return; } else { try { JedisDatabase database = new JedisDatabase(address, port, auth); api = new PermissionsAPI(this, config.getString("default-group"), database); } catch (Exception e) { logSevere("Configuration is not correct. Plugin failed to load."); e.printStackTrace(); return; } } } else { logSevere("ERROR : NO DATABASE BACKEND ENABLED."); logSevere("To use this plugin, you have to enable redis or redis sentinel"); return; } } catch (Exception e) { this.getLogger().info("An error occured while trying to load configuration."); this.getLogger().info("API will be loaded with a null default group."); } this.getProxy().getPluginManager().registerCommand(this, new CommandRefresh(api)); this.getProxy().getPluginManager().registerListener(this, new PlayerListener(this)); } @Override public void logSevere(String s) { this.getLogger().severe(s); } @Override public void logWarning(String s) { this.getLogger().warning(s); } @Override public void logInfo(String s) { this.getLogger().info(s); } @Override public void runRepeatedTaskAsync(Runnable runnable, long delay, long before) { this.getProxy().getScheduler().schedule(this, runnable, before * 50, delay * 50, TimeUnit.MILLISECONDS); // Un tick = 50 ms } @Override public void runAsync(Runnable runnable) { this.getProxy().getScheduler().runAsync(this, runnable); } @Override public boolean isOnline(UUID uuid) { return (getProxy().getPlayer(uuid) != null); } @Override public RawPlayer getPlayer(UUID player) { return new VirtPlayer(player); } @Override public UUID getPlayerId(String name) { ProxiedPlayer player = getProxy().getPlayer(name); return (player == null) ? null : player.getUniqueId(); } @Override public String getPlayerName(UUID id) { ProxiedPlayer player = getProxy().getPlayer(id); return (player == null) ? null : player.getName(); } }
src/main/java/net/zyuiop/permissions/bungee/PermissionBungee.java
package net.zyuiop.permissions.bungee; import net.md_5.bungee.api.connection.ProxiedPlayer; import net.md_5.bungee.api.plugin.Plugin; import net.md_5.bungee.config.Configuration; import net.md_5.bungee.config.ConfigurationProvider; import net.md_5.bungee.config.YamlConfiguration; import net.zyuiop.crosspermissions.api.PermissionsAPI; import net.zyuiop.crosspermissions.api.database.JedisDatabase; import net.zyuiop.crosspermissions.api.database.JedisSentinelDatabase; import net.zyuiop.crosspermissions.api.rawtypes.RawPlayer; import net.zyuiop.crosspermissions.api.rawtypes.RawPlugin; import java.io.File; import java.nio.file.Files; import java.util.*; import java.util.concurrent.TimeUnit; /** * This file is licensed under MIT License * A copy of the license is provided with the source * (C) zyuiop 2015 */ public class PermissionBungee extends Plugin implements RawPlugin { public static PermissionsAPI api; public void onEnable() { // Registering listener if (!getDataFolder().exists()) getDataFolder().mkdir(); String defaultGroup = null; try { File file = new File(getDataFolder(), "config.yml"); if (!file.exists()) { Files.copy(getResourceAsStream("config.yml"), file.toPath()); } Configuration config = ConfigurationProvider.getProvider(YamlConfiguration.class).load(file); defaultGroup = config.getString("default-group"); if (config.getBoolean("redis-sentinel.enabled", false)) { logInfo("Trying to load API with database mode : REDIS SENTINEL."); String master = config.getString("redis-sentinel.master"); String auth = config.getString("redis-sentinel.auth"); List<String> ips = config.getStringList("redis-sentinel.sentinels"); if (master == null || auth == null || ips == null) { logSevere("Configuration is not complete. Plugin failed to load."); return; } else { try { Set<String> iplist = new HashSet<>(); iplist.addAll(ips); JedisSentinelDatabase database = new JedisSentinelDatabase(iplist, master, auth); api = new PermissionsAPI(this, config.getString("default-group"), database); } catch (Exception e) { logSevere("Configuration is not correct. Plugin failed to load."); e.printStackTrace(); return; } } } else if (config.getBoolean("redis.enabled", false)) { logInfo("Trying to load API with database mode : REDIS."); String address = config.getString("redis.address"); String auth = config.getString("redis.auth"); int port = config.getInt("redis.port", 6379); if (address == null || auth == null) { logSevere("Configuration is not complete. Plugin failed to load."); return; } else { try { JedisDatabase database = new JedisDatabase(address, port, auth); api = new PermissionsAPI(this, config.getString("default-group"), database); } catch (Exception e) { logSevere("Configuration is not correct. Plugin failed to load."); e.printStackTrace(); return; } } } else { logSevere("ERROR : NO DATABASE BACKEND ENABLED."); logSevere("To use this plugin, you have to enable redis or redis sentinel"); return; } } catch (Exception e) { this.getLogger().info("An error occured while trying to load configuration."); this.getLogger().info("API will be loaded with a null default group."); } this.getProxy().getPluginManager().registerCommand(this, new CommandRefresh(api)); this.getProxy().getPluginManager().registerListener(this, new PlayerListener(this)); } @Override public void logSevere(String s) { this.getLogger().severe(s); } @Override public void logWarning(String s) { this.getLogger().warning(s); } @Override public void logInfo(String s) { this.getLogger().info(s); } @Override public void runRepeatedTaskAsync(Runnable runnable, long delay, long before) { this.getProxy().getScheduler().schedule(this, runnable, before * 50, delay * 50, TimeUnit.MILLISECONDS); // Un tick = 50 ms } @Override public void runAsync(Runnable runnable) { this.getProxy().getScheduler().runAsync(this, runnable); } @Override public boolean isOnline(UUID uuid) { return (getProxy().getPlayer(uuid) != null); } @Override public RawPlayer getPlayer(UUID player) { return new VirtPlayer(player); } @Override public UUID getPlayerId(String name) { ProxiedPlayer player = getProxy().getPlayer(name); return (player == null) ? null : player.getUniqueId(); } @Override public String getPlayerName(UUID id) { ProxiedPlayer player = getProxy().getPlayer(id); return (player == null) ? null : player.getName(); } }
Better support for no-auth
src/main/java/net/zyuiop/permissions/bungee/PermissionBungee.java
Better support for no-auth
Java
mit
fcc14919794a90b4682179e39836b233ec3a66d3
0
ramswaroop/Algorithms-and-Data-Structures-in-Java
package com.rampatra.blockchain; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * @author rampatra * @since 2019-03-05 */ public class Blockchain { // TODO: P2P private List<Block> blockchain; private int difficulty; public Blockchain(List<Block> blockchain, int difficulty) { this.blockchain = blockchain; this.difficulty = difficulty; this.blockchain.add(getGenesisBlock("Blockchain in Java")); } public List<Block> getBlockchain() { return blockchain; } public void mine(String data) { Block previousBlock = blockchain.get(blockchain.size() - 1); Block nextBlock = getNextBlock(previousBlock, data); if (isValidNextBlock(previousBlock, nextBlock)) { blockchain.add(nextBlock); } else { throw new RuntimeException("Invalid block"); } } private Block getGenesisBlock(String data) { final long timestamp = new Date().getTime(); int nonce = 0; String hash; while (!isValidHashDifficulty(hash = calculateHashForBlock(0, "0", timestamp, data, nonce))) { nonce++; } return new Block(0, "0", timestamp, data, hash, nonce); } private Block getNextBlock(Block previousBlock, String data) { final int index = previousBlock.getIndex() + 1; final long timestamp = new Date().getTime(); int nonce = 0; String hash; while (!isValidHashDifficulty( hash = calculateHashForBlock(index, previousBlock.getHash(), timestamp, data, nonce))) { nonce++; } return new Block(index, previousBlock.getHash(), timestamp, data, hash, nonce); } private boolean isValidNextBlock(Block previousBlock, Block nextBlock) { String nextBlockHash = calculateHashForBlock(nextBlock.getIndex(), previousBlock.getHash(), nextBlock.getTimestamp(), nextBlock.getData(), nextBlock.getNonce()); if (previousBlock.getIndex() + 1 != nextBlock.getIndex()) { return false; } else if (!previousBlock.getHash().equals(nextBlock.getPreviousHash())) { return false; } else if (!this.isValidHashDifficulty(nextBlockHash)) { return false; } else if (!nextBlockHash.equals(nextBlock.getHash())) { return false; } else { return true; } } private boolean isValidHashDifficulty(String hash) { for (int i = 0; i < difficulty; i++) { if (hash.charAt(i) != '0') { return false; } } return true; } private String calculateHashForBlock(final int index, final String previousHash, final long timestamp, final String data, final int nonce) { try { MessageDigest digest = MessageDigest.getInstance("SHA-256"); byte[] encodedhash = digest.digest( (index + previousHash + timestamp + data + nonce).getBytes(StandardCharsets.UTF_8)); return bytesToHex(encodedhash); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("Encryption Error: {}", e); } } private static String bytesToHex(byte[] hash) { StringBuilder hexString = new StringBuilder(); for (int i = 0; i < hash.length; i++) { String hex = Integer.toHexString(0xff & hash[i]); if (hex.length() == 1) hexString.append('0'); hexString.append(hex); } return hexString.toString(); } public static void main(String[] args) { Blockchain blockchain = new Blockchain(new ArrayList<>(), 3); blockchain.mine("12"); blockchain.mine("26"); System.out.println("Blockchain: " + blockchain.getBlockchain()); } }
src/main/java/com/rampatra/blockchain/Blockchain.java
package com.rampatra.blockchain; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Date; import java.util.List; /** * @author rampatra * @since 2019-03-05 */ public class Blockchain { // TODO: WIP private List<Block> blockchain; private int difficulty; public Blockchain(List<Block> blockchain, int difficulty) { this.blockchain = blockchain; this.difficulty = difficulty; } public void mine(String data) { if (blockchain.size() == 0) { blockchain.add(getGenesisBlock(data)); } else { Block previousBlock = blockchain.get(blockchain.size() - 1); blockchain.add(getNextBlock(previousBlock, data)); } } private boolean isValidNextBlock(Block previousBlock, Block nextBlock) { String nextBlockHash = calculateHashForBlock(nextBlock.getIndex(), previousBlock.getHash(), nextBlock.getTimestamp(), nextBlock.getData(), nextBlock.getNonce()); if (previousBlock.getIndex() + 1 != nextBlock.getIndex()) { return false; } else if (!previousBlock.getHash().equals(nextBlock.getPreviousHash())) { return false; } else if (!this.isValidHashDifficulty(nextBlockHash)) { return false; } else if (!nextBlockHash.equals(nextBlock.getHash())) { return false; } else { return true; } } private Block getGenesisBlock(String data) { final long timestamp = new Date().getTime(); String hash = calculateHashForBlock(0, "0", timestamp, data, 0); return new Block(0, "0", timestamp, data, hash, 0); } private Block getNextBlock(Block previousBlock, String data) { final int index = previousBlock.getIndex() + 1; final long timestamp = new Date().getTime(); final String hash = calculateHashForBlock(index, previousBlock.getHash(), timestamp, data, 0); return new Block(index, previousBlock.getHash(), timestamp, data, hash, 0); } private boolean isValidHashDifficulty(String hash) { for (int i = 0; i < difficulty; i++) { if (hash.charAt(i) != '0') { return false; } } return true; } private String calculateHashForBlock(final int index, final String previousHash, final long timestamp, final String data, final int nonce) { try { MessageDigest digest = MessageDigest.getInstance("SHA-256"); byte[] encodedhash = digest.digest( (index + previousHash + timestamp + data + nonce).getBytes(StandardCharsets.UTF_8)); return bytesToHex(encodedhash); } catch (NoSuchAlgorithmException e) { // do nothing for now } return ""; } private static String bytesToHex(byte[] hash) { StringBuilder hexString = new StringBuilder(); for (int i = 0; i < hash.length; i++) { String hex = Integer.toHexString(0xff & hash[i]); if (hex.length() == 1) hexString.append('0'); hexString.append(hex); } return hexString.toString(); } }
Very basic blockchain implementation in Java
src/main/java/com/rampatra/blockchain/Blockchain.java
Very basic blockchain implementation in Java
Java
mit
ebb6123bc92e5a7f091436b6512e4f6ac9faa939
0
dreamhead/moco,dreamhead/moco
package com.github.dreamhead.moco; import com.google.common.eventbus.Subscribe; public interface MocoMonitor { @Subscribe void onMessageArrived(Request request); @Subscribe void onException(Throwable t); @Subscribe void onMessageLeave(Response response); @Subscribe void onUnexpectedMessage(Request request); }
moco-core/src/main/java/com/github/dreamhead/moco/MocoMonitor.java
package com.github.dreamhead.moco; import com.google.common.eventbus.Subscribe; public interface MocoMonitor { @Subscribe void onMessageArrived(final Request request); @Subscribe void onException(final Throwable t); @Subscribe void onMessageLeave(final Response response); @Subscribe void onUnexpectedMessage(final Request request); }
removed redundant final from moco monitor
moco-core/src/main/java/com/github/dreamhead/moco/MocoMonitor.java
removed redundant final from moco monitor
Java
mit
66029c98f9b3f583ac2de6427727340cfbd34155
0
JetBrains/ideavim,JetBrains/ideavim
package com.maddyhome.idea.vim; import com.intellij.notification.Notification; import com.intellij.notification.NotificationType; import com.intellij.notification.Notifications; import com.intellij.openapi.application.ApplicationNamesInfo; import com.intellij.openapi.application.PathManager; import com.intellij.openapi.application.ex.ApplicationEx; import com.intellij.openapi.application.ex.ApplicationManagerEx; import com.intellij.openapi.components.impl.stores.StorageUtil; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.keymap.Keymap; import com.intellij.openapi.keymap.KeymapManager; import com.intellij.openapi.keymap.impl.KeymapImpl; import com.intellij.openapi.keymap.impl.KeymapManagerImpl; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.InvalidDataException; import com.intellij.openapi.util.JDOMUtil; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.maddyhome.idea.vim.ui.VimKeymapDialog; import org.jdom.Document; import org.jdom.Element; import org.jetbrains.annotations.Nullable; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; /** * @author oleg */ public class VimKeyMapUtil { private static Logger LOG = Logger.getInstance(VimKeyMapUtil.class); private static final String VIM_XML = "Vim.xml"; private static final String IDEAVIM_NOTIFICATION_ID = "ideavim"; private static final String IDEAVIM_NOTIFICATION_TITLE = "IdeaVim"; /** * @return true if keymap was installed or was successfully installed */ public static boolean installKeyBoardBindings() { LOG.debug("Check for keyboard bindings"); final KeymapManagerImpl manager = (KeymapManagerImpl)KeymapManager.getInstance(); final Keymap keymap = manager.getKeymap("Vim"); if (keymap != null) { return true; } final String keyMapsPath = PathManager.getConfigPath() + File.separatorChar + "keymaps"; final LocalFileSystem localFileSystem = LocalFileSystem.getInstance(); final VirtualFile keyMapsFolder = localFileSystem.refreshAndFindFileByPath(keyMapsPath); if (keyMapsFolder == null) { LOG.error("Failed to install vim keymap. Empty keymaps folder"); return false; } LOG.debug("No vim keyboard installed found. Installing"); String keymapPath = PathManager.getPluginsPath() + File.separatorChar + IDEAVIM_NOTIFICATION_TITLE + File.separatorChar + VIM_XML; File vimKeyMapFile = new File(keymapPath); // Look in development path if (!vimKeyMapFile.exists() || !vimKeyMapFile.isFile()) { final String resource = VimKeyMapUtil.class.getResource("").toString(); keymapPath = resource.toString().substring("file:".length(), resource.indexOf("out")) + "community/plugins/ideavim/keymap/" + VIM_XML; vimKeyMapFile = new File(keymapPath); } if (!vimKeyMapFile.exists() || !vimKeyMapFile.isFile()) { final String error = "Installation of the Vim keymap failed because Vim keymap file not found: " + keymapPath; LOG.error(error); Notifications.Bus.notify(new Notification(IDEAVIM_NOTIFICATION_ID, IDEAVIM_NOTIFICATION_TITLE, error, NotificationType.ERROR)); return false; } try { final VirtualFile vimKeyMap2Copy = localFileSystem.refreshAndFindFileByIoFile(vimKeyMapFile); if (vimKeyMap2Copy == null){ final String error = "Installation of the Vim keymap failed because Vim keymap file not found: " + keymapPath; LOG.error(error); Notifications.Bus.notify(new Notification(IDEAVIM_NOTIFICATION_ID, IDEAVIM_NOTIFICATION_TITLE, error, NotificationType.ERROR)); return false; } final VirtualFile vimKeyMapVFile = localFileSystem.copyFile(VimPlugin.getInstance(), vimKeyMap2Copy, keyMapsFolder, VIM_XML); final String path = vimKeyMapVFile.getPath(); final Document document = StorageUtil.loadDocument(new FileInputStream(path)); if (document == null) { LOG.error("Failed to install vim keymap. Vim.xml file is corrupted"); Notifications.Bus.notify(new Notification(IDEAVIM_NOTIFICATION_ID, IDEAVIM_NOTIFICATION_TITLE, "Failed to install vim keymap. Vim.xml file is corrupted", NotificationType.ERROR)); return false; } // Prompt user to select the parent for the Vim keyboard configureVimParentKeymap(path, document, false); final KeymapImpl vimKeyMap = new KeymapImpl(); final Keymap[] allKeymaps = manager.getAllKeymaps(); vimKeyMap.readExternal(document.getRootElement(), allKeymaps); manager.addKeymap(vimKeyMap); return true; } catch (Exception e) { reportError(e); return false; } } private static void requestRestartOrShutdown(final Project project) { final ApplicationEx app = ApplicationManagerEx.getApplicationEx(); if (app.isRestartCapable()) { if (Messages.showDialog(project, "Restart " + ApplicationNamesInfo.getInstance().getProductName() + " to activate changes?", "Vim keymap changed", new String[]{"&Restart", "&Postpone"}, 0, Messages.getQuestionIcon()) == 0) { app.restart(); } } else { if (Messages.showDialog(project, "Shut down " + ApplicationNamesInfo.getInstance().getProductName() + " to activate changes?", "Vim keymap changed", new String[]{"&Shut Down", "&Postpone"}, 0, Messages.getQuestionIcon()) == 0){ app.exit(true); } } } /** * Changes parent keymap for the Vim * @return true if document was changed succesfully */ private static boolean configureVimParentKeymap(final String path, final Document document, final boolean showNotification) throws IOException { final Element rootElement = document.getRootElement(); final String parentKeymap = rootElement.getAttributeValue("parent"); final VimKeymapDialog vimKeymapDialog = new VimKeymapDialog(parentKeymap); vimKeymapDialog.show(); if (vimKeymapDialog.getExitCode() != DialogWrapper.OK_EXIT_CODE){ return false; } rootElement.removeAttribute("parent"); final Keymap selectedKeymap = vimKeymapDialog.getSelectedKeymap(); final String keymapName = selectedKeymap.getName(); rootElement.setAttribute("parent", keymapName); // Save modified keymap to the file JDOMUtil.writeDocument(document, path, "\n"); if (showNotification) { Notifications.Bus.notify(new Notification(IDEAVIM_NOTIFICATION_ID, IDEAVIM_NOTIFICATION_TITLE, "Successfully configured vim keymap to be based on " + selectedKeymap.getPresentableName(), NotificationType.INFORMATION)); } return true; } /** * @return true if keymap was switched successfully, false otherwise */ public static boolean switchKeymapBindings(final boolean enableVimKeymap) { LOG.debug("Enabling keymap"); final KeymapManagerImpl manager = (KeymapManagerImpl)KeymapManager.getInstance(); // In case if Vim keymap is already in use or we don't need it, we have nothing to do if (manager.getActiveKeymap().getName().equals("Vim") == enableVimKeymap){ return false; } // Get keymap to enable final String keymapName2Enable = enableVimKeymap ? "Vim" : VimPlugin.getInstance().getPreviousKeyMap(); if (keymapName2Enable.isEmpty()) { return false; } if (keymapName2Enable.equals(manager.getActiveKeymap().getName())) { return false; } LOG.debug("Enabling keymap:" + keymapName2Enable); final Keymap keymap = manager.getKeymap(keymapName2Enable); if (keymap == null) { Notifications.Bus.notify(new Notification(IDEAVIM_NOTIFICATION_ID, IDEAVIM_NOTIFICATION_TITLE, "Failed to enable keymap: " + keymapName2Enable, NotificationType.ERROR)); LOG.error("Failed to enable keymap: " + keymapName2Enable); return false; } // Save previous keymap to enable after VIM emulation is turned off if (enableVimKeymap) { VimPlugin.getInstance().setPreviousKeyMap(manager.getActiveKeymap().getName()); } manager.setActiveKeymap(keymap); final String keyMapPresentableName = keymap.getPresentableName(); Notifications.Bus.notify(new Notification(IDEAVIM_NOTIFICATION_ID, IDEAVIM_NOTIFICATION_TITLE, keyMapPresentableName + " keymap was successfully enabled", NotificationType.INFORMATION)); LOG.debug(keyMapPresentableName + " keymap was successfully enabled"); return true; } public static void reconfigureParentKeymap(final Project project) { final VirtualFile vimKeymapFile = getVimKeymapFile(); if (vimKeymapFile == null) { LOG.error("Failed to find Vim keymap"); Notifications.Bus.notify(new Notification(IDEAVIM_NOTIFICATION_ID, IDEAVIM_NOTIFICATION_TITLE, "Failed to find Vim keymap", NotificationType.ERROR)); return; } try { final String path = vimKeymapFile.getPath(); final Document document = StorageUtil.loadDocument(new FileInputStream(path)); if (document == null) { LOG.error("Failed to install vim keymap. Vim.xml file is corrupted"); Notifications.Bus.notify(new Notification(IDEAVIM_NOTIFICATION_ID, IDEAVIM_NOTIFICATION_TITLE, "Vim.xml file is corrupted", NotificationType.ERROR)); return; } // Prompt user to select the parent for the Vim keyboard if (configureVimParentKeymap(path, document, true)) { final KeymapManagerImpl manager = (KeymapManagerImpl) KeymapManager.getInstance(); final KeymapImpl vimKeyMap = new KeymapImpl(); final Keymap[] allKeymaps = manager.getAllKeymaps(); vimKeyMap.readExternal(document.getRootElement(), allKeymaps); manager.addKeymap(vimKeyMap); requestRestartOrShutdown(project); } } catch (FileNotFoundException e) { reportError(e); } catch (IOException e) { reportError(e); } catch (InvalidDataException e) { reportError(e); } } private static void reportError(final Exception e) { LOG.error("Failed to reconfigure vim keymap.\n" + e); Notifications.Bus .notify(new Notification(IDEAVIM_NOTIFICATION_ID, IDEAVIM_NOTIFICATION_TITLE, "Failed to reconfigure vim keymap.\n" + e, NotificationType.ERROR)); } @Nullable public static VirtualFile getVimKeymapFile() { final String keyMapsPath = PathManager.getConfigPath() + File.separatorChar + "keymaps"; final LocalFileSystem localFileSystem = LocalFileSystem.getInstance(); return localFileSystem.refreshAndFindFileByPath(keyMapsPath + File.separatorChar + VIM_XML); } }
src/com/maddyhome/idea/vim/VimKeyMapUtil.java
package com.maddyhome.idea.vim; import com.intellij.notification.Notification; import com.intellij.notification.NotificationType; import com.intellij.notification.Notifications; import com.intellij.openapi.application.ApplicationNamesInfo; import com.intellij.openapi.application.PathManager; import com.intellij.openapi.application.ex.ApplicationEx; import com.intellij.openapi.application.ex.ApplicationManagerEx; import com.intellij.openapi.components.impl.stores.StorageUtil; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.keymap.Keymap; import com.intellij.openapi.keymap.KeymapManager; import com.intellij.openapi.keymap.impl.KeymapImpl; import com.intellij.openapi.keymap.impl.KeymapManagerImpl; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.InvalidDataException; import com.intellij.openapi.util.JDOMUtil; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.maddyhome.idea.vim.ui.VimKeymapDialog; import org.jdom.Document; import org.jdom.Element; import org.jetbrains.annotations.Nullable; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; /** * @author oleg */ public class VimKeyMapUtil { private static Logger LOG = Logger.getInstance(VimKeyMapUtil.class); private static final String VIM_XML = "Vim.xml"; private static final String IDEAVIM_NOTIFICATION_ID = "ideavim"; private static final String IDEAVIM_NOTIFICATION_TITLE = "IdeaVim"; /** * @return true if keymap was installed or was successfully installed */ public static boolean installKeyBoardBindings() { LOG.debug("Check for keyboard bindings"); final KeymapManagerImpl manager = (KeymapManagerImpl)KeymapManager.getInstance(); final Keymap keymap = manager.getKeymap("Vim"); if (keymap != null) { return true; } final String keyMapsPath = PathManager.getConfigPath() + File.separatorChar + "keymaps"; final LocalFileSystem localFileSystem = LocalFileSystem.getInstance(); final VirtualFile keyMapsFolder = localFileSystem.refreshAndFindFileByPath(keyMapsPath); if (keyMapsFolder == null) { LOG.error("Failed to install vim keymap. Empty keymaps folder"); return false; } LOG.debug("No vim keyboard installed found. Installing"); String keymapPath = PathManager.getPluginsPath() + File.separatorChar + IDEAVIM_NOTIFICATION_TITLE + File.separatorChar + VIM_XML; File vimKeyMapFile = new File(keymapPath); // Look in development path if (!vimKeyMapFile.exists() || !vimKeyMapFile.isFile()) { final String resource = VimKeyMapUtil.class.getResource("").toString(); keymapPath = resource.toString().substring("file:".length(), resource.indexOf("out")) + "community/plugins/ideavim/keymap/" + VIM_XML; vimKeyMapFile = new File(keymapPath); } if (!vimKeyMapFile.exists() || !vimKeyMapFile.isFile()) { final String error = "Installation of the Vim keymap failed because Vim keymap file not found: " + keymapPath; LOG.error(error); Notifications.Bus.notify(new Notification(IDEAVIM_NOTIFICATION_ID, IDEAVIM_NOTIFICATION_TITLE, error, NotificationType.ERROR)); return false; } try { final VirtualFile vimKeyMap2Copy = localFileSystem.refreshAndFindFileByIoFile(vimKeyMapFile); if (vimKeyMap2Copy == null){ final String error = "Installation of the Vim keymap failed because Vim keymap file not found: " + keymapPath; LOG.error(error); Notifications.Bus.notify(new Notification(IDEAVIM_NOTIFICATION_ID, IDEAVIM_NOTIFICATION_TITLE, error, NotificationType.ERROR)); return false; } final VirtualFile vimKeyMapVFile = localFileSystem.copyFile(VimPlugin.getInstance(), vimKeyMap2Copy, keyMapsFolder, VIM_XML); final String path = vimKeyMapVFile.getPath(); final Document document = StorageUtil.loadDocument(new FileInputStream(path)); if (document == null) { LOG.error("Failed to install vim keymap. Vim.xml file is corrupted"); Notifications.Bus.notify(new Notification(IDEAVIM_NOTIFICATION_ID, IDEAVIM_NOTIFICATION_TITLE, "Failed to install vim keymap. Vim.xml file is corrupted", NotificationType.ERROR)); return false; } // Prompt user to select the parent for the Vim keyboard configureVimParentKeymap(path, document, false); final KeymapImpl vimKeyMap = new KeymapImpl(); final Keymap[] allKeymaps = manager.getAllKeymaps(); vimKeyMap.readExternal(document.getRootElement(), allKeymaps); manager.addKeymap(vimKeyMap); return true; } catch (Exception e) { reportError(e); return false; } } private static void requestRestartOrShutdown(final Project project) { final ApplicationEx app = ApplicationManagerEx.getApplicationEx(); if (app.isRestartCapable()) { if (Messages.showDialog(project, "Restart " + ApplicationNamesInfo.getInstance().getProductName() + " to activate changes?", "Vim keymap changed", new String[]{"Shut Down", "&Postpone"}, 0, Messages.getQuestionIcon()) == 0) { app.restart(); } } else { if (Messages.showDialog(project, "Shut down " + ApplicationNamesInfo.getInstance().getProductName() + " to activate changes?", "Vim keymap changed", new String[]{"Shut Down", "&Postpone"}, 0, Messages.getQuestionIcon()) == 0){ app.exit(true); } } } /** * Changes parent keymap for the Vim * @return true if document was changed succesfully */ private static boolean configureVimParentKeymap(final String path, final Document document, final boolean showNotification) throws IOException { final Element rootElement = document.getRootElement(); final String parentKeymap = rootElement.getAttributeValue("parent"); final VimKeymapDialog vimKeymapDialog = new VimKeymapDialog(parentKeymap); vimKeymapDialog.show(); if (vimKeymapDialog.getExitCode() != DialogWrapper.OK_EXIT_CODE){ return false; } rootElement.removeAttribute("parent"); final Keymap selectedKeymap = vimKeymapDialog.getSelectedKeymap(); final String keymapName = selectedKeymap.getName(); rootElement.setAttribute("parent", keymapName); // Save modified keymap to the file JDOMUtil.writeDocument(document, path, "\n"); if (showNotification) { Notifications.Bus.notify(new Notification(IDEAVIM_NOTIFICATION_ID, IDEAVIM_NOTIFICATION_TITLE, "Successfully configured vim keymap to be based on " + selectedKeymap.getPresentableName(), NotificationType.INFORMATION)); } return true; } /** * @return true if keymap was switched successfully, false otherwise */ public static boolean switchKeymapBindings(final boolean enableVimKeymap) { LOG.debug("Enabling keymap"); final KeymapManagerImpl manager = (KeymapManagerImpl)KeymapManager.getInstance(); // In case if Vim keymap is already in use or we don't need it, we have nothing to do if (manager.getActiveKeymap().getName().equals("Vim") == enableVimKeymap){ return false; } // Get keymap to enable final String keymapName2Enable = enableVimKeymap ? "Vim" : VimPlugin.getInstance().getPreviousKeyMap(); if (keymapName2Enable.isEmpty()) { return false; } if (keymapName2Enable.equals(manager.getActiveKeymap().getName())) { return false; } LOG.debug("Enabling keymap:" + keymapName2Enable); final Keymap keymap = manager.getKeymap(keymapName2Enable); if (keymap == null) { Notifications.Bus.notify(new Notification(IDEAVIM_NOTIFICATION_ID, IDEAVIM_NOTIFICATION_TITLE, "Failed to enable keymap: " + keymapName2Enable, NotificationType.ERROR)); LOG.error("Failed to enable keymap: " + keymapName2Enable); return false; } // Save previous keymap to enable after VIM emulation is turned off if (enableVimKeymap) { VimPlugin.getInstance().setPreviousKeyMap(manager.getActiveKeymap().getName()); } manager.setActiveKeymap(keymap); final String keyMapPresentableName = keymap.getPresentableName(); Notifications.Bus.notify(new Notification(IDEAVIM_NOTIFICATION_ID, IDEAVIM_NOTIFICATION_TITLE, keyMapPresentableName + " keymap was successfully enabled", NotificationType.INFORMATION)); LOG.debug(keyMapPresentableName + " keymap was successfully enabled"); return true; } public static void reconfigureParentKeymap(final Project project) { final VirtualFile vimKeymapFile = getVimKeymapFile(); if (vimKeymapFile == null) { LOG.error("Failed to find Vim keymap"); Notifications.Bus.notify(new Notification(IDEAVIM_NOTIFICATION_ID, IDEAVIM_NOTIFICATION_TITLE, "Failed to find Vim keymap", NotificationType.ERROR)); return; } try { final String path = vimKeymapFile.getPath(); final Document document = StorageUtil.loadDocument(new FileInputStream(path)); if (document == null) { LOG.error("Failed to install vim keymap. Vim.xml file is corrupted"); Notifications.Bus.notify(new Notification(IDEAVIM_NOTIFICATION_ID, IDEAVIM_NOTIFICATION_TITLE, "Vim.xml file is corrupted", NotificationType.ERROR)); return; } // Prompt user to select the parent for the Vim keyboard if (configureVimParentKeymap(path, document, true)) { final KeymapManagerImpl manager = (KeymapManagerImpl) KeymapManager.getInstance(); final KeymapImpl vimKeyMap = new KeymapImpl(); final Keymap[] allKeymaps = manager.getAllKeymaps(); vimKeyMap.readExternal(document.getRootElement(), allKeymaps); manager.addKeymap(vimKeyMap); requestRestartOrShutdown(project); } } catch (FileNotFoundException e) { reportError(e); } catch (IOException e) { reportError(e); } catch (InvalidDataException e) { reportError(e); } } private static void reportError(final Exception e) { LOG.error("Failed to reconfigure vim keymap.\n" + e); Notifications.Bus .notify(new Notification(IDEAVIM_NOTIFICATION_ID, IDEAVIM_NOTIFICATION_TITLE, "Failed to reconfigure vim keymap.\n" + e, NotificationType.ERROR)); } @Nullable public static VirtualFile getVimKeymapFile() { final String keyMapsPath = PathManager.getConfigPath() + File.separatorChar + "keymaps"; final LocalFileSystem localFileSystem = LocalFileSystem.getInstance(); return localFileSystem.refreshAndFindFileByPath(keyMapsPath + File.separatorChar + VIM_XML); } }
Cosmetics
src/com/maddyhome/idea/vim/VimKeyMapUtil.java
Cosmetics
Java
epl-1.0
df13eda1d5a4f2225921b5c4a01b7cede98dfbf7
0
hacktx/electron,hacktx/electron
package com.hacktx.electron.activities; import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.view.inputmethod.EditorInfo; import android.widget.EditText; import android.widget.TextView; import com.google.android.gms.vision.CameraSource; import com.google.android.gms.vision.MultiProcessor; import com.google.android.gms.vision.barcode.Barcode; import com.google.android.gms.vision.barcode.BarcodeDetector; import com.hacktx.electron.R; import com.hacktx.electron.utils.PreferencesUtils; import com.hacktx.electron.vision.BarcodeTrackerFactory; import com.hacktx.electron.vision.CameraSourcePreview; import com.hacktx.electron.vision.GraphicOverlay; import com.hacktx.electron.vision.VisionCallback; import java.io.IOException; public class MainActivity extends AppCompatActivity { private CameraSourcePreview mPreview; private GraphicOverlay mGraphicOverlay; private CameraSource mCameraSource; private boolean scanning; @Override public void onCreate(Bundle state) { super.onCreate(state); checkIfShowWelcomeActivity(); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); if (toolbar != null) { setSupportActionBar(toolbar); getSupportActionBar().setTitle(R.string.app_name); } mPreview = (CameraSourcePreview) findViewById(R.id.preview); mGraphicOverlay = (GraphicOverlay) findViewById(R.id.overlay); BarcodeDetector barcodeDetector = new BarcodeDetector.Builder(this).build(); BarcodeTrackerFactory barcodeFactory = new BarcodeTrackerFactory(mGraphicOverlay, new VisionCallback() { @Override public void onFound(final Barcode barcode) { runOnUiThread(new Runnable() { public void run() { if(scanning && barcode.format == Barcode.QR_CODE) { scanning = false; showConfirmationDialog(barcode.rawValue); } } }); } }); barcodeDetector.setProcessor(new MultiProcessor.Builder<>(barcodeFactory).build()); mCameraSource = new CameraSource.Builder(this, barcodeDetector) .setFacing(CameraSource.CAMERA_FACING_BACK) .setRequestedPreviewSize(1600, 1024) .build(); startCameraSource(); } private void startCameraSource() { try { mPreview.start(mCameraSource, mGraphicOverlay); scanning = true; } catch (IOException e) { mCameraSource.release(); mCameraSource = null; } } @Override protected void onResume() { super.onResume(); startCameraSource(); } @Override protected void onPause() { super.onPause(); mPreview.stop(); } @Override protected void onDestroy() { super.onDestroy(); mCameraSource.release(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); switch (id) { case R.id.action_enter_email: showEmailDialog(); return true; case R.id.action_settings: startActivity(new Intent(this, PreferencesActivity.class)); return true; } return super.onOptionsItemSelected(item); } private void checkIfShowWelcomeActivity() { if (PreferencesUtils.getFirstLaunch(this) || PreferencesUtils.getVolunteerId(this).isEmpty()) { startActivity(new Intent(this, WelcomeActivity.class)); finish(); } } private void showEmailDialog() { final Dialog dialog = new Dialog(this); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setContentView(R.layout.dialog_email); WindowManager.LayoutParams params = dialog.getWindow().getAttributes(); params.width = WindowManager.LayoutParams.MATCH_PARENT; dialog.getWindow().setAttributes(params); dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); dialog.show(); final EditText emailEditText = (EditText) dialog.findViewById(R.id.emailDialogEditText); emailEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_DONE) { dialog.dismiss(); showConfirmationDialog(emailEditText.getText().toString()); } return true; } }); dialog.findViewById(R.id.emailDialogCancel).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); } }); dialog.findViewById(R.id.emailDialogOk).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); showConfirmationDialog(emailEditText.getText().toString()); } }); } private void showConfirmationDialog(String email) { AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.AppCompatAlertDialogStyle); builder.setTitle(R.string.dialog_verify_title); builder.setMessage(email); builder.setPositiveButton(R.string.dialog_verify_approve, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO: Notify Nucleus dialog.dismiss(); scanning = true; } }); builder.setNegativeButton(R.string.dialog_verify_deny, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); scanning = true; } }); builder.show(); } }
app/src/main/java/com/hacktx/electron/activities/MainActivity.java
package com.hacktx.electron.activities; import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.view.inputmethod.EditorInfo; import android.widget.EditText; import android.widget.TextView; import com.google.android.gms.vision.CameraSource; import com.google.android.gms.vision.MultiProcessor; import com.google.android.gms.vision.barcode.Barcode; import com.google.android.gms.vision.barcode.BarcodeDetector; import com.hacktx.electron.R; import com.hacktx.electron.utils.PreferencesUtils; import com.hacktx.electron.vision.BarcodeTrackerFactory; import com.hacktx.electron.vision.CameraSourcePreview; import com.hacktx.electron.vision.GraphicOverlay; import com.hacktx.electron.vision.VisionCallback; import java.io.IOException; public class MainActivity extends AppCompatActivity { private CameraSourcePreview mPreview; private GraphicOverlay mGraphicOverlay; private CameraSource mCameraSource; @Override public void onCreate(Bundle state) { super.onCreate(state); checkIfShowWelcomeActivity(); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); if (toolbar != null) { setSupportActionBar(toolbar); getSupportActionBar().setTitle(R.string.app_name); } mPreview = (CameraSourcePreview) findViewById(R.id.preview); mGraphicOverlay = (GraphicOverlay) findViewById(R.id.overlay); BarcodeDetector barcodeDetector = new BarcodeDetector.Builder(this).build(); BarcodeTrackerFactory barcodeFactory = new BarcodeTrackerFactory(mGraphicOverlay, new VisionCallback() { @Override public void onFound(final Barcode barcode) { runOnUiThread(new Runnable() { public void run() { // TODO: Show dialog only once if(barcode.format == Barcode.QR_CODE) { showConfirmationDialog(barcode.rawValue); } } }); } }); barcodeDetector.setProcessor(new MultiProcessor.Builder<>(barcodeFactory).build()); mCameraSource = new CameraSource.Builder(this, barcodeDetector) .setFacing(CameraSource.CAMERA_FACING_BACK) .setRequestedPreviewSize(1600, 1024) .build(); } //starting the preview private void startCameraSource() { try { mPreview.start(mCameraSource, mGraphicOverlay); } catch (IOException e) { mCameraSource.release(); mCameraSource = null; } } @Override protected void onResume() { super.onResume(); startCameraSource(); //start } @Override protected void onPause() { super.onPause(); mPreview.stop(); //stop } @Override protected void onDestroy() { super.onDestroy(); mCameraSource.release(); //release the resources } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); switch (id) { case R.id.action_enter_email: showEmailDialog(); return true; case R.id.action_settings: startActivity(new Intent(this, PreferencesActivity.class)); return true; } return super.onOptionsItemSelected(item); } private void checkIfShowWelcomeActivity() { if (PreferencesUtils.getFirstLaunch(this) || PreferencesUtils.getVolunteerId(this).isEmpty()) { startActivity(new Intent(this, WelcomeActivity.class)); finish(); } } private void showEmailDialog() { final Dialog dialog = new Dialog(this); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setContentView(R.layout.dialog_email); WindowManager.LayoutParams params = dialog.getWindow().getAttributes(); params.width = WindowManager.LayoutParams.MATCH_PARENT; dialog.getWindow().setAttributes(params); dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); dialog.show(); final EditText emailEditText = (EditText) dialog.findViewById(R.id.emailDialogEditText); emailEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_DONE) { dialog.dismiss(); showConfirmationDialog(emailEditText.getText().toString()); } return true; } }); dialog.findViewById(R.id.emailDialogCancel).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); } }); dialog.findViewById(R.id.emailDialogOk).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); showConfirmationDialog(emailEditText.getText().toString()); } }); } private void showConfirmationDialog(String email) { AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.AppCompatAlertDialogStyle); builder.setTitle(R.string.dialog_verify_title); builder.setMessage(email); builder.setPositiveButton(R.string.dialog_verify_approve, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO: Notify Nucleus dialog.dismiss(); } }); builder.setNegativeButton(R.string.dialog_verify_deny, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.show(); } }
Show confirmation dialog only once
app/src/main/java/com/hacktx/electron/activities/MainActivity.java
Show confirmation dialog only once
Java
mpl-2.0
5ae44f4ff03a18fdfdb25a6f7feae22e9091ea53
0
JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core
/************************************************************************* * * $RCSfile: UnoDialog2.java,v $ * * $Revision: 1.6 $ * * last change: $Author: vg $ $Date: 2005-03-08 15:46:25 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * */ package com.sun.star.wizards.ui; import java.awt.Color; import com.sun.star.awt.*; import com.sun.star.beans.XPropertySet; import com.sun.star.lang.IllegalArgumentException; import com.sun.star.lang.XMultiServiceFactory; import com.sun.star.uno.AnyConverter; import com.sun.star.uno.UnoRuntime; import com.sun.star.uno.XInterface; import com.sun.star.wizards.common.Helper; import com.sun.star.wizards.common.SystemDialog; import com.sun.star.wizards.ui.event.*; /** * This class contains convenience methods for inserting components to a dialog. * It was created for use with the automatic conversion of Basic XML Dialog * description files to a Java class which builds the same dialog through the UNO API.<br/> * It uses an Event-Listener method, which calls a method through reflection * wenn an event on a component is trigered. * see the classes AbstractListener, CommonListener, MethodInvocation for details. */ public class UnoDialog2 extends UnoDialog implements EventNames { public AbstractListener guiEventListener; /** * Override this method to return another listener. */ protected AbstractListener createListener() { return new CommonListener(); } public UnoDialog2(XMultiServiceFactory xmsf) { super(xmsf, new String[] { }, new Object[] { }); guiEventListener = createListener(); } public XButton insertButton(String sName, String actionPerformed, Object eventTarget, String[] sPropNames, Object[] oPropValues) { XButton xButton = (XButton) insertControlModel2("com.sun.star.awt.UnoControlButtonModel", sName, sPropNames, oPropValues, XButton.class); if (actionPerformed != null) { xButton.addActionListener((XActionListener) guiEventListener); guiEventListener.add(sName, EVENT_ACTION_PERFORMED, actionPerformed, eventTarget); } return xButton; } public XButton insertButton(String sName, String actionPerformed, String[] sPropNames, Object[] oPropValues) { return insertButton(sName, actionPerformed, this, sPropNames, oPropValues); } public XCheckBox insertCheckBox(String sName, String itemChanged, Object eventTarget, String[] sPropNames, Object[] oPropValues) { XCheckBox xCheckBox = (XCheckBox) insertControlModel2("com.sun.star.awt.UnoControlCheckBoxModel", sName, sPropNames, oPropValues, XCheckBox.class); if (itemChanged != null) { xCheckBox.addItemListener((XItemListener) guiEventListener); guiEventListener.add(sName, EVENT_ITEM_CHANGED, itemChanged, eventTarget); } return xCheckBox; } public XCheckBox insertCheckBox(String sName, String itemChanged, String[] sPropNames, Object[] oPropValues) { return insertCheckBox(sName, itemChanged, this, sPropNames, oPropValues); } public XComboBox insertComboBox(String sName, String actionPerformed, String itemChanged, String textChanged, Object eventTarget, String[] sPropNames, Object[] oPropValues) { XComboBox xComboBox = (XComboBox) insertControlModel2("com.sun.star.awt.UnoControlComboBoxModel", sName, sPropNames, oPropValues, XComboBox.class); if (actionPerformed != null) { xComboBox.addActionListener((XActionListener) guiEventListener); guiEventListener.add(sName, EVENT_ACTION_PERFORMED, actionPerformed, eventTarget); } if (itemChanged != null) { xComboBox.addItemListener((XItemListener) guiEventListener); guiEventListener.add(sName, EVENT_ITEM_CHANGED, itemChanged, eventTarget); } if (textChanged != null) { XTextComponent xTextComponent = (XTextComponent) UnoRuntime.queryInterface(XTextComponent.class,xComboBox); xTextComponent.addTextListener((XTextListener)guiEventListener); guiEventListener.add(sName,EVENT_TEXT_CHANGED, textChanged, eventTarget); } return xComboBox; } public XComboBox insertComboBox(String sName, String actionPerformed, String itemChanged, String textChanged, String[] sPropNames, Object[] oPropValues) { return insertComboBox(sName, actionPerformed, textChanged, itemChanged, this, sPropNames, oPropValues); } public XListBox insertListBox(String sName, String actionPerformed, String itemChanged, Object eventTarget, String[] sPropNames, Object[] oPropValues) { XListBox xListBox = (XListBox) insertControlModel2("com.sun.star.awt.UnoControlListBoxModel", sName, sPropNames, oPropValues, XListBox.class); if (actionPerformed != null) { xListBox.addActionListener((XActionListener) guiEventListener); guiEventListener.add(sName, EVENT_ACTION_PERFORMED, actionPerformed, eventTarget); } if (itemChanged != null) { xListBox.addItemListener((XItemListener) guiEventListener); guiEventListener.add(sName, EVENT_ITEM_CHANGED, itemChanged, eventTarget); } return xListBox; } public XListBox insertListBox(String sName, String actionPerformed, String itemChanged, String[] sPropNames, Object[] oPropValues) { return insertListBox(sName, actionPerformed, itemChanged, this, sPropNames, oPropValues); } public XRadioButton insertRadioButton(String sName, String itemChanged, Object eventTarget, String[] sPropNames, Object[] oPropValues) { XRadioButton xRadioButton = (XRadioButton) insertControlModel2("com.sun.star.awt.UnoControlRadioButtonModel", sName, sPropNames, oPropValues, XRadioButton.class); if (itemChanged != null) { xRadioButton.addItemListener((XItemListener) guiEventListener); guiEventListener.add(sName, EVENT_ITEM_CHANGED, itemChanged, eventTarget); } return xRadioButton; } public XRadioButton insertRadioButton(String sName, String itemChanged, String[] sPropNames, Object[] oPropValues) { return insertRadioButton(sName, itemChanged, this, sPropNames, oPropValues); } public XControl insertTitledBox(String sName, String[] sPropNames, Object[] oPropValues) { Object oTitledBox = insertControlModel2("com.sun.star.awt.UnoControlGroupBoxModel", sName, sPropNames, oPropValues); return (XControl) UnoRuntime.queryInterface(XControl.class, oTitledBox); } public XTextComponent insertTextField(String sName, String sTextChanged, Object eventTarget, String[] sPropNames, Object[] oPropValues) { return (XTextComponent) insertEditField(sName, sTextChanged, eventTarget, "com.sun.star.awt.UnoControlEditModel", sPropNames, oPropValues, XTextComponent.class); } public XTextComponent insertTextField(String sName, String sTextChanged, String[] sPropNames, Object[] oPropValues) { return insertTextField(sName, sTextChanged, this, sPropNames, oPropValues); } public XControl insertImage(String sName, String[] sPropNames, Object[] oPropValues) { return (XControl) insertControlModel2("com.sun.star.awt.UnoControlImageControlModel", sName, sPropNames, oPropValues, XControl.class); } public XControl insertInfoImage(int _posx, int _posy, int _iStep){ return insertImage("imgHint", new String[] {"Border", "Height", "ImageURL", "PositionX", "PositionY", "ScaleImage", "Step","Width"}, new Object[] { new Short((short)0), new Integer(10), UIConsts.INFOIMAGEURL, new Integer(_posx), new Integer(_posy), Boolean.FALSE, new Integer(_iStep), new Integer(10)}); } /** * This method is used for creating Edit, Currency, Date, Formatted, Pattern, File * and Time edit components. */ private Object insertEditField(String sName, String sTextChanged, Object eventTarget, String sModelClass, String[] sPropNames, Object[] oPropValues, Class type) { XTextComponent xField = (XTextComponent) insertControlModel2(sModelClass, sName, sPropNames, oPropValues, XTextComponent.class); if (sTextChanged != null) { xField.addTextListener((XTextListener) guiEventListener); guiEventListener.add(sName, EVENT_TEXT_CHANGED, sTextChanged, eventTarget); } return UnoRuntime.queryInterface(type, xField); } public XControl insertFileControl(String sName, String sTextChanged, Object eventTarget, String[] sPropNames, Object[] oPropValues) { return (XControl) insertEditField(sName, sTextChanged, eventTarget, "com.sun.star.awt.UnoControlFileControlModel", sPropNames, oPropValues, XControl.class); } public XControl insertFileControl(String sName, String sTextChanged, String[] sPropNames, Object[] oPropValues) { return insertFileControl(sName, sTextChanged, this, sPropNames, oPropValues); } public XCurrencyField insertCurrencyField(String sName, String sTextChanged, Object eventTarget, String[] sPropNames, Object[] oPropValues) { return (XCurrencyField) insertEditField(sName, sTextChanged, eventTarget, "com.sun.star.awt.UnoControlCurrencyFieldModel", sPropNames, oPropValues, XCurrencyField.class); } public XCurrencyField insertCurrencyField(String sName, String sTextChanged, String[] sPropNames, Object[] oPropValues) { return insertCurrencyField(sName, sTextChanged, this, sPropNames, oPropValues); } public XDateField insertDateField(String sName, String sTextChanged, Object eventTarget, String[] sPropNames, Object[] oPropValues) { return (XDateField) insertEditField(sName, sTextChanged, eventTarget, "com.sun.star.awt.UnoControlDateFieldModel", sPropNames, oPropValues, XDateField.class); } public XDateField insertDateField(String sName, String sTextChanged, String[] sPropNames, Object[] oPropValues) { return insertDateField(sName, sTextChanged, this, sPropNames, oPropValues); } public XNumericField insertNumericField(String sName, String sTextChanged, Object eventTarget, String[] sPropNames, Object[] oPropValues) { return (XNumericField) insertEditField(sName, sTextChanged, eventTarget, "com.sun.star.awt.UnoControlNumericFieldModel", sPropNames, oPropValues, XNumericField.class); } public XNumericField insertNumericField(String sName, String sTextChanged, String[] sPropNames, Object[] oPropValues) { return insertNumericField(sName, sTextChanged, this, sPropNames, oPropValues); } public XTimeField insertTimeField(String sName, String sTextChanged, Object eventTarget, String[] sPropNames, Object[] oPropValues) { return (XTimeField) insertEditField(sName, sTextChanged, eventTarget, "com.sun.star.awt.UnoControlTimeFieldModel", sPropNames, oPropValues, XTimeField.class); } public XTimeField insertTimeField(String sName, String sTextChanged, String[] sPropNames, Object[] oPropValues) { return insertTimeField(sName, sTextChanged, this, sPropNames, oPropValues); } public XPatternField insertPatternField(String sName, String sTextChanged, Object eventTarget, String[] sPropNames, Object[] oPropValues) { return (XPatternField) insertEditField(sName, sTextChanged, eventTarget, "com.sun.star.awt.UnoControlPatternFieldModel", sPropNames, oPropValues, XPatternField.class); } public XPatternField insertPatternField(String sName, String sTextChanged, String[] sPropNames, Object[] oPropValues) { return insertPatternField(sName, sTextChanged, this, sPropNames, oPropValues); } public XTextComponent insertFormattedField(String sName, String sTextChanged, Object eventTarget, String[] sPropNames, Object[] oPropValues) { return (XTextComponent) insertEditField(sName, sTextChanged, eventTarget, "com.sun.star.awt.UnoControlFormattedFieldModel", sPropNames, oPropValues, XTextComponent.class); } public XTextComponent insertFormattedField(String sName, String sTextChanged, String[] sPropNames, Object[] oPropValues) { return insertFormattedField(sName, sTextChanged, this, sPropNames, oPropValues); } public XControl insertFixedLine(String sName, String[] sPropNames, Object[] oPropValues) { Object oLine = insertControlModel2("com.sun.star.awt.UnoControlFixedLineModel", sName, sPropNames, oPropValues); return (XControl) UnoRuntime.queryInterface(XControl.class, oLine); } public XScrollBar insertScrollBar(String sName, String[] sPropNames, Object[] oPropValues) { Object oScrollBar = insertControlModel2("com.sun.star.awt.UnoControlScrollBarModel", sName, sPropNames, oPropValues); return (XScrollBar) UnoRuntime.queryInterface(XScrollBar.class, oScrollBar); } public XProgressBar insertProgressBar(String sName, String[] sPropNames, Object[] oPropValues) { Object oProgressBar = insertControlModel2("com.sun.star.awt.UnoControlProgressBarModel", sName, sPropNames, oPropValues); return (XProgressBar) UnoRuntime.queryInterface(XProgressBar.class, oProgressBar); } public XControl insertGroupBox(String sName, String[] sPropNames, Object[] oPropValues) { Object oGroupBox = insertControlModel2("com.sun.star.awt.UnoControlGroupBoxModel", sName, sPropNames, oPropValues); return (XControl) UnoRuntime.queryInterface(XControl.class, oGroupBox); } public Object insertControlModel2(String serviceName, String componentName, String[] sPropNames, Object[] oPropValues) { try { //System.out.println("Inserting : " + componentName); XInterface xControlModel = insertControlModel(serviceName, componentName, new String[] { }, new Object[] { }); Helper.setUnoPropertyValues(xControlModel, sPropNames, oPropValues); //setControlPropertiesDebug(xControlModel, sPropNames, oPropValues); //System.out.println(" Setting props successfull !"); Helper.setUnoPropertyValue(xControlModel, "Name", componentName); } catch (Exception ex) { ex.printStackTrace(); } return xDlgContainer.getControl(componentName); } private void setControlPropertiesDebug(Object model, String[] names, Object[] values) { for (int i = 0; i<names.length; i++) { System.out.println(" Settings: " + names[i]); Helper.setUnoPropertyValue(model,names[i],values[i]); } } public Object insertControlModel2(String serviceName, String componentName, String[] sPropNames, Object[] oPropValues, Class type) { return UnoRuntime.queryInterface(type, insertControlModel2(serviceName, componentName, sPropNames, oPropValues)); } public String translateURL(String relativeURL) { return ""; } public static Object getControlModel(Object unoControl) { Object obj = ((XControl) UnoRuntime.queryInterface(XControl.class, unoControl)).getModel(); return obj; } public int showMessageBox(String windowServiceName, int windowAttribute, String MessageText) { return SystemDialog.showMessageBox(xMSF, this.xControl.getPeer(), windowServiceName, windowAttribute, MessageText); } }
wizards/com/sun/star/wizards/ui/UnoDialog2.java
/************************************************************************* * * $RCSfile: UnoDialog2.java,v $ * * $Revision: 1.5 $ * * last change: $Author: vg $ $Date: 2005-02-21 14:07:05 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * */ package com.sun.star.wizards.ui; import java.awt.Color; import com.sun.star.awt.*; import com.sun.star.beans.XPropertySet; import com.sun.star.lang.IllegalArgumentException; import com.sun.star.lang.XMultiServiceFactory; import com.sun.star.uno.AnyConverter; import com.sun.star.uno.UnoRuntime; import com.sun.star.uno.XInterface; import com.sun.star.wizards.common.Helper; import com.sun.star.wizards.common.SystemDialog; import com.sun.star.wizards.ui.event.*; /** * This class contains convenience methods for inserting components to a dialog. * It was created for use with the automatic conversion of Basic XML Dialog * description files to a Java class which builds the same dialog through the UNO API.<br/> * It uses an Event-Listener method, which calls a method through reflection * wenn an event on a component is trigered. * see the classes AbstractListener, CommonListener, MethodInvocation for details. */ public class UnoDialog2 extends UnoDialog implements EventNames { public AbstractListener guiEventListener; /** * Override this method to return another listener. */ protected AbstractListener createListener() { return new CommonListener(); } public UnoDialog2(XMultiServiceFactory xmsf) { super(xmsf, new String[] { }, new Object[] { }); guiEventListener = createListener(); } public XButton insertButton(String sName, String actionPerformed, Object eventTarget, String[] sPropNames, Object[] oPropValues) { XButton xButton = (XButton) insertControlModel2("com.sun.star.awt.UnoControlButtonModel", sName, sPropNames, oPropValues, XButton.class); if (actionPerformed != null) { xButton.addActionListener((XActionListener) guiEventListener); guiEventListener.add(sName, EVENT_ACTION_PERFORMED, actionPerformed, eventTarget); } return xButton; } public XButton insertButton(String sName, String actionPerformed, String[] sPropNames, Object[] oPropValues) { return insertButton(sName, actionPerformed, this, sPropNames, oPropValues); } public XCheckBox insertCheckBox(String sName, String itemChanged, Object eventTarget, String[] sPropNames, Object[] oPropValues) { XCheckBox xCheckBox = (XCheckBox) insertControlModel2("com.sun.star.awt.UnoControlCheckBoxModel", sName, sPropNames, oPropValues, XCheckBox.class); if (itemChanged != null) { xCheckBox.addItemListener((XItemListener) guiEventListener); guiEventListener.add(sName, EVENT_ITEM_CHANGED, itemChanged, eventTarget); } return xCheckBox; } public XCheckBox insertCheckBox(String sName, String itemChanged, String[] sPropNames, Object[] oPropValues) { return insertCheckBox(sName, itemChanged, this, sPropNames, oPropValues); } public XComboBox insertComboBox(String sName, String actionPerformed, String itemChanged, String textChanged, Object eventTarget, String[] sPropNames, Object[] oPropValues) { XComboBox xComboBox = (XComboBox) insertControlModel2("com.sun.star.awt.UnoControlComboBoxModel", sName, sPropNames, oPropValues, XComboBox.class); if (actionPerformed != null) { xComboBox.addActionListener((XActionListener) guiEventListener); guiEventListener.add(sName, EVENT_ACTION_PERFORMED, actionPerformed, eventTarget); } if (itemChanged != null) { xComboBox.addItemListener((XItemListener) guiEventListener); guiEventListener.add(sName, EVENT_ITEM_CHANGED, itemChanged, eventTarget); } if (textChanged != null) { XTextComponent xTextComponent = (XTextComponent) UnoRuntime.queryInterface(XTextComponent.class,xComboBox); xTextComponent.addTextListener((XTextListener)guiEventListener); guiEventListener.add(sName,EVENT_TEXT_CHANGED, textChanged, eventTarget); } return xComboBox; } public XComboBox insertComboBox(String sName, String actionPerformed, String itemChanged, String textChanged, String[] sPropNames, Object[] oPropValues) { return insertComboBox(sName, actionPerformed, textChanged, itemChanged, this, sPropNames, oPropValues); } public XListBox insertListBox(String sName, String actionPerformed, String itemChanged, Object eventTarget, String[] sPropNames, Object[] oPropValues) { XListBox xListBox = (XListBox) insertControlModel2("com.sun.star.awt.UnoControlListBoxModel", sName, sPropNames, oPropValues, XListBox.class); if (actionPerformed != null) { xListBox.addActionListener((XActionListener) guiEventListener); guiEventListener.add(sName, EVENT_ACTION_PERFORMED, actionPerformed, eventTarget); } if (itemChanged != null) { xListBox.addItemListener((XItemListener) guiEventListener); guiEventListener.add(sName, EVENT_ITEM_CHANGED, itemChanged, eventTarget); } return xListBox; } public XListBox insertListBox(String sName, String actionPerformed, String itemChanged, String[] sPropNames, Object[] oPropValues) { return insertListBox(sName, actionPerformed, itemChanged, this, sPropNames, oPropValues); } public XRadioButton insertRadioButton(String sName, String itemChanged, Object eventTarget, String[] sPropNames, Object[] oPropValues) { XRadioButton xRadioButton = (XRadioButton) insertControlModel2("com.sun.star.awt.UnoControlRadioButtonModel", sName, sPropNames, oPropValues, XRadioButton.class); if (itemChanged != null) { xRadioButton.addItemListener((XItemListener) guiEventListener); guiEventListener.add(sName, EVENT_ITEM_CHANGED, itemChanged, eventTarget); } return xRadioButton; } public XRadioButton insertRadioButton(String sName, String itemChanged, String[] sPropNames, Object[] oPropValues) { return insertRadioButton(sName, itemChanged, this, sPropNames, oPropValues); } public XControl insertTitledBox(String sName, String[] sPropNames, Object[] oPropValues) { Object oTitledBox = insertControlModel2("com.sun.star.awt.UnoControlGroupBoxModel", sName, sPropNames, oPropValues); return (XControl) UnoRuntime.queryInterface(XControl.class, oTitledBox); } public XTextComponent insertTextField(String sName, String sTextChanged, Object eventTarget, String[] sPropNames, Object[] oPropValues) { return (XTextComponent) insertEditField(sName, sTextChanged, eventTarget, "com.sun.star.awt.UnoControlEditModel", sPropNames, oPropValues, XTextComponent.class); } public XTextComponent insertTextField(String sName, String sTextChanged, String[] sPropNames, Object[] oPropValues) { return insertTextField(sName, sTextChanged, this, sPropNames, oPropValues); } public XControl insertImage(String sName, String[] sPropNames, Object[] oPropValues) { return (XControl) insertControlModel2("com.sun.star.awt.UnoControlImageControlModel", sName, sPropNames, oPropValues, XControl.class); } public XControl insertInfoImage(int _posx, int _posy, int _iStep){ return insertImage("imgHint", new String[] {"Border", "Height", "ImageURL", "PositionX", "PositionY", "ScaleImage", "Step","Width"}, new Object[] { new Short((short)0), new Integer(10), UIConsts.INFOIMAGEURL, new Integer(_posx), new Integer(_posy), Boolean.FALSE, new Integer(_iStep), new Integer(10)}); } /** * This method is used for creating Edit, Currency, Date, Formatted, Pattern, File * and Time edit components. */ private Object insertEditField(String sName, String sTextChanged, Object eventTarget, String sModelClass, String[] sPropNames, Object[] oPropValues, Class type) { XTextComponent xField = (XTextComponent) insertControlModel2(sModelClass, sName, sPropNames, oPropValues, XTextComponent.class); if (sTextChanged != null) { xField.addTextListener((XTextListener) guiEventListener); guiEventListener.add(sName, EVENT_TEXT_CHANGED, sTextChanged, eventTarget); } return UnoRuntime.queryInterface(type, xField); } public XControl insertFileControl(String sName, String sTextChanged, Object eventTarget, String[] sPropNames, Object[] oPropValues) { return (XControl) insertEditField(sName, sTextChanged, eventTarget, "com.sun.star.awt.UnoControlFileControlModel", sPropNames, oPropValues, XControl.class); } public XControl insertFileControl(String sName, String sTextChanged, String[] sPropNames, Object[] oPropValues) { return insertFileControl(sName, sTextChanged, this, sPropNames, oPropValues); } public XCurrencyField insertCurrencyField(String sName, String sTextChanged, Object eventTarget, String[] sPropNames, Object[] oPropValues) { return (XCurrencyField) insertEditField(sName, sTextChanged, eventTarget, "com.sun.star.awt.UnoControlCurrencyFieldModel", sPropNames, oPropValues, XCurrencyField.class); } public XCurrencyField insertCurrencyField(String sName, String sTextChanged, String[] sPropNames, Object[] oPropValues) { return insertCurrencyField(sName, sTextChanged, this, sPropNames, oPropValues); } public XDateField insertDateField(String sName, String sTextChanged, Object eventTarget, String[] sPropNames, Object[] oPropValues) { return (XDateField) insertEditField(sName, sTextChanged, eventTarget, "com.sun.star.awt.UnoControlDateFieldModel", sPropNames, oPropValues, XDateField.class); } public XDateField insertDateField(String sName, String sTextChanged, String[] sPropNames, Object[] oPropValues) { return insertDateField(sName, sTextChanged, this, sPropNames, oPropValues); } public XNumericField insertNumericField(String sName, String sTextChanged, Object eventTarget, String[] sPropNames, Object[] oPropValues) { return (XNumericField) insertEditField(sName, sTextChanged, eventTarget, "com.sun.star.awt.UnoControlNumericFieldModel", sPropNames, oPropValues, XNumericField.class); } public XNumericField insertNumericField(String sName, String sTextChanged, String[] sPropNames, Object[] oPropValues) { return insertNumericField(sName, sTextChanged, this, sPropNames, oPropValues); } public XTimeField insertTimeField(String sName, String sTextChanged, Object eventTarget, String[] sPropNames, Object[] oPropValues) { return (XTimeField) insertEditField(sName, sTextChanged, eventTarget, "com.sun.star.awt.UnoControlTimeFieldModel", sPropNames, oPropValues, XTimeField.class); } public XTimeField insertTimeField(String sName, String sTextChanged, String[] sPropNames, Object[] oPropValues) { return insertTimeField(sName, sTextChanged, this, sPropNames, oPropValues); } public XPatternField insertPatternField(String sName, String sTextChanged, Object eventTarget, String[] sPropNames, Object[] oPropValues) { return (XPatternField) insertEditField(sName, sTextChanged, eventTarget, "com.sun.star.awt.UnoControlPatternFieldModel", sPropNames, oPropValues, XPatternField.class); } public XPatternField insertPatternField(String sName, String sTextChanged, String[] sPropNames, Object[] oPropValues) { return insertPatternField(sName, sTextChanged, this, sPropNames, oPropValues); } public XTextComponent insertFormattedField(String sName, String sTextChanged, Object eventTarget, String[] sPropNames, Object[] oPropValues) { return (XTextComponent) insertEditField(sName, sTextChanged, eventTarget, "com.sun.star.awt.UnoControlFormattedFieldModel", sPropNames, oPropValues, XTextComponent.class); } public XTextComponent insertFormattedField(String sName, String sTextChanged, String[] sPropNames, Object[] oPropValues) { return insertFormattedField(sName, sTextChanged, this, sPropNames, oPropValues); } public XControl insertFixedLine(String sName, String[] sPropNames, Object[] oPropValues) { Object oLine = insertControlModel2("com.sun.star.awt.UnoControlFixedLineModel", sName, sPropNames, oPropValues); return (XControl) UnoRuntime.queryInterface(XControl.class, oLine); } public XScrollBar insertScrollBar(String sName, String[] sPropNames, Object[] oPropValues) { Object oScrollBar = insertControlModel2("com.sun.star.awt.UnoControlScrollBarModel", sName, sPropNames, oPropValues); return (XScrollBar) UnoRuntime.queryInterface(XScrollBar.class, oScrollBar); } public XProgressBar insertProgressBar(String sName, String[] sPropNames, Object[] oPropValues) { Object oProgressBar = insertControlModel2("com.sun.star.awt.UnoControlProgressBarModel", sName, sPropNames, oPropValues); return (XProgressBar) UnoRuntime.queryInterface(XProgressBar.class, oProgressBar); } public XControl insertGroupBox(String sName, String[] sPropNames, Object[] oPropValues) { Object oGroupBox = insertControlModel2("com.sun.star.awt.UnoControlGroupBoxModel", sName, sPropNames, oPropValues); return (XControl) UnoRuntime.queryInterface(XControl.class, oGroupBox); } public Object insertControlModel2(String serviceName, String componentName, String[] sPropNames, Object[] oPropValues) { try { //System.out.println("Inserting : " + componentName); XInterface xControlModel = insertControlModel(serviceName, componentName, new String[] { }, new Object[] { }); Helper.setUnoPropertyValues(xControlModel, sPropNames, oPropValues); //setControlPropertiesDebug(xControlModel, sPropNames, oPropValues); //System.out.println(" Setting props successfull !"); Helper.setUnoPropertyValue(xControlModel, "Name", componentName); } catch (Exception ex) { ex.printStackTrace(); } return xDlgContainer.getControl(componentName); } private void setControlPropertiesDebug(Object model, String[] names, Object[] values) { for (int i = 0; i<names.length; i++) { System.out.println(" Settings: " + names[i]); Helper.setUnoPropertyValue(model,names[i],values[i]); } } public Object insertControlModel2(String serviceName, String componentName, String[] sPropNames, Object[] oPropValues, Class type) { return UnoRuntime.queryInterface(type, insertControlModel2(serviceName, componentName, sPropNames, oPropValues)); } public String translateURL(String relativeURL) { return ""; } public static Object getControlModel(Object unoControl) { Object obj = ((XControl) UnoRuntime.queryInterface(XControl.class, unoControl)).getModel(); return obj; } public int showMessageBox(String windowServiceName, int windowAttribute, String MessageText) { return SystemDialog.showMessageBox(xMSF, this.xControl.getPeer(), windowServiceName, windowAttribute, MessageText); } }
INTEGRATION: CWS toolkit01 (1.4.50); FILE MERGED 2005/02/25 12:08:36 bc 1.4.50.2: RESYNC: (1.4-1.5); FILE MERGED 2005/02/23 17:38:47 bc 1.4.50.1: ##several changes in Webwizard
wizards/com/sun/star/wizards/ui/UnoDialog2.java
INTEGRATION: CWS toolkit01 (1.4.50); FILE MERGED 2005/02/25 12:08:36 bc 1.4.50.2: RESYNC: (1.4-1.5); FILE MERGED 2005/02/23 17:38:47 bc 1.4.50.1: ##several changes in Webwizard
Java
mpl-2.0
edd6e53a2d22acbe6d1bae06f3b29b865b84afe1
0
MatjazDev/Numerus,TheMatjaz/jNumerus
/* * Copyright (c) 2015, Matjaž <[email protected]> matjaz.it * * This Source Code Form is part of the project Numerus, a roman numerals * library for Java. The library and its source code may be found on: * https://github.com/MatjazDev/Numerus and http://matjaz.it/numerus * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/ */ package it.matjaz.numerus.core; import java.io.Serializable; import java.util.Objects; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * A container for syntactically correct roman numerals saved as strings. * <p> * This class saves a string passed though the constructor or the setter if and * only if is a roman number with a correct syntax, which happens if the string * matches the {@link #CORRECT_ROMAN_SYNTAX_REGEX}. * <p> * Any string with other characters, different order, too many characters or * anyhow incorrect syntax gets refused with {@link NumberFormatException}, * which may contain some indication of the syntax error in the Exception * message. * <p> * The structure of a syntactically roman numeral is composed of the following * characters <i>in this order</i>: * <ol> * <ul>0-3 <b>M</b></ul> * <ul>0-1 <b>CM</b> or 0-1 <b>CD</b> or ( 0-1 <b>D</b> and 0-3 <b>C</b> )</ul> * <ul>0-1 <b>XC</b> or 0-1 <b>XL</b> or ( 0-1 <b>L</b> and 0-3 <b>X</b> )</ul> * <ul>0-1 <b>IX</b> or 0-1 <b>IV</b> or ( 0-1 <b>V</b> and 0-3 <b>I</b> )</ul> * </ol> * <p> * For the integer values of the symbols, see {@link RomanCharMapFactory}. * * @author Matjaž <a href="mailto:[email protected]">[email protected]</a> * <a href="http://matjaz.it">www.matjaz.it</a> */ public class RomanNumeral implements Serializable, Cloneable, CharSequence { /** * The passed string representing the roman numeral. * * It is a serializable field. */ private String numeral; /** * Big regex matching all syntactically correct roman numerals. * <p> * Contains all possible cases of roman numerals. If a string does not match * this regex, then is not a roman numeral. The structure of a syntactically * roman numeral is composed of the following numeral <i>in this order</i>: * <ol> * <ul>0-3 <b>M</b></ul> * <ul>0-1 <b>CM</b> or 0-1 <b>CD</b> or ( 0-1 <b>D</b> and 0-3 <b>C</b> * )</ul> * <ul>0-1 <b>XC</b> or 0-1 <b>XL</b> or ( 0-1 <b>L</b> and 0-3 <b>X</b> * )</ul> * <ul>0-1 <b>IX</b> or 0-1 <b>IV</b> or ( 0-1 <b>V</b> and 0-3 <b>I</b> * )</ul> * </ol> * <p> * <a href="http://stackoverflow.com/a/267405">Source of the idea</a> of * this regex with a great explanation. */ public final String CORRECT_ROMAN_SYNTAX_REGEX = "^(M{0,3})(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$"; /** * Regex matching any non roman characters. * <p> * If a string contains any character matching with this regex, then is not * a roman numeral, because contains illegal characters. */ public final String NON_ROMAN_CHARS_REGEX = "[^MDCLXVI]"; /** * Regex matching four consecutive characters M or C or X or I. */ private final String FOUR_CONSECUTIVE_TEN_LIKE_CHARS_REGEX = "(MMMM|CCCC|XXXX|IIII)"; /** * Regex matching two characters D or L or V in the same string. */ private final String TWO_SAME_FIVE_LIKE_CHARS_REGEX = "(D.*D|L.*L|V.*V)"; /** * Serializable class version number. * <p> * It is used during deserialization to verify that the sender and receiver * of a serialized object have loaded classes for that object that are * compatible with respect to serialization. * <p> * This UID is a date and all objects stored before this date won't be * compatible with older ones. * [<a href="http://c2.com/ppr/wiki/JavaIdioms/AlwaysDeclareSerialVersionUid.html">Source * of the idea</a>] * * @see Serializable */ private static final long serialVersionUID = 20150422L; /** * Constructs an empty RomanNumeral. * <p> * Contains no value so {@link #setNumeral(java.lang.String) the setter} * needs to be used before using the RomanNumeral. Calling this method and * then the setter leads to the same result. */ public RomanNumeral() { this.numeral = ""; } /** * Constructs a RomanNumeral with initialized value. * <p> * The passed string gets checked for syntax correctness. If the syntax is * illegal, then a {@link NumberFormatException} is thrown. * <p> * Whitespace charactes in the passed String are removed and the characters * are upcased. * * @param symbols the initial roman numeral to be stored. */ public RomanNumeral(String symbols) { this.numeral = cleanUpcaseAndSyntaxCheckString(symbols); } /** * Getter of the roman numerals String. * <p> * If RomanNumeral is not initialized, the returned String is <b>empty</b>. * * @return a String containing the roman numeral. */ public String getNumeral() { return numeral; } /** * Checks if this RomanNumeral contains a numeral or not. * <p> * Returns <code>true</code> if this RomanNumeal has a roman numeral stored * in it, else <code>false</code> if contains just an empty string. The * verification is done by confronting an empty String with the result of * the {@link #getNumeral() getter}. The only way it can contain an empty * string is to be initialized with the * {@link #RomanNumeral() default constructor} (the one without parameters) * without setting the value after that with the * {@link #setNumeral(java.lang.String) setter}. * * @return <code>true</code> has a roman numeral stored in it, else * <code>false</code> if it's empty. */ public boolean isInitialized() { return !"".equals(getNumeral()); } /** * Setter of the roman numerals String. * <p> * The passed string gets checked for syntax correctness. If the syntax is * illegal, then a {@link NumberFormatException} is thrown. * <p> * Whitespace charactes in the passed String are removed and the characters * are upcased. * * @param numeral the new roman numeral to be stored. */ public void setNumeral(String numeral) { this.numeral = cleanUpcaseAndSyntaxCheckString(numeral); } /** * Performs a check of the syntax of the given roman numeral without storing * it in a RomanNumeral. * <p> * Returns <code>true</code> if the passed String matches the syntax of * roman numerals; else <code>false</code>. Useful to just quickly check if * a String is a roman numeral when an instance of it is not needed. If the * result is <code>true</code>, then the passed String can be successfully * stored in a RomanNumeral by * {@link #RomanNumeral(java.lang.String) constructor} or * {@link #setNumeral(java.lang.String) setter}. * * @param numeralsToCheck the String to check the roman syntax on. * @return <code>true</code> if the passed String is a roman numeral; else * <code>false</code>. */ public static boolean isCorrectRomanSyntax(String numeralsToCheck) { try { new RomanNumeral().cleanUpcaseAndSyntaxCheckString(numeralsToCheck); return true; } catch (NumberFormatException ex) { return false; } } /** * Removes all whitespace characters, upcases the String and verifies the * roman syntax. * <p> * If the syntax does not match, an exception is thrown. * * @param symbols string to be cleaned, upcased and checked. * @return given string without whitespaces and upcased. */ private String cleanUpcaseAndSyntaxCheckString(String symbols) { String cleanSymbols = symbols.replaceAll("\\s+", "").toUpperCase(); throwExceptionIfIllegalRomanSyntax(cleanSymbols); return cleanSymbols; } /** * Finds all the substrings of the given string matching the regex. * <p> * Check for all substring of <code>textToParse</code> matching the * <code>regex</code>, appends them sequentially to a String and returns it. * <p> * <a href="http://stackoverflow.com/a/5705591">Source of the idea</a> of * the algorithm. * * @param textToParse String to be checked for matches. * @param regex to be searched in <code>textToParse</code> * @return a String containing all the matches. */ private static String findAllRegexMatchingSubstrings(String textToParse, String regex) { StringBuilder matches = new StringBuilder(); Matcher matcher = Pattern.compile(regex).matcher(textToParse); while (matcher.find()) { matches.append(matcher.group()); } return matches.toString(); } private void throwExceptionIfIllegalRomanSyntax(String symbols) { if (symbols.isEmpty()) { throw new NumberFormatException("Empty roman numeral."); } if (symbols.length() >= 20) { throw new NumberFormatException("Impossibly long roman numeral."); } if (!symbols.matches(CORRECT_ROMAN_SYNTAX_REGEX)) { String illegalChars; illegalChars = findAllRegexMatchingSubstrings(symbols, NON_ROMAN_CHARS_REGEX); if (!illegalChars.isEmpty()) { throw new NumberFormatException("Non roman characters: " + illegalChars); } illegalChars = findAllRegexMatchingSubstrings(symbols, FOUR_CONSECUTIVE_TEN_LIKE_CHARS_REGEX); if (!illegalChars.isEmpty()) { throw new NumberFormatException("Four consecutive: " + illegalChars); } illegalChars = findAllRegexMatchingSubstrings(symbols, TWO_SAME_FIVE_LIKE_CHARS_REGEX); if (!illegalChars.isEmpty()) { throw new NumberFormatException("Two D, L or V same characters: " + illegalChars); } throw new NumberFormatException("Generic roman numeral syntax error."); } } /** * Returns the hash of this RomanNumeral. * <p> * The hashcode is created using only the roman numeral String in this * RomanNumeral. Uses {@link Objects#hashCode(java.lang.Object)} and * overrides {@link Object#hashCode()}. * * @return the hash of this RomanNumeral. * @see Object#hashCode() */ @Override public int hashCode() { int hash = 7; hash = 71 * hash + Objects.hashCode(this.numeral); return hash; } /** * Verifies if the passed Object is equal to this. * <p> * Returns <code>true</code> if the passed Object is a RomanNumeral and * contains the same roman numeral as this one, else <code>false</code>. * * @param otherRomanNumeral to compare with this. * @return a boolean telling if the two RomanNumerals are equal. * @see Object#equals(java.lang.Object) */ @Override public boolean equals(Object otherRomanNumeral) { if (otherRomanNumeral == null) { return false; } if (getClass() != otherRomanNumeral.getClass()) { return false; } final RomanNumeral other = (RomanNumeral) otherRomanNumeral; return Objects.equals(this.numeral, other.getNumeral()); } /** * Returns a String representation of this RomanNumeral, which is the roman * numeral String stored in it. * <p> * This method is a delegate method and just calls {@link #getNumeral()} so * the returned string is exactly the same for both. This method is here for * compatibility reasons. * * @return a String containing the roman numeral. * @see #getNumeral() * @see Object#toString() */ @Override public String toString() { return getNumeral(); } /** * Returns a {@link Object#clone() clone} of this object with the same * numeral. * <p> * The original and the RomanNumeral store an equal roman numeral and * applying an {@link #equals(java.lang.Object) equals() } method to them, * will result <code>true</code>. * <p> * Since the only field of RomanNumeral is a String, the * CloneNotSupportedException should never raise. * <p> * Delegates {@link Object#clone()}. * * @return a RomanNumeral with the same numeral. * @throws CloneNotSupportedException when super object is not cloneable. * @see Object#clone() */ @Override public RomanNumeral clone() throws CloneNotSupportedException { return (RomanNumeral) super.clone(); } /** * Returns the lenght of the roman numeral contained in this RomanNumeral * expressed as number of characters. * <p> * Delegates {@link String#length()}. * * @return number of characters in the roman numeral. * @see String#length() */ @Override public int length() { return numeral.length(); } /** * Returns the character of the roman numeral at the given index. * <p> * Delegates {@link String#charAt(int)}. * * @param index of the wanted character in the roman numeral. * @return the character at the given index. * @see String#charAt(int) */ @Override public char charAt(int index) { return numeral.charAt(index); } /** * Returns a CharSequence containing a part of this RomanNumeral. * <p> * The returned CharSequence contains the characters of the roman numeral * from the start index (included) to the end index (exluded). * <p> * Delegates {@link String#subSequence(int, int)}. * * @param startIncluded index of the first character to be included. * @param endNotIncluded index of the first character after the end of the * wanted part. * @return a part of the roman numeral as CharSequence. * @see String#subSequence(int, int) */ @Override public CharSequence subSequence(int startIncluded, int endNotIncluded) { return numeral.subSequence(startIncluded, endNotIncluded); } }
src/main/java/it/matjaz/numerus/core/RomanNumeral.java
/* * Copyright (c) 2015, Matjaž <[email protected]> matjaz.it * * This Source Code Form is part of the project Numerus, a roman numerals * library for Java. The library and its source code may be found on: * https://github.com/MatjazDev/Numerus and http://matjaz.it/numerus * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/ */ package it.matjaz.numerus.core; import java.io.Serializable; import java.util.Objects; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * A container for syntactically correct roman numerals saved as strings. * <p> * This class saves a string passed though the constructor or the setter if and * only if is a roman number with a correct syntax, which happens if the string * matches the {@link #CORRECT_ROMAN_SYNTAX_REGEX}. * <p> * Any string with other characters, different order, too many characters or * anyhow incorrect syntax gets refused with {@link NumberFormatException}, * which may contain some indication of the syntax error in the Exception * message. * <p> * The structure of a syntactically roman numeral is composed of the following * characters <i>in this order</i>: * <ol> * <ul>0-3 <b>M</b></ul> * <ul>0-1 <b>CM</b> or 0-1 <b>CD</b> or ( 0-1 <b>D</b> and 0-3 <b>C</b> )</ul> * <ul>0-1 <b>XC</b> or 0-1 <b>XL</b> or ( 0-1 <b>L</b> and 0-3 <b>X</b> )</ul> * <ul>0-1 <b>IX</b> or 0-1 <b>IV</b> or ( 0-1 <b>V</b> and 0-3 <b>I</b> )</ul> * </ol> * <p> * For the integer values of the symbols, see {@link RomanCharMapFactory}. * * @author Matjaž <a href="mailto:[email protected]">[email protected]</a> * <a href="http://matjaz.it">www.matjaz.it</a> */ public class RomanNumeral implements Serializable, Cloneable, CharSequence { /** * The passed string representing the roman numeral. * * It is a serializable field. */ private String numeral; /** * Big regex matching all syntactically correct roman numerals. * <p> * Contains all possible cases of roman numerals. If a string does not match * this regex, then is not a roman numeral. The structure of a syntactically * roman numeral is composed of the following numeral <i>in this order</i>: * <ol> * <ul>0-3 <b>M</b></ul> * <ul>0-1 <b>CM</b> or 0-1 <b>CD</b> or ( 0-1 <b>D</b> and 0-3 <b>C</b> * )</ul> * <ul>0-1 <b>XC</b> or 0-1 <b>XL</b> or ( 0-1 <b>L</b> and 0-3 <b>X</b> * )</ul> * <ul>0-1 <b>IX</b> or 0-1 <b>IV</b> or ( 0-1 <b>V</b> and 0-3 <b>I</b> * )</ul> * </ol> * <p> * <a href="http://stackoverflow.com/a/267405">Source of the idea</a> of * this regex with a great explanation. */ public final String CORRECT_ROMAN_SYNTAX_REGEX = "^(M{0,3})(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$"; /** * Regex matching any non roman characters. * <p> * If a string contains any character matching with this regex, then is not * a roman numeral, because contains illegal characters. */ public final String NON_ROMAN_CHARS_REGEX = "[^MDCLXVI]"; /** * Regex matching four consecutive characters M or C or X or I. */ private final String FOUR_CONSECUTIVE_TEN_LIKE_CHARS_REGEX = "(MMMM|CCCC|XXXX|IIII)"; /** * Regex matching two characters D or L or V in the same string. */ private final String TWO_SAME_FIVE_LIKE_CHARS_REGEX = "(D.*D|L.*L|V.*V)"; /** * Constructs an empty RomanNumeral. * <p> * Contains no value so {@link #setNumeral(java.lang.String) the setter} * needs to be used before using the RomanNumeral. Calling this method and * then the setter leads to the same result. */ public RomanNumeral() { this.numeral = ""; } /** * Constructs a RomanNumeral with initialized value. * <p> * The passed string gets checked for syntax correctness. If the syntax is * illegal, then a {@link NumberFormatException} is thrown. * <p> * Whitespace charactes in the passed String are removed and the characters * are upcased. * * @param symbols the initial roman numeral to be stored. */ public RomanNumeral(String symbols) { this.numeral = cleanUpcaseAndSyntaxCheckString(symbols); } /** * Getter of the roman numerals String. * <p> * If RomanNumeral is not initialized, the returned String is <b>empty</b>. * * @return a String containing the roman numeral. */ public String getNumeral() { return numeral; } /** * Checks if this RomanNumeral contains a numeral or not. * <p> * Returns <code>true</code> if this RomanNumeal has a roman numeral stored * in it, else <code>false</code> if contains just an empty string. The * verification is done by confronting an empty String with the result of * the {@link #getNumeral() getter}. The only way it can contain an empty * string is to be initialized with the * {@link #RomanNumeral() default constructor} (the one without parameters) * without setting the value after that with the * {@link #setNumeral(java.lang.String) setter}. * * @return <code>true</code> has a roman numeral stored in it, else * <code>false</code> if it's empty. */ public boolean isInitialized() { return !"".equals(getNumeral()); } /** * Setter of the roman numerals String. * <p> * The passed string gets checked for syntax correctness. If the syntax is * illegal, then a {@link NumberFormatException} is thrown. * <p> * Whitespace charactes in the passed String are removed and the characters * are upcased. * * @param numeral the new roman numeral to be stored. */ public void setNumeral(String numeral) { this.numeral = cleanUpcaseAndSyntaxCheckString(numeral); } /** * Performs a check of the syntax of the given roman numeral without storing * it in a RomanNumeral. * <p> * Returns <code>true</code> if the passed String matches the syntax of * roman numerals; else <code>false</code>. Useful to just quickly check if * a String is a roman numeral when an instance of it is not needed. If the * result is <code>true</code>, then the passed String can be successfully * stored in a RomanNumeral by * {@link #RomanNumeral(java.lang.String) constructor} or * {@link #setNumeral(java.lang.String) setter}. * * @param numeralsToCheck the String to check the roman syntax on. * @return <code>true</code> if the passed String is a roman numeral; else * <code>false</code>. */ public static boolean isCorrectRomanSyntax(String numeralsToCheck) { try { new RomanNumeral().cleanUpcaseAndSyntaxCheckString(numeralsToCheck); return true; } catch (NumberFormatException ex) { return false; } } /** * Removes all whitespace characters, upcases the String and verifies the * roman syntax. * <p> * If the syntax does not match, an exception is thrown. * * @param symbols string to be cleaned, upcased and checked. * @return given string without whitespaces and upcased. */ private String cleanUpcaseAndSyntaxCheckString(String symbols) { String cleanSymbols = symbols.replaceAll("\\s+", "").toUpperCase(); throwExceptionIfIllegalRomanSyntax(cleanSymbols); return cleanSymbols; } /** * Finds all the substrings of the given string matching the regex. * <p> * Check for all substring of <code>textToParse</code> matching the * <code>regex</code>, appends them sequentially to a String and returns it. * <p> * <a href="http://stackoverflow.com/a/5705591">Source of the idea</a> of * the algorithm. * * @param textToParse String to be checked for matches. * @param regex to be searched in <code>textToParse</code> * @return a String containing all the matches. */ private static String findAllRegexMatchingSubstrings(String textToParse, String regex) { StringBuilder matches = new StringBuilder(); Matcher matcher = Pattern.compile(regex).matcher(textToParse); while (matcher.find()) { matches.append(matcher.group()); } return matches.toString(); } private void throwExceptionIfIllegalRomanSyntax(String symbols) { if (symbols.isEmpty()) { throw new NumberFormatException("Empty roman numeral."); } if (symbols.length() >= 20) { throw new NumberFormatException("Impossibly long roman numeral."); } if (!symbols.matches(CORRECT_ROMAN_SYNTAX_REGEX)) { String illegalChars; illegalChars = findAllRegexMatchingSubstrings(symbols, NON_ROMAN_CHARS_REGEX); if (!illegalChars.isEmpty()) { throw new NumberFormatException("Non roman characters: " + illegalChars); } illegalChars = findAllRegexMatchingSubstrings(symbols, FOUR_CONSECUTIVE_TEN_LIKE_CHARS_REGEX); if (!illegalChars.isEmpty()) { throw new NumberFormatException("Four consecutive: " + illegalChars); } illegalChars = findAllRegexMatchingSubstrings(symbols, TWO_SAME_FIVE_LIKE_CHARS_REGEX); if (!illegalChars.isEmpty()) { throw new NumberFormatException("Two D, L or V same characters: " + illegalChars); } throw new NumberFormatException("Generic roman numeral syntax error."); } } /** * Returns the hash of this RomanNumeral. * <p> * The hashcode is created using only the roman numeral String in this * RomanNumeral. Uses {@link Objects#hashCode(java.lang.Object)} and * overrides {@link Object#hashCode()}. * * @return the hash of this RomanNumeral. * @see Object#hashCode() */ @Override public int hashCode() { int hash = 7; hash = 71 * hash + Objects.hashCode(this.numeral); return hash; } /** * Verifies if the passed Object is equal to this. * <p> * Returns <code>true</code> if the passed Object is a RomanNumeral and * contains the same roman numeral as this one, else <code>false</code>. * * @param otherRomanNumeral to compare with this. * @return a boolean telling if the two RomanNumerals are equal. * @see Object#equals(java.lang.Object) */ @Override public boolean equals(Object otherRomanNumeral) { if (otherRomanNumeral == null) { return false; } if (getClass() != otherRomanNumeral.getClass()) { return false; } final RomanNumeral other = (RomanNumeral) otherRomanNumeral; return Objects.equals(this.numeral, other.getNumeral()); } /** * Returns a String representation of this RomanNumeral, which is the roman * numeral String stored in it. * <p> * This method is a delegate method and just calls {@link #getNumeral()} so * the returned string is exactly the same for both. This method is here for * compatibility reasons. * * @return a String containing the roman numeral. * @see #getNumeral() * @see Object#toString() */ @Override public String toString() { return getNumeral(); } /** * Returns a {@link Object#clone() clone} of this object with the same * numeral. * <p> * The original and the RomanNumeral store an equal roman numeral and * applying an {@link #equals(java.lang.Object) equals() } method to them, * will result <code>true</code>. * <p> * Since the only field of RomanNumeral is a String, the * CloneNotSupportedException should never raise. * <p> * Delegates {@link Object#clone()}. * * @return a RomanNumeral with the same numeral. * @throws CloneNotSupportedException when super object is not cloneable. * @see Object#clone() */ @Override public RomanNumeral clone() throws CloneNotSupportedException { return (RomanNumeral) super.clone(); } /** * Returns the lenght of the roman numeral contained in this RomanNumeral * expressed as number of characters. * <p> * Delegates {@link String#length()}. * * @return number of characters in the roman numeral. * @see String#length() */ @Override public int length() { return numeral.length(); } /** * Returns the character of the roman numeral at the given index. * <p> * Delegates {@link String#charAt(int)}. * * @param index of the wanted character in the roman numeral. * @return the character at the given index. * @see String#charAt(int) */ @Override public char charAt(int index) { return numeral.charAt(index); } /** * Returns a CharSequence containing a part of this RomanNumeral. * <p> * The returned CharSequence contains the characters of the roman numeral * from the start index (included) to the end index (exluded). * <p> * Delegates {@link String#subSequence(int, int)}. * * @param startIncluded index of the first character to be included. * @param endNotIncluded index of the first character after the end of the * wanted part. * @return a part of the roman numeral as CharSequence. * @see String#subSequence(int, int) */ @Override public CharSequence subSequence(int startIncluded, int endNotIncluded) { return numeral.subSequence(startIncluded, endNotIncluded); } }
Fix missing serialVersionUID in RomanNumeral
src/main/java/it/matjaz/numerus/core/RomanNumeral.java
Fix missing serialVersionUID in RomanNumeral
Java
lgpl-2.1
85c6f88f204d2260ec2c0bc053aa6cb264f3b599
0
exedio/copernica,exedio/copernica,exedio/copernica
/* * Copyright (C) 2004-2006 exedio GmbH (www.exedio.com) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package com.exedio.cope; import java.util.Collection; import java.util.List; public final class CompositeCondition extends Condition { private final Operator operator; public final Condition[] conditions; /** * @throws NullPointerException if <tt>conditions==null</tt> * @throws RuntimeException if <tt>conditions.size()==0</tt> */ public CompositeCondition(final Operator operator, final List<? extends Condition> conditions) { this(operator, conditions.toArray(new Condition[conditions.size()])); } /** * @throws NullPointerException if <tt>conditions==null</tt> * @throws RuntimeException if <tt>conditions.length==0</tt> */ public CompositeCondition(final Operator operator, final Condition[] conditions) { if(operator==null) throw new NullPointerException("operator must not be null"); if(conditions==null) throw new NullPointerException("conditions must not be null"); if(conditions.length==0) throw new RuntimeException("composite condition must have at least one subcondition"); for(int i = 0; i<conditions.length; i++) if(conditions[i]==null) throw new NullPointerException("condition " + i + " must not be null"); this.operator = operator; this.conditions = conditions; } void append(final Statement bf) { bf.append('('); conditions[0].append(bf); for(int i = 1; i<conditions.length; i++) { bf.append(operator.sql); conditions[i].append(bf); } bf.append(')'); } void check(final Query query) { for(int i = 0; i<conditions.length; i++) conditions[i].check(query); } public boolean equals(final Object other) { if(!(other instanceof CompositeCondition)) return false; final CompositeCondition o = (CompositeCondition)other; if(!operator.equals(o.operator) || conditions.length!=o.conditions.length) return false; for(int i = 0; i<conditions.length; i++) { if(!conditions[i].equals(o.conditions[i])) return false; } return true; } public int hashCode() { int result = operator.hashCode(); for(int i = 0; i<conditions.length; i++) result = (31*result) + conditions[i].hashCode(); // may not be commutative return result; } public String toString() { final StringBuffer bf = new StringBuffer(); bf.append('('); bf.append(conditions[0].toString()); for(int i = 1; i<conditions.length; i++) { bf.append(operator). append(' '). append(conditions[i].toString()); } bf.append(')'); return bf.toString(); } public static final <E> CompositeCondition in(final Function<E> function, final Collection<E> values) { final EqualCondition[] result = new EqualCondition[values.size()]; int i = 0; for(E value : values) result[i++] = function.equal(value); return new CompositeCondition(Operator.OR, result); } static enum Operator { AND(" and "), OR(" or "); private final String sql; Operator(final String sql) { this.sql = sql; } } }
runtime/src/com/exedio/cope/CompositeCondition.java
/* * Copyright (C) 2004-2006 exedio GmbH (www.exedio.com) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package com.exedio.cope; import java.util.Collection; import java.util.List; public final class CompositeCondition extends Condition { private final Operator operator; public final Condition[] conditions; /** * @throws NullPointerException if <tt>conditions==null</tt> * @throws RuntimeException if <tt>conditions.size()==0</tt> */ public CompositeCondition(final Operator operator, final List<? extends Condition> conditions) { this(operator, conditions.toArray(new Condition[conditions.size()])); } /** * @throws NullPointerException if <tt>conditions==null</tt> * @throws RuntimeException if <tt>conditions.length==0</tt> */ public CompositeCondition(final Operator operator, final Condition[] conditions) { if(operator==null) throw new NullPointerException("operator must not be null"); if(conditions==null) throw new NullPointerException("conditions must not be null"); if(conditions.length==0) throw new RuntimeException("composite condition must have at least one subcondition"); for(int i = 0; i<conditions.length; i++) if(conditions[i]==null) throw new NullPointerException("condition " + i + " must not be null"); this.operator = operator; this.conditions = conditions; } void append(final Statement bf) { bf.append('('); conditions[0].append(bf); for(int i = 1; i<conditions.length; i++) { bf.append(operator.sql); conditions[i].append(bf); } bf.append(')'); } void check(final Query query) { for(int i = 0; i<conditions.length; i++) conditions[i].check(query); } public boolean equals(final Object other) { if(!(other instanceof CompositeCondition)) return false; final CompositeCondition o = (CompositeCondition)other; if(!operator.equals(o.operator) || conditions.length!=o.conditions.length) return false; for(int i = 0; i<conditions.length; i++) { if(!conditions[i].equals(o.conditions[i])) return false; } return true; } public int hashCode() { int result = operator.hashCode(); for(int i = 0; i<conditions.length; i++) result = (31*result) + conditions[i].hashCode(); // may not be commutative return result; } public String toString() { final StringBuffer buf = new StringBuffer(); buf.append('('); buf.append(conditions[0].toString()); for(int i = 1; i<conditions.length; i++) { buf.append(operator). append(' '). append(conditions[i].toString()); } buf.append(')'); return buf.toString(); } public static final <E> CompositeCondition in(final Function<E> function, final Collection<E> values) { final EqualCondition[] result = new EqualCondition[values.size()]; int i = 0; for(E value : values) result[i++] = function.equal(value); return new CompositeCondition(Operator.OR, result); } static enum Operator { AND(" and "), OR(" or "); private final String sql; Operator(final String sql) { this.sql = sql; } } }
rename local variable git-svn-id: 9dbc6da3594b32e13bcf3b3752e372ea5bc7c2cc@5702 e7d4fc99-c606-0410-b9bf-843393a9eab7
runtime/src/com/exedio/cope/CompositeCondition.java
rename local variable
Java
apache-2.0
e5ae092ba6f81f57206f7ec01caf77d630ab71f7
0
outskywind/myproject
package org.lotus.algorithm.strings; import org.junit.Test; import java.util.Arrays; /** * Created by quanchengyun on 2019/10/7. */ public class Strings { public static char[] str= {'a','b','c','d','e','f','g','h'}; private static char[] getStr(){ return Arrays.copyOf(str,str.length); } //1.翻转子字符串----------------------------------------------------------- /** * 在原字符串中把字符串尾部的m个字符移动到字符串的头部, * 要求:长度为n的字符串操作时间复杂度为O(n),空间复杂度为O(1)。 * 例如,原字符串为”Ilovebaofeng”,m=7,输出结果为:”baofengIlove”。 * * : (x~y~)~=y~~x~~=yx */ public static void revertChar(char[] str , int m){ //0,n-1 //x= str[0],str[n-1-m] , y = n-1-m+1 , n-1 if(m>=str.length){ System.out.print("invalid param m"); } revert(str,0,str.length-1-m); revert(str,str.length-m,str.length-1); revert(str,0,str.length-1); System.out.println(str); } private static void revert(char[] str , int start ,int end){ int j=start; int k=end; while(j < k){ char v = str[j]; str[j]=str[k]; str[k]= v; j++; k--; } } @Test public void testRevert(){ revertChar(getStr(),3); revertChar(getStr(),4); revertChar(getStr(),5); } /** *单词翻转。输入一个英文句子,翻转句子中单词的顺序,但单词内字符的顺序不变,句子中单词以空格符隔开。 * 为简单起见,标点符号和普通字母一样处理。例如,输入“I am a student.”,则输出“student. a am I” * (x~_y~_z~)~ = z~~_y~~_x~~ = z_y_x */ private static void revertWord(){ //略 } //1.end----------------------------------------------------------------------- //2.最长回文子串问题------------------------------------------------------------ /** * 1.manacher 算法 ,扩展字符数组填充特殊字符# ,2N-1 * 2. 以i为中心扩展查找 */ private static void palindromic(char[] str){ char[] extend = new char[str.length*2-1]; for(int i=0,j=0;i<str.length;i++,j++){ extend[j]=str[i]; j++; if (j<extend.length) extend[j]='#'; } int[] mp = new int[extend.length]; int m=0,r=0; for(int i=0;i<extend.length;i++){ mp[i]= i < r ? Math.min(mp[2*m-i],r-i):1; while(i-mp[i]>=0 && i+mp[i]<extend.length && extend[i-mp[i]]==extend[i+mp[i]]){ mp[i]++; } //i为中心的构成回文,如果i大于等于 r ,那么扩展后 r=i,m=i if(i+mp[i] > r) { r=i+mp[i]; m=i; } } //找到最大的那一个 int max=0; for(int i=0;i<mp.length;i++){ if (mp[i]>mp[max]){ max=i; } } if (mp[max]>1) { int left = max-mp[max]+1; int right = max+mp[max]-1; left = (left+1)/2; right = (right-1)/2; for (int i=left;i<=right;i++){ System.out.print(str[i]); } } } @Test public void testPalindromic(){ char[] origin = "abcdeffeffedcab".toCharArray(); palindromic(origin); } //2. end------------------------------ //3. 字符串匹配 hash------------------------------------- /** * h(s[i])= s[i]*b^i mod M * h(s) = h(s[0])+...+ h(s[n]) * h(s[l,r]) = h(s[0,r])-h(s[0,l-1]) * h(s[l,r])=h(s[l-1,r-1]) - h(s[l-1]) + h(s[r]); * 找出在目标字符串中 target 包含的 模式子串 pattern * * O(N+M) 平均时间,极端情况下,O(N*M) */ public static int patternMatch( char[] target,char[] pattern){ //计算字符串hash //前缀hash --Rabin-Karp if(pattern.length>target.length){ return -1; } //缺陷是计算的数字要在一个long 范围内 int b = 233; int M = 1000000007; long hashPattern = 0; long hashTarget = 0; long bl = 1; for(int i=1;i<pattern.length;i++){ bl = bl*b; } bl=bl%M; for(int i=0;i<pattern.length;i++){ hashPattern = (hashPattern*b+pattern[i])%M; hashTarget = (hashTarget*b+target[i])%M; } int pos = -1; for(int i=0;i<target.length-pattern.length;i++){ if (hashPattern == hashTarget){ pos=i; //这里如果相等,严谨来说还需要一个个比较 //基于hash 映射的 字符串匹配算法,效率取决于hash的效率 break; } hashTarget = (hashTarget*b - (target[i]*bl*b)%M + target[i+pattern.length])%M; } return pos; } @Test public void testPatternMatch(){ char[] target = ("afhkcvaofaaamvakidwvbhadoavbiqqqqhsdlkczovoavaqafbmkginl" + "ogapipahnfjadnvcxbxdiazdlkfdfeeigdbjvqweqiutfafpvpzvbadbahufu").toCharArray(); char[] pattern = "lkfdf".toCharArray(); int pos = patternMatch(target,pattern); System.out.println(pos); } /** * 字符串匹配 BM 算法 * */ public int BMPattern(char[] target, char[] pattern){ //计算前后缀move //表示当前字符为结尾的 /** * pattern + + + + + + + + + [i + + + ] + + + [+ + + +] * + + + + + + + + + [+ + + + ] + + + [+ + + +] * length=4 ,以及最长匹配的 k ,m */ int length=0; //当前字符失配时,好后缀规则移动的距离 int[] move = new int[pattern.length]; int j=-1;//当前字符为首的后缀,长度 int k=-1;// 已找到的最大的匹配的后缀的首字符 int l=-1;// 已找到的最大的匹配的后缀的长度 // int tail= pattern.length-1; for(int i=tail;i>=0;i--){ int old_l=l; //k==-1 没有任何匹配的后缀子串 if (l<=0){ //与tail比较 if (pattern[i]==pattern[tail]){ k=i; l=l+1; // } } else { //计算当前包含当前字符的子串 长度是否 > 当前最大子串 if(j>l){ k=i; l=j; } //找到了新的串 更新move //只更新长度比之前子串长的部分的move值 if(l>old_l){ move[tail-l+1]=tail-l+1-k; } } if (j=-1) j= (pattern[i]==pattern[tail-j])?j+1:0; } //再次补正move for(int i=0;i<=tail-l;i++){ move[i]= move[tail-l+1]; } for (int i=0;i<pattern.length;i++){ System.out.print(pattern[i]+" "); } System.out.println(); for (int i=0;i<move.length;i++){ System.out.print(move[i]+" "); } System.out.println(); return 0; } @Test public void testBMPattern(){ char[] target = ("afhkcvaofaaamvakidwvbhadoavbiqqqqhsdlkczovoavaqafbmkginl" + "ogapipahnfjadnvcxbxdiazdlkfdfeeigdbjvqweqiutfafpvpzvbadbahufu").toCharArray(); char[] pattern = "xc dcbacba nbmbadcba".toCharArray(); int pos = BMPattern(target,pattern); System.out.println(pos); } /*private long hash(char[] str,int dwHashType){ long seed1= 0x7FED7FED; long seed2= 0xEEEEEEEE; long[] cryptTable=prepareCryptTable(); int ch; for (int i=0;i<str.length;i++) { ch = str[i]; seed1 = cryptTable[(dwHashType << 8) + ch] ^ (seed1 + seed2); seed2 = ch + seed1 + seed2 + (seed2 << 5) + 3; } return seed1; } static long[] prepareCryptTable() { long seed = 0x00100001; int index2=0,index1=0, i=0; long[] cryptTable = new long[256]; for(index1 = 0; index1 < 256; index1++) { for(index2 = index1, i = 0; i < 5; i++, index2 += 256) { long temp1, temp2; seed = (seed * 125 + 3) % 0x2AAAAB; temp1 = (seed & 0xFFFF) << 0x10; seed = (seed * 125 + 3) % 0x2AAAAB; temp2 = (seed & 0xFFFF); cryptTable[index2] = ( temp1 | temp2 ); } } return cryptTable; }*/ //3. end-------------------------------------------- }
algorithm/src/main/java/org/lotus/algorithm/strings/Strings.java
package org.lotus.algorithm.strings; import org.junit.Test; import java.util.Arrays; /** * Created by quanchengyun on 2019/10/7. */ public class Strings { public static char[] str= {'a','b','c','d','e','f','g','h'}; private static char[] getStr(){ return Arrays.copyOf(str,str.length); } //1.翻转子字符串----------------------------------------------------------- /** * 在原字符串中把字符串尾部的m个字符移动到字符串的头部, * 要求:长度为n的字符串操作时间复杂度为O(n),空间复杂度为O(1)。 * 例如,原字符串为”Ilovebaofeng”,m=7,输出结果为:”baofengIlove”。 * * : (x~y~)~=y~~x~~=yx */ public static void revertChar(char[] str , int m){ //0,n-1 //x= str[0],str[n-1-m] , y = n-1-m+1 , n-1 if(m>=str.length){ System.out.print("invalid param m"); } revert(str,0,str.length-1-m); revert(str,str.length-m,str.length-1); revert(str,0,str.length-1); System.out.println(str); } private static void revert(char[] str , int start ,int end){ int j=start; int k=end; while(j < k){ char v = str[j]; str[j]=str[k]; str[k]= v; j++; k--; } } @Test public void testRevert(){ revertChar(getStr(),3); revertChar(getStr(),4); revertChar(getStr(),5); } /** *单词翻转。输入一个英文句子,翻转句子中单词的顺序,但单词内字符的顺序不变,句子中单词以空格符隔开。 * 为简单起见,标点符号和普通字母一样处理。例如,输入“I am a student.”,则输出“student. a am I” * (x~_y~_z~)~ = z~~_y~~_x~~ = z_y_x */ private static void revertWord(){ //略 } //1.end----------------------------------------------------------------------- //2.最长回文子串问题------------------------------------------------------------ /** * 1.manacher 算法 ,扩展字符数组填充特殊字符# ,2N-1 * 2. 以i为中心扩展查找 */ private static void palindromic(char[] str){ char[] extend = new char[str.length*2-1]; for(int i=0,j=0;i<str.length;i++,j++){ extend[j]=str[i]; j++; if (j<extend.length) extend[j]='#'; } int[] mp = new int[extend.length]; int m=0,r=0; for(int i=0;i<extend.length;i++){ mp[i]= i < r ? Math.min(mp[2*m-i],r-i):1; while(i-mp[i]>=0 && i+mp[i]<extend.length && extend[i-mp[i]]==extend[i+mp[i]]){ mp[i]++; } //i为中心的构成回文,如果i大于等于 r ,那么扩展后 r=i,m=i if(i+mp[i] > r) { r=i+mp[i]; m=i; } } //找到最大的那一个 int max=0; for(int i=0;i<mp.length;i++){ if (mp[i]>mp[max]){ max=i; } } if (mp[max]>1) { int left = max-mp[max]+1; int right = max+mp[max]-1; left = (left+1)/2; right = (right-1)/2; for (int i=left;i<=right;i++){ System.out.print(str[i]); } } } @Test public void testPalindromic(){ char[] origin = "abcdeffeffedcab".toCharArray(); palindromic(origin); } //2. end------------------------------ //3. 字符串匹配 hash------------------------------------- /** * h(s[i])= s[i]*b^i mod M * h(s) = h(s[0])+...+ h(s[n]) * h(s[l,r]) = h(s[0,r])-h(s[0,l-1]) * h(s[l,r])=h(s[l-1,r-1]) - h(s[l-1]) + h(s[r]); * 找出在目标字符串中 target 包含的 模式子串 pattern * * O(N+M) 平均时间,极端情况下,O(N*M) */ public static int patternMatch( char[] target,char[] pattern){ //计算字符串hash //前缀hash --Rabin-Karp if(pattern.length>target.length){ return -1; } //缺陷是计算的数字要在一个long 范围内 int b = 233; int M = 1000000007; long hashPattern = 0; long hashTarget = 0; long bl = 1; for(int i=1;i<pattern.length;i++){ bl = bl*b; } bl=bl%M; for(int i=0;i<pattern.length;i++){ hashPattern = (hashPattern*b+pattern[i])%M; hashTarget = (hashTarget*b+target[i])%M; } int pos = -1; for(int i=0;i<target.length-pattern.length;i++){ if (hashPattern == hashTarget){ pos=i; //这里如果相等,严谨来说还需要一个个比较 //基于hash 映射的 字符串匹配算法,效率取决于hash的效率 break; } hashTarget = (hashTarget*b - (target[i]*bl*b)%M + target[i+pattern.length])%M; } return pos; } @Test public void testPatternMatch(){ char[] target = ("afhkcvaofaaamvakidwvbhadoavbiqqqqhsdlkczovoavaqafbmkginl" + "ogapipahnfjadnvcxbxdiazdlkfdfeeigdbjvqweqiutfafpvpzvbadbahufu").toCharArray(); char[] pattern = "lkfdf".toCharArray(); int pos = patternMatch(target,pattern); System.out.println(pos); } /** * 字符串匹配 BM 算法 * */ public int BMPattern(){ //计算前后缀move } /*private long hash(char[] str,int dwHashType){ long seed1= 0x7FED7FED; long seed2= 0xEEEEEEEE; long[] cryptTable=prepareCryptTable(); int ch; for (int i=0;i<str.length;i++) { ch = str[i]; seed1 = cryptTable[(dwHashType << 8) + ch] ^ (seed1 + seed2); seed2 = ch + seed1 + seed2 + (seed2 << 5) + 3; } return seed1; } static long[] prepareCryptTable() { long seed = 0x00100001; int index2=0,index1=0, i=0; long[] cryptTable = new long[256]; for(index1 = 0; index1 < 256; index1++) { for(index2 = index1, i = 0; i < 5; i++, index2 += 256) { long temp1, temp2; seed = (seed * 125 + 3) % 0x2AAAAB; temp1 = (seed & 0xFFFF) << 0x10; seed = (seed * 125 + 3) % 0x2AAAAB; temp2 = (seed & 0xFFFF); cryptTable[index2] = ( temp1 | temp2 ); } } return cryptTable; }*/ //3. end-------------------------------------------- }
commit
algorithm/src/main/java/org/lotus/algorithm/strings/Strings.java
commit
Java
apache-2.0
577b05756b57ebe7bc360f1dc533b76b1048912a
0
hw-beijing/cocos2d,hw-beijing/cocos2d,owant/cocos2d,owant/cocos2d,owant/cocos2d,ZhouWeikuan/cocos2d,owant/cocos2d,owant/cocos2d,owant/cocos2d,ZhouWeikuan/cocos2d,hw-beijing/cocos2d,owant/cocos2d,ZhouWeikuan/cocos2d,ZhouWeikuan/cocos2d,ZhouWeikuan/cocos2d,ZhouWeikuan/cocos2d,hw-beijing/cocos2d,hw-beijing/cocos2d,owant/cocos2d,hw-beijing/cocos2d,hw-beijing/cocos2d,hw-beijing/cocos2d
package org.cocos2d.types; import java.io.IOException; /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @author Denis M. Kishenko * @version $Revision$ */ // | m[0] m[4] m[8] m[12] | | m11 m21 m31 m41 | | a c 0 tx | |m00 m01 m02 | // | m[1] m[5] m[9] m[13] | | m12 m22 m32 m42 | | b d 0 ty | |m10 m11 m12 | // | m[2] m[6] m[10] m[14] | <=> | m13 m23 m33 m43 | <=> | 0 0 1 0 | <=> | | // | m[3] m[7] m[11] m[15] | | m14 m24 m34 m44 | | 0 0 0 1 | | | /** * The Class AffineTransform represents a linear transformation (rotation, * scaling, or shear) followed by a translation that acts on a coordinate space. * It preserves collinearity of points and ratios of distances between collinear * points: so if A, B, and C are on a line, then after the space has been * transformed via the affine transform, the images of the three points will * still be on a line, and the ratio of the distance from A to B with the * distance from B to C will be the same as the corresponding ratio in the image * space. * * @since Android 1.0 */ public class CGAffineTransform { /** * The Constant serialVersionUID. */ private static final long serialVersionUID = 1330973210523860834L; /** * The Constant TYPE_IDENTITY. */ public static final int TYPE_IDENTITY = 0; /** * The Constant TYPE_TRANSLATION. */ public static final int TYPE_TRANSLATION = 1; /** * The Constant TYPE_UNIFORM_SCALE. */ public static final int TYPE_UNIFORM_SCALE = 2; /** * The Constant TYPE_GENERAL_SCALE. */ public static final int TYPE_GENERAL_SCALE = 4; /** * The Constant TYPE_QUADRANT_ROTATION. */ public static final int TYPE_QUADRANT_ROTATION = 8; /** * The Constant TYPE_GENERAL_ROTATION. */ public static final int TYPE_GENERAL_ROTATION = 16; /** * The Constant TYPE_GENERAL_TRANSFORM. */ public static final int TYPE_GENERAL_TRANSFORM = 32; /** * The Constant TYPE_FLIP. */ public static final int TYPE_FLIP = 64; /** * The Constant TYPE_MASK_SCALE. */ public static final int TYPE_MASK_SCALE = TYPE_UNIFORM_SCALE | TYPE_GENERAL_SCALE; /** * The Constant TYPE_MASK_ROTATION. */ public static final int TYPE_MASK_ROTATION = TYPE_QUADRANT_ROTATION | TYPE_GENERAL_ROTATION; /** * The <code>TYPE_UNKNOWN</code> is an initial type value. */ static final int TYPE_UNKNOWN = -1; /** * The min value equivalent to zero. If absolute value less then ZERO it * considered as zero. */ public static final double ZERO = 1E-10; /** * The values of transformation matrix. */ public double m00; /** * The m10. */ public double m10; /** * The m01. */ public double m01; /** * The m11. */ public double m11; /** * The m02. */ public double m02; /** * The m12. */ public double m12; /** * The transformation <code>type</code>. */ transient int type; public static CGAffineTransform identity() { return new CGAffineTransform(); } /** * Instantiates a new affine transform of type <code>TYPE_IDENTITY</code> * (which leaves coordinates unchanged). */ public CGAffineTransform() { type = TYPE_IDENTITY; m00 = m11 = 1.0; m10 = m01 = m02 = m12 = 0.0; } /** * Instantiates a new affine transform that has the same data as the given * AffineTransform. * * @param t the transform to copy. */ public CGAffineTransform(CGAffineTransform t) { this.type = t.type; this.m00 = t.m00; this.m10 = t.m10; this.m01 = t.m01; this.m11 = t.m11; this.m02 = t.m02; this.m12 = t.m12; } /** * Instantiates a new affine transform by specifying the values of the 2x3 * transformation matrix as floats. The type is set to the default type: * <code>TYPE_UNKNOWN</code> * * @param m00 the m00 entry in the transformation matrix. * @param m10 the m10 entry in the transformation matrix. * @param m01 the m01 entry in the transformation matrix. * @param m11 the m11 entry in the transformation matrix. * @param m02 the m02 entry in the transformation matrix. * @param m12 the m12 entry in the transformation matrix. */ public CGAffineTransform(float m00, float m10, float m01, float m11, float m02, float m12) { this.type = TYPE_UNKNOWN; this.m00 = m00; this.m10 = m10; this.m01 = m01; this.m11 = m11; this.m02 = m02; this.m12 = m12; } /** * Instantiates a new affine transform by specifying the values of the 2x3 * transformation matrix as doubles. The type is set to the default type: * <code>TYPE_UNKNOWN</code> * * @param m00 the m00 entry in the transformation matrix. * @param m10 the m10 entry in the transformation matrix. * @param m01 the m01 entry in the transformation matrix. * @param m11 the m11 entry in the transformation matrix. * @param m02 the m02 entry in the transformation matrix. * @param m12 the m12 entry in the transformation matrix. */ public CGAffineTransform(double m00, double m10, double m01, double m11, double m02, double m12) { this.type = TYPE_UNKNOWN; this.m00 = m00; this.m10 = m10; this.m01 = m01; this.m11 = m11; this.m02 = m02; this.m12 = m12; } public static CGAffineTransform make(double m00, double m10, double m01, double m11, double m02, double m12) { return new CGAffineTransform(m00, m10, m01, m11, m02, m12); } /** * Instantiates a new affine transform by reading the values of the * transformation matrix from an array of floats. The mapping from the array * to the matrix starts with <code>matrix[0]</code> giving the top-left * entry of the matrix and proceeds with the usual left-to-right and * top-down ordering. * <p/> * If the array has only four entries, then the two entries of the last row * of the transformation matrix default to zero. * * @param matrix the array of four or six floats giving the values of the * matrix. * @throws ArrayIndexOutOfBoundsException if the size of the array is 0, 1, 2, 3, or 5. */ public CGAffineTransform(float[] matrix) { this.type = TYPE_UNKNOWN; m00 = matrix[0]; m10 = matrix[1]; m01 = matrix[2]; m11 = matrix[3]; if (matrix.length > 4) { m02 = matrix[4]; m12 = matrix[5]; } } /** * Instantiates a new affine transform by reading the values of the * transformation matrix from an array of doubles. The mapping from the * array to the matrix starts with <code>matrix[0]</code> giving the * top-left entry of the matrix and proceeds with the usual left-to-right * and top-down ordering. * <p/> * If the array has only four entries, then the two entries of the last row * of the transformation matrix default to zero. * * @param matrix the array of four or six doubles giving the values of the * matrix. * @throws ArrayIndexOutOfBoundsException if the size of the array is 0, 1, 2, 3, or 5. */ public CGAffineTransform(double[] matrix) { this.type = TYPE_UNKNOWN; m00 = matrix[0]; m10 = matrix[1]; m01 = matrix[2]; m11 = matrix[3]; if (matrix.length > 4) { m02 = matrix[4]; m12 = matrix[5]; } } /** * Returns type of the affine transformation. * <p/> * The type is computed as follows: Label the entries of the transformation * matrix as three rows (m00, m01), (m10, m11), and (m02, m12). Then if the * original basis vectors are (1, 0) and (0, 1), the new basis vectors after * transformation are given by (m00, m01) and (m10, m11), and the * translation vector is (m02, m12). * <p/> * The types are classified as follows: <br/> TYPE_IDENTITY - no change<br/> * TYPE_TRANSLATION - The translation vector isn't zero<br/> * TYPE_UNIFORM_SCALE - The new basis vectors have equal length<br/> * TYPE_GENERAL_SCALE - The new basis vectors dont' have equal length<br/> * TYPE_FLIP - The new basis vector orientation differs from the original * one<br/> TYPE_QUADRANT_ROTATION - The new basis is a rotation of the * original by 90, 180, 270, or 360 degrees<br/> TYPE_GENERAL_ROTATION - The * new basis is a rotation of the original by an arbitrary angle<br/> * TYPE_GENERAL_TRANSFORM - The transformation can't be inverted.<br/> * <p/> * Note that multiple types are possible, thus the types can be combined * using bitwise combinations. * * @return the type of the Affine Transform. */ public int getType() { if (type != TYPE_UNKNOWN) { return type; } int type = 0; if (m00 * m01 + m10 * m11 != 0.0) { type |= TYPE_GENERAL_TRANSFORM; return type; } if (m02 != 0.0 || m12 != 0.0) { type |= TYPE_TRANSLATION; } else if (m00 == 1.0 && m11 == 1.0 && m01 == 0.0 && m10 == 0.0) { type = TYPE_IDENTITY; return type; } if (m00 * m11 - m01 * m10 < 0.0) { type |= TYPE_FLIP; } double dx = m00 * m00 + m10 * m10; double dy = m01 * m01 + m11 * m11; if (dx != dy) { type |= TYPE_GENERAL_SCALE; } else if (dx != 1.0) { type |= TYPE_UNIFORM_SCALE; } if ((m00 == 0.0 && m11 == 0.0) || (m10 == 0.0 && m01 == 0.0 && (m00 < 0.0 || m11 < 0.0))) { type |= TYPE_QUADRANT_ROTATION; } else if (m01 != 0.0 || m10 != 0.0) { type |= TYPE_GENERAL_ROTATION; } return type; } /** * Gets the scale x entry of the transformation matrix (the upper left * matrix entry). * * @return the scale x value. */ public double getScaleX() { return m00; } /** * Gets the scale y entry of the transformation matrix (the lower right * entry of the linear transformation). * * @return the scale y value. */ public double getScaleY() { return m11; } /** * Gets the shear x entry of the transformation matrix (the upper right * entry of the linear transformation). * * @return the shear x value. */ public double getShearX() { return m01; } /** * Gets the shear y entry of the transformation matrix (the lower left entry * of the linear transformation). * * @return the shear y value. */ public double getShearY() { return m10; } /** * Gets the x coordinate of the translation vector. * * @return the x coordinate of the translation vector. */ public double getTranslateX() { return m02; } /** * Gets the y coordinate of the translation vector. * * @return the y coordinate of the translation vector. */ public double getTranslateY() { return m12; } /** * Checks if the AffineTransformation is the identity. * * @return true, if the AffineTransformation is the identity. */ public boolean isIdentity() { return getType() == TYPE_IDENTITY; } /** * Writes the values of the transformation matrix into the given array of * doubles. If the array has length 4, only the linear transformation part * will be written into it. If it has length greater than 4, the translation * vector will be included as well. * * @param matrix the array to fill with the values of the matrix. * @throws ArrayIndexOutOfBoundsException if the size of the array is 0, 1, 2, 3, or 5. */ public void getMatrix(double[] matrix) { matrix[0] = m00; matrix[1] = m10; matrix[2] = m01; matrix[3] = m11; if (matrix.length > 4) { matrix[4] = m02; matrix[5] = m12; } } /** * Gets the determinant of the linear transformation matrix. * * @return the determinant of the linear transformation matrix. */ public double getDeterminant() { return m00 * m11 - m01 * m10; } /** * Sets the transform in terms of a list of double values. * * @param m00 the m00 coordinate of the transformation matrix. * @param m10 the m10 coordinate of the transformation matrix. * @param m01 the m01 coordinate of the transformation matrix. * @param m11 the m11 coordinate of the transformation matrix. * @param m02 the m02 coordinate of the transformation matrix. * @param m12 the m12 coordinate of the transformation matrix. */ public void setTransform(double m00, double m10, double m01, double m11, double m02, double m12) { this.type = TYPE_UNKNOWN; this.m00 = m00; this.m10 = m10; this.m01 = m01; this.m11 = m11; this.m02 = m02; this.m12 = m12; } /** * Sets the transform's data to match the data of the transform sent as a * parameter. * * @param t the transform that gives the new values. */ public void setTransform(CGAffineTransform t) { setTransform(t.m00, t.m10, t.m01, t.m11, t.m02, t.m12); type = t.type; } /** * Sets the transform to the identity transform. */ public void setToIdentity() { type = TYPE_IDENTITY; m00 = m11 = 1.0; m10 = m01 = m02 = m12 = 0.0; } /** * Sets the transformation to a translation alone. Sets the linear part of * the transformation to identity and the translation vector to the values * sent as parameters. Sets the type to <code>TYPE_IDENTITY</code> if the * resulting AffineTransformation is the identity transformation, otherwise * sets it to <code>TYPE_TRANSLATION</code>. * * @param mx the distance to translate in the x direction. * @param my the distance to translate in the y direction. */ public void setToTranslation(double mx, double my) { m00 = m11 = 1.0; m01 = m10 = 0.0; m02 = mx; m12 = my; if (mx == 0.0 && my == 0.0) { type = TYPE_IDENTITY; } else { type = TYPE_TRANSLATION; } } /** * Sets the transformation to being a scale alone, eliminating rotation, * shear, and translation elements. Sets the type to * <code>TYPE_IDENTITY</code> if the resulting AffineTransformation is the * identity transformation, otherwise sets it to <code>TYPE_UNKNOWN</code>. * * @param scx the scaling factor in the x direction. * @param scy the scaling factor in the y direction. */ public void setToScale(double scx, double scy) { m00 = scx; m11 = scy; m10 = m01 = m02 = m12 = 0.0; if (scx != 1.0 || scy != 1.0) { type = TYPE_UNKNOWN; } else { type = TYPE_IDENTITY; } } /** * Sets the transformation to being a shear alone, eliminating rotation, * scaling, and translation elements. Sets the type to * <code>TYPE_IDENTITY</code> if the resulting AffineTransformation is the * identity transformation, otherwise sets it to <code>TYPE_UNKNOWN</code>. * * @param shx the shearing factor in the x direction. * @param shy the shearing factor in the y direction. */ public void setToShear(double shx, double shy) { m00 = m11 = 1.0; m02 = m12 = 0.0; m01 = shx; m10 = shy; if (shx != 0.0 || shy != 0.0) { type = TYPE_UNKNOWN; } else { type = TYPE_IDENTITY; } } /** * Sets the transformation to being a rotation alone, eliminating shearing, * scaling, and translation elements. Sets the type to * <code>TYPE_IDENTITY</code> if the resulting AffineTransformation is the * identity transformation, otherwise sets it to <code>TYPE_UNKNOWN</code>. * * @param angle the angle of rotation in radians. */ public void setToRotation(double angle) { double sin = Math.sin(angle); double cos = Math.cos(angle); if (Math.abs(cos) < ZERO) { cos = 0.0; sin = sin > 0.0 ? 1.0 : -1.0; } else if (Math.abs(sin) < ZERO) { sin = 0.0; cos = cos > 0.0 ? 1.0 : -1.0; } m00 = m11 = cos; m01 = -sin; m10 = sin; m02 = m12 = 0.0; type = TYPE_UNKNOWN; } /** * Sets the transformation to being a rotation followed by a translation. * Sets the type to <code>TYPE_UNKNOWN</code>. * * @param angle the angle of rotation in radians. * @param px the distance to translate in the x direction. * @param py the distance to translate in the y direction. */ public void setToRotation(double angle, double px, double py) { setToRotation(angle); m02 = px * (1.0 - m00) + py * m10; m12 = py * (1.0 - m00) - px * m10; type = TYPE_UNKNOWN; } /** * Creates a new AffineTransformation that is a translation alone with the * translation vector given by the values sent as parameters. The new * transformation's type is <code>TYPE_IDENTITY</code> if the * AffineTransformation is the identity transformation, otherwise it's * <code>TYPE_TRANSLATION</code>. * * @param mx the distance to translate in the x direction. * @param my the distance to translate in the y direction. * @return the new AffineTransformation. */ public static CGAffineTransform makeTranslation(double mx, double my) { CGAffineTransform t = new CGAffineTransform(); t.setToTranslation(mx, my); return t; } /** * Creates a new AffineTransformation that is a scale alone. The new * transformation's type is <code>TYPE_IDENTITY</code> if the * AffineTransformation is the identity transformation, otherwise it's * <code>TYPE_UNKNOWN</code>. * * @param scx the scaling factor in the x direction. * @param scY the scaling factor in the y direction. * @return the new AffineTransformation. */ public static CGAffineTransform makeScale(double scx, double scY) { CGAffineTransform t = new CGAffineTransform(); t.setToScale(scx, scY); return t; } /** * Creates a new AffineTransformation that is a shear alone. The new * transformation's type is <code>TYPE_IDENTITY</code> if the * AffineTransformation is the identity transformation, otherwise it's * <code>TYPE_UNKNOWN</code>. * * @param shx the shearing factor in the x direction. * @param shy the shearing factor in the y direction. * @return the new AffineTransformation. */ public static CGAffineTransform makeShear(double shx, double shy) { CGAffineTransform m = new CGAffineTransform(); m.setToShear(shx, shy); return m; } /** * Creates a new AffineTransformation that is a rotation alone. The new * transformation's type is <code>TYPE_IDENTITY</code> if the * AffineTransformation is the identity transformation, otherwise it's * <code>TYPE_UNKNOWN</code>. * * @param angle the angle of rotation in radians. * @return the new AffineTransformation. */ public static CGAffineTransform makeRotation(double angle) { CGAffineTransform t = new CGAffineTransform(); t.setToRotation(angle); return t; } /** * Creates a new AffineTransformation that is a rotation followed by a * translation. Sets the type to <code>TYPE_UNKNOWN</code>. * * @param angle the angle of rotation in radians. * @param x the distance to translate in the x direction. * @param y the distance to translate in the y direction. * @return the new AffineTransformation. */ public static CGAffineTransform makeRotation(double angle, double x, double y) { CGAffineTransform t = new CGAffineTransform(); t.setToRotation(angle, x, y); return t; } /** * Applies a translation to this AffineTransformation. * * @param mx the distance to translate in the x direction. * @param my the distance to translate in the y direction. */ public CGAffineTransform getTransformTranslate(double mx, double my) { return getTransformConcat(CGAffineTransform.makeTranslation(mx, my)); } /** * Applies a scaling transformation to this AffineTransformation. * * @param scx the scaling factor in the x direction. * @param scy the scaling factor in the y direction. */ public CGAffineTransform getTransformScale(double scx, double scy) { return getTransformConcat(CGAffineTransform.makeScale(scx, scy)); } /** * Applies a shearing transformation to this AffineTransformation. * * @param shx the shearing factor in the x direction. * @param shy the shearing factor in the y direction. */ public void shear(double shx, double shy) { getTransformConcat(CGAffineTransform.makeShear(shx, shy)); } /** * Applies a rotation transformation to this AffineTransformation. * * @param angle the angle of rotation in radians. */ public CGAffineTransform getTransformRotate(double angle) { return getTransformConcat(CGAffineTransform.makeRotation(angle)); } /** * Applies a rotation and translation transformation to this * AffineTransformation. * * @param angle the angle of rotation in radians. * @param px the distance to translate in the x direction. * @param py the distance to translate in the y direction. */ public void rotate(double angle, double px, double py) { getTransformConcat(CGAffineTransform.makeRotation(angle, px, py)); } /** * Multiplies the matrix representations of two AffineTransform objects. * * @param t1 - the AffineTransform object is a multiplicand * @param t2 - the AffineTransform object is a multiplier * @return an AffineTransform object that is the result of t1 multiplied by * the matrix t2. */ public static CGAffineTransform multiply(CGAffineTransform t1, CGAffineTransform t2) { return new CGAffineTransform(t1.m00 * t2.m00 + t1.m10 * t2.m01, // m00 t1.m00 * t2.m10 + t1.m10 * t2.m11, // m01 t1.m01 * t2.m00 + t1.m11 * t2.m01, // m10 t1.m01 * t2.m10 + t1.m11 * t2.m11, // m11 t1.m02 * t2.m00 + t1.m12 * t2.m01 + t2.m02, // m02 t1.m02 * t2.m10 + t1.m12 * t2.m11 + t2.m12);// m12 } /** * Applies the given AffineTransform to this AffineTransform via matrix * multiplication. * * @param t the AffineTransform to apply to this AffineTransform. */ public CGAffineTransform getTransformConcat(CGAffineTransform t) { return multiply(t, this); } /** * Changes the current AffineTransform the one obtained by taking the * transform t and applying this AffineTransform to it. * * @param t the AffineTransform that this AffineTransform is multiplied * by. */ public CGAffineTransform preConcatenate(CGAffineTransform t) { return multiply(this, t); } /** * Creates an AffineTransform that is the inverse of this transform. * * @return the affine transform that is the inverse of this AffineTransform. * @throws NoninvertibleTransformException * if this AffineTransform cannot be inverted (the determinant * of the linear transformation part is zero). */ public CGAffineTransform getTransformInvert() /*throws NoninvertibleTransformException*/ { double det = getDeterminant(); if (Math.abs(det) < ZERO) { // throw new NoninvertibleTransformException("Determinant is zero"); return this; } return new CGAffineTransform(m11 / det, // m00 -m10 / det, // m10 -m01 / det, // m01 m00 / det, // m11 (m01 * m12 - m11 * m02) / det, // m02 (m10 * m02 - m00 * m12) / det // m12 ); } /** * Apply the current AffineTransform to the point. * * @param src the original point. * @param dst Point2D object to be filled with the destination coordinates * (where the original point is sent by this AffineTransform). * May be null. * @return the point in the AffineTransform's image space where the original * point is sent. */ public CGPoint applyTransform(CGPoint src) { CGPoint dst = CGPoint.make(0, 0); float x = src.x; float y = src.y; dst.x = (float) (x * m00 + y * m01 + m02); dst.y = (float) (x * m10 + y * m11 + m12); return dst; } /** * Applies this AffineTransform to an array of points. * * @param src the array of points to be transformed. * @param srcOff the offset in the source point array of the first point to be * transformed. * @param dst the point array where the images of the points (after applying * the AffineTransformation) should be placed. * @param dstOff the offset in the destination array where the new values * should be written. * @param length the number of points to transform. * @throws ArrayIndexOutOfBoundsException if <code>srcOff + length > src.length</code> or * <code>dstOff + length > dst.length</code>. */ public void transform(CGPoint[] src, int srcOff, CGPoint[] dst, int dstOff, int length) { while (--length >= 0) { CGPoint srcPoint = src[srcOff++]; double x = srcPoint.x; double y = srcPoint.y; CGPoint dstPoint = dst[dstOff]; if (dstPoint == null) { dstPoint = CGPoint.zero(); } dstPoint.x = (float) (x * m00 + y * m01 + m02); dstPoint.y = (float) (x * m10 + y * m11 + m12); dst[dstOff++] = dstPoint; } } /** * Applies this AffineTransform to a set of points given as an array of * double values where every two values in the array give the coordinates of * a point; the even-indexed values giving the x coordinates and the * odd-indexed values giving the y coordinates. * * @param src the array of points to be transformed. * @param srcOff the offset in the source point array of the first point to be * transformed. * @param dst the point array where the images of the points (after applying * the AffineTransformation) should be placed. * @param dstOff the offset in the destination array where the new values * should be written. * @param length the number of points to transform. * @throws ArrayIndexOutOfBoundsException if <code>srcOff + length*2 > src.length</code> or * <code>dstOff + length*2 > dst.length</code>. */ public void transform(double[] src, int srcOff, double[] dst, int dstOff, int length) { int step = 2; if (src == dst && srcOff < dstOff && dstOff < srcOff + length * 2) { srcOff = srcOff + length * 2 - 2; dstOff = dstOff + length * 2 - 2; step = -2; } while (--length >= 0) { double x = src[srcOff + 0]; double y = src[srcOff + 1]; dst[dstOff + 0] = x * m00 + y * m01 + m02; dst[dstOff + 1] = x * m10 + y * m11 + m12; srcOff += step; dstOff += step; } } /** * Applies this AffineTransform to a set of points given as an array of * float values where every two values in the array give the coordinates of * a point; the even-indexed values giving the x coordinates and the * odd-indexed values giving the y coordinates. * * @param src the array of points to be transformed. * @param srcOff the offset in the source point array of the first point to be * transformed. * @param dst the point array where the images of the points (after applying * the AffineTransformation) should be placed. * @param dstOff the offset in the destination array where the new values * should be written. * @param length the number of points to transform. * @throws ArrayIndexOutOfBoundsException if <code>srcOff + length*2 > src.length</code> or * <code>dstOff + length*2 > dst.length</code>. */ public void transform(float[] src, int srcOff, float[] dst, int dstOff, int length) { int step = 2; if (src == dst && srcOff < dstOff && dstOff < srcOff + length * 2) { srcOff = srcOff + length * 2 - 2; dstOff = dstOff + length * 2 - 2; step = -2; } while (--length >= 0) { double x = src[srcOff + 0]; double y = src[srcOff + 1]; dst[dstOff + 0] = (float) (x * m00 + y * m01 + m02); dst[dstOff + 1] = (float) (x * m10 + y * m11 + m12); srcOff += step; dstOff += step; } } /** * Applies this AffineTransform to a set of points given as an array of * float values where every two values in the array give the coordinates of * a point; the even-indexed values giving the x coordinates and the * odd-indexed values giving the y coordinates. The destination coordinates * are given as values of type <code>double</code>. * * @param src the array of points to be transformed. * @param srcOff the offset in the source point array of the first point to be * transformed. * @param dst the point array where the images of the points (after applying * the AffineTransformation) should be placed. * @param dstOff the offset in the destination array where the new values * should be written. * @param length the number of points to transform. * @throws ArrayIndexOutOfBoundsException if <code>srcOff + length*2 > src.length</code> or * <code>dstOff + length*2 > dst.length</code>. */ public void transform(float[] src, int srcOff, double[] dst, int dstOff, int length) { while (--length >= 0) { float x = src[srcOff++]; float y = src[srcOff++]; dst[dstOff++] = x * m00 + y * m01 + m02; dst[dstOff++] = x * m10 + y * m11 + m12; } } /** * Applies this AffineTransform to a set of points given as an array of * double values where every two values in the array give the coordinates of * a point; the even-indexed values giving the x coordinates and the * odd-indexed values giving the y coordinates. The destination coordinates * are given as values of type <code>float</code>. * * @param src the array of points to be transformed. * @param srcOff the offset in the source point array of the first point to be * transformed. * @param dst the point array where the images of the points (after applying * the AffineTransformation) should be placed. * @param dstOff the offset in the destination array where the new values * should be written. * @param length the number of points to transform. * @throws ArrayIndexOutOfBoundsException if <code>srcOff + length*2 > src.length</code> or * <code>dstOff + length*2 > dst.length</code>. */ public void transform(double[] src, int srcOff, float[] dst, int dstOff, int length) { while (--length >= 0) { double x = src[srcOff++]; double y = src[srcOff++]; dst[dstOff++] = (float) (x * m00 + y * m01 + m02); dst[dstOff++] = (float) (x * m10 + y * m11 + m12); } } /** * Transforms the point according to the linear transformation part of this * AffineTransformation (without applying the translation). * * @param src the original point. * @param dst the point object where the result of the delta transform is * written. * @return the result of applying the delta transform (linear part only) to * the original point. */ // TODO: is this right? if dst is null, we check what it's an // instance of? Shouldn't it be src instanceof Point2D.Double? public CGPoint deltaTransform(CGPoint src, CGPoint dst) { if (dst == null) { dst = CGPoint.make(0, 0); } double x = src.x; double y = src.y; dst.x = (float) (x * m00 + y * m01); dst.y = (float) (x * m10 + y * m11); return dst; } /** * Applies the linear transformation part of this AffineTransform (ignoring * the translation part) to a set of points given as an array of double * values where every two values in the array give the coordinates of a * point; the even-indexed values giving the x coordinates and the * odd-indexed values giving the y coordinates. * * @param src the array of points to be transformed. * @param srcOff the offset in the source point array of the first point to be * transformed. * @param dst the point array where the images of the points (after applying * the delta transformation) should be placed. * @param dstOff the offset in the destination array where the new values * should be written. * @param length the number of points to transform. * @throws ArrayIndexOutOfBoundsException if <code>srcOff + length*2 > src.length</code> or * <code>dstOff + length*2 > dst.length</code>. */ public void deltaTransform(double[] src, int srcOff, double[] dst, int dstOff, int length) { while (--length >= 0) { double x = src[srcOff++]; double y = src[srcOff++]; dst[dstOff++] = x * m00 + y * m01; dst[dstOff++] = x * m10 + y * m11; } } /** * Transforms the point according to the inverse of this * AffineTransformation. * * @param src the original point. * @param dst the point object where the result of the inverse transform is * written (may be null). * @return the result of applying the inverse transform. Inverse transform. * @throws NoninvertibleTransformException * if this AffineTransform cannot be inverted (the determinant * of the linear transformation part is zero). */ public CGPoint inverseTransform(CGPoint src, CGPoint dst) throws NoninvertibleTransformException { double det = getDeterminant(); if (Math.abs(det) < ZERO) { throw new NoninvertibleTransformException("Determinant is zero"); //$NON-NLS-1$ } if (dst == null) { dst = CGPoint.zero(); } double x = src.x - m02; double y = src.y - m12; dst.x = (float) ((x * m11 - y * m01) / det); dst.y = (float) ((y * m00 - x * m10) / det); return dst; } /** * Applies the inverse of this AffineTransform to a set of points given as * an array of double values where every two values in the array give the * coordinates of a point; the even-indexed values giving the x coordinates * and the odd-indexed values giving the y coordinates. * * @param src the array of points to be transformed. * @param srcOff the offset in the source point array of the first point to be * transformed. * @param dst the point array where the images of the points (after applying * the inverse of the AffineTransformation) should be placed. * @param dstOff the offset in the destination array where the new values * should be written. * @param length the number of points to transform. * @throws ArrayIndexOutOfBoundsException if <code>srcOff + length*2 > src.length</code> or * <code>dstOff + length*2 > dst.length</code>. * @throws NoninvertibleTransformException * if this AffineTransform cannot be inverted (the determinant * of the linear transformation part is zero). */ public void inverseTransform(double[] src, int srcOff, double[] dst, int dstOff, int length) throws NoninvertibleTransformException { double det = getDeterminant(); if (Math.abs(det) < ZERO) { throw new NoninvertibleTransformException("Determinant is zero"); //$NON-NLS-1$ } while (--length >= 0) { double x = src[srcOff++] - m02; double y = src[srcOff++] - m12; dst[dstOff++] = (x * m11 - y * m01) / det; dst[dstOff++] = (y * m00 - x * m10) / det; } } public void set(double m00, double m10, double m01, double m11, double m02, double m12) { this.type = TYPE_UNKNOWN; this.m00 = m00; this.m10 = m10; this.m01 = m01; this.m11 = m11; this.m02 = m02; this.m12 = m12; } public void translate(double mx, double my) { type = TYPE_UNKNOWN; m02 = mx * m00 + my * m01 + m02; m12 = mx * m10 + my * m11 + m12; } public void rotate(double angle) { double sin = Math.sin(angle); double cos = Math.cos(angle); if (Math.abs(cos) < ZERO) { cos = 0.0; sin = sin > 0.0 ? 1.0 : -1.0; } else if (Math.abs(sin) < ZERO) { sin = 0.0; cos = cos > 0.0 ? 1.0 : -1.0; } type = TYPE_UNKNOWN; double m00 = cos * this.m00 + sin * this.m01; double m10 = cos * this.m10 + sin * this.m11; double m01 = -sin * this.m00 + cos * this.m01; double m11 = -sin * this.m10 + cos * this.m11; this.m00 = m00; this.m01 = m01; this.m10 = m10; this.m11 = m11; } public void scale(double scx, double scy) { type = TYPE_UNKNOWN; m00 = scx * m00; double m10 = scx * this.m10; double m01 = scy * this.m01; m11 = scy * m11; this.m01 = m01; this.m10 = m10; } public void multiply(CGAffineTransform t) { double m00 = this.m00 * t.m00 + this.m10 * t.m01; double m01 = this.m00 * t.m10 + this.m10 * t.m11; double m10 = this.m01 * t.m00 + this.m11 * t.m01; double m11 = this.m01 * t.m10 + this.m11 * t.m11; double m02 = this.m02 * t.m00 + this.m12 * t.m01 + t.m02; double m12 = this.m02 * t.m10 + this.m12 * t.m11 + t.m12; this.m00 = m00; this.m01 = m01; this.m10 = m10; this.m11 = m11; this.m02 = m02; this.m12 = m12; } // /** // * Creates a new shape whose data is given by applying this AffineTransform // * to the specified shape. // * // * @param src // * the original shape whose data is to be transformed. // * @return the new shape found by applying this AffineTransform to the // * original shape. // */ // public Shape createTransformedShape(Shape src) { // if (src == null) { // return null; // } // if (src instanceof GeneralPath) { // return ((GeneralPath)src).createTransformedShape(this); // } // PathIterator path = src.getPathIterator(this); // GeneralPath dst = new GeneralPath(path.getWindingRule()); // dst.append(path, false); // return dst; // } @Override public String toString() { return getClass().getName() + "[[" + m00 + ", " + m01 + ", " + m02 + "], [" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + m10 + ", " + m11 + ", " + m12 + "]]"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } @Override public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e) { throw new InternalError(); } } @Override public int hashCode() { HashCode hash = new HashCode(); hash.append(m00); hash.append(m01); hash.append(m02); hash.append(m10); hash.append(m11); hash.append(m12); return hash.hashCode(); } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (obj instanceof CGAffineTransform) { CGAffineTransform t = (CGAffineTransform) obj; return m00 == t.m00 && m01 == t.m01 && m02 == t.m02 && m10 == t.m10 && m11 == t.m11 && m12 == t.m12; } return false; } /** * Writes the AffineTrassform object to the output steam. * * @param stream - the output stream. * @throws java.io.IOException - if there are I/O errors while writing to the output stream. */ private void writeObject(java.io.ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); } /** * Read the AffineTransform object from the input stream. * * @param stream - the input stream. * @throws IOException - if there are I/O errors while reading from the input * stream. * @throws ClassNotFoundException - if class could not be found. */ private void readObject(java.io.ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); type = TYPE_UNKNOWN; } public static void CGAffineToGL(CGAffineTransform t, float []m) { // | m[0] m[4] m[8] m[12] | | m11 m21 m31 m41 | | a c 0 tx | // | m[1] m[5] m[9] m[13] | | m12 m22 m32 m42 | | b d 0 ty | // | m[2] m[6] m[10] m[14] | <=> | m13 m23 m33 m43 | <=> | 0 0 1 0 | // | m[3] m[7] m[11] m[15] | | m14 m24 m34 m44 | | 0 0 0 1 | m[2] = m[3] = m[6] = m[7] = m[8] = m[9] = m[11] = m[14] = 0.0f; m[10] = m[15] = 1.0f; m[0] = (float)t.m00; m[4] = (float)t.m01; m[12] = (float)t.m02; m[1] = (float)t.m10; m[5] = (float)t.m11; m[13] = (float)t.m12; } public static void GLToCGAffine(float []m, CGAffineTransform t) { t.m00 = m[0]; t.m01 = m[4]; t.m02 = m[12]; t.m10 = m[1]; t.m11 = m[5]; t.m12 = m[13]; } } final class HashCode { private final HashCode hashCode = new HashCode(); /** * Returns accumulated hashCode */ public final int hashCode() { return hashCode.hashCode(); } /** * Appends value's hashCode to the current hashCode. * * @param value new element * @return this */ public final HashCode append(int value) { return hashCode.append(value); } /** * Appends value's hashCode to the current hashCode. * * @param value new element * @return this */ public final HashCode append(long value) { return hashCode.append(value); } /** * Appends value's hashCode to the current hashCode. * * @param value new element * @return this */ public final HashCode append(float value) { return hashCode.append(value); } /** * Appends value's hashCode to the current hashCode. * * @param value new element * @return this */ public final HashCode append(double value) { return hashCode.append(value); } /** * Appends value's hashCode to the current hashCode. * * @param value new element * @return this */ public final HashCode append(boolean value) { return hashCode.append(value); } /** * Appends value's hashCode to the current hashCode. * * @param value new element * @return this */ public final HashCode append(Object value) { return hashCode.append(value); } }
cocos2d-android/src/org/cocos2d/types/CGAffineTransform.java
package org.cocos2d.types; import java.io.IOException; /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @author Denis M. Kishenko * @version $Revision$ */ // | m[0] m[4] m[8] m[12] | | m11 m21 m31 m41 | | a c 0 tx | |m00 m01 m02 | // | m[1] m[5] m[9] m[13] | | m12 m22 m32 m42 | | b d 0 ty | |m10 m11 m12 | // | m[2] m[6] m[10] m[14] | <=> | m13 m23 m33 m43 | <=> | 0 0 1 0 | <=> | | // | m[3] m[7] m[11] m[15] | | m14 m24 m34 m44 | | 0 0 0 1 | | | /** * The Class AffineTransform represents a linear transformation (rotation, * scaling, or shear) followed by a translation that acts on a coordinate space. * It preserves collinearity of points and ratios of distances between collinear * points: so if A, B, and C are on a line, then after the space has been * transformed via the affine transform, the images of the three points will * still be on a line, and the ratio of the distance from A to B with the * distance from B to C will be the same as the corresponding ratio in the image * space. * * @since Android 1.0 */ public class CGAffineTransform { /** * The Constant serialVersionUID. */ private static final long serialVersionUID = 1330973210523860834L; /** * The Constant TYPE_IDENTITY. */ public static final int TYPE_IDENTITY = 0; /** * The Constant TYPE_TRANSLATION. */ public static final int TYPE_TRANSLATION = 1; /** * The Constant TYPE_UNIFORM_SCALE. */ public static final int TYPE_UNIFORM_SCALE = 2; /** * The Constant TYPE_GENERAL_SCALE. */ public static final int TYPE_GENERAL_SCALE = 4; /** * The Constant TYPE_QUADRANT_ROTATION. */ public static final int TYPE_QUADRANT_ROTATION = 8; /** * The Constant TYPE_GENERAL_ROTATION. */ public static final int TYPE_GENERAL_ROTATION = 16; /** * The Constant TYPE_GENERAL_TRANSFORM. */ public static final int TYPE_GENERAL_TRANSFORM = 32; /** * The Constant TYPE_FLIP. */ public static final int TYPE_FLIP = 64; /** * The Constant TYPE_MASK_SCALE. */ public static final int TYPE_MASK_SCALE = TYPE_UNIFORM_SCALE | TYPE_GENERAL_SCALE; /** * The Constant TYPE_MASK_ROTATION. */ public static final int TYPE_MASK_ROTATION = TYPE_QUADRANT_ROTATION | TYPE_GENERAL_ROTATION; /** * The <code>TYPE_UNKNOWN</code> is an initial type value. */ static final int TYPE_UNKNOWN = -1; /** * The min value equivalent to zero. If absolute value less then ZERO it * considered as zero. */ public static final double ZERO = 1E-10; /** * The values of transformation matrix. */ public double m00; /** * The m10. */ public double m10; /** * The m01. */ public double m01; /** * The m11. */ public double m11; /** * The m02. */ public double m02; /** * The m12. */ public double m12; /** * The transformation <code>type</code>. */ transient int type; public static CGAffineTransform identity() { return new CGAffineTransform(); } /** * Instantiates a new affine transform of type <code>TYPE_IDENTITY</code> * (which leaves coordinates unchanged). */ public CGAffineTransform() { type = TYPE_IDENTITY; m00 = m11 = 1.0; m10 = m01 = m02 = m12 = 0.0; } /** * Instantiates a new affine transform that has the same data as the given * AffineTransform. * * @param t the transform to copy. */ public CGAffineTransform(CGAffineTransform t) { this.type = t.type; this.m00 = t.m00; this.m10 = t.m10; this.m01 = t.m01; this.m11 = t.m11; this.m02 = t.m02; this.m12 = t.m12; } /** * Instantiates a new affine transform by specifying the values of the 2x3 * transformation matrix as floats. The type is set to the default type: * <code>TYPE_UNKNOWN</code> * * @param m00 the m00 entry in the transformation matrix. * @param m10 the m10 entry in the transformation matrix. * @param m01 the m01 entry in the transformation matrix. * @param m11 the m11 entry in the transformation matrix. * @param m02 the m02 entry in the transformation matrix. * @param m12 the m12 entry in the transformation matrix. */ public CGAffineTransform(float m00, float m10, float m01, float m11, float m02, float m12) { this.type = TYPE_UNKNOWN; this.m00 = m00; this.m10 = m10; this.m01 = m01; this.m11 = m11; this.m02 = m02; this.m12 = m12; } /** * Instantiates a new affine transform by specifying the values of the 2x3 * transformation matrix as doubles. The type is set to the default type: * <code>TYPE_UNKNOWN</code> * * @param m00 the m00 entry in the transformation matrix. * @param m10 the m10 entry in the transformation matrix. * @param m01 the m01 entry in the transformation matrix. * @param m11 the m11 entry in the transformation matrix. * @param m02 the m02 entry in the transformation matrix. * @param m12 the m12 entry in the transformation matrix. */ public CGAffineTransform(double m00, double m10, double m01, double m11, double m02, double m12) { this.type = TYPE_UNKNOWN; this.m00 = m00; this.m10 = m10; this.m01 = m01; this.m11 = m11; this.m02 = m02; this.m12 = m12; } public static CGAffineTransform make(double m00, double m10, double m01, double m11, double m02, double m12) { return new CGAffineTransform(m00, m10, m01, m11, m02, m12); } /** * Instantiates a new affine transform by reading the values of the * transformation matrix from an array of floats. The mapping from the array * to the matrix starts with <code>matrix[0]</code> giving the top-left * entry of the matrix and proceeds with the usual left-to-right and * top-down ordering. * <p/> * If the array has only four entries, then the two entries of the last row * of the transformation matrix default to zero. * * @param matrix the array of four or six floats giving the values of the * matrix. * @throws ArrayIndexOutOfBoundsException if the size of the array is 0, 1, 2, 3, or 5. */ public CGAffineTransform(float[] matrix) { this.type = TYPE_UNKNOWN; m00 = matrix[0]; m10 = matrix[1]; m01 = matrix[2]; m11 = matrix[3]; if (matrix.length > 4) { m02 = matrix[4]; m12 = matrix[5]; } } /** * Instantiates a new affine transform by reading the values of the * transformation matrix from an array of doubles. The mapping from the * array to the matrix starts with <code>matrix[0]</code> giving the * top-left entry of the matrix and proceeds with the usual left-to-right * and top-down ordering. * <p/> * If the array has only four entries, then the two entries of the last row * of the transformation matrix default to zero. * * @param matrix the array of four or six doubles giving the values of the * matrix. * @throws ArrayIndexOutOfBoundsException if the size of the array is 0, 1, 2, 3, or 5. */ public CGAffineTransform(double[] matrix) { this.type = TYPE_UNKNOWN; m00 = matrix[0]; m10 = matrix[1]; m01 = matrix[2]; m11 = matrix[3]; if (matrix.length > 4) { m02 = matrix[4]; m12 = matrix[5]; } } /** * Returns type of the affine transformation. * <p/> * The type is computed as follows: Label the entries of the transformation * matrix as three rows (m00, m01), (m10, m11), and (m02, m12). Then if the * original basis vectors are (1, 0) and (0, 1), the new basis vectors after * transformation are given by (m00, m01) and (m10, m11), and the * translation vector is (m02, m12). * <p/> * The types are classified as follows: <br/> TYPE_IDENTITY - no change<br/> * TYPE_TRANSLATION - The translation vector isn't zero<br/> * TYPE_UNIFORM_SCALE - The new basis vectors have equal length<br/> * TYPE_GENERAL_SCALE - The new basis vectors dont' have equal length<br/> * TYPE_FLIP - The new basis vector orientation differs from the original * one<br/> TYPE_QUADRANT_ROTATION - The new basis is a rotation of the * original by 90, 180, 270, or 360 degrees<br/> TYPE_GENERAL_ROTATION - The * new basis is a rotation of the original by an arbitrary angle<br/> * TYPE_GENERAL_TRANSFORM - The transformation can't be inverted.<br/> * <p/> * Note that multiple types are possible, thus the types can be combined * using bitwise combinations. * * @return the type of the Affine Transform. */ public int getType() { if (type != TYPE_UNKNOWN) { return type; } int type = 0; if (m00 * m01 + m10 * m11 != 0.0) { type |= TYPE_GENERAL_TRANSFORM; return type; } if (m02 != 0.0 || m12 != 0.0) { type |= TYPE_TRANSLATION; } else if (m00 == 1.0 && m11 == 1.0 && m01 == 0.0 && m10 == 0.0) { type = TYPE_IDENTITY; return type; } if (m00 * m11 - m01 * m10 < 0.0) { type |= TYPE_FLIP; } double dx = m00 * m00 + m10 * m10; double dy = m01 * m01 + m11 * m11; if (dx != dy) { type |= TYPE_GENERAL_SCALE; } else if (dx != 1.0) { type |= TYPE_UNIFORM_SCALE; } if ((m00 == 0.0 && m11 == 0.0) || (m10 == 0.0 && m01 == 0.0 && (m00 < 0.0 || m11 < 0.0))) { type |= TYPE_QUADRANT_ROTATION; } else if (m01 != 0.0 || m10 != 0.0) { type |= TYPE_GENERAL_ROTATION; } return type; } /** * Gets the scale x entry of the transformation matrix (the upper left * matrix entry). * * @return the scale x value. */ public double getScaleX() { return m00; } /** * Gets the scale y entry of the transformation matrix (the lower right * entry of the linear transformation). * * @return the scale y value. */ public double getScaleY() { return m11; } /** * Gets the shear x entry of the transformation matrix (the upper right * entry of the linear transformation). * * @return the shear x value. */ public double getShearX() { return m01; } /** * Gets the shear y entry of the transformation matrix (the lower left entry * of the linear transformation). * * @return the shear y value. */ public double getShearY() { return m10; } /** * Gets the x coordinate of the translation vector. * * @return the x coordinate of the translation vector. */ public double getTranslateX() { return m02; } /** * Gets the y coordinate of the translation vector. * * @return the y coordinate of the translation vector. */ public double getTranslateY() { return m12; } /** * Checks if the AffineTransformation is the identity. * * @return true, if the AffineTransformation is the identity. */ public boolean isIdentity() { return getType() == TYPE_IDENTITY; } /** * Writes the values of the transformation matrix into the given array of * doubles. If the array has length 4, only the linear transformation part * will be written into it. If it has length greater than 4, the translation * vector will be included as well. * * @param matrix the array to fill with the values of the matrix. * @throws ArrayIndexOutOfBoundsException if the size of the array is 0, 1, 2, 3, or 5. */ public void getMatrix(double[] matrix) { matrix[0] = m00; matrix[1] = m10; matrix[2] = m01; matrix[3] = m11; if (matrix.length > 4) { matrix[4] = m02; matrix[5] = m12; } } /** * Gets the determinant of the linear transformation matrix. * * @return the determinant of the linear transformation matrix. */ public double getDeterminant() { return m00 * m11 - m01 * m10; } /** * Sets the transform in terms of a list of double values. * * @param m00 the m00 coordinate of the transformation matrix. * @param m10 the m10 coordinate of the transformation matrix. * @param m01 the m01 coordinate of the transformation matrix. * @param m11 the m11 coordinate of the transformation matrix. * @param m02 the m02 coordinate of the transformation matrix. * @param m12 the m12 coordinate of the transformation matrix. */ public void setTransform(double m00, double m10, double m01, double m11, double m02, double m12) { this.type = TYPE_UNKNOWN; this.m00 = m00; this.m10 = m10; this.m01 = m01; this.m11 = m11; this.m02 = m02; this.m12 = m12; } /** * Sets the transform's data to match the data of the transform sent as a * parameter. * * @param t the transform that gives the new values. */ public void setTransform(CGAffineTransform t) { setTransform(t.m00, t.m10, t.m01, t.m11, t.m02, t.m12); type = t.type; } /** * Sets the transform to the identity transform. */ public void setToIdentity() { type = TYPE_IDENTITY; m00 = m11 = 1.0; m10 = m01 = m02 = m12 = 0.0; } /** * Sets the transformation to a translation alone. Sets the linear part of * the transformation to identity and the translation vector to the values * sent as parameters. Sets the type to <code>TYPE_IDENTITY</code> if the * resulting AffineTransformation is the identity transformation, otherwise * sets it to <code>TYPE_TRANSLATION</code>. * * @param mx the distance to translate in the x direction. * @param my the distance to translate in the y direction. */ public void setToTranslation(double mx, double my) { m00 = m11 = 1.0; m01 = m10 = 0.0; m02 = mx; m12 = my; if (mx == 0.0 && my == 0.0) { type = TYPE_IDENTITY; } else { type = TYPE_TRANSLATION; } } /** * Sets the transformation to being a scale alone, eliminating rotation, * shear, and translation elements. Sets the type to * <code>TYPE_IDENTITY</code> if the resulting AffineTransformation is the * identity transformation, otherwise sets it to <code>TYPE_UNKNOWN</code>. * * @param scx the scaling factor in the x direction. * @param scy the scaling factor in the y direction. */ public void setToScale(double scx, double scy) { m00 = scx; m11 = scy; m10 = m01 = m02 = m12 = 0.0; if (scx != 1.0 || scy != 1.0) { type = TYPE_UNKNOWN; } else { type = TYPE_IDENTITY; } } /** * Sets the transformation to being a shear alone, eliminating rotation, * scaling, and translation elements. Sets the type to * <code>TYPE_IDENTITY</code> if the resulting AffineTransformation is the * identity transformation, otherwise sets it to <code>TYPE_UNKNOWN</code>. * * @param shx the shearing factor in the x direction. * @param shy the shearing factor in the y direction. */ public void setToShear(double shx, double shy) { m00 = m11 = 1.0; m02 = m12 = 0.0; m01 = shx; m10 = shy; if (shx != 0.0 || shy != 0.0) { type = TYPE_UNKNOWN; } else { type = TYPE_IDENTITY; } } /** * Sets the transformation to being a rotation alone, eliminating shearing, * scaling, and translation elements. Sets the type to * <code>TYPE_IDENTITY</code> if the resulting AffineTransformation is the * identity transformation, otherwise sets it to <code>TYPE_UNKNOWN</code>. * * @param angle the angle of rotation in radians. */ public void setToRotation(double angle) { double sin = Math.sin(angle); double cos = Math.cos(angle); if (Math.abs(cos) < ZERO) { cos = 0.0; sin = sin > 0.0 ? 1.0 : -1.0; } else if (Math.abs(sin) < ZERO) { sin = 0.0; cos = cos > 0.0 ? 1.0 : -1.0; } m00 = m11 = cos; m01 = -sin; m10 = sin; m02 = m12 = 0.0; type = TYPE_UNKNOWN; } /** * Sets the transformation to being a rotation followed by a translation. * Sets the type to <code>TYPE_UNKNOWN</code>. * * @param angle the angle of rotation in radians. * @param px the distance to translate in the x direction. * @param py the distance to translate in the y direction. */ public void setToRotation(double angle, double px, double py) { setToRotation(angle); m02 = px * (1.0 - m00) + py * m10; m12 = py * (1.0 - m00) - px * m10; type = TYPE_UNKNOWN; } /** * Creates a new AffineTransformation that is a translation alone with the * translation vector given by the values sent as parameters. The new * transformation's type is <code>TYPE_IDENTITY</code> if the * AffineTransformation is the identity transformation, otherwise it's * <code>TYPE_TRANSLATION</code>. * * @param mx the distance to translate in the x direction. * @param my the distance to translate in the y direction. * @return the new AffineTransformation. */ public static CGAffineTransform makeTranslation(double mx, double my) { CGAffineTransform t = new CGAffineTransform(); t.setToTranslation(mx, my); return t; } /** * Creates a new AffineTransformation that is a scale alone. The new * transformation's type is <code>TYPE_IDENTITY</code> if the * AffineTransformation is the identity transformation, otherwise it's * <code>TYPE_UNKNOWN</code>. * * @param scx the scaling factor in the x direction. * @param scY the scaling factor in the y direction. * @return the new AffineTransformation. */ public static CGAffineTransform makeScale(double scx, double scY) { CGAffineTransform t = new CGAffineTransform(); t.setToScale(scx, scY); return t; } /** * Creates a new AffineTransformation that is a shear alone. The new * transformation's type is <code>TYPE_IDENTITY</code> if the * AffineTransformation is the identity transformation, otherwise it's * <code>TYPE_UNKNOWN</code>. * * @param shx the shearing factor in the x direction. * @param shy the shearing factor in the y direction. * @return the new AffineTransformation. */ public static CGAffineTransform makeShear(double shx, double shy) { CGAffineTransform m = new CGAffineTransform(); m.setToShear(shx, shy); return m; } /** * Creates a new AffineTransformation that is a rotation alone. The new * transformation's type is <code>TYPE_IDENTITY</code> if the * AffineTransformation is the identity transformation, otherwise it's * <code>TYPE_UNKNOWN</code>. * * @param angle the angle of rotation in radians. * @return the new AffineTransformation. */ public static CGAffineTransform makeRotation(double angle) { CGAffineTransform t = new CGAffineTransform(); t.setToRotation(angle); return t; } /** * Creates a new AffineTransformation that is a rotation followed by a * translation. Sets the type to <code>TYPE_UNKNOWN</code>. * * @param angle the angle of rotation in radians. * @param x the distance to translate in the x direction. * @param y the distance to translate in the y direction. * @return the new AffineTransformation. */ public static CGAffineTransform makeRotation(double angle, double x, double y) { CGAffineTransform t = new CGAffineTransform(); t.setToRotation(angle, x, y); return t; } /** * Applies a translation to this AffineTransformation. * * @param mx the distance to translate in the x direction. * @param my the distance to translate in the y direction. */ public CGAffineTransform getTransformTranslate(double mx, double my) { return getTransformConcat(CGAffineTransform.makeTranslation(mx, my)); } /** * Applies a scaling transformation to this AffineTransformation. * * @param scx the scaling factor in the x direction. * @param scy the scaling factor in the y direction. */ public CGAffineTransform getTransformScale(double scx, double scy) { return getTransformConcat(CGAffineTransform.makeScale(scx, scy)); } /** * Applies a shearing transformation to this AffineTransformation. * * @param shx the shearing factor in the x direction. * @param shy the shearing factor in the y direction. */ public void shear(double shx, double shy) { getTransformConcat(CGAffineTransform.makeShear(shx, shy)); } /** * Applies a rotation transformation to this AffineTransformation. * * @param angle the angle of rotation in radians. */ public CGAffineTransform getTransformRotate(double angle) { return getTransformConcat(CGAffineTransform.makeRotation(angle)); } /** * Applies a rotation and translation transformation to this * AffineTransformation. * * @param angle the angle of rotation in radians. * @param px the distance to translate in the x direction. * @param py the distance to translate in the y direction. */ public void rotate(double angle, double px, double py) { getTransformConcat(CGAffineTransform.makeRotation(angle, px, py)); } /** * Multiplies the matrix representations of two AffineTransform objects. * * @param t1 - the AffineTransform object is a multiplicand * @param t2 - the AffineTransform object is a multiplier * @return an AffineTransform object that is the result of t1 multiplied by * the matrix t2. */ public static CGAffineTransform multiply(CGAffineTransform t1, CGAffineTransform t2) { return new CGAffineTransform(t1.m00 * t2.m00 + t1.m10 * t2.m01, // m00 t1.m00 * t2.m10 + t1.m10 * t2.m11, // m01 t1.m01 * t2.m00 + t1.m11 * t2.m01, // m10 t1.m01 * t2.m10 + t1.m11 * t2.m11, // m11 t1.m02 * t2.m00 + t1.m12 * t2.m01 + t2.m02, // m02 t1.m02 * t2.m10 + t1.m12 * t2.m11 + t2.m12);// m12 } /** * Applies the given AffineTransform to this AffineTransform via matrix * multiplication. * * @param t the AffineTransform to apply to this AffineTransform. */ public CGAffineTransform getTransformConcat(CGAffineTransform t) { return multiply(t, this); } /** * Changes the current AffineTransform the one obtained by taking the * transform t and applying this AffineTransform to it. * * @param t the AffineTransform that this AffineTransform is multiplied * by. */ public CGAffineTransform preConcatenate(CGAffineTransform t) { return multiply(this, t); } /** * Creates an AffineTransform that is the inverse of this transform. * * @return the affine transform that is the inverse of this AffineTransform. * @throws NoninvertibleTransformException * if this AffineTransform cannot be inverted (the determinant * of the linear transformation part is zero). */ public CGAffineTransform getTransformInvert() /*throws NoninvertibleTransformException*/ { double det = getDeterminant(); if (Math.abs(det) < ZERO) { // throw new NoninvertibleTransformException("Determinant is zero"); return this; } return new CGAffineTransform(m11 / det, // m00 -m10 / det, // m10 -m01 / det, // m01 m00 / det, // m11 (m01 * m12 - m11 * m02) / det, // m02 (m10 * m02 - m00 * m12) / det // m12 ); } /** * Apply the current AffineTransform to the point. * * @param src the original point. * @param dst Point2D object to be filled with the destination coordinates * (where the original point is sent by this AffineTransform). * May be null. * @return the point in the AffineTransform's image space where the original * point is sent. */ public CGPoint applyTransform(CGPoint src) { CGPoint dst = CGPoint.make(0, 0); float x = src.x; float y = src.y; dst.x = (float) (x * m00 + y * m01 + m02); dst.y = (float) (x * m10 + y * m11 + m12); return dst; } /** * Applies this AffineTransform to an array of points. * * @param src the array of points to be transformed. * @param srcOff the offset in the source point array of the first point to be * transformed. * @param dst the point array where the images of the points (after applying * the AffineTransformation) should be placed. * @param dstOff the offset in the destination array where the new values * should be written. * @param length the number of points to transform. * @throws ArrayIndexOutOfBoundsException if <code>srcOff + length > src.length</code> or * <code>dstOff + length > dst.length</code>. */ public void transform(CGPoint[] src, int srcOff, CGPoint[] dst, int dstOff, int length) { while (--length >= 0) { CGPoint srcPoint = src[srcOff++]; double x = srcPoint.x; double y = srcPoint.y; CGPoint dstPoint = dst[dstOff]; if (dstPoint == null) { dstPoint = CGPoint.zero(); } dstPoint.x = (float) (x * m00 + y * m01 + m02); dstPoint.y = (float) (x * m10 + y * m11 + m12); dst[dstOff++] = dstPoint; } } /** * Applies this AffineTransform to a set of points given as an array of * double values where every two values in the array give the coordinates of * a point; the even-indexed values giving the x coordinates and the * odd-indexed values giving the y coordinates. * * @param src the array of points to be transformed. * @param srcOff the offset in the source point array of the first point to be * transformed. * @param dst the point array where the images of the points (after applying * the AffineTransformation) should be placed. * @param dstOff the offset in the destination array where the new values * should be written. * @param length the number of points to transform. * @throws ArrayIndexOutOfBoundsException if <code>srcOff + length*2 > src.length</code> or * <code>dstOff + length*2 > dst.length</code>. */ public void transform(double[] src, int srcOff, double[] dst, int dstOff, int length) { int step = 2; if (src == dst && srcOff < dstOff && dstOff < srcOff + length * 2) { srcOff = srcOff + length * 2 - 2; dstOff = dstOff + length * 2 - 2; step = -2; } while (--length >= 0) { double x = src[srcOff + 0]; double y = src[srcOff + 1]; dst[dstOff + 0] = x * m00 + y * m01 + m02; dst[dstOff + 1] = x * m10 + y * m11 + m12; srcOff += step; dstOff += step; } } /** * Applies this AffineTransform to a set of points given as an array of * float values where every two values in the array give the coordinates of * a point; the even-indexed values giving the x coordinates and the * odd-indexed values giving the y coordinates. * * @param src the array of points to be transformed. * @param srcOff the offset in the source point array of the first point to be * transformed. * @param dst the point array where the images of the points (after applying * the AffineTransformation) should be placed. * @param dstOff the offset in the destination array where the new values * should be written. * @param length the number of points to transform. * @throws ArrayIndexOutOfBoundsException if <code>srcOff + length*2 > src.length</code> or * <code>dstOff + length*2 > dst.length</code>. */ public void transform(float[] src, int srcOff, float[] dst, int dstOff, int length) { int step = 2; if (src == dst && srcOff < dstOff && dstOff < srcOff + length * 2) { srcOff = srcOff + length * 2 - 2; dstOff = dstOff + length * 2 - 2; step = -2; } while (--length >= 0) { double x = src[srcOff + 0]; double y = src[srcOff + 1]; dst[dstOff + 0] = (float) (x * m00 + y * m01 + m02); dst[dstOff + 1] = (float) (x * m10 + y * m11 + m12); srcOff += step; dstOff += step; } } /** * Applies this AffineTransform to a set of points given as an array of * float values where every two values in the array give the coordinates of * a point; the even-indexed values giving the x coordinates and the * odd-indexed values giving the y coordinates. The destination coordinates * are given as values of type <code>double</code>. * * @param src the array of points to be transformed. * @param srcOff the offset in the source point array of the first point to be * transformed. * @param dst the point array where the images of the points (after applying * the AffineTransformation) should be placed. * @param dstOff the offset in the destination array where the new values * should be written. * @param length the number of points to transform. * @throws ArrayIndexOutOfBoundsException if <code>srcOff + length*2 > src.length</code> or * <code>dstOff + length*2 > dst.length</code>. */ public void transform(float[] src, int srcOff, double[] dst, int dstOff, int length) { while (--length >= 0) { float x = src[srcOff++]; float y = src[srcOff++]; dst[dstOff++] = x * m00 + y * m01 + m02; dst[dstOff++] = x * m10 + y * m11 + m12; } } /** * Applies this AffineTransform to a set of points given as an array of * double values where every two values in the array give the coordinates of * a point; the even-indexed values giving the x coordinates and the * odd-indexed values giving the y coordinates. The destination coordinates * are given as values of type <code>float</code>. * * @param src the array of points to be transformed. * @param srcOff the offset in the source point array of the first point to be * transformed. * @param dst the point array where the images of the points (after applying * the AffineTransformation) should be placed. * @param dstOff the offset in the destination array where the new values * should be written. * @param length the number of points to transform. * @throws ArrayIndexOutOfBoundsException if <code>srcOff + length*2 > src.length</code> or * <code>dstOff + length*2 > dst.length</code>. */ public void transform(double[] src, int srcOff, float[] dst, int dstOff, int length) { while (--length >= 0) { double x = src[srcOff++]; double y = src[srcOff++]; dst[dstOff++] = (float) (x * m00 + y * m01 + m02); dst[dstOff++] = (float) (x * m10 + y * m11 + m12); } } /** * Transforms the point according to the linear transformation part of this * AffineTransformation (without applying the translation). * * @param src the original point. * @param dst the point object where the result of the delta transform is * written. * @return the result of applying the delta transform (linear part only) to * the original point. */ // TODO: is this right? if dst is null, we check what it's an // instance of? Shouldn't it be src instanceof Point2D.Double? public CGPoint deltaTransform(CGPoint src, CGPoint dst) { if (dst == null) { dst = CGPoint.make(0, 0); } double x = src.x; double y = src.y; dst.x = (float) (x * m00 + y * m01); dst.y = (float) (x * m10 + y * m11); return dst; } /** * Applies the linear transformation part of this AffineTransform (ignoring * the translation part) to a set of points given as an array of double * values where every two values in the array give the coordinates of a * point; the even-indexed values giving the x coordinates and the * odd-indexed values giving the y coordinates. * * @param src the array of points to be transformed. * @param srcOff the offset in the source point array of the first point to be * transformed. * @param dst the point array where the images of the points (after applying * the delta transformation) should be placed. * @param dstOff the offset in the destination array where the new values * should be written. * @param length the number of points to transform. * @throws ArrayIndexOutOfBoundsException if <code>srcOff + length*2 > src.length</code> or * <code>dstOff + length*2 > dst.length</code>. */ public void deltaTransform(double[] src, int srcOff, double[] dst, int dstOff, int length) { while (--length >= 0) { double x = src[srcOff++]; double y = src[srcOff++]; dst[dstOff++] = x * m00 + y * m01; dst[dstOff++] = x * m10 + y * m11; } } /** * Transforms the point according to the inverse of this * AffineTransformation. * * @param src the original point. * @param dst the point object where the result of the inverse transform is * written (may be null). * @return the result of applying the inverse transform. Inverse transform. * @throws NoninvertibleTransformException * if this AffineTransform cannot be inverted (the determinant * of the linear transformation part is zero). */ public CGPoint inverseTransform(CGPoint src, CGPoint dst) throws NoninvertibleTransformException { double det = getDeterminant(); if (Math.abs(det) < ZERO) { throw new NoninvertibleTransformException("Determinant is zero"); //$NON-NLS-1$ } if (dst == null) { dst = CGPoint.zero(); } double x = src.x - m02; double y = src.y - m12; dst.x = (float) ((x * m11 - y * m01) / det); dst.y = (float) ((y * m00 - x * m10) / det); return dst; } /** * Applies the inverse of this AffineTransform to a set of points given as * an array of double values where every two values in the array give the * coordinates of a point; the even-indexed values giving the x coordinates * and the odd-indexed values giving the y coordinates. * * @param src the array of points to be transformed. * @param srcOff the offset in the source point array of the first point to be * transformed. * @param dst the point array where the images of the points (after applying * the inverse of the AffineTransformation) should be placed. * @param dstOff the offset in the destination array where the new values * should be written. * @param length the number of points to transform. * @throws ArrayIndexOutOfBoundsException if <code>srcOff + length*2 > src.length</code> or * <code>dstOff + length*2 > dst.length</code>. * @throws NoninvertibleTransformException * if this AffineTransform cannot be inverted (the determinant * of the linear transformation part is zero). */ public void inverseTransform(double[] src, int srcOff, double[] dst, int dstOff, int length) throws NoninvertibleTransformException { double det = getDeterminant(); if (Math.abs(det) < ZERO) { throw new NoninvertibleTransformException("Determinant is zero"); //$NON-NLS-1$ } while (--length >= 0) { double x = src[srcOff++] - m02; double y = src[srcOff++] - m12; dst[dstOff++] = (x * m11 - y * m01) / det; dst[dstOff++] = (y * m00 - x * m10) / det; } } public void set(double m00, double m10, double m01, double m11, double m02, double m12) { this.type = TYPE_UNKNOWN; this.m00 = m00; this.m10 = m10; this.m01 = m01; this.m11 = m11; this.m02 = m02; this.m12 = m12; } public void translate(double mx, double my) { type = TYPE_UNKNOWN; m02 = mx * m00 + my * m01 + m02; m12 = mx * m10 + my * m11 + m12; } public void rotate(double angle) { double sin = Math.sin(angle); double cos = Math.cos(angle); if (Math.abs(cos) < ZERO) { cos = 0.0; sin = sin > 0.0 ? 1.0 : -1.0; } else if (Math.abs(sin) < ZERO) { sin = 0.0; cos = cos > 0.0 ? 1.0 : -1.0; } type = TYPE_UNKNOWN; double m00 = cos * this.m00 + sin * this.m01; double m10 = cos * this.m10 + sin * this.m11; double m01 = -sin * this.m00 + cos * this.m01; double m11 = -sin * this.m10 + cos * this.m11; this.m00 = m00; this.m01 = m01; this.m10 = m10; this.m11 = m11; } public void scale(double scx, double scy) { type = TYPE_UNKNOWN; m00 = scx * m00; double m10 = scx * this.m10; double m01 = scy * this.m01; m11 = scy * m11; this.m01 = m01; this.m10 = m10; } public void multiply(CGAffineTransform t) { m00 = this.m00 * t.m00 + this.m10 * t.m01; m01 = this.m00 * t.m10 + this.m10 * t.m11; m10 = this.m01 * t.m00 + this.m11 * t.m01; m11 = this.m01 * t.m10 + this.m11 * t.m11; m02 = this.m02 * t.m00 + this.m12 * t.m01 + t.m02; m12 = this.m02 * t.m10 + this.m12 * t.m11 + t.m12; } // /** // * Creates a new shape whose data is given by applying this AffineTransform // * to the specified shape. // * // * @param src // * the original shape whose data is to be transformed. // * @return the new shape found by applying this AffineTransform to the // * original shape. // */ // public Shape createTransformedShape(Shape src) { // if (src == null) { // return null; // } // if (src instanceof GeneralPath) { // return ((GeneralPath)src).createTransformedShape(this); // } // PathIterator path = src.getPathIterator(this); // GeneralPath dst = new GeneralPath(path.getWindingRule()); // dst.append(path, false); // return dst; // } @Override public String toString() { return getClass().getName() + "[[" + m00 + ", " + m01 + ", " + m02 + "], [" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + m10 + ", " + m11 + ", " + m12 + "]]"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } @Override public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e) { throw new InternalError(); } } @Override public int hashCode() { HashCode hash = new HashCode(); hash.append(m00); hash.append(m01); hash.append(m02); hash.append(m10); hash.append(m11); hash.append(m12); return hash.hashCode(); } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (obj instanceof CGAffineTransform) { CGAffineTransform t = (CGAffineTransform) obj; return m00 == t.m00 && m01 == t.m01 && m02 == t.m02 && m10 == t.m10 && m11 == t.m11 && m12 == t.m12; } return false; } /** * Writes the AffineTrassform object to the output steam. * * @param stream - the output stream. * @throws java.io.IOException - if there are I/O errors while writing to the output stream. */ private void writeObject(java.io.ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); } /** * Read the AffineTransform object from the input stream. * * @param stream - the input stream. * @throws IOException - if there are I/O errors while reading from the input * stream. * @throws ClassNotFoundException - if class could not be found. */ private void readObject(java.io.ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); type = TYPE_UNKNOWN; } public static void CGAffineToGL(CGAffineTransform t, float []m) { // | m[0] m[4] m[8] m[12] | | m11 m21 m31 m41 | | a c 0 tx | // | m[1] m[5] m[9] m[13] | | m12 m22 m32 m42 | | b d 0 ty | // | m[2] m[6] m[10] m[14] | <=> | m13 m23 m33 m43 | <=> | 0 0 1 0 | // | m[3] m[7] m[11] m[15] | | m14 m24 m34 m44 | | 0 0 0 1 | m[2] = m[3] = m[6] = m[7] = m[8] = m[9] = m[11] = m[14] = 0.0f; m[10] = m[15] = 1.0f; m[0] = (float)t.m00; m[4] = (float)t.m01; m[12] = (float)t.m02; m[1] = (float)t.m10; m[5] = (float)t.m11; m[13] = (float)t.m12; } public static void GLToCGAffine(float []m, CGAffineTransform t) { t.m00 = m[0]; t.m01 = m[4]; t.m02 = m[12]; t.m10 = m[1]; t.m11 = m[5]; t.m12 = m[13]; } } final class HashCode { private final HashCode hashCode = new HashCode(); /** * Returns accumulated hashCode */ public final int hashCode() { return hashCode.hashCode(); } /** * Appends value's hashCode to the current hashCode. * * @param value new element * @return this */ public final HashCode append(int value) { return hashCode.append(value); } /** * Appends value's hashCode to the current hashCode. * * @param value new element * @return this */ public final HashCode append(long value) { return hashCode.append(value); } /** * Appends value's hashCode to the current hashCode. * * @param value new element * @return this */ public final HashCode append(float value) { return hashCode.append(value); } /** * Appends value's hashCode to the current hashCode. * * @param value new element * @return this */ public final HashCode append(double value) { return hashCode.append(value); } /** * Appends value's hashCode to the current hashCode. * * @param value new element * @return this */ public final HashCode append(boolean value) { return hashCode.append(value); } /** * Appends value's hashCode to the current hashCode. * * @param value new element * @return this */ public final HashCode append(Object value) { return hashCode.append(value); } }
Bugfix to CGAffineTransform.multiply. Thanks opengenius!
cocos2d-android/src/org/cocos2d/types/CGAffineTransform.java
Bugfix to CGAffineTransform.multiply. Thanks opengenius!
Java
apache-2.0
d7802c76be7fb11b1bf7206b190af2904e59b463
0
santhosh-tekuri/jlibs,santhosh-tekuri/jlibs
/** * JLibs: Common Utilities for Java * Copyright (C) 2009 Santhosh Kumar T <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. */ package jlibs.core.nio.channels; import jlibs.core.lang.ByteSequence; import jlibs.core.lang.Bytes; import jlibs.core.nio.AttachmentSupport; import jlibs.core.nio.ClientChannel; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.ReadableByteChannel; import java.util.Arrays; import java.util.Iterator; /** * @author Santhosh Kumar */ public abstract class InputChannel extends AttachmentSupport implements ReadableByteChannel{ protected final ClientChannel client; protected InputChannel(ClientChannel client){ this.client = client; IOChannelHandler handler = client.attachment() instanceof IOChannelHandler ? (IOChannelHandler)client.attachment() : null; if(handler==null) client.attach(handler=new IOChannelHandler()); handler.input = this; } public final ClientChannel client(){ return client; } public final void addInterest() throws IOException{ if(activateInterest()) client.addInterest(ClientChannel.OP_READ); else if(handler!=null) handler.onRead(this); } protected boolean activateInterest(){ return unread==null; } public void removeInterest() throws IOException{ client.removeInterest(ClientChannel.OP_READ); } protected InputHandler handler; public void setHandler(InputHandler handler){ this.handler = handler; } private boolean eof; @Override public final int read(ByteBuffer dst) throws IOException{ int pos = dst.position(); if(unread!=null){ Iterator<ByteSequence> sequences = unread.iterator(); while(sequences.hasNext()){ ByteSequence seq = sequences.next(); int remaining = Math.min(dst.remaining(), seq.length()); System.arraycopy(seq.buffer(), seq.offset(), dst.array(), dst.arrayOffset() + dst.position(), remaining); dst.position(dst.position()+remaining); if(remaining==seq.length()) sequences.remove(); else{ unread.remove(remaining); return dst.position()-pos; } } if(unread.isEmpty()) unread = null; } int read = 0; if(dst.hasRemaining()) read = doRead(dst); int result = dst.position() == pos && read == -1 ? -1 : dst.position() - pos; eof = result==-1; return result; } protected abstract int doRead(ByteBuffer dst) throws IOException; public boolean isEOF(){ return eof; } protected Bytes unread; public final void unread(byte buff[], int offset, int length, boolean clone){ if(length==0) return; eof = false; if(unread==null) unread = new Bytes(); if(clone){ buff = Arrays.copyOfRange(buff, offset, offset + length); offset = 0; } unread.prepend(new ByteSequence(buff, offset, length)); } public long pending(){ return unread==null ? 0 : unread.size(); } private boolean closed; @Override public final boolean isOpen(){ return !closed; } @Override public final void close() throws IOException{ closed = true; unread = null; } }
core/src/main/java/jlibs/core/nio/channels/InputChannel.java
/** * JLibs: Common Utilities for Java * Copyright (C) 2009 Santhosh Kumar T <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. */ package jlibs.core.nio.channels; import jlibs.core.lang.ByteSequence; import jlibs.core.lang.Bytes; import jlibs.core.nio.AttachmentSupport; import jlibs.core.nio.ClientChannel; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.ReadableByteChannel; import java.util.Arrays; import java.util.Iterator; /** * @author Santhosh Kumar */ public abstract class InputChannel extends AttachmentSupport implements ReadableByteChannel{ protected final ClientChannel client; protected InputChannel(ClientChannel client){ this.client = client; IOChannelHandler handler = client.attachment() instanceof IOChannelHandler ? (IOChannelHandler)client.attachment() : null; if(handler==null) client.attach(handler=new IOChannelHandler()); handler.input = this; } public final ClientChannel client(){ return client; } public final void addInterest() throws IOException{ if(activateInterest()) client.addInterest(ClientChannel.OP_READ); else if(handler!=null) handler.onRead(this); } protected boolean activateInterest(){ return unread==null; } public void removeInterest() throws IOException{ client.removeInterest(ClientChannel.OP_READ); } protected InputHandler handler; public void setHandler(InputHandler handler){ this.handler = handler; } private boolean eof; @Override public final int read(ByteBuffer dst) throws IOException{ int pos = dst.position(); if(unread!=null){ Iterator<ByteSequence> sequences = unread.iterator(); while(sequences.hasNext()){ ByteSequence seq = sequences.next(); int remaining = Math.min(dst.remaining(), seq.length()); System.arraycopy(seq.buffer(), seq.offset(), dst.array(), dst.arrayOffset() + dst.position(), remaining); dst.position(dst.position()+remaining); if(remaining==seq.length()) sequences.remove(); else{ unread.remove(remaining); return dst.position()-pos; } } if(unread.isEmpty()) unread = null; } int read = 0; if(dst.hasRemaining()) read = doRead(dst); int result = dst.position() == pos && read == -1 ? -1 : dst.position() - pos; eof = result==-1; return result; } protected abstract int doRead(ByteBuffer dst) throws IOException; public boolean isEOF(){ return eof; } private Bytes unread; public final void unread(byte buff[], int offset, int length, boolean clone){ if(length==0) return; eof = false; if(unread==null) unread = new Bytes(); if(clone){ buff = Arrays.copyOfRange(buff, offset, offset + length); offset = 0; } unread.prepend(new ByteSequence(buff, offset, length)); } public long pending(){ return unread==null ? 0 : unread.size(); } private boolean closed; @Override public final boolean isOpen(){ return !closed; } @Override public final void close() throws IOException{ closed = true; unread = null; } }
unread is made protected
core/src/main/java/jlibs/core/nio/channels/InputChannel.java
unread is made protected
Java
apache-2.0
3d887eef57f08a47133b9941e157ed4544b10b6f
0
remibantos/jeeshop,remibantos/jeeshop,remibantos/jeeshop,remibantos/jeeshop
package org.rembx.jeeshop.catalog; import java.util.Date; import java.util.List; /** * Created by remi on 20/05/14. */ public class Category { private Integer id; private String name; private String description; private List<Category> childCategories; private List<Product> childProducts; private Date startDate; private Date endDate; private Boolean disabled; private Promotion promotion; }
src/main/java/org/rembx/jeeshop/catalog/Category.java
package org.rembx.jeeshop.catalog; import java.util.Date; import java.util.List; /** * Created by remi on 20/05/14. */ public class Category { private Integer id; private String name; private String description; private List<Category> childCategories; private List<Product> childProducts; private Date startDate; private Date endDate; private Boolean disabled; private Image thumbnail; private Image smallImage; private Image largeImage; private Video video; }
Init domain classes
src/main/java/org/rembx/jeeshop/catalog/Category.java
Init domain classes
Java
apache-2.0
c45474b65e737c1c2d30f8b489163381b2adeabc
0
venicegeo/pz-gateway,venicegeo/pz-gateway,venicegeo/pz-gateway
/** * Copyright 2016, RadiantBlue Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ package gateway.controller; import gateway.controller.util.GatewayUtil; import gateway.controller.util.PiazzaRestController; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; import java.security.Principal; import model.response.ErrorResponse; import model.response.EventListResponse; import model.response.EventTypeListResponse; import model.response.PiazzaResponse; import model.workflow.Event; import model.workflow.EventType; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; import util.PiazzaLogger; /** * REST controller defining end points that interact with the Piazza workflow * service; including events and event types. * * @author Patrick.Doody * */ @Api @CrossOrigin @RestController public class EventController extends PiazzaRestController { @Autowired private GatewayUtil gatewayUtil; @Autowired private PiazzaLogger logger; @Value("${workflow.url}") private String WORKFLOW_URL; private static final String DEFAULT_PAGE_SIZE = "10"; private static final String DEFAULT_PAGE = "0"; private static final String DEFAULT_ORDER = "asc"; private RestTemplate restTemplate = new RestTemplate(); /** * Gets all events from the workflow component. * * @see http://pz-swagger.stage.geointservices.io/#!/Event/get_event * * @param user * The user submitting the request * @return The list of events, or the appropriate error. */ @RequestMapping(value = "/event", method = RequestMethod.GET, produces = "application/json") @ApiOperation(value = "Get all Events", notes = "Retrieves a list of all Events.", tags = { "Event", "Workflow" }, response=EventListResponse.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "The list of Events.") }) public ResponseEntity<?> getEvents( @ApiParam(value = "The name of the event type to filter by.") @RequestParam(value = "eventType", required = false) String eventType, @ApiParam(value = "The field to use for sorting.") @RequestParam(value = "key", required = false) String key, @ApiParam(value = "Indicates ascending or descending order.") @RequestParam(value = "order", required = false, defaultValue = DEFAULT_ORDER) String order, @ApiParam(value = "Paginating large numbers of results. This will determine the starting page for the query.") @RequestParam(value = "page", required = false, defaultValue = DEFAULT_PAGE) Integer page, @ApiParam(value = "The number of results to be returned per query.") @RequestParam(value = "per_page", required = false, defaultValue = DEFAULT_PAGE_SIZE) Integer pageSize, Principal user) { try { // Log the request logger.log(String.format("User %s queried for Events.", gatewayUtil.getPrincipalName(user)), PiazzaLogger.INFO); // Broker the request to Workflow String url = String.format("%s/v2/%s?page=%s&per_page=%s&order=%s&sort_by=%s&eventType=%s", WORKFLOW_URL, "event", page, pageSize, order, key != null ? key : "", eventType != null ? eventType : ""); String response = restTemplate.getForObject(url, String.class); return new ResponseEntity<String>(response, HttpStatus.OK); } catch (Exception exception) { exception.printStackTrace(); String error = String.format("Error Querying Events by user %s: %s", gatewayUtil.getPrincipalName(user), exception.getMessage()); logger.log(error, PiazzaLogger.ERROR); return new ResponseEntity<PiazzaResponse>(new ErrorResponse(null, error, "Gateway"), HttpStatus.INTERNAL_SERVER_ERROR); } } /** * Fires a new event to the workflow component. * * @see pz-swagger.stage.geointservices.io/#!/Event/post_event_eventTypeId * * @param event * The event to be fired * @param user * The user submitting the event * @return The event ID, or an error. */ @RequestMapping(value = "/event/", method = RequestMethod.POST, produces = "application/json") @ApiOperation(value = "Creates an Event for the Event Type", notes = "Fires an Event with the Piazza Workflow component. Events must conform to the specified Event Type.", tags = { "Event", "Workflow" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "The ID of the newly created Event") }) public ResponseEntity<?> fireEvent( @ApiParam(value = "The Event JSON object.", required = true) @RequestBody String event, Principal user) { try { // Log the request logger.log(String.format("User %s has fired an event.", gatewayUtil.getPrincipalName(user)), PiazzaLogger.INFO); // Broker the request to Workflow String response = restTemplate.postForObject(String.format("%s/v2/%s", WORKFLOW_URL, "event"), event, String.class); return new ResponseEntity<String>(response, HttpStatus.OK); } catch (Exception exception) { exception.printStackTrace(); String error = String.format("Error Submitting Event by user %s: %s", gatewayUtil.getPrincipalName(user), exception.getMessage()); logger.log(error, PiazzaLogger.ERROR); return new ResponseEntity<PiazzaResponse>(new ErrorResponse(null, error, "Gateway"), HttpStatus.INTERNAL_SERVER_ERROR); } } /** * Gets the Specific event details for a single event. * * @see "http://pz-swagger.stage.geointservices.io/#!/Event/get_event_eventTypeId_eventId" * * @param eventType * The event type of the event * @param eventId * the unique ID of the event * @param user * The user executing the request * @return The event metadata, or an error */ @RequestMapping(value = "/event/{eventId}", method = RequestMethod.GET, produces = "application/json") @ApiOperation(value = "Get a specifc Event", notes = "Gets a specific Event by it's ID, that corresponds with the Event Type.", tags = { "Event", "Workflow" }, response = Event.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "The requested Event.") }) public ResponseEntity<?> getEventInformation( @ApiParam(value = "The Event ID for the event to retrieve.", required = true) @PathVariable(value = "eventId") String eventId, Principal user) { try { // Log the message logger.log(String.format("User %s requesting information on Event %s", gatewayUtil.getPrincipalName(user), eventId), PiazzaLogger.INFO); // Broker the request to pz-workflow String response = restTemplate.getForObject(String.format("%s/v2/%s/%s", WORKFLOW_URL, "event", eventId), String.class); return new ResponseEntity<String>(response, HttpStatus.OK); } catch (Exception exception) { exception.printStackTrace(); String error = String.format("Error Querying Event %s by user %s: %s", eventId, gatewayUtil.getPrincipalName(user), exception.getMessage()); logger.log(error, PiazzaLogger.ERROR); return new ResponseEntity<PiazzaResponse>(new ErrorResponse(null, error, "Gateway"), HttpStatus.INTERNAL_SERVER_ERROR); } } /** * Deletes the Specific Event * * @see "http://pz-swagger.stage.geointservices.io/#!/Event/delete_event_eventTypeId_eventId" * * @param eventType * The event type of the event to delete * @param eventId * the unique ID of the event to delete * @param user * The user executing the request * @return 200 OK, or an error */ @RequestMapping(value = "/event/{eventId}", method = RequestMethod.DELETE, produces = "application/json") @ApiOperation(value = "Delete a specific Event", notes = "Deletes a specific Event by it's ID, that corresponds with the Event Type.", tags = { "Event", "Workflow" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "Confirmation of delete.") }) public ResponseEntity<?> deleteEvent( @ApiParam(value = "The Event ID for the event to delete.", required = true) @PathVariable(value = "eventId") String eventId, Principal user) { try { // Log the message logger.log(String.format("User %s Requesting Deletion for Event %s", gatewayUtil.getPrincipalName(user), eventId), PiazzaLogger.INFO); // Broker the request to pz-workflow restTemplate.delete(String.format("%s/v2/%s/%s", WORKFLOW_URL, "event", eventId), String.class); return null; } catch (Exception exception) { exception.printStackTrace(); String error = String.format("Error Deleting Event %s by user %s: %s", eventId, gatewayUtil.getPrincipalName(user), exception.getMessage()); logger.log(error, PiazzaLogger.ERROR); return new ResponseEntity<PiazzaResponse>(new ErrorResponse(null, error, "Gateway"), HttpStatus.INTERNAL_SERVER_ERROR); } } /** * Gets the list of Event Types. * * @see "http://pz-swagger.stage.geointservices.io/#!/Event_Type/get_eventType" * * @return The list of event types, or an error. */ @RequestMapping(value = "/eventType", method = RequestMethod.GET, produces = "application/json") @ApiOperation(value = "List Event Types", notes = "Lists all Event Types that have been registered with the Piazza Workflow service.", tags = { "Event Type", "Workflow" }, response=EventTypeListResponse.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "The list of Event Types.") }) public ResponseEntity<?> getEventTypes( @ApiParam(value = "The field to use for sorting.") @RequestParam(value = "key", required = false) String key, @ApiParam(value = "Indicates ascending or descending order.") @RequestParam(value = "order", required = false, defaultValue = DEFAULT_ORDER) String order, @ApiParam(value = "Paginating large numbers of results. This will determine the starting page for the query.") @RequestParam(value = "page", required = false, defaultValue = DEFAULT_PAGE) Integer page, @ApiParam(value = "The number of results to be returned per query.") @RequestParam(value = "per_page", required = false, defaultValue = DEFAULT_PAGE_SIZE) Integer pageSize, Principal user) { try { // Log the request logger.log( String.format("User %s has requested a list of Event Types.", gatewayUtil.getPrincipalName(user)), PiazzaLogger.INFO); // Broker the request to Workflow String url = String.format("%s/v2/%s?page=%s&per_page=%s&order=%s&sort_by=%s", WORKFLOW_URL, "eventType", page, pageSize, order, key != null ? key : ""); String response = restTemplate.getForObject(url, String.class); return new ResponseEntity<String>(response, HttpStatus.OK); } catch (Exception exception) { exception.printStackTrace(); String error = String.format("Error Querying Event Types by user %s: %s", gatewayUtil.getPrincipalName(user), exception.getMessage()); logger.log(error, PiazzaLogger.ERROR); return new ResponseEntity<PiazzaResponse>(new ErrorResponse(null, error, "Gateway"), HttpStatus.INTERNAL_SERVER_ERROR); } } /** * Creates a new Event Type. * * @see "http://pz-swagger.stage.geointservices.io/#!/Event_Type/post_eventType" * * @param eventType * The event Type JSON. * @param user * The user making the request * @return The ID of the event type, or an error. */ @RequestMapping(value = "/eventType", method = RequestMethod.POST, produces = "application/json") @ApiOperation(value = "Register an Event Type", notes = "Defines an Event Type with the Workflow component, that defines a schema that Events can conform to and be fired for.", tags = { "Event Type", "Workflow" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "The ID of the newly created Event Type") }) public ResponseEntity<?> createEventType( @ApiParam(value = "The Event Type information. This defines the Schema for the Events that must be followed.", required = true) @RequestBody String eventType, Principal user) { try { // Log the message logger.log(String.format("User %s has requested a new Event Type to be created.", gatewayUtil.getPrincipalName(user)), PiazzaLogger.INFO); // Proxy the request to Workflow String url = String.format("%s/v2/%s", WORKFLOW_URL, "eventType"); String response = restTemplate.postForObject(url, eventType, String.class); return new ResponseEntity<String>(response, HttpStatus.OK); } catch (Exception exception) { exception.printStackTrace(); String error = String.format("Error Creating Event Type by user %s: %s", gatewayUtil.getPrincipalName(user), exception.getMessage()); logger.log(error, PiazzaLogger.ERROR); return new ResponseEntity<PiazzaResponse>(new ErrorResponse(null, error, "Gateway"), HttpStatus.INTERNAL_SERVER_ERROR); } } /** * Gets Event type metadata by the ID of the event type. * * @see "http://pz-swagger.stage.geointservices.io/#!/Event_Type/get_eventType_eventTypeId" * * @param eventTypeId * Event type ID * @param user * The user submitting the request * @return Event type information, or an error */ @RequestMapping(value = "/eventType/{eventTypeId}", method = RequestMethod.GET, produces = "application/json") @ApiOperation(value = "Get an Event Type", notes = "Returns the metadata for a specific Event Type by its unique identifier.", tags = { "Event Type", "Workflow" }, response = EventType.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "The Event Type metadata.") }) public ResponseEntity<?> getEventType( @ApiParam(value = "The unique identifier for the Event Type.", required = true) @PathVariable(value = "eventTypeId") String eventTypeId, Principal user) { try { // Log the request logger.log(String.format("User %s has requested information for Event Type %s", gatewayUtil.getPrincipalName(user), eventTypeId), PiazzaLogger.INFO); // Proxy the request to Workflow String url = String.format("%s/v2/%s/%s", WORKFLOW_URL, "eventType", eventTypeId); String response = restTemplate.getForObject(url, String.class); return new ResponseEntity<String>(response, HttpStatus.OK); } catch (Exception exception) { exception.printStackTrace(); String error = String.format("Error Getting Event Type ID %s by user %s: %s", eventTypeId, gatewayUtil.getPrincipalName(user), exception.getMessage()); logger.log(error, PiazzaLogger.ERROR); return new ResponseEntity<PiazzaResponse>(new ErrorResponse(null, error, "Gateway"), HttpStatus.INTERNAL_SERVER_ERROR); } } /** * Deletes an Event Type * * @see "http://pz-swagger.stage.geointservices.io/#!/Event_Type/delete_eventType_eventTypeId" * * @param eventTypeId * The ID of the event type to delete * @param user * The user executing the request * @return 200 OK if deleted, error if exceptions occurred */ @RequestMapping(value = "/eventType/{eventTypeId}", method = RequestMethod.DELETE, produces = "application/json") @ApiOperation(value = "Delete an Event Type", notes = "Deletes a specific Event Type, specified by its unique identifier.", tags = { "Event Type", "Workflow" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "Confirmation of Event Type deletion.") }) public ResponseEntity<?> deleteEventType( @ApiParam(value = "The unique identifier for the Event Type to delete.", required = true) @PathVariable(value = "eventTypeId") String eventTypeId, Principal user) { try { // Log the request logger.log(String.format("User %s has requested deletion of Event Type %s", gatewayUtil.getPrincipalName(user), eventTypeId), PiazzaLogger.INFO); // Proxy the request to Workflow String url = String.format("%s/v2/%s/%s", WORKFLOW_URL, "eventType", eventTypeId); restTemplate.delete(url); return null; } catch (Exception exception) { exception.printStackTrace(); String error = String.format("Error Deleting Event Type ID %s by user %s: %s", eventTypeId, gatewayUtil.getPrincipalName(user), exception.getMessage()); logger.log(error, PiazzaLogger.ERROR); return new ResponseEntity<PiazzaResponse>(new ErrorResponse(null, error, "Gateway"), HttpStatus.INTERNAL_SERVER_ERROR); } } }
src/main/java/gateway/controller/EventController.java
/** * Copyright 2016, RadiantBlue Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ package gateway.controller; import gateway.controller.util.GatewayUtil; import gateway.controller.util.PiazzaRestController; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; import java.security.Principal; import model.response.ErrorResponse; import model.response.EventListResponse; import model.response.EventTypeListResponse; import model.response.PiazzaResponse; import model.workflow.EventType; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; import com.fasterxml.jackson.dataformat.yaml.snakeyaml.events.Event; import util.PiazzaLogger; /** * REST controller defining end points that interact with the Piazza workflow * service; including events and event types. * * @author Patrick.Doody * */ @Api @CrossOrigin @RestController public class EventController extends PiazzaRestController { @Autowired private GatewayUtil gatewayUtil; @Autowired private PiazzaLogger logger; @Value("${workflow.url}") private String WORKFLOW_URL; private static final String DEFAULT_PAGE_SIZE = "10"; private static final String DEFAULT_PAGE = "0"; private static final String DEFAULT_ORDER = "asc"; private RestTemplate restTemplate = new RestTemplate(); /** * Gets all events from the workflow component. * * @see http://pz-swagger.stage.geointservices.io/#!/Event/get_event * * @param user * The user submitting the request * @return The list of events, or the appropriate error. */ @RequestMapping(value = "/event", method = RequestMethod.GET, produces = "application/json") @ApiOperation(value = "Get all Events", notes = "Retrieves a list of all Events.", tags = { "Event", "Workflow" }, response=EventListResponse.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "The list of Events.") }) public ResponseEntity<?> getEvents( @ApiParam(value = "The name of the event type to filter by.") @RequestParam(value = "eventType", required = false) String eventType, @ApiParam(value = "The field to use for sorting.") @RequestParam(value = "key", required = false) String key, @ApiParam(value = "Indicates ascending or descending order.") @RequestParam(value = "order", required = false, defaultValue = DEFAULT_ORDER) String order, @ApiParam(value = "Paginating large numbers of results. This will determine the starting page for the query.") @RequestParam(value = "page", required = false, defaultValue = DEFAULT_PAGE) Integer page, @ApiParam(value = "The number of results to be returned per query.") @RequestParam(value = "per_page", required = false, defaultValue = DEFAULT_PAGE_SIZE) Integer pageSize, Principal user) { try { // Log the request logger.log(String.format("User %s queried for Events.", gatewayUtil.getPrincipalName(user)), PiazzaLogger.INFO); // Broker the request to Workflow String url = String.format("%s/v2/%s?page=%s&per_page=%s&order=%s&sort_by=%s&eventType=%s", WORKFLOW_URL, "event", page, pageSize, order, key != null ? key : "", eventType != null ? eventType : ""); String response = restTemplate.getForObject(url, String.class); return new ResponseEntity<String>(response, HttpStatus.OK); } catch (Exception exception) { exception.printStackTrace(); String error = String.format("Error Querying Events by user %s: %s", gatewayUtil.getPrincipalName(user), exception.getMessage()); logger.log(error, PiazzaLogger.ERROR); return new ResponseEntity<PiazzaResponse>(new ErrorResponse(null, error, "Gateway"), HttpStatus.INTERNAL_SERVER_ERROR); } } /** * Fires a new event to the workflow component. * * @see pz-swagger.stage.geointservices.io/#!/Event/post_event_eventTypeId * * @param event * The event to be fired * @param user * The user submitting the event * @return The event ID, or an error. */ @RequestMapping(value = "/event/", method = RequestMethod.POST, produces = "application/json") @ApiOperation(value = "Creates an Event for the Event Type", notes = "Fires an Event with the Piazza Workflow component. Events must conform to the specified Event Type.", tags = { "Event", "Workflow" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "The ID of the newly created Event") }) public ResponseEntity<?> fireEvent( @ApiParam(value = "The Event JSON object.", required = true) @RequestBody String event, Principal user) { try { // Log the request logger.log(String.format("User %s has fired an event.", gatewayUtil.getPrincipalName(user)), PiazzaLogger.INFO); // Broker the request to Workflow String response = restTemplate.postForObject(String.format("%s/v2/%s", WORKFLOW_URL, "event"), event, String.class); return new ResponseEntity<String>(response, HttpStatus.OK); } catch (Exception exception) { exception.printStackTrace(); String error = String.format("Error Submitting Event by user %s: %s", gatewayUtil.getPrincipalName(user), exception.getMessage()); logger.log(error, PiazzaLogger.ERROR); return new ResponseEntity<PiazzaResponse>(new ErrorResponse(null, error, "Gateway"), HttpStatus.INTERNAL_SERVER_ERROR); } } /** * Gets the Specific event details for a single event. * * @see "http://pz-swagger.stage.geointservices.io/#!/Event/get_event_eventTypeId_eventId" * * @param eventType * The event type of the event * @param eventId * the unique ID of the event * @param user * The user executing the request * @return The event metadata, or an error */ @RequestMapping(value = "/event/{eventId}", method = RequestMethod.GET, produces = "application/json") @ApiOperation(value = "Get a specifc Event", notes = "Gets a specific Event by it's ID, that corresponds with the Event Type.", tags = { "Event", "Workflow" }, response = Event.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "The requested Event.") }) public ResponseEntity<?> getEventInformation( @ApiParam(value = "The Event ID for the event to retrieve.", required = true) @PathVariable(value = "eventId") String eventId, Principal user) { try { // Log the message logger.log(String.format("User %s requesting information on Event %s", gatewayUtil.getPrincipalName(user), eventId), PiazzaLogger.INFO); // Broker the request to pz-workflow String response = restTemplate.getForObject(String.format("%s/v2/%s/%s", WORKFLOW_URL, "event", eventId), String.class); return new ResponseEntity<String>(response, HttpStatus.OK); } catch (Exception exception) { exception.printStackTrace(); String error = String.format("Error Querying Event %s by user %s: %s", eventId, gatewayUtil.getPrincipalName(user), exception.getMessage()); logger.log(error, PiazzaLogger.ERROR); return new ResponseEntity<PiazzaResponse>(new ErrorResponse(null, error, "Gateway"), HttpStatus.INTERNAL_SERVER_ERROR); } } /** * Deletes the Specific Event * * @see "http://pz-swagger.stage.geointservices.io/#!/Event/delete_event_eventTypeId_eventId" * * @param eventType * The event type of the event to delete * @param eventId * the unique ID of the event to delete * @param user * The user executing the request * @return 200 OK, or an error */ @RequestMapping(value = "/event/{eventId}", method = RequestMethod.DELETE, produces = "application/json") @ApiOperation(value = "Delete a specific Event", notes = "Deletes a specific Event by it's ID, that corresponds with the Event Type.", tags = { "Event", "Workflow" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "Confirmation of delete.") }) public ResponseEntity<?> deleteEvent( @ApiParam(value = "The Event ID for the event to delete.", required = true) @PathVariable(value = "eventId") String eventId, Principal user) { try { // Log the message logger.log(String.format("User %s Requesting Deletion for Event %s", gatewayUtil.getPrincipalName(user), eventId), PiazzaLogger.INFO); // Broker the request to pz-workflow restTemplate.delete(String.format("%s/v2/%s/%s", WORKFLOW_URL, "event", eventId), String.class); return null; } catch (Exception exception) { exception.printStackTrace(); String error = String.format("Error Deleting Event %s by user %s: %s", eventId, gatewayUtil.getPrincipalName(user), exception.getMessage()); logger.log(error, PiazzaLogger.ERROR); return new ResponseEntity<PiazzaResponse>(new ErrorResponse(null, error, "Gateway"), HttpStatus.INTERNAL_SERVER_ERROR); } } /** * Gets the list of Event Types. * * @see "http://pz-swagger.stage.geointservices.io/#!/Event_Type/get_eventType" * * @return The list of event types, or an error. */ @RequestMapping(value = "/eventType", method = RequestMethod.GET, produces = "application/json") @ApiOperation(value = "List Event Types", notes = "Lists all Event Types that have been registered with the Piazza Workflow service.", tags = { "Event Type", "Workflow" }, response=EventTypeListResponse.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "The list of Event Types.") }) public ResponseEntity<?> getEventTypes( @ApiParam(value = "The field to use for sorting.") @RequestParam(value = "key", required = false) String key, @ApiParam(value = "Indicates ascending or descending order.") @RequestParam(value = "order", required = false, defaultValue = DEFAULT_ORDER) String order, @ApiParam(value = "Paginating large numbers of results. This will determine the starting page for the query.") @RequestParam(value = "page", required = false, defaultValue = DEFAULT_PAGE) Integer page, @ApiParam(value = "The number of results to be returned per query.") @RequestParam(value = "per_page", required = false, defaultValue = DEFAULT_PAGE_SIZE) Integer pageSize, Principal user) { try { // Log the request logger.log( String.format("User %s has requested a list of Event Types.", gatewayUtil.getPrincipalName(user)), PiazzaLogger.INFO); // Broker the request to Workflow String url = String.format("%s/v2/%s?page=%s&per_page=%s&order=%s&sort_by=%s", WORKFLOW_URL, "eventType", page, pageSize, order, key != null ? key : ""); String response = restTemplate.getForObject(url, String.class); return new ResponseEntity<String>(response, HttpStatus.OK); } catch (Exception exception) { exception.printStackTrace(); String error = String.format("Error Querying Event Types by user %s: %s", gatewayUtil.getPrincipalName(user), exception.getMessage()); logger.log(error, PiazzaLogger.ERROR); return new ResponseEntity<PiazzaResponse>(new ErrorResponse(null, error, "Gateway"), HttpStatus.INTERNAL_SERVER_ERROR); } } /** * Creates a new Event Type. * * @see "http://pz-swagger.stage.geointservices.io/#!/Event_Type/post_eventType" * * @param eventType * The event Type JSON. * @param user * The user making the request * @return The ID of the event type, or an error. */ @RequestMapping(value = "/eventType", method = RequestMethod.POST, produces = "application/json") @ApiOperation(value = "Register an Event Type", notes = "Defines an Event Type with the Workflow component, that defines a schema that Events can conform to and be fired for.", tags = { "Event Type", "Workflow" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "The ID of the newly created Event Type") }) public ResponseEntity<?> createEventType( @ApiParam(value = "The Event Type information. This defines the Schema for the Events that must be followed.", required = true) @RequestBody String eventType, Principal user) { try { // Log the message logger.log(String.format("User %s has requested a new Event Type to be created.", gatewayUtil.getPrincipalName(user)), PiazzaLogger.INFO); // Proxy the request to Workflow String url = String.format("%s/v2/%s", WORKFLOW_URL, "eventType"); String response = restTemplate.postForObject(url, eventType, String.class); return new ResponseEntity<String>(response, HttpStatus.OK); } catch (Exception exception) { exception.printStackTrace(); String error = String.format("Error Creating Event Type by user %s: %s", gatewayUtil.getPrincipalName(user), exception.getMessage()); logger.log(error, PiazzaLogger.ERROR); return new ResponseEntity<PiazzaResponse>(new ErrorResponse(null, error, "Gateway"), HttpStatus.INTERNAL_SERVER_ERROR); } } /** * Gets Event type metadata by the ID of the event type. * * @see "http://pz-swagger.stage.geointservices.io/#!/Event_Type/get_eventType_eventTypeId" * * @param eventTypeId * Event type ID * @param user * The user submitting the request * @return Event type information, or an error */ @RequestMapping(value = "/eventType/{eventTypeId}", method = RequestMethod.GET, produces = "application/json") @ApiOperation(value = "Get an Event Type", notes = "Returns the metadata for a specific Event Type by its unique identifier.", tags = { "Event Type", "Workflow" }, response = EventType.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "The Event Type metadata.") }) public ResponseEntity<?> getEventType( @ApiParam(value = "The unique identifier for the Event Type.", required = true) @PathVariable(value = "eventTypeId") String eventTypeId, Principal user) { try { // Log the request logger.log(String.format("User %s has requested information for Event Type %s", gatewayUtil.getPrincipalName(user), eventTypeId), PiazzaLogger.INFO); // Proxy the request to Workflow String url = String.format("%s/v2/%s/%s", WORKFLOW_URL, "eventType", eventTypeId); String response = restTemplate.getForObject(url, String.class); return new ResponseEntity<String>(response, HttpStatus.OK); } catch (Exception exception) { exception.printStackTrace(); String error = String.format("Error Getting Event Type ID %s by user %s: %s", eventTypeId, gatewayUtil.getPrincipalName(user), exception.getMessage()); logger.log(error, PiazzaLogger.ERROR); return new ResponseEntity<PiazzaResponse>(new ErrorResponse(null, error, "Gateway"), HttpStatus.INTERNAL_SERVER_ERROR); } } /** * Deletes an Event Type * * @see "http://pz-swagger.stage.geointservices.io/#!/Event_Type/delete_eventType_eventTypeId" * * @param eventTypeId * The ID of the event type to delete * @param user * The user executing the request * @return 200 OK if deleted, error if exceptions occurred */ @RequestMapping(value = "/eventType/{eventTypeId}", method = RequestMethod.DELETE, produces = "application/json") @ApiOperation(value = "Delete an Event Type", notes = "Deletes a specific Event Type, specified by its unique identifier.", tags = { "Event Type", "Workflow" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "Confirmation of Event Type deletion.") }) public ResponseEntity<?> deleteEventType( @ApiParam(value = "The unique identifier for the Event Type to delete.", required = true) @PathVariable(value = "eventTypeId") String eventTypeId, Principal user) { try { // Log the request logger.log(String.format("User %s has requested deletion of Event Type %s", gatewayUtil.getPrincipalName(user), eventTypeId), PiazzaLogger.INFO); // Proxy the request to Workflow String url = String.format("%s/v2/%s/%s", WORKFLOW_URL, "eventType", eventTypeId); restTemplate.delete(url); return null; } catch (Exception exception) { exception.printStackTrace(); String error = String.format("Error Deleting Event Type ID %s by user %s: %s", eventTypeId, gatewayUtil.getPrincipalName(user), exception.getMessage()); logger.log(error, PiazzaLogger.ERROR); return new ResponseEntity<PiazzaResponse>(new ErrorResponse(null, error, "Gateway"), HttpStatus.INTERNAL_SERVER_ERROR); } } }
Fix event reference
src/main/java/gateway/controller/EventController.java
Fix event reference
Java
apache-2.0
dcda1701bfdc78901a5183ec80863e361778720d
0
josephcsible/GravityBox
/* * Copyright (C) 2013 CyanKang Project * Copyright (C) 2013 Peter Gregus for GravityBox Project (C3C076@xda) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ceco.kitkat.gravitybox; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.ConnectivityManager; import android.net.TrafficStats; import android.os.SystemClock; import android.util.AttributeSet; import android.view.View; import android.widget.TextView; import java.text.DecimalFormat; import java.text.NumberFormat; import java.io.IOException; import java.io.BufferedReader; import java.io.FileReader; import com.ceco.kitkat.gravitybox.R; import com.ceco.kitkat.gravitybox.StatusBarIconManager.ColorInfo; import com.ceco.kitkat.gravitybox.StatusBarIconManager.IconManagerListener; import de.robv.android.xposed.XposedBridge; public class TrafficMeter extends TextView implements IconManagerListener { public static final String TAG = "GB:TrafficMeter"; private static final boolean DEBUG = false; public static final int INACTIVITY_MODE_DEFAULT = 0; public static final int INACTIVITY_MODE_HIDDEN = 1; public static final int INACTIVITY_MODE_SUMMARY = 2; Context mContext; boolean mAttached; boolean mTrafficMeterEnable; boolean mTrafficMeterHide = false; int mTrafficMeterSummaryTime = 0; long mTotalRxBytes; long mLastUpdateTime; long mTrafficBurstStartTime; long mTrafficBurstStartBytes; long mKeepOnUntil = Long.MIN_VALUE; int mPosition = GravityBoxSettings.DT_POSITION_AUTO; String mB = "B"; String mKB = "KB"; String mMB = "MB"; String mS = "s"; NumberFormat mDecimalFormat = new DecimalFormat("##0.0"); NumberFormat mIntegerFormat = NumberFormat.getIntegerInstance(); private static void log(String message) { XposedBridge.log(TAG + ": " + message); } public TrafficMeter(Context context) { this(context, null); } public TrafficMeter(Context context, AttributeSet attrs) { this(context, attrs, 0); } public TrafficMeter(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); mContext = context; try { Context gbContext = mContext.createPackageContext( GravityBox.PACKAGE_NAME, Context.CONTEXT_IGNORE_SECURITY); mB = gbContext.getString(R.string.byte_abbr); mKB = gbContext.getString(R.string.kilobyte_abbr); mMB = gbContext.getString(R.string.megabyte_abbr); mS = gbContext.getString(R.string.second_abbr); } catch (Exception e) { log(e.getMessage()); } updateState(); } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); if (!mAttached) { mAttached = true; IntentFilter filter = new IntentFilter(); filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); getContext().registerReceiver(mIntentReceiver, filter, null, getHandler()); if (DEBUG) log("attached to window"); } } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); if (mAttached) { stopTrafficUpdates(); getContext().unregisterReceiver(mIntentReceiver); mAttached = false; if (DEBUG) log("detached from window"); } } private final BroadcastReceiver mIntentReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) { updateState(); } } }; @Override public void onScreenStateChanged(int screenState) { if (screenState == SCREEN_STATE_OFF) { stopTrafficUpdates(); } else { startTrafficUpdates(); } super.onScreenStateChanged(screenState); } private void stopTrafficUpdates() { if (mAttached) { getHandler().removeCallbacks(mRunnable); setText(""); if (DEBUG) log("traffic updates stopped"); } } public void startTrafficUpdates() { if (mAttached && getConnectAvailable()) { mTotalRxBytes = TrafficStats.getTotalRxBytes(); if (mTotalRxBytes == 0) { // On some old devices, the traffic status will stick on 0B/s // So let's check by another way mTotalRxBytes = getTotalReceivedBytes(); } mLastUpdateTime = SystemClock.elapsedRealtime(); mTrafficBurstStartTime = Long.MIN_VALUE; getHandler().removeCallbacks(mRunnable); getHandler().post(mRunnable); if (DEBUG) log("traffic updates started"); } } private String formatTraffic(long bytes, boolean speed) { if (bytes > 10485760) { // 1024 * 1024 * 10 return (speed ? "" : "(") + mIntegerFormat.format(bytes / 1048576) + (speed ? mMB + "/" + mS : mMB + ")"); } else if (bytes > 1048576) { // 1024 * 1024 return (speed ? "" : "(") + mDecimalFormat.format(((float) bytes) / 1048576f) + (speed ? mMB + "/" + mS : mMB + ")"); } else if (bytes > 10240) { // 1024 * 10 return (speed ? "" : "(") + mIntegerFormat.format(bytes / 1024) + (speed ? mKB + "/" + mS : mKB + ")"); } else if (bytes > 1024) { // 1024 return (speed ? "" : "(") + mDecimalFormat.format(((float) bytes) / 1024f) + (speed ? mKB + "/" + mS : mKB + ")"); } else { return (speed ? "" : "(") + mIntegerFormat.format(bytes) + (speed ? mB + "/" + mS : mB + ")"); } } private boolean getConnectAvailable() { try { ConnectivityManager connectivityManager = (ConnectivityManager) mContext .getSystemService(Context.CONNECTIVITY_SERVICE); return connectivityManager.getActiveNetworkInfo().isConnected() || getTotalReceivedBytes() != 0; } catch (Exception ignored) { } return false; } Runnable mRunnable = new Runnable() { @Override public void run() { long td = SystemClock.elapsedRealtime() - mLastUpdateTime; if (!mTrafficMeterEnable) { return; } long currentRxBytes = TrafficStats.getTotalRxBytes(); long newBytes = currentRxBytes - mTotalRxBytes; if (newBytes <= 0) { // On some old devices, the traffic status will stick on 0B/s // So let's check by another way currentRxBytes = getTotalReceivedBytes(); newBytes = currentRxBytes - mTotalRxBytes; } if (mTrafficMeterHide && newBytes == 0) { long trafficBurstBytes = currentRxBytes - mTrafficBurstStartBytes; if (trafficBurstBytes != 0 && mTrafficMeterSummaryTime != 0) { setText(formatTraffic(trafficBurstBytes, false)); if (DEBUG) log("Traffic burst ended: " + trafficBurstBytes + "B in " + (SystemClock.elapsedRealtime() - mTrafficBurstStartTime) / 1000 + "s"); mKeepOnUntil = SystemClock.elapsedRealtime() + mTrafficMeterSummaryTime; mTrafficBurstStartTime = Long.MIN_VALUE; mTrafficBurstStartBytes = currentRxBytes; } } else { if (mTrafficMeterHide && mTrafficBurstStartTime == Long.MIN_VALUE) { mTrafficBurstStartTime = mLastUpdateTime; mTrafficBurstStartBytes = mTotalRxBytes; } if (td > 0) { setText(formatTraffic(newBytes * 1000 / td, true)); } } // Hide if there is no traffic if (mTrafficMeterHide && newBytes == 0) { if (getVisibility() != GONE && mKeepOnUntil < SystemClock.elapsedRealtime()) { setText(""); setVisibility(View.GONE); } } else { if (getVisibility() != VISIBLE) { setVisibility(View.VISIBLE); } } mTotalRxBytes = currentRxBytes; mLastUpdateTime = SystemClock.elapsedRealtime(); getHandler().postDelayed(mRunnable, 1000); } }; private void updateState() { if (DEBUG) log("updating state"); if (mTrafficMeterEnable && getConnectAvailable()) { setVisibility(View.VISIBLE); startTrafficUpdates(); } else { stopTrafficUpdates(); setVisibility(View.GONE); setText(""); } } private long getTotalReceivedBytes() { String line; String[] segs; long received = 0; int i; long tmp = 0; boolean isNum; try { FileReader fr = new FileReader("/proc/net/dev"); BufferedReader in = new BufferedReader(fr, 500); while ((line = in.readLine()) != null) { line = line.trim(); if (line.startsWith("rmnet") || line.startsWith("eth") || line.startsWith("wlan")) { segs = line.split(":")[1].split(" "); for (i = 0; i < segs.length; i++) { isNum = true; try { tmp = Long.parseLong(segs[i]); } catch (Exception e) { isNum = false; } if (isNum == true) { received = received + tmp; break; } } } } in.close(); } catch (IOException e) { return -1; } return received; } public void setTrafficMeterEnabled(boolean enabled) { mTrafficMeterEnable = enabled; updateState(); } public void setTrafficMeterPosition(int position) { mPosition = position; } public int getTrafficMeterPosition() { return mPosition; } public void setInactivityMode(int mode) { switch (mode) { case INACTIVITY_MODE_HIDDEN: mTrafficMeterHide = true; mTrafficMeterSummaryTime = 0; break; case INACTIVITY_MODE_SUMMARY: mTrafficMeterHide = true; mTrafficMeterSummaryTime = 3000; break; case INACTIVITY_MODE_DEFAULT: default: mTrafficMeterHide = false; mTrafficMeterSummaryTime = 0; break; } } @Override public void onIconManagerStatusChanged(int flags, ColorInfo colorInfo) { if ((flags & StatusBarIconManager.FLAG_ICON_COLOR_CHANGED) != 0) { setTextColor(colorInfo.coloringEnabled ? colorInfo.iconColor[0] : colorInfo.defaultIconColor); } else if ((flags & StatusBarIconManager.FLAG_LOW_PROFILE_CHANGED) != 0) { setAlpha(colorInfo.lowProfile ? 0 : 1); } else if ((flags & StatusBarIconManager.FLAG_ICON_ALPHA_CHANGED) != 0) { setAlpha(colorInfo.alphaTextAndBattery); } } }
src/com/ceco/kitkat/gravitybox/TrafficMeter.java
/* * Copyright (C) 2013 CyanKang Project * Copyright (C) 2013 Peter Gregus for GravityBox Project (C3C076@xda) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ceco.kitkat.gravitybox; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.ConnectivityManager; import android.net.TrafficStats; import android.os.SystemClock; import android.util.AttributeSet; import android.view.View; import android.widget.TextView; import java.text.DecimalFormat; import java.text.NumberFormat; import com.ceco.kitkat.gravitybox.R; import com.ceco.kitkat.gravitybox.StatusBarIconManager.ColorInfo; import com.ceco.kitkat.gravitybox.StatusBarIconManager.IconManagerListener; import de.robv.android.xposed.XposedBridge; public class TrafficMeter extends TextView implements IconManagerListener { public static final String TAG = "GB:TrafficMeter"; private static final boolean DEBUG = false; public static final int INACTIVITY_MODE_DEFAULT = 0; public static final int INACTIVITY_MODE_HIDDEN = 1; public static final int INACTIVITY_MODE_SUMMARY = 2; Context mContext; boolean mAttached; boolean mTrafficMeterEnable; boolean mTrafficMeterHide = false; int mTrafficMeterSummaryTime = 0; long mTotalRxBytes; long mLastUpdateTime; long mTrafficBurstStartTime; long mTrafficBurstStartBytes; long mKeepOnUntil = Long.MIN_VALUE; int mPosition = GravityBoxSettings.DT_POSITION_AUTO; String mB = "B"; String mKB = "KB"; String mMB = "MB"; String mS = "s"; NumberFormat mDecimalFormat = new DecimalFormat("##0.0"); NumberFormat mIntegerFormat = NumberFormat.getIntegerInstance(); private static void log(String message) { XposedBridge.log(TAG + ": " + message); } public TrafficMeter(Context context) { this(context, null); } public TrafficMeter(Context context, AttributeSet attrs) { this(context, attrs, 0); } public TrafficMeter(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); mContext = context; try { Context gbContext = mContext.createPackageContext( GravityBox.PACKAGE_NAME, Context.CONTEXT_IGNORE_SECURITY); mB = gbContext.getString(R.string.byte_abbr); mKB = gbContext.getString(R.string.kilobyte_abbr); mMB = gbContext.getString(R.string.megabyte_abbr); mS = gbContext.getString(R.string.second_abbr); } catch (Exception e) { log(e.getMessage()); } updateState(); } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); if (!mAttached) { mAttached = true; IntentFilter filter = new IntentFilter(); filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); getContext().registerReceiver(mIntentReceiver, filter, null, getHandler()); if (DEBUG) log("attached to window"); } } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); if (mAttached) { stopTrafficUpdates(); getContext().unregisterReceiver(mIntentReceiver); mAttached = false; if (DEBUG) log("detached from window"); } } private final BroadcastReceiver mIntentReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) { updateState(); } } }; @Override public void onScreenStateChanged(int screenState) { if (screenState == SCREEN_STATE_OFF) { stopTrafficUpdates(); } else { startTrafficUpdates(); } super.onScreenStateChanged(screenState); } private void stopTrafficUpdates() { if (mAttached) { getHandler().removeCallbacks(mRunnable); setText(""); if (DEBUG) log("traffic updates stopped"); } } public void startTrafficUpdates() { if (mAttached && getConnectAvailable()) { mTotalRxBytes = TrafficStats.getTotalRxBytes(); mLastUpdateTime = SystemClock.elapsedRealtime(); mTrafficBurstStartTime = Long.MIN_VALUE; getHandler().removeCallbacks(mRunnable); getHandler().post(mRunnable); if (DEBUG) log("traffic updates started"); } } private String formatTraffic(long bytes, boolean speed) { if (bytes > 10485760) { // 1024 * 1024 * 10 return (speed ? "" : "(") + mIntegerFormat.format(bytes / 1048576) + (speed ? mMB + "/" + mS : mMB + ")"); } else if (bytes > 1048576) { // 1024 * 1024 return (speed ? "" : "(") + mDecimalFormat.format(((float) bytes) / 1048576f) + (speed ? mMB + "/" + mS : mMB + ")"); } else if (bytes > 10240) { // 1024 * 10 return (speed ? "" : "(") + mIntegerFormat.format(bytes / 1024) + (speed ? mKB + "/" + mS : mKB + ")"); } else if (bytes > 1024) { // 1024 return (speed ? "" : "(") + mDecimalFormat.format(((float) bytes) / 1024f) + (speed ? mKB + "/" + mS : mKB + ")"); } else { return (speed ? "" : "(") + mIntegerFormat.format(bytes) + (speed ? mB + "/" + mS : mB + ")"); } } private boolean getConnectAvailable() { try { ConnectivityManager connectivityManager = (ConnectivityManager) mContext .getSystemService(Context.CONNECTIVITY_SERVICE); return connectivityManager.getActiveNetworkInfo().isConnected(); } catch (Exception ignored) { } return false; } Runnable mRunnable = new Runnable() { @Override public void run() { long td = SystemClock.elapsedRealtime() - mLastUpdateTime; if (!mTrafficMeterEnable) { return; } long currentRxBytes = TrafficStats.getTotalRxBytes(); long newBytes = currentRxBytes - mTotalRxBytes; if (mTrafficMeterHide && newBytes == 0) { long trafficBurstBytes = currentRxBytes - mTrafficBurstStartBytes; if (trafficBurstBytes != 0 && mTrafficMeterSummaryTime != 0) { setText(formatTraffic(trafficBurstBytes, false)); if (DEBUG) log("Traffic burst ended: " + trafficBurstBytes + "B in " + (SystemClock.elapsedRealtime() - mTrafficBurstStartTime) / 1000 + "s"); mKeepOnUntil = SystemClock.elapsedRealtime() + mTrafficMeterSummaryTime; mTrafficBurstStartTime = Long.MIN_VALUE; mTrafficBurstStartBytes = currentRxBytes; } } else { if (mTrafficMeterHide && mTrafficBurstStartTime == Long.MIN_VALUE) { mTrafficBurstStartTime = mLastUpdateTime; mTrafficBurstStartBytes = mTotalRxBytes; } if (td > 0) { setText(formatTraffic(newBytes * 1000 / td, true)); } } // Hide if there is no traffic if (mTrafficMeterHide && newBytes == 0) { if (getVisibility() != GONE && mKeepOnUntil < SystemClock.elapsedRealtime()) { setText(""); setVisibility(View.GONE); } } else { if (getVisibility() != VISIBLE) { setVisibility(View.VISIBLE); } } mTotalRxBytes = currentRxBytes; mLastUpdateTime = SystemClock.elapsedRealtime(); getHandler().postDelayed(mRunnable, 1000); } }; private void updateState() { if (DEBUG) log("updating state"); if (mTrafficMeterEnable && getConnectAvailable()) { setVisibility(View.VISIBLE); startTrafficUpdates(); } else { stopTrafficUpdates(); setVisibility(View.GONE); setText(""); } } public void setTrafficMeterEnabled(boolean enabled) { mTrafficMeterEnable = enabled; updateState(); } public void setTrafficMeterPosition(int position) { mPosition = position; } public int getTrafficMeterPosition() { return mPosition; } public void setInactivityMode(int mode) { switch (mode) { case INACTIVITY_MODE_HIDDEN: mTrafficMeterHide = true; mTrafficMeterSummaryTime = 0; break; case INACTIVITY_MODE_SUMMARY: mTrafficMeterHide = true; mTrafficMeterSummaryTime = 3000; break; case INACTIVITY_MODE_DEFAULT: default: mTrafficMeterHide = false; mTrafficMeterSummaryTime = 0; break; } } @Override public void onIconManagerStatusChanged(int flags, ColorInfo colorInfo) { if ((flags & StatusBarIconManager.FLAG_ICON_COLOR_CHANGED) != 0) { setTextColor(colorInfo.coloringEnabled ? colorInfo.iconColor[0] : colorInfo.defaultIconColor); } else if ((flags & StatusBarIconManager.FLAG_LOW_PROFILE_CHANGED) != 0) { setAlpha(colorInfo.lowProfile ? 0 : 1); } else if ((flags & StatusBarIconManager.FLAG_ICON_ALPHA_CHANGED) != 0) { setAlpha(colorInfo.alphaTextAndBattery); } } }
TrafficMeter: double-check traffic stats On some old devices(like my poor MI-ONE Plus), the traffic stats used to stick on 0B/s forever. This patch does a workaround to this bug by checking traffic stats from /proc/net/dev when the Android interface returns zero. Revised by C3C0: - fixed identation (we use spaces instead of tabs) - buffered reader needs to be closed explicitly, otherwise leaks may occur
src/com/ceco/kitkat/gravitybox/TrafficMeter.java
TrafficMeter: double-check traffic stats
Java
apache-2.0
8384a2ba8d4deccb847e64f5ae1eef0d75f5fc38
0
vamshikr/java-api,mirswamp/java-api
package edu.uiuc.ncsa.swamp.util; import org.apache.commons.lang.ArrayUtils; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.util.EntityUtils; import java.util.HashSet; /** * Utilities used for debugging. * <p>Created by Jeff Gaynor<br> * on 10/8/14 at 11:21 AM */ public class DebugUtil { public static boolean isDebugOff() { return debugOff; } /** * Set this to false to globally turn off all debug prints. * @param debugOff */ public static void setDebugOff(boolean debugOff) { DebugUtil.debugOff = debugOff; } static boolean debugOff = false; public static void say(Object x) { if(debugOff) return; System.out.println(x.toString()); } public static void say(String x) { if(debugOff) return; System.out.println(x); } public static void say(Object obj, Object x) { if(debugOff) return; say(obj.getClass().getSimpleName() + x); } public static boolean isJSONStringEmpty(String x) { return x == null || 0 == x.length() || "null".equals(x); // needed if, say, JSON returns the string "null". } public static Character[] intersection(Character[] x, String y) { return intersection(x, ArrayUtils.toObject(y.toCharArray())); } public static Character[] intersection(String x, String y) { return intersection(ArrayUtils.toObject(x.toCharArray()), ArrayUtils.toObject(y.toCharArray())); } public static Character[] intersection(Character[] x, Character[] y) { HashSet<Character> a = new HashSet<Character>(); // cuts out duplicates. for (int i = 0; i < x.length; i++) { for (int j = 0; j < y.length; j++) { if (x[i].equals(y[j])) { a.add(x[i]); } } } Character[] z = new Character[a.size()]; a.toArray(z); return z; } public static void printPost(HttpPost post) { printPost(post, null); } public static void printPost(HttpPost post, HttpEntity entity) { if(debugOff) return; try { say(""); // make a blank line so this is more readable. Header[] headers = post.getAllHeaders(); String content = EntityUtils.toString(entity); say(post.toString()); if (headers != null && 0 < headers.length) { for (Header header : headers) { say(header.getName() + ": " + header.getValue()); } } else { say("(no headers)"); } if (entity == null) { say("No body to post"); } else { say("=========== content"); say(content); say("=========== end content"); } } catch (Throwable t) { t.printStackTrace(); say("Was unable to print the post"); } } }
src/main/java/edu/uiuc/ncsa/swamp/util/DebugUtil.java
package edu.uiuc.ncsa.swamp.util; import org.apache.commons.lang.ArrayUtils; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.util.EntityUtils; import java.util.HashSet; /** * Utilities used for debugging. * <p>Created by Jeff Gaynor<br> * on 10/8/14 at 11:21 AM */ public class DebugUtil { public static boolean isDebugOff() { return debugOff; } /** * Set this to false to globally turn off all debug prints. * @param debugOff */ public static void setDebugOff(boolean debugOff) { DebugUtil.debugOff = debugOff; } static boolean debugOff = false; public static void say(Object x) { if(debugOff) return; System.out.println(x.toString()); } public static void say(String x) { if(debugOff) return; System.out.println(x); } public static void say(Object obj, Object x) { if(debugOff) return; say(obj.getClass().getSimpleName() + x); } public static boolean isJSONStringEmpty(String x) { return x == null || 0 == x.length() || x == "null"; // needed if, say, JSON returns the string "null". } public static Character[] intersection(Character[] x, String y) { return intersection(x, ArrayUtils.toObject(y.toCharArray())); } public static Character[] intersection(String x, String y) { return intersection(ArrayUtils.toObject(x.toCharArray()), ArrayUtils.toObject(y.toCharArray())); } public static Character[] intersection(Character[] x, Character[] y) { HashSet<Character> a = new HashSet<Character>(); // cuts out duplicates. for (int i = 0; i < x.length; i++) { for (int j = 0; j < y.length; j++) { if (x[i].equals(y[j])) { a.add(x[i]); } } } Character[] z = new Character[a.size()]; a.toArray(z); return z; } public static void printPost(HttpPost post) { printPost(post, null); } public static void printPost(HttpPost post, HttpEntity entity) { if(debugOff) return; try { say(""); // make a blank line so this is more readable. Header[] headers = post.getAllHeaders(); String content = EntityUtils.toString(entity); say(post.toString()); if (headers != null && 0 < headers.length) { for (Header header : headers) { say(header.getName() + ": " + header.getValue()); } } else { say("(no headers)"); } if (entity == null) { say("No body to post"); } else { say("=========== content"); say(content); say("=========== end content"); } } catch (Throwable t) { t.printStackTrace(); say("Was unable to print the post"); } } }
CWE 597 - Use of Wrong Operator in String Compare Using '==' or '!=' to compare strings only works if intern version is used on both sides. Use the equals() method instead. Found by Checkstyle, FindBugs, error-prone, and PMD in SWAMP.
src/main/java/edu/uiuc/ncsa/swamp/util/DebugUtil.java
CWE 597 - Use of Wrong Operator in String Compare
Java
apache-2.0
837b61c2d8852ca9875f8c7c2e435361f94fbb98
0
ripdajacker/commons-betwixt,ripdajacker/commons-betwixt,ripdajacker/commons-betwixt
/* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//betwixt/src/test/org/apache/commons/betwixt/xmlunit/XmlTestCase.java,v 1.8 2003/07/02 19:55:02 rdonkin Exp $ * $Revision: 1.8 $ * $Date: 2003/07/02 19:55:02 $ * * ==================================================================== * * The Apache Software License, Version 1.1 * * Copyright (c) 1999-2002 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Commons", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * * $Id: XmlTestCase.java,v 1.8 2003/07/02 19:55:02 rdonkin Exp $ */ package org.apache.commons.betwixt.xmlunit; import java.util.Collections; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Iterator; import java.io.File; import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import junit.framework.AssertionFailedError; import junit.framework.TestCase; import org.w3c.dom.Attr; import org.w3c.dom.DOMException; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.NodeList; import org.w3c.dom.Node; import org.xml.sax.InputSource; import org.xml.sax.SAXException; /** * Provides xml test utilities. * Hopefully, these might be moved into [xmlunit] sometime. * * @author Robert Burrell Donkin */ public class XmlTestCase extends TestCase { protected static boolean debug = false; DocumentBuilderFactory domFactory; public XmlTestCase(String testName) { super(testName); } public void xmlAssertIsomorphicContent( org.w3c.dom.Document documentOne, org.w3c.dom.Document documentTwo) throws AssertionFailedError { log("Testing documents:" + documentOne.getDocumentElement().getNodeName() + " and " + documentTwo.getDocumentElement().getNodeName()); xmlAssertIsomorphicContent(documentOne, documentTwo, false); } public void xmlAssertIsomorphicContent( org.w3c.dom.Document documentOne, org.w3c.dom.Document documentTwo, boolean orderIndependent) throws AssertionFailedError { xmlAssertIsomorphicContent(null, documentOne, documentTwo, orderIndependent); } public void xmlAssertIsomorphicContent( String message, org.w3c.dom.Document documentOne, org.w3c.dom.Document documentTwo) throws AssertionFailedError { xmlAssertIsomorphicContent(message, documentOne, documentTwo, false); } public void xmlAssertIsomorphicContent( String message, org.w3c.dom.Document documentOne, org.w3c.dom.Document documentTwo, boolean orderIndependent) throws AssertionFailedError { // two documents have isomorphic content iff their root elements // are isomophic xmlAssertIsomorphic( message, documentOne.getDocumentElement(), documentTwo.getDocumentElement(), orderIndependent); } public void xmlAssertIsomorphic( org.w3c.dom.Node rootOne, org.w3c.dom.Node rootTwo) throws AssertionFailedError { xmlAssertIsomorphic(rootOne, rootTwo, false); } public void xmlAssertIsomorphic( org.w3c.dom.Node rootOne, org.w3c.dom.Node rootTwo, boolean orderIndependent) throws AssertionFailedError { xmlAssertIsomorphic(null, rootOne, rootTwo, orderIndependent); } public void xmlAssertIsomorphic( String message, org.w3c.dom.Node rootOne, org.w3c.dom.Node rootTwo) { xmlAssertIsomorphic(message, rootOne, rootTwo, false); } public void xmlAssertIsomorphic( String message, org.w3c.dom.Node rootOne, org.w3c.dom.Node rootTwo, boolean orderIndependent) throws AssertionFailedError { // first normalize the xml rootOne.normalize(); rootTwo.normalize(); // going to use recursion so avoid normalizing each time testIsomorphic(message, rootOne, rootTwo, orderIndependent); } private void testIsomorphic( String message, org.w3c.dom.Node nodeOne, org.w3c.dom.Node nodeTwo) throws AssertionFailedError { testIsomorphic(message, nodeOne, nodeTwo, false); } private void testIsomorphic( String message, org.w3c.dom.Node nodeOne, org.w3c.dom.Node nodeTwo, boolean orderIndependent) throws AssertionFailedError { try { if (debug) { log( "node 1 name=" + nodeOne.getNodeName() + " qname=" + nodeOne.getLocalName()); log( "node 2 name=" + nodeTwo.getNodeName() + " qname=" + nodeTwo.getLocalName()); } // compare node properties log("Comparing node properties"); assertEquals( (null == message ? "(Unequal node types)" : message + "(Unequal node types)"), nodeOne.getNodeType(), nodeTwo.getNodeType()); assertEquals( (null == message ? "(Unequal node names)" : message + "(Unequal node names)"), nodeOne.getNodeName(), nodeTwo.getNodeName()); assertEquals( (null == message ? "(Unequal node values)" : message + "(Unequal node values)"), trim(nodeOne.getNodeValue()), trim(nodeTwo.getNodeValue())); assertEquals( (null == message ? "(Unequal local names)" : message + "(Unequal local names)"), nodeOne.getLocalName(), nodeTwo.getLocalName()); assertEquals( (null == message ? "(Unequal namespace)" : message + "(Unequal namespace)"), nodeOne.getNamespaceURI(), nodeTwo.getNamespaceURI()); // compare attributes log("Comparing attributes"); // make sure both have them first assertEquals( (null == message ? "(Unequal attributes)" : message + "(Unequal attributes)"), nodeOne.hasAttributes(), nodeTwo.hasAttributes()); if (nodeOne.hasAttributes()) { // do the actual comparison // first we check the number of attributes are equal // we then check that for every attribute of node one, // a corresponding attribute exists in node two // (this should be sufficient to prove equality) NamedNodeMap attributesOne = nodeOne.getAttributes(); NamedNodeMap attributesTwo = nodeTwo.getAttributes(); assertEquals( (null == message ? "(Unequal attributes)" : message + "(Unequal attributes)"), attributesOne.getLength(), attributesTwo.getLength()); for (int i=0, size=attributesOne.getLength(); i<size; i++) { Attr attributeOne = (Attr) attributesOne.item(i); Attr attributeTwo = (Attr) attributesTwo.getNamedItemNS( attributeOne.getNamespaceURI(), attributeOne.getLocalName()); if (attributeTwo == null) { attributeTwo = (Attr) attributesTwo.getNamedItem(attributeOne.getName()); } // check attribute two exists if (attributeTwo == null) { String diagnosis = "[Missing attribute (" + attributeOne.getName() + ")]"; fail((null == message ? diagnosis : message + diagnosis)); } // now check attribute values assertEquals( (null == message ? "(Unequal attribute values)" : message + "(Unequal attribute values)"), attributeOne.getValue(), attributeTwo.getValue()); } } // compare children log("Comparing children"); // this time order is important // so we can just go down the list and compare node-wise using recursion List listOne = sanitize(nodeOne.getChildNodes()); List listTwo = sanitize(nodeTwo.getChildNodes()); if (orderIndependent) { log("[Order Independent]"); Comparator nodeByName = new NodeByNameComparator(); Collections.sort(listOne, nodeByName); Collections.sort(listTwo, nodeByName); } Iterator it = listOne.iterator(); Iterator iter2 = listTwo.iterator(); while (it.hasNext() & iter2.hasNext()) { Node nextOne = ((Node)it.next()); Node nextTwo = ((Node)iter2.next()); log(nextOne.getNodeName() + ":" + nextOne.getNodeValue()); log(nextTwo.getNodeName() + ":" + nextTwo.getNodeValue()); } assertEquals( (null == message ? "(Unequal child nodes@" + nodeOne.getNodeName() +")": message + "(Unequal child nodes @" + nodeOne.getNodeName() +")"), listOne.size(), listTwo.size()); it = listOne.iterator(); iter2 = listTwo.iterator(); while (it.hasNext() & iter2.hasNext()) { Node nextOne = ((Node)it.next()); Node nextTwo = ((Node)iter2.next()); log(nextOne.getNodeName() + " vs " + nextTwo.getNodeName()); testIsomorphic(message, nextOne, nextTwo, orderIndependent); } } catch (DOMException ex) { fail((null == message ? "" : message + " ") + "DOM exception" + ex.toString()); } } protected DocumentBuilder createDocumentBuilder() { try { return getDomFactory().newDocumentBuilder(); } catch (ParserConfigurationException e) { fail("Cannot create DOM builder: " + e.toString()); } // just to keep the compiler happy return null; } protected DocumentBuilderFactory getDomFactory() { // lazy creation if (domFactory == null) { domFactory = DocumentBuilderFactory.newInstance(); } return domFactory; } protected Document parseString(StringWriter writer) { try { return createDocumentBuilder().parse(new InputSource(new StringReader(writer.getBuffer().toString()))); } catch (SAXException e) { fail("Cannot create parse string: " + e.toString()); } catch (IOException e) { fail("Cannot create parse string: " + e.toString()); } // just to keep the compiler happy return null; } protected Document parseString(String string) { try { return createDocumentBuilder().parse(new InputSource(new StringReader(string))); } catch (SAXException e) { fail("Cannot create parse string: " + e.toString()); } catch (IOException e) { fail("Cannot create parse string: " + e.toString()); } // just to keep the compiler happy return null; } protected Document parseFile(String path) { try { return createDocumentBuilder().parse(new File(path)); } catch (SAXException e) { fail("Cannot create parse file: " + e.toString()); } catch (IOException e) { fail("Cannot create parse file: " + e.toString()); } // just to keep the compiler happy return null; } private void log(String message) { if (debug) { System.out.println("[XmlTestCase]" + message); } } private String trim(String trimThis) { if (trimThis == null) { return trimThis; } return trimThis.trim(); } private List sanitize(NodeList nodes) { ArrayList list = new ArrayList(); for (int i=0, size=nodes.getLength(); i<size; i++) { if ( nodes.item(i).getNodeType() == Node.TEXT_NODE ) { if ( !( nodes.item(i).getNodeValue() == null || nodes.item(i).getNodeValue().trim().length() == 0 )) { list.add(nodes.item(i)); } else { log("Ignoring text node:" + nodes.item(i).getNodeValue()); } } else { list.add(nodes.item(i)); } } return list; } private class NodeByNameComparator implements Comparator { public int compare(Object objOne, Object objTwo) { String nameOne = ((Node) objOne).getNodeName(); String nameTwo = ((Node) objTwo).getNodeName(); if (nameOne == null) { if (nameTwo == null) { return 0; } return -1; } if (nameTwo == null) { return 1; } return nameOne.compareTo(nameTwo); } } }
src/test/org/apache/commons/betwixt/xmlunit/XmlTestCase.java
/* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//betwixt/src/test/org/apache/commons/betwixt/xmlunit/XmlTestCase.java,v 1.7 2003/07/01 21:39:31 rdonkin Exp $ * $Revision: 1.7 $ * $Date: 2003/07/01 21:39:31 $ * * ==================================================================== * * The Apache Software License, Version 1.1 * * Copyright (c) 1999-2002 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Commons", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * * $Id: XmlTestCase.java,v 1.7 2003/07/01 21:39:31 rdonkin Exp $ */ package org.apache.commons.betwixt.xmlunit; import java.util.Collections; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Iterator; import java.io.File; import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import junit.framework.AssertionFailedError; import junit.framework.TestCase; import org.w3c.dom.Attr; import org.w3c.dom.DOMException; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.NodeList; import org.w3c.dom.Node; import org.xml.sax.InputSource; import org.xml.sax.SAXException; /** * Provides xml test utilities. * Hopefully, these might be moved into [xmlunit] sometime. * * @author Robert Burrell Donkin */ public class XmlTestCase extends TestCase { protected static boolean debug = false; DocumentBuilderFactory domFactory; public XmlTestCase(String testName) { super(testName); } public void testXMLUnit() throws Exception { xmlAssertIsomorphicContent( parseFile("src/test/org/apache/commons/betwixt/xmlunit/rss-example.xml"), parseFile("src/test/org/apache/commons/betwixt/xmlunit/rss-example.xml")); } public void xmlAssertIsomorphicContent( org.w3c.dom.Document documentOne, org.w3c.dom.Document documentTwo) throws AssertionFailedError { log("Testing documents:" + documentOne.getDocumentElement().getNodeName() + " and " + documentTwo.getDocumentElement().getNodeName()); xmlAssertIsomorphicContent(documentOne, documentTwo, false); } public void xmlAssertIsomorphicContent( org.w3c.dom.Document documentOne, org.w3c.dom.Document documentTwo, boolean orderIndependent) throws AssertionFailedError { xmlAssertIsomorphicContent(null, documentOne, documentTwo, orderIndependent); } public void xmlAssertIsomorphicContent( String message, org.w3c.dom.Document documentOne, org.w3c.dom.Document documentTwo) throws AssertionFailedError { xmlAssertIsomorphicContent(message, documentOne, documentTwo, false); } public void xmlAssertIsomorphicContent( String message, org.w3c.dom.Document documentOne, org.w3c.dom.Document documentTwo, boolean orderIndependent) throws AssertionFailedError { // two documents have isomorphic content iff their root elements // are isomophic xmlAssertIsomorphic( message, documentOne.getDocumentElement(), documentTwo.getDocumentElement(), orderIndependent); } public void xmlAssertIsomorphic( org.w3c.dom.Node rootOne, org.w3c.dom.Node rootTwo) throws AssertionFailedError { xmlAssertIsomorphic(rootOne, rootTwo, false); } public void xmlAssertIsomorphic( org.w3c.dom.Node rootOne, org.w3c.dom.Node rootTwo, boolean orderIndependent) throws AssertionFailedError { xmlAssertIsomorphic(null, rootOne, rootTwo, orderIndependent); } public void xmlAssertIsomorphic( String message, org.w3c.dom.Node rootOne, org.w3c.dom.Node rootTwo) { xmlAssertIsomorphic(message, rootOne, rootTwo, false); } public void xmlAssertIsomorphic( String message, org.w3c.dom.Node rootOne, org.w3c.dom.Node rootTwo, boolean orderIndependent) throws AssertionFailedError { // first normalize the xml rootOne.normalize(); rootTwo.normalize(); // going to use recursion so avoid normalizing each time testIsomorphic(message, rootOne, rootTwo, orderIndependent); } private void testIsomorphic( String message, org.w3c.dom.Node nodeOne, org.w3c.dom.Node nodeTwo) throws AssertionFailedError { testIsomorphic(message, nodeOne, nodeTwo, false); } private void testIsomorphic( String message, org.w3c.dom.Node nodeOne, org.w3c.dom.Node nodeTwo, boolean orderIndependent) throws AssertionFailedError { try { if (debug) { log( "node 1 name=" + nodeOne.getNodeName() + " qname=" + nodeOne.getLocalName()); log( "node 2 name=" + nodeTwo.getNodeName() + " qname=" + nodeTwo.getLocalName()); } // compare node properties log("Comparing node properties"); assertEquals( (null == message ? "(Unequal node types)" : message + "(Unequal node types)"), nodeOne.getNodeType(), nodeTwo.getNodeType()); assertEquals( (null == message ? "(Unequal node names)" : message + "(Unequal node names)"), nodeOne.getNodeName(), nodeTwo.getNodeName()); assertEquals( (null == message ? "(Unequal node values)" : message + "(Unequal node values)"), trim(nodeOne.getNodeValue()), trim(nodeTwo.getNodeValue())); assertEquals( (null == message ? "(Unequal local names)" : message + "(Unequal local names)"), nodeOne.getLocalName(), nodeTwo.getLocalName()); assertEquals( (null == message ? "(Unequal namespace)" : message + "(Unequal namespace)"), nodeOne.getNamespaceURI(), nodeTwo.getNamespaceURI()); // compare attributes log("Comparing attributes"); // make sure both have them first assertEquals( (null == message ? "(Unequal attributes)" : message + "(Unequal attributes)"), nodeOne.hasAttributes(), nodeTwo.hasAttributes()); if (nodeOne.hasAttributes()) { // do the actual comparison // first we check the number of attributes are equal // we then check that for every attribute of node one, // a corresponding attribute exists in node two // (this should be sufficient to prove equality) NamedNodeMap attributesOne = nodeOne.getAttributes(); NamedNodeMap attributesTwo = nodeTwo.getAttributes(); assertEquals( (null == message ? "(Unequal attributes)" : message + "(Unequal attributes)"), attributesOne.getLength(), attributesTwo.getLength()); for (int i=0, size=attributesOne.getLength(); i<size; i++) { Attr attributeOne = (Attr) attributesOne.item(i); Attr attributeTwo = (Attr) attributesTwo.getNamedItemNS( attributeOne.getNamespaceURI(), attributeOne.getLocalName()); if (attributeTwo == null) { attributeTwo = (Attr) attributesTwo.getNamedItem(attributeOne.getName()); } // check attribute two exists if (attributeTwo == null) { String diagnosis = "[Missing attribute (" + attributeOne.getName() + ")]"; fail((null == message ? diagnosis : message + diagnosis)); } // now check attribute values assertEquals( (null == message ? "(Unequal attribute values)" : message + "(Unequal attribute values)"), attributeOne.getValue(), attributeTwo.getValue()); } } // compare children log("Comparing children"); // this time order is important // so we can just go down the list and compare node-wise using recursion List listOne = sanitize(nodeOne.getChildNodes()); List listTwo = sanitize(nodeTwo.getChildNodes()); if (orderIndependent) { log("[Order Independent]"); Comparator nodeByName = new NodeByNameComparator(); Collections.sort(listOne, nodeByName); Collections.sort(listTwo, nodeByName); } Iterator it = listOne.iterator(); Iterator iter2 = listTwo.iterator(); while (it.hasNext() & iter2.hasNext()) { Node nextOne = ((Node)it.next()); Node nextTwo = ((Node)iter2.next()); log(nextOne.getNodeName() + ":" + nextOne.getNodeValue()); log(nextTwo.getNodeName() + ":" + nextTwo.getNodeValue()); } assertEquals( (null == message ? "(Unequal child nodes@" + nodeOne.getNodeName() +")": message + "(Unequal child nodes @" + nodeOne.getNodeName() +")"), listOne.size(), listTwo.size()); it = listOne.iterator(); iter2 = listTwo.iterator(); while (it.hasNext() & iter2.hasNext()) { Node nextOne = ((Node)it.next()); Node nextTwo = ((Node)iter2.next()); log(nextOne.getNodeName() + " vs " + nextTwo.getNodeName()); testIsomorphic(message, nextOne, nextTwo, orderIndependent); } } catch (DOMException ex) { fail((null == message ? "" : message + " ") + "DOM exception" + ex.toString()); } } protected DocumentBuilder createDocumentBuilder() { try { return getDomFactory().newDocumentBuilder(); } catch (ParserConfigurationException e) { fail("Cannot create DOM builder: " + e.toString()); } // just to keep the compiler happy return null; } protected DocumentBuilderFactory getDomFactory() { // lazy creation if (domFactory == null) { domFactory = DocumentBuilderFactory.newInstance(); } return domFactory; } protected Document parseString(StringWriter writer) { try { return createDocumentBuilder().parse(new InputSource(new StringReader(writer.getBuffer().toString()))); } catch (SAXException e) { fail("Cannot create parse string: " + e.toString()); } catch (IOException e) { fail("Cannot create parse string: " + e.toString()); } // just to keep the compiler happy return null; } protected Document parseString(String string) { try { return createDocumentBuilder().parse(new InputSource(new StringReader(string))); } catch (SAXException e) { fail("Cannot create parse string: " + e.toString()); } catch (IOException e) { fail("Cannot create parse string: " + e.toString()); } // just to keep the compiler happy return null; } protected Document parseFile(String path) { try { return createDocumentBuilder().parse(new File(path)); } catch (SAXException e) { fail("Cannot create parse file: " + e.toString()); } catch (IOException e) { fail("Cannot create parse file: " + e.toString()); } // just to keep the compiler happy return null; } private void log(String message) { if (debug) { System.out.println("[XmlTestCase]" + message); } } private String trim(String trimThis) { if (trimThis == null) { return trimThis; } return trimThis.trim(); } private List sanitize(NodeList nodes) { ArrayList list = new ArrayList(); for (int i=0, size=nodes.getLength(); i<size; i++) { if ( nodes.item(i).getNodeType() == Node.TEXT_NODE ) { if ( !( nodes.item(i).getNodeValue() == null || nodes.item(i).getNodeValue().trim().length() == 0 )) { list.add(nodes.item(i)); } else { log("Ignoring text node:" + nodes.item(i).getNodeValue()); } } else { list.add(nodes.item(i)); } } return list; } private class NodeByNameComparator implements Comparator { public int compare(Object objOne, Object objTwo) { String nameOne = ((Node) objOne).getNodeName(); String nameTwo = ((Node) objTwo).getNodeName(); if (nameOne == null) { if (nameTwo == null) { return 0; } return -1; } if (nameTwo == null) { return 1; } return nameOne.compareTo(nameTwo); } } }
Added separate test for xmlunit git-svn-id: e0a2df7b4ce4cc32c17d1b5ef795a6b05535dcc2@129144 13f79535-47bb-0310-9956-ffa450edef68
src/test/org/apache/commons/betwixt/xmlunit/XmlTestCase.java
Added separate test for xmlunit
Java
apache-2.0
36a5282c7d2379e0d8ba790638dcc7eaf67e619f
0
MyersResearchGroup/iBioSim,MyersResearchGroup/iBioSim,MyersResearchGroup/iBioSim
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.LhpnFile; import lpn.parser.Transition; 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 (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, null, null); // 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()) { System.out.println("------- curStateArray ----------"); 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("####### lpnTranStack #########"); 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, null, null); 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 (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()) { System.out.println("******* curStateArray *******"); printStateArray(curStateArray); System.out.println("******* nextStateArray *******"); printStateArray(nextStateArray); 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()) { System.out.println("***nextStateMap for stateStackTop after firedTran being added: "); 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()); } } } // System.out.println("-----------------------"); } 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()) { System.out.println("******** lpnTranStack ***********"); printLpnTranStack(lpnTranStack); } curIndexStack.push(0); totalStates++; } else { if (Options.getOutputSgFlag()) { if (Options.getDebugMode()) { System.out.println("******* curStateArray *******"); printStateArray(curStateArray); System.out.println("******* nextStateArray *******"); 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()) { System.out.println("***nextStateMap for stateStackTop after firedTran being added: "); printNextStateMap(stateStackTop.getNextStateMap()); } for (PrjState prjState : prjStateSet) { if (prjState == stateStackTop) { prjState.setNextStateMap((HashMap<Transition, PrjState>) stateStackTop.getNextStateMap().clone()); if (Options.getDebugMode()) { System.out.println("***nextStateMap for prjState: "); printNextStateMap(prjState.getNextStateMap()); } } } // System.out.println("-----------------------"); } } } 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 drawDependencyGraphsForNecessarySets(LhpnFile[] lpnList, HashMap<LpnTransitionPair, StaticSets> staticSetsMap) { String fileName = Options.getPrjSgPath() + "_necessarySet.dot"; BufferedWriter out; try { out = new BufferedWriter(new FileWriter(fileName)); out.write("digraph G {\n"); for (LpnTransitionPair seedTran : staticSetsMap.keySet()) { for (LpnTransitionPair canEnableTran : staticSetsMap.get(seedTran).getEnableSet()) { } } 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>(); for (int i=0; i<lpnList.length; i++) allTransitions.put(i, lpnList[i].getAllTransitions()); HashMap<LpnTransitionPair, Integer> tranFiringFreq = new HashMap<LpnTransitionPair, Integer>(allTransitions.keySet().size()); for (int lpnIndex=0; lpnIndex<lpnList.length; lpnIndex++) { if (Options.getDebugMode()) System.out.println("LPN = " + lpnList[lpnIndex].getLabel()); for (Transition curTran: allTransitions.get(lpnIndex)) { StaticSets curStatic = new StaticSets(curTran, allTransitions); curStatic.buildCurTranDisableOtherTransSet(lpnIndex); if (Options.getPORdeadlockPreserve()) curStatic.buildOtherTransDisableCurTranSet(lpnIndex); curStatic.buildModifyAssignSet(); curStatic.buildEnableBySettingEnablingTrue(); // if (Options.getDebugMode()) // curStatic.buildEnableByBringingToken(); LpnTransitionPair lpnTranPair = new LpnTransitionPair(lpnIndex,curTran.getIndex()); staticSetsMap.put(lpnTranPair, curStatic); //if (!Options.getNecessaryUsingDependencyGraphs()) tranFiringFreq.put(lpnTranPair, 0); } } if (Options.getDebugMode()) { printStaticSetsMap(lpnList, staticSetsMap); writeStaticSetsMapToPORDebugFile(lpnList, staticSetsMap); // if (Options.getNecessaryUsingDependencyGraphs()) // drawDependencyGraphsForNecessarySets(lpnList, staticSetsMap); } boolean init = true; LpnTranList initAmpleTrans = new LpnTranList(); if (Options.getDebugMode()) System.out.println("call getAmple on curStateArray at 0: "); // if (Options.getNecessaryUsingDependencyGraphs()) // tranFiringFreq = null; initAmpleTrans = getAmple(initStateArray, null, staticSetsMap, init, tranFiringFreq, sgList, stateStack, stateStackTop); lpnTranStack.push(initAmpleTrans); init = false; if (Options.getDebugMode()) { System.out.println("+++++++ Push trans onto lpnTranStack @ 1++++++++"); printTransitionSet(initAmpleTrans, ""); } 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()) { System.out.println("~~~~~~~~~~~ loop begins ~~~~~~~~~~~"); writeStringWithNewLineToPORDebugFile("~~~~~~~~~~~ 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("####### lpnTranStack #########"); printLpnTranStack(lpnTranStack); // System.out.println("####### stateStack #########"); // printStateStack(stateStack); System.out.println("####### prjStateSet #########"); printPrjStateSet(prjStateSet); System.out.println("%%%%%%% Remove stateStackTop from stateStack %%%%%%%%"); } stateStack.remove(stateStackTop); stateStackTop = stateStackTop.getFather(); continue; } Transition firedTran = curAmpleTrans.removeLast(); if (Options.getDebugMode()) { System.out.println("#################################"); System.out.println("Fired Transition: " + firedTran.getLpn().getLabel() + "(" + firedTran.getName() + ")"); System.out.println("#################################"); writeStringWithNewLineToPORDebugFile("#################################"); writeStringWithNewLineToPORDebugFile("Fired Transition: " + firedTran.getLpn().getLabel() + "(" + firedTran.getName() + ")"); writeStringWithNewLineToPORDebugFile("#################################"); } LpnTransitionPair firedLpnTranPair = new LpnTransitionPair(firedTran.getLpn().getLpnIndex(), firedTran.getIndex()); // if (!Options.getNecessaryUsingDependencyGraphs()) { 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, null, null); 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(); // if (Options.getNecessaryUsingDependencyGraphs()) // nextAmpleTrans = getAmple(curStateArray, nextStateArray, staticSetsMap, init, null, sgList, prjStateSet, stateStackTop); // else nextAmpleTrans = getAmple(curStateArray, nextStateArray, staticSetsMap, init, tranFiringFreq, sgList, 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()) { System.out.println("******* curStateArray *******"); printStateArray(curStateArray); System.out.println("******* nextStateArray *******"); printStateArray(nextStateArray); 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()) { System.out.println("***nextStateMap for stateStackTop after firedTran being added: "); 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()); } } } // System.out.println("-----------------------"); } 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()) { System.out.println("******* curStateArray *******"); printStateArray(curStateArray); System.out.println("******* nextStateArray *******"); 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()) { System.out.println("***nextStateMap for stateStackTop after firedTran being added: "); printNextStateMap(stateStackTop.getNextStateMap()); } for (PrjState prjState : prjStateSet) { if (prjState == stateStackTop) { prjState.setNextStateMap((HashMap<Transition, PrjState>) stateStackTop.getNextStateMap().clone()); if (Options.getDebugMode()) { System.out.println("***nextStateMap for prjState: "); printNextStateMap(prjState.getNextStateMap()); } } } // System.out.println("-----------------------"); } 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, ""); System.out.println("******* lpnTranStack ***************"); 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); PORdebugBufferedWriter = new BufferedWriter(PORdebugFileStream); } catch (Exception e) { e.printStackTrace(); System.err.println("Error producing the debugging file for partial order reduction."); } } private void writeStringWithNewLineToPORDebugFile(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) { if (Options.getNecessaryUsingDependencyGraphs()) fileName = Options.getPrjSgPath() + Options.getLogName() + "_" + Options.getPOR() + "_" + Options.getCycleClosingMthd() + "_" + Options.getCycleClosingAmpleMethd() + ".log"; else 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()) System.out.println("****** behavioral: cycle closing check ********"); 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()) { System.out.println("******* nextStateArray *******"); 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"); System.out.println("******** behavioral: end of cycle closing check *****"); } } 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) { // System.out.println("---> calling function search_dfsPORrefinedCycleRule"); // if (cycleClosingMthdIndex == 1) // System.out.println("---> POR with behavioral analysis"); // else if (cycleClosingMthdIndex == 2) // System.out.println("---> POR with behavioral analysis and state trace-back"); // else if (cycleClosingMthdIndex == 4) // System.out.println("---> POR with Peled's cycle condition"); // 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(); // //// System.out.println("------- curStateArray ----------"); //// 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; // System.out.println("-------------- curAmpleArray --------------"); // for (LinkedList<Transition> tranList : curAmpleArray) { // printTransLinkedList(tranList); // } //// System.out.println("-------------- curAmpleArray --------------"); //// for (LinkedList<Transition> tranList : curAmpleArray) { //// printTransLinkedList(tranList); //// } //// System.out.println("-------------- nextAmpleArray --------------"); //// 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) { // System.out.println("*** Verification failed: deadlock."); // 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 printStaticSetsMap( LhpnFile[] lpnList, HashMap<LpnTransitionPair,StaticSets> staticSetsMap) { System.out.println("---------- staticSetsMap -----------"); for (LpnTransitionPair lpnTranPair : staticSetsMap.keySet()) { StaticSets statSets = staticSetsMap.get(lpnTranPair); printLpnTranPair(lpnList, statSets.getTran(), statSets.getDisableSet(), "disableSet"); printLpnTranPair(lpnList, statSets.getTran(), statSets.getEnableBySettingEnablingTrue(), "enableBySetingEnablingTrue"); } } private void writeStaticSetsMapToPORDebugFile( LhpnFile[] lpnList, HashMap<LpnTransitionPair,StaticSets> staticSetsMap) { try { PORdebugBufferedWriter.write("---------- staticSetsMap -----------"); PORdebugBufferedWriter.newLine(); for (LpnTransitionPair lpnTranPair : staticSetsMap.keySet()) { StaticSets statSets = staticSetsMap.get(lpnTranPair); writeLpnTranPairToPORDebugFile(lpnList, statSets.getTran(), statSets.getDisableSet(), "disableSet"); writeLpnTranPairToPORDebugFile(lpnList, statSets.getTran(), statSets.getEnableBySettingEnablingTrue(), "enableBySetingEnablingTrue"); } } 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 printPlacesIndices(ArrayList<String> allPlaces) { // System.out.println("Indices of all places: "); // for (int i=0; i < allPlaces.size(); i++) { // System.out.println(allPlaces.get(i) + "\t" + i); // } // // } // // private void printTransIndices(Transition[] allTransitions) { // System.out.println("Indices of all transitions: "); // for (int i=0; i < allTransitions.length; i++) { // System.out.println(allTransitions[i].getName() + "\t" + allTransitions[i].getIndex()); // } // } // 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> curDisable, String setName) { try { //PORdebugBufferedWriter.write(setName + " for " + curTran.getName() + "(" + curTran.getIndex() + ")" + " is: "); PORdebugBufferedWriter.write(setName + " for (" + curTran.getLpn().getLabel() + " , " + curTran.getName() + ") is: "); if (curDisable.isEmpty()) { PORdebugBufferedWriter.write("empty"); PORdebugBufferedWriter.newLine(); } else { for (LpnTransitionPair lpnTranPair: curDisable) { PORdebugBufferedWriter.append("(" + lpnList[lpnTranPair.getLpnIndex()].getLabel() + ", " + lpnList[lpnTranPair.getLpnIndex()].getAllTransitions()[lpnTranPair.getTranIndex()].getName() + ")," + "\t"); } 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, 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()) { System.out.println("******** Partial Order Reduction ************"); printIntegerSet(curEnabled, sgList, "Enabled set"); System.out.println("******* Begin POR"); writeStringWithNewLineToPORDebugFile("******* Partial Order Reduction *******"); writeIntegerSetToPORDebugFile(curEnabled, sgList, "Enabled set"); writeStringWithNewLineToPORDebugFile("******* Begin POR *******"); } if (curEnabled.isEmpty()) { return ample; } // if (Options.getNecessaryUsingDependencyGraphs()) // ready = partialOrderReductionUsingDependencyGraphs(stateArray, curEnabled, staticSetsMap, sgList); // else ready = partialOrderReduction(stateArray, curEnabled, staticSetsMap, tranFiringFreq, sgList); if (Options.getDebugMode()) { System.out.println("******* End POR *******"); printIntegerSet(ready, sgList, "Ready set"); System.out.println("********************"); writeStringWithNewLineToPORDebugFile("******* End POR *******"); writeIntegerSetToPORDebugFile(ready, sgList, "Ready set"); writeStringWithNewLineToPORDebugFile("********************"); } // ************* Priority: tran fired less times first ************* //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)) { // System.out.println("****** Transitions are possibly ignored in a cycle.******"); // 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, null, null); // 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, null, null); 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) { //System.out.println("*** Verification failed: deadlock."); 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, null, null); 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("-------------------------------------\n" + "---> 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, null, null); 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) { //System.err.println("*** Verification failed: deadlock."); 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, null, null); 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() + ", "); // System.out.println("\n-----------------------------------------------------\n"); // 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 # of states : " + prjStateSet.size() + "\n-----------------------------------------------------\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"); // System.out.println("\n ---------111111-------------\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("\n-------------------------\n"); } //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> partialOrderReductionUsingDependencyGraphs(State[] curStateArray, HashSet<LpnTransitionPair> curEnabled, HashMap<LpnTransitionPair, StaticSets> staticMap, StateGraph[] sgList) { if (curEnabled.size() == 1) return curEnabled; HashSet<LpnTransitionPair> ready = new HashSet<LpnTransitionPair>(); LhpnFile[] lpnList = new LhpnFile[sgList.length]; for (int i=0; i<sgList.length; i++) { lpnList[i] = sgList[i].getLpn(); } // enabledTran is independent of other transitions for (LpnTransitionPair enabledTran : curEnabled) { if (staticMap.get(enabledTran).getDisableSet().isEmpty()) { ready.add(enabledTran); return ready; } } for (LpnTransitionPair enabledTran : curEnabled) { if (Options.getDebugMode()) { System.out.println("@ partialOrderReduction, consider transition " + sgList[enabledTran.getLpnIndex()].getLpn().getLabel() + "("+ sgList[enabledTran.getLpnIndex()].getLpn().getTransition(enabledTran.getTranIndex()) + "). Compute its dependent set."); writeStringWithNewLineToPORDebugFile("@ partialOrderReduction, consider transition " + sgList[enabledTran.getLpnIndex()].getLpn().getLabel() + "("+ sgList[enabledTran.getLpnIndex()].getLpn().getTransition(enabledTran.getTranIndex()) + "). Compute its dependent set."); } HashSet<LpnTransitionPair> dependent = new HashSet<LpnTransitionPair>(); boolean isCycleClosingAmpleComputation = false; dependent = computeDependent(curStateArray,enabledTran,dependent,curEnabled,staticMap, lpnList, isCycleClosingAmpleComputation); // printIntegerSet(dependent, sgList, "dependent set for enabled transition " + sgList[enabledTran.getLpnIndex()].getLpn().getLabel() // + "(" + enabledTransition.getName() + ")"); if (ready.isEmpty()) ready = (HashSet<LpnTransitionPair>) dependent.clone(); else if (dependent.size() < ready.size() && !ready.isEmpty()) ready = (HashSet<LpnTransitionPair>) dependent.clone(); if (ready.size() == 1) { cachedNecessarySets.clear(); return ready; } } cachedNecessarySets.clear(); return ready; } private HashSet<LpnTransitionPair> partialOrderReduction(State[] curStateArray, HashSet<LpnTransitionPair> curEnabled, HashMap<LpnTransitionPair, StaticSets> staticMap, HashMap<LpnTransitionPair,Integer> tranFiringFreqMap, StateGraph[] sgList) { if (curEnabled.size() == 1) return curEnabled; HashSet<LpnTransitionPair> ready = null; LhpnFile[] lpnList = new LhpnFile[sgList.length]; for (int i=0; i<sgList.length; i++) { lpnList[i] = sgList[i].getLpn(); } DependentSetComparator depComp = new DependentSetComparator(tranFiringFreqMap); PriorityQueue<DependentSet> dependentSetQueue = new PriorityQueue<DependentSet>(curEnabled.size(), depComp); for (LpnTransitionPair enabledTran : curEnabled) { if (Options.getDebugMode()){ System.out.println("@ partialOrderReduction, consider transition " + sgList[enabledTran.getLpnIndex()].getLpn().getLabel() + "("+ sgList[enabledTran.getLpnIndex()].getLpn().getTransition(enabledTran.getTranIndex()) + ")"); writeStringWithNewLineToPORDebugFile("@ partialOrderReduction, consider transition " + sgList[enabledTran.getLpnIndex()].getLpn().getLabel() + "("+ sgList[enabledTran.getLpnIndex()].getLpn().getTransition(enabledTran.getTranIndex()) + ")"); } 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); // printIntegerSet(dependent, sgList, "dependent set for enabled transition " + sgList[enabledTran.getLpnIndex()].getLpn().getLabel() // + "(" + enabledTransition.getName() + ")"); // 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); // if (ready.isEmpty()) // ready = (HashSet<LpnTransitionPair>) dependent.clone(); // else if (dependent.size() < ready.size() && !ready.isEmpty()) // ready = (HashSet<LpnTransitionPair>) dependent.clone(); // if (ready.size() == 1) { // cachedNecessarySets.clear(); // return ready; // } } cachedNecessarySets.clear(); ready = dependentSetQueue.poll().getDependent(); 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()) { System.out.println("@ getDependentSet, consider transition " + lpnList[seedTran.getLpnIndex()].getTransition(seedTran.getTranIndex()).getName()); //printIntegerSet(canModifyAssign, lpnList, lpnList[enabledLpnTran.getLpnIndex()].getTransition(enabledLpnTran.getTranIndex()) + " can modify assignments"); printIntegerSet(disableSet, lpnList, "Disable set for " + lpnList[seedTran.getLpnIndex()].getTransition(seedTran.getTranIndex())); writeStringWithNewLineToPORDebugFile("@ getDependentSet, consider transition " + lpnList[seedTran.getLpnIndex()].getTransition(seedTran.getTranIndex()).getName()); writeIntegerSetToPORDebugFile(disableSet, lpnList, "Disable set for " + lpnList[seedTran.getLpnIndex()].getTransition(seedTran.getTranIndex())); } dependent.add(seedTran); // for (LpnTransitionPair lpnTranPair : canModifyAssign) { // if (curEnabled.contains(lpnTranPair)) // dependent.add(lpnTranPair); // } if (Options.getDebugMode()) { printIntegerSet(dependent, lpnList, "@ getDependentSet at 0, dependent set for " + lpnList[seedTran.getLpnIndex()].getTransition(seedTran.getTranIndex())); writeIntegerSetToPORDebugFile(dependent, lpnList, "@ getDependentSet at 0, dependent set for " + lpnList[seedTran.getLpnIndex()].getTransition(seedTran.getTranIndex())); } // // dependent is equal to enabled. Terminate. // if (dependent.size() == curEnabled.size()) { // if (Options.getDebugMode()) // System.out.println("Check 0: dependent == curEnabled. Return dependent."); // return dependent; // } for (LpnTransitionPair tranInDisableSet : disableSet) { if (Options.getDebugMode()) { System.out.println("Consider transition in the disable set of " + lpnList[seedTran.getLpnIndex()].getLabel() + "(" + lpnList[seedTran.getLpnIndex()].getTransition(seedTran.getTranIndex()) + "): " + lpnList[tranInDisableSet.getLpnIndex()].getLabel() +"(" + lpnList[tranInDisableSet.getLpnIndex()].getTransition(tranInDisableSet.getTranIndex()) + ")"); writeStringWithNewLineToPORDebugFile("Consider transition in the disable set of " + lpnList[seedTran.getLpnIndex()].getLabel() + "(" + lpnList[seedTran.getLpnIndex()].getTransition(seedTran.getTranIndex()) + "): " + lpnList[tranInDisableSet.getLpnIndex()].getLabel() +"(" + lpnList[tranInDisableSet.getLpnIndex()].getTransition(tranInDisableSet.getTranIndex()) + ")"); } 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()) { printIntegerSet(dependent, lpnList, "@ getDependentSet at 1 for transition " + lpnList[seedTran.getLpnIndex()].getTransition(seedTran.getTranIndex())); writeIntegerSetToPORDebugFile(dependent, lpnList, "@ getDependentSet at 1 for transition " + lpnList[seedTran.getLpnIndex()].getTransition(seedTran.getTranIndex())); } } 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 origTran = new LpnTransitionPair(tranInDisableSet.getLpnIndex(), tranInDisableSet.getTranIndex()); HashSet<LpnTransitionPair> necessary = null; if (Options.getDebugMode()) { printCachedNecessarySets(lpnList); writeCachedNecessarySetsToPORDebugFile(lpnList); } if (cachedNecessarySets.containsKey(tranInDisableSet)) { if (Options.getDebugMode()) { System.out.println("Found transition " + lpnList[tranInDisableSet.getLpnIndex()].getLabel() + "(" + lpnList[tranInDisableSet.getLpnIndex()].getTransition(tranInDisableSet.getTranIndex()).getName() + ") in the cached necessary sets."); writeStringWithNewLineToPORDebugFile("Found transition " + lpnList[tranInDisableSet.getLpnIndex()].getLabel() + "(" + lpnList[tranInDisableSet.getLpnIndex()].getTransition(tranInDisableSet.getTranIndex()).getName() + ") in the cached necessary sets."); } necessary = cachedNecessarySets.get(tranInDisableSet); } else { if (Options.getNecessaryUsingDependencyGraphs()) { if (Options.getDebugMode()) { System.out.println("==== Compute necessary using BFS ===="); writeStringWithNewLineToPORDebugFile("==== Compute necessary using BFS ===="); } necessary = computeNecessaryUsingDependencyGraphs(curStateArray,tranInDisableSet,curEnabled, staticMap, lpnList); } else { if (Options.getDebugMode()) { System.out.println("==== Compute necessary using DFS ===="); writeStringWithNewLineToPORDebugFile("==== Compute necessary using DFS ===="); } necessary = computeNecessary(curStateArray,tranInDisableSet,dependent,curEnabled, staticMap, lpnList, origTran); } } if (necessary != null && !necessary.isEmpty()) { cachedNecessarySets.put(tranInDisableSet, necessary); if (Options.getDebugMode()) { printIntegerSet(necessary, lpnList, "necessary set for transition " + lpnList[tranInDisableSet.getLpnIndex()].getLabel() + "(" + lpnList[tranInDisableSet.getLpnIndex()].getTransition(tranInDisableSet.getTranIndex()) + ")"); writeIntegerSetToPORDebugFile(necessary, lpnList, "necessary set for transition " + lpnList[tranInDisableSet.getLpnIndex()].getLabel() + "(" + lpnList[tranInDisableSet.getLpnIndex()].getTransition(tranInDisableSet.getTranIndex()) + ")"); } for (LpnTransitionPair tranNecessary : necessary) { if (!dependent.contains(tranNecessary)) { if (Options.getDebugMode()) { printIntegerSet(dependent, lpnList, "Dependent set for " + lpnList[seedTran.getLpnIndex()].getLabel() + "(" + lpnList[seedTran.getLpnIndex()].getTransition(seedTran.getTranIndex()) + "):"); System.out.println("It does not contain this transition found by computeNecessary: " + lpnList[tranNecessary.getLpnIndex()].getLabel() + "(" + lpnList[tranNecessary.getLpnIndex()].getTransition(tranNecessary.getTranIndex()) + ")" + ". Compute its dependent set."); writeIntegerSetToPORDebugFile(dependent, lpnList, "Dependent set for " + lpnList[seedTran.getLpnIndex()].getLabel() + "(" + lpnList[seedTran.getLpnIndex()].getTransition(seedTran.getTranIndex()) + "):"); writeStringWithNewLineToPORDebugFile("It does not contain this transition found by computeNecessary: " + lpnList[tranNecessary.getLpnIndex()].getLabel() + "(" + lpnList[tranNecessary.getLpnIndex()].getTransition(tranNecessary.getTranIndex()) + ")" + ". Compute its dependent set."); } dependent.addAll(computeDependent(curStateArray,tranNecessary,dependent,curEnabled,staticMap, lpnList, isCycleClosingAmpleComputation)); } } } else { if (Options.getDebugMode()) { System.out.println("necessary set for transition " + lpnList[seedTran.getLpnIndex()].getTransition(seedTran.getTranIndex()) + " is empty."); writeStringWithNewLineToPORDebugFile("necessary set for transition " + lpnList[seedTran.getLpnIndex()].getTransition(seedTran.getTranIndex()) + " is empty."); } dependent.addAll(curEnabled); } if (Options.getDebugMode()) { printIntegerSet(dependent, lpnList, "@ getDependentSet at 2, dependent set for transition " + lpnList[seedTran.getLpnIndex()].getTransition(seedTran.getTranIndex())); writeIntegerSetToPORDebugFile(dependent, lpnList, "@ getDependentSet at 2, dependent set for transition " + lpnList[seedTran.getLpnIndex()].getTransition(seedTran.getTranIndex())); } } } return dependent; } @SuppressWarnings("unchecked") private HashSet<LpnTransitionPair> computeNecessary(State[] curStateArray, LpnTransitionPair tran, HashSet<LpnTransitionPair> dependent, HashSet<LpnTransitionPair> curEnabledIndices, HashMap<LpnTransitionPair, StaticSets> staticMap, LhpnFile[] lpnList, LpnTransitionPair origTran) { if (Options.getDebugMode()) { System.out.println("@ getNecessary, consider transition: " + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(tran.getTranIndex()).getName() + ")"); writeStringWithNewLineToPORDebugFile("@ getNecessary, consider transition: " + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(tran.getTranIndex()).getName() + ")"); } if (cachedNecessarySets.containsKey(tran)) { if (Options.getDebugMode()) { System.out.println("Found transition" + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(tran.getTranIndex()).getName() + ")" + "'s necessary set in the cached necessary sets. "); writeStringWithNewLineToPORDebugFile("Found transition" + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(tran.getTranIndex()).getName() + ")" + "'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()) { System.out.println("####### compute nMarking for transition " + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(tran.getTranIndex()).getName() + ") " + "########"); writeStringWithNewLineToPORDebugFile("####### compute nMarking for transition " + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(tran.getTranIndex()).getName() + ") " + "########"); } HashSet<LpnTransitionPair> nMarkingTemp = new HashSet<LpnTransitionPair>(); String placeName = lpnList[tran.getLpnIndex()].getAllPlaces().get(place); if (Options.getDebugMode()) { System.out.println("preset place of " + transition.getName() + " is " + placeName); writeStringWithNewLineToPORDebugFile("preset place of " + transition.getName() + " 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()) { System.out.println("preset transition of " + placeName + " is " + lpnList[presetTran.getLpnIndex()].getLabel() + "(" + lpnList[presetTran.getLpnIndex()].getTransition(presetTran.getTranIndex()) + ")"); writeStringWithNewLineToPORDebugFile("preset transition of " + placeName + " is " + lpnList[presetTran.getLpnIndex()].getLabel() + "(" + lpnList[presetTran.getLpnIndex()].getTransition(presetTran.getTranIndex()) + ")"); } if (origTran.getVisitedTrans().contains(presetTran)) { if (Options.getDebugMode()) { System.out.println("Transition " + lpnList[presetTran.getLpnIndex()].getLabel() + "(" + lpnList[presetTran.getLpnIndex()].getTransition(presetTran.getTranIndex()) + ") is visted before by " + lpnList[origTran.getLpnIndex()].getLabel() + "(" + lpnList[origTran.getLpnIndex()].getTransition(origTran.getTranIndex()).getName() + ")."); writeStringWithNewLineToPORDebugFile("Transition " + lpnList[presetTran.getLpnIndex()].getLabel() + "(" + lpnList[presetTran.getLpnIndex()].getTransition(presetTran.getTranIndex()) + ") is visted before by " + lpnList[origTran.getLpnIndex()].getLabel() + "(" + lpnList[origTran.getLpnIndex()].getTransition(origTran.getTranIndex()).getName() + ")."); } if (cachedNecessarySets.containsKey(presetTran)) { if (Options.getDebugMode()) { System.out.println("Found transition" + lpnList[presetTran.getLpnIndex()].getLabel() + "(" + lpnList[presetTran.getLpnIndex()].getTransition(presetTran.getTranIndex()).getName() + ")" + "'s necessary set in the cached necessary sets. Add it to nMarkingTemp."); writeStringWithNewLineToPORDebugFile("Found transition" + lpnList[presetTran.getLpnIndex()].getLabel() + "(" + lpnList[presetTran.getLpnIndex()].getTransition(presetTran.getTranIndex()).getName() + ")" + "'s necessary set in the cached necessary sets. Add it to nMarkingTemp."); } nMarkingTemp = cachedNecessarySets.get(presetTran); } if (curEnabledIndices.contains(presetTran)) { if (Options.getDebugMode()) { System.out.println("@ nMarking: curEnabled contains transition " + lpnList[presetTran.getLpnIndex()].getLabel() + "(" + lpnList[presetTran.getLpnIndex()].getTransition(presetTran.getTranIndex()).getName() + "). Add to nMarkingTmp."); writeStringWithNewLineToPORDebugFile("@ nMarking: curEnabled contains transition " + lpnList[presetTran.getLpnIndex()].getLabel() + "(" + lpnList[presetTran.getLpnIndex()].getTransition(presetTran.getTranIndex()).getName() + "). Add to nMarkingTmp."); } nMarkingTemp.add(new LpnTransitionPair(tran.getLpnIndex(), presetTrans[j]));; } continue; } else origTran.addVisitedTran(presetTran); if (Options.getDebugMode()) { System.out.println("~~~~~~~~~ transVisited for transition " + lpnList[origTran.getLpnIndex()].getLabel() + "(" + lpnList[origTran.getLpnIndex()].getTransition(origTran.getTranIndex()).getName() + ")~~~~~~~~~"); writeStringWithNewLineToPORDebugFile("~~~~~~~~~ transVisited for transition " + lpnList[origTran.getLpnIndex()].getLabel() + "(" + lpnList[origTran.getLpnIndex()].getTransition(origTran.getTranIndex()).getName() + ")~~~~~~~~~"); for (LpnTransitionPair visitedTran : origTran.getVisitedTrans()) { System.out.println(lpnList[visitedTran.getLpnIndex()].getLabel() + "(" + lpnList[visitedTran.getLpnIndex()].getTransition(visitedTran.getTranIndex()).getName() + ") "); writeStringWithNewLineToPORDebugFile(lpnList[visitedTran.getLpnIndex()].getLabel() + "(" + lpnList[visitedTran.getLpnIndex()].getTransition(visitedTran.getTranIndex()).getName() + ") "); } System.out.println("@ getNecessary, consider transition: " + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(presetTrans[j]).getName() + ")."); writeStringWithNewLineToPORDebugFile("@ getNecessary, consider transition: " + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(presetTrans[j]).getName() + ")."); } if (curEnabledIndices.contains(presetTran)) { if (Options.getDebugMode()) { System.out.println("@ nMarking: curEnabled contains transition " + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(presetTran.getTranIndex()).getName() + "). Add to nMarkingTmp."); writeStringWithNewLineToPORDebugFile("@ nMarking: curEnabled contains transition " + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(presetTran.getTranIndex()).getName() + "). Add to nMarkingTmp."); } nMarkingTemp.add(new LpnTransitionPair(tran.getLpnIndex(), presetTrans[j])); } else { if (Options.getDebugMode()) { System.out.println("@ nMarking: transition " + lpnList[tran.getLpnIndex()].getTransition(presetTrans[j]).getName() + " is not enabled. Compute its necessary set."); writeStringWithNewLineToPORDebugFile("@ nMarking: transition " + lpnList[tran.getLpnIndex()].getTransition(presetTrans[j]).getName() + " is not enabled. Compute its necessary set."); } HashSet<LpnTransitionPair> tmp = null; tmp = computeNecessary(curStateArray, presetTran, dependent, curEnabledIndices, staticMap, lpnList, origTran); if (tmp != null) nMarkingTemp.addAll(tmp); else if (Options.getDebugMode()) { System.out.println("@ nMarking: necessary set for transition " + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(presetTrans[j]).getName() + ") is null."); writeStringWithNewLineToPORDebugFile("@ nMarking: necessary set for transition " + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(presetTrans[j]).getName() + ") is null."); } } } if (nMarkingTemp != null) if (nMarking == null || nMarkingTemp.size() < nMarking.size()) nMarking = (HashSet<LpnTransitionPair>) nMarkingTemp.clone(); } else if (Options.getDebugMode()) { System.out.println("Place " + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getAllPlaces().get(place) + ") is marked."); writeStringWithNewLineToPORDebugFile("Place " + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getAllPlaces().get(place) + ") is marked."); } } // Search for transition(s) that can help to enable the current transition. HashSet<LpnTransitionPair> nEnable = null; int[] varValueVector = curStateArray[tran.getLpnIndex()].getVector();//curState.getVector(); HashSet<LpnTransitionPair> canEnable = staticMap.get(tran).getEnableBySettingEnablingTrue(); if (Options.getDebugMode()) { System.out.println("####### compute nEnable for transition " + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(tran.getTranIndex()).getName() + ") " + "########"); printIntegerSet(canEnable, lpnList, lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(tran.getTranIndex()) + ") can be enabled by"); writeStringWithNewLineToPORDebugFile("####### compute nEnable for transition " + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(tran.getTranIndex()).getName() + ") " + "########"); writeIntegerSetToPORDebugFile(canEnable, lpnList, lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(tran.getTranIndex()) + ") 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 (LpnTransitionPair tranCanEnable : canEnable) { if (curEnabledIndices.contains(tranCanEnable)) { nEnable.add(tranCanEnable); if (Options.getDebugMode()) { System.out.println("@ nEnable: curEnabled contains transition " + lpnList[tranCanEnable.getLpnIndex()].getLabel() + "(" + lpnList[tranCanEnable.getLpnIndex()].getTransition(tranCanEnable.getTranIndex()).getName() + "). Add to nEnable."); writeStringWithNewLineToPORDebugFile("@ nEnable: curEnabled contains transition " + lpnList[tranCanEnable.getLpnIndex()].getLabel() + "(" + lpnList[tranCanEnable.getLpnIndex()].getTransition(tranCanEnable.getTranIndex()).getName() + "). Add to nEnable."); } } else { if (origTran.getVisitedTrans().contains(tranCanEnable)) { if (Options.getDebugMode()) { System.out.println("Transition " + lpnList[tranCanEnable.getLpnIndex()].getLabel() + "(" + lpnList[tranCanEnable.getLpnIndex()].getTransition(tranCanEnable.getTranIndex()) + ") is visted before by " + lpnList[origTran.getLpnIndex()].getLabel() + "(" + lpnList[origTran.getLpnIndex()].getTransition(origTran.getTranIndex()).getName() + ")."); writeStringWithNewLineToPORDebugFile("Transition " + lpnList[tranCanEnable.getLpnIndex()].getLabel() + "(" + lpnList[tranCanEnable.getLpnIndex()].getTransition(tranCanEnable.getTranIndex()) + ") is visted before by " + lpnList[origTran.getLpnIndex()].getLabel() + "(" + lpnList[origTran.getLpnIndex()].getTransition(origTran.getTranIndex()).getName() + ")."); } if (cachedNecessarySets.containsKey(tranCanEnable)) { if (Options.getDebugMode()) { System.out.println("Found transition" + lpnList[tranCanEnable.getLpnIndex()].getLabel() + "(" + lpnList[tranCanEnable.getLpnIndex()].getTransition(tranCanEnable.getTranIndex()).getName() + ")" + "'s necessary set in the cached necessary sets. Add it to nMarkingTemp."); writeStringWithNewLineToPORDebugFile("Found transition" + lpnList[tranCanEnable.getLpnIndex()].getLabel() + "(" + lpnList[tranCanEnable.getLpnIndex()].getTransition(tranCanEnable.getTranIndex()).getName() + ")" + "'s necessary set in the cached necessary sets. Add it to nMarkingTemp."); } nEnable.addAll(cachedNecessarySets.get(tranCanEnable)); } continue; } else origTran.addVisitedTran(tranCanEnable); if (Options.getDebugMode()) { System.out.println("@ nEnable: transition " + lpnList[tranCanEnable.getLpnIndex()].getTransition(tranCanEnable.getTranIndex()).getName() + " is not enabled. Compute its necessary set."); writeStringWithNewLineToPORDebugFile("@ nEnable: transition " + lpnList[tranCanEnable.getLpnIndex()].getTransition(tranCanEnable.getTranIndex()).getName() + " is not enabled. Compute its necessary set."); } HashSet<LpnTransitionPair> tmp = null; tmp = computeNecessary(curStateArray, tranCanEnable, dependent, curEnabledIndices, staticMap, lpnList, origTran); if (tmp != null) nEnable.addAll(tmp); else if (Options.getDebugMode()) { System.out.println("@ nEnable: necessary set for transition " + lpnList[tranCanEnable.getLpnIndex()].getLabel() + "(" + lpnList[tranCanEnable.getLpnIndex()].getTransition(tranCanEnable.getTranIndex()).getName() + ") is null."); writeStringWithNewLineToPORDebugFile("@ nEnable: necessary set for transition " + lpnList[tranCanEnable.getLpnIndex()].getLabel() + "(" + lpnList[tranCanEnable.getLpnIndex()].getTransition(tranCanEnable.getTranIndex()).getName() + ") is null."); } } } } if (Options.getDebugMode()) { if (transition.getEnablingTree() == null) { System.out.println("@ nEnable: transition " + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(tran.getTranIndex()).getName() + ") has no enabling condition."); writeStringWithNewLineToPORDebugFile("@ nEnable: transition " + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(tran.getTranIndex()).getName() + ") has no enabling condition."); } else if (transition.getEnablingTree().evaluateExpr(lpnList[tran.getLpnIndex()].getAllVarsWithValuesAsString(varValueVector)) !=0.0) { System.out.println("@ nEnable: transition " + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(tran.getTranIndex()).getName() + ")'s enabling condition is true."); writeStringWithNewLineToPORDebugFile("@ nEnable: transition " + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(tran.getTranIndex()).getName() + ")'s enabling condition is true."); } else if (transition.getEnablingTree() != null && transition.getEnablingTree().evaluateExpr(lpnList[tran.getLpnIndex()].getAllVarsWithValuesAsString(varValueVector)) == 0.0 && canEnable.isEmpty()) { System.out.println("@ nEnable: transition " + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(tran.getTranIndex()).getName() + ")'s enabling condition is false, but no other transitions that can help to enable it were found ."); writeStringWithNewLineToPORDebugFile("@ nEnable: transition " + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(tran.getTranIndex()).getName() + ")'s enabling condition is false, but no other transitions that can help to enable it were found ."); } printIntegerSet(nMarking, lpnList, "nMarking for transition " + transition.getName()); printIntegerSet(nEnable, lpnList, "nEnable for transition " + transition.getName()); writeIntegerSetToPORDebugFile(nMarking, lpnList, "nMarking for transition " + transition.getName()); writeIntegerSetToPORDebugFile(nEnable, lpnList, "nEnable for transition " + transition.getName()); } if (nEnable == null && nMarking != null) { if (!nMarking.isEmpty()) cachedNecessarySets.put(tran, nMarking); if (Options.getDebugMode()) { printCachedNecessarySets(lpnList); writeCachedNecessarySetsToPORDebugFile(lpnList); } return nMarking; } else if (nMarking == null && nEnable != null) { if (!nEnable.isEmpty()) cachedNecessarySets.put(tran, nEnable); if (Options.getDebugMode()) { printCachedNecessarySets(lpnList); 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()) { printCachedNecessarySets(lpnList); writeCachedNecessarySetsToPORDebugFile(lpnList); } return nMarking; } else { cachedNecessarySets.put(tran, nEnable); if (Options.getDebugMode()) { printCachedNecessarySets(lpnList); writeCachedNecessarySetsToPORDebugFile(lpnList); } return nEnable; } } else if (nMarking.isEmpty() && !nEnable.isEmpty()) { cachedNecessarySets.put(tran, nEnable); if (Options.getDebugMode()) { printCachedNecessarySets(lpnList); writeCachedNecessarySetsToPORDebugFile(lpnList); } return nEnable; } else { cachedNecessarySets.put(tran, nMarking); if (Options.getDebugMode()) { printCachedNecessarySets(lpnList); writeCachedNecessarySetsToPORDebugFile(lpnList); } return nMarking; } } } private HashSet<LpnTransitionPair> computeNecessaryUsingDependencyGraphs(State[] curStateArray, LpnTransitionPair seedTran, HashSet<LpnTransitionPair> curEnabled, HashMap<LpnTransitionPair, StaticSets> staticMap, LhpnFile[] lpnList) { if (Options.getDebugMode()) { System.out.println("@ getNecessary, consider transition: " + lpnList[seedTran.getLpnIndex()].getLabel() + "(" + lpnList[seedTran.getLpnIndex()].getTransition(seedTran.getTranIndex()).getName() + ")"); writeStringWithNewLineToPORDebugFile("@ getNecessary, consider transition: " + lpnList[seedTran.getLpnIndex()].getLabel() + "(" + lpnList[seedTran.getLpnIndex()].getTransition(seedTran.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(seedTran); //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()) { System.out.println("Found transition" + lpnList[curTran.getLpnIndex()].getLabel() + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()).getName() + ")" + "'s necessary set in the cached necessary sets. Terminate BFS."); writeStringWithNewLineToPORDebugFile("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); // 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 enable trnasition " + lpnList[curTran.getLpnIndex()].getLabel() + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()) + ") "); writeIntegerSetToPORDebugFile(canEnable, lpnList, "Neighbors that can help to enable trnasition " + lpnList[curTran.getLpnIndex()].getLabel() + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()) + ") "); } for (LpnTransitionPair neighborTran : canEnable) { if (curEnabled.contains(neighborTran)) { 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(seedTran, necessarySet); if (Options.getDebugMode()) { System.out.println("Enabled neighbor that can help to enable trnasition " + lpnList[curTran.getLpnIndex()].getLabel() + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()) + "): " + lpnList[neighborTran.getLpnIndex()].getLabel() + "(" + lpnList[neighborTran.getLpnIndex()].getTransition(neighborTran.getTranIndex()) + ")"); writeStringWithNewLineToPORDebugFile("Enabled neighbor that can help to enable trnasition " + lpnList[curTran.getLpnIndex()].getLabel() + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()) + "): " + lpnList[neighborTran.getLpnIndex()].getLabel() + "(" + lpnList[neighborTran.getLpnIndex()].getTransition(neighborTran.getTranIndex()) + ")"); } return necessarySet; } if (!allExploredTrans.contains(neighborTran)) { allExploredTrans.add(neighborTran); exploredTransQueue.add(neighborTran); } } canEnable.clear(); } return null; } private HashSet<LpnTransitionPair> buildCanBringTokenSet( LpnTransitionPair curTran, LhpnFile[] lpnList, State[] curStateArray) { // Build transition(s) set that can help to bring the marking(s). Transition curTransition = lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()); int[] presetPlaces = lpnList[curTran.getLpnIndex()].getPresetIndex(curTransition.getName()); HashSet<LpnTransitionPair> canBringToken = new HashSet<LpnTransitionPair>(); for (int i=0; i < presetPlaces.length; i++) { int place = presetPlaces[i]; if (curStateArray[curTran.getLpnIndex()].getMarking()[place]==0) { String placeName = lpnList[curTran.getLpnIndex()].getAllPlaces().get(place); int[] presetTrans = lpnList[curTran.getLpnIndex()].getPresetIndex(placeName); for (int j=0; j < presetTrans.length; j++) { LpnTransitionPair presetTran = new LpnTransitionPair(curTran.getLpnIndex(), presetTrans[j]); canBringToken.add(presetTran); } } } return canBringToken; } 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) { writeStringWithNewLineToPORDebugFile("================ cachedNecessarySets ================="); for (LpnTransitionPair key : cachedNecessarySets.keySet()) { writeStringToPORDebugFile(lpnList[key.getLpnIndex()].getLabel() + "(" + lpnList[key.getLpnIndex()].getTransition(key.getTranIndex()).getName() + ") => "); HashSet<LpnTransitionPair> necessarySet = cachedNecessarySets.get(key); for (LpnTransitionPair necessary : necessarySet) { writeStringToPORDebugFile(lpnList[necessary.getLpnIndex()].getLabel() + "(" + lpnList[necessary.getLpnIndex()].getTransition(necessary.getTranIndex()).getName() + ") "); } writeStringWithNewLineToPORDebugFile(""); } } 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) { writeStringWithNewLineToPORDebugFile("null"); } else if (indicies.isEmpty()) { writeStringWithNewLineToPORDebugFile("empty"); } else { for (LpnTransitionPair lpnTranPair : indicies) { writeStringToPORDebugFile("\t" + sgList[lpnTranPair.getLpnIndex()].getLpn().getLabel() + "(" + sgList[lpnTranPair.getLpnIndex()].getLpn().getAllTransitions()[lpnTranPair.getTranIndex()].getName() + ") \t"); } writeStringWithNewLineToPORDebugFile(""); } } 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) { writeStringWithNewLineToPORDebugFile("null"); } else if (indicies.isEmpty()) { writeStringWithNewLineToPORDebugFile("empty"); } else { for (LpnTransitionPair lpnTranPair : indicies) { writeStringToPORDebugFile(lpnList[lpnTranPair.getLpnIndex()].getLabel() + "(" + lpnList[lpnTranPair.getLpnIndex()].getAllTransitions()[lpnTranPair.getTranIndex()].getName() + ") \t"); } writeStringWithNewLineToPORDebugFile(""); } } }
gui/src/verification/platu/logicAnalysis/Analysis.java
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.LhpnFile; import lpn.parser.Transition; 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 (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()) { System.out.println("------- curStateArray ----------"); 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("####### lpnTranStack #########"); 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 (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()) { System.out.println("******* curStateArray *******"); printStateArray(curStateArray); System.out.println("******* nextStateArray *******"); printStateArray(nextStateArray); 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()) { System.out.println("***nextStateMap for stateStackTop after firedTran being added: "); 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()); } } } // System.out.println("-----------------------"); } 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()) { System.out.println("******** lpnTranStack ***********"); printLpnTranStack(lpnTranStack); } curIndexStack.push(0); totalStates++; } else { if (Options.getOutputSgFlag()) { if (Options.getDebugMode()) { System.out.println("******* curStateArray *******"); printStateArray(curStateArray); System.out.println("******* nextStateArray *******"); 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()) { System.out.println("***nextStateMap for stateStackTop after firedTran being added: "); printNextStateMap(stateStackTop.getNextStateMap()); } for (PrjState prjState : prjStateSet) { if (prjState == stateStackTop) { prjState.setNextStateMap((HashMap<Transition, PrjState>) stateStackTop.getNextStateMap().clone()); if (Options.getDebugMode()) { System.out.println("***nextStateMap for prjState: "); printNextStateMap(prjState.getNextStateMap()); } } } // System.out.println("-----------------------"); } } } 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 drawDependencyGraphsForNecessarySets(LhpnFile[] lpnList, HashMap<LpnTransitionPair, StaticSets> staticSetsMap) { String fileName = Options.getPrjSgPath() + "_necessarySet.dot"; BufferedWriter out; try { out = new BufferedWriter(new FileWriter(fileName)); out.write("digraph G {\n"); for (LpnTransitionPair seedTran : staticSetsMap.keySet()) { for (LpnTransitionPair canEnableTran : staticSetsMap.get(seedTran).getEnableSet()) { } } 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>(); for (int i=0; i<lpnList.length; i++) allTransitions.put(i, lpnList[i].getAllTransitions()); HashMap<LpnTransitionPair, Integer> tranFiringFreq = new HashMap<LpnTransitionPair, Integer>(allTransitions.keySet().size()); for (int lpnIndex=0; lpnIndex<lpnList.length; lpnIndex++) { if (Options.getDebugMode()) System.out.println("LPN = " + lpnList[lpnIndex].getLabel()); for (Transition curTran: allTransitions.get(lpnIndex)) { StaticSets curStatic = new StaticSets(curTran, allTransitions); curStatic.buildCurTranDisableOtherTransSet(lpnIndex); if (Options.getPORdeadlockPreserve()) curStatic.buildOtherTransDisableCurTranSet(lpnIndex); curStatic.buildModifyAssignSet(); curStatic.buildEnableBySettingEnablingTrue(); // if (Options.getDebugMode()) // curStatic.buildEnableByBringingToken(); LpnTransitionPair lpnTranPair = new LpnTransitionPair(lpnIndex,curTran.getIndex()); staticSetsMap.put(lpnTranPair, curStatic); //if (!Options.getNecessaryUsingDependencyGraphs()) tranFiringFreq.put(lpnTranPair, 0); } } if (Options.getDebugMode()) { printStaticSetsMap(lpnList, staticSetsMap); writeStaticSetsMapToPORDebugFile(lpnList, staticSetsMap); // if (Options.getNecessaryUsingDependencyGraphs()) // drawDependencyGraphsForNecessarySets(lpnList, staticSetsMap); } boolean init = true; LpnTranList initAmpleTrans = new LpnTranList(); if (Options.getDebugMode()) System.out.println("call getAmple on curStateArray at 0: "); // if (Options.getNecessaryUsingDependencyGraphs()) // tranFiringFreq = null; initAmpleTrans = getAmple(initStateArray, null, staticSetsMap, init, tranFiringFreq, sgList, stateStack, stateStackTop); lpnTranStack.push(initAmpleTrans); init = false; if (Options.getDebugMode()) { System.out.println("+++++++ Push trans onto lpnTranStack @ 1++++++++"); printTransitionSet(initAmpleTrans, ""); } 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()) { System.out.println("~~~~~~~~~~~ loop begins ~~~~~~~~~~~"); writeStringWithNewLineToPORDebugFile("~~~~~~~~~~~ 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("####### lpnTranStack #########"); printLpnTranStack(lpnTranStack); // System.out.println("####### stateStack #########"); // printStateStack(stateStack); System.out.println("####### prjStateSet #########"); printPrjStateSet(prjStateSet); System.out.println("%%%%%%% Remove stateStackTop from stateStack %%%%%%%%"); } stateStack.remove(stateStackTop); stateStackTop = stateStackTop.getFather(); continue; } Transition firedTran = curAmpleTrans.removeLast(); if (Options.getDebugMode()) { System.out.println("#################################"); System.out.println("Fired Transition: " + firedTran.getLpn().getLabel() + "(" + firedTran.getName() + ")"); System.out.println("#################################"); writeStringWithNewLineToPORDebugFile("#################################"); writeStringWithNewLineToPORDebugFile("Fired Transition: " + firedTran.getLpn().getLabel() + "(" + firedTran.getName() + ")"); writeStringWithNewLineToPORDebugFile("#################################"); } LpnTransitionPair firedLpnTranPair = new LpnTransitionPair(firedTran.getLpn().getLpnIndex(), firedTran.getIndex()); // if (!Options.getNecessaryUsingDependencyGraphs()) { 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(); // if (Options.getNecessaryUsingDependencyGraphs()) // nextAmpleTrans = getAmple(curStateArray, nextStateArray, staticSetsMap, init, null, sgList, prjStateSet, stateStackTop); // else nextAmpleTrans = getAmple(curStateArray, nextStateArray, staticSetsMap, init, tranFiringFreq, sgList, 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()) { System.out.println("******* curStateArray *******"); printStateArray(curStateArray); System.out.println("******* nextStateArray *******"); printStateArray(nextStateArray); 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()) { System.out.println("***nextStateMap for stateStackTop after firedTran being added: "); 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()); } } } // System.out.println("-----------------------"); } 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()) { System.out.println("******* curStateArray *******"); printStateArray(curStateArray); System.out.println("******* nextStateArray *******"); 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()) { System.out.println("***nextStateMap for stateStackTop after firedTran being added: "); printNextStateMap(stateStackTop.getNextStateMap()); } for (PrjState prjState : prjStateSet) { if (prjState == stateStackTop) { prjState.setNextStateMap((HashMap<Transition, PrjState>) stateStackTop.getNextStateMap().clone()); if (Options.getDebugMode()) { System.out.println("***nextStateMap for prjState: "); printNextStateMap(prjState.getNextStateMap()); } } } // System.out.println("-----------------------"); } 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, ""); System.out.println("******* lpnTranStack ***************"); 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); PORdebugBufferedWriter = new BufferedWriter(PORdebugFileStream); } catch (Exception e) { e.printStackTrace(); System.err.println("Error producing the debugging file for partial order reduction."); } } private void writeStringWithNewLineToPORDebugFile(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) { if (Options.getNecessaryUsingDependencyGraphs()) fileName = Options.getPrjSgPath() + Options.getLogName() + "_" + Options.getPOR() + "_" + Options.getCycleClosingMthd() + "_" + Options.getCycleClosingAmpleMethd() + ".log"; else 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()) System.out.println("****** behavioral: cycle closing check ********"); 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()) { System.out.println("******* nextStateArray *******"); 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"); System.out.println("******** behavioral: end of cycle closing check *****"); } } 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) { // System.out.println("---> calling function search_dfsPORrefinedCycleRule"); // if (cycleClosingMthdIndex == 1) // System.out.println("---> POR with behavioral analysis"); // else if (cycleClosingMthdIndex == 2) // System.out.println("---> POR with behavioral analysis and state trace-back"); // else if (cycleClosingMthdIndex == 4) // System.out.println("---> POR with Peled's cycle condition"); // 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(); // //// System.out.println("------- curStateArray ----------"); //// 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; // System.out.println("-------------- curAmpleArray --------------"); // for (LinkedList<Transition> tranList : curAmpleArray) { // printTransLinkedList(tranList); // } //// System.out.println("-------------- curAmpleArray --------------"); //// for (LinkedList<Transition> tranList : curAmpleArray) { //// printTransLinkedList(tranList); //// } //// System.out.println("-------------- nextAmpleArray --------------"); //// 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) { // System.out.println("*** Verification failed: deadlock."); // 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 printStaticSetsMap( LhpnFile[] lpnList, HashMap<LpnTransitionPair,StaticSets> staticSetsMap) { System.out.println("---------- staticSetsMap -----------"); for (LpnTransitionPair lpnTranPair : staticSetsMap.keySet()) { StaticSets statSets = staticSetsMap.get(lpnTranPair); printLpnTranPair(lpnList, statSets.getTran(), statSets.getDisableSet(), "disableSet"); printLpnTranPair(lpnList, statSets.getTran(), statSets.getEnableBySettingEnablingTrue(), "enableBySetingEnablingTrue"); } } private void writeStaticSetsMapToPORDebugFile( LhpnFile[] lpnList, HashMap<LpnTransitionPair,StaticSets> staticSetsMap) { try { PORdebugBufferedWriter.write("---------- staticSetsMap -----------"); PORdebugBufferedWriter.newLine(); for (LpnTransitionPair lpnTranPair : staticSetsMap.keySet()) { StaticSets statSets = staticSetsMap.get(lpnTranPair); writeLpnTranPairToPORDebugFile(lpnList, statSets.getTran(), statSets.getDisableSet(), "disableSet"); writeLpnTranPairToPORDebugFile(lpnList, statSets.getTran(), statSets.getEnableBySettingEnablingTrue(), "enableBySetingEnablingTrue"); } } 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 printPlacesIndices(ArrayList<String> allPlaces) { // System.out.println("Indices of all places: "); // for (int i=0; i < allPlaces.size(); i++) { // System.out.println(allPlaces.get(i) + "\t" + i); // } // // } // // private void printTransIndices(Transition[] allTransitions) { // System.out.println("Indices of all transitions: "); // for (int i=0; i < allTransitions.length; i++) { // System.out.println(allTransitions[i].getName() + "\t" + allTransitions[i].getIndex()); // } // } // 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> curDisable, String setName) { try { //PORdebugBufferedWriter.write(setName + " for " + curTran.getName() + "(" + curTran.getIndex() + ")" + " is: "); PORdebugBufferedWriter.write(setName + " for (" + curTran.getLpn().getLabel() + " , " + curTran.getName() + ") is: "); if (curDisable.isEmpty()) { PORdebugBufferedWriter.write("empty"); PORdebugBufferedWriter.newLine(); } else { for (LpnTransitionPair lpnTranPair: curDisable) { PORdebugBufferedWriter.append("(" + lpnList[lpnTranPair.getLpnIndex()].getLabel() + ", " + lpnList[lpnTranPair.getLpnIndex()].getAllTransitions()[lpnTranPair.getTranIndex()].getName() + ")," + "\t"); } 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, 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()) { System.out.println("******** Partial Order Reduction ************"); printIntegerSet(curEnabled, sgList, "Enabled set"); System.out.println("******* Begin POR"); writeStringWithNewLineToPORDebugFile("******* Partial Order Reduction *******"); writeIntegerSetToPORDebugFile(curEnabled, sgList, "Enabled set"); writeStringWithNewLineToPORDebugFile("******* Begin POR *******"); } if (curEnabled.isEmpty()) { return ample; } // if (Options.getNecessaryUsingDependencyGraphs()) // ready = partialOrderReductionUsingDependencyGraphs(stateArray, curEnabled, staticSetsMap, sgList); // else ready = partialOrderReduction(stateArray, curEnabled, staticSetsMap, tranFiringFreq, sgList); if (Options.getDebugMode()) { System.out.println("******* End POR *******"); printIntegerSet(ready, sgList, "Ready set"); System.out.println("********************"); writeStringWithNewLineToPORDebugFile("******* End POR *******"); writeIntegerSetToPORDebugFile(ready, sgList, "Ready set"); writeStringWithNewLineToPORDebugFile("********************"); } // ************* Priority: tran fired less times first ************* //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)) { // System.out.println("****** Transitions are possibly ignored in a cycle.******"); // 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) { //System.out.println("*** Verification failed: deadlock."); 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("-------------------------------------\n" + "---> 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) { //System.err.println("*** Verification failed: deadlock."); 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() + ", "); // System.out.println("\n-----------------------------------------------------\n"); // 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 # of states : " + prjStateSet.size() + "\n-----------------------------------------------------\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"); // System.out.println("\n ---------111111-------------\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("\n-------------------------\n"); } //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> partialOrderReductionUsingDependencyGraphs(State[] curStateArray, HashSet<LpnTransitionPair> curEnabled, HashMap<LpnTransitionPair, StaticSets> staticMap, StateGraph[] sgList) { if (curEnabled.size() == 1) return curEnabled; HashSet<LpnTransitionPair> ready = new HashSet<LpnTransitionPair>(); LhpnFile[] lpnList = new LhpnFile[sgList.length]; for (int i=0; i<sgList.length; i++) { lpnList[i] = sgList[i].getLpn(); } // enabledTran is independent of other transitions for (LpnTransitionPair enabledTran : curEnabled) { if (staticMap.get(enabledTran).getDisableSet().isEmpty()) { ready.add(enabledTran); return ready; } } for (LpnTransitionPair enabledTran : curEnabled) { if (Options.getDebugMode()) { System.out.println("@ partialOrderReduction, consider transition " + sgList[enabledTran.getLpnIndex()].getLpn().getLabel() + "("+ sgList[enabledTran.getLpnIndex()].getLpn().getTransition(enabledTran.getTranIndex()) + "). Compute its dependent set."); writeStringWithNewLineToPORDebugFile("@ partialOrderReduction, consider transition " + sgList[enabledTran.getLpnIndex()].getLpn().getLabel() + "("+ sgList[enabledTran.getLpnIndex()].getLpn().getTransition(enabledTran.getTranIndex()) + "). Compute its dependent set."); } HashSet<LpnTransitionPair> dependent = new HashSet<LpnTransitionPair>(); boolean isCycleClosingAmpleComputation = false; dependent = computeDependent(curStateArray,enabledTran,dependent,curEnabled,staticMap, lpnList, isCycleClosingAmpleComputation); // printIntegerSet(dependent, sgList, "dependent set for enabled transition " + sgList[enabledTran.getLpnIndex()].getLpn().getLabel() // + "(" + enabledTransition.getName() + ")"); if (ready.isEmpty()) ready = (HashSet<LpnTransitionPair>) dependent.clone(); else if (dependent.size() < ready.size() && !ready.isEmpty()) ready = (HashSet<LpnTransitionPair>) dependent.clone(); if (ready.size() == 1) { cachedNecessarySets.clear(); return ready; } } cachedNecessarySets.clear(); return ready; } private HashSet<LpnTransitionPair> partialOrderReduction(State[] curStateArray, HashSet<LpnTransitionPair> curEnabled, HashMap<LpnTransitionPair, StaticSets> staticMap, HashMap<LpnTransitionPair,Integer> tranFiringFreqMap, StateGraph[] sgList) { if (curEnabled.size() == 1) return curEnabled; HashSet<LpnTransitionPair> ready = null; LhpnFile[] lpnList = new LhpnFile[sgList.length]; for (int i=0; i<sgList.length; i++) { lpnList[i] = sgList[i].getLpn(); } DependentSetComparator depComp = new DependentSetComparator(tranFiringFreqMap); PriorityQueue<DependentSet> dependentSetQueue = new PriorityQueue<DependentSet>(curEnabled.size(), depComp); for (LpnTransitionPair enabledTran : curEnabled) { if (Options.getDebugMode()){ System.out.println("@ partialOrderReduction, consider transition " + sgList[enabledTran.getLpnIndex()].getLpn().getLabel() + "("+ sgList[enabledTran.getLpnIndex()].getLpn().getTransition(enabledTran.getTranIndex()) + ")"); writeStringWithNewLineToPORDebugFile("@ partialOrderReduction, consider transition " + sgList[enabledTran.getLpnIndex()].getLpn().getLabel() + "("+ sgList[enabledTran.getLpnIndex()].getLpn().getTransition(enabledTran.getTranIndex()) + ")"); } 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); // printIntegerSet(dependent, sgList, "dependent set for enabled transition " + sgList[enabledTran.getLpnIndex()].getLpn().getLabel() // + "(" + enabledTransition.getName() + ")"); // 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); // if (ready.isEmpty()) // ready = (HashSet<LpnTransitionPair>) dependent.clone(); // else if (dependent.size() < ready.size() && !ready.isEmpty()) // ready = (HashSet<LpnTransitionPair>) dependent.clone(); // if (ready.size() == 1) { // cachedNecessarySets.clear(); // return ready; // } } cachedNecessarySets.clear(); ready = dependentSetQueue.poll().getDependent(); 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()) { System.out.println("@ getDependentSet, consider transition " + lpnList[seedTran.getLpnIndex()].getTransition(seedTran.getTranIndex()).getName()); //printIntegerSet(canModifyAssign, lpnList, lpnList[enabledLpnTran.getLpnIndex()].getTransition(enabledLpnTran.getTranIndex()) + " can modify assignments"); printIntegerSet(disableSet, lpnList, "Disable set for " + lpnList[seedTran.getLpnIndex()].getTransition(seedTran.getTranIndex())); writeStringWithNewLineToPORDebugFile("@ getDependentSet, consider transition " + lpnList[seedTran.getLpnIndex()].getTransition(seedTran.getTranIndex()).getName()); writeIntegerSetToPORDebugFile(disableSet, lpnList, "Disable set for " + lpnList[seedTran.getLpnIndex()].getTransition(seedTran.getTranIndex())); } dependent.add(seedTran); // for (LpnTransitionPair lpnTranPair : canModifyAssign) { // if (curEnabled.contains(lpnTranPair)) // dependent.add(lpnTranPair); // } if (Options.getDebugMode()) { printIntegerSet(dependent, lpnList, "@ getDependentSet at 0, dependent set for " + lpnList[seedTran.getLpnIndex()].getTransition(seedTran.getTranIndex())); writeIntegerSetToPORDebugFile(dependent, lpnList, "@ getDependentSet at 0, dependent set for " + lpnList[seedTran.getLpnIndex()].getTransition(seedTran.getTranIndex())); } // // dependent is equal to enabled. Terminate. // if (dependent.size() == curEnabled.size()) { // if (Options.getDebugMode()) // System.out.println("Check 0: dependent == curEnabled. Return dependent."); // return dependent; // } for (LpnTransitionPair tranInDisableSet : disableSet) { if (Options.getDebugMode()) { System.out.println("Consider transition in the disable set of " + lpnList[seedTran.getLpnIndex()].getLabel() + "(" + lpnList[seedTran.getLpnIndex()].getTransition(seedTran.getTranIndex()) + "): " + lpnList[tranInDisableSet.getLpnIndex()].getLabel() +"(" + lpnList[tranInDisableSet.getLpnIndex()].getTransition(tranInDisableSet.getTranIndex()) + ")"); writeStringWithNewLineToPORDebugFile("Consider transition in the disable set of " + lpnList[seedTran.getLpnIndex()].getLabel() + "(" + lpnList[seedTran.getLpnIndex()].getTransition(seedTran.getTranIndex()) + "): " + lpnList[tranInDisableSet.getLpnIndex()].getLabel() +"(" + lpnList[tranInDisableSet.getLpnIndex()].getTransition(tranInDisableSet.getTranIndex()) + ")"); } 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()) { printIntegerSet(dependent, lpnList, "@ getDependentSet at 1 for transition " + lpnList[seedTran.getLpnIndex()].getTransition(seedTran.getTranIndex())); writeIntegerSetToPORDebugFile(dependent, lpnList, "@ getDependentSet at 1 for transition " + lpnList[seedTran.getLpnIndex()].getTransition(seedTran.getTranIndex())); } } 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 origTran = new LpnTransitionPair(tranInDisableSet.getLpnIndex(), tranInDisableSet.getTranIndex()); HashSet<LpnTransitionPair> necessary = null; if (Options.getDebugMode()) { printCachedNecessarySets(lpnList); writeCachedNecessarySetsToPORDebugFile(lpnList); } if (cachedNecessarySets.containsKey(tranInDisableSet)) { if (Options.getDebugMode()) { System.out.println("Found transition " + lpnList[tranInDisableSet.getLpnIndex()].getLabel() + "(" + lpnList[tranInDisableSet.getLpnIndex()].getTransition(tranInDisableSet.getTranIndex()).getName() + ") in the cached necessary sets."); writeStringWithNewLineToPORDebugFile("Found transition " + lpnList[tranInDisableSet.getLpnIndex()].getLabel() + "(" + lpnList[tranInDisableSet.getLpnIndex()].getTransition(tranInDisableSet.getTranIndex()).getName() + ") in the cached necessary sets."); } necessary = cachedNecessarySets.get(tranInDisableSet); } else { if (Options.getNecessaryUsingDependencyGraphs()) { if (Options.getDebugMode()) { System.out.println("==== Compute necessary using BFS ===="); writeStringWithNewLineToPORDebugFile("==== Compute necessary using BFS ===="); } necessary = computeNecessaryUsingDependencyGraphs(curStateArray,tranInDisableSet,curEnabled, staticMap, lpnList); } else { if (Options.getDebugMode()) { System.out.println("==== Compute necessary using DFS ===="); writeStringWithNewLineToPORDebugFile("==== Compute necessary using DFS ===="); } necessary = computeNecessary(curStateArray,tranInDisableSet,dependent,curEnabled, staticMap, lpnList, origTran); } } if (necessary != null && !necessary.isEmpty()) { cachedNecessarySets.put(tranInDisableSet, necessary); if (Options.getDebugMode()) { printIntegerSet(necessary, lpnList, "necessary set for transition " + lpnList[tranInDisableSet.getLpnIndex()].getLabel() + "(" + lpnList[tranInDisableSet.getLpnIndex()].getTransition(tranInDisableSet.getTranIndex()) + ")"); writeIntegerSetToPORDebugFile(necessary, lpnList, "necessary set for transition " + lpnList[tranInDisableSet.getLpnIndex()].getLabel() + "(" + lpnList[tranInDisableSet.getLpnIndex()].getTransition(tranInDisableSet.getTranIndex()) + ")"); } for (LpnTransitionPair tranNecessary : necessary) { if (!dependent.contains(tranNecessary)) { if (Options.getDebugMode()) { printIntegerSet(dependent, lpnList, "Dependent set for " + lpnList[seedTran.getLpnIndex()].getLabel() + "(" + lpnList[seedTran.getLpnIndex()].getTransition(seedTran.getTranIndex()) + "):"); System.out.println("It does not contain this transition found by computeNecessary: " + lpnList[tranNecessary.getLpnIndex()].getLabel() + "(" + lpnList[tranNecessary.getLpnIndex()].getTransition(tranNecessary.getTranIndex()) + ")" + ". Compute its dependent set."); writeIntegerSetToPORDebugFile(dependent, lpnList, "Dependent set for " + lpnList[seedTran.getLpnIndex()].getLabel() + "(" + lpnList[seedTran.getLpnIndex()].getTransition(seedTran.getTranIndex()) + "):"); writeStringWithNewLineToPORDebugFile("It does not contain this transition found by computeNecessary: " + lpnList[tranNecessary.getLpnIndex()].getLabel() + "(" + lpnList[tranNecessary.getLpnIndex()].getTransition(tranNecessary.getTranIndex()) + ")" + ". Compute its dependent set."); } dependent.addAll(computeDependent(curStateArray,tranNecessary,dependent,curEnabled,staticMap, lpnList, isCycleClosingAmpleComputation)); } } } else { if (Options.getDebugMode()) { System.out.println("necessary set for transition " + lpnList[seedTran.getLpnIndex()].getTransition(seedTran.getTranIndex()) + " is empty."); writeStringWithNewLineToPORDebugFile("necessary set for transition " + lpnList[seedTran.getLpnIndex()].getTransition(seedTran.getTranIndex()) + " is empty."); } dependent.addAll(curEnabled); } if (Options.getDebugMode()) { printIntegerSet(dependent, lpnList, "@ getDependentSet at 2, dependent set for transition " + lpnList[seedTran.getLpnIndex()].getTransition(seedTran.getTranIndex())); writeIntegerSetToPORDebugFile(dependent, lpnList, "@ getDependentSet at 2, dependent set for transition " + lpnList[seedTran.getLpnIndex()].getTransition(seedTran.getTranIndex())); } } } return dependent; } @SuppressWarnings("unchecked") private HashSet<LpnTransitionPair> computeNecessary(State[] curStateArray, LpnTransitionPair tran, HashSet<LpnTransitionPair> dependent, HashSet<LpnTransitionPair> curEnabledIndices, HashMap<LpnTransitionPair, StaticSets> staticMap, LhpnFile[] lpnList, LpnTransitionPair origTran) { if (Options.getDebugMode()) { System.out.println("@ getNecessary, consider transition: " + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(tran.getTranIndex()).getName() + ")"); writeStringWithNewLineToPORDebugFile("@ getNecessary, consider transition: " + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(tran.getTranIndex()).getName() + ")"); } if (cachedNecessarySets.containsKey(tran)) { if (Options.getDebugMode()) { System.out.println("Found transition" + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(tran.getTranIndex()).getName() + ")" + "'s necessary set in the cached necessary sets. "); writeStringWithNewLineToPORDebugFile("Found transition" + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(tran.getTranIndex()).getName() + ")" + "'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()) { System.out.println("####### compute nMarking for transition " + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(tran.getTranIndex()).getName() + ") " + "########"); writeStringWithNewLineToPORDebugFile("####### compute nMarking for transition " + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(tran.getTranIndex()).getName() + ") " + "########"); } HashSet<LpnTransitionPair> nMarkingTemp = new HashSet<LpnTransitionPair>(); String placeName = lpnList[tran.getLpnIndex()].getAllPlaces().get(place); if (Options.getDebugMode()) { System.out.println("preset place of " + transition.getName() + " is " + placeName); writeStringWithNewLineToPORDebugFile("preset place of " + transition.getName() + " 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()) { System.out.println("preset transition of " + placeName + " is " + lpnList[presetTran.getLpnIndex()].getLabel() + "(" + lpnList[presetTran.getLpnIndex()].getTransition(presetTran.getTranIndex()) + ")"); writeStringWithNewLineToPORDebugFile("preset transition of " + placeName + " is " + lpnList[presetTran.getLpnIndex()].getLabel() + "(" + lpnList[presetTran.getLpnIndex()].getTransition(presetTran.getTranIndex()) + ")"); } if (origTran.getVisitedTrans().contains(presetTran)) { if (Options.getDebugMode()) { System.out.println("Transition " + lpnList[presetTran.getLpnIndex()].getLabel() + "(" + lpnList[presetTran.getLpnIndex()].getTransition(presetTran.getTranIndex()) + ") is visted before by " + lpnList[origTran.getLpnIndex()].getLabel() + "(" + lpnList[origTran.getLpnIndex()].getTransition(origTran.getTranIndex()).getName() + ")."); writeStringWithNewLineToPORDebugFile("Transition " + lpnList[presetTran.getLpnIndex()].getLabel() + "(" + lpnList[presetTran.getLpnIndex()].getTransition(presetTran.getTranIndex()) + ") is visted before by " + lpnList[origTran.getLpnIndex()].getLabel() + "(" + lpnList[origTran.getLpnIndex()].getTransition(origTran.getTranIndex()).getName() + ")."); } if (cachedNecessarySets.containsKey(presetTran)) { if (Options.getDebugMode()) { System.out.println("Found transition" + lpnList[presetTran.getLpnIndex()].getLabel() + "(" + lpnList[presetTran.getLpnIndex()].getTransition(presetTran.getTranIndex()).getName() + ")" + "'s necessary set in the cached necessary sets. Add it to nMarkingTemp."); writeStringWithNewLineToPORDebugFile("Found transition" + lpnList[presetTran.getLpnIndex()].getLabel() + "(" + lpnList[presetTran.getLpnIndex()].getTransition(presetTran.getTranIndex()).getName() + ")" + "'s necessary set in the cached necessary sets. Add it to nMarkingTemp."); } nMarkingTemp = cachedNecessarySets.get(presetTran); } if (curEnabledIndices.contains(presetTran)) { if (Options.getDebugMode()) { System.out.println("@ nMarking: curEnabled contains transition " + lpnList[presetTran.getLpnIndex()].getLabel() + "(" + lpnList[presetTran.getLpnIndex()].getTransition(presetTran.getTranIndex()).getName() + "). Add to nMarkingTmp."); writeStringWithNewLineToPORDebugFile("@ nMarking: curEnabled contains transition " + lpnList[presetTran.getLpnIndex()].getLabel() + "(" + lpnList[presetTran.getLpnIndex()].getTransition(presetTran.getTranIndex()).getName() + "). Add to nMarkingTmp."); } nMarkingTemp.add(new LpnTransitionPair(tran.getLpnIndex(), presetTrans[j]));; } continue; } else origTran.addVisitedTran(presetTran); if (Options.getDebugMode()) { System.out.println("~~~~~~~~~ transVisited for transition " + lpnList[origTran.getLpnIndex()].getLabel() + "(" + lpnList[origTran.getLpnIndex()].getTransition(origTran.getTranIndex()).getName() + ")~~~~~~~~~"); writeStringWithNewLineToPORDebugFile("~~~~~~~~~ transVisited for transition " + lpnList[origTran.getLpnIndex()].getLabel() + "(" + lpnList[origTran.getLpnIndex()].getTransition(origTran.getTranIndex()).getName() + ")~~~~~~~~~"); for (LpnTransitionPair visitedTran : origTran.getVisitedTrans()) { System.out.println(lpnList[visitedTran.getLpnIndex()].getLabel() + "(" + lpnList[visitedTran.getLpnIndex()].getTransition(visitedTran.getTranIndex()).getName() + ") "); writeStringWithNewLineToPORDebugFile(lpnList[visitedTran.getLpnIndex()].getLabel() + "(" + lpnList[visitedTran.getLpnIndex()].getTransition(visitedTran.getTranIndex()).getName() + ") "); } System.out.println("@ getNecessary, consider transition: " + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(presetTrans[j]).getName() + ")."); writeStringWithNewLineToPORDebugFile("@ getNecessary, consider transition: " + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(presetTrans[j]).getName() + ")."); } if (curEnabledIndices.contains(presetTran)) { if (Options.getDebugMode()) { System.out.println("@ nMarking: curEnabled contains transition " + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(presetTran.getTranIndex()).getName() + "). Add to nMarkingTmp."); writeStringWithNewLineToPORDebugFile("@ nMarking: curEnabled contains transition " + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(presetTran.getTranIndex()).getName() + "). Add to nMarkingTmp."); } nMarkingTemp.add(new LpnTransitionPair(tran.getLpnIndex(), presetTrans[j])); } else { if (Options.getDebugMode()) { System.out.println("@ nMarking: transition " + lpnList[tran.getLpnIndex()].getTransition(presetTrans[j]).getName() + " is not enabled. Compute its necessary set."); writeStringWithNewLineToPORDebugFile("@ nMarking: transition " + lpnList[tran.getLpnIndex()].getTransition(presetTrans[j]).getName() + " is not enabled. Compute its necessary set."); } HashSet<LpnTransitionPair> tmp = null; tmp = computeNecessary(curStateArray, presetTran, dependent, curEnabledIndices, staticMap, lpnList, origTran); if (tmp != null) nMarkingTemp.addAll(tmp); else if (Options.getDebugMode()) { System.out.println("@ nMarking: necessary set for transition " + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(presetTrans[j]).getName() + ") is null."); writeStringWithNewLineToPORDebugFile("@ nMarking: necessary set for transition " + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(presetTrans[j]).getName() + ") is null."); } } } if (nMarkingTemp != null) if (nMarking == null || nMarkingTemp.size() < nMarking.size()) nMarking = (HashSet<LpnTransitionPair>) nMarkingTemp.clone(); } else if (Options.getDebugMode()) { System.out.println("Place " + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getAllPlaces().get(place) + ") is marked."); writeStringWithNewLineToPORDebugFile("Place " + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getAllPlaces().get(place) + ") is marked."); } } // Search for transition(s) that can help to enable the current transition. HashSet<LpnTransitionPair> nEnable = null; int[] varValueVector = curStateArray[tran.getLpnIndex()].getVector();//curState.getVector(); HashSet<LpnTransitionPair> canEnable = staticMap.get(tran).getEnableBySettingEnablingTrue(); if (Options.getDebugMode()) { System.out.println("####### compute nEnable for transition " + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(tran.getTranIndex()).getName() + ") " + "########"); printIntegerSet(canEnable, lpnList, lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(tran.getTranIndex()) + ") can be enabled by"); writeStringWithNewLineToPORDebugFile("####### compute nEnable for transition " + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(tran.getTranIndex()).getName() + ") " + "########"); writeIntegerSetToPORDebugFile(canEnable, lpnList, lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(tran.getTranIndex()) + ") 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 (LpnTransitionPair tranCanEnable : canEnable) { if (curEnabledIndices.contains(tranCanEnable)) { nEnable.add(tranCanEnable); if (Options.getDebugMode()) { System.out.println("@ nEnable: curEnabled contains transition " + lpnList[tranCanEnable.getLpnIndex()].getLabel() + "(" + lpnList[tranCanEnable.getLpnIndex()].getTransition(tranCanEnable.getTranIndex()).getName() + "). Add to nEnable."); writeStringWithNewLineToPORDebugFile("@ nEnable: curEnabled contains transition " + lpnList[tranCanEnable.getLpnIndex()].getLabel() + "(" + lpnList[tranCanEnable.getLpnIndex()].getTransition(tranCanEnable.getTranIndex()).getName() + "). Add to nEnable."); } } else { if (origTran.getVisitedTrans().contains(tranCanEnable)) { if (Options.getDebugMode()) { System.out.println("Transition " + lpnList[tranCanEnable.getLpnIndex()].getLabel() + "(" + lpnList[tranCanEnable.getLpnIndex()].getTransition(tranCanEnable.getTranIndex()) + ") is visted before by " + lpnList[origTran.getLpnIndex()].getLabel() + "(" + lpnList[origTran.getLpnIndex()].getTransition(origTran.getTranIndex()).getName() + ")."); writeStringWithNewLineToPORDebugFile("Transition " + lpnList[tranCanEnable.getLpnIndex()].getLabel() + "(" + lpnList[tranCanEnable.getLpnIndex()].getTransition(tranCanEnable.getTranIndex()) + ") is visted before by " + lpnList[origTran.getLpnIndex()].getLabel() + "(" + lpnList[origTran.getLpnIndex()].getTransition(origTran.getTranIndex()).getName() + ")."); } if (cachedNecessarySets.containsKey(tranCanEnable)) { if (Options.getDebugMode()) { System.out.println("Found transition" + lpnList[tranCanEnable.getLpnIndex()].getLabel() + "(" + lpnList[tranCanEnable.getLpnIndex()].getTransition(tranCanEnable.getTranIndex()).getName() + ")" + "'s necessary set in the cached necessary sets. Add it to nMarkingTemp."); writeStringWithNewLineToPORDebugFile("Found transition" + lpnList[tranCanEnable.getLpnIndex()].getLabel() + "(" + lpnList[tranCanEnable.getLpnIndex()].getTransition(tranCanEnable.getTranIndex()).getName() + ")" + "'s necessary set in the cached necessary sets. Add it to nMarkingTemp."); } nEnable.addAll(cachedNecessarySets.get(tranCanEnable)); } continue; } else origTran.addVisitedTran(tranCanEnable); if (Options.getDebugMode()) { System.out.println("@ nEnable: transition " + lpnList[tranCanEnable.getLpnIndex()].getTransition(tranCanEnable.getTranIndex()).getName() + " is not enabled. Compute its necessary set."); writeStringWithNewLineToPORDebugFile("@ nEnable: transition " + lpnList[tranCanEnable.getLpnIndex()].getTransition(tranCanEnable.getTranIndex()).getName() + " is not enabled. Compute its necessary set."); } HashSet<LpnTransitionPair> tmp = null; tmp = computeNecessary(curStateArray, tranCanEnable, dependent, curEnabledIndices, staticMap, lpnList, origTran); if (tmp != null) nEnable.addAll(tmp); else if (Options.getDebugMode()) { System.out.println("@ nEnable: necessary set for transition " + lpnList[tranCanEnable.getLpnIndex()].getLabel() + "(" + lpnList[tranCanEnable.getLpnIndex()].getTransition(tranCanEnable.getTranIndex()).getName() + ") is null."); writeStringWithNewLineToPORDebugFile("@ nEnable: necessary set for transition " + lpnList[tranCanEnable.getLpnIndex()].getLabel() + "(" + lpnList[tranCanEnable.getLpnIndex()].getTransition(tranCanEnable.getTranIndex()).getName() + ") is null."); } } } } if (Options.getDebugMode()) { if (transition.getEnablingTree() == null) { System.out.println("@ nEnable: transition " + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(tran.getTranIndex()).getName() + ") has no enabling condition."); writeStringWithNewLineToPORDebugFile("@ nEnable: transition " + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(tran.getTranIndex()).getName() + ") has no enabling condition."); } else if (transition.getEnablingTree().evaluateExpr(lpnList[tran.getLpnIndex()].getAllVarsWithValuesAsString(varValueVector)) !=0.0) { System.out.println("@ nEnable: transition " + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(tran.getTranIndex()).getName() + ")'s enabling condition is true."); writeStringWithNewLineToPORDebugFile("@ nEnable: transition " + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(tran.getTranIndex()).getName() + ")'s enabling condition is true."); } else if (transition.getEnablingTree() != null && transition.getEnablingTree().evaluateExpr(lpnList[tran.getLpnIndex()].getAllVarsWithValuesAsString(varValueVector)) == 0.0 && canEnable.isEmpty()) { System.out.println("@ nEnable: transition " + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(tran.getTranIndex()).getName() + ")'s enabling condition is false, but no other transitions that can help to enable it were found ."); writeStringWithNewLineToPORDebugFile("@ nEnable: transition " + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(tran.getTranIndex()).getName() + ")'s enabling condition is false, but no other transitions that can help to enable it were found ."); } printIntegerSet(nMarking, lpnList, "nMarking for transition " + transition.getName()); printIntegerSet(nEnable, lpnList, "nEnable for transition " + transition.getName()); writeIntegerSetToPORDebugFile(nMarking, lpnList, "nMarking for transition " + transition.getName()); writeIntegerSetToPORDebugFile(nEnable, lpnList, "nEnable for transition " + transition.getName()); } if (nEnable == null && nMarking != null) { if (!nMarking.isEmpty()) cachedNecessarySets.put(tran, nMarking); if (Options.getDebugMode()) { printCachedNecessarySets(lpnList); writeCachedNecessarySetsToPORDebugFile(lpnList); } return nMarking; } else if (nMarking == null && nEnable != null) { if (!nEnable.isEmpty()) cachedNecessarySets.put(tran, nEnable); if (Options.getDebugMode()) { printCachedNecessarySets(lpnList); 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()) { printCachedNecessarySets(lpnList); writeCachedNecessarySetsToPORDebugFile(lpnList); } return nMarking; } else { cachedNecessarySets.put(tran, nEnable); if (Options.getDebugMode()) { printCachedNecessarySets(lpnList); writeCachedNecessarySetsToPORDebugFile(lpnList); } return nEnable; } } else if (nMarking.isEmpty() && !nEnable.isEmpty()) { cachedNecessarySets.put(tran, nEnable); if (Options.getDebugMode()) { printCachedNecessarySets(lpnList); writeCachedNecessarySetsToPORDebugFile(lpnList); } return nEnable; } else { cachedNecessarySets.put(tran, nMarking); if (Options.getDebugMode()) { printCachedNecessarySets(lpnList); writeCachedNecessarySetsToPORDebugFile(lpnList); } return nMarking; } } } private HashSet<LpnTransitionPair> computeNecessaryUsingDependencyGraphs(State[] curStateArray, LpnTransitionPair seedTran, HashSet<LpnTransitionPair> curEnabled, HashMap<LpnTransitionPair, StaticSets> staticMap, LhpnFile[] lpnList) { if (Options.getDebugMode()) { System.out.println("@ getNecessary, consider transition: " + lpnList[seedTran.getLpnIndex()].getLabel() + "(" + lpnList[seedTran.getLpnIndex()].getTransition(seedTran.getTranIndex()).getName() + ")"); writeStringWithNewLineToPORDebugFile("@ getNecessary, consider transition: " + lpnList[seedTran.getLpnIndex()].getLabel() + "(" + lpnList[seedTran.getLpnIndex()].getTransition(seedTran.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(seedTran); //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()) { System.out.println("Found transition" + lpnList[curTran.getLpnIndex()].getLabel() + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()).getName() + ")" + "'s necessary set in the cached necessary sets. Terminate BFS."); writeStringWithNewLineToPORDebugFile("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); // 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 enable trnasition " + lpnList[curTran.getLpnIndex()].getLabel() + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()) + ") "); writeIntegerSetToPORDebugFile(canEnable, lpnList, "Neighbors that can help to enable trnasition " + lpnList[curTran.getLpnIndex()].getLabel() + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()) + ") "); } for (LpnTransitionPair neighborTran : canEnable) { if (curEnabled.contains(neighborTran)) { 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(seedTran, necessarySet); if (Options.getDebugMode()) { System.out.println("Enabled neighbor that can help to enable trnasition " + lpnList[curTran.getLpnIndex()].getLabel() + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()) + "): " + lpnList[neighborTran.getLpnIndex()].getLabel() + "(" + lpnList[neighborTran.getLpnIndex()].getTransition(neighborTran.getTranIndex()) + ")"); writeStringWithNewLineToPORDebugFile("Enabled neighbor that can help to enable trnasition " + lpnList[curTran.getLpnIndex()].getLabel() + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()) + "): " + lpnList[neighborTran.getLpnIndex()].getLabel() + "(" + lpnList[neighborTran.getLpnIndex()].getTransition(neighborTran.getTranIndex()) + ")"); } return necessarySet; } if (!allExploredTrans.contains(neighborTran)) { allExploredTrans.add(neighborTran); exploredTransQueue.add(neighborTran); } } canEnable.clear(); } return null; } private HashSet<LpnTransitionPair> buildCanBringTokenSet( LpnTransitionPair curTran, LhpnFile[] lpnList, State[] curStateArray) { // Build transition(s) set that can help to bring the marking(s). Transition curTransition = lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()); int[] presetPlaces = lpnList[curTran.getLpnIndex()].getPresetIndex(curTransition.getName()); HashSet<LpnTransitionPair> canBringToken = new HashSet<LpnTransitionPair>(); for (int i=0; i < presetPlaces.length; i++) { int place = presetPlaces[i]; if (curStateArray[curTran.getLpnIndex()].getMarking()[place]==0) { String placeName = lpnList[curTran.getLpnIndex()].getAllPlaces().get(place); int[] presetTrans = lpnList[curTran.getLpnIndex()].getPresetIndex(placeName); for (int j=0; j < presetTrans.length; j++) { LpnTransitionPair presetTran = new LpnTransitionPair(curTran.getLpnIndex(), presetTrans[j]); canBringToken.add(presetTran); } } } return canBringToken; } 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) { writeStringWithNewLineToPORDebugFile("================ cachedNecessarySets ================="); for (LpnTransitionPair key : cachedNecessarySets.keySet()) { writeStringToPORDebugFile(lpnList[key.getLpnIndex()].getLabel() + "(" + lpnList[key.getLpnIndex()].getTransition(key.getTranIndex()).getName() + ") => "); HashSet<LpnTransitionPair> necessarySet = cachedNecessarySets.get(key); for (LpnTransitionPair necessary : necessarySet) { writeStringToPORDebugFile(lpnList[necessary.getLpnIndex()].getLabel() + "(" + lpnList[necessary.getLpnIndex()].getTransition(necessary.getTranIndex()).getName() + ") "); } writeStringWithNewLineToPORDebugFile(""); } } 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) { writeStringWithNewLineToPORDebugFile("null"); } else if (indicies.isEmpty()) { writeStringWithNewLineToPORDebugFile("empty"); } else { for (LpnTransitionPair lpnTranPair : indicies) { writeStringToPORDebugFile("\t" + sgList[lpnTranPair.getLpnIndex()].getLpn().getLabel() + "(" + sgList[lpnTranPair.getLpnIndex()].getLpn().getAllTransitions()[lpnTranPair.getTranIndex()].getName() + ") \t"); } writeStringWithNewLineToPORDebugFile(""); } } 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) { writeStringWithNewLineToPORDebugFile("null"); } else if (indicies.isEmpty()) { writeStringWithNewLineToPORDebugFile("empty"); } else { for (LpnTransitionPair lpnTranPair : indicies) { writeStringToPORDebugFile(lpnList[lpnTranPair.getLpnIndex()].getLabel() + "(" + lpnList[lpnTranPair.getLpnIndex()].getAllTransitions()[lpnTranPair.getTranIndex()].getName() + ") \t"); } writeStringWithNewLineToPORDebugFile(""); } } }
Changed fire method to reflect adding a couple new parameters to the method.
gui/src/verification/platu/logicAnalysis/Analysis.java
Changed fire method to reflect adding a couple new parameters to the method.
Java
apache-2.0
e78c134d1c0f61249b9fd7181c225577155892e2
0
aertoria/opennlp,Eagles2F/opennlp,jsubercaze/opennlp-tools-steroids,aertoria/opennlp,jsubercaze/opennlp-tools-steroids,aertoria/opennlp,jsubercaze/opennlp-tools-steroids,Eagles2F/opennlp,Eagles2F/opennlp
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.util; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Test; /** * Tests for the {@link Span} class. */ public class SpanTest { /** * Test for {@link Span#getStart()}. */ @Test public void testGetStart() { assertEquals(5, new Span(5, 6).getStart()); } /** * Test for {@link Span#getEnd()}. */ @Test public void testGetEnd() { assertEquals(6, new Span(5, 6).getEnd()); } /** * Test for {@link Span#length()}. */ @Test public void testLength() { assertEquals(11, new Span(10, 21).length()); } /** * Test for {@link Span#contains(Span)}. */ @Test public void testContains() { Span a = new Span(500, 900); Span b = new Span(520, 600); assertEquals(true, a.contains(b)); } /** * Test for {@link Span#contains(Span)}. */ @Test public void testContainsWithEqual() { Span a = new Span(500, 900); assertEquals(true, a.contains(a)); } /** * Test for {@link Span#contains(Span)}. */ @Test public void testContainsWithLowerIntersect() { Span a = new Span(500, 900); Span b = new Span(450, 1000); assertEquals(false, a.contains(b)); } /** * Test for {@link Span#contains(Span)}. */ @Test public void testContainsWithHigherIntersect() { Span a = new Span(500, 900); Span b = new Span(500, 1000); assertEquals(false, a.contains(b)); } /** * Test for {@link Span#contains(int)}. */ @Test public void testContainsInt() { Span a = new Span(10, 300); /* NOTE: here the span does not contain the endpoint marked as the end * for the span. This is because the end should be placed one past the * true end for the span. The indexes used must observe the same * requirements for the contains function. */ assertFalse(a.contains(9)); assertTrue(a.contains(10)); assertTrue(a.contains(200)); assertTrue(a.contains(299)); assertFalse(a.contains(300)); } /** * Test for {@link Span#startsWith(Span)}. */ @Test public void testStartsWith() { Span a = new Span(10, 50); Span b = new Span(10, 12); assertTrue(a.startsWith(a)); assertTrue(a.startsWith(b)); assertFalse(b.startsWith(a)); } /** * Test for {@link Span#intersects(Span)}. */ @Test public void testIntersects() { Span a = new Span(10, 50); Span b = new Span(40, 100); assertTrue(a.intersects(b)); assertTrue(b.intersects(a)); Span c = new Span(10, 20); Span d = new Span(40, 50); assertFalse(c.intersects(d)); assertFalse(d.intersects(c)); assertTrue(b.intersects(d)); } /** * Test for {@link Span#crosses(Span)}. */ @Test public void testCrosses() { Span a = new Span(10, 50); Span b = new Span(40, 100); assertTrue(a.crosses(b)); assertTrue(b.crosses(a)); Span c = new Span(10, 20); Span d = new Span(40, 50); assertFalse(c.crosses(d)); assertFalse(d.crosses(c)); assertFalse(b.crosses(d)); } /** * Test for {@link Span#compareTo(Object)}. */ @Test public void testCompareToLower() { Span a = new Span(100, 1000); Span b = new Span(10, 50); assertEquals(true, a.compareTo(b) > 0); } /** * Test for {@link Span#compareTo(Object)}. */ @Test public void testCompareToHigher() { Span a = new Span(100, 200); Span b = new Span(300, 400); assertEquals(true, a.compareTo(b) < 0); } /** * Test for {@link Span#compareTo(Object)}. */ @Test public void testCompareToEquals() { Span a = new Span(30, 1000); Span b = new Span(30, 1000); assertEquals(true, a.compareTo(b) == 0); } /** * Test for {@link Span#hashCode()}. */ @Test public void testhHashCode() { assertEquals(new Span(10, 11), new Span(10, 11)); } /** * Test for {@link Span#equals(Object)}. */ @Test public void testEqualsWithNull() { Span a = new Span(0, 0); assertEquals(a.equals(null), false); } /** * Test for {@link Span#equals(Object)}. */ @Test public void testEquals() { Span a1 = new Span(100, 1000, "test"); Span a2 = new Span(100, 1000, "test"); assertTrue(a1.equals(a2)); // end is different Span b1 = new Span(100, 100, "test"); assertFalse(a1.equals(b1)); // type is different Span c1 = new Span(100, 1000, "Test"); assertFalse(a1.equals(c1)); Span d1 = new Span(100, 1000); assertFalse(d1.equals(a1)); assertFalse(a1.equals(d1)); } /** * Test for {@link Span#toString()}. */ @Test public void testToString() { new Span(50, 100).toString(); } }
opennlp-tools/src/test/java/opennlp/tools/util/SpanTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.util; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Test; /** * Tests for the {@link Span} class. */ public class SpanTest { /** * Test for {@link Span#getStart()}. */ @Test public void testGetStart() { assertEquals(5, new Span(5, 6).getStart()); } /** * Test for {@link Span#getEnd()}. */ @Test public void testGetEnd() { assertEquals(6, new Span(5, 6).getEnd()); } /** * Test for {@link Span#length()}. */ @Test public void testLength() { assertEquals(11, new Span(10, 21).length()); } /** * Test for {@link Span#contains(Span)}. */ @Test public void testContains() { Span a = new Span(500, 900); Span b = new Span(520, 600); assertEquals(true, a.contains(b)); } /** * Test for {@link Span#contains(Span)}. */ @Test public void testContainsWithEqual() { Span a = new Span(500, 900); assertEquals(true, a.contains(a)); } /** * Test for {@link Span#contains(Span)}. */ @Test public void testContainsWithLowerIntersect() { Span a = new Span(500, 900); Span b = new Span(450, 1000); assertEquals(false, a.contains(b)); } /** * Test for {@link Span#contains(Span)}. */ @Test public void testContainsWithHigherIntersect() { Span a = new Span(500, 900); Span b = new Span(500, 1000); assertEquals(false, a.contains(b)); } /** * Test for {@link Span#contains(int)}. */ @Test public void testContainsInt() { Span a = new Span(10, 300); assertFalse(a.contains(9)); assertTrue(a.contains(10)); assertTrue(a.contains(200)); assertTrue(a.contains(300)); assertFalse(a.contains(301)); } /** * Test for {@link Span#startsWith(Span)}. */ @Test public void testStartsWith() { Span a = new Span(10, 50); Span b = new Span(10, 12); assertTrue(a.startsWith(a)); assertTrue(a.startsWith(b)); assertFalse(b.startsWith(a)); } /** * Test for {@link Span#intersects(Span)}. */ @Test public void testIntersects() { Span a = new Span(10, 50); Span b = new Span(40, 100); assertTrue(a.intersects(b)); assertTrue(b.intersects(a)); Span c = new Span(10, 20); Span d = new Span(40, 50); assertFalse(c.intersects(d)); assertFalse(d.intersects(c)); assertTrue(b.intersects(d)); } /** * Test for {@link Span#crosses(Span)}. */ @Test public void testCrosses() { Span a = new Span(10, 50); Span b = new Span(40, 100); assertTrue(a.crosses(b)); assertTrue(b.crosses(a)); Span c = new Span(10, 20); Span d = new Span(40, 50); assertFalse(c.crosses(d)); assertFalse(d.crosses(c)); assertFalse(b.crosses(d)); } /** * Test for {@link Span#compareTo(Object)}. */ @Test public void testCompareToLower() { Span a = new Span(100, 1000); Span b = new Span(10, 50); assertEquals(true, a.compareTo(b) > 0); } /** * Test for {@link Span#compareTo(Object)}. */ @Test public void testCompareToHigher() { Span a = new Span(100, 200); Span b = new Span(300, 400); assertEquals(true, a.compareTo(b) < 0); } /** * Test for {@link Span#compareTo(Object)}. */ @Test public void testCompareToEquals() { Span a = new Span(30, 1000); Span b = new Span(30, 1000); assertEquals(true, a.compareTo(b) == 0); } /** * Test for {@link Span#hashCode()}. */ @Test public void testhHashCode() { assertEquals(new Span(10, 11), new Span(10, 11)); } /** * Test for {@link Span#equals(Object)}. */ @Test public void testEqualsWithNull() { Span a = new Span(0, 0); assertEquals(a.equals(null), false); } /** * Test for {@link Span#equals(Object)}. */ @Test public void testEquals() { Span a1 = new Span(100, 1000, "test"); Span a2 = new Span(100, 1000, "test"); assertTrue(a1.equals(a2)); // end is different Span b1 = new Span(100, 100, "test"); assertFalse(a1.equals(b1)); // type is different Span c1 = new Span(100, 1000, "Test"); assertFalse(a1.equals(c1)); Span d1 = new Span(100, 1000); assertFalse(d1.equals(a1)); assertFalse(a1.equals(d1)); } /** * Test for {@link Span#toString()}. */ @Test public void testToString() { new Span(50, 100).toString(); } }
OPENNLP-298: fixed the SpanTest class to properly check the span indexes. git-svn-id: 924c1ce098d5c0cf43d98e06e1f2b659f3b417ce@1174507 13f79535-47bb-0310-9956-ffa450edef68
opennlp-tools/src/test/java/opennlp/tools/util/SpanTest.java
OPENNLP-298: fixed the SpanTest class to properly check the span indexes.
Java
apache-2.0
e9a1541d3cb497666e809158d80edcffbef86189
0
marco-dev/c-geo-opensource,S-Bartfast/cgeo,ThibaultR/cgeo,Huertix/cgeo,superspindel/cgeo,superspindel/cgeo,auricgoldfinger/cgeo,pstorch/cgeo,vishwakulkarni/cgeo,tobiasge/cgeo,lewurm/cgeo,schwabe/cgeo,SammysHP/cgeo,cgeo/cgeo,cgeo/cgeo,superspindel/cgeo,matej116/cgeo,schwabe/cgeo,lewurm/cgeo,samueltardieu/cgeo,cgeo/cgeo,KublaikhanGeek/cgeo,marco-dev/c-geo-opensource,ThibaultR/cgeo,yummy222/cgeo,kumy/cgeo,tobiasge/cgeo,kumy/cgeo,madankb/cgeo,xiaoyanit/cgeo,yummy222/cgeo,rsudev/c-geo-opensource,schwabe/cgeo,kumy/cgeo,matej116/cgeo,pstorch/cgeo,S-Bartfast/cgeo,auricgoldfinger/cgeo,Huertix/cgeo,ThibaultR/cgeo,Bananeweizen/cgeo,S-Bartfast/cgeo,xiaoyanit/cgeo,lewurm/cgeo,KublaikhanGeek/cgeo,marco-dev/c-geo-opensource,matej116/cgeo,SammysHP/cgeo,yummy222/cgeo,Bananeweizen/cgeo,brok85/cgeo,brok85/cgeo,samueltardieu/cgeo,mucek4/cgeo,madankb/cgeo,Bananeweizen/cgeo,auricgoldfinger/cgeo,Huertix/cgeo,SammysHP/cgeo,rsudev/c-geo-opensource,schwabe/cgeo,cgeo/cgeo,samueltardieu/cgeo,pstorch/cgeo,rsudev/c-geo-opensource,brok85/cgeo,mucek4/cgeo,madankb/cgeo,vishwakulkarni/cgeo,tobiasge/cgeo,xiaoyanit/cgeo,mucek4/cgeo,vishwakulkarni/cgeo,KublaikhanGeek/cgeo
package cgeo.geocaching.connector.gc; import java.util.regex.Pattern; /** * These patterns have been optimized for speed. Improve them only if you can prove * that *YOUR* pattern is faster. Use RegExRealPerformanceTest to show. * * For further information about patterns have a look at * http://download.oracle.com/javase/1.4.2/docs/api/java/util/regex/Pattern.html * * @author blafoo */ public final class GCConstants { /** Live Map */ public final static String URL_LIVE_MAP = "http://www.geocaching.com/map/default.aspx"; /** Live Map pop-up */ public final static String URL_LIVE_MAP_DETAILS = "http://www.geocaching.com/map/map.details"; /** Caches in a tile */ public final static String URL_MAP_INFO = "http://www.geocaching.com/map/map.info"; /** Tile itself */ public final static String URL_MAP_TILE = "http://www.geocaching.com/map/map.png"; /** * Patterns for parsing the result of a (detailed) search */ public final static Pattern PATTERN_HINT = Pattern.compile("<div id=\"div_hint\"[^>]*>(.*?)</div>"); public final static Pattern PATTERN_DESC = Pattern.compile("<span id=\"ctl00_ContentBody_LongDescription\">(.*?)</span>\\s*</div>\\s*<p>\\s*</p>\\s*<p id=\"ctl00_ContentBody_hints\">"); public final static Pattern PATTERN_SHORTDESC = Pattern.compile("<span id=\"ctl00_ContentBody_ShortDescription\">(.*?)</span>\\s*</div>"); public final static Pattern PATTERN_GEOCODE = Pattern.compile("class=\"CoordInfoCode\">(GC[0-9A-Z]+)</span>"); public final static Pattern PATTERN_CACHEID = Pattern.compile("/seek/log\\.aspx\\?ID=(\\d+)"); public final static Pattern PATTERN_GUID = Pattern.compile(Pattern.quote("&wid=") + "([0-9a-z\\-]+)" + Pattern.quote("&")); public final static Pattern PATTERN_SIZE = Pattern.compile("<div class=\"CacheSize[^\"]*\">[^<]*<p[^>]*>[^S]*Size[^:]*:[^<]*<span[^>]*>[^<]*<img src=\"[^\"]*/icons/container/[a-z_]+\\.gif\" alt=\"\\w+: ([^\"]+)\"[^>]*>[^<]*<small>[^<]*</small>[^<]*</span>[^<]*</p>"); public final static Pattern PATTERN_LATLON = Pattern.compile("<span id=\"uxLatLon\" style=\"font-weight:bold;\"[^>]*>(.*?)</span>"); public final static Pattern PATTERN_LATLON_ORIG = Pattern.compile("\\{\"isUserDefined\":true[^}]+?\"oldLatLngDisplay\":\"([^\"]+)\"\\}"); public final static Pattern PATTERN_LOCATION = Pattern.compile(Pattern.quote("<span id=\"ctl00_ContentBody_Location\">In ") + "(?:<a href=[^>]*>)?(.*?)<"); public final static Pattern PATTERN_PERSONALNOTE = Pattern.compile("<p id=\"cache_note\"[^>]*>(.*?)</p>"); public final static Pattern PATTERN_NAME = Pattern.compile("<span id=\"ctl00_ContentBody_CacheName\">(.*?)</span>"); public final static Pattern PATTERN_DIFFICULTY = Pattern.compile("<span id=\"ctl00_ContentBody_uxLegendScale\"[^>]*>[^<]*<img src=\"[^\"]*/images/stars/stars([0-9_]+)\\.gif\""); public final static Pattern PATTERN_TERRAIN = Pattern.compile("<span id=\"ctl00_ContentBody_Localize[\\d]+\"[^>]*>[^<]*<img src=\"[^\"]*/images/stars/stars([0-9_]+)\\.gif\""); public final static Pattern PATTERN_OWNERREAL = Pattern.compile("<a id=\"ctl00_ContentBody_uxFindLinksHiddenByThisUser\" href=\"[^\"]*/seek/nearest\\.aspx\\?u=(.*?)\""); public final static Pattern PATTERN_FOUND = Pattern.compile("<a id=\"ctl00_ContentBody_hlFoundItLog\"[^<]*<img src=\".*/images/stockholm/16x16/check\\.gif\"[^>]*>[^<]*</a>[^<]*</p>"); public final static Pattern PATTERN_FOUND_ALTERNATIVE = Pattern.compile("<div class=\"StatusInformationWidget FavoriteWidget\""); public final static Pattern PATTERN_OWNER = Pattern.compile("<span class=\"minorCacheDetails\">[^<]+<a href=\"[^\"]+\">([^<]+)</a></span>"); public final static Pattern PATTERN_TYPE = Pattern.compile("<img src=\"[^\"]*/WptTypes/\\d+\\.gif\" alt=\"([^\"]+?)\" title=\"[^\"]+\" width=\"32\" height=\"32\""); public final static Pattern PATTERN_HIDDEN = Pattern.compile("<span class=\"minorCacheDetails\">\\W*Hidden[\\s:]*([^<]+?)</span>"); public final static Pattern PATTERN_HIDDENEVENT = Pattern.compile("Event\\s*Date\\s*:\\s*([^<]+)</span>", Pattern.DOTALL); public final static Pattern PATTERN_FAVORITE = Pattern.compile("<img src=\"/images/icons/icon_favDelete.png\" alt=\"Remove from your Favorites\" title=\"Remove from your Favorites\" />"); public final static Pattern PATTERN_FAVORITECOUNT = Pattern.compile("<a id=\"uxFavContainerLink\"[^>]+>[^<]*<div[^<]*<span class=\"favorite-value\">\\D*([0-9]+?)</span>"); public final static Pattern PATTERN_COUNTLOGS = Pattern.compile("<span id=\"ctl00_ContentBody_lblFindCounts\"><p(.+?)</p></span>"); public final static Pattern PATTERN_LOGBOOK = Pattern.compile("initalLogs = (\\{.+\\});"); /** Two groups ! */ public final static Pattern PATTERN_COUNTLOG = Pattern.compile("<img src=\"/images/icons/([a-z_]+)\\.gif\"[^>]+> (\\d*[,.]?\\d+)"); public static final Pattern PATTERN_PREMIUMMEMBERS = Pattern.compile("<p class=\"Warning NoBottomSpacing\">This is a Premium Member Only cache.</p>"); public final static Pattern PATTERN_ATTRIBUTES = Pattern.compile("<h3 class=\"WidgetHeader\">[^<]*<img[^>]+>\\W*Attributes[^<]*</h3>[^<]*<div class=\"WidgetBody\">((?:[^<]*<img src=\"[^\"]+\" alt=\"[^\"]+\"[^>]*>)+?)[^<]*<p"); /** Two groups ! */ public final static Pattern PATTERN_ATTRIBUTESINSIDE = Pattern.compile("[^<]*<img src=\"([^\"]+)\" alt=\"([^\"]+?)\""); public final static Pattern PATTERN_SPOILERS = Pattern.compile("<p class=\"NoPrint\">\\s+((?:<a href=\"http://img\\.geocaching\\.com/cache/[^.]+\\.jpg\"[^>]+><img class=\"StatusIcon\"[^>]+><span>[^<]+</span></a><br />(?:[^<]+<br /><br />)?)+)\\s+</p>"); public final static Pattern PATTERN_SPOILERSINSIDE = Pattern.compile("<a href=\"(http://img\\.geocaching\\.com/cache/[^.]+\\.jpg)\"[^>]+><img class=\"StatusIcon\"[^>]+><span>([^<]+)</span></a><br />(?:([^<]+)<br /><br />)?"); public final static Pattern PATTERN_INVENTORY = Pattern.compile("<span id=\"ctl00_ContentBody_uxTravelBugList_uxInventoryLabel\">\\W*Inventory[^<]*</span>[^<]*</h3>[^<]*<div class=\"WidgetBody\">([^<]*<ul>(([^<]*<li>[^<]*<a href=\"[^\"]+\"[^>]*>[^<]*<img src=\"[^\"]+\"[^>]*>[^<]*<span>[^<]+<\\/span>[^<]*<\\/a>[^<]*<\\/li>)+)[^<]*<\\/ul>)?"); public final static Pattern PATTERN_INVENTORYINSIDE = Pattern.compile("[^<]*<li>[^<]*<a href=\"[a-z0-9\\-\\_\\.\\?\\/\\:\\@]*\\/track\\/details\\.aspx\\?guid=([0-9a-z\\-]+)[^\"]*\"[^>]*>[^<]*<img src=\"[^\"]+\"[^>]*>[^<]*<span>([^<]+)<\\/span>[^<]*<\\/a>[^<]*<\\/li>"); public final static Pattern PATTERN_WATCHLIST = Pattern.compile("icon_stop_watchlist.gif"); // Info box top-right public static final Pattern PATTERN_LOGIN_NAME = Pattern.compile("\"SignedInProfileLink\">([^<]+)</a>"); public static final Pattern PATTERN_MEMBER_STATUS = Pattern.compile("<span id=\"ctl00_litPMLevel\">([^<]+)</span>"); /** Use replaceAll("[,.]","") on the resulting string before converting to an int */ public static final Pattern PATTERN_CACHES_FOUND = Pattern.compile("title=\"Caches Found\"[\\s\\w=\"/.]*/>\\s*([\\d,.]+)"); public static final Pattern PATTERN_AVATAR_IMAGE_PROFILE_PAGE = Pattern.compile("<img src=\"(http://img.geocaching.com/user/avatar/[0-9a-f-]+\\.jpg)\"[^>]*\\salt=\"Avatar\""); public static final Pattern PATTERN_LOGIN_NAME_LOGIN_PAGE = Pattern.compile("<h4>Success:</h4> <p>You are logged in as[^<]*<strong><span id=\"ctl00_ContentBody_lbUsername\"[^>]*>([^<]+)[^<]*</span>"); public static final Pattern PATTERN_CUSTOMDATE = Pattern.compile("<option selected=\"selected\" value=\"([ /Mdy-]+)\">"); /** * Patterns for parsing trackables */ public final static Pattern PATTERN_TRACKABLE_GUID = Pattern.compile("<a id=\"ctl00_ContentBody_lnkPrint\" title=\"[^\"]*\" href=\".*sheet\\.aspx\\?guid=([a-z0-9\\-]+)\"[^>]*>[^<]*</a>"); public final static Pattern PATTERN_TRACKABLE_GEOCODE = Pattern.compile("<span id=\"ctl00_ContentBody_BugDetails_BugTBNum\" String=\"[^\"]*\">Use[^<]*<strong>(TB[0-9A-Z]+)[^<]*</strong> to reference this item.[^<]*</span>"); public final static Pattern PATTERN_TRACKABLE_NAME = Pattern.compile("<h2[^>]*>(?:[^<]*<img[^>]*>)?[^<]*<span id=\"ctl00_ContentBody_lbHeading\">([^<]+)</span>[^<]*</h2>"); /** Two groups ! */ public final static Pattern PATTERN_TRACKABLE_OWNER = Pattern.compile("<dt>\\W*Owner:[^<]*</dt>[^<]*<dd>[^<]*<a id=\"ctl00_ContentBody_BugDetails_BugOwner\" title=\"[^\"]*\" href=\"[^\"]*/profile/\\?guid=([a-z0-9\\-]+)\">([^<]+)<\\/a>[^<]*</dd>"); public final static Pattern PATTERN_TRACKABLE_RELEASES = Pattern.compile("<dt>\\W*Released:[^<]*</dt>[^<]*<dd>[^<]*<span id=\"ctl00_ContentBody_BugDetails_BugReleaseDate\">([^<]+)<\\/span>[^<]*</dd>"); public final static Pattern PATTERN_TRACKABLE_ORIGIN = Pattern.compile("<dt>\\W*Origin:[^<]*</dt>[^<]*<dd>[^<]*<span id=\"ctl00_ContentBody_BugDetails_BugOrigin\">([^<]+)<\\/span>[^<]*</dd>"); /** Two groups ! */ public final static Pattern PATTERN_TRACKABLE_SPOTTEDCACHE = Pattern.compile("<dt>\\W*Recently Spotted:[^<]*</dt>[^<]*<dd>[^<]*<a id=\"ctl00_ContentBody_BugDetails_BugLocation\" title=\"[^\"]*\" href=\"[^\"]*/seek/cache_details.aspx\\?guid=([a-z0-9\\-]+)\">In ([^<]+)</a>[^<]*</dd>"); /** Two groups ! */ public final static Pattern PATTERN_TRACKABLE_SPOTTEDUSER = Pattern.compile("<dt>\\W*Recently Spotted:[^<]*</dt>[^<]*<dd>[^<]*<a id=\"ctl00_ContentBody_BugDetails_BugLocation\" href=\"[^\"]*/profile/\\?guid=([a-z0-9\\-]+)\">In the hands of ([^<]+).</a>[^<]*</dd>"); public final static Pattern PATTERN_TRACKABLE_SPOTTEDUNKNOWN = Pattern.compile("<dt>\\W*Recently Spotted:[^<]*</dt>[^<]*<dd>[^<]*<a id=\"ctl00_ContentBody_BugDetails_BugLocation\">Unknown Location[^<]*</a>[^<]*</dd>"); public final static Pattern PATTERN_TRACKABLE_SPOTTEDOWNER = Pattern.compile("<dt>\\W*Recently Spotted:[^<]*</dt>[^<]*<dd>[^<]*<a id=\"ctl00_ContentBody_BugDetails_BugLocation\">In the hands of the owner[^<]*</a>[^<]*</dd>"); public final static Pattern PATTERN_TRACKABLE_GOAL = Pattern.compile("<div id=\"TrackableGoal\">[^<]*<p>(.*?)</p>[^<]*</div>", Pattern.DOTALL); /** Four groups */ public final static Pattern PATTERN_TRACKABLE_DETAILSIMAGE = Pattern.compile("<h3>\\W*About This Item[^<]*</h3>[^<]*<div id=\"TrackableDetails\">([^<]*<p>([^<]*<img id=\"ctl00_ContentBody_BugDetails_BugImage\" class=\"[^\"]+\" src=\"([^\"]+)\"[^>]*>)?[^<]*</p>)?[^<]*<p[^>]*>(.*)</p>[^<]*</div> <div id=\"ctl00_ContentBody_BugDetails_uxAbuseReport\">"); public final static Pattern PATTERN_TRACKABLE_ICON = Pattern.compile("<img id=\"ctl00_ContentBody_BugTypeImage\" class=\"TravelBugHeaderIcon\" src=\"([^\"]+)\"[^>]*>"); public final static Pattern PATTERN_TRACKABLE_TYPE = Pattern.compile("<img id=\"ctl00_ContentBody_BugTypeImage\" class=\"TravelBugHeaderIcon\" src=\"[^\"]+\" alt=\"([^\"]+)\"[^>]*>"); public final static Pattern PATTERN_TRACKABLE_DISTANCE = Pattern.compile("<h4[^>]*\\W*Tracking History \\(([0-9.,]+(km|mi))[^\\)]*\\)"); public final static Pattern PATTERN_TRACKABLE_LOG = Pattern.compile("<tr class=\"Data.+?src=\"/images/icons/([^.]+)\\.gif[^>]+>&nbsp;([^<]+)</td>.+?guid.+?>([^<]+)</a>.+?(?:guid=([^\"]+)\">(<span class=\"Strike\">)?([^<]+)</.+?)?<td colspan=\"4\">(.+?)(?:<ul.+?ul>)?\\s*</td>\\s*</tr>"); public final static Pattern PATTERN_TRACKABLE_LOG_IMAGES = Pattern.compile(".+?<li><a href=\"([^\"]+)\".+?LogImgTitle.+?>([^<]+)</"); /** * Patterns for parsing the result of a search (next) */ public final static Pattern PATTERN_SEARCH_TYPE = Pattern.compile("<td class=\"Merge\">[^<]*<a href=\"[^\"]*/seek/cache_details\\.aspx\\?guid=[^\"]+\"[^>]+>[^<]*<img src=\"[^\"]*/images/wpttypes/[^.]+\\.gif\" alt=\"([^\"]+)\" title=\"[^\"]+\"[^>]*>[^<]*</a>"); public final static Pattern PATTERN_SEARCH_GUIDANDDISABLED = Pattern.compile("<img src=\"[^\"]*/images/wpttypes/[^>]*>[^<]*</a></td><td class=\"Merge\">[^<]*<a href=\"[^\"]*/seek/cache_details\\.aspx\\?guid=([a-z0-9\\-]+)\" class=\"lnk([^\"]*)\">([^<]*<span>)?([^<]*)(</span>[^<]*)?</a>[^<]+<br />([^<]*)<span[^>]+>([^<]*)</span>([^<]*<img[^>]+>)?[^<]*<br />[^<]*</td>"); /** Two groups **/ public final static Pattern PATTERN_SEARCH_TRACKABLES = Pattern.compile("<a id=\"ctl00_ContentBody_dlResults_ctl[0-9]+_uxTravelBugList\" class=\"tblist\" data-tbcount=\"([0-9]+)\" data-id=\"[^\"]*\"[^>]*>(.*)</a>"); /** Second group used */ public final static Pattern PATTERN_SEARCH_TRACKABLESINSIDE = Pattern.compile("(<img src=\"[^\"]+\" alt=\"([^\"]+)\" title=\"[^\"]*\" />[^<]*)"); public final static Pattern PATTERN_SEARCH_DIRECTION = Pattern.compile("<img id=\"ctl00_ContentBody_dlResults_ctl[0-9]+_uxDistanceAndHeading\" title=\"[^\"]*\" src=\"[^\"]*/seek/CacheDir\\.ashx\\?k=([^\"]+)\"[^>]*>"); public final static Pattern PATTERN_SEARCH_GEOCODE = Pattern.compile("\\|\\W*(GC[0-9A-Z]+)[^\\|]*\\|"); public final static Pattern PATTERN_SEARCH_ID = Pattern.compile("name=\"CID\"[^v]*value=\"([0-9]+)\""); public final static Pattern PATTERN_SEARCH_FAVORITE = Pattern.compile("<span id=\"ctl00_ContentBody_dlResults_ctl[0-9]+_uxFavoritesValue\" title=\"[^\"]*\" class=\"favorite-rank\">([0-9]+)</span>"); public final static Pattern PATTERN_SEARCH_TOTALCOUNT = Pattern.compile("<td class=\"PageBuilderWidget\"><span>Total Records[^<]*<b>(\\d+)<\\/b>"); public final static Pattern PATTERN_SEARCH_RECAPTCHA = Pattern.compile("<script[^>]*src=\"[^\"]*/recaptcha/api/challenge\\?k=([^\"]+)\"[^>]*>"); public final static Pattern PATTERN_SEARCH_RECAPTCHACHALLENGE = Pattern.compile("challenge : '([^']+)'"); /** * Patterns for waypoints */ public final static Pattern PATTERN_WPTYPE = Pattern.compile("\\/wpttypes\\/sm\\/(.+)\\.jpg"); public final static Pattern PATTERN_WPPREFIXORLOOKUPORLATLON = Pattern.compile(">([^<]*<[^>]+>)?([^<]+)(<[^>]+>[^<]*)?<\\/td>"); public final static Pattern PATTERN_WPNAME = Pattern.compile(">[^<]*<a[^>]+>([^<]*)<\\/a>"); public final static Pattern PATTERN_WPNOTE = Pattern.compile("colspan=\"6\">(.*)<\\/td>"); /** * Patterns for different purposes */ /** replace linebreak and paragraph tags */ public final static Pattern PATTERN_LINEBREAK = Pattern.compile("<(br|p)[^>]*>"); public final static Pattern PATTERN_TYPEBOX = Pattern.compile("<select name=\"ctl00\\$ContentBody\\$LogBookPanel1\\$ddLogType\" id=\"ctl00_ContentBody_LogBookPanel1_ddLogType\"[^>]*>" + "(([^<]*<option[^>]*>[^<]+</option>)+)[^<]*</select>", Pattern.CASE_INSENSITIVE); public final static Pattern PATTERN_TYPE2 = Pattern.compile("<option( selected=\"selected\")? value=\"(\\d+)\">[^<]+</option>", Pattern.CASE_INSENSITIVE); // FIXME: pattern is over specified public final static Pattern PATTERN_TRACKABLE = Pattern.compile("<tr id=\"ctl00_ContentBody_LogBookPanel1_uxTrackables_repTravelBugs_ctl[0-9]+_row\"[^>]*>" + "[^<]*<td>[^<]*<a href=\"[^\"]+\">([A-Z0-9]+)</a>[^<]*</td>[^<]*<td>([^<]+)</td>[^<]*<td>" + "[^<]*<select name=\"ctl00\\$ContentBody\\$LogBookPanel1\\$uxTrackables\\$repTravelBugs\\$ctl([0-9]+)\\$ddlAction\"[^>]*>" + "([^<]*<option value=\"([0-9]+)(_[a-z]+)?\">[^<]+</option>)+" + "[^<]*</select>[^<]*</td>[^<]*</tr>", Pattern.CASE_INSENSITIVE); public final static Pattern PATTERN_MAINTENANCE = Pattern.compile("<span id=\"ctl00_ContentBody_LogBookPanel1_lbConfirm\"[^>]*>([^<]*<font[^>]*>)?([^<]+)(</font>[^<]*)?</span>", Pattern.CASE_INSENSITIVE); public final static Pattern PATTERN_OK1 = Pattern.compile("<h2[^>]*>[^<]*<span id=\"ctl00_ContentBody_lbHeading\"[^>]*>[^<]*</span>[^<]*</h2>", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE); public final static Pattern PATTERN_OK2 = Pattern.compile("<div id=[\"|']ctl00_ContentBody_LogBookPanel1_ViewLogPanel[\"|']>", Pattern.CASE_INSENSITIVE); public final static Pattern PATTERN_VIEWSTATEFIELDCOUNT = Pattern.compile("id=\"__VIEWSTATEFIELDCOUNT\"[^(value)]+value=\"(\\d+)\"[^>]+>", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE); public final static Pattern PATTERN_VIEWSTATES = Pattern.compile("id=\"__VIEWSTATE(\\d*)\"[^(value)]+value=\"([^\"]+)\"[^>]+>", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE); public final static Pattern PATTERN_USERTOKEN2 = Pattern.compile("userToken\\s*=\\s*'([^']+)'"); /** * Patterns for GC and TB codes */ public final static Pattern PATTERN_GC_CODE = Pattern.compile("GC[0-9A-Z]+", Pattern.CASE_INSENSITIVE); public final static Pattern PATTERN_TB_CODE = Pattern.compile("TB[0-9A-Z]+", Pattern.CASE_INSENSITIVE); /** Live Map since 14.02.2012 */ public final static Pattern PATTERN_USERSESSION = Pattern.compile("UserSession\\('([^']+)'"); public final static Pattern PATTERN_SESSIONTOKEN = Pattern.compile("sessionToken:'([^']+)'"); public final static String STRING_PREMIUMONLY_2 = "Sorry, the owner of this listing has made it viewable to Premium Members only."; public final static String STRING_PREMIUMONLY_1 = "has chosen to make this cache listing visible to Premium Members only."; public final static String STRING_UNPUBLISHED_OWNER = "Cache is Unpublished"; public final static String STRING_UNPUBLISHED_OTHER = "you cannot view this cache listing until it has been published"; public final static String STRING_UNKNOWN_ERROR = "An Error Has Occurred"; public final static String STRING_CACHEINFORMATIONTABLE = "<div id=\"ctl00_ContentBody_CacheInformationTable\" class=\"CacheInformationTable\">"; public final static String STRING_DISABLED = "<li>This cache is temporarily unavailable."; public final static String STRING_ARCHIVED = "<li>This cache has been archived,"; public final static String STRING_CACHEDETAILS = "id=\"cacheDetails\""; /** Number of logs to retrieve from GC.com */ public final static int NUMBER_OF_LOGS = 35; private GCConstants() { // this class shall not have instances } }
main/src/cgeo/geocaching/connector/gc/GCConstants.java
package cgeo.geocaching.connector.gc; import java.util.regex.Pattern; /** * These patterns have been optimized for speed. Improve them only if you can prove * that *YOUR* pattern is faster. Use RegExRealPerformanceTest to show. * * For further information about patterns have a look at * http://download.oracle.com/javase/1.4.2/docs/api/java/util/regex/Pattern.html * * @author blafoo */ public final class GCConstants { /** Live Map */ public final static String URL_LIVE_MAP = "http://www.geocaching.com/map/default.aspx"; /** Live Map pop-up */ public final static String URL_LIVE_MAP_DETAILS = "http://www.geocaching.com/map/map.details"; /** Caches in a tile */ public final static String URL_MAP_INFO = "http://www.geocaching.com/map/map.info"; /** Tile itself */ public final static String URL_MAP_TILE = "http://www.geocaching.com/map/map.png"; /** * Patterns for parsing the result of a (detailed) search */ public final static Pattern PATTERN_HINT = Pattern.compile("<div id=\"div_hint\"[^>]*>(.*?)</div>"); public final static Pattern PATTERN_DESC = Pattern.compile("<span id=\"ctl00_ContentBody_LongDescription\"><div class=\"UserSuppliedContent\">(.*?)</div>\\s*<p>\\s*</p>\\s*<p id=\"ctl00_ContentBody_hints\">"); public final static Pattern PATTERN_SHORTDESC = Pattern.compile("<span id=\"ctl00_ContentBody_ShortDescription\">(.*?)</span>\\s*</div>"); public final static Pattern PATTERN_GEOCODE = Pattern.compile("class=\"CoordInfoCode\">(GC[0-9A-Z]+)</span>"); public final static Pattern PATTERN_CACHEID = Pattern.compile("/seek/log\\.aspx\\?ID=(\\d+)"); public final static Pattern PATTERN_GUID = Pattern.compile(Pattern.quote("&wid=") + "([0-9a-z\\-]+)" + Pattern.quote("&")); public final static Pattern PATTERN_SIZE = Pattern.compile("<div class=\"CacheSize[^\"]*\">[^<]*<p[^>]*>[^S]*Size[^:]*:[^<]*<span[^>]*>[^<]*<img src=\"[^\"]*/icons/container/[a-z_]+\\.gif\" alt=\"\\w+: ([^\"]+)\"[^>]*>[^<]*<small>[^<]*</small>[^<]*</span>[^<]*</p>"); public final static Pattern PATTERN_LATLON = Pattern.compile("<span id=\"uxLatLon\" style=\"font-weight:bold;\"[^>]*>(.*?)</span>"); public final static Pattern PATTERN_LATLON_ORIG = Pattern.compile("\\{\"isUserDefined\":true[^}]+?\"oldLatLngDisplay\":\"([^\"]+)\"\\}"); public final static Pattern PATTERN_LOCATION = Pattern.compile(Pattern.quote("<span id=\"ctl00_ContentBody_Location\">In ") + "(?:<a href=[^>]*>)?(.*?)<"); public final static Pattern PATTERN_PERSONALNOTE = Pattern.compile("<p id=\"cache_note\"[^>]*>(.*?)</p>"); public final static Pattern PATTERN_NAME = Pattern.compile("<span id=\"ctl00_ContentBody_CacheName\">(.*?)</span>"); public final static Pattern PATTERN_DIFFICULTY = Pattern.compile("<span id=\"ctl00_ContentBody_uxLegendScale\"[^>]*>[^<]*<img src=\"[^\"]*/images/stars/stars([0-9_]+)\\.gif\""); public final static Pattern PATTERN_TERRAIN = Pattern.compile("<span id=\"ctl00_ContentBody_Localize[\\d]+\"[^>]*>[^<]*<img src=\"[^\"]*/images/stars/stars([0-9_]+)\\.gif\""); public final static Pattern PATTERN_OWNERREAL = Pattern.compile("<a id=\"ctl00_ContentBody_uxFindLinksHiddenByThisUser\" href=\"[^\"]*/seek/nearest\\.aspx\\?u=(.*?)\""); public final static Pattern PATTERN_FOUND = Pattern.compile("<a id=\"ctl00_ContentBody_hlFoundItLog\"[^<]*<img src=\".*/images/stockholm/16x16/check\\.gif\"[^>]*>[^<]*</a>[^<]*</p>"); public final static Pattern PATTERN_FOUND_ALTERNATIVE = Pattern.compile("<div class=\"StatusInformationWidget FavoriteWidget\""); public final static Pattern PATTERN_OWNER = Pattern.compile("<span class=\"minorCacheDetails\">[^<]+<a href=\"[^\"]+\">([^<]+)</a></span>"); public final static Pattern PATTERN_TYPE = Pattern.compile("<img src=\"[^\"]*/WptTypes/\\d+\\.gif\" alt=\"([^\"]+?)\" title=\"[^\"]+\" width=\"32\" height=\"32\""); public final static Pattern PATTERN_HIDDEN = Pattern.compile("<span class=\"minorCacheDetails\">\\W*Hidden[\\s:]*([^<]+?)</span>"); public final static Pattern PATTERN_HIDDENEVENT = Pattern.compile("Event\\s*Date\\s*:\\s*([^<]+)</span>", Pattern.DOTALL); public final static Pattern PATTERN_FAVORITE = Pattern.compile("<img src=\"/images/icons/icon_favDelete.png\" alt=\"Remove from your Favorites\" title=\"Remove from your Favorites\" />"); public final static Pattern PATTERN_FAVORITECOUNT = Pattern.compile("<a id=\"uxFavContainerLink\"[^>]+>[^<]*<div[^<]*<span class=\"favorite-value\">\\D*([0-9]+?)</span>"); public final static Pattern PATTERN_COUNTLOGS = Pattern.compile("<span id=\"ctl00_ContentBody_lblFindCounts\"><p(.+?)</p></span>"); public final static Pattern PATTERN_LOGBOOK = Pattern.compile("initalLogs = (\\{.+\\});"); /** Two groups ! */ public final static Pattern PATTERN_COUNTLOG = Pattern.compile("<img src=\"/images/icons/([a-z_]+)\\.gif\"[^>]+> (\\d*[,.]?\\d+)"); public static final Pattern PATTERN_PREMIUMMEMBERS = Pattern.compile("<p class=\"Warning NoBottomSpacing\">This is a Premium Member Only cache.</p>"); public final static Pattern PATTERN_ATTRIBUTES = Pattern.compile("<h3 class=\"WidgetHeader\">[^<]*<img[^>]+>\\W*Attributes[^<]*</h3>[^<]*<div class=\"WidgetBody\">((?:[^<]*<img src=\"[^\"]+\" alt=\"[^\"]+\"[^>]*>)+?)[^<]*<p"); /** Two groups ! */ public final static Pattern PATTERN_ATTRIBUTESINSIDE = Pattern.compile("[^<]*<img src=\"([^\"]+)\" alt=\"([^\"]+?)\""); public final static Pattern PATTERN_SPOILERS = Pattern.compile("<p class=\"NoPrint\">\\s+((?:<a href=\"http://img\\.geocaching\\.com/cache/[^.]+\\.jpg\"[^>]+><img class=\"StatusIcon\"[^>]+><span>[^<]+</span></a><br />(?:[^<]+<br /><br />)?)+)\\s+</p>"); public final static Pattern PATTERN_SPOILERSINSIDE = Pattern.compile("<a href=\"(http://img\\.geocaching\\.com/cache/[^.]+\\.jpg)\"[^>]+><img class=\"StatusIcon\"[^>]+><span>([^<]+)</span></a><br />(?:([^<]+)<br /><br />)?"); public final static Pattern PATTERN_INVENTORY = Pattern.compile("<span id=\"ctl00_ContentBody_uxTravelBugList_uxInventoryLabel\">\\W*Inventory[^<]*</span>[^<]*</h3>[^<]*<div class=\"WidgetBody\">([^<]*<ul>(([^<]*<li>[^<]*<a href=\"[^\"]+\"[^>]*>[^<]*<img src=\"[^\"]+\"[^>]*>[^<]*<span>[^<]+<\\/span>[^<]*<\\/a>[^<]*<\\/li>)+)[^<]*<\\/ul>)?"); public final static Pattern PATTERN_INVENTORYINSIDE = Pattern.compile("[^<]*<li>[^<]*<a href=\"[a-z0-9\\-\\_\\.\\?\\/\\:\\@]*\\/track\\/details\\.aspx\\?guid=([0-9a-z\\-]+)[^\"]*\"[^>]*>[^<]*<img src=\"[^\"]+\"[^>]*>[^<]*<span>([^<]+)<\\/span>[^<]*<\\/a>[^<]*<\\/li>"); public final static Pattern PATTERN_WATCHLIST = Pattern.compile("icon_stop_watchlist.gif"); // Info box top-right public static final Pattern PATTERN_LOGIN_NAME = Pattern.compile("\"SignedInProfileLink\">([^<]+)</a>"); public static final Pattern PATTERN_MEMBER_STATUS = Pattern.compile("<span id=\"ctl00_litPMLevel\">([^<]+)</span>"); /** Use replaceAll("[,.]","") on the resulting string before converting to an int */ public static final Pattern PATTERN_CACHES_FOUND = Pattern.compile("title=\"Caches Found\"[\\s\\w=\"/.]*/>\\s*([\\d,.]+)"); public static final Pattern PATTERN_AVATAR_IMAGE_PROFILE_PAGE = Pattern.compile("<img src=\"(http://img.geocaching.com/user/avatar/[0-9a-f-]+\\.jpg)\"[^>]*\\salt=\"Avatar\""); public static final Pattern PATTERN_LOGIN_NAME_LOGIN_PAGE = Pattern.compile("<h4>Success:</h4> <p>You are logged in as[^<]*<strong><span id=\"ctl00_ContentBody_lbUsername\"[^>]*>([^<]+)[^<]*</span>"); public static final Pattern PATTERN_CUSTOMDATE = Pattern.compile("<option selected=\"selected\" value=\"([ /Mdy-]+)\">"); /** * Patterns for parsing trackables */ public final static Pattern PATTERN_TRACKABLE_GUID = Pattern.compile("<a id=\"ctl00_ContentBody_lnkPrint\" title=\"[^\"]*\" href=\".*sheet\\.aspx\\?guid=([a-z0-9\\-]+)\"[^>]*>[^<]*</a>"); public final static Pattern PATTERN_TRACKABLE_GEOCODE = Pattern.compile("<span id=\"ctl00_ContentBody_BugDetails_BugTBNum\" String=\"[^\"]*\">Use[^<]*<strong>(TB[0-9A-Z]+)[^<]*</strong> to reference this item.[^<]*</span>"); public final static Pattern PATTERN_TRACKABLE_NAME = Pattern.compile("<h2[^>]*>(?:[^<]*<img[^>]*>)?[^<]*<span id=\"ctl00_ContentBody_lbHeading\">([^<]+)</span>[^<]*</h2>"); /** Two groups ! */ public final static Pattern PATTERN_TRACKABLE_OWNER = Pattern.compile("<dt>\\W*Owner:[^<]*</dt>[^<]*<dd>[^<]*<a id=\"ctl00_ContentBody_BugDetails_BugOwner\" title=\"[^\"]*\" href=\"[^\"]*/profile/\\?guid=([a-z0-9\\-]+)\">([^<]+)<\\/a>[^<]*</dd>"); public final static Pattern PATTERN_TRACKABLE_RELEASES = Pattern.compile("<dt>\\W*Released:[^<]*</dt>[^<]*<dd>[^<]*<span id=\"ctl00_ContentBody_BugDetails_BugReleaseDate\">([^<]+)<\\/span>[^<]*</dd>"); public final static Pattern PATTERN_TRACKABLE_ORIGIN = Pattern.compile("<dt>\\W*Origin:[^<]*</dt>[^<]*<dd>[^<]*<span id=\"ctl00_ContentBody_BugDetails_BugOrigin\">([^<]+)<\\/span>[^<]*</dd>"); /** Two groups ! */ public final static Pattern PATTERN_TRACKABLE_SPOTTEDCACHE = Pattern.compile("<dt>\\W*Recently Spotted:[^<]*</dt>[^<]*<dd>[^<]*<a id=\"ctl00_ContentBody_BugDetails_BugLocation\" title=\"[^\"]*\" href=\"[^\"]*/seek/cache_details.aspx\\?guid=([a-z0-9\\-]+)\">In ([^<]+)</a>[^<]*</dd>"); /** Two groups ! */ public final static Pattern PATTERN_TRACKABLE_SPOTTEDUSER = Pattern.compile("<dt>\\W*Recently Spotted:[^<]*</dt>[^<]*<dd>[^<]*<a id=\"ctl00_ContentBody_BugDetails_BugLocation\" href=\"[^\"]*/profile/\\?guid=([a-z0-9\\-]+)\">In the hands of ([^<]+).</a>[^<]*</dd>"); public final static Pattern PATTERN_TRACKABLE_SPOTTEDUNKNOWN = Pattern.compile("<dt>\\W*Recently Spotted:[^<]*</dt>[^<]*<dd>[^<]*<a id=\"ctl00_ContentBody_BugDetails_BugLocation\">Unknown Location[^<]*</a>[^<]*</dd>"); public final static Pattern PATTERN_TRACKABLE_SPOTTEDOWNER = Pattern.compile("<dt>\\W*Recently Spotted:[^<]*</dt>[^<]*<dd>[^<]*<a id=\"ctl00_ContentBody_BugDetails_BugLocation\">In the hands of the owner[^<]*</a>[^<]*</dd>"); public final static Pattern PATTERN_TRACKABLE_GOAL = Pattern.compile("<div id=\"TrackableGoal\">[^<]*<p>(.*?)</p>[^<]*</div>", Pattern.DOTALL); /** Four groups */ public final static Pattern PATTERN_TRACKABLE_DETAILSIMAGE = Pattern.compile("<h3>\\W*About This Item[^<]*</h3>[^<]*<div id=\"TrackableDetails\">([^<]*<p>([^<]*<img id=\"ctl00_ContentBody_BugDetails_BugImage\" class=\"[^\"]+\" src=\"([^\"]+)\"[^>]*>)?[^<]*</p>)?[^<]*<p[^>]*>(.*)</p>[^<]*</div> <div id=\"ctl00_ContentBody_BugDetails_uxAbuseReport\">"); public final static Pattern PATTERN_TRACKABLE_ICON = Pattern.compile("<img id=\"ctl00_ContentBody_BugTypeImage\" class=\"TravelBugHeaderIcon\" src=\"([^\"]+)\"[^>]*>"); public final static Pattern PATTERN_TRACKABLE_TYPE = Pattern.compile("<img id=\"ctl00_ContentBody_BugTypeImage\" class=\"TravelBugHeaderIcon\" src=\"[^\"]+\" alt=\"([^\"]+)\"[^>]*>"); public final static Pattern PATTERN_TRACKABLE_DISTANCE = Pattern.compile("<h4[^>]*\\W*Tracking History \\(([0-9.,]+(km|mi))[^\\)]*\\)"); public final static Pattern PATTERN_TRACKABLE_LOG = Pattern.compile("<tr class=\"Data.+?src=\"/images/icons/([^.]+)\\.gif[^>]+>&nbsp;([^<]+)</td>.+?guid.+?>([^<]+)</a>.+?(?:guid=([^\"]+)\">(<span class=\"Strike\">)?([^<]+)</.+?)?<td colspan=\"4\">(.+?)(?:<ul.+?ul>)?\\s*</td>\\s*</tr>"); public final static Pattern PATTERN_TRACKABLE_LOG_IMAGES = Pattern.compile(".+?<li><a href=\"([^\"]+)\".+?LogImgTitle.+?>([^<]+)</"); /** * Patterns for parsing the result of a search (next) */ public final static Pattern PATTERN_SEARCH_TYPE = Pattern.compile("<td class=\"Merge\">[^<]*<a href=\"[^\"]*/seek/cache_details\\.aspx\\?guid=[^\"]+\"[^>]+>[^<]*<img src=\"[^\"]*/images/wpttypes/[^.]+\\.gif\" alt=\"([^\"]+)\" title=\"[^\"]+\"[^>]*>[^<]*</a>"); public final static Pattern PATTERN_SEARCH_GUIDANDDISABLED = Pattern.compile("<img src=\"[^\"]*/images/wpttypes/[^>]*>[^<]*</a></td><td class=\"Merge\">[^<]*<a href=\"[^\"]*/seek/cache_details\\.aspx\\?guid=([a-z0-9\\-]+)\" class=\"lnk([^\"]*)\">([^<]*<span>)?([^<]*)(</span>[^<]*)?</a>[^<]+<br />([^<]*)<span[^>]+>([^<]*)</span>([^<]*<img[^>]+>)?[^<]*<br />[^<]*</td>"); /** Two groups **/ public final static Pattern PATTERN_SEARCH_TRACKABLES = Pattern.compile("<a id=\"ctl00_ContentBody_dlResults_ctl[0-9]+_uxTravelBugList\" class=\"tblist\" data-tbcount=\"([0-9]+)\" data-id=\"[^\"]*\"[^>]*>(.*)</a>"); /** Second group used */ public final static Pattern PATTERN_SEARCH_TRACKABLESINSIDE = Pattern.compile("(<img src=\"[^\"]+\" alt=\"([^\"]+)\" title=\"[^\"]*\" />[^<]*)"); public final static Pattern PATTERN_SEARCH_DIRECTION = Pattern.compile("<img id=\"ctl00_ContentBody_dlResults_ctl[0-9]+_uxDistanceAndHeading\" title=\"[^\"]*\" src=\"[^\"]*/seek/CacheDir\\.ashx\\?k=([^\"]+)\"[^>]*>"); public final static Pattern PATTERN_SEARCH_GEOCODE = Pattern.compile("\\|\\W*(GC[0-9A-Z]+)[^\\|]*\\|"); public final static Pattern PATTERN_SEARCH_ID = Pattern.compile("name=\"CID\"[^v]*value=\"([0-9]+)\""); public final static Pattern PATTERN_SEARCH_FAVORITE = Pattern.compile("<span id=\"ctl00_ContentBody_dlResults_ctl[0-9]+_uxFavoritesValue\" title=\"[^\"]*\" class=\"favorite-rank\">([0-9]+)</span>"); public final static Pattern PATTERN_SEARCH_TOTALCOUNT = Pattern.compile("<td class=\"PageBuilderWidget\"><span>Total Records[^<]*<b>(\\d+)<\\/b>"); public final static Pattern PATTERN_SEARCH_RECAPTCHA = Pattern.compile("<script[^>]*src=\"[^\"]*/recaptcha/api/challenge\\?k=([^\"]+)\"[^>]*>"); public final static Pattern PATTERN_SEARCH_RECAPTCHACHALLENGE = Pattern.compile("challenge : '([^']+)'"); /** * Patterns for waypoints */ public final static Pattern PATTERN_WPTYPE = Pattern.compile("\\/wpttypes\\/sm\\/(.+)\\.jpg"); public final static Pattern PATTERN_WPPREFIXORLOOKUPORLATLON = Pattern.compile(">([^<]*<[^>]+>)?([^<]+)(<[^>]+>[^<]*)?<\\/td>"); public final static Pattern PATTERN_WPNAME = Pattern.compile(">[^<]*<a[^>]+>([^<]*)<\\/a>"); public final static Pattern PATTERN_WPNOTE = Pattern.compile("colspan=\"6\">(.*)<\\/td>"); /** * Patterns for different purposes */ /** replace linebreak and paragraph tags */ public final static Pattern PATTERN_LINEBREAK = Pattern.compile("<(br|p)[^>]*>"); public final static Pattern PATTERN_TYPEBOX = Pattern.compile("<select name=\"ctl00\\$ContentBody\\$LogBookPanel1\\$ddLogType\" id=\"ctl00_ContentBody_LogBookPanel1_ddLogType\"[^>]*>" + "(([^<]*<option[^>]*>[^<]+</option>)+)[^<]*</select>", Pattern.CASE_INSENSITIVE); public final static Pattern PATTERN_TYPE2 = Pattern.compile("<option( selected=\"selected\")? value=\"(\\d+)\">[^<]+</option>", Pattern.CASE_INSENSITIVE); // FIXME: pattern is over specified public final static Pattern PATTERN_TRACKABLE = Pattern.compile("<tr id=\"ctl00_ContentBody_LogBookPanel1_uxTrackables_repTravelBugs_ctl[0-9]+_row\"[^>]*>" + "[^<]*<td>[^<]*<a href=\"[^\"]+\">([A-Z0-9]+)</a>[^<]*</td>[^<]*<td>([^<]+)</td>[^<]*<td>" + "[^<]*<select name=\"ctl00\\$ContentBody\\$LogBookPanel1\\$uxTrackables\\$repTravelBugs\\$ctl([0-9]+)\\$ddlAction\"[^>]*>" + "([^<]*<option value=\"([0-9]+)(_[a-z]+)?\">[^<]+</option>)+" + "[^<]*</select>[^<]*</td>[^<]*</tr>", Pattern.CASE_INSENSITIVE); public final static Pattern PATTERN_MAINTENANCE = Pattern.compile("<span id=\"ctl00_ContentBody_LogBookPanel1_lbConfirm\"[^>]*>([^<]*<font[^>]*>)?([^<]+)(</font>[^<]*)?</span>", Pattern.CASE_INSENSITIVE); public final static Pattern PATTERN_OK1 = Pattern.compile("<h2[^>]*>[^<]*<span id=\"ctl00_ContentBody_lbHeading\"[^>]*>[^<]*</span>[^<]*</h2>", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE); public final static Pattern PATTERN_OK2 = Pattern.compile("<div id=[\"|']ctl00_ContentBody_LogBookPanel1_ViewLogPanel[\"|']>", Pattern.CASE_INSENSITIVE); public final static Pattern PATTERN_VIEWSTATEFIELDCOUNT = Pattern.compile("id=\"__VIEWSTATEFIELDCOUNT\"[^(value)]+value=\"(\\d+)\"[^>]+>", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE); public final static Pattern PATTERN_VIEWSTATES = Pattern.compile("id=\"__VIEWSTATE(\\d*)\"[^(value)]+value=\"([^\"]+)\"[^>]+>", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE); public final static Pattern PATTERN_USERTOKEN2 = Pattern.compile("userToken\\s*=\\s*'([^']+)'"); /** * Patterns for GC and TB codes */ public final static Pattern PATTERN_GC_CODE = Pattern.compile("GC[0-9A-Z]+", Pattern.CASE_INSENSITIVE); public final static Pattern PATTERN_TB_CODE = Pattern.compile("TB[0-9A-Z]+", Pattern.CASE_INSENSITIVE); /** Live Map since 14.02.2012 */ public final static Pattern PATTERN_USERSESSION = Pattern.compile("UserSession\\('([^']+)'"); public final static Pattern PATTERN_SESSIONTOKEN = Pattern.compile("sessionToken:'([^']+)'"); public final static String STRING_PREMIUMONLY_2 = "Sorry, the owner of this listing has made it viewable to Premium Members only."; public final static String STRING_PREMIUMONLY_1 = "has chosen to make this cache listing visible to Premium Members only."; public final static String STRING_UNPUBLISHED_OWNER = "Cache is Unpublished"; public final static String STRING_UNPUBLISHED_OTHER = "you cannot view this cache listing until it has been published"; public final static String STRING_UNKNOWN_ERROR = "An Error Has Occurred"; public final static String STRING_CACHEINFORMATIONTABLE = "<div id=\"ctl00_ContentBody_CacheInformationTable\" class=\"CacheInformationTable\">"; public final static String STRING_DISABLED = "<li>This cache is temporarily unavailable."; public final static String STRING_ARCHIVED = "<li>This cache has been archived,"; public final static String STRING_CACHEDETAILS = "id=\"cacheDetails\""; /** Number of logs to retrieve from GC.com */ public final static int NUMBER_OF_LOGS = 35; private GCConstants() { // this class shall not have instances } }
Fix: Long description parsing
main/src/cgeo/geocaching/connector/gc/GCConstants.java
Fix: Long description parsing
Java
apache-2.0
d1644eebc3f5b85247a205836df5b41fc6dd88fc
0
edoliberty/sketches-core,pjain1/sketches-core,DataSketches/sketches-core
package com.yahoo.sketches.hll; import com.yahoo.sketches.Util; import com.yahoo.sketches.hash.MurmurHash3; @SuppressWarnings("cast") public class HllSketch { // derived using some formulas in Ting's paper (link?) private static final double HLL_REL_ERROR_NUMER = 1.04; public static HllSketchBuilder builder() { return new HllSketchBuilder(); } private Fields.UpdateCallback updateCallback; private final Preamble preamble; private Fields fields; public HllSketch(Fields fields) { this.fields = fields; this.updateCallback = new NoopUpdateCallback(); this.preamble = fields.getPreamble(); } public void update(byte[] key) { updateWithHash(MurmurHash3.hash(key, Util.DEFAULT_UPDATE_SEED)); } public void update(int[] key) { updateWithHash(MurmurHash3.hash(key, Util.DEFAULT_UPDATE_SEED)); } public void update(long[] key) { updateWithHash(MurmurHash3.hash(key, Util.DEFAULT_UPDATE_SEED)); } public double getEstimate() { double rawEst = getRawEstimate(); int logK = preamble.getLogConfigK(); double[] x_arr = Interpolation.interpolation_x_arrs[logK - Interpolation.INTERPOLATION_MIN_LOG_K]; double[] y_arr = Interpolation.interpolation_y_arrs[logK - Interpolation.INTERPOLATION_MIN_LOG_K]; if (rawEst < x_arr[0]) { return 0; } if (rawEst > x_arr[x_arr.length - 1]) { return rawEst; } double adjEst = Interpolation.cubicInterpolateUsingTable(x_arr, y_arr, rawEst); int configK = preamble.getConfigK(); if (adjEst > 3.0 * configK) { return adjEst; } double linEst = getLinearEstimate(); double avgEst = (adjEst + linEst) / 2.0; /* the following constant 0.64 comes from empirical measurements (see below) of the crossover point between the average error of the linear estimator and the adjusted hll estimator */ if (avgEst > 0.64 * configK) { return adjEst; } return linEst; } public double getUpperBound(double numStdDevs) { return getEstimate() / (1.0 - eps(numStdDevs)); } public double getLowerBound(double numStdDevs) { double lowerBound = getEstimate() / (1.0 + eps(numStdDevs)); double numNonZeros = (double) preamble.getConfigK(); numNonZeros -= numBucketsAtZero(); if (lowerBound < numNonZeros) { return numNonZeros; } return lowerBound; } private double getRawEstimate() { int numBuckets = preamble.getConfigK(); double correctionFactor = 0.7213 / (1.0 + 1.079 / (double) numBuckets); correctionFactor *= numBuckets * numBuckets; correctionFactor /= inversePowerOf2Sum(); return correctionFactor; } private double getLinearEstimate() { int configK = preamble.getConfigK(); long longV = numBucketsAtZero(); if (longV == 0) { return configK * Math.log(configK / 0.5); } return (configK * (HarmonicNumbers.harmonicNumber(configK) - HarmonicNumbers.harmonicNumber(longV))); } public HllSketch union(HllSketch that) { BucketIterator iter = that.fields.getBucketIterator(); while (iter.next()) { fields = fields.updateBucket(iter.getKey(), iter.getValue(), updateCallback); } return this; } private void updateWithHash(long[] hash) { byte newValue = (byte) (Long.numberOfLeadingZeros(hash[1]) + 1); int slotno = (int) hash[0] & (preamble.getConfigK() - 1); fields = fields.updateBucket(slotno, newValue, updateCallback); } private double eps(double numStdDevs) { return numStdDevs * HLL_REL_ERROR_NUMER / Math.sqrt(preamble.getConfigK()); } public byte[] toByteArray() { int numBytes = (preamble.getPreambleSize() << 3) + fields.numBytesToSerialize(); byte[] retVal = new byte[numBytes]; fields.intoByteArray(retVal, preamble.intoByteArray(retVal, 0)); return retVal; } public byte[] toByteArrayNoPreamble() { byte[] retVal = new byte[fields.numBytesToSerialize()]; fields.intoByteArray(retVal, 0); return retVal; } public HllSketch asCompact() { return new HllSketch(fields.toCompact()); } public int numBuckets() { return preamble.getConfigK(); } /** * Get the update Callback. This is protected because it is intended that only children might *call* * the method. It is not expected that this would be overridden by a child class. If someone overrides * it and weird things happen, the bug lies in the fact that it was overridden. * * @return The updateCallback registered with the HllSketch */ protected Fields.UpdateCallback getUpdateCallback() { return updateCallback; } /** * Set the update callback. This is protected because it is intended that only children might *call* * the method. It is not expected that this would be overridden by a child class. If someone overrides * it and weird things happen, the bug lies in the fact that it was overridden. * * @param updateCallback the update callback for the HllSketch to use when talking with its Fields */ protected void setUpdateCallback(Fields.UpdateCallback updateCallback) { this.updateCallback = updateCallback; } //Helper methods that are potential extension points for children /** * The sum of the inverse powers of 2 * @return the sum of the inverse powers of 2 */ protected double inversePowerOf2Sum() { return HllUtils.computeInvPow2Sum(numBuckets(), fields.getBucketIterator()); } protected int numBucketsAtZero() { int retVal = 0; int count = 0; BucketIterator bucketIter = fields.getBucketIterator(); while (bucketIter.next()) { if (bucketIter.getValue() == 0) { ++retVal; } ++count; } // All skipped buckets are 0. retVal += fields.getPreamble().getConfigK() - count; return retVal; } }
src/main/java/com/yahoo/sketches/hll/HllSketch.java
package com.yahoo.sketches.hll; import com.yahoo.sketches.Util; import com.yahoo.sketches.hash.MurmurHash3; @SuppressWarnings("cast") public class HllSketch { // derived using some formulas in Ting's paper (link?) private static final double HIP_REL_ERROR_NUMER = 0.836083874576235; public static HllSketchBuilder builder() { return new HllSketchBuilder(); } private Fields.UpdateCallback updateCallback; private final Preamble preamble; private Fields fields; public HllSketch(Fields fields) { this.fields = fields; this.updateCallback = new NoopUpdateCallback(); this.preamble = fields.getPreamble(); } public void update(byte[] key) { updateWithHash(MurmurHash3.hash(key, Util.DEFAULT_UPDATE_SEED)); } public void update(int[] key) { updateWithHash(MurmurHash3.hash(key, Util.DEFAULT_UPDATE_SEED)); } public void update(long[] key) { updateWithHash(MurmurHash3.hash(key, Util.DEFAULT_UPDATE_SEED)); } public double getEstimate() { double rawEst = getRawEstimate(); int logK = preamble.getLogConfigK(); double[] x_arr = Interpolation.interpolation_x_arrs[logK - Interpolation.INTERPOLATION_MIN_LOG_K]; double[] y_arr = Interpolation.interpolation_y_arrs[logK - Interpolation.INTERPOLATION_MIN_LOG_K]; if (rawEst < x_arr[0]) { return 0; } if (rawEst > x_arr[x_arr.length - 1]) { return rawEst; } double adjEst = Interpolation.cubicInterpolateUsingTable(x_arr, y_arr, rawEst); int configK = preamble.getConfigK(); if (adjEst > 3.0 * configK) { return adjEst; } double linEst = getLinearEstimate(); double avgEst = (adjEst + linEst) / 2.0; /* the following constant 0.64 comes from empirical measurements (see below) of the crossover point between the average error of the linear estimator and the adjusted hll estimator */ if (avgEst > 0.64 * configK) { return adjEst; } return linEst; } public double getUpperBound(double numStdDevs) { return getEstimate() / (1.0 - eps(numStdDevs)); } public double getLowerBound(double numStdDevs) { double lowerBound = getEstimate() / (1.0 + eps(numStdDevs)); double numNonZeros = (double) preamble.getConfigK(); numNonZeros -= numBucketsAtZero(); if (lowerBound < numNonZeros) { return numNonZeros; } return lowerBound; } private double getRawEstimate() { int numBuckets = preamble.getConfigK(); double correctionFactor = 0.7213 / (1.0 + 1.079 / (double) numBuckets); correctionFactor *= numBuckets * numBuckets; correctionFactor /= inversePowerOf2Sum(); return correctionFactor; } private double getLinearEstimate() { int configK = preamble.getConfigK(); long longV = numBucketsAtZero(); if (longV == 0) { return configK * Math.log(configK / 0.5); } return (configK * (HarmonicNumbers.harmonicNumber(configK) - HarmonicNumbers.harmonicNumber(longV))); } public HllSketch union(HllSketch that) { BucketIterator iter = that.fields.getBucketIterator(); while (iter.next()) { fields = fields.updateBucket(iter.getKey(), iter.getValue(), updateCallback); } return this; } private void updateWithHash(long[] hash) { byte newValue = (byte) (Long.numberOfLeadingZeros(hash[1]) + 1); int slotno = (int) hash[0] & (preamble.getConfigK() - 1); fields = fields.updateBucket(slotno, newValue, updateCallback); } private double eps(double numStdDevs) { return numStdDevs * HIP_REL_ERROR_NUMER / Math.sqrt(preamble.getConfigK()); } public byte[] toByteArray() { int numBytes = (preamble.getPreambleSize() << 3) + fields.numBytesToSerialize(); byte[] retVal = new byte[numBytes]; fields.intoByteArray(retVal, preamble.intoByteArray(retVal, 0)); return retVal; } public byte[] toByteArrayNoPreamble() { byte[] retVal = new byte[fields.numBytesToSerialize()]; fields.intoByteArray(retVal, 0); return retVal; } public HllSketch asCompact() { return new HllSketch(fields.toCompact()); } public int numBuckets() { return preamble.getConfigK(); } /** * Get the update Callback. This is protected because it is intended that only children might *call* * the method. It is not expected that this would be overridden by a child class. If someone overrides * it and weird things happen, the bug lies in the fact that it was overridden. * * @return The updateCallback registered with the HllSketch */ protected Fields.UpdateCallback getUpdateCallback() { return updateCallback; } /** * Set the update callback. This is protected because it is intended that only children might *call* * the method. It is not expected that this would be overridden by a child class. If someone overrides * it and weird things happen, the bug lies in the fact that it was overridden. * * @param updateCallback the update callback for the HllSketch to use when talking with its Fields */ protected void setUpdateCallback(Fields.UpdateCallback updateCallback) { this.updateCallback = updateCallback; } //Helper methods that are potential extension points for children /** * The sum of the inverse powers of 2 * @return the sum of the inverse powers of 2 */ protected double inversePowerOf2Sum() { return HllUtils.computeInvPow2Sum(numBuckets(), fields.getBucketIterator()); } protected int numBucketsAtZero() { int retVal = 0; int count = 0; BucketIterator bucketIter = fields.getBucketIterator(); while (bucketIter.next()) { if (bucketIter.getValue() == 0) { ++retVal; } ++count; } // All skipped buckets are 0. retVal += fields.getPreamble().getConfigK() - count; return retVal; } }
Bug fix: HllSketch without HIP bounds calculations were way off. The HllSketch eps() method was using the HIP_REL_ERROR_NUMER = 0.836083874576235 constant instead of HLL_REL_ERROR_NUMER = 1.04. These are correctly used in Kevin's C code, but incorrect in Alex's HLL java code and everthing since. I am fixing it here but nowhere else.
src/main/java/com/yahoo/sketches/hll/HllSketch.java
Bug fix: HllSketch without HIP bounds calculations were way off. The HllSketch eps() method was using the HIP_REL_ERROR_NUMER = 0.836083874576235 constant instead of HLL_REL_ERROR_NUMER = 1.04. These are correctly used in Kevin's C code, but incorrect in Alex's HLL java code and everthing since. I am fixing it here but nowhere else.
Java
apache-2.0
f868e8a68cfac3fd6b36d31c7d58071ed12ddf35
0
danielsun1106/groovy-parser,danielsun1106/groovy-parser
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.groovy.parser.antlr4; import groovy.lang.IntRange; import org.antlr.v4.runtime.ANTLRErrorListener; import org.antlr.v4.runtime.ANTLRInputStream; import org.antlr.v4.runtime.CharStream; import org.antlr.v4.runtime.CommonTokenStream; import org.antlr.v4.runtime.RecognitionException; import org.antlr.v4.runtime.Recognizer; import org.antlr.v4.runtime.Token; import org.antlr.v4.runtime.atn.PredictionMode; import org.antlr.v4.runtime.misc.ParseCancellationException; import org.antlr.v4.runtime.tree.ParseTree; import org.antlr.v4.runtime.tree.TerminalNode; import org.apache.groovy.parser.antlr4.internal.AtnManager; import org.apache.groovy.parser.antlr4.internal.DescriptiveErrorStrategy; import org.apache.groovy.parser.antlr4.util.StringUtils; import org.apache.groovy.util.Maps; import org.codehaus.groovy.GroovyBugError; import org.codehaus.groovy.antlr.EnumHelper; import org.codehaus.groovy.ast.ASTNode; import org.codehaus.groovy.ast.AnnotationNode; import org.codehaus.groovy.ast.ClassHelper; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.ast.ConstructorNode; import org.codehaus.groovy.ast.EnumConstantClassNode; import org.codehaus.groovy.ast.FieldNode; import org.codehaus.groovy.ast.GenericsType; import org.codehaus.groovy.ast.ImportNode; import org.codehaus.groovy.ast.InnerClassNode; import org.codehaus.groovy.ast.MethodNode; import org.codehaus.groovy.ast.ModuleNode; import org.codehaus.groovy.ast.NodeMetaDataHandler; import org.codehaus.groovy.ast.PackageNode; import org.codehaus.groovy.ast.Parameter; import org.codehaus.groovy.ast.PropertyNode; import org.codehaus.groovy.ast.expr.AnnotationConstantExpression; import org.codehaus.groovy.ast.expr.ArgumentListExpression; import org.codehaus.groovy.ast.expr.ArrayExpression; import org.codehaus.groovy.ast.expr.AttributeExpression; import org.codehaus.groovy.ast.expr.BinaryExpression; import org.codehaus.groovy.ast.expr.BitwiseNegationExpression; import org.codehaus.groovy.ast.expr.BooleanExpression; import org.codehaus.groovy.ast.expr.CastExpression; import org.codehaus.groovy.ast.expr.ClassExpression; import org.codehaus.groovy.ast.expr.ClosureExpression; import org.codehaus.groovy.ast.expr.ClosureListExpression; import org.codehaus.groovy.ast.expr.ConstantExpression; import org.codehaus.groovy.ast.expr.ConstructorCallExpression; import org.codehaus.groovy.ast.expr.DeclarationExpression; import org.codehaus.groovy.ast.expr.ElvisOperatorExpression; import org.codehaus.groovy.ast.expr.EmptyExpression; import org.codehaus.groovy.ast.expr.Expression; import org.codehaus.groovy.ast.expr.GStringExpression; import org.codehaus.groovy.ast.expr.LambdaExpression; import org.codehaus.groovy.ast.expr.ListExpression; import org.codehaus.groovy.ast.expr.MapEntryExpression; import org.codehaus.groovy.ast.expr.MapExpression; import org.codehaus.groovy.ast.expr.MethodCallExpression; import org.codehaus.groovy.ast.expr.MethodPointerExpression; import org.codehaus.groovy.ast.expr.MethodReferenceExpression; import org.codehaus.groovy.ast.expr.NamedArgumentListExpression; import org.codehaus.groovy.ast.expr.NotExpression; import org.codehaus.groovy.ast.expr.PostfixExpression; import org.codehaus.groovy.ast.expr.PrefixExpression; import org.codehaus.groovy.ast.expr.PropertyExpression; import org.codehaus.groovy.ast.expr.RangeExpression; import org.codehaus.groovy.ast.expr.SpreadExpression; import org.codehaus.groovy.ast.expr.SpreadMapExpression; import org.codehaus.groovy.ast.expr.TernaryExpression; import org.codehaus.groovy.ast.expr.TupleExpression; import org.codehaus.groovy.ast.expr.UnaryMinusExpression; import org.codehaus.groovy.ast.expr.UnaryPlusExpression; import org.codehaus.groovy.ast.expr.VariableExpression; import org.codehaus.groovy.ast.stmt.AssertStatement; import org.codehaus.groovy.ast.stmt.BlockStatement; import org.codehaus.groovy.ast.stmt.BreakStatement; import org.codehaus.groovy.ast.stmt.CaseStatement; import org.codehaus.groovy.ast.stmt.CatchStatement; import org.codehaus.groovy.ast.stmt.ContinueStatement; import org.codehaus.groovy.ast.stmt.DoWhileStatement; import org.codehaus.groovy.ast.stmt.EmptyStatement; import org.codehaus.groovy.ast.stmt.ExpressionStatement; import org.codehaus.groovy.ast.stmt.ForStatement; import org.codehaus.groovy.ast.stmt.IfStatement; import org.codehaus.groovy.ast.stmt.ReturnStatement; import org.codehaus.groovy.ast.stmt.Statement; import org.codehaus.groovy.ast.stmt.SwitchStatement; import org.codehaus.groovy.ast.stmt.SynchronizedStatement; import org.codehaus.groovy.ast.stmt.ThrowStatement; import org.codehaus.groovy.ast.stmt.TryCatchStatement; import org.codehaus.groovy.ast.stmt.WhileStatement; import org.codehaus.groovy.control.CompilationFailedException; import org.codehaus.groovy.control.CompilePhase; import org.codehaus.groovy.control.SourceUnit; import org.codehaus.groovy.control.messages.SyntaxErrorMessage; import org.codehaus.groovy.runtime.IOGroovyMethods; import org.codehaus.groovy.runtime.StringGroovyMethods; import org.codehaus.groovy.syntax.Numbers; import org.codehaus.groovy.syntax.SyntaxException; import org.codehaus.groovy.syntax.Types; import org.objectweb.asm.Opcodes; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.reflect.Field; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Deque; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.logging.Logger; import java.util.stream.Collectors; import java.util.stream.Stream; import static org.apache.groovy.parser.antlr4.GroovyLangParser.*; import static org.codehaus.groovy.runtime.DefaultGroovyMethods.asBoolean; import static org.codehaus.groovy.runtime.DefaultGroovyMethods.last; /** * Building the AST from the parse tree generated by Antlr4 * * @author <a href="mailto:[email protected]">Daniel.Sun</a> * Created on 2016/08/14 */ public class AstBuilder extends GroovyParserBaseVisitor<Object> implements GroovyParserVisitor<Object> { public AstBuilder(SourceUnit sourceUnit, ClassLoader classLoader) { this.sourceUnit = sourceUnit; this.moduleNode = new ModuleNode(sourceUnit); this.classLoader = classLoader; // unused for the time being CharStream charStream = new ANTLRInputStream( this.readSourceCode(sourceUnit)); this.lexer = new GroovyLangLexer(charStream); this.parser = new GroovyLangParser( new CommonTokenStream(this.lexer)); this.parser.setErrorHandler(new DescriptiveErrorStrategy(charStream)); this.tryWithResourcesASTTransformation = new TryWithResourcesASTTransformation(this); this.groovydocManager = new GroovydocManager(this); } private GroovyParserRuleContext buildCST() { GroovyParserRuleContext result; // parsing have to wait util clearing is complete. AtnManager.RRWL.readLock().lock(); try { result = buildCST(PredictionMode.SLL); } catch (Throwable t) { // if some syntax error occurred in the lexer, no need to retry the powerful LL mode if (t instanceof GroovySyntaxError && GroovySyntaxError.LEXER == ((GroovySyntaxError) t).getSource()) { throw t; } result = buildCST(PredictionMode.LL); } finally { AtnManager.RRWL.readLock().unlock(); } return result; } private GroovyParserRuleContext buildCST(PredictionMode predictionMode) { parser.getInterpreter().setPredictionMode(predictionMode); if (PredictionMode.SLL.equals(predictionMode)) { this.removeErrorListeners(); } else { ((CommonTokenStream) parser.getInputStream()).reset(); this.addErrorListeners(); } return parser.compilationUnit(); } public ModuleNode buildAST() { try { return (ModuleNode) this.visit(this.buildCST()); } catch (Throwable t) { CompilationFailedException cfe; if (t instanceof CompilationFailedException) { cfe = (CompilationFailedException) t; } else if (t instanceof ParseCancellationException) { cfe = createParsingFailedException(t.getCause()); } else { cfe = createParsingFailedException(t); } // LOGGER.log(Level.SEVERE, "Failed to build AST", cfe); throw cfe; } } @Override public ModuleNode visitCompilationUnit(CompilationUnitContext ctx) { this.visit(ctx.packageDeclaration()); ctx.statement().stream() .map(this::visit) // .filter(e -> e instanceof Statement) .forEach(e -> { if (e instanceof DeclarationListStatement) { // local variable declaration ((DeclarationListStatement) e).getDeclarationStatements().forEach(moduleNode::addStatement); } else if (e instanceof Statement) { moduleNode.addStatement((Statement) e); } else if (e instanceof MethodNode) { // script method moduleNode.addMethod((MethodNode) e); } }); this.classNodeList.forEach(moduleNode::addClass); if (this.isPackageInfoDeclaration()) { this.addPackageInfoClassNode(); } else { // if groovy source file only contains blank(including EOF), add "return null" to the AST if (this.isBlankScript(ctx)) { this.addEmptyReturnStatement(); } } this.configureScriptClassNode(); return moduleNode; } @Override public PackageNode visitPackageDeclaration(PackageDeclarationContext ctx) { String packageName = this.visitQualifiedName(ctx.qualifiedName()); moduleNode.setPackageName(packageName + DOT_STR); PackageNode packageNode = moduleNode.getPackage(); packageNode.addAnnotations(this.visitAnnotationsOpt(ctx.annotationsOpt())); return this.configureAST(packageNode, ctx); } @Override public ImportNode visitImportDeclaration(ImportDeclarationContext ctx) { ImportNode importNode; boolean hasStatic = asBoolean(ctx.STATIC()); boolean hasStar = asBoolean(ctx.MUL()); boolean hasAlias = asBoolean(ctx.alias); List<AnnotationNode> annotationNodeList = this.visitAnnotationsOpt(ctx.annotationsOpt()); if (hasStatic) { if (hasStar) { // e.g. import static java.lang.Math.* String qualifiedName = this.visitQualifiedName(ctx.qualifiedName()); ClassNode type = ClassHelper.make(qualifiedName); this.configureAST(type, ctx); moduleNode.addStaticStarImport(type.getText(), type, annotationNodeList); importNode = last(moduleNode.getStaticStarImports().values()); } else { // e.g. import static java.lang.Math.pow List<GroovyParserRuleContext> identifierList = new LinkedList<>(ctx.qualifiedName().qualifiedNameElement()); int identifierListSize = identifierList.size(); String name = identifierList.get(identifierListSize - 1).getText(); ClassNode classNode = ClassHelper.make( identifierList.stream() .limit(identifierListSize - 1) .map(ParseTree::getText) .collect(Collectors.joining(DOT_STR))); String alias = hasAlias ? ctx.alias.getText() : name; this.configureAST(classNode, ctx); moduleNode.addStaticImport(classNode, name, alias, annotationNodeList); importNode = last(moduleNode.getStaticImports().values()); } } else { if (hasStar) { // e.g. import java.util.* String qualifiedName = this.visitQualifiedName(ctx.qualifiedName()); moduleNode.addStarImport(qualifiedName + DOT_STR, annotationNodeList); importNode = last(moduleNode.getStarImports()); } else { // e.g. import java.util.Map String qualifiedName = this.visitQualifiedName(ctx.qualifiedName()); String name = last(ctx.qualifiedName().qualifiedNameElement()).getText(); ClassNode classNode = ClassHelper.make(qualifiedName); String alias = hasAlias ? ctx.alias.getText() : name; this.configureAST(classNode, ctx); moduleNode.addImport(alias, classNode, annotationNodeList); importNode = last(moduleNode.getImports()); } } return this.configureAST(importNode, ctx); } // statement { -------------------------------------------------------------------- @Override public AssertStatement visitAssertStatement(AssertStatementContext ctx) { Expression conditionExpression = (Expression) this.visit(ctx.ce); if (conditionExpression instanceof BinaryExpression) { BinaryExpression binaryExpression = (BinaryExpression) conditionExpression; if (binaryExpression.getOperation().getType() == Types.ASSIGN) { throw createParsingFailedException("Assignment expression is not allowed in the assert statement", conditionExpression); } } BooleanExpression booleanExpression = this.configureAST( new BooleanExpression(conditionExpression), conditionExpression); if (!asBoolean(ctx.me)) { return this.configureAST( new AssertStatement(booleanExpression), ctx); } return this.configureAST(new AssertStatement(booleanExpression, (Expression) this.visit(ctx.me)), ctx); } @Override public AssertStatement visitAssertStmtAlt(AssertStmtAltContext ctx) { return this.configureAST(this.visitAssertStatement(ctx.assertStatement()), ctx); } @Override public IfStatement visitIfElseStmtAlt(IfElseStmtAltContext ctx) { Expression conditionExpression = this.visitExpressionInPar(ctx.expressionInPar()); BooleanExpression booleanExpression = this.configureAST( new BooleanExpression(conditionExpression), conditionExpression); Statement ifBlock = this.unpackStatement( (Statement) this.visit(ctx.tb)); Statement elseBlock = this.unpackStatement( asBoolean(ctx.ELSE()) ? (Statement) this.visit(ctx.fb) : EmptyStatement.INSTANCE); return this.configureAST(new IfStatement(booleanExpression, ifBlock, elseBlock), ctx); } @Override public Statement visitLoopStmtAlt(LoopStmtAltContext ctx) { return this.configureAST((Statement) this.visit(ctx.loopStatement()), ctx); } @Override public ForStatement visitForStmtAlt(ForStmtAltContext ctx) { Pair<Parameter, Expression> controlPair = this.visitForControl(ctx.forControl()); Statement loopBlock = this.unpackStatement((Statement) this.visit(ctx.statement())); return this.configureAST( new ForStatement(controlPair.getKey(), controlPair.getValue(), asBoolean(loopBlock) ? loopBlock : EmptyStatement.INSTANCE), ctx); } @Override public Pair<Parameter, Expression> visitForControl(ForControlContext ctx) { if (asBoolean(ctx.enhancedForControl())) { // e.g. for(int i in 0..<10) {} return this.visitEnhancedForControl(ctx.enhancedForControl()); } if (asBoolean(ctx.classicalForControl())) { // e.g. for(int i = 0; i < 10; i++) {} return this.visitClassicalForControl(ctx.classicalForControl()); } throw createParsingFailedException("Unsupported for control: " + ctx.getText(), ctx); } @Override public Expression visitForInit(ForInitContext ctx) { if (!asBoolean(ctx)) { return EmptyExpression.INSTANCE; } if (asBoolean(ctx.localVariableDeclaration())) { DeclarationListStatement declarationListStatement = this.visitLocalVariableDeclaration(ctx.localVariableDeclaration()); List<?> declarationExpressionList = declarationListStatement.getDeclarationExpressions(); if (declarationExpressionList.size() == 1) { return this.configureAST((Expression) declarationExpressionList.get(0), ctx); } else { return this.configureAST(new ClosureListExpression((List<Expression>) declarationExpressionList), ctx); } } if (asBoolean(ctx.expressionList())) { return this.translateExpressionList(ctx.expressionList()); } throw createParsingFailedException("Unsupported for init: " + ctx.getText(), ctx); } @Override public Expression visitForUpdate(ForUpdateContext ctx) { if (!asBoolean(ctx)) { return EmptyExpression.INSTANCE; } return this.translateExpressionList(ctx.expressionList()); } private Expression translateExpressionList(ExpressionListContext ctx) { List<Expression> expressionList = this.visitExpressionList(ctx); if (expressionList.size() == 1) { return this.configureAST(expressionList.get(0), ctx); } else { return this.configureAST(new ClosureListExpression(expressionList), ctx); } } @Override public Pair<Parameter, Expression> visitEnhancedForControl(EnhancedForControlContext ctx) { Parameter parameter = this.configureAST( new Parameter(this.visitType(ctx.type()), this.visitVariableDeclaratorId(ctx.variableDeclaratorId()).getName()), ctx.variableDeclaratorId()); // FIXME Groovy will ignore variableModifier of parameter in the for control // In order to make the new parser behave same with the old one, we do not process variableModifier* return new Pair<>(parameter, (Expression) this.visit(ctx.expression())); } @Override public Pair<Parameter, Expression> visitClassicalForControl(ClassicalForControlContext ctx) { ClosureListExpression closureListExpression = new ClosureListExpression(); closureListExpression.addExpression(this.visitForInit(ctx.forInit())); closureListExpression.addExpression(asBoolean(ctx.expression()) ? (Expression) this.visit(ctx.expression()) : EmptyExpression.INSTANCE); closureListExpression.addExpression(this.visitForUpdate(ctx.forUpdate())); return new Pair<>(ForStatement.FOR_LOOP_DUMMY, closureListExpression); } @Override public WhileStatement visitWhileStmtAlt(WhileStmtAltContext ctx) { Expression conditionExpression = this.visitExpressionInPar(ctx.expressionInPar()); BooleanExpression booleanExpression = this.configureAST( new BooleanExpression(conditionExpression), conditionExpression); Statement loopBlock = this.unpackStatement((Statement) this.visit(ctx.statement())); return this.configureAST( new WhileStatement(booleanExpression, asBoolean(loopBlock) ? loopBlock : EmptyStatement.INSTANCE), ctx); } @Override public DoWhileStatement visitDoWhileStmtAlt(DoWhileStmtAltContext ctx) { Expression conditionExpression = this.visitExpressionInPar(ctx.expressionInPar()); BooleanExpression booleanExpression = this.configureAST( new BooleanExpression(conditionExpression), conditionExpression ); Statement loopBlock = this.unpackStatement((Statement) this.visit(ctx.statement())); return this.configureAST( new DoWhileStatement(booleanExpression, asBoolean(loopBlock) ? loopBlock : EmptyStatement.INSTANCE), ctx); } @Override public Statement visitTryCatchStmtAlt(TryCatchStmtAltContext ctx) { return this.configureAST(this.visitTryCatchStatement(ctx.tryCatchStatement()), ctx); } @Override public Statement visitTryCatchStatement(TryCatchStatementContext ctx) { TryCatchStatement tryCatchStatement = new TryCatchStatement((Statement) this.visit(ctx.block()), this.visitFinallyBlock(ctx.finallyBlock())); if (asBoolean(ctx.resources())) { this.visitResources(ctx.resources()).forEach(tryCatchStatement::addResource); } ctx.catchClause().stream().map(this::visitCatchClause) .reduce(new LinkedList<CatchStatement>(), (r, e) -> { r.addAll(e); // merge several LinkedList<CatchStatement> instances into one LinkedList<CatchStatement> instance return r; }) .forEach(tryCatchStatement::addCatch); return this.configureAST( tryWithResourcesASTTransformation.transform( this.configureAST(tryCatchStatement, ctx)), ctx); } @Override public List<ExpressionStatement> visitResources(ResourcesContext ctx) { return this.visitResourceList(ctx.resourceList()); } @Override public List<ExpressionStatement> visitResourceList(ResourceListContext ctx) { return ctx.resource().stream().map(this::visitResource).collect(Collectors.toList()); } @Override public ExpressionStatement visitResource(ResourceContext ctx) { if (asBoolean(ctx.localVariableDeclaration())) { List<ExpressionStatement> declarationStatements = this.visitLocalVariableDeclaration(ctx.localVariableDeclaration()).getDeclarationStatements(); if (declarationStatements.size() > 1) { throw createParsingFailedException("Multi resources can not be declared in one statement", ctx); } return declarationStatements.get(0); } else if (asBoolean(ctx.expression())) { Expression expression = (Expression) this.visit(ctx.expression()); if (!(expression instanceof BinaryExpression && Types.ASSIGN == ((BinaryExpression) expression).getOperation().getType() && ((BinaryExpression) expression).getLeftExpression() instanceof VariableExpression)) { throw createParsingFailedException("Only variable declarations are allowed to declare resource", ctx); } BinaryExpression assignmentExpression = (BinaryExpression) expression; return this.configureAST( new ExpressionStatement( this.configureAST( new DeclarationExpression( this.configureAST( new VariableExpression(assignmentExpression.getLeftExpression().getText()), assignmentExpression.getLeftExpression() ), assignmentExpression.getOperation(), assignmentExpression.getRightExpression() ), ctx) ), ctx); } throw createParsingFailedException("Unsupported resource declaration: " + ctx.getText(), ctx); } /** * Multi-catch(1..*) clause will be unpacked to several normal catch clauses, so the return type is List * * @param ctx the parse tree * @return */ @Override public List<CatchStatement> visitCatchClause(CatchClauseContext ctx) { // FIXME Groovy will ignore variableModifier of parameter in the catch clause // In order to make the new parser behave same with the old one, we do not process variableModifier* return this.visitCatchType(ctx.catchType()).stream() .map(e -> this.configureAST( new CatchStatement( // FIXME The old parser does not set location info for the parameter of the catch clause. // we could make it better //this.configureAST(new Parameter(e, this.visitIdentifier(ctx.identifier())), ctx.Identifier()), new Parameter(e, this.visitIdentifier(ctx.identifier())), this.visitBlock(ctx.block())), ctx)) .collect(Collectors.toList()); } @Override public List<ClassNode> visitCatchType(CatchTypeContext ctx) { if (!asBoolean(ctx)) { return Collections.singletonList(ClassHelper.OBJECT_TYPE); } return ctx.qualifiedClassName().stream() .map(this::visitQualifiedClassName) .collect(Collectors.toList()); } @Override public Statement visitFinallyBlock(FinallyBlockContext ctx) { if (!asBoolean(ctx)) { return EmptyStatement.INSTANCE; } return this.configureAST( this.createBlockStatement((Statement) this.visit(ctx.block())), ctx); } @Override public SwitchStatement visitSwitchStmtAlt(SwitchStmtAltContext ctx) { return this.configureAST(this.visitSwitchStatement(ctx.switchStatement()), ctx); } public SwitchStatement visitSwitchStatement(SwitchStatementContext ctx) { List<Statement> statementList = ctx.switchBlockStatementGroup().stream() .map(this::visitSwitchBlockStatementGroup) .reduce(new LinkedList<>(), (r, e) -> { r.addAll(e); return r; }); List<CaseStatement> caseStatementList = new LinkedList<>(); List<Statement> defaultStatementList = new LinkedList<>(); statementList.forEach(e -> { if (e instanceof CaseStatement) { caseStatementList.add((CaseStatement) e); } else if (isTrue(e, IS_SWITCH_DEFAULT)) { defaultStatementList.add(e); } }); int defaultStatementListSize = defaultStatementList.size(); if (defaultStatementListSize > 1) { throw createParsingFailedException("switch statement should have only one default case, which should appear at last", defaultStatementList.get(0)); } if (defaultStatementListSize > 0 && last(statementList) instanceof CaseStatement) { throw createParsingFailedException("default case should appear at last", defaultStatementList.get(0)); } return this.configureAST( new SwitchStatement( this.visitExpressionInPar(ctx.expressionInPar()), caseStatementList, defaultStatementListSize == 0 ? EmptyStatement.INSTANCE : defaultStatementList.get(0) ), ctx); } @Override @SuppressWarnings({"unchecked"}) public List<Statement> visitSwitchBlockStatementGroup(SwitchBlockStatementGroupContext ctx) { int labelCnt = ctx.switchLabel().size(); List<Token> firstLabelHolder = new ArrayList<>(1); return (List<Statement>) ctx.switchLabel().stream() .map(e -> (Object) this.visitSwitchLabel(e)) .reduce(new ArrayList<Statement>(4), (r, e) -> { List<Statement> statementList = (List<Statement>) r; Pair<Token, Expression> pair = (Pair<Token, Expression>) e; boolean isLast = labelCnt - 1 == statementList.size(); switch (pair.getKey().getType()) { case CASE: { if (!asBoolean(statementList)) { firstLabelHolder.add(pair.getKey()); } statementList.add( this.configureAST( new CaseStatement( pair.getValue(), // check whether processing the last label. if yes, block statement should be attached. isLast ? this.visitBlockStatements(ctx.blockStatements()) : EmptyStatement.INSTANCE ), firstLabelHolder.get(0))); break; } case DEFAULT: { BlockStatement blockStatement = this.visitBlockStatements(ctx.blockStatements()); blockStatement.putNodeMetaData(IS_SWITCH_DEFAULT, true); statementList.add( // this.configureAST(blockStatement, pair.getKey()) blockStatement ); break; } } return statementList; }); } @Override public Pair<Token, Expression> visitSwitchLabel(SwitchLabelContext ctx) { if (asBoolean(ctx.CASE())) { return new Pair<>(ctx.CASE().getSymbol(), (Expression) this.visit(ctx.expression())); } else if (asBoolean(ctx.DEFAULT())) { return new Pair<>(ctx.DEFAULT().getSymbol(), EmptyExpression.INSTANCE); } throw createParsingFailedException("Unsupported switch label: " + ctx.getText(), ctx); } @Override public SynchronizedStatement visitSynchronizedStmtAlt(SynchronizedStmtAltContext ctx) { return this.configureAST( new SynchronizedStatement(this.visitExpressionInPar(ctx.expressionInPar()), this.visitBlock(ctx.block())), ctx); } @Override public ExpressionStatement visitExpressionStmtAlt(ExpressionStmtAltContext ctx) { return (ExpressionStatement) this.visit(ctx.statementExpression()); } @Override public ReturnStatement visitReturnStmtAlt(ReturnStmtAltContext ctx) { return this.configureAST(new ReturnStatement(asBoolean(ctx.expression()) ? (Expression) this.visit(ctx.expression()) : ConstantExpression.EMPTY_EXPRESSION), ctx); } @Override public ThrowStatement visitThrowStmtAlt(ThrowStmtAltContext ctx) { return this.configureAST( new ThrowStatement((Expression) this.visit(ctx.expression())), ctx); } @Override public Statement visitLabeledStmtAlt(LabeledStmtAltContext ctx) { Statement statement = (Statement) this.visit(ctx.statement()); statement.addStatementLabel(this.visitIdentifier(ctx.identifier())); return statement; // this.configureAST(statement, ctx); } @Override public BreakStatement visitBreakStatement(BreakStatementContext ctx) { String label = asBoolean(ctx.identifier()) ? this.visitIdentifier(ctx.identifier()) : null; return this.configureAST(new BreakStatement(label), ctx); } @Override public BreakStatement visitBreakStmtAlt(BreakStmtAltContext ctx) { return this.configureAST(this.visitBreakStatement(ctx.breakStatement()), ctx); } @Override public ContinueStatement visitContinueStatement(ContinueStatementContext ctx) { String label = asBoolean(ctx.identifier()) ? this.visitIdentifier(ctx.identifier()) : null; return this.configureAST(new ContinueStatement(label), ctx); } @Override public ContinueStatement visitContinueStmtAlt(ContinueStmtAltContext ctx) { return this.configureAST(this.visitContinueStatement(ctx.continueStatement()), ctx); } @Override public ImportNode visitImportStmtAlt(ImportStmtAltContext ctx) { return this.configureAST(this.visitImportDeclaration(ctx.importDeclaration()), ctx); } @Override public ClassNode visitTypeDeclarationStmtAlt(TypeDeclarationStmtAltContext ctx) { return this.configureAST(this.visitTypeDeclaration(ctx.typeDeclaration()), ctx); } @Override public Statement visitLocalVariableDeclarationStmtAlt(LocalVariableDeclarationStmtAltContext ctx) { return this.configureAST(this.visitLocalVariableDeclaration(ctx.localVariableDeclaration()), ctx); } @Override public MethodNode visitMethodDeclarationStmtAlt(MethodDeclarationStmtAltContext ctx) { return this.configureAST(this.visitMethodDeclaration(ctx.methodDeclaration()), ctx); } // } statement -------------------------------------------------------------------- @Override public ClassNode visitTypeDeclaration(TypeDeclarationContext ctx) { if (asBoolean(ctx.classDeclaration())) { // e.g. class A {} ctx.classDeclaration().putNodeMetaData(TYPE_DECLARATION_MODIFIERS, this.visitClassOrInterfaceModifiersOpt(ctx.classOrInterfaceModifiersOpt())); return this.configureAST(this.visitClassDeclaration(ctx.classDeclaration()), ctx); } throw createParsingFailedException("Unsupported type declaration: " + ctx.getText(), ctx); } private void initUsingGenerics(ClassNode classNode) { if (classNode.isUsingGenerics()) { return; } if (!classNode.isEnum()) { classNode.setUsingGenerics(classNode.getSuperClass().isUsingGenerics()); } if (!classNode.isUsingGenerics() && null != classNode.getInterfaces()) { for (ClassNode anInterface : classNode.getInterfaces()) { classNode.setUsingGenerics(classNode.isUsingGenerics() || anInterface.isUsingGenerics()); if (classNode.isUsingGenerics()) break; } } } @Override public ClassNode visitClassDeclaration(ClassDeclarationContext ctx) { String packageName = moduleNode.getPackageName(); packageName = null != packageName ? packageName : ""; List<ModifierNode> modifierNodeList = ctx.getNodeMetaData(TYPE_DECLARATION_MODIFIERS); Objects.requireNonNull(modifierNodeList, "modifierNodeList should not be null"); ModifierManager modifierManager = new ModifierManager(this, modifierNodeList); int modifiers = modifierManager.getClassModifiersOpValue(); boolean syntheticPublic = ((modifiers & Opcodes.ACC_SYNTHETIC) != 0); modifiers &= ~Opcodes.ACC_SYNTHETIC; final ClassNode outerClass = classNodeStack.peek(); ClassNode classNode; String className = this.visitIdentifier(ctx.identifier()); if (asBoolean(ctx.ENUM())) { classNode = EnumHelper.makeEnumNode( asBoolean(outerClass) ? className : packageName + className, modifiers, null, outerClass); } else { if (asBoolean(outerClass)) { classNode = new InnerClassNode( outerClass, outerClass.getName() + "$" + className, modifiers | (outerClass.isInterface() ? Opcodes.ACC_STATIC : 0), ClassHelper.OBJECT_TYPE); } else { classNode = new ClassNode( packageName + className, modifiers, ClassHelper.OBJECT_TYPE); } } this.configureAST(classNode, ctx); classNode.putNodeMetaData(CLASS_NAME, className); classNode.setSyntheticPublic(syntheticPublic); if (asBoolean(ctx.TRAIT())) { classNode.addAnnotation(new AnnotationNode(ClassHelper.make(GROOVY_TRANSFORM_TRAIT))); } classNode.addAnnotations(modifierManager.getAnnotations()); classNode.setGenericsTypes(this.visitTypeParameters(ctx.typeParameters())); boolean isInterface = asBoolean(ctx.INTERFACE()) && !asBoolean(ctx.AT()); boolean isInterfaceWithDefaultMethods = false; // declaring interface with default method if (isInterface && this.containsDefaultMethods(ctx)) { isInterfaceWithDefaultMethods = true; classNode.addAnnotation(new AnnotationNode(ClassHelper.make(GROOVY_TRANSFORM_TRAIT))); classNode.putNodeMetaData(IS_INTERFACE_WITH_DEFAULT_METHODS, true); } if (asBoolean(ctx.CLASS()) || asBoolean(ctx.TRAIT()) || isInterfaceWithDefaultMethods) { // class OR trait OR interface with default methods classNode.setSuperClass(this.visitType(ctx.sc)); classNode.setInterfaces(this.visitTypeList(ctx.is)); this.initUsingGenerics(classNode); } else if (isInterface) { // interface(NOT annotation) classNode.setModifiers(classNode.getModifiers() | Opcodes.ACC_INTERFACE | Opcodes.ACC_ABSTRACT); classNode.setSuperClass(ClassHelper.OBJECT_TYPE); classNode.setInterfaces(this.visitTypeList(ctx.scs)); this.initUsingGenerics(classNode); this.hackMixins(classNode); } else if (asBoolean(ctx.ENUM())) { // enum classNode.setModifiers(classNode.getModifiers() | Opcodes.ACC_ENUM | Opcodes.ACC_FINAL); classNode.setInterfaces(this.visitTypeList(ctx.is)); this.initUsingGenerics(classNode); } else if (asBoolean(ctx.AT())) { // annotation classNode.setModifiers(classNode.getModifiers() | Opcodes.ACC_INTERFACE | Opcodes.ACC_ABSTRACT | Opcodes.ACC_ANNOTATION); classNode.addInterface(ClassHelper.Annotation_TYPE); this.hackMixins(classNode); } else { throw createParsingFailedException("Unsupported class declaration: " + ctx.getText(), ctx); } // we put the class already in output to avoid the most inner classes // will be used as first class later in the loader. The first class // there determines what GCL#parseClass for example will return, so we // have here to ensure it won't be the inner class if (asBoolean(ctx.CLASS()) || asBoolean(ctx.TRAIT())) { classNodeList.add(classNode); } int oldAnonymousInnerClassCounter = this.anonymousInnerClassCounter; classNodeStack.push(classNode); ctx.classBody().putNodeMetaData(CLASS_DECLARATION_CLASS_NODE, classNode); this.visitClassBody(ctx.classBody()); classNodeStack.pop(); this.anonymousInnerClassCounter = oldAnonymousInnerClassCounter; if (!(asBoolean(ctx.CLASS()) || asBoolean(ctx.TRAIT()))) { classNodeList.add(classNode); } groovydocManager.handle(classNode, ctx); return classNode; } @SuppressWarnings({"unchecked"}) private boolean containsDefaultMethods(ClassDeclarationContext ctx) { List<MethodDeclarationContext> methodDeclarationContextList = (List<MethodDeclarationContext>) ctx.classBody().classBodyDeclaration().stream() .map(ClassBodyDeclarationContext::memberDeclaration) .filter(Objects::nonNull) .map(e -> (Object) e.methodDeclaration()) .filter(Objects::nonNull).reduce(new LinkedList<MethodDeclarationContext>(), (r, e) -> { MethodDeclarationContext methodDeclarationContext = (MethodDeclarationContext) e; if (createModifierManager(methodDeclarationContext).contains(DEFAULT)) { ((List) r).add(methodDeclarationContext); } return r; }); return !methodDeclarationContextList.isEmpty(); } @Override public Void visitClassBody(ClassBodyContext ctx) { ClassNode classNode = ctx.getNodeMetaData(CLASS_DECLARATION_CLASS_NODE); Objects.requireNonNull(classNode, "classNode should not be null"); if (asBoolean(ctx.enumConstants())) { ctx.enumConstants().putNodeMetaData(CLASS_DECLARATION_CLASS_NODE, classNode); this.visitEnumConstants(ctx.enumConstants()); } ctx.classBodyDeclaration().forEach(e -> { e.putNodeMetaData(CLASS_DECLARATION_CLASS_NODE, classNode); this.visitClassBodyDeclaration(e); }); return null; } @Override public List<FieldNode> visitEnumConstants(EnumConstantsContext ctx) { ClassNode classNode = ctx.getNodeMetaData(CLASS_DECLARATION_CLASS_NODE); Objects.requireNonNull(classNode, "classNode should not be null"); return ctx.enumConstant().stream() .map(e -> { e.putNodeMetaData(CLASS_DECLARATION_CLASS_NODE, classNode); return this.visitEnumConstant(e); }) .collect(Collectors.toList()); } @Override public FieldNode visitEnumConstant(EnumConstantContext ctx) { ClassNode classNode = ctx.getNodeMetaData(CLASS_DECLARATION_CLASS_NODE); Objects.requireNonNull(classNode, "classNode should not be null"); InnerClassNode anonymousInnerClassNode = null; if (asBoolean(ctx.anonymousInnerClassDeclaration())) { ctx.anonymousInnerClassDeclaration().putNodeMetaData(ANONYMOUS_INNER_CLASS_SUPER_CLASS, classNode); anonymousInnerClassNode = this.visitAnonymousInnerClassDeclaration(ctx.anonymousInnerClassDeclaration()); } FieldNode enumConstant = EnumHelper.addEnumConstant( classNode, this.visitIdentifier(ctx.identifier()), createEnumConstantInitExpression(ctx.arguments(), anonymousInnerClassNode)); enumConstant.addAnnotations(this.visitAnnotationsOpt(ctx.annotationsOpt())); groovydocManager.handle(enumConstant, ctx); return this.configureAST(enumConstant, ctx); } private Expression createEnumConstantInitExpression(ArgumentsContext ctx, InnerClassNode anonymousInnerClassNode) { if (!asBoolean(ctx) && !asBoolean(anonymousInnerClassNode)) { return null; } TupleExpression argumentListExpression = (TupleExpression) this.visitArguments(ctx); List<Expression> expressions = argumentListExpression.getExpressions(); if (expressions.size() == 1) { Expression expression = expressions.get(0); if (expression instanceof NamedArgumentListExpression) { // e.g. SOME_ENUM_CONSTANT(a: "1", b: "2") List<MapEntryExpression> mapEntryExpressionList = ((NamedArgumentListExpression) expression).getMapEntryExpressions(); ListExpression listExpression = new ListExpression( mapEntryExpressionList.stream() .map(e -> (Expression) e) .collect(Collectors.toList())); if (asBoolean(anonymousInnerClassNode)) { listExpression.addExpression( this.configureAST( new ClassExpression(anonymousInnerClassNode), anonymousInnerClassNode)); } if (mapEntryExpressionList.size() > 1) { listExpression.setWrapped(true); } return this.configureAST(listExpression, ctx); } if (!asBoolean(anonymousInnerClassNode)) { if (expression instanceof ListExpression) { ListExpression listExpression = new ListExpression(); listExpression.addExpression(expression); return this.configureAST(listExpression, ctx); } return expression; } ListExpression listExpression = new ListExpression(); if (expression instanceof ListExpression) { ((ListExpression) expression).getExpressions().forEach(listExpression::addExpression); } else { listExpression.addExpression(expression); } listExpression.addExpression( this.configureAST( new ClassExpression(anonymousInnerClassNode), anonymousInnerClassNode)); return this.configureAST(listExpression, ctx); } ListExpression listExpression = new ListExpression(expressions); if (asBoolean(anonymousInnerClassNode)) { listExpression.addExpression( this.configureAST( new ClassExpression(anonymousInnerClassNode), anonymousInnerClassNode)); } if (asBoolean(ctx)) { listExpression.setWrapped(true); } return asBoolean(ctx) ? this.configureAST(listExpression, ctx) : this.configureAST(listExpression, anonymousInnerClassNode); } @Override public Void visitClassBodyDeclaration(ClassBodyDeclarationContext ctx) { ClassNode classNode = ctx.getNodeMetaData(CLASS_DECLARATION_CLASS_NODE); Objects.requireNonNull(classNode, "classNode should not be null"); if (asBoolean(ctx.memberDeclaration())) { ctx.memberDeclaration().putNodeMetaData(CLASS_DECLARATION_CLASS_NODE, classNode); this.visitMemberDeclaration(ctx.memberDeclaration()); } else if (asBoolean(ctx.block())) { Statement statement = this.visitBlock(ctx.block()); if (asBoolean(ctx.STATIC())) { // e.g. static { } classNode.addStaticInitializerStatements(Collections.singletonList(statement), false); } else { // e.g. { } classNode.addObjectInitializerStatements( this.configureAST( this.createBlockStatement(statement), statement)); } } return null; } @Override public Void visitMemberDeclaration(MemberDeclarationContext ctx) { ClassNode classNode = ctx.getNodeMetaData(CLASS_DECLARATION_CLASS_NODE); Objects.requireNonNull(classNode, "classNode should not be null"); if (asBoolean(ctx.methodDeclaration())) { ctx.methodDeclaration().putNodeMetaData(CLASS_DECLARATION_CLASS_NODE, classNode); this.visitMethodDeclaration(ctx.methodDeclaration()); } else if (asBoolean(ctx.fieldDeclaration())) { ctx.fieldDeclaration().putNodeMetaData(CLASS_DECLARATION_CLASS_NODE, classNode); this.visitFieldDeclaration(ctx.fieldDeclaration()); } else if (asBoolean(ctx.classDeclaration())) { ctx.classDeclaration().putNodeMetaData(TYPE_DECLARATION_MODIFIERS, this.visitModifiersOpt(ctx.modifiersOpt())); ctx.classDeclaration().putNodeMetaData(CLASS_DECLARATION_CLASS_NODE, classNode); this.visitClassDeclaration(ctx.classDeclaration()); } return null; } @Override public GenericsType[] visitTypeParameters(TypeParametersContext ctx) { if (!asBoolean(ctx)) { return null; } return ctx.typeParameter().stream() .map(this::visitTypeParameter) .toArray(GenericsType[]::new); } @Override public GenericsType visitTypeParameter(TypeParameterContext ctx) { return this.configureAST( new GenericsType( this.configureAST(ClassHelper.make(this.visitClassName(ctx.className())), ctx), this.visitTypeBound(ctx.typeBound()), null ), ctx); } @Override public ClassNode[] visitTypeBound(TypeBoundContext ctx) { if (!asBoolean(ctx)) { return null; } return ctx.type().stream() .map(this::visitType) .toArray(ClassNode[]::new); } @Override public Void visitFieldDeclaration(FieldDeclarationContext ctx) { ClassNode classNode = ctx.getNodeMetaData(CLASS_DECLARATION_CLASS_NODE); Objects.requireNonNull(classNode, "classNode should not be null"); ctx.variableDeclaration().putNodeMetaData(CLASS_DECLARATION_CLASS_NODE, classNode); this.visitVariableDeclaration(ctx.variableDeclaration()); return null; } private ConstructorCallExpression checkThisAndSuperConstructorCall(Statement statement) { if (!(statement instanceof BlockStatement)) { // method code must be a BlockStatement return null; } BlockStatement blockStatement = (BlockStatement) statement; List<Statement> statementList = blockStatement.getStatements(); for (int i = 0, n = statementList.size(); i < n; i++) { Statement s = statementList.get(i); if (s instanceof ExpressionStatement) { Expression expression = ((ExpressionStatement) s).getExpression(); if ((expression instanceof ConstructorCallExpression) && 0 != i) { return (ConstructorCallExpression) expression; } } } return null; } private ModifierManager createModifierManager(MethodDeclarationContext ctx) { List<ModifierNode> modifierNodeList = Collections.emptyList(); if (asBoolean(ctx.modifiers())) { modifierNodeList = this.visitModifiers(ctx.modifiers()); } else if (asBoolean(ctx.modifiersOpt())) { modifierNodeList = this.visitModifiersOpt(ctx.modifiersOpt()); } return new ModifierManager(this, modifierNodeList); } private void validateParametersOfMethodDeclaration(Parameter[] parameters, ClassNode classNode) { if (!classNode.isInterface()) { return; } for (Parameter parameter : parameters) { if (parameter.hasInitialExpression()) { throw createParsingFailedException("Cannot specify default value for method parameter '" + parameter.getName() + " = " + parameter.getInitialExpression().getText() + "' inside an interface", parameter); } } } @Override public MethodNode visitMethodDeclaration(MethodDeclarationContext ctx) { ModifierManager modifierManager = createModifierManager(ctx); String methodName = this.visitMethodName(ctx.methodName()); ClassNode returnType = this.visitReturnType(ctx.returnType()); Parameter[] parameters = this.visitFormalParameters(ctx.formalParameters()); ClassNode[] exceptions = this.visitQualifiedClassNameList(ctx.qualifiedClassNameList()); anonymousInnerClassesDefinedInMethodStack.push(new LinkedList<>()); Statement code = this.visitMethodBody(ctx.methodBody()); List<InnerClassNode> anonymousInnerClassList = anonymousInnerClassesDefinedInMethodStack.pop(); MethodNode methodNode; // if classNode is not null, the method declaration is for class declaration ClassNode classNode = ctx.getNodeMetaData(CLASS_DECLARATION_CLASS_NODE); if (asBoolean(classNode)) { validateParametersOfMethodDeclaration(parameters, classNode); methodNode = createConstructorOrMethodNodeForClass(ctx, modifierManager, methodName, returnType, parameters, exceptions, code, classNode); } else { // script method declaration methodNode = createScriptMethodNode(modifierManager, methodName, returnType, parameters, exceptions, code); } anonymousInnerClassList.forEach(e -> e.setEnclosingMethod(methodNode)); methodNode.setGenericsTypes(this.visitTypeParameters(ctx.typeParameters())); methodNode.setSyntheticPublic( this.isSyntheticPublic( this.isAnnotationDeclaration(classNode), classNode instanceof EnumConstantClassNode, asBoolean(ctx.returnType()), modifierManager)); if (modifierManager.contains(STATIC)) { for (Parameter parameter : methodNode.getParameters()) { parameter.setInStaticContext(true); } methodNode.getVariableScope().setInStaticContext(true); } this.configureAST(methodNode, ctx); validateMethodDeclaration(ctx, methodNode, modifierManager, classNode); groovydocManager.handle(methodNode, ctx); return methodNode; } private void validateMethodDeclaration(MethodDeclarationContext ctx, MethodNode methodNode, ModifierManager modifierManager, ClassNode classNode) { boolean isAbstractMethod = methodNode.isAbstract(); boolean hasMethodBody = asBoolean(methodNode.getCode()); if (9 == ctx.ct) { // script if (isAbstractMethod || !hasMethodBody) { // method should not be declared abstract in the script throw createParsingFailedException("You can not define a " + (isAbstractMethod ? "abstract" : "") + " method[" + methodNode.getName() + "] " + (!hasMethodBody ? "without method body" : "") + " in the script. Try " + (isAbstractMethod ? "removing the 'abstract'" : "") + (isAbstractMethod && !hasMethodBody ? " and" : "") + (!hasMethodBody ? " adding a method body" : ""), methodNode); } } else { if (!isAbstractMethod && !hasMethodBody) { // non-abstract method without body in the non-script(e.g. class, enum, trait) is not allowed! throw createParsingFailedException("You defined a method[" + methodNode.getName() + "] without body. Try adding a method body, or declare it abstract", methodNode); } boolean isInterfaceOrAbstractClass = asBoolean(classNode) && classNode.isAbstract() && !classNode.isAnnotationDefinition(); if (isInterfaceOrAbstractClass && !modifierManager.contains(DEFAULT) && isAbstractMethod && hasMethodBody) { throw createParsingFailedException("You defined an abstract method[" + methodNode.getName() + "] with body. Try removing the method body" + (classNode.isInterface() ? ", or declare it default" : ""), methodNode); } } modifierManager.validate(methodNode); if (methodNode instanceof ConstructorNode) { modifierManager.validate((ConstructorNode) methodNode); } } private MethodNode createScriptMethodNode(ModifierManager modifierManager, String methodName, ClassNode returnType, Parameter[] parameters, ClassNode[] exceptions, Statement code) { MethodNode methodNode; methodNode = new MethodNode( methodName, modifierManager.contains(PRIVATE) ? Opcodes.ACC_PRIVATE : Opcodes.ACC_PUBLIC, returnType, parameters, exceptions, code); modifierManager.processMethodNode(methodNode); return methodNode; } private MethodNode createConstructorOrMethodNodeForClass(MethodDeclarationContext ctx, ModifierManager modifierManager, String methodName, ClassNode returnType, Parameter[] parameters, ClassNode[] exceptions, Statement code, ClassNode classNode) { MethodNode methodNode; String className = classNode.getNodeMetaData(CLASS_NAME); int modifiers = modifierManager.getClassMemberModifiersOpValue(); boolean hasReturnType = asBoolean(ctx.returnType()); boolean hasMethodBody = asBoolean(ctx.methodBody()); if (!hasReturnType && hasMethodBody && methodName.equals(className)) { // constructor declaration methodNode = createConstructorNodeForClass(methodName, parameters, exceptions, code, classNode, modifiers); } else { // class memeber method declaration if (!hasReturnType && hasMethodBody && (0 == modifierManager.getModifierCount())) { throw createParsingFailedException("Invalid method declaration: " + methodName, ctx); } methodNode = createMethodNodeForClass(ctx, modifierManager, methodName, returnType, parameters, exceptions, code, classNode, modifiers); } modifierManager.attachAnnotations(methodNode); return methodNode; } private MethodNode createMethodNodeForClass(MethodDeclarationContext ctx, ModifierManager modifierManager, String methodName, ClassNode returnType, Parameter[] parameters, ClassNode[] exceptions, Statement code, ClassNode classNode, int modifiers) { MethodNode methodNode; if (asBoolean(ctx.elementValue())) { // the code of annotation method code = this.configureAST( new ExpressionStatement( this.visitElementValue(ctx.elementValue())), ctx.elementValue()); } modifiers |= !modifierManager.contains(STATIC) && (classNode.isInterface() || (isTrue(classNode, IS_INTERFACE_WITH_DEFAULT_METHODS) && !modifierManager.contains(DEFAULT))) ? Opcodes.ACC_ABSTRACT : 0; checkWhetherMethodNodeWithSameSignatureExists(classNode, methodName, parameters, ctx); methodNode = classNode.addMethod(methodName, modifiers, returnType, parameters, exceptions, code); methodNode.setAnnotationDefault(asBoolean(ctx.elementValue())); return methodNode; } private void checkWhetherMethodNodeWithSameSignatureExists(ClassNode classNode, String methodName, Parameter[] parameters, MethodDeclarationContext ctx) { MethodNode sameSigMethodNode = classNode.getDeclaredMethod(methodName, parameters); if (null == sameSigMethodNode) { return; } throw createParsingFailedException("The method " + sameSigMethodNode.getText() + " duplicates another method of the same signature", ctx); } private ConstructorNode createConstructorNodeForClass(String methodName, Parameter[] parameters, ClassNode[] exceptions, Statement code, ClassNode classNode, int modifiers) { ConstructorCallExpression thisOrSuperConstructorCallExpression = this.checkThisAndSuperConstructorCall(code); if (asBoolean(thisOrSuperConstructorCallExpression)) { throw createParsingFailedException(thisOrSuperConstructorCallExpression.getText() + " should be the first statement in the constructor[" + methodName + "]", thisOrSuperConstructorCallExpression); } return classNode.addConstructor( modifiers, parameters, exceptions, code); } @Override public String visitMethodName(MethodNameContext ctx) { if (asBoolean(ctx.identifier())) { return this.visitIdentifier(ctx.identifier()); } if (asBoolean(ctx.stringLiteral())) { return this.visitStringLiteral(ctx.stringLiteral()).getText(); } throw createParsingFailedException("Unsupported method name: " + ctx.getText(), ctx); } @Override public ClassNode visitReturnType(ReturnTypeContext ctx) { if (!asBoolean(ctx)) { return ClassHelper.OBJECT_TYPE; } if (asBoolean(ctx.type())) { return this.visitType(ctx.type()); } if (asBoolean(ctx.VOID())) { return ClassHelper.VOID_TYPE; } throw createParsingFailedException("Unsupported return type: " + ctx.getText(), ctx); } @Override public Statement visitMethodBody(MethodBodyContext ctx) { if (!asBoolean(ctx)) { return null; } return this.configureAST(this.visitBlock(ctx.block()), ctx); } @Override public DeclarationListStatement visitLocalVariableDeclaration(LocalVariableDeclarationContext ctx) { return this.configureAST(this.visitVariableDeclaration(ctx.variableDeclaration()), ctx); } private ModifierManager createModifierManager(VariableDeclarationContext ctx) { List<ModifierNode> modifierNodeList = Collections.emptyList(); if (asBoolean(ctx.variableModifiers())) { modifierNodeList = this.visitVariableModifiers(ctx.variableModifiers()); } else if (asBoolean(ctx.variableModifiersOpt())) { modifierNodeList = this.visitVariableModifiersOpt(ctx.variableModifiersOpt()); } else if (asBoolean(ctx.modifiers())) { modifierNodeList = this.visitModifiers(ctx.modifiers()); } else if (asBoolean(ctx.modifiersOpt())) { modifierNodeList = this.visitModifiersOpt(ctx.modifiersOpt()); } return new ModifierManager(this, modifierNodeList); } private DeclarationListStatement createMultiAssignmentDeclarationListStatement(VariableDeclarationContext ctx, ModifierManager modifierManager) { if (!modifierManager.contains(DEF)) { throw createParsingFailedException("keyword def is required to declare tuple, e.g. def (int a, int b) = [1, 2]", ctx); } return this.configureAST( new DeclarationListStatement( this.configureAST( modifierManager.attachAnnotations( new DeclarationExpression( new ArgumentListExpression( this.visitTypeNamePairs(ctx.typeNamePairs()).stream() .peek(e -> modifierManager.processVariableExpression((VariableExpression) e)) .collect(Collectors.toList()) ), this.createGroovyTokenByType(ctx.ASSIGN().getSymbol(), Types.ASSIGN), this.visitVariableInitializer(ctx.variableInitializer()) ) ), ctx ) ), ctx ); } @Override public DeclarationListStatement visitVariableDeclaration(VariableDeclarationContext ctx) { ModifierManager modifierManager = this.createModifierManager(ctx); if (asBoolean(ctx.typeNamePairs())) { // e.g. def (int a, int b) = [1, 2] return this.createMultiAssignmentDeclarationListStatement(ctx, modifierManager); } ClassNode variableType = this.visitType(ctx.type()); ctx.variableDeclarators().putNodeMetaData(VARIABLE_DECLARATION_VARIABLE_TYPE, variableType); List<DeclarationExpression> declarationExpressionList = this.visitVariableDeclarators(ctx.variableDeclarators()); // if classNode is not null, the variable declaration is for class declaration. In other words, it is a field declaration ClassNode classNode = ctx.getNodeMetaData(CLASS_DECLARATION_CLASS_NODE); if (asBoolean(classNode)) { return createFieldDeclarationListStatement(ctx, modifierManager, variableType, declarationExpressionList, classNode); } declarationExpressionList.forEach(e -> { VariableExpression variableExpression = (VariableExpression) e.getLeftExpression(); modifierManager.processVariableExpression(variableExpression); modifierManager.attachAnnotations(e); }); int size = declarationExpressionList.size(); if (size > 0) { DeclarationExpression declarationExpression = declarationExpressionList.get(0); if (1 == size) { this.configureAST(declarationExpression, ctx); } else { // Tweak start of first declaration declarationExpression.setLineNumber(ctx.getStart().getLine()); declarationExpression.setColumnNumber(ctx.getStart().getCharPositionInLine() + 1); } } return this.configureAST(new DeclarationListStatement(declarationExpressionList), ctx); } private DeclarationListStatement createFieldDeclarationListStatement(VariableDeclarationContext ctx, ModifierManager modifierManager, ClassNode variableType, List<DeclarationExpression> declarationExpressionList, ClassNode classNode) { for (int i = 0, n = declarationExpressionList.size(); i < n; i++) { DeclarationExpression declarationExpression = declarationExpressionList.get(i); VariableExpression variableExpression = (VariableExpression) declarationExpression.getLeftExpression(); String fieldName = variableExpression.getName(); int modifiers = modifierManager.getClassMemberModifiersOpValue(); Expression initialValue = EmptyExpression.INSTANCE.equals(declarationExpression.getRightExpression()) ? null : declarationExpression.getRightExpression(); Object defaultValue = findDefaultValueByType(variableType); if (classNode.isInterface()) { if (!asBoolean(initialValue)) { initialValue = !asBoolean(defaultValue) ? null : new ConstantExpression(defaultValue); } modifiers |= Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC | Opcodes.ACC_FINAL; } if (isFieldDeclaration(modifierManager, classNode)) { declareField(ctx, modifierManager, variableType, classNode, i, variableExpression, fieldName, modifiers, initialValue); } else { declareProperty(ctx, modifierManager, variableType, classNode, i, variableExpression, fieldName, modifiers, initialValue); } } return null; } private void declareProperty(VariableDeclarationContext ctx, ModifierManager modifierManager, ClassNode variableType, ClassNode classNode, int i, VariableExpression variableExpression, String fieldName, int modifiers, Expression initialValue) { if (classNode.hasProperty(fieldName)) { throw createParsingFailedException("The property '" + fieldName + "' is declared multiple times", ctx); } PropertyNode propertyNode; FieldNode fieldNode = classNode.getDeclaredField(fieldName); if (fieldNode != null && !classNode.hasProperty(fieldName)) { classNode.getFields().remove(fieldNode); propertyNode = new PropertyNode(fieldNode, modifiers | Opcodes.ACC_PUBLIC, null, null); classNode.addProperty(propertyNode); } else { propertyNode = classNode.addProperty( fieldName, modifiers | Opcodes.ACC_PUBLIC, variableType, initialValue, null, null); fieldNode = propertyNode.getField(); } fieldNode.setModifiers(modifiers & ~Opcodes.ACC_PUBLIC | Opcodes.ACC_PRIVATE); fieldNode.setSynthetic(!classNode.isInterface()); modifierManager.attachAnnotations(fieldNode); groovydocManager.handle(fieldNode, ctx); groovydocManager.handle(propertyNode, ctx); if (0 == i) { this.configureAST(fieldNode, ctx, initialValue); this.configureAST(propertyNode, ctx, initialValue); } else { this.configureAST(fieldNode, variableExpression, initialValue); this.configureAST(propertyNode, variableExpression, initialValue); } } private void declareField(VariableDeclarationContext ctx, ModifierManager modifierManager, ClassNode variableType, ClassNode classNode, int i, VariableExpression variableExpression, String fieldName, int modifiers, Expression initialValue) { FieldNode existingFieldNode = classNode.getDeclaredField(fieldName); if (null != existingFieldNode && !existingFieldNode.isSynthetic()) { throw createParsingFailedException("The field '" + fieldName + "' is declared multiple times", ctx); } FieldNode fieldNode; PropertyNode propertyNode = classNode.getProperty(fieldName); if (null != propertyNode && propertyNode.getField().isSynthetic()) { classNode.getFields().remove(propertyNode.getField()); fieldNode = new FieldNode(fieldName, modifiers, variableType, classNode.redirect(), initialValue); propertyNode.setField(fieldNode); classNode.addField(fieldNode); } else { fieldNode = classNode.addField( fieldName, modifiers, variableType, initialValue); } modifierManager.attachAnnotations(fieldNode); groovydocManager.handle(fieldNode, ctx); if (0 == i) { this.configureAST(fieldNode, ctx, initialValue); } else { this.configureAST(fieldNode, variableExpression, initialValue); } } private boolean isFieldDeclaration(ModifierManager modifierManager, ClassNode classNode) { return classNode.isInterface() || modifierManager.containsVisibilityModifier(); } @Override public List<Expression> visitTypeNamePairs(TypeNamePairsContext ctx) { return ctx.typeNamePair().stream().map(this::visitTypeNamePair).collect(Collectors.toList()); } @Override public VariableExpression visitTypeNamePair(TypeNamePairContext ctx) { return this.configureAST( new VariableExpression( this.visitVariableDeclaratorId(ctx.variableDeclaratorId()).getName(), this.visitType(ctx.type())), ctx); } @Override public List<DeclarationExpression> visitVariableDeclarators(VariableDeclaratorsContext ctx) { ClassNode variableType = ctx.getNodeMetaData(VARIABLE_DECLARATION_VARIABLE_TYPE); Objects.requireNonNull(variableType, "variableType should not be null"); return ctx.variableDeclarator().stream() .map(e -> { e.putNodeMetaData(VARIABLE_DECLARATION_VARIABLE_TYPE, variableType); return this.visitVariableDeclarator(e); // return this.configureAST(this.visitVariableDeclarator(e), ctx); }) .collect(Collectors.toList()); } @Override public DeclarationExpression visitVariableDeclarator(VariableDeclaratorContext ctx) { ClassNode variableType = ctx.getNodeMetaData(VARIABLE_DECLARATION_VARIABLE_TYPE); Objects.requireNonNull(variableType, "variableType should not be null"); org.codehaus.groovy.syntax.Token token; if (asBoolean(ctx.ASSIGN())) { token = createGroovyTokenByType(ctx.ASSIGN().getSymbol(), Types.ASSIGN); } else { token = new org.codehaus.groovy.syntax.Token(Types.ASSIGN, ASSIGN_STR, ctx.start.getLine(), 1); } return this.configureAST( new DeclarationExpression( this.configureAST( new VariableExpression( this.visitVariableDeclaratorId(ctx.variableDeclaratorId()).getName(), variableType ), ctx.variableDeclaratorId()), token, this.visitVariableInitializer(ctx.variableInitializer())), ctx); } @Override public Expression visitVariableInitializer(VariableInitializerContext ctx) { if (!asBoolean(ctx)) { return EmptyExpression.INSTANCE; } return this.configureAST( this.visitEnhancedStatementExpression(ctx.enhancedStatementExpression()), ctx); } @Override public List<Expression> visitVariableInitializers(VariableInitializersContext ctx) { if (!asBoolean(ctx)) { return Collections.emptyList(); } return ctx.variableInitializer().stream() .map(this::visitVariableInitializer) .collect(Collectors.toList()); } @Override public List<Expression> visitArrayInitializer(ArrayInitializerContext ctx) { if (!asBoolean(ctx)) { return Collections.emptyList(); } return this.visitVariableInitializers(ctx.variableInitializers()); } @Override public Statement visitBlock(BlockContext ctx) { if (!asBoolean(ctx)) { return this.createBlockStatement(); } return this.configureAST( this.visitBlockStatementsOpt(ctx.blockStatementsOpt()), ctx); } @Override public ExpressionStatement visitNormalExprAlt(NormalExprAltContext ctx) { return this.configureAST(new ExpressionStatement((Expression) this.visit(ctx.expression())), ctx); } @Override public ExpressionStatement visitCommandExprAlt(CommandExprAltContext ctx) { return this.configureAST(new ExpressionStatement(this.visitCommandExpression(ctx.commandExpression())), ctx); } @Override public Expression visitCommandExpression(CommandExpressionContext ctx) { Expression baseExpr = this.visitPathExpression(ctx.pathExpression()); Expression arguments = this.visitEnhancedArgumentList(ctx.enhancedArgumentList()); MethodCallExpression methodCallExpression; if (baseExpr instanceof PropertyExpression) { // e.g. obj.a 1, 2 methodCallExpression = this.configureAST( this.createMethodCallExpression( (PropertyExpression) baseExpr, arguments), arguments); } else if (baseExpr instanceof MethodCallExpression && !isInsideParentheses(baseExpr)) { // e.g. m {} a, b OR m(...) a, b if (asBoolean(arguments)) { // The error should never be thrown. throw new GroovyBugError("When baseExpr is a instance of MethodCallExpression, which should follow NO argumentList"); } methodCallExpression = (MethodCallExpression) baseExpr; } else if ( !isInsideParentheses(baseExpr) && (baseExpr instanceof VariableExpression /* e.g. m 1, 2 */ || baseExpr instanceof GStringExpression /* e.g. "$m" 1, 2 */ || (baseExpr instanceof ConstantExpression && isTrue(baseExpr, IS_STRING)) /* e.g. "m" 1, 2 */) ) { methodCallExpression = this.configureAST( this.createMethodCallExpression(baseExpr, arguments), arguments); } else { // e.g. a[x] b, new A() b, etc. methodCallExpression = this.configureAST( new MethodCallExpression( baseExpr, CALL_STR, arguments ), arguments ); methodCallExpression.setImplicitThis(false); } if (!asBoolean(ctx.commandArgument())) { return this.configureAST(methodCallExpression, ctx); } return this.configureAST( (Expression) ctx.commandArgument().stream() .map(e -> (Object) e) .reduce(methodCallExpression, (r, e) -> { CommandArgumentContext commandArgumentContext = (CommandArgumentContext) e; commandArgumentContext.putNodeMetaData(CMD_EXPRESSION_BASE_EXPR, r); return this.visitCommandArgument(commandArgumentContext); } ), ctx); } @Override public Expression visitCommandArgument(CommandArgumentContext ctx) { // e.g. x y a b we call "x y" as the base expression Expression baseExpr = ctx.getNodeMetaData(CMD_EXPRESSION_BASE_EXPR); Expression primaryExpr = (Expression) this.visit(ctx.primary()); if (asBoolean(ctx.enhancedArgumentList())) { // e.g. x y a b if (baseExpr instanceof PropertyExpression) { // the branch should never reach, because a.b.c will be parsed as a path expression, not a method call throw createParsingFailedException("Unsupported command argument: " + ctx.getText(), ctx); } // the following code will process "a b" of "x y a b" MethodCallExpression methodCallExpression = new MethodCallExpression( baseExpr, this.createConstantExpression(primaryExpr), this.visitEnhancedArgumentList(ctx.enhancedArgumentList()) ); methodCallExpression.setImplicitThis(false); return this.configureAST(methodCallExpression, ctx); } else if (asBoolean(ctx.pathElement())) { // e.g. x y a.b Expression pathExpression = this.createPathExpression( this.configureAST( new PropertyExpression(baseExpr, this.createConstantExpression(primaryExpr)), primaryExpr ), ctx.pathElement() ); return this.configureAST(pathExpression, ctx); } // e.g. x y a return this.configureAST( new PropertyExpression( baseExpr, primaryExpr instanceof VariableExpression ? this.createConstantExpression(primaryExpr) : primaryExpr ), primaryExpr ); } // expression { -------------------------------------------------------------------- @Override public ClassNode visitCastParExpression(CastParExpressionContext ctx) { return this.visitType(ctx.type()); } @Override public Expression visitParExpression(ParExpressionContext ctx) { Expression expression = this.visitExpressionInPar(ctx.expressionInPar()); Integer insideParenLevel = expression.getNodeMetaData(INSIDE_PARENTHESES_LEVEL); if (null != insideParenLevel) { insideParenLevel++; } else { insideParenLevel = 1; } expression.putNodeMetaData(INSIDE_PARENTHESES_LEVEL, insideParenLevel); return this.configureAST(expression, ctx); } @Override public Expression visitExpressionInPar(ExpressionInParContext ctx) { return this.visitEnhancedStatementExpression(ctx.enhancedStatementExpression()); } @Override public Expression visitEnhancedStatementExpression(EnhancedStatementExpressionContext ctx) { Expression expression; if (asBoolean(ctx.statementExpression())) { expression = ((ExpressionStatement) this.visit(ctx.statementExpression())).getExpression(); } else if (asBoolean(ctx.standardLambdaExpression())) { expression = this.visitStandardLambdaExpression(ctx.standardLambdaExpression()); } else { throw createParsingFailedException("Unsupported enhanced statement expression: " + ctx.getText(), ctx); } return this.configureAST(expression, ctx); } @Override public Expression visitPathExpression(PathExpressionContext ctx) { return //this.configureAST( this.createPathExpression((Expression) this.visit(ctx.primary()), ctx.pathElement()); //ctx); } @Override public Expression visitPathElement(PathElementContext ctx) { Expression baseExpr = ctx.getNodeMetaData(PATH_EXPRESSION_BASE_EXPR); Objects.requireNonNull(baseExpr, "baseExpr is required!"); if (asBoolean(ctx.namePart())) { Expression namePartExpr = this.visitNamePart(ctx.namePart()); GenericsType[] genericsTypes = this.visitNonWildcardTypeArguments(ctx.nonWildcardTypeArguments()); if (asBoolean(ctx.DOT())) { if (asBoolean(ctx.AT())) { // e.g. obj.@a return this.configureAST(new AttributeExpression(baseExpr, namePartExpr), ctx); } else { // e.g. obj.p PropertyExpression propertyExpression = new PropertyExpression(baseExpr, namePartExpr); propertyExpression.putNodeMetaData(PATH_EXPRESSION_BASE_EXPR_GENERICS_TYPES, genericsTypes); return this.configureAST(propertyExpression, ctx); } } else if (asBoolean(ctx.SAFE_DOT())) { if (asBoolean(ctx.AT())) { // e.g. obj?.@a return this.configureAST(new AttributeExpression(baseExpr, namePartExpr, true), ctx); } else { // e.g. obj?.p PropertyExpression propertyExpression = new PropertyExpression(baseExpr, namePartExpr, true); propertyExpression.putNodeMetaData(PATH_EXPRESSION_BASE_EXPR_GENERICS_TYPES, genericsTypes); return this.configureAST(propertyExpression, ctx); } } else if (asBoolean(ctx.METHOD_POINTER())) { // e.g. obj.&m return this.configureAST(new MethodPointerExpression(baseExpr, namePartExpr), ctx); } else if (asBoolean(ctx.METHOD_REFERENCE())) { // e.g. obj::m return this.configureAST(new MethodReferenceExpression(baseExpr, namePartExpr), ctx); } else if (asBoolean(ctx.SPREAD_DOT())) { if (asBoolean(ctx.AT())) { // e.g. obj*.@a AttributeExpression attributeExpression = new AttributeExpression(baseExpr, namePartExpr, true); attributeExpression.setSpreadSafe(true); return this.configureAST(attributeExpression, ctx); } else { // e.g. obj*.p PropertyExpression propertyExpression = new PropertyExpression(baseExpr, namePartExpr, true); propertyExpression.putNodeMetaData(PATH_EXPRESSION_BASE_EXPR_GENERICS_TYPES, genericsTypes); propertyExpression.setSpreadSafe(true); return this.configureAST(propertyExpression, ctx); } } } if (asBoolean(ctx.indexPropertyArgs())) { // e.g. list[1, 3, 5] Pair<Token, Expression> pair = this.visitIndexPropertyArgs(ctx.indexPropertyArgs()); return this.configureAST( new BinaryExpression(baseExpr, createGroovyToken(pair.getKey()), pair.getValue(), asBoolean(ctx.indexPropertyArgs().QUESTION())), ctx); } if (asBoolean(ctx.namedPropertyArgs())) { // this is a special way to new instance, e.g. Person(name: 'Daniel.Sun', location: 'Shanghai') List<MapEntryExpression> mapEntryExpressionList = this.visitNamedPropertyArgs(ctx.namedPropertyArgs()); Expression right; if (mapEntryExpressionList.size() == 1) { MapEntryExpression mapEntryExpression = mapEntryExpressionList.get(0); if (mapEntryExpression.getKeyExpression() instanceof SpreadMapExpression) { right = mapEntryExpression.getKeyExpression(); } else { right = mapEntryExpression; } } else { ListExpression listExpression = this.configureAST( new ListExpression( mapEntryExpressionList.stream() .map( e -> { if (e.getKeyExpression() instanceof SpreadMapExpression) { return e.getKeyExpression(); } return e; } ) .collect(Collectors.toList())), ctx.namedPropertyArgs() ); listExpression.setWrapped(true); right = listExpression; } return this.configureAST( new BinaryExpression(baseExpr, createGroovyToken(ctx.namedPropertyArgs().LBRACK().getSymbol()), right), ctx); } if (asBoolean(ctx.arguments())) { Expression argumentsExpr = this.visitArguments(ctx.arguments()); this.configureAST(argumentsExpr, ctx); if (isInsideParentheses(baseExpr)) { // e.g. (obj.x)(), (obj.@x)() MethodCallExpression methodCallExpression = new MethodCallExpression( baseExpr, CALL_STR, argumentsExpr ); methodCallExpression.setImplicitThis(false); return this.configureAST(methodCallExpression, ctx); } if (baseExpr instanceof AttributeExpression) { // e.g. obj.@a(1, 2) AttributeExpression attributeExpression = (AttributeExpression) baseExpr; attributeExpression.setSpreadSafe(false); // whether attributeExpression is spread safe or not, we must reset it as false MethodCallExpression methodCallExpression = new MethodCallExpression( attributeExpression, CALL_STR, argumentsExpr ); return this.configureAST(methodCallExpression, ctx); } if (baseExpr instanceof PropertyExpression) { // e.g. obj.a(1, 2) MethodCallExpression methodCallExpression = this.createMethodCallExpression((PropertyExpression) baseExpr, argumentsExpr); return this.configureAST(methodCallExpression, ctx); } if (baseExpr instanceof VariableExpression) { // void and primitive type AST node must be an instance of VariableExpression String baseExprText = baseExpr.getText(); if (VOID_STR.equals(baseExprText)) { // e.g. void() MethodCallExpression methodCallExpression = new MethodCallExpression( this.createConstantExpression(baseExpr), CALL_STR, argumentsExpr ); methodCallExpression.setImplicitThis(false); return this.configureAST(methodCallExpression, ctx); } else if (PRIMITIVE_TYPE_SET.contains(baseExprText)) { // e.g. int(), long(), float(), etc. throw createParsingFailedException("Primitive type literal: " + baseExprText + " cannot be used as a method name", ctx); } } if (baseExpr instanceof VariableExpression || baseExpr instanceof GStringExpression || (baseExpr instanceof ConstantExpression && isTrue(baseExpr, IS_STRING))) { // e.g. m(), "$m"(), "m"() String baseExprText = baseExpr.getText(); if (SUPER_STR.equals(baseExprText) || THIS_STR.equals(baseExprText)) { // e.g. this(...), super(...) // class declaration is not allowed in the closure, // so if this and super is inside the closure, it will not be constructor call. // e.g. src/test/org/codehaus/groovy/transform/MapConstructorTransformTest.groovy: // @MapConstructor(pre={ super(args?.first, args?.last); args = args ?: [:] }, post = { first = first?.toUpperCase() }) if (ctx.isInsideClosure) { return this.configureAST( new MethodCallExpression( baseExpr, baseExprText, argumentsExpr ), ctx); } return this.configureAST( new ConstructorCallExpression( SUPER_STR.equals(baseExprText) ? ClassNode.SUPER : ClassNode.THIS, argumentsExpr ), ctx); } MethodCallExpression methodCallExpression = this.createMethodCallExpression(baseExpr, argumentsExpr); return this.configureAST(methodCallExpression, ctx); } // e.g. 1(), 1.1(), ((int) 1 / 2)(1, 2), {a, b -> a + b }(1, 2), m()() MethodCallExpression methodCallExpression = new MethodCallExpression(baseExpr, CALL_STR, argumentsExpr); methodCallExpression.setImplicitThis(false); return this.configureAST(methodCallExpression, ctx); } if (asBoolean(ctx.closure())) { ClosureExpression closureExpression = this.visitClosure(ctx.closure()); if (baseExpr instanceof MethodCallExpression) { MethodCallExpression methodCallExpression = (MethodCallExpression) baseExpr; Expression argumentsExpression = methodCallExpression.getArguments(); if (argumentsExpression instanceof ArgumentListExpression) { // normal arguments, e.g. 1, 2 ArgumentListExpression argumentListExpression = (ArgumentListExpression) argumentsExpression; argumentListExpression.getExpressions().add(closureExpression); return this.configureAST(methodCallExpression, ctx); } if (argumentsExpression instanceof TupleExpression) { // named arguments, e.g. x: 1, y: 2 TupleExpression tupleExpression = (TupleExpression) argumentsExpression; NamedArgumentListExpression namedArgumentListExpression = (NamedArgumentListExpression) tupleExpression.getExpression(0); if (asBoolean(tupleExpression.getExpressions())) { methodCallExpression.setArguments( this.configureAST( new ArgumentListExpression( Stream.of( this.configureAST( new MapExpression(namedArgumentListExpression.getMapEntryExpressions()), namedArgumentListExpression ), closureExpression ).collect(Collectors.toList()) ), tupleExpression ) ); } else { // the branch should never reach, because named arguments must not be empty methodCallExpression.setArguments( this.configureAST( new ArgumentListExpression(closureExpression), tupleExpression)); } return this.configureAST(methodCallExpression, ctx); } } // e.g. 1 {}, 1.1 {} if (baseExpr instanceof ConstantExpression && isTrue(baseExpr, IS_NUMERIC)) { MethodCallExpression methodCallExpression = new MethodCallExpression( baseExpr, CALL_STR, this.configureAST( new ArgumentListExpression(closureExpression), closureExpression ) ); methodCallExpression.setImplicitThis(false); return this.configureAST(methodCallExpression, ctx); } if (baseExpr instanceof PropertyExpression) { // e.g. obj.m { } PropertyExpression propertyExpression = (PropertyExpression) baseExpr; MethodCallExpression methodCallExpression = this.createMethodCallExpression( propertyExpression, this.configureAST( new ArgumentListExpression(closureExpression), closureExpression ) ); return this.configureAST(methodCallExpression, ctx); } // e.g. m { return 1; } MethodCallExpression methodCallExpression = new MethodCallExpression( VariableExpression.THIS_EXPRESSION, (baseExpr instanceof VariableExpression) ? this.createConstantExpression(baseExpr) : baseExpr, this.configureAST( new ArgumentListExpression(closureExpression), closureExpression) ); return this.configureAST(methodCallExpression, ctx); } throw createParsingFailedException("Unsupported path element: " + ctx.getText(), ctx); } @Override public GenericsType[] visitNonWildcardTypeArguments(NonWildcardTypeArgumentsContext ctx) { if (!asBoolean(ctx)) { return null; } return Arrays.stream(this.visitTypeList(ctx.typeList())) .map(this::createGenericsType) .toArray(GenericsType[]::new); } @Override public ClassNode[] visitTypeList(TypeListContext ctx) { if (!asBoolean(ctx)) { return new ClassNode[0]; } return ctx.type().stream() .map(this::visitType) .toArray(ClassNode[]::new); } @Override public Expression visitArguments(ArgumentsContext ctx) { if (!asBoolean(ctx) || !asBoolean(ctx.enhancedArgumentList())) { return new ArgumentListExpression(); } return this.configureAST(this.visitEnhancedArgumentList(ctx.enhancedArgumentList()), ctx); } @Override public Expression visitEnhancedArgumentList(EnhancedArgumentListContext ctx) { if (!asBoolean(ctx)) { return null; } List<Expression> expressionList = new LinkedList<>(); List<MapEntryExpression> mapEntryExpressionList = new LinkedList<>(); ctx.enhancedArgumentListElement().stream() .map(this::visitEnhancedArgumentListElement) .forEach(e -> { if (e instanceof MapEntryExpression) { MapEntryExpression mapEntryExpression = (MapEntryExpression) e; validateDuplicatedNamedParameter(mapEntryExpressionList, mapEntryExpression); mapEntryExpressionList.add(mapEntryExpression); } else { expressionList.add(e); } }); if (!asBoolean(mapEntryExpressionList)) { // e.g. arguments like 1, 2 OR someArg, e -> e return this.configureAST( new ArgumentListExpression(expressionList), ctx); } if (!asBoolean(expressionList)) { // e.g. arguments like x: 1, y: 2 return this.configureAST( new TupleExpression( this.configureAST( new NamedArgumentListExpression(mapEntryExpressionList), ctx)), ctx); } if (asBoolean(mapEntryExpressionList) && asBoolean(expressionList)) { // e.g. arguments like x: 1, 'a', y: 2, 'b', z: 3 ArgumentListExpression argumentListExpression = new ArgumentListExpression(expressionList); argumentListExpression.getExpressions().add(0, new MapExpression(mapEntryExpressionList)); // TODO: confirm BUG OR NOT? All map entries will be put at first, which is not friendly to Groovy developers return this.configureAST(argumentListExpression, ctx); } throw createParsingFailedException("Unsupported argument list: " + ctx.getText(), ctx); } private void validateDuplicatedNamedParameter(List<MapEntryExpression> mapEntryExpressionList, MapEntryExpression mapEntryExpression) { Expression keyExpression = mapEntryExpression.getKeyExpression(); if (null == keyExpression) { return; } String parameterName = keyExpression.getText(); boolean isDuplicatedNamedParameter = mapEntryExpressionList.stream().anyMatch(m -> m.getKeyExpression().getText().equals(parameterName)); if (!isDuplicatedNamedParameter) { return; } throw createParsingFailedException("Duplicated named parameter '" + parameterName + "' found", mapEntryExpression); } @Override public Expression visitEnhancedArgumentListElement(EnhancedArgumentListElementContext ctx) { if (asBoolean(ctx.expressionListElement())) { return this.configureAST(this.visitExpressionListElement(ctx.expressionListElement()), ctx); } if (asBoolean(ctx.standardLambdaExpression())) { return this.configureAST(this.visitStandardLambdaExpression(ctx.standardLambdaExpression()), ctx); } if (asBoolean(ctx.mapEntry())) { return this.configureAST(this.visitMapEntry(ctx.mapEntry()), ctx); } throw createParsingFailedException("Unsupported enhanced argument list element: " + ctx.getText(), ctx); } @Override public ConstantExpression visitStringLiteral(StringLiteralContext ctx) { String text = ctx.StringLiteral().getText(); int slashyType = text.startsWith("/") ? StringUtils.SLASHY : text.startsWith("$/") ? StringUtils.DOLLAR_SLASHY : StringUtils.NONE_SLASHY; if (text.startsWith("'''") || text.startsWith("\"\"\"")) { text = StringUtils.removeCR(text); // remove CR in the multiline string text = text.length() == 6 ? "" : text.substring(3, text.length() - 3); } else if (text.startsWith("'") || text.startsWith("/") || text.startsWith("\"")) { if (text.startsWith("/")) { // the slashy string can span rows, so we have to remove CR for it text = StringUtils.removeCR(text); // remove CR in the multiline string } text = text.length() == 2 ? "" : text.substring(1, text.length() - 1); } else if (text.startsWith("$/")) { text = StringUtils.removeCR(text); text = text.length() == 4 ? "" : text.substring(2, text.length() - 2); } //handle escapes. text = StringUtils.replaceEscapes(text, slashyType); ConstantExpression constantExpression = new ConstantExpression(text, true); constantExpression.putNodeMetaData(IS_STRING, true); return this.configureAST(constantExpression, ctx); } @Override public Pair<Token, Expression> visitIndexPropertyArgs(IndexPropertyArgsContext ctx) { List<Expression> expressionList = this.visitExpressionList(ctx.expressionList()); if (expressionList.size() == 1) { Expression expr = expressionList.get(0); Expression indexExpr; if (expr instanceof SpreadExpression) { // e.g. a[*[1, 2]] ListExpression listExpression = new ListExpression(expressionList); listExpression.setWrapped(false); indexExpr = listExpression; } else { // e.g. a[1] indexExpr = expr; } return new Pair<>(ctx.LBRACK().getSymbol(), indexExpr); } // e.g. a[1, 2] ListExpression listExpression = new ListExpression(expressionList); listExpression.setWrapped(true); return new Pair<>(ctx.LBRACK().getSymbol(), this.configureAST(listExpression, ctx)); } @Override public List<MapEntryExpression> visitNamedPropertyArgs(NamedPropertyArgsContext ctx) { return this.visitMapEntryList(ctx.mapEntryList()); } @Override public Expression visitNamePart(NamePartContext ctx) { if (asBoolean(ctx.identifier())) { return this.configureAST(new ConstantExpression(this.visitIdentifier(ctx.identifier())), ctx); } else if (asBoolean(ctx.stringLiteral())) { return this.configureAST(this.visitStringLiteral(ctx.stringLiteral()), ctx); } else if (asBoolean(ctx.dynamicMemberName())) { return this.configureAST(this.visitDynamicMemberName(ctx.dynamicMemberName()), ctx); } else if (asBoolean(ctx.keywords())) { return this.configureAST(new ConstantExpression(ctx.keywords().getText()), ctx); } throw createParsingFailedException("Unsupported name part: " + ctx.getText(), ctx); } @Override public Expression visitDynamicMemberName(DynamicMemberNameContext ctx) { if (asBoolean(ctx.parExpression())) { return this.configureAST(this.visitParExpression(ctx.parExpression()), ctx); } else if (asBoolean(ctx.gstring())) { return this.configureAST(this.visitGstring(ctx.gstring()), ctx); } throw createParsingFailedException("Unsupported dynamic member name: " + ctx.getText(), ctx); } @Override public Expression visitPostfixExpression(PostfixExpressionContext ctx) { Expression pathExpr = this.visitPathExpression(ctx.pathExpression()); if (asBoolean(ctx.op)) { PostfixExpression postfixExpression = new PostfixExpression(pathExpr, createGroovyToken(ctx.op)); if (ctx.isInsideAssert) { // powerassert requires different column for values, so we have to copy the location of op return this.configureAST(postfixExpression, ctx.op); } else { return this.configureAST(postfixExpression, ctx); } } return this.configureAST(pathExpr, ctx); } @Override public Expression visitPostfixExprAlt(PostfixExprAltContext ctx) { return this.visitPostfixExpression(ctx.postfixExpression()); } @Override public Expression visitUnaryNotExprAlt(UnaryNotExprAltContext ctx) { if (asBoolean(ctx.NOT())) { return this.configureAST( new NotExpression((Expression) this.visit(ctx.expression())), ctx); } if (asBoolean(ctx.BITNOT())) { return this.configureAST( new BitwiseNegationExpression((Expression) this.visit(ctx.expression())), ctx); } throw createParsingFailedException("Unsupported unary expression: " + ctx.getText(), ctx); } @Override public CastExpression visitCastExprAlt(CastExprAltContext ctx) { return this.configureAST( new CastExpression( this.visitCastParExpression(ctx.castParExpression()), (Expression) this.visit(ctx.expression()) ), ctx ); } @Override public BinaryExpression visitPowerExprAlt(PowerExprAltContext ctx) { return this.createBinaryExpression(ctx.left, ctx.op, ctx.right, ctx); } @Override public Expression visitUnaryAddExprAlt(UnaryAddExprAltContext ctx) { ExpressionContext expressionCtx = ctx.expression(); Expression expression = (Expression) this.visit(expressionCtx); Boolean insidePar = isInsideParentheses(expression); switch (ctx.op.getType()) { case ADD: { if (expression instanceof ConstantExpression && !insidePar) { return this.configureAST(expression, ctx); } return this.configureAST(new UnaryPlusExpression(expression), ctx); } case SUB: { if (expression instanceof ConstantExpression && !insidePar) { ConstantExpression constantExpression = (ConstantExpression) expression; String integerLiteralText = constantExpression.getNodeMetaData(INTEGER_LITERAL_TEXT); if (null != integerLiteralText) { return this.configureAST(new ConstantExpression(Numbers.parseInteger(null, SUB_STR + integerLiteralText)), ctx); } String floatingPointLiteralText = constantExpression.getNodeMetaData(FLOATING_POINT_LITERAL_TEXT); if (null != floatingPointLiteralText) { return this.configureAST(new ConstantExpression(Numbers.parseDecimal(SUB_STR + floatingPointLiteralText)), ctx); } throw new GroovyBugError("Failed to find the original number literal text: " + constantExpression.getText()); } return this.configureAST(new UnaryMinusExpression(expression), ctx); } case INC: case DEC: return this.configureAST(new PrefixExpression(this.createGroovyToken(ctx.op), expression), ctx); default: throw createParsingFailedException("Unsupported unary operation: " + ctx.getText(), ctx); } } @Override public BinaryExpression visitMultiplicativeExprAlt(MultiplicativeExprAltContext ctx) { return this.createBinaryExpression(ctx.left, ctx.op, ctx.right, ctx); } @Override public BinaryExpression visitAdditiveExprAlt(AdditiveExprAltContext ctx) { return this.createBinaryExpression(ctx.left, ctx.op, ctx.right, ctx); } @Override public Expression visitShiftExprAlt(ShiftExprAltContext ctx) { Expression left = (Expression) this.visit(ctx.left); Expression right = (Expression) this.visit(ctx.right); if (asBoolean(ctx.rangeOp)) { return this.configureAST(new RangeExpression(left, right, !ctx.rangeOp.getText().endsWith("<")), ctx); } org.codehaus.groovy.syntax.Token op = null; Token antlrToken = null; if (asBoolean(ctx.dlOp)) { op = this.createGroovyToken(ctx.dlOp, 2); antlrToken = ctx.dlOp; } else if (asBoolean(ctx.dgOp)) { op = this.createGroovyToken(ctx.dgOp, 2); antlrToken = ctx.dgOp; } else if (asBoolean(ctx.tgOp)) { op = this.createGroovyToken(ctx.tgOp, 3); antlrToken = ctx.tgOp; } else { throw createParsingFailedException("Unsupported shift expression: " + ctx.getText(), ctx); } BinaryExpression binaryExpression = new BinaryExpression(left, op, right); if (isTrue(ctx, IS_INSIDE_CONDITIONAL_EXPRESSION)) { return this.configureAST(binaryExpression, antlrToken); } return this.configureAST(binaryExpression, ctx); } @Override public Expression visitRelationalExprAlt(RelationalExprAltContext ctx) { switch (ctx.op.getType()) { case AS: return this.configureAST( CastExpression.asExpression(this.visitType(ctx.type()), (Expression) this.visit(ctx.left)), ctx); case INSTANCEOF: case NOT_INSTANCEOF: ctx.type().putNodeMetaData(IS_INSIDE_INSTANCEOF_EXPR, true); return this.configureAST( new BinaryExpression((Expression) this.visit(ctx.left), this.createGroovyToken(ctx.op), this.configureAST(new ClassExpression(this.visitType(ctx.type())), ctx.type())), ctx); case LE: case GE: case GT: case LT: case IN: case NOT_IN: { if (ctx.op.getType() == IN || ctx.op.getType() == NOT_IN ) { return this.createBinaryExpression(ctx.left, ctx.op, ctx.right, ctx); } return this.configureAST( this.createBinaryExpression(ctx.left, ctx.op, ctx.right), ctx); } default: throw createParsingFailedException("Unsupported relational expression: " + ctx.getText(), ctx); } } @Override public BinaryExpression visitEqualityExprAlt(EqualityExprAltContext ctx) { return this.configureAST( this.createBinaryExpression(ctx.left, ctx.op, ctx.right), ctx); } @Override public BinaryExpression visitRegexExprAlt(RegexExprAltContext ctx) { return this.configureAST( this.createBinaryExpression(ctx.left, ctx.op, ctx.right), ctx); } @Override public BinaryExpression visitAndExprAlt(AndExprAltContext ctx) { return this.createBinaryExpression(ctx.left, ctx.op, ctx.right, ctx); } @Override public BinaryExpression visitExclusiveOrExprAlt(ExclusiveOrExprAltContext ctx) { return this.createBinaryExpression(ctx.left, ctx.op, ctx.right, ctx); } @Override public BinaryExpression visitInclusiveOrExprAlt(InclusiveOrExprAltContext ctx) { return this.createBinaryExpression(ctx.left, ctx.op, ctx.right, ctx); } @Override public BinaryExpression visitLogicalAndExprAlt(LogicalAndExprAltContext ctx) { return this.configureAST( this.createBinaryExpression(ctx.left, ctx.op, ctx.right), ctx); } @Override public BinaryExpression visitLogicalOrExprAlt(LogicalOrExprAltContext ctx) { return this.configureAST( this.createBinaryExpression(ctx.left, ctx.op, ctx.right), ctx); } @Override public Expression visitConditionalExprAlt(ConditionalExprAltContext ctx) { ctx.fb.putNodeMetaData(IS_INSIDE_CONDITIONAL_EXPRESSION, true); if (asBoolean(ctx.ELVIS())) { // e.g. a == 6 ?: 0 return this.configureAST( new ElvisOperatorExpression((Expression) this.visit(ctx.con), (Expression) this.visit(ctx.fb)), ctx); } ctx.tb.putNodeMetaData(IS_INSIDE_CONDITIONAL_EXPRESSION, true); return this.configureAST( new TernaryExpression( this.configureAST(new BooleanExpression((Expression) this.visit(ctx.con)), ctx.con), (Expression) this.visit(ctx.tb), (Expression) this.visit(ctx.fb)), ctx); } @Override public BinaryExpression visitMultipleAssignmentExprAlt(MultipleAssignmentExprAltContext ctx) { return this.configureAST( new BinaryExpression( this.visitVariableNames(ctx.left), this.createGroovyToken(ctx.op), ((ExpressionStatement) this.visit(ctx.right)).getExpression()), ctx); } @Override public BinaryExpression visitAssignmentExprAlt(AssignmentExprAltContext ctx) { Expression leftExpr = (Expression) this.visit(ctx.left); if (leftExpr instanceof VariableExpression && isInsideParentheses(leftExpr)) { // it is a special multiple assignment whose variable count is only one, e.g. (a) = [1] if ((Integer) leftExpr.getNodeMetaData(INSIDE_PARENTHESES_LEVEL) > 1) { throw createParsingFailedException("Nested parenthesis is not allowed in multiple assignment, e.g. ((a)) = b", ctx); } return this.configureAST( new BinaryExpression( this.configureAST(new TupleExpression(leftExpr), ctx.left), this.createGroovyToken(ctx.op), this.visitEnhancedStatementExpression(ctx.enhancedStatementExpression())), ctx); } // the LHS expression should be a variable which is not inside any parentheses if ( !( (leftExpr instanceof VariableExpression // && !(THIS_STR.equals(leftExpr.getText()) || SUPER_STR.equals(leftExpr.getText())) // commented, e.g. this = value // this will be transformed to $this && !isInsideParentheses(leftExpr)) // e.g. p = 123 || leftExpr instanceof PropertyExpression // e.g. obj.p = 123 || (leftExpr instanceof BinaryExpression // && !(((BinaryExpression) leftExpr).getRightExpression() instanceof ListExpression) // commented, e.g. list[1, 2] = [11, 12] && Types.LEFT_SQUARE_BRACKET == ((BinaryExpression) leftExpr).getOperation().getType()) // e.g. map[a] = 123 OR map['a'] = 123 OR map["$a"] = 123 ) ) { throw createParsingFailedException("The LHS of an assignment should be a variable or a field accessing expression", ctx); } return this.configureAST( new BinaryExpression( leftExpr, this.createGroovyToken(ctx.op), this.visitEnhancedStatementExpression(ctx.enhancedStatementExpression())), ctx); } // } expression -------------------------------------------------------------------- // primary { -------------------------------------------------------------------- @Override public VariableExpression visitIdentifierPrmrAlt(IdentifierPrmrAltContext ctx) { return this.configureAST(new VariableExpression(this.visitIdentifier(ctx.identifier())), ctx); } @Override public ConstantExpression visitLiteralPrmrAlt(LiteralPrmrAltContext ctx) { return this.configureAST((ConstantExpression) this.visit(ctx.literal()), ctx); } @Override public GStringExpression visitGstringPrmrAlt(GstringPrmrAltContext ctx) { return this.configureAST((GStringExpression) this.visit(ctx.gstring()), ctx); } @Override public Expression visitNewPrmrAlt(NewPrmrAltContext ctx) { return this.configureAST(this.visitCreator(ctx.creator()), ctx); } @Override public VariableExpression visitThisPrmrAlt(ThisPrmrAltContext ctx) { return this.configureAST(new VariableExpression(ctx.THIS().getText()), ctx); } @Override public VariableExpression visitSuperPrmrAlt(SuperPrmrAltContext ctx) { return this.configureAST(new VariableExpression(ctx.SUPER().getText()), ctx); } @Override public Expression visitParenPrmrAlt(ParenPrmrAltContext ctx) { return this.configureAST(this.visitParExpression(ctx.parExpression()), ctx); } @Override public ClosureExpression visitClosurePrmrAlt(ClosurePrmrAltContext ctx) { return this.configureAST(this.visitClosure(ctx.closure()), ctx); } @Override public ClosureExpression visitLambdaPrmrAlt(LambdaPrmrAltContext ctx) { return this.configureAST(this.visitStandardLambdaExpression(ctx.standardLambdaExpression()), ctx); } @Override public ListExpression visitListPrmrAlt(ListPrmrAltContext ctx) { return this.configureAST( this.visitList(ctx.list()), ctx); } @Override public MapExpression visitMapPrmrAlt(MapPrmrAltContext ctx) { return this.configureAST(this.visitMap(ctx.map()), ctx); } @Override public VariableExpression visitTypePrmrAlt(TypePrmrAltContext ctx) { return this.configureAST( this.visitBuiltInType(ctx.builtInType()), ctx); } // } primary -------------------------------------------------------------------- @Override public Expression visitCreator(CreatorContext ctx) { ClassNode classNode = this.visitCreatedName(ctx.createdName()); Expression arguments = this.visitArguments(ctx.arguments()); if (asBoolean(ctx.arguments())) { // create instance of class if (asBoolean(ctx.anonymousInnerClassDeclaration())) { ctx.anonymousInnerClassDeclaration().putNodeMetaData(ANONYMOUS_INNER_CLASS_SUPER_CLASS, classNode); InnerClassNode anonymousInnerClassNode = this.visitAnonymousInnerClassDeclaration(ctx.anonymousInnerClassDeclaration()); List<InnerClassNode> anonymousInnerClassList = anonymousInnerClassesDefinedInMethodStack.peek(); if (null != anonymousInnerClassList) { // if the anonymous class is created in a script, no anonymousInnerClassList is available. anonymousInnerClassList.add(anonymousInnerClassNode); } ConstructorCallExpression constructorCallExpression = new ConstructorCallExpression(anonymousInnerClassNode, arguments); constructorCallExpression.setUsingAnonymousInnerClass(true); return this.configureAST(constructorCallExpression, ctx); } return this.configureAST( new ConstructorCallExpression(classNode, arguments), ctx); } if (asBoolean(ctx.LBRACK()) || asBoolean(ctx.dims())) { // create array ArrayExpression arrayExpression; List<List<AnnotationNode>> allDimList; if (asBoolean(ctx.arrayInitializer())) { ClassNode elementType = classNode; allDimList = this.visitDims(ctx.dims()); for (int i = 0, n = allDimList.size() - 1; i < n; i++) { elementType = elementType.makeArray(); } arrayExpression = new ArrayExpression( elementType, this.visitArrayInitializer(ctx.arrayInitializer())); } else { Expression[] empties; List<List<AnnotationNode>> emptyDimList = this.visitDimsOpt(ctx.dimsOpt()); if (asBoolean(emptyDimList)) { empties = new Expression[emptyDimList.size()]; Arrays.setAll(empties, i -> ConstantExpression.EMPTY_EXPRESSION); } else { empties = new Expression[0]; } arrayExpression = new ArrayExpression( classNode, null, Stream.concat( ctx.expression().stream() .map(e -> (Expression) this.visit(e)), Arrays.stream(empties) ).collect(Collectors.toList())); List<List<AnnotationNode>> exprDimList = ctx.annotationsOpt().stream().map(this::visitAnnotationsOpt).collect(Collectors.toList()); allDimList = new ArrayList<>(exprDimList); Collections.reverse(emptyDimList); allDimList.addAll(emptyDimList); Collections.reverse(allDimList); } arrayExpression.setType(createArrayType(classNode, allDimList)); return this.configureAST(arrayExpression, ctx); } throw createParsingFailedException("Unsupported creator: " + ctx.getText(), ctx); } private ClassNode createArrayType(ClassNode classNode, List<List<AnnotationNode>> dimList) { ClassNode arrayType = classNode; for (int i = 0, n = dimList.size(); i < n; i++) { arrayType = arrayType.makeArray(); arrayType.addAnnotations(dimList.get(i)); } return arrayType; } private String genAnonymousClassName(String outerClassName) { return outerClassName + "$" + this.anonymousInnerClassCounter++; } @Override public InnerClassNode visitAnonymousInnerClassDeclaration(AnonymousInnerClassDeclarationContext ctx) { ClassNode superClass = ctx.getNodeMetaData(ANONYMOUS_INNER_CLASS_SUPER_CLASS); Objects.requireNonNull(superClass, "superClass should not be null"); InnerClassNode anonymousInnerClass; ClassNode outerClass = this.classNodeStack.peek(); outerClass = asBoolean(outerClass) ? outerClass : moduleNode.getScriptClassDummy(); String fullName = this.genAnonymousClassName(outerClass.getName()); if (1 == ctx.t) { // anonymous enum anonymousInnerClass = new EnumConstantClassNode(outerClass, fullName, superClass.getModifiers() | Opcodes.ACC_FINAL, superClass.getPlainNodeReference()); // and remove the final modifier from classNode to allow the sub class superClass.setModifiers(superClass.getModifiers() & ~Opcodes.ACC_FINAL); } else { // anonymous inner class anonymousInnerClass = new InnerClassNode(outerClass, fullName, Opcodes.ACC_PUBLIC, superClass); } anonymousInnerClass.setUsingGenerics(false); anonymousInnerClass.setAnonymous(true); anonymousInnerClass.putNodeMetaData(CLASS_NAME, fullName); this.configureAST(anonymousInnerClass, ctx); classNodeStack.push(anonymousInnerClass); ctx.classBody().putNodeMetaData(CLASS_DECLARATION_CLASS_NODE, anonymousInnerClass); this.visitClassBody(ctx.classBody()); classNodeStack.pop(); classNodeList.add(anonymousInnerClass); return anonymousInnerClass; } @Override public ClassNode visitCreatedName(CreatedNameContext ctx) { ClassNode classNode = null; if (asBoolean(ctx.qualifiedClassName())) { classNode = this.visitQualifiedClassName(ctx.qualifiedClassName()); if (asBoolean(ctx.typeArgumentsOrDiamond())) { classNode.setGenericsTypes( this.visitTypeArgumentsOrDiamond(ctx.typeArgumentsOrDiamond())); } classNode = this.configureAST(classNode, ctx); } else if (asBoolean(ctx.primitiveType())) { classNode = this.configureAST( this.visitPrimitiveType(ctx.primitiveType()), ctx); } if (!asBoolean(classNode)) { throw createParsingFailedException("Unsupported created name: " + ctx.getText(), ctx); } classNode.addAnnotations(this.visitAnnotationsOpt(ctx.annotationsOpt())); return classNode; } @Override public MapExpression visitMap(MapContext ctx) { return this.configureAST( new MapExpression(this.visitMapEntryList(ctx.mapEntryList())), ctx); } @Override public List<MapEntryExpression> visitMapEntryList(MapEntryListContext ctx) { if (!asBoolean(ctx)) { return Collections.emptyList(); } return this.createMapEntryList(ctx.mapEntry()); } private List<MapEntryExpression> createMapEntryList(List<? extends MapEntryContext> mapEntryContextList) { if (!asBoolean(mapEntryContextList)) { return Collections.emptyList(); } return mapEntryContextList.stream() .map(this::visitMapEntry) .collect(Collectors.toList()); } @Override public MapEntryExpression visitMapEntry(MapEntryContext ctx) { Expression keyExpr; Expression valueExpr = (Expression) this.visit(ctx.expression()); if (asBoolean(ctx.MUL())) { keyExpr = this.configureAST(new SpreadMapExpression(valueExpr), ctx); } else if (asBoolean(ctx.mapEntryLabel())) { keyExpr = this.visitMapEntryLabel(ctx.mapEntryLabel()); } else { throw createParsingFailedException("Unsupported map entry: " + ctx.getText(), ctx); } return this.configureAST( new MapEntryExpression(keyExpr, valueExpr), ctx); } @Override public Expression visitMapEntryLabel(MapEntryLabelContext ctx) { if (asBoolean(ctx.keywords())) { return this.configureAST(this.visitKeywords(ctx.keywords()), ctx); } else if (asBoolean(ctx.primary())) { Expression expression = (Expression) this.visit(ctx.primary()); // if the key is variable and not inside parentheses, convert it to a constant, e.g. [a:1, b:2] if (expression instanceof VariableExpression && !isInsideParentheses(expression)) { expression = this.configureAST( new ConstantExpression(((VariableExpression) expression).getName()), expression); } return this.configureAST(expression, ctx); } throw createParsingFailedException("Unsupported map entry label: " + ctx.getText(), ctx); } @Override public ConstantExpression visitKeywords(KeywordsContext ctx) { return this.configureAST(new ConstantExpression(ctx.getText()), ctx); } /* @Override public VariableExpression visitIdentifier(IdentifierContext ctx) { return this.configureAST(new VariableExpression(ctx.getText()), ctx); } */ @Override public VariableExpression visitBuiltInType(BuiltInTypeContext ctx) { String text; if (asBoolean(ctx.VOID())) { text = ctx.VOID().getText(); } else if (asBoolean(ctx.BuiltInPrimitiveType())) { text = ctx.BuiltInPrimitiveType().getText(); } else { throw createParsingFailedException("Unsupported built-in type: " + ctx, ctx); } return this.configureAST(new VariableExpression(text), ctx); } @Override public ListExpression visitList(ListContext ctx) { return this.configureAST( new ListExpression( this.visitExpressionList(ctx.expressionList())), ctx); } @Override public List<Expression> visitExpressionList(ExpressionListContext ctx) { if (!asBoolean(ctx)) { return Collections.emptyList(); } return this.createExpressionList(ctx.expressionListElement()); } private List<Expression> createExpressionList(List<? extends ExpressionListElementContext> expressionListElementContextList) { if (!asBoolean(expressionListElementContextList)) { return Collections.emptyList(); } return expressionListElementContextList.stream() .map(this::visitExpressionListElement) .collect(Collectors.toList()); } @Override public Expression visitExpressionListElement(ExpressionListElementContext ctx) { Expression expression = (Expression) this.visit(ctx.expression()); if (asBoolean(ctx.MUL())) { return this.configureAST(new SpreadExpression(expression), ctx); } return this.configureAST(expression, ctx); } // literal { -------------------------------------------------------------------- @Override public ConstantExpression visitIntegerLiteralAlt(IntegerLiteralAltContext ctx) { String text = ctx.IntegerLiteral().getText(); ConstantExpression constantExpression = new ConstantExpression(Numbers.parseInteger(null, text), !text.startsWith(SUB_STR)); constantExpression.putNodeMetaData(IS_NUMERIC, true); constantExpression.putNodeMetaData(INTEGER_LITERAL_TEXT, text); return this.configureAST(constantExpression, ctx); } @Override public ConstantExpression visitFloatingPointLiteralAlt(FloatingPointLiteralAltContext ctx) { String text = ctx.FloatingPointLiteral().getText(); ConstantExpression constantExpression = new ConstantExpression(Numbers.parseDecimal(text), !text.startsWith(SUB_STR)); constantExpression.putNodeMetaData(IS_NUMERIC, true); constantExpression.putNodeMetaData(FLOATING_POINT_LITERAL_TEXT, text); return this.configureAST(constantExpression, ctx); } @Override public ConstantExpression visitStringLiteralAlt(StringLiteralAltContext ctx) { return this.configureAST( this.visitStringLiteral(ctx.stringLiteral()), ctx); } @Override public ConstantExpression visitBooleanLiteralAlt(BooleanLiteralAltContext ctx) { return this.configureAST(new ConstantExpression("true".equals(ctx.BooleanLiteral().getText()), true), ctx); } @Override public ConstantExpression visitNullLiteralAlt(NullLiteralAltContext ctx) { return this.configureAST(new ConstantExpression(null), ctx); } // } literal -------------------------------------------------------------------- // gstring { -------------------------------------------------------------------- @Override public GStringExpression visitGstring(GstringContext ctx) { List<ConstantExpression> strings = new LinkedList<>(); String begin = ctx.GStringBegin().getText(); final int slashyType = begin.startsWith("/") ? StringUtils.SLASHY : begin.startsWith("$/") ? StringUtils.DOLLAR_SLASHY : StringUtils.NONE_SLASHY; { String it = begin; if (it.startsWith("\"\"\"")) { it = StringUtils.removeCR(it); it = it.substring(2); // translate leading """ to " } else if (it.startsWith("$/")) { it = StringUtils.removeCR(it); it = "\"" + it.substring(2); // translate leading $/ to " } else if (it.startsWith("/")) { it = StringUtils.removeCR(it); } it = StringUtils.replaceEscapes(it, slashyType); it = (it.length() == 2) ? "" : StringGroovyMethods.getAt(it, new IntRange(true, 1, -2)); strings.add(this.configureAST(new ConstantExpression(it), ctx.GStringBegin())); } List<ConstantExpression> partStrings = ctx.GStringPart().stream() .map(e -> { String it = e.getText(); it = StringUtils.removeCR(it); it = StringUtils.replaceEscapes(it, slashyType); it = it.length() == 1 ? "" : StringGroovyMethods.getAt(it, new IntRange(true, 0, -2)); return this.configureAST(new ConstantExpression(it), e); }).collect(Collectors.toList()); strings.addAll(partStrings); { String it = ctx.GStringEnd().getText(); if (it.endsWith("\"\"\"")) { it = StringUtils.removeCR(it); it = StringGroovyMethods.getAt(it, new IntRange(true, 0, -3)); // translate tailing """ to " } else if (it.endsWith("/$")) { it = StringUtils.removeCR(it); it = StringGroovyMethods.getAt(it, new IntRange(false, 0, -2)) + "\""; // translate tailing /$ to " } else if (it.endsWith("/")) { it = StringUtils.removeCR(it); } it = StringUtils.replaceEscapes(it, slashyType); it = (it.length() == 1) ? "" : StringGroovyMethods.getAt(it, new IntRange(true, 0, -2)); strings.add(this.configureAST(new ConstantExpression(it), ctx.GStringEnd())); } List<Expression> values = ctx.gstringValue().stream() .map(e -> { Expression expression = this.visitGstringValue(e); if (expression instanceof ClosureExpression && !asBoolean(e.closure().ARROW())) { List<Statement> statementList = ((BlockStatement) ((ClosureExpression) expression).getCode()).getStatements(); if (statementList.stream().allMatch(x -> !asBoolean(x))) { return this.configureAST(new ConstantExpression(null), e); } return this.configureAST(new MethodCallExpression(expression, CALL_STR, new ArgumentListExpression()), e); } return expression; }) .collect(Collectors.toList()); StringBuilder verbatimText = new StringBuilder(ctx.getText().length()); for (int i = 0, n = strings.size(), s = values.size(); i < n; i++) { verbatimText.append(strings.get(i).getValue()); if (i == s) { continue; } Expression value = values.get(i); if (!asBoolean(value)) { continue; } verbatimText.append(DOLLAR_STR); verbatimText.append(value.getText()); } return this.configureAST(new GStringExpression(verbatimText.toString(), strings, values), ctx); } @Override public Expression visitGstringValue(GstringValueContext ctx) { if (asBoolean(ctx.gstringPath())) { return this.configureAST(this.visitGstringPath(ctx.gstringPath()), ctx); } if (asBoolean(ctx.LBRACE())) { if (asBoolean(ctx.statementExpression())) { return this.configureAST(((ExpressionStatement) this.visit(ctx.statementExpression())).getExpression(), ctx.statementExpression()); } else { // e.g. "${}" return this.configureAST(new ConstantExpression(null), ctx); } } if (asBoolean(ctx.closure())) { return this.configureAST(this.visitClosure(ctx.closure()), ctx); } throw createParsingFailedException("Unsupported gstring value: " + ctx.getText(), ctx); } @Override public Expression visitGstringPath(GstringPathContext ctx) { VariableExpression variableExpression = new VariableExpression(this.visitIdentifier(ctx.identifier())); if (asBoolean(ctx.GStringPathPart())) { Expression propertyExpression = ctx.GStringPathPart().stream() .map(e -> this.configureAST((Expression) new ConstantExpression(e.getText().substring(1)), e)) .reduce(this.configureAST(variableExpression, ctx.identifier()), (r, e) -> this.configureAST(new PropertyExpression(r, e), e)); return this.configureAST(propertyExpression, ctx); } return this.configureAST(variableExpression, ctx); } // } gstring -------------------------------------------------------------------- @Override public LambdaExpression visitStandardLambdaExpression(StandardLambdaExpressionContext ctx) { return this.configureAST(this.createLambda(ctx.standardLambdaParameters(), ctx.lambdaBody()), ctx); } private LambdaExpression createLambda(StandardLambdaParametersContext standardLambdaParametersContext, LambdaBodyContext lambdaBodyContext) { return new LambdaExpression( this.visitStandardLambdaParameters(standardLambdaParametersContext), this.visitLambdaBody(lambdaBodyContext)); } @Override public Parameter[] visitStandardLambdaParameters(StandardLambdaParametersContext ctx) { if (asBoolean(ctx.variableDeclaratorId())) { return new Parameter[]{ this.configureAST( new Parameter( ClassHelper.OBJECT_TYPE, this.visitVariableDeclaratorId(ctx.variableDeclaratorId()).getName() ), ctx.variableDeclaratorId() ) }; } Parameter[] parameters = this.visitFormalParameters(ctx.formalParameters()); if (0 == parameters.length) { return null; } return parameters; } @Override public Statement visitLambdaBody(LambdaBodyContext ctx) { if (asBoolean(ctx.statementExpression())) { return this.configureAST((ExpressionStatement) this.visit(ctx.statementExpression()), ctx); } if (asBoolean(ctx.block())) { return this.configureAST(this.visitBlock(ctx.block()), ctx); } throw createParsingFailedException("Unsupported lambda body: " + ctx.getText(), ctx); } @Override public ClosureExpression visitClosure(ClosureContext ctx) { Parameter[] parameters = asBoolean(ctx.formalParameterList()) ? this.visitFormalParameterList(ctx.formalParameterList()) : null; if (!asBoolean(ctx.ARROW())) { parameters = Parameter.EMPTY_ARRAY; } Statement code = this.visitBlockStatementsOpt(ctx.blockStatementsOpt()); return this.configureAST(new ClosureExpression(parameters, code), ctx); } @Override public Parameter[] visitFormalParameters(FormalParametersContext ctx) { if (!asBoolean(ctx)) { return new Parameter[0]; } return this.visitFormalParameterList(ctx.formalParameterList()); } @Override public Parameter[] visitFormalParameterList(FormalParameterListContext ctx) { if (!asBoolean(ctx)) { return new Parameter[0]; } List<Parameter> parameterList = new LinkedList<>(); if (asBoolean(ctx.thisFormalParameter())) { parameterList.add(this.visitThisFormalParameter(ctx.thisFormalParameter())); } if (asBoolean(ctx.formalParameter())) { parameterList.addAll( ctx.formalParameter().stream() .map(this::visitFormalParameter) .collect(Collectors.toList())); } if (asBoolean(ctx.lastFormalParameter())) { parameterList.add(this.visitLastFormalParameter(ctx.lastFormalParameter())); } validateParameterList(parameterList); return parameterList.toArray(new Parameter[0]); } private void validateParameterList(List<Parameter> parameterList) { for (int n = parameterList.size(), i = n - 1; i >= 0; i--) { Parameter parameter = parameterList.get(i); for (Parameter otherParameter : parameterList) { if (otherParameter == parameter) { continue; } if (otherParameter.getName().equals(parameter.getName())) { throw createParsingFailedException("Duplicated parameter '" + parameter.getName() + "' found.", parameter); } } } } @Override public Parameter visitFormalParameter(FormalParameterContext ctx) { return this.processFormalParameter(ctx, ctx.variableModifiersOpt(), ctx.type(), null, ctx.variableDeclaratorId(), ctx.expression()); } @Override public Parameter visitThisFormalParameter(ThisFormalParameterContext ctx) { return this.configureAST(new Parameter(this.visitType(ctx.type()), THIS_STR), ctx); } @Override public Parameter visitLastFormalParameter(LastFormalParameterContext ctx) { return this.processFormalParameter(ctx, ctx.variableModifiersOpt(), ctx.type(), ctx.ELLIPSIS(), ctx.variableDeclaratorId(), ctx.expression()); } @Override public List<ModifierNode> visitClassOrInterfaceModifiersOpt(ClassOrInterfaceModifiersOptContext ctx) { if (asBoolean(ctx.classOrInterfaceModifiers())) { return this.visitClassOrInterfaceModifiers(ctx.classOrInterfaceModifiers()); } return Collections.emptyList(); } @Override public List<ModifierNode> visitClassOrInterfaceModifiers(ClassOrInterfaceModifiersContext ctx) { return ctx.classOrInterfaceModifier().stream() .map(this::visitClassOrInterfaceModifier) .collect(Collectors.toList()); } @Override public ModifierNode visitClassOrInterfaceModifier(ClassOrInterfaceModifierContext ctx) { if (asBoolean(ctx.annotation())) { return this.configureAST(new ModifierNode(this.visitAnnotation(ctx.annotation()), ctx.getText()), ctx); } if (asBoolean(ctx.m)) { return this.configureAST(new ModifierNode(ctx.m.getType(), ctx.getText()), ctx); } throw createParsingFailedException("Unsupported class or interface modifier: " + ctx.getText(), ctx); } @Override public ModifierNode visitModifier(ModifierContext ctx) { if (asBoolean(ctx.classOrInterfaceModifier())) { return this.configureAST(this.visitClassOrInterfaceModifier(ctx.classOrInterfaceModifier()), ctx); } if (asBoolean(ctx.m)) { return this.configureAST(new ModifierNode(ctx.m.getType(), ctx.getText()), ctx); } throw createParsingFailedException("Unsupported modifier: " + ctx.getText(), ctx); } @Override public List<ModifierNode> visitModifiers(ModifiersContext ctx) { return ctx.modifier().stream() .map(this::visitModifier) .collect(Collectors.toList()); } @Override public List<ModifierNode> visitModifiersOpt(ModifiersOptContext ctx) { if (asBoolean(ctx.modifiers())) { return this.visitModifiers(ctx.modifiers()); } return Collections.emptyList(); } @Override public ModifierNode visitVariableModifier(VariableModifierContext ctx) { if (asBoolean(ctx.annotation())) { return this.configureAST(new ModifierNode(this.visitAnnotation(ctx.annotation()), ctx.getText()), ctx); } if (asBoolean(ctx.m)) { return this.configureAST(new ModifierNode(ctx.m.getType(), ctx.getText()), ctx); } throw createParsingFailedException("Unsupported variable modifier", ctx); } @Override public List<ModifierNode> visitVariableModifiersOpt(VariableModifiersOptContext ctx) { if (asBoolean(ctx.variableModifiers())) { return this.visitVariableModifiers(ctx.variableModifiers()); } return Collections.emptyList(); } @Override public List<ModifierNode> visitVariableModifiers(VariableModifiersContext ctx) { return ctx.variableModifier().stream() .map(this::visitVariableModifier) .collect(Collectors.toList()); } @Override public List<List<AnnotationNode>> visitDims(DimsContext ctx) { List<List<AnnotationNode>> dimList = ctx.annotationsOpt().stream() .map(this::visitAnnotationsOpt) .collect(Collectors.toList()); Collections.reverse(dimList); return dimList; } @Override public List<List<AnnotationNode>> visitDimsOpt(DimsOptContext ctx) { if (!asBoolean(ctx.dims())) { return Collections.emptyList(); } return this.visitDims(ctx.dims()); } // type { -------------------------------------------------------------------- @Override public ClassNode visitType(TypeContext ctx) { if (!asBoolean(ctx)) { return ClassHelper.OBJECT_TYPE; } ClassNode classNode = null; if (asBoolean(ctx.classOrInterfaceType())) { ctx.classOrInterfaceType().putNodeMetaData(IS_INSIDE_INSTANCEOF_EXPR, ctx.getNodeMetaData(IS_INSIDE_INSTANCEOF_EXPR)); classNode = this.visitClassOrInterfaceType(ctx.classOrInterfaceType()); } else if (asBoolean(ctx.primitiveType())) { classNode = this.visitPrimitiveType(ctx.primitiveType()); } if (!asBoolean(classNode)) { throw createParsingFailedException("Unsupported type: " + ctx.getText(), ctx); } classNode.addAnnotations(this.visitAnnotationsOpt(ctx.annotationsOpt())); List<List<AnnotationNode>> dimList = this.visitDimsOpt(ctx.dimsOpt()); if (asBoolean(dimList)) { // clear array's generics type info. Groovy's bug? array's generics type will be ignored. e.g. List<String>[]... p classNode.setGenericsTypes(null); classNode.setUsingGenerics(false); classNode = this.createArrayType(classNode, dimList); } return this.configureAST(classNode, ctx); } @Override public ClassNode visitClassOrInterfaceType(ClassOrInterfaceTypeContext ctx) { ClassNode classNode; if (asBoolean(ctx.qualifiedClassName())) { ctx.qualifiedClassName().putNodeMetaData(IS_INSIDE_INSTANCEOF_EXPR, ctx.getNodeMetaData(IS_INSIDE_INSTANCEOF_EXPR)); classNode = this.visitQualifiedClassName(ctx.qualifiedClassName()); } else { ctx.qualifiedStandardClassName().putNodeMetaData(IS_INSIDE_INSTANCEOF_EXPR, ctx.getNodeMetaData(IS_INSIDE_INSTANCEOF_EXPR)); classNode = this.visitQualifiedStandardClassName(ctx.qualifiedStandardClassName()); } if (asBoolean(ctx.typeArguments())) { classNode.setGenericsTypes( this.visitTypeArguments(ctx.typeArguments())); } return this.configureAST(classNode, ctx); } @Override public GenericsType[] visitTypeArgumentsOrDiamond(TypeArgumentsOrDiamondContext ctx) { if (asBoolean(ctx.typeArguments())) { return this.visitTypeArguments(ctx.typeArguments()); } if (asBoolean(ctx.LT())) { // e.g. <> return new GenericsType[0]; } throw createParsingFailedException("Unsupported type arguments or diamond: " + ctx.getText(), ctx); } @Override public GenericsType[] visitTypeArguments(TypeArgumentsContext ctx) { return ctx.typeArgument().stream().map(this::visitTypeArgument).toArray(GenericsType[]::new); } @Override public GenericsType visitTypeArgument(TypeArgumentContext ctx) { if (asBoolean(ctx.QUESTION())) { ClassNode baseType = this.configureAST(ClassHelper.makeWithoutCaching(QUESTION_STR), ctx.QUESTION()); baseType.addAnnotations(this.visitAnnotationsOpt(ctx.annotationsOpt())); if (!asBoolean(ctx.type())) { GenericsType genericsType = new GenericsType(baseType); genericsType.setWildcard(true); genericsType.setName(QUESTION_STR); return this.configureAST(genericsType, ctx); } ClassNode[] upperBounds = null; ClassNode lowerBound = null; ClassNode classNode = this.visitType(ctx.type()); if (asBoolean(ctx.EXTENDS())) { upperBounds = new ClassNode[]{classNode}; } else if (asBoolean(ctx.SUPER())) { lowerBound = classNode; } GenericsType genericsType = new GenericsType(baseType, upperBounds, lowerBound); genericsType.setWildcard(true); genericsType.setName(QUESTION_STR); return this.configureAST(genericsType, ctx); } else if (asBoolean(ctx.type())) { return this.configureAST( this.createGenericsType( this.visitType(ctx.type())), ctx); } throw createParsingFailedException("Unsupported type argument: " + ctx.getText(), ctx); } @Override public ClassNode visitPrimitiveType(PrimitiveTypeContext ctx) { return this.configureAST(ClassHelper.make(ctx.getText()), ctx); } // } type -------------------------------------------------------------------- @Override public VariableExpression visitVariableDeclaratorId(VariableDeclaratorIdContext ctx) { return this.configureAST(new VariableExpression(this.visitIdentifier(ctx.identifier())), ctx); } @Override public TupleExpression visitVariableNames(VariableNamesContext ctx) { return this.configureAST( new TupleExpression( ctx.variableDeclaratorId().stream() .map(this::visitVariableDeclaratorId) .collect(Collectors.toList()) ), ctx); } @Override public BlockStatement visitBlockStatementsOpt(BlockStatementsOptContext ctx) { if (asBoolean(ctx.blockStatements())) { return this.configureAST(this.visitBlockStatements(ctx.blockStatements()), ctx); } return this.configureAST(this.createBlockStatement(), ctx); } @Override public BlockStatement visitBlockStatements(BlockStatementsContext ctx) { return this.configureAST( this.createBlockStatement( ctx.blockStatement().stream() .map(this::visitBlockStatement) .filter(e -> asBoolean(e)) .collect(Collectors.toList())), ctx); } @Override public Statement visitBlockStatement(BlockStatementContext ctx) { if (asBoolean(ctx.localVariableDeclaration())) { return this.configureAST(this.visitLocalVariableDeclaration(ctx.localVariableDeclaration()), ctx); } if (asBoolean(ctx.statement())) { Object astNode = this.visit(ctx.statement()); //this.configureAST((Statement) this.visit(ctx.statement()), ctx); if (astNode instanceof MethodNode) { throw createParsingFailedException("Method definition not expected here", ctx); } else { return (Statement) astNode; } } throw createParsingFailedException("Unsupported block statement: " + ctx.getText(), ctx); } @Override public List<AnnotationNode> visitAnnotationsOpt(AnnotationsOptContext ctx) { if (!asBoolean(ctx)) { return Collections.emptyList(); } return ctx.annotation().stream() .map(this::visitAnnotation) .collect(Collectors.toList()); } @Override public AnnotationNode visitAnnotation(AnnotationContext ctx) { String annotationName = this.visitAnnotationName(ctx.annotationName()); AnnotationNode annotationNode = new AnnotationNode(ClassHelper.make(annotationName)); List<Pair<String, Expression>> annotationElementValues = this.visitElementValues(ctx.elementValues()); annotationElementValues.forEach(e -> annotationNode.addMember(e.getKey(), e.getValue())); return this.configureAST(annotationNode, ctx); } @Override public List<Pair<String, Expression>> visitElementValues(ElementValuesContext ctx) { if (!asBoolean(ctx)) { return Collections.emptyList(); } List<Pair<String, Expression>> annotationElementValues = new LinkedList<>(); if (asBoolean(ctx.elementValuePairs())) { this.visitElementValuePairs(ctx.elementValuePairs()).entrySet().forEach(e -> { annotationElementValues.add(new Pair<>(e.getKey(), e.getValue())); }); } else if (asBoolean(ctx.elementValue())) { annotationElementValues.add(new Pair<>(VALUE_STR, this.visitElementValue(ctx.elementValue()))); } return annotationElementValues; } @Override public String visitAnnotationName(AnnotationNameContext ctx) { return this.visitQualifiedClassName(ctx.qualifiedClassName()).getName(); } @Override public Map<String, Expression> visitElementValuePairs(ElementValuePairsContext ctx) { return ctx.elementValuePair().stream() .map(this::visitElementValuePair) .collect(Collectors.toMap( Pair::getKey, Pair::getValue, (k, v) -> { throw new IllegalStateException(String.format("Duplicate key %s", k)); }, LinkedHashMap::new )); } @Override public Pair<String, Expression> visitElementValuePair(ElementValuePairContext ctx) { return new Pair<>(ctx.elementValuePairName().getText(), this.visitElementValue(ctx.elementValue())); } @Override public Expression visitElementValue(ElementValueContext ctx) { if (asBoolean(ctx.expression())) { return this.configureAST((Expression) this.visit(ctx.expression()), ctx); } if (asBoolean(ctx.annotation())) { return this.configureAST(new AnnotationConstantExpression(this.visitAnnotation(ctx.annotation())), ctx); } if (asBoolean(ctx.elementValueArrayInitializer())) { return this.configureAST(this.visitElementValueArrayInitializer(ctx.elementValueArrayInitializer()), ctx); } throw createParsingFailedException("Unsupported element value: " + ctx.getText(), ctx); } @Override public ListExpression visitElementValueArrayInitializer(ElementValueArrayInitializerContext ctx) { return this.configureAST(new ListExpression(ctx.elementValue().stream().map(this::visitElementValue).collect(Collectors.toList())), ctx); } @Override public String visitClassName(ClassNameContext ctx) { String text = ctx.getText(); if (!text.contains("\\")) { return text; } return StringUtils.replaceHexEscapes(text); } @Override public String visitIdentifier(IdentifierContext ctx) { String text = ctx.getText(); if (!text.contains("\\")) { return text; } return StringUtils.replaceHexEscapes(text); } @Override public String visitQualifiedName(QualifiedNameContext ctx) { return ctx.qualifiedNameElement().stream() .map(ParseTree::getText) .collect(Collectors.joining(DOT_STR)); } @Override public ClassNode visitAnnotatedQualifiedClassName(AnnotatedQualifiedClassNameContext ctx) { ClassNode classNode = this.visitQualifiedClassName(ctx.qualifiedClassName()); classNode.addAnnotations(this.visitAnnotationsOpt(ctx.annotationsOpt())); return classNode; } @Override public ClassNode[] visitQualifiedClassNameList(QualifiedClassNameListContext ctx) { if (!asBoolean(ctx)) { return new ClassNode[0]; } return ctx.annotatedQualifiedClassName().stream() .map(this::visitAnnotatedQualifiedClassName) .toArray(ClassNode[]::new); } @Override public ClassNode visitQualifiedClassName(QualifiedClassNameContext ctx) { return this.createClassNode(ctx); } @Override public ClassNode visitQualifiedStandardClassName(QualifiedStandardClassNameContext ctx) { return this.createClassNode(ctx); } private ClassNode createClassNode(GroovyParserRuleContext ctx) { ClassNode result = ClassHelper.make(ctx.getText()); if (!isTrue(ctx, IS_INSIDE_INSTANCEOF_EXPR)) { // type in the "instanceof" expression should not have proxy to redirect to it result = this.proxyClassNode(result); } return this.configureAST(result, ctx); } private ClassNode proxyClassNode(ClassNode classNode) { if (!classNode.isUsingGenerics()) { return classNode; } ClassNode cn = ClassHelper.makeWithoutCaching(classNode.getName()); cn.setRedirect(classNode); return cn; } /** * Visit tree safely, no NPE occurred when the tree is null. * * @param tree an AST node * @return the visiting result */ @Override public Object visit(ParseTree tree) { if (!asBoolean(tree)) { return null; } return super.visit(tree); } // e.g. obj.a(1, 2) or obj.a 1, 2 private MethodCallExpression createMethodCallExpression(PropertyExpression propertyExpression, Expression arguments) { MethodCallExpression methodCallExpression = new MethodCallExpression( propertyExpression.getObjectExpression(), propertyExpression.getProperty(), arguments ); methodCallExpression.setImplicitThis(false); methodCallExpression.setSafe(propertyExpression.isSafe()); methodCallExpression.setSpreadSafe(propertyExpression.isSpreadSafe()); // method call obj*.m(): "safe"(false) and "spreadSafe"(true) // property access obj*.p: "safe"(true) and "spreadSafe"(true) // so we have to reset safe here. if (propertyExpression.isSpreadSafe()) { methodCallExpression.setSafe(false); } // if the generics types meta data is not empty, it is a generic method call, e.g. obj.<Integer>a(1, 2) methodCallExpression.setGenericsTypes( propertyExpression.getNodeMetaData(PATH_EXPRESSION_BASE_EXPR_GENERICS_TYPES)); return methodCallExpression; } // e.g. m(1, 2) or m 1, 2 private MethodCallExpression createMethodCallExpression(Expression baseExpr, Expression arguments) { MethodCallExpression methodCallExpression = new MethodCallExpression( VariableExpression.THIS_EXPRESSION, (baseExpr instanceof VariableExpression) ? this.createConstantExpression(baseExpr) : baseExpr, arguments ); return methodCallExpression; } private Parameter processFormalParameter(GroovyParserRuleContext ctx, VariableModifiersOptContext variableModifiersOptContext, TypeContext typeContext, TerminalNode ellipsis, VariableDeclaratorIdContext variableDeclaratorIdContext, ExpressionContext expressionContext) { ClassNode classNode = this.visitType(typeContext); if (asBoolean(ellipsis)) { classNode = this.configureAST(classNode.makeArray(), classNode); } Parameter parameter = new ModifierManager(this, this.visitVariableModifiersOpt(variableModifiersOptContext)) .processParameter( this.configureAST( new Parameter( classNode, this.visitVariableDeclaratorId(variableDeclaratorIdContext).getName() ), ctx ) ); if (asBoolean(expressionContext)) { parameter.setInitialExpression((Expression) this.visit(expressionContext)); } return parameter; } private Expression createPathExpression(Expression primaryExpr, List<? extends PathElementContext> pathElementContextList) { return (Expression) pathElementContextList.stream() .map(e -> (Object) e) .reduce(primaryExpr, (r, e) -> { PathElementContext pathElementContext = (PathElementContext) e; pathElementContext.putNodeMetaData(PATH_EXPRESSION_BASE_EXPR, r); return this.visitPathElement(pathElementContext); } ); } private GenericsType createGenericsType(ClassNode classNode) { return this.configureAST(new GenericsType(classNode), classNode); } private ConstantExpression createConstantExpression(Expression expression) { if (expression instanceof ConstantExpression) { return (ConstantExpression) expression; } return this.configureAST(new ConstantExpression(expression.getText()), expression); } private BinaryExpression createBinaryExpression(ExpressionContext left, Token op, ExpressionContext right) { return new BinaryExpression((Expression) this.visit(left), this.createGroovyToken(op), (Expression) this.visit(right)); } private BinaryExpression createBinaryExpression(ExpressionContext left, Token op, ExpressionContext right, ExpressionContext ctx) { BinaryExpression binaryExpression = this.createBinaryExpression(left, op, right); if (isTrue(ctx, IS_INSIDE_CONDITIONAL_EXPRESSION)) { return this.configureAST(binaryExpression, op); } return this.configureAST(binaryExpression, ctx); } private Statement unpackStatement(Statement statement) { if (statement instanceof DeclarationListStatement) { List<ExpressionStatement> expressionStatementList = ((DeclarationListStatement) statement).getDeclarationStatements(); if (1 == expressionStatementList.size()) { return expressionStatementList.get(0); } return this.configureAST(this.createBlockStatement(statement), statement); // if DeclarationListStatement contains more than 1 declarations, maybe it's better to create a block to hold them } return statement; } public BlockStatement createBlockStatement(Statement... statements) { return this.createBlockStatement(Arrays.asList(statements)); } private BlockStatement createBlockStatement(List<Statement> statementList) { return this.appendStatementsToBlockStatement(new BlockStatement(), statementList); } public BlockStatement appendStatementsToBlockStatement(BlockStatement bs, Statement... statements) { return this.appendStatementsToBlockStatement(bs, Arrays.asList(statements)); } private BlockStatement appendStatementsToBlockStatement(BlockStatement bs, List<Statement> statementList) { return (BlockStatement) statementList.stream() .reduce(bs, (r, e) -> { BlockStatement blockStatement = (BlockStatement) r; if (e instanceof DeclarationListStatement) { ((DeclarationListStatement) e).getDeclarationStatements().forEach(blockStatement::addStatement); } else { blockStatement.addStatement(e); } return blockStatement; }); } private boolean isAnnotationDeclaration(ClassNode classNode) { return asBoolean(classNode) && classNode.isAnnotationDefinition(); } private boolean isSyntheticPublic( boolean isAnnotationDeclaration, boolean isAnonymousInnerEnumDeclaration, boolean hasReturnType, ModifierManager modifierManager ) { return this.isSyntheticPublic( isAnnotationDeclaration, isAnonymousInnerEnumDeclaration, modifierManager.containsAnnotations(), modifierManager.containsVisibilityModifier(), modifierManager.containsNonVisibilityModifier(), hasReturnType, modifierManager.contains(DEF)); } /** * @param isAnnotationDeclaration whether the method is defined in an annotation * @param isAnonymousInnerEnumDeclaration whether the method is defined in an anonymous inner enum * @param hasAnnotation whether the method declaration has annotations * @param hasVisibilityModifier whether the method declaration contains visibility modifier(e.g. public, protected, private) * @param hasModifier whether the method declaration has modifier(e.g. visibility modifier, final, static and so on) * @param hasReturnType whether the method declaration has an return type(e.g. String, generic types) * @param hasDef whether the method declaration using def keyword * @return the result */ private boolean isSyntheticPublic( boolean isAnnotationDeclaration, boolean isAnonymousInnerEnumDeclaration, boolean hasAnnotation, boolean hasVisibilityModifier, boolean hasModifier, boolean hasReturnType, boolean hasDef) { if (hasVisibilityModifier) { return false; } if (isAnnotationDeclaration) { return true; } if (hasDef && hasReturnType) { return true; } if (hasModifier || hasAnnotation || !hasReturnType) { return true; } return isAnonymousInnerEnumDeclaration; } // the mixins of interface and annotation should be null private void hackMixins(ClassNode classNode) { try { // FIXME Hack with visibility. Field field = ClassNode.class.getDeclaredField("mixins"); field.setAccessible(true); field.set(classNode, null); } catch (IllegalAccessException | NoSuchFieldException e) { throw new GroovyBugError("Failed to access mixins field", e); } } private static final Map<ClassNode, Object> TYPE_DEFAULT_VALUE_MAP = Maps.of( ClassHelper.int_TYPE, 0, ClassHelper.long_TYPE, 0L, ClassHelper.double_TYPE, 0.0D, ClassHelper.float_TYPE, 0.0F, ClassHelper.short_TYPE, (short) 0, ClassHelper.byte_TYPE, (byte) 0, ClassHelper.char_TYPE, (char) 0, ClassHelper.boolean_TYPE, Boolean.FALSE ); private Object findDefaultValueByType(ClassNode type) { return TYPE_DEFAULT_VALUE_MAP.get(type); } private boolean isPackageInfoDeclaration() { String name = this.sourceUnit.getName(); return null != name && name.endsWith(PACKAGE_INFO_FILE_NAME); } private boolean isBlankScript(CompilationUnitContext ctx) { return moduleNode.getStatementBlock().isEmpty() && moduleNode.getMethods().isEmpty() && moduleNode.getClasses().isEmpty(); } private boolean isInsideParentheses(NodeMetaDataHandler nodeMetaDataHandler) { Integer insideParenLevel = nodeMetaDataHandler.getNodeMetaData(INSIDE_PARENTHESES_LEVEL); if (null != insideParenLevel) { return insideParenLevel > 0; } return false; } private void addEmptyReturnStatement() { moduleNode.addStatement(ReturnStatement.RETURN_NULL_OR_VOID); } private void addPackageInfoClassNode() { List<ClassNode> classNodeList = moduleNode.getClasses(); ClassNode packageInfoClassNode = ClassHelper.make(moduleNode.getPackageName() + PACKAGE_INFO); if (!classNodeList.contains(packageInfoClassNode)) { moduleNode.addClass(packageInfoClassNode); } } private org.codehaus.groovy.syntax.Token createGroovyTokenByType(Token token, int type) { if (null == token) { throw new IllegalArgumentException("token should not be null"); } return new org.codehaus.groovy.syntax.Token(type, token.getText(), token.getLine(), token.getCharPositionInLine()); } private org.codehaus.groovy.syntax.Token createGroovyToken(Token token) { return this.createGroovyToken(token, 1); } private org.codehaus.groovy.syntax.Token createGroovyToken(Token token, int cardinality) { String text = StringGroovyMethods.multiply((CharSequence) token.getText(), cardinality); return new org.codehaus.groovy.syntax.Token( "..<".equals(token.getText()) || "..".equals(token.getText()) ? Types.RANGE_OPERATOR : Types.lookup(text, Types.ANY), text, token.getLine(), token.getCharPositionInLine() + 1 ); } /* private org.codehaus.groovy.syntax.Token createGroovyToken(String text, int startLine, int startColumn) { return new org.codehaus.groovy.syntax.Token( Types.lookup(text, Types.ANY), text, startLine, startColumn ); } */ /** * set the script source position */ private void configureScriptClassNode() { ClassNode scriptClassNode = moduleNode.getScriptClassDummy(); if (!asBoolean(scriptClassNode)) { return; } List<Statement> statements = moduleNode.getStatementBlock().getStatements(); if (!statements.isEmpty()) { Statement firstStatement = statements.get(0); Statement lastStatement = statements.get(statements.size() - 1); scriptClassNode.setSourcePosition(firstStatement); scriptClassNode.setLastColumnNumber(lastStatement.getLastColumnNumber()); scriptClassNode.setLastLineNumber(lastStatement.getLastLineNumber()); } } /** * Sets location(lineNumber, colNumber, lastLineNumber, lastColumnNumber) for node using standard context information. * Note: this method is implemented to be closed over ASTNode. It returns same node as it received in arguments. * * @param astNode Node to be modified. * @param ctx Context from which information is obtained. * @return Modified astNode. */ private <T extends ASTNode> T configureAST(T astNode, GroovyParserRuleContext ctx) { Token start = ctx.getStart(); Token stop = ctx.getStop(); astNode.setLineNumber(start.getLine()); astNode.setColumnNumber(start.getCharPositionInLine() + 1); Pair<Integer, Integer> stopTokenEndPosition = endPosition(stop); astNode.setLastLineNumber(stopTokenEndPosition.getKey()); astNode.setLastColumnNumber(stopTokenEndPosition.getValue()); return astNode; } private Pair<Integer, Integer> endPosition(Token token) { String stopText = token.getText(); int stopTextLength = 0; int newLineCnt = 0; if (null != stopText) { stopTextLength = stopText.length(); newLineCnt = (int) StringUtils.countChar(stopText, '\n'); } if (0 == newLineCnt) { return new Pair<Integer, Integer>(token.getLine(), token.getCharPositionInLine() + 1 + token.getText().length()); } else { // e.g. GStringEnd contains newlines, we should fix the location info return new Pair<Integer, Integer>(token.getLine() + newLineCnt, stopTextLength - stopText.lastIndexOf('\n')); } } private <T extends ASTNode> T configureAST(T astNode, TerminalNode terminalNode) { return this.configureAST(astNode, terminalNode.getSymbol()); } private <T extends ASTNode> T configureAST(T astNode, Token token) { astNode.setLineNumber(token.getLine()); astNode.setColumnNumber(token.getCharPositionInLine() + 1); astNode.setLastLineNumber(token.getLine()); astNode.setLastColumnNumber(token.getCharPositionInLine() + 1 + token.getText().length()); return astNode; } private <T extends ASTNode> T configureAST(T astNode, ASTNode source) { astNode.setLineNumber(source.getLineNumber()); astNode.setColumnNumber(source.getColumnNumber()); astNode.setLastLineNumber(source.getLastLineNumber()); astNode.setLastColumnNumber(source.getLastColumnNumber()); return astNode; } private <T extends ASTNode> T configureAST(T astNode, GroovyParserRuleContext ctx, ASTNode stop) { Token start = ctx.getStart(); astNode.setLineNumber(start.getLine()); astNode.setColumnNumber(start.getCharPositionInLine() + 1); if (asBoolean(stop)) { astNode.setLastLineNumber(stop.getLastLineNumber()); astNode.setLastColumnNumber(stop.getLastColumnNumber()); } else { Pair<Integer, Integer> endPosition = endPosition(start); astNode.setLastLineNumber(endPosition.getKey()); astNode.setLastColumnNumber(endPosition.getValue()); } return astNode; } private <T extends ASTNode> T configureAST(T astNode, ASTNode start, ASTNode stop) { astNode.setLineNumber(start.getLineNumber()); astNode.setColumnNumber(start.getColumnNumber()); if (asBoolean(stop)) { astNode.setLastLineNumber(stop.getLastLineNumber()); astNode.setLastColumnNumber(stop.getLastColumnNumber()); } else { astNode.setLastLineNumber(start.getLastLineNumber()); astNode.setLastColumnNumber(start.getLastColumnNumber()); } return astNode; } private boolean isTrue(NodeMetaDataHandler nodeMetaDataHandler, String key) { Object nmd = nodeMetaDataHandler.getNodeMetaData(key); if (null == nmd) { return false; } if (!(nmd instanceof Boolean)) { throw new GroovyBugError(nodeMetaDataHandler + " node meta data[" + key + "] is not an instance of Boolean"); } return (Boolean) nmd; } private CompilationFailedException createParsingFailedException(String msg, GroovyParserRuleContext ctx) { return createParsingFailedException( new SyntaxException(msg, ctx.start.getLine(), ctx.start.getCharPositionInLine() + 1, ctx.stop.getLine(), ctx.stop.getCharPositionInLine() + 1 + ctx.stop.getText().length())); } public CompilationFailedException createParsingFailedException(String msg, ASTNode node) { Objects.requireNonNull(node, "node passed into createParsingFailedException should not be null"); return createParsingFailedException( new SyntaxException(msg, node.getLineNumber(), node.getColumnNumber(), node.getLastLineNumber(), node.getLastColumnNumber())); } /* private CompilationFailedException createParsingFailedException(String msg, Token token) { return createParsingFailedException( new SyntaxException(msg, token.getLine(), token.getCharPositionInLine() + 1, token.getLine(), token.getCharPositionInLine() + 1 + token.getText().length())); } */ private CompilationFailedException createParsingFailedException(Throwable t) { if (t instanceof SyntaxException) { this.collectSyntaxError((SyntaxException) t); } else if (t instanceof GroovySyntaxError) { GroovySyntaxError groovySyntaxError = (GroovySyntaxError) t; this.collectSyntaxError( new SyntaxException( groovySyntaxError.getMessage(), groovySyntaxError, groovySyntaxError.getLine(), groovySyntaxError.getColumn())); } else if (t instanceof Exception) { this.collectException((Exception) t); } return new CompilationFailedException( CompilePhase.PARSING.getPhaseNumber(), this.sourceUnit, t); } private void collectSyntaxError(SyntaxException e) { sourceUnit.getErrorCollector().addFatalError(new SyntaxErrorMessage(e, sourceUnit)); } private void collectException(Exception e) { sourceUnit.getErrorCollector().addException(e, this.sourceUnit); } private String readSourceCode(SourceUnit sourceUnit) { String text = null; try { text = IOGroovyMethods.getText(sourceUnit.getSource().getReader()); } catch (IOException e) { LOGGER.severe(createExceptionMessage(e)); throw new RuntimeException("Error occurred when reading source code.", e); } return text; } private ANTLRErrorListener createANTLRErrorListener() { return new ANTLRErrorListener() { @Override public void syntaxError( Recognizer recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) { collectSyntaxError(new SyntaxException(msg, line, charPositionInLine + 1)); } }; } private void removeErrorListeners() { lexer.removeErrorListeners(); parser.removeErrorListeners(); } private void addErrorListeners() { lexer.removeErrorListeners(); lexer.addErrorListener(this.createANTLRErrorListener()); parser.removeErrorListeners(); parser.addErrorListener(this.createANTLRErrorListener()); } private String createExceptionMessage(Throwable t) { StringWriter sw = new StringWriter(); try (PrintWriter pw = new PrintWriter(sw)) { t.printStackTrace(pw); } return sw.toString(); } private class DeclarationListStatement extends Statement { private List<ExpressionStatement> declarationStatements; public DeclarationListStatement(DeclarationExpression... declarations) { this(Arrays.asList(declarations)); } public DeclarationListStatement(List<DeclarationExpression> declarations) { this.declarationStatements = declarations.stream() .map(e -> configureAST(new ExpressionStatement(e), e)) .collect(Collectors.toList()); } public List<ExpressionStatement> getDeclarationStatements() { List<String> declarationListStatementLabels = this.getStatementLabels(); this.declarationStatements.forEach(e -> { if (null != declarationListStatementLabels) { // clear existing statement labels before setting labels if (null != e.getStatementLabels()) { e.getStatementLabels().clear(); } declarationListStatementLabels.forEach(e::addStatementLabel); } }); return this.declarationStatements; } public List<DeclarationExpression> getDeclarationExpressions() { return this.declarationStatements.stream() .map(e -> (DeclarationExpression) e.getExpression()) .collect(Collectors.toList()); } } private static class Pair<K, V> { private K key; private V value; public Pair(K key, V value) { this.key = key; this.value = value; } public K getKey() { return key; } public void setKey(K key) { this.key = key; } public V getValue() { return value; } public void setValue(V value) { this.value = value; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pair<?, ?> pair = (Pair<?, ?>) o; return Objects.equals(key, pair.key) && Objects.equals(value, pair.value); } @Override public int hashCode() { return Objects.hash(key, value); } } private final ModuleNode moduleNode; private final SourceUnit sourceUnit; private final ClassLoader classLoader; // Our ClassLoader, which provides information on external types private final GroovyLangLexer lexer; private final GroovyLangParser parser; private final TryWithResourcesASTTransformation tryWithResourcesASTTransformation; private final GroovydocManager groovydocManager; private final List<ClassNode> classNodeList = new LinkedList<>(); private final Deque<ClassNode> classNodeStack = new ArrayDeque<>(); private final Deque<List<InnerClassNode>> anonymousInnerClassesDefinedInMethodStack = new ArrayDeque<>(); private int anonymousInnerClassCounter = 1; private static final String QUESTION_STR = "?"; private static final String DOT_STR = "."; private static final String SUB_STR = "-"; private static final String ASSIGN_STR = "="; private static final String VALUE_STR = "value"; private static final String DOLLAR_STR = "$"; private static final String CALL_STR = "call"; private static final String THIS_STR = "this"; private static final String SUPER_STR = "super"; private static final String VOID_STR = "void"; private static final String PACKAGE_INFO = "package-info"; private static final String PACKAGE_INFO_FILE_NAME = PACKAGE_INFO + ".groovy"; private static final String GROOVY_TRANSFORM_TRAIT = "groovy.transform.Trait"; private static final Set<String> PRIMITIVE_TYPE_SET = Collections.unmodifiableSet(new HashSet<>(Arrays.asList("boolean", "char", "byte", "short", "int", "long", "float", "double"))); private static final Logger LOGGER = Logger.getLogger(AstBuilder.class.getName()); private static final String INSIDE_PARENTHESES_LEVEL = "_INSIDE_PARENTHESES_LEVEL"; private static final String IS_INSIDE_INSTANCEOF_EXPR = "_IS_INSIDE_INSTANCEOF_EXPR"; private static final String IS_SWITCH_DEFAULT = "_IS_SWITCH_DEFAULT"; private static final String IS_NUMERIC = "_IS_NUMERIC"; private static final String IS_STRING = "_IS_STRING"; private static final String IS_INTERFACE_WITH_DEFAULT_METHODS = "_IS_INTERFACE_WITH_DEFAULT_METHODS"; private static final String IS_INSIDE_CONDITIONAL_EXPRESSION = "_IS_INSIDE_CONDITIONAL_EXPRESSION"; private static final String PATH_EXPRESSION_BASE_EXPR = "_PATH_EXPRESSION_BASE_EXPR"; private static final String PATH_EXPRESSION_BASE_EXPR_GENERICS_TYPES = "_PATH_EXPRESSION_BASE_EXPR_GENERICS_TYPES"; private static final String CMD_EXPRESSION_BASE_EXPR = "_CMD_EXPRESSION_BASE_EXPR"; private static final String TYPE_DECLARATION_MODIFIERS = "_TYPE_DECLARATION_MODIFIERS"; private static final String CLASS_DECLARATION_CLASS_NODE = "_CLASS_DECLARATION_CLASS_NODE"; private static final String VARIABLE_DECLARATION_VARIABLE_TYPE = "_VARIABLE_DECLARATION_VARIABLE_TYPE"; private static final String ANONYMOUS_INNER_CLASS_SUPER_CLASS = "_ANONYMOUS_INNER_CLASS_SUPER_CLASS"; private static final String INTEGER_LITERAL_TEXT = "_INTEGER_LITERAL_TEXT"; private static final String FLOATING_POINT_LITERAL_TEXT = "_FLOATING_POINT_LITERAL_TEXT"; private static final String CLASS_NAME = "_CLASS_NAME"; }
src/main/java/org/apache/groovy/parser/antlr4/AstBuilder.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.groovy.parser.antlr4; import groovy.lang.IntRange; import org.antlr.v4.runtime.ANTLRErrorListener; import org.antlr.v4.runtime.ANTLRInputStream; import org.antlr.v4.runtime.CharStream; import org.antlr.v4.runtime.CommonTokenStream; import org.antlr.v4.runtime.RecognitionException; import org.antlr.v4.runtime.Recognizer; import org.antlr.v4.runtime.Token; import org.antlr.v4.runtime.atn.PredictionMode; import org.antlr.v4.runtime.misc.ParseCancellationException; import org.antlr.v4.runtime.tree.ParseTree; import org.antlr.v4.runtime.tree.TerminalNode; import org.apache.groovy.parser.antlr4.internal.AtnManager; import org.apache.groovy.parser.antlr4.internal.DescriptiveErrorStrategy; import org.apache.groovy.parser.antlr4.util.StringUtils; import org.apache.groovy.util.Maps; import org.codehaus.groovy.GroovyBugError; import org.codehaus.groovy.antlr.EnumHelper; import org.codehaus.groovy.ast.ASTNode; import org.codehaus.groovy.ast.AnnotationNode; import org.codehaus.groovy.ast.ClassHelper; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.ast.ConstructorNode; import org.codehaus.groovy.ast.EnumConstantClassNode; import org.codehaus.groovy.ast.FieldNode; import org.codehaus.groovy.ast.GenericsType; import org.codehaus.groovy.ast.ImportNode; import org.codehaus.groovy.ast.InnerClassNode; import org.codehaus.groovy.ast.MethodNode; import org.codehaus.groovy.ast.ModuleNode; import org.codehaus.groovy.ast.NodeMetaDataHandler; import org.codehaus.groovy.ast.PackageNode; import org.codehaus.groovy.ast.Parameter; import org.codehaus.groovy.ast.PropertyNode; import org.codehaus.groovy.ast.expr.AnnotationConstantExpression; import org.codehaus.groovy.ast.expr.ArgumentListExpression; import org.codehaus.groovy.ast.expr.ArrayExpression; import org.codehaus.groovy.ast.expr.AttributeExpression; import org.codehaus.groovy.ast.expr.BinaryExpression; import org.codehaus.groovy.ast.expr.BitwiseNegationExpression; import org.codehaus.groovy.ast.expr.BooleanExpression; import org.codehaus.groovy.ast.expr.CastExpression; import org.codehaus.groovy.ast.expr.ClassExpression; import org.codehaus.groovy.ast.expr.ClosureExpression; import org.codehaus.groovy.ast.expr.ClosureListExpression; import org.codehaus.groovy.ast.expr.ConstantExpression; import org.codehaus.groovy.ast.expr.ConstructorCallExpression; import org.codehaus.groovy.ast.expr.DeclarationExpression; import org.codehaus.groovy.ast.expr.ElvisOperatorExpression; import org.codehaus.groovy.ast.expr.EmptyExpression; import org.codehaus.groovy.ast.expr.Expression; import org.codehaus.groovy.ast.expr.GStringExpression; import org.codehaus.groovy.ast.expr.LambdaExpression; import org.codehaus.groovy.ast.expr.ListExpression; import org.codehaus.groovy.ast.expr.MapEntryExpression; import org.codehaus.groovy.ast.expr.MapExpression; import org.codehaus.groovy.ast.expr.MethodCallExpression; import org.codehaus.groovy.ast.expr.MethodPointerExpression; import org.codehaus.groovy.ast.expr.MethodReferenceExpression; import org.codehaus.groovy.ast.expr.NamedArgumentListExpression; import org.codehaus.groovy.ast.expr.NotExpression; import org.codehaus.groovy.ast.expr.PostfixExpression; import org.codehaus.groovy.ast.expr.PrefixExpression; import org.codehaus.groovy.ast.expr.PropertyExpression; import org.codehaus.groovy.ast.expr.RangeExpression; import org.codehaus.groovy.ast.expr.SpreadExpression; import org.codehaus.groovy.ast.expr.SpreadMapExpression; import org.codehaus.groovy.ast.expr.TernaryExpression; import org.codehaus.groovy.ast.expr.TupleExpression; import org.codehaus.groovy.ast.expr.UnaryMinusExpression; import org.codehaus.groovy.ast.expr.UnaryPlusExpression; import org.codehaus.groovy.ast.expr.VariableExpression; import org.codehaus.groovy.ast.stmt.AssertStatement; import org.codehaus.groovy.ast.stmt.BlockStatement; import org.codehaus.groovy.ast.stmt.BreakStatement; import org.codehaus.groovy.ast.stmt.CaseStatement; import org.codehaus.groovy.ast.stmt.CatchStatement; import org.codehaus.groovy.ast.stmt.ContinueStatement; import org.codehaus.groovy.ast.stmt.DoWhileStatement; import org.codehaus.groovy.ast.stmt.EmptyStatement; import org.codehaus.groovy.ast.stmt.ExpressionStatement; import org.codehaus.groovy.ast.stmt.ForStatement; import org.codehaus.groovy.ast.stmt.IfStatement; import org.codehaus.groovy.ast.stmt.ReturnStatement; import org.codehaus.groovy.ast.stmt.Statement; import org.codehaus.groovy.ast.stmt.SwitchStatement; import org.codehaus.groovy.ast.stmt.SynchronizedStatement; import org.codehaus.groovy.ast.stmt.ThrowStatement; import org.codehaus.groovy.ast.stmt.TryCatchStatement; import org.codehaus.groovy.ast.stmt.WhileStatement; import org.codehaus.groovy.control.CompilationFailedException; import org.codehaus.groovy.control.CompilePhase; import org.codehaus.groovy.control.SourceUnit; import org.codehaus.groovy.control.messages.SyntaxErrorMessage; import org.codehaus.groovy.runtime.IOGroovyMethods; import org.codehaus.groovy.runtime.StringGroovyMethods; import org.codehaus.groovy.syntax.Numbers; import org.codehaus.groovy.syntax.SyntaxException; import org.codehaus.groovy.syntax.Types; import org.objectweb.asm.Opcodes; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.reflect.Field; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Deque; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.logging.Logger; import java.util.stream.Collectors; import java.util.stream.Stream; import static org.apache.groovy.parser.antlr4.GroovyLangParser.*; import static org.codehaus.groovy.runtime.DefaultGroovyMethods.asBoolean; import static org.codehaus.groovy.runtime.DefaultGroovyMethods.last; /** * Building the AST from the parse tree generated by Antlr4 * * @author <a href="mailto:[email protected]">Daniel.Sun</a> * Created on 2016/08/14 */ public class AstBuilder extends GroovyParserBaseVisitor<Object> implements GroovyParserVisitor<Object> { public AstBuilder(SourceUnit sourceUnit, ClassLoader classLoader) { this.sourceUnit = sourceUnit; this.moduleNode = new ModuleNode(sourceUnit); this.classLoader = classLoader; // unused for the time being CharStream charStream = new ANTLRInputStream( this.readSourceCode(sourceUnit)); this.lexer = new GroovyLangLexer(charStream); this.parser = new GroovyLangParser( new CommonTokenStream(this.lexer)); this.parser.setErrorHandler(new DescriptiveErrorStrategy(charStream)); this.tryWithResourcesASTTransformation = new TryWithResourcesASTTransformation(this); this.groovydocManager = new GroovydocManager(this); } private GroovyParserRuleContext buildCST() { GroovyParserRuleContext result; // parsing have to wait util clearing is complete. AtnManager.RRWL.readLock().lock(); try { result = buildCST(PredictionMode.SLL); } catch (Throwable t) { // if some syntax error occurred in the lexer, no need to retry the powerful LL mode if (t instanceof GroovySyntaxError && GroovySyntaxError.LEXER == ((GroovySyntaxError) t).getSource()) { throw t; } result = buildCST(PredictionMode.LL); } finally { AtnManager.RRWL.readLock().unlock(); } return result; } private GroovyParserRuleContext buildCST(PredictionMode predictionMode) { parser.getInterpreter().setPredictionMode(predictionMode); if (PredictionMode.SLL.equals(predictionMode)) { this.removeErrorListeners(); } else { ((CommonTokenStream) parser.getInputStream()).reset(); this.addErrorListeners(); } return parser.compilationUnit(); } public ModuleNode buildAST() { try { return (ModuleNode) this.visit(this.buildCST()); } catch (Throwable t) { CompilationFailedException cfe; if (t instanceof CompilationFailedException) { cfe = (CompilationFailedException) t; } else if (t instanceof ParseCancellationException) { cfe = createParsingFailedException(t.getCause()); } else { cfe = createParsingFailedException(t); } // LOGGER.log(Level.SEVERE, "Failed to build AST", cfe); throw cfe; } } @Override public ModuleNode visitCompilationUnit(CompilationUnitContext ctx) { this.visit(ctx.packageDeclaration()); ctx.statement().stream() .map(this::visit) // .filter(e -> e instanceof Statement) .forEach(e -> { if (e instanceof DeclarationListStatement) { // local variable declaration ((DeclarationListStatement) e).getDeclarationStatements().forEach(moduleNode::addStatement); } else if (e instanceof Statement) { moduleNode.addStatement((Statement) e); } else if (e instanceof MethodNode) { // script method moduleNode.addMethod((MethodNode) e); } }); this.classNodeList.forEach(moduleNode::addClass); if (this.isPackageInfoDeclaration()) { this.addPackageInfoClassNode(); } else { // if groovy source file only contains blank(including EOF), add "return null" to the AST if (this.isBlankScript(ctx)) { this.addEmptyReturnStatement(); } } this.configureScriptClassNode(); return moduleNode; } @Override public PackageNode visitPackageDeclaration(PackageDeclarationContext ctx) { String packageName = this.visitQualifiedName(ctx.qualifiedName()); moduleNode.setPackageName(packageName + DOT_STR); PackageNode packageNode = moduleNode.getPackage(); packageNode.addAnnotations(this.visitAnnotationsOpt(ctx.annotationsOpt())); return this.configureAST(packageNode, ctx); } @Override public ImportNode visitImportDeclaration(ImportDeclarationContext ctx) { ImportNode importNode; boolean hasStatic = asBoolean(ctx.STATIC()); boolean hasStar = asBoolean(ctx.MUL()); boolean hasAlias = asBoolean(ctx.alias); List<AnnotationNode> annotationNodeList = this.visitAnnotationsOpt(ctx.annotationsOpt()); if (hasStatic) { if (hasStar) { // e.g. import static java.lang.Math.* String qualifiedName = this.visitQualifiedName(ctx.qualifiedName()); ClassNode type = ClassHelper.make(qualifiedName); this.configureAST(type, ctx); moduleNode.addStaticStarImport(type.getText(), type, annotationNodeList); importNode = last(moduleNode.getStaticStarImports().values()); } else { // e.g. import static java.lang.Math.pow List<GroovyParserRuleContext> identifierList = new LinkedList<>(ctx.qualifiedName().qualifiedNameElement()); int identifierListSize = identifierList.size(); String name = identifierList.get(identifierListSize - 1).getText(); ClassNode classNode = ClassHelper.make( identifierList.stream() .limit(identifierListSize - 1) .map(ParseTree::getText) .collect(Collectors.joining(DOT_STR))); String alias = hasAlias ? ctx.alias.getText() : name; this.configureAST(classNode, ctx); moduleNode.addStaticImport(classNode, name, alias, annotationNodeList); importNode = last(moduleNode.getStaticImports().values()); } } else { if (hasStar) { // e.g. import java.util.* String qualifiedName = this.visitQualifiedName(ctx.qualifiedName()); moduleNode.addStarImport(qualifiedName + DOT_STR, annotationNodeList); importNode = last(moduleNode.getStarImports()); } else { // e.g. import java.util.Map String qualifiedName = this.visitQualifiedName(ctx.qualifiedName()); String name = last(ctx.qualifiedName().qualifiedNameElement()).getText(); ClassNode classNode = ClassHelper.make(qualifiedName); String alias = hasAlias ? ctx.alias.getText() : name; this.configureAST(classNode, ctx); moduleNode.addImport(alias, classNode, annotationNodeList); importNode = last(moduleNode.getImports()); } } return this.configureAST(importNode, ctx); } // statement { -------------------------------------------------------------------- @Override public AssertStatement visitAssertStatement(AssertStatementContext ctx) { Expression conditionExpression = (Expression) this.visit(ctx.ce); if (conditionExpression instanceof BinaryExpression) { BinaryExpression binaryExpression = (BinaryExpression) conditionExpression; if (binaryExpression.getOperation().getType() == Types.ASSIGN) { throw createParsingFailedException("Assignment expression is not allowed in the assert statement", conditionExpression); } } BooleanExpression booleanExpression = this.configureAST( new BooleanExpression(conditionExpression), conditionExpression); if (!asBoolean(ctx.me)) { return this.configureAST( new AssertStatement(booleanExpression), ctx); } return this.configureAST(new AssertStatement(booleanExpression, (Expression) this.visit(ctx.me)), ctx); } @Override public AssertStatement visitAssertStmtAlt(AssertStmtAltContext ctx) { return this.configureAST(this.visitAssertStatement(ctx.assertStatement()), ctx); } @Override public IfStatement visitIfElseStmtAlt(IfElseStmtAltContext ctx) { Expression conditionExpression = this.visitExpressionInPar(ctx.expressionInPar()); BooleanExpression booleanExpression = this.configureAST( new BooleanExpression(conditionExpression), conditionExpression); Statement ifBlock = this.unpackStatement( (Statement) this.visit(ctx.tb)); Statement elseBlock = this.unpackStatement( asBoolean(ctx.ELSE()) ? (Statement) this.visit(ctx.fb) : EmptyStatement.INSTANCE); return this.configureAST(new IfStatement(booleanExpression, ifBlock, elseBlock), ctx); } @Override public Statement visitLoopStmtAlt(LoopStmtAltContext ctx) { return this.configureAST((Statement) this.visit(ctx.loopStatement()), ctx); } @Override public ForStatement visitForStmtAlt(ForStmtAltContext ctx) { Pair<Parameter, Expression> controlPair = this.visitForControl(ctx.forControl()); Statement loopBlock = this.unpackStatement((Statement) this.visit(ctx.statement())); return this.configureAST( new ForStatement(controlPair.getKey(), controlPair.getValue(), asBoolean(loopBlock) ? loopBlock : EmptyStatement.INSTANCE), ctx); } @Override public Pair<Parameter, Expression> visitForControl(ForControlContext ctx) { if (asBoolean(ctx.enhancedForControl())) { // e.g. for(int i in 0..<10) {} return this.visitEnhancedForControl(ctx.enhancedForControl()); } if (asBoolean(ctx.classicalForControl())) { // e.g. for(int i = 0; i < 10; i++) {} return this.visitClassicalForControl(ctx.classicalForControl()); } throw createParsingFailedException("Unsupported for control: " + ctx.getText(), ctx); } @Override public Expression visitForInit(ForInitContext ctx) { if (!asBoolean(ctx)) { return EmptyExpression.INSTANCE; } if (asBoolean(ctx.localVariableDeclaration())) { DeclarationListStatement declarationListStatement = this.visitLocalVariableDeclaration(ctx.localVariableDeclaration()); List<?> declarationExpressionList = declarationListStatement.getDeclarationExpressions(); if (declarationExpressionList.size() == 1) { return this.configureAST((Expression) declarationExpressionList.get(0), ctx); } else { return this.configureAST(new ClosureListExpression((List<Expression>) declarationExpressionList), ctx); } } if (asBoolean(ctx.expressionList())) { return this.translateExpressionList(ctx.expressionList()); } throw createParsingFailedException("Unsupported for init: " + ctx.getText(), ctx); } @Override public Expression visitForUpdate(ForUpdateContext ctx) { if (!asBoolean(ctx)) { return EmptyExpression.INSTANCE; } return this.translateExpressionList(ctx.expressionList()); } private Expression translateExpressionList(ExpressionListContext ctx) { List<Expression> expressionList = this.visitExpressionList(ctx); if (expressionList.size() == 1) { return this.configureAST(expressionList.get(0), ctx); } else { return this.configureAST(new ClosureListExpression(expressionList), ctx); } } @Override public Pair<Parameter, Expression> visitEnhancedForControl(EnhancedForControlContext ctx) { Parameter parameter = this.configureAST( new Parameter(this.visitType(ctx.type()), this.visitVariableDeclaratorId(ctx.variableDeclaratorId()).getName()), ctx.variableDeclaratorId()); // FIXME Groovy will ignore variableModifier of parameter in the for control // In order to make the new parser behave same with the old one, we do not process variableModifier* return new Pair<>(parameter, (Expression) this.visit(ctx.expression())); } @Override public Pair<Parameter, Expression> visitClassicalForControl(ClassicalForControlContext ctx) { ClosureListExpression closureListExpression = new ClosureListExpression(); closureListExpression.addExpression(this.visitForInit(ctx.forInit())); closureListExpression.addExpression(asBoolean(ctx.expression()) ? (Expression) this.visit(ctx.expression()) : EmptyExpression.INSTANCE); closureListExpression.addExpression(this.visitForUpdate(ctx.forUpdate())); return new Pair<>(ForStatement.FOR_LOOP_DUMMY, closureListExpression); } @Override public WhileStatement visitWhileStmtAlt(WhileStmtAltContext ctx) { Expression conditionExpression = this.visitExpressionInPar(ctx.expressionInPar()); BooleanExpression booleanExpression = this.configureAST( new BooleanExpression(conditionExpression), conditionExpression); Statement loopBlock = this.unpackStatement((Statement) this.visit(ctx.statement())); return this.configureAST( new WhileStatement(booleanExpression, asBoolean(loopBlock) ? loopBlock : EmptyStatement.INSTANCE), ctx); } @Override public DoWhileStatement visitDoWhileStmtAlt(DoWhileStmtAltContext ctx) { Expression conditionExpression = this.visitExpressionInPar(ctx.expressionInPar()); BooleanExpression booleanExpression = this.configureAST( new BooleanExpression(conditionExpression), conditionExpression ); Statement loopBlock = this.unpackStatement((Statement) this.visit(ctx.statement())); return this.configureAST( new DoWhileStatement(booleanExpression, asBoolean(loopBlock) ? loopBlock : EmptyStatement.INSTANCE), ctx); } @Override public Statement visitTryCatchStmtAlt(TryCatchStmtAltContext ctx) { return this.configureAST(this.visitTryCatchStatement(ctx.tryCatchStatement()), ctx); } @Override public Statement visitTryCatchStatement(TryCatchStatementContext ctx) { TryCatchStatement tryCatchStatement = new TryCatchStatement((Statement) this.visit(ctx.block()), this.visitFinallyBlock(ctx.finallyBlock())); if (asBoolean(ctx.resources())) { this.visitResources(ctx.resources()).forEach(tryCatchStatement::addResource); } ctx.catchClause().stream().map(this::visitCatchClause) .reduce(new LinkedList<CatchStatement>(), (r, e) -> { r.addAll(e); // merge several LinkedList<CatchStatement> instances into one LinkedList<CatchStatement> instance return r; }) .forEach(tryCatchStatement::addCatch); return this.configureAST( tryWithResourcesASTTransformation.transform( this.configureAST(tryCatchStatement, ctx)), ctx); } @Override public List<ExpressionStatement> visitResources(ResourcesContext ctx) { return this.visitResourceList(ctx.resourceList()); } @Override public List<ExpressionStatement> visitResourceList(ResourceListContext ctx) { return ctx.resource().stream().map(this::visitResource).collect(Collectors.toList()); } @Override public ExpressionStatement visitResource(ResourceContext ctx) { if (asBoolean(ctx.localVariableDeclaration())) { List<ExpressionStatement> declarationStatements = this.visitLocalVariableDeclaration(ctx.localVariableDeclaration()).getDeclarationStatements(); if (declarationStatements.size() > 1) { throw createParsingFailedException("Multi resources can not be declared in one statement", ctx); } return declarationStatements.get(0); } else if (asBoolean(ctx.expression())) { Expression expression = (Expression) this.visit(ctx.expression()); if (!(expression instanceof BinaryExpression && Types.ASSIGN == ((BinaryExpression) expression).getOperation().getType() && ((BinaryExpression) expression).getLeftExpression() instanceof VariableExpression)) { throw createParsingFailedException("Only variable declarations are allowed to declare resource", ctx); } BinaryExpression assignmentExpression = (BinaryExpression) expression; return this.configureAST( new ExpressionStatement( this.configureAST( new DeclarationExpression( this.configureAST( new VariableExpression(assignmentExpression.getLeftExpression().getText()), assignmentExpression.getLeftExpression() ), assignmentExpression.getOperation(), assignmentExpression.getRightExpression() ), ctx) ), ctx); } throw createParsingFailedException("Unsupported resource declaration: " + ctx.getText(), ctx); } /** * Multi-catch(1..*) clause will be unpacked to several normal catch clauses, so the return type is List * * @param ctx the parse tree * @return */ @Override public List<CatchStatement> visitCatchClause(CatchClauseContext ctx) { // FIXME Groovy will ignore variableModifier of parameter in the catch clause // In order to make the new parser behave same with the old one, we do not process variableModifier* return this.visitCatchType(ctx.catchType()).stream() .map(e -> this.configureAST( new CatchStatement( // FIXME The old parser does not set location info for the parameter of the catch clause. // we could make it better //this.configureAST(new Parameter(e, this.visitIdentifier(ctx.identifier())), ctx.Identifier()), new Parameter(e, this.visitIdentifier(ctx.identifier())), this.visitBlock(ctx.block())), ctx)) .collect(Collectors.toList()); } @Override public List<ClassNode> visitCatchType(CatchTypeContext ctx) { if (!asBoolean(ctx)) { return Collections.singletonList(ClassHelper.OBJECT_TYPE); } return ctx.qualifiedClassName().stream() .map(this::visitQualifiedClassName) .collect(Collectors.toList()); } @Override public Statement visitFinallyBlock(FinallyBlockContext ctx) { if (!asBoolean(ctx)) { return EmptyStatement.INSTANCE; } return this.configureAST( this.createBlockStatement((Statement) this.visit(ctx.block())), ctx); } @Override public SwitchStatement visitSwitchStmtAlt(SwitchStmtAltContext ctx) { return this.configureAST(this.visitSwitchStatement(ctx.switchStatement()), ctx); } public SwitchStatement visitSwitchStatement(SwitchStatementContext ctx) { List<Statement> statementList = ctx.switchBlockStatementGroup().stream() .map(this::visitSwitchBlockStatementGroup) .reduce(new LinkedList<>(), (r, e) -> { r.addAll(e); return r; }); List<CaseStatement> caseStatementList = new LinkedList<>(); List<Statement> defaultStatementList = new LinkedList<>(); statementList.forEach(e -> { if (e instanceof CaseStatement) { caseStatementList.add((CaseStatement) e); } else if (isTrue(e, IS_SWITCH_DEFAULT)) { defaultStatementList.add(e); } }); int defaultStatementListSize = defaultStatementList.size(); if (defaultStatementListSize > 1) { throw createParsingFailedException("switch statement should have only one default case, which should appear at last", defaultStatementList.get(0)); } if (defaultStatementListSize > 0 && last(statementList) instanceof CaseStatement) { throw createParsingFailedException("default case should appear at last", defaultStatementList.get(0)); } return this.configureAST( new SwitchStatement( this.visitExpressionInPar(ctx.expressionInPar()), caseStatementList, defaultStatementListSize == 0 ? EmptyStatement.INSTANCE : defaultStatementList.get(0) ), ctx); } @Override @SuppressWarnings({"unchecked"}) public List<Statement> visitSwitchBlockStatementGroup(SwitchBlockStatementGroupContext ctx) { int labelCnt = ctx.switchLabel().size(); List<Token> firstLabelHolder = new ArrayList<>(1); return (List<Statement>) ctx.switchLabel().stream() .map(e -> (Object) this.visitSwitchLabel(e)) .reduce(new ArrayList<Statement>(4), (r, e) -> { List<Statement> statementList = (List<Statement>) r; Pair<Token, Expression> pair = (Pair<Token, Expression>) e; boolean isLast = labelCnt - 1 == statementList.size(); switch (pair.getKey().getType()) { case CASE: { if (!asBoolean(statementList)) { firstLabelHolder.add(pair.getKey()); } statementList.add( this.configureAST( new CaseStatement( pair.getValue(), // check whether processing the last label. if yes, block statement should be attached. isLast ? this.visitBlockStatements(ctx.blockStatements()) : EmptyStatement.INSTANCE ), firstLabelHolder.get(0))); break; } case DEFAULT: { BlockStatement blockStatement = this.visitBlockStatements(ctx.blockStatements()); blockStatement.putNodeMetaData(IS_SWITCH_DEFAULT, true); statementList.add( // this.configureAST(blockStatement, pair.getKey()) blockStatement ); break; } } return statementList; }); } @Override public Pair<Token, Expression> visitSwitchLabel(SwitchLabelContext ctx) { if (asBoolean(ctx.CASE())) { return new Pair<>(ctx.CASE().getSymbol(), (Expression) this.visit(ctx.expression())); } else if (asBoolean(ctx.DEFAULT())) { return new Pair<>(ctx.DEFAULT().getSymbol(), EmptyExpression.INSTANCE); } throw createParsingFailedException("Unsupported switch label: " + ctx.getText(), ctx); } @Override public SynchronizedStatement visitSynchronizedStmtAlt(SynchronizedStmtAltContext ctx) { return this.configureAST( new SynchronizedStatement(this.visitExpressionInPar(ctx.expressionInPar()), this.visitBlock(ctx.block())), ctx); } @Override public ExpressionStatement visitExpressionStmtAlt(ExpressionStmtAltContext ctx) { return (ExpressionStatement) this.visit(ctx.statementExpression()); } @Override public ReturnStatement visitReturnStmtAlt(ReturnStmtAltContext ctx) { return this.configureAST(new ReturnStatement(asBoolean(ctx.expression()) ? (Expression) this.visit(ctx.expression()) : ConstantExpression.EMPTY_EXPRESSION), ctx); } @Override public ThrowStatement visitThrowStmtAlt(ThrowStmtAltContext ctx) { return this.configureAST( new ThrowStatement((Expression) this.visit(ctx.expression())), ctx); } @Override public Statement visitLabeledStmtAlt(LabeledStmtAltContext ctx) { Statement statement = (Statement) this.visit(ctx.statement()); statement.addStatementLabel(this.visitIdentifier(ctx.identifier())); return statement; // this.configureAST(statement, ctx); } @Override public BreakStatement visitBreakStatement(BreakStatementContext ctx) { String label = asBoolean(ctx.identifier()) ? this.visitIdentifier(ctx.identifier()) : null; return this.configureAST(new BreakStatement(label), ctx); } @Override public BreakStatement visitBreakStmtAlt(BreakStmtAltContext ctx) { return this.configureAST(this.visitBreakStatement(ctx.breakStatement()), ctx); } @Override public ContinueStatement visitContinueStatement(ContinueStatementContext ctx) { String label = asBoolean(ctx.identifier()) ? this.visitIdentifier(ctx.identifier()) : null; return this.configureAST(new ContinueStatement(label), ctx); } @Override public ContinueStatement visitContinueStmtAlt(ContinueStmtAltContext ctx) { return this.configureAST(this.visitContinueStatement(ctx.continueStatement()), ctx); } @Override public ImportNode visitImportStmtAlt(ImportStmtAltContext ctx) { return this.configureAST(this.visitImportDeclaration(ctx.importDeclaration()), ctx); } @Override public ClassNode visitTypeDeclarationStmtAlt(TypeDeclarationStmtAltContext ctx) { return this.configureAST(this.visitTypeDeclaration(ctx.typeDeclaration()), ctx); } @Override public Statement visitLocalVariableDeclarationStmtAlt(LocalVariableDeclarationStmtAltContext ctx) { return this.configureAST(this.visitLocalVariableDeclaration(ctx.localVariableDeclaration()), ctx); } @Override public MethodNode visitMethodDeclarationStmtAlt(MethodDeclarationStmtAltContext ctx) { return this.configureAST(this.visitMethodDeclaration(ctx.methodDeclaration()), ctx); } // } statement -------------------------------------------------------------------- @Override public ClassNode visitTypeDeclaration(TypeDeclarationContext ctx) { if (asBoolean(ctx.classDeclaration())) { // e.g. class A {} ctx.classDeclaration().putNodeMetaData(TYPE_DECLARATION_MODIFIERS, this.visitClassOrInterfaceModifiersOpt(ctx.classOrInterfaceModifiersOpt())); return this.configureAST(this.visitClassDeclaration(ctx.classDeclaration()), ctx); } throw createParsingFailedException("Unsupported type declaration: " + ctx.getText(), ctx); } private void initUsingGenerics(ClassNode classNode) { if (classNode.isUsingGenerics()) { return; } if (!classNode.isEnum()) { classNode.setUsingGenerics(classNode.getSuperClass().isUsingGenerics()); } if (!classNode.isUsingGenerics() && null != classNode.getInterfaces()) { for (ClassNode anInterface : classNode.getInterfaces()) { classNode.setUsingGenerics(classNode.isUsingGenerics() || anInterface.isUsingGenerics()); if (classNode.isUsingGenerics()) break; } } } @Override public ClassNode visitClassDeclaration(ClassDeclarationContext ctx) { String packageName = moduleNode.getPackageName(); packageName = null != packageName ? packageName : ""; List<ModifierNode> modifierNodeList = ctx.getNodeMetaData(TYPE_DECLARATION_MODIFIERS); Objects.requireNonNull(modifierNodeList, "modifierNodeList should not be null"); ModifierManager modifierManager = new ModifierManager(this, modifierNodeList); int modifiers = modifierManager.getClassModifiersOpValue(); boolean syntheticPublic = ((modifiers & Opcodes.ACC_SYNTHETIC) != 0); modifiers &= ~Opcodes.ACC_SYNTHETIC; final ClassNode outerClass = classNodeStack.peek(); ClassNode classNode; String className = this.visitIdentifier(ctx.identifier()); if (asBoolean(ctx.ENUM())) { classNode = EnumHelper.makeEnumNode( asBoolean(outerClass) ? className : packageName + className, modifiers, null, outerClass); } else { if (asBoolean(outerClass)) { classNode = new InnerClassNode( outerClass, outerClass.getName() + "$" + className, modifiers | (outerClass.isInterface() ? Opcodes.ACC_STATIC : 0), ClassHelper.OBJECT_TYPE); } else { classNode = new ClassNode( packageName + className, modifiers, ClassHelper.OBJECT_TYPE); } } this.configureAST(classNode, ctx); classNode.putNodeMetaData(CLASS_NAME, className); classNode.setSyntheticPublic(syntheticPublic); if (asBoolean(ctx.TRAIT())) { classNode.addAnnotation(new AnnotationNode(ClassHelper.make(GROOVY_TRANSFORM_TRAIT))); } classNode.addAnnotations(modifierManager.getAnnotations()); classNode.setGenericsTypes(this.visitTypeParameters(ctx.typeParameters())); boolean isInterface = asBoolean(ctx.INTERFACE()) && !asBoolean(ctx.AT()); boolean isInterfaceWithDefaultMethods = false; // declaring interface with default method if (isInterface && this.containsDefaultMethods(ctx)) { isInterfaceWithDefaultMethods = true; classNode.addAnnotation(new AnnotationNode(ClassHelper.make(GROOVY_TRANSFORM_TRAIT))); classNode.putNodeMetaData(IS_INTERFACE_WITH_DEFAULT_METHODS, true); } if (asBoolean(ctx.CLASS()) || asBoolean(ctx.TRAIT()) || isInterfaceWithDefaultMethods) { // class OR trait OR interface with default methods classNode.setSuperClass(this.visitType(ctx.sc)); classNode.setInterfaces(this.visitTypeList(ctx.is)); this.initUsingGenerics(classNode); } else if (isInterface) { // interface(NOT annotation) classNode.setModifiers(classNode.getModifiers() | Opcodes.ACC_INTERFACE | Opcodes.ACC_ABSTRACT); classNode.setSuperClass(ClassHelper.OBJECT_TYPE); classNode.setInterfaces(this.visitTypeList(ctx.scs)); this.initUsingGenerics(classNode); this.hackMixins(classNode); } else if (asBoolean(ctx.ENUM())) { // enum classNode.setModifiers(classNode.getModifiers() | Opcodes.ACC_ENUM | Opcodes.ACC_FINAL); classNode.setInterfaces(this.visitTypeList(ctx.is)); this.initUsingGenerics(classNode); } else if (asBoolean(ctx.AT())) { // annotation classNode.setModifiers(classNode.getModifiers() | Opcodes.ACC_INTERFACE | Opcodes.ACC_ABSTRACT | Opcodes.ACC_ANNOTATION); classNode.addInterface(ClassHelper.Annotation_TYPE); this.hackMixins(classNode); } else { throw createParsingFailedException("Unsupported class declaration: " + ctx.getText(), ctx); } // we put the class already in output to avoid the most inner classes // will be used as first class later in the loader. The first class // there determines what GCL#parseClass for example will return, so we // have here to ensure it won't be the inner class if (asBoolean(ctx.CLASS()) || asBoolean(ctx.TRAIT())) { classNodeList.add(classNode); } int oldAnonymousInnerClassCounter = this.anonymousInnerClassCounter; classNodeStack.push(classNode); ctx.classBody().putNodeMetaData(CLASS_DECLARATION_CLASS_NODE, classNode); this.visitClassBody(ctx.classBody()); classNodeStack.pop(); this.anonymousInnerClassCounter = oldAnonymousInnerClassCounter; if (!(asBoolean(ctx.CLASS()) || asBoolean(ctx.TRAIT()))) { classNodeList.add(classNode); } groovydocManager.handle(classNode, ctx); return classNode; } @SuppressWarnings({"unchecked"}) private boolean containsDefaultMethods(ClassDeclarationContext ctx) { List<MethodDeclarationContext> methodDeclarationContextList = (List<MethodDeclarationContext>) ctx.classBody().classBodyDeclaration().stream() .map(ClassBodyDeclarationContext::memberDeclaration) .filter(Objects::nonNull) .map(e -> (Object) e.methodDeclaration()) .filter(Objects::nonNull).reduce(new LinkedList<MethodDeclarationContext>(), (r, e) -> { MethodDeclarationContext methodDeclarationContext = (MethodDeclarationContext) e; if (createModifierManager(methodDeclarationContext).contains(DEFAULT)) { ((List) r).add(methodDeclarationContext); } return r; }); return !methodDeclarationContextList.isEmpty(); } @Override public Void visitClassBody(ClassBodyContext ctx) { ClassNode classNode = ctx.getNodeMetaData(CLASS_DECLARATION_CLASS_NODE); Objects.requireNonNull(classNode, "classNode should not be null"); if (asBoolean(ctx.enumConstants())) { ctx.enumConstants().putNodeMetaData(CLASS_DECLARATION_CLASS_NODE, classNode); this.visitEnumConstants(ctx.enumConstants()); } ctx.classBodyDeclaration().forEach(e -> { e.putNodeMetaData(CLASS_DECLARATION_CLASS_NODE, classNode); this.visitClassBodyDeclaration(e); }); return null; } @Override public List<FieldNode> visitEnumConstants(EnumConstantsContext ctx) { ClassNode classNode = ctx.getNodeMetaData(CLASS_DECLARATION_CLASS_NODE); Objects.requireNonNull(classNode, "classNode should not be null"); return ctx.enumConstant().stream() .map(e -> { e.putNodeMetaData(CLASS_DECLARATION_CLASS_NODE, classNode); return this.visitEnumConstant(e); }) .collect(Collectors.toList()); } @Override public FieldNode visitEnumConstant(EnumConstantContext ctx) { ClassNode classNode = ctx.getNodeMetaData(CLASS_DECLARATION_CLASS_NODE); Objects.requireNonNull(classNode, "classNode should not be null"); InnerClassNode anonymousInnerClassNode = null; if (asBoolean(ctx.anonymousInnerClassDeclaration())) { ctx.anonymousInnerClassDeclaration().putNodeMetaData(ANONYMOUS_INNER_CLASS_SUPER_CLASS, classNode); anonymousInnerClassNode = this.visitAnonymousInnerClassDeclaration(ctx.anonymousInnerClassDeclaration()); } FieldNode enumConstant = EnumHelper.addEnumConstant( classNode, this.visitIdentifier(ctx.identifier()), createEnumConstantInitExpression(ctx.arguments(), anonymousInnerClassNode)); enumConstant.addAnnotations(this.visitAnnotationsOpt(ctx.annotationsOpt())); groovydocManager.handle(enumConstant, ctx); return this.configureAST(enumConstant, ctx); } private Expression createEnumConstantInitExpression(ArgumentsContext ctx, InnerClassNode anonymousInnerClassNode) { if (!asBoolean(ctx) && !asBoolean(anonymousInnerClassNode)) { return null; } TupleExpression argumentListExpression = (TupleExpression) this.visitArguments(ctx); List<Expression> expressions = argumentListExpression.getExpressions(); if (expressions.size() == 1) { Expression expression = expressions.get(0); if (expression instanceof NamedArgumentListExpression) { // e.g. SOME_ENUM_CONSTANT(a: "1", b: "2") List<MapEntryExpression> mapEntryExpressionList = ((NamedArgumentListExpression) expression).getMapEntryExpressions(); ListExpression listExpression = new ListExpression( mapEntryExpressionList.stream() .map(e -> (Expression) e) .collect(Collectors.toList())); if (asBoolean(anonymousInnerClassNode)) { listExpression.addExpression( this.configureAST( new ClassExpression(anonymousInnerClassNode), anonymousInnerClassNode)); } if (mapEntryExpressionList.size() > 1) { listExpression.setWrapped(true); } return this.configureAST(listExpression, ctx); } if (!asBoolean(anonymousInnerClassNode)) { if (expression instanceof ListExpression) { ListExpression listExpression = new ListExpression(); listExpression.addExpression(expression); return this.configureAST(listExpression, ctx); } return expression; } ListExpression listExpression = new ListExpression(); if (expression instanceof ListExpression) { ((ListExpression) expression).getExpressions().forEach(listExpression::addExpression); } else { listExpression.addExpression(expression); } listExpression.addExpression( this.configureAST( new ClassExpression(anonymousInnerClassNode), anonymousInnerClassNode)); return this.configureAST(listExpression, ctx); } ListExpression listExpression = new ListExpression(expressions); if (asBoolean(anonymousInnerClassNode)) { listExpression.addExpression( this.configureAST( new ClassExpression(anonymousInnerClassNode), anonymousInnerClassNode)); } if (asBoolean(ctx)) { listExpression.setWrapped(true); } return asBoolean(ctx) ? this.configureAST(listExpression, ctx) : this.configureAST(listExpression, anonymousInnerClassNode); } @Override public Void visitClassBodyDeclaration(ClassBodyDeclarationContext ctx) { ClassNode classNode = ctx.getNodeMetaData(CLASS_DECLARATION_CLASS_NODE); Objects.requireNonNull(classNode, "classNode should not be null"); if (asBoolean(ctx.memberDeclaration())) { ctx.memberDeclaration().putNodeMetaData(CLASS_DECLARATION_CLASS_NODE, classNode); this.visitMemberDeclaration(ctx.memberDeclaration()); } else if (asBoolean(ctx.block())) { Statement statement = this.visitBlock(ctx.block()); if (asBoolean(ctx.STATIC())) { // e.g. static { } classNode.addStaticInitializerStatements(Collections.singletonList(statement), false); } else { // e.g. { } classNode.addObjectInitializerStatements( this.configureAST( this.createBlockStatement(statement), statement)); } } return null; } @Override public Void visitMemberDeclaration(MemberDeclarationContext ctx) { ClassNode classNode = ctx.getNodeMetaData(CLASS_DECLARATION_CLASS_NODE); Objects.requireNonNull(classNode, "classNode should not be null"); if (asBoolean(ctx.methodDeclaration())) { ctx.methodDeclaration().putNodeMetaData(CLASS_DECLARATION_CLASS_NODE, classNode); this.visitMethodDeclaration(ctx.methodDeclaration()); } else if (asBoolean(ctx.fieldDeclaration())) { ctx.fieldDeclaration().putNodeMetaData(CLASS_DECLARATION_CLASS_NODE, classNode); this.visitFieldDeclaration(ctx.fieldDeclaration()); } else if (asBoolean(ctx.classDeclaration())) { ctx.classDeclaration().putNodeMetaData(TYPE_DECLARATION_MODIFIERS, this.visitModifiersOpt(ctx.modifiersOpt())); ctx.classDeclaration().putNodeMetaData(CLASS_DECLARATION_CLASS_NODE, classNode); this.visitClassDeclaration(ctx.classDeclaration()); } return null; } @Override public GenericsType[] visitTypeParameters(TypeParametersContext ctx) { if (!asBoolean(ctx)) { return null; } return ctx.typeParameter().stream() .map(this::visitTypeParameter) .toArray(GenericsType[]::new); } @Override public GenericsType visitTypeParameter(TypeParameterContext ctx) { return this.configureAST( new GenericsType( this.configureAST(ClassHelper.make(this.visitClassName(ctx.className())), ctx), this.visitTypeBound(ctx.typeBound()), null ), ctx); } @Override public ClassNode[] visitTypeBound(TypeBoundContext ctx) { if (!asBoolean(ctx)) { return null; } return ctx.type().stream() .map(this::visitType) .toArray(ClassNode[]::new); } @Override public Void visitFieldDeclaration(FieldDeclarationContext ctx) { ClassNode classNode = ctx.getNodeMetaData(CLASS_DECLARATION_CLASS_NODE); Objects.requireNonNull(classNode, "classNode should not be null"); ctx.variableDeclaration().putNodeMetaData(CLASS_DECLARATION_CLASS_NODE, classNode); this.visitVariableDeclaration(ctx.variableDeclaration()); return null; } private ConstructorCallExpression checkThisAndSuperConstructorCall(Statement statement) { if (!(statement instanceof BlockStatement)) { // method code must be a BlockStatement return null; } BlockStatement blockStatement = (BlockStatement) statement; List<Statement> statementList = blockStatement.getStatements(); for (int i = 0, n = statementList.size(); i < n; i++) { Statement s = statementList.get(i); if (s instanceof ExpressionStatement) { Expression expression = ((ExpressionStatement) s).getExpression(); if ((expression instanceof ConstructorCallExpression) && 0 != i) { return (ConstructorCallExpression) expression; } } } return null; } private ModifierManager createModifierManager(MethodDeclarationContext ctx) { List<ModifierNode> modifierNodeList = Collections.emptyList(); if (asBoolean(ctx.modifiers())) { modifierNodeList = this.visitModifiers(ctx.modifiers()); } else if (asBoolean(ctx.modifiersOpt())) { modifierNodeList = this.visitModifiersOpt(ctx.modifiersOpt()); } return new ModifierManager(this, modifierNodeList); } private void validateParametersOfMethodDeclaration(Parameter[] parameters, ClassNode classNode) { if (!classNode.isInterface()) { return; } for (Parameter parameter : parameters) { if (parameter.hasInitialExpression()) { throw createParsingFailedException("Cannot specify default value for method parameter '" + parameter.getName() + " = " + parameter.getInitialExpression().getText() + "' inside an interface", parameter); } } } @Override public MethodNode visitMethodDeclaration(MethodDeclarationContext ctx) { ModifierManager modifierManager = createModifierManager(ctx); String methodName = this.visitMethodName(ctx.methodName()); ClassNode returnType = this.visitReturnType(ctx.returnType()); Parameter[] parameters = this.visitFormalParameters(ctx.formalParameters()); ClassNode[] exceptions = this.visitQualifiedClassNameList(ctx.qualifiedClassNameList()); anonymousInnerClassesDefinedInMethodStack.push(new LinkedList<>()); Statement code = this.visitMethodBody(ctx.methodBody()); List<InnerClassNode> anonymousInnerClassList = anonymousInnerClassesDefinedInMethodStack.pop(); MethodNode methodNode; // if classNode is not null, the method declaration is for class declaration ClassNode classNode = ctx.getNodeMetaData(CLASS_DECLARATION_CLASS_NODE); if (asBoolean(classNode)) { validateParametersOfMethodDeclaration(parameters, classNode); methodNode = createConstructorOrMethodNodeForClass(ctx, modifierManager, methodName, returnType, parameters, exceptions, code, classNode); } else { // script method declaration methodNode = createScriptMethodNode(modifierManager, methodName, returnType, parameters, exceptions, code); } anonymousInnerClassList.forEach(e -> e.setEnclosingMethod(methodNode)); methodNode.setGenericsTypes(this.visitTypeParameters(ctx.typeParameters())); methodNode.setSyntheticPublic( this.isSyntheticPublic( this.isAnnotationDeclaration(classNode), classNode instanceof EnumConstantClassNode, asBoolean(ctx.returnType()), modifierManager)); if (modifierManager.contains(STATIC)) { for (Parameter parameter : methodNode.getParameters()) { parameter.setInStaticContext(true); } methodNode.getVariableScope().setInStaticContext(true); } this.configureAST(methodNode, ctx); validateMethodDeclaration(ctx, methodNode, modifierManager, classNode); groovydocManager.handle(methodNode, ctx); return methodNode; } private void validateMethodDeclaration(MethodDeclarationContext ctx, MethodNode methodNode, ModifierManager modifierManager, ClassNode classNode) { boolean isAbstractMethod = methodNode.isAbstract(); boolean hasMethodBody = asBoolean(methodNode.getCode()); if (9 == ctx.ct) { // script if (isAbstractMethod || !hasMethodBody) { // method should not be declared abstract in the script throw createParsingFailedException("You can not define a " + (isAbstractMethod ? "abstract" : "") + " method[" + methodNode.getName() + "] " + (!hasMethodBody ? "without method body" : "") + " in the script. Try " + (isAbstractMethod ? "removing the 'abstract'" : "") + (isAbstractMethod && !hasMethodBody ? " and" : "") + (!hasMethodBody ? " adding a method body" : ""), methodNode); } } else { if (!isAbstractMethod && !hasMethodBody) { // non-abstract method without body in the non-script(e.g. class, enum, trait) is not allowed! throw createParsingFailedException("You defined a method[" + methodNode.getName() + "] without body. Try adding a method body, or declare it abstract", methodNode); } boolean isInterfaceOrAbstractClass = asBoolean(classNode) && classNode.isAbstract() && !classNode.isAnnotationDefinition(); if (isInterfaceOrAbstractClass && !modifierManager.contains(DEFAULT) && isAbstractMethod && hasMethodBody) { throw createParsingFailedException("You defined an abstract method[" + methodNode.getName() + "] with body. Try removing the method body" + (classNode.isInterface() ? ", or declare it default" : ""), methodNode); } } modifierManager.validate(methodNode); if (methodNode instanceof ConstructorNode) { modifierManager.validate((ConstructorNode) methodNode); } } private MethodNode createScriptMethodNode(ModifierManager modifierManager, String methodName, ClassNode returnType, Parameter[] parameters, ClassNode[] exceptions, Statement code) { MethodNode methodNode; methodNode = new MethodNode( methodName, modifierManager.contains(PRIVATE) ? Opcodes.ACC_PRIVATE : Opcodes.ACC_PUBLIC, returnType, parameters, exceptions, code); modifierManager.processMethodNode(methodNode); return methodNode; } private MethodNode createConstructorOrMethodNodeForClass(MethodDeclarationContext ctx, ModifierManager modifierManager, String methodName, ClassNode returnType, Parameter[] parameters, ClassNode[] exceptions, Statement code, ClassNode classNode) { MethodNode methodNode; String className = classNode.getNodeMetaData(CLASS_NAME); int modifiers = modifierManager.getClassMemberModifiersOpValue(); boolean hasReturnType = asBoolean(ctx.returnType()); boolean hasMethodBody = asBoolean(ctx.methodBody()); if (!hasReturnType && hasMethodBody && methodName.equals(className)) { // constructor declaration methodNode = createConstructorNodeForClass(methodName, parameters, exceptions, code, classNode, modifiers); } else { // class memeber method declaration if (!hasReturnType && hasMethodBody && (0 == modifierManager.getModifierCount())) { throw createParsingFailedException("Invalid method declaration: " + methodName, ctx); } methodNode = createMethodNodeForClass(ctx, modifierManager, methodName, returnType, parameters, exceptions, code, classNode, modifiers); } modifierManager.attachAnnotations(methodNode); return methodNode; } private MethodNode createMethodNodeForClass(MethodDeclarationContext ctx, ModifierManager modifierManager, String methodName, ClassNode returnType, Parameter[] parameters, ClassNode[] exceptions, Statement code, ClassNode classNode, int modifiers) { MethodNode methodNode; if (asBoolean(ctx.elementValue())) { // the code of annotation method code = this.configureAST( new ExpressionStatement( this.visitElementValue(ctx.elementValue())), ctx.elementValue()); } modifiers |= !modifierManager.contains(STATIC) && (classNode.isInterface() || (isTrue(classNode, IS_INTERFACE_WITH_DEFAULT_METHODS) && !modifierManager.contains(DEFAULT))) ? Opcodes.ACC_ABSTRACT : 0; checkWhetherMethodNodeWithSameSignatureExists(classNode, methodName, parameters, ctx); methodNode = classNode.addMethod(methodName, modifiers, returnType, parameters, exceptions, code); methodNode.setAnnotationDefault(asBoolean(ctx.elementValue())); return methodNode; } private void checkWhetherMethodNodeWithSameSignatureExists(ClassNode classNode, String methodName, Parameter[] parameters, MethodDeclarationContext ctx) { MethodNode sameSigMethodNode = classNode.getDeclaredMethod(methodName, parameters); if (null == sameSigMethodNode) { return; } throw createParsingFailedException("The method " + sameSigMethodNode.getText() + " duplicates another method of the same signature", ctx); } private ConstructorNode createConstructorNodeForClass(String methodName, Parameter[] parameters, ClassNode[] exceptions, Statement code, ClassNode classNode, int modifiers) { ConstructorCallExpression thisOrSuperConstructorCallExpression = this.checkThisAndSuperConstructorCall(code); if (asBoolean(thisOrSuperConstructorCallExpression)) { throw createParsingFailedException(thisOrSuperConstructorCallExpression.getText() + " should be the first statement in the constructor[" + methodName + "]", thisOrSuperConstructorCallExpression); } return classNode.addConstructor( modifiers, parameters, exceptions, code); } @Override public String visitMethodName(MethodNameContext ctx) { if (asBoolean(ctx.identifier())) { return this.visitIdentifier(ctx.identifier()); } if (asBoolean(ctx.stringLiteral())) { return this.visitStringLiteral(ctx.stringLiteral()).getText(); } throw createParsingFailedException("Unsupported method name: " + ctx.getText(), ctx); } @Override public ClassNode visitReturnType(ReturnTypeContext ctx) { if (!asBoolean(ctx)) { return ClassHelper.OBJECT_TYPE; } if (asBoolean(ctx.type())) { return this.visitType(ctx.type()); } if (asBoolean(ctx.VOID())) { return ClassHelper.VOID_TYPE; } throw createParsingFailedException("Unsupported return type: " + ctx.getText(), ctx); } @Override public Statement visitMethodBody(MethodBodyContext ctx) { if (!asBoolean(ctx)) { return null; } return this.configureAST(this.visitBlock(ctx.block()), ctx); } @Override public DeclarationListStatement visitLocalVariableDeclaration(LocalVariableDeclarationContext ctx) { return this.configureAST(this.visitVariableDeclaration(ctx.variableDeclaration()), ctx); } private ModifierManager createModifierManager(VariableDeclarationContext ctx) { List<ModifierNode> modifierNodeList = Collections.emptyList(); if (asBoolean(ctx.variableModifiers())) { modifierNodeList = this.visitVariableModifiers(ctx.variableModifiers()); } else if (asBoolean(ctx.variableModifiersOpt())) { modifierNodeList = this.visitVariableModifiersOpt(ctx.variableModifiersOpt()); } else if (asBoolean(ctx.modifiers())) { modifierNodeList = this.visitModifiers(ctx.modifiers()); } else if (asBoolean(ctx.modifiersOpt())) { modifierNodeList = this.visitModifiersOpt(ctx.modifiersOpt()); } return new ModifierManager(this, modifierNodeList); } private DeclarationListStatement createMultiAssignmentDeclarationListStatement(VariableDeclarationContext ctx, ModifierManager modifierManager) { if (!modifierManager.contains(DEF)) { throw createParsingFailedException("keyword def is required to declare tuple, e.g. def (int a, int b) = [1, 2]", ctx); } return this.configureAST( new DeclarationListStatement( this.configureAST( modifierManager.attachAnnotations( new DeclarationExpression( new ArgumentListExpression( this.visitTypeNamePairs(ctx.typeNamePairs()).stream() .peek(e -> modifierManager.processVariableExpression((VariableExpression) e)) .collect(Collectors.toList()) ), this.createGroovyTokenByType(ctx.ASSIGN().getSymbol(), Types.ASSIGN), this.visitVariableInitializer(ctx.variableInitializer()) ) ), ctx ) ), ctx ); } @Override public DeclarationListStatement visitVariableDeclaration(VariableDeclarationContext ctx) { ModifierManager modifierManager = this.createModifierManager(ctx); if (asBoolean(ctx.typeNamePairs())) { // e.g. def (int a, int b) = [1, 2] return this.createMultiAssignmentDeclarationListStatement(ctx, modifierManager); } ClassNode variableType = this.visitType(ctx.type()); ctx.variableDeclarators().putNodeMetaData(VARIABLE_DECLARATION_VARIABLE_TYPE, variableType); List<DeclarationExpression> declarationExpressionList = this.visitVariableDeclarators(ctx.variableDeclarators()); // if classNode is not null, the variable declaration is for class declaration. In other words, it is a field declaration ClassNode classNode = ctx.getNodeMetaData(CLASS_DECLARATION_CLASS_NODE); if (asBoolean(classNode)) { return createFieldDeclarationListStatement(ctx, modifierManager, variableType, declarationExpressionList, classNode); } declarationExpressionList.forEach(e -> { VariableExpression variableExpression = (VariableExpression) e.getLeftExpression(); modifierManager.processVariableExpression(variableExpression); modifierManager.attachAnnotations(e); }); int size = declarationExpressionList.size(); if (size > 0) { DeclarationExpression declarationExpression = declarationExpressionList.get(0); if (1 == size) { this.configureAST(declarationExpression, ctx); } else { // Tweak start of first declaration declarationExpression.setLineNumber(ctx.getStart().getLine()); declarationExpression.setColumnNumber(ctx.getStart().getCharPositionInLine() + 1); } } return this.configureAST(new DeclarationListStatement(declarationExpressionList), ctx); } private DeclarationListStatement createFieldDeclarationListStatement(VariableDeclarationContext ctx, ModifierManager modifierManager, ClassNode variableType, List<DeclarationExpression> declarationExpressionList, ClassNode classNode) { for (int i = 0, n = declarationExpressionList.size(); i < n; i++) { DeclarationExpression declarationExpression = declarationExpressionList.get(i); VariableExpression variableExpression = (VariableExpression) declarationExpression.getLeftExpression(); String fieldName = variableExpression.getName(); int modifiers = modifierManager.getClassMemberModifiersOpValue(); Expression initialValue = EmptyExpression.INSTANCE.equals(declarationExpression.getRightExpression()) ? null : declarationExpression.getRightExpression(); Object defaultValue = findDefaultValueByType(variableType); if (classNode.isInterface()) { if (!asBoolean(initialValue)) { initialValue = !asBoolean(defaultValue) ? null : new ConstantExpression(defaultValue); } modifiers |= Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC | Opcodes.ACC_FINAL; } if (isFieldDeclaration(modifierManager, classNode)) { declareField(ctx, modifierManager, variableType, classNode, i, variableExpression, fieldName, modifiers, initialValue); } else { declareProperty(ctx, modifierManager, variableType, classNode, i, variableExpression, fieldName, modifiers, initialValue); } } return null; } private void declareProperty(VariableDeclarationContext ctx, ModifierManager modifierManager, ClassNode variableType, ClassNode classNode, int i, VariableExpression variableExpression, String fieldName, int modifiers, Expression initialValue) { if (classNode.hasProperty(fieldName)) { throw createParsingFailedException("The property '" + fieldName + "' is declared multiple times", ctx); } PropertyNode propertyNode; FieldNode fieldNode = classNode.getDeclaredField(fieldName); if (fieldNode != null && !classNode.hasProperty(fieldName)) { classNode.getFields().remove(fieldNode); propertyNode = new PropertyNode(fieldNode, modifiers | Opcodes.ACC_PUBLIC, null, null); classNode.addProperty(propertyNode); } else { propertyNode = classNode.addProperty( fieldName, modifiers | Opcodes.ACC_PUBLIC, variableType, initialValue, null, null); fieldNode = propertyNode.getField(); } fieldNode.setModifiers(modifiers & ~Opcodes.ACC_PUBLIC | Opcodes.ACC_PRIVATE); fieldNode.setSynthetic(!classNode.isInterface()); modifierManager.attachAnnotations(fieldNode); groovydocManager.handle(fieldNode, ctx); groovydocManager.handle(propertyNode, ctx); if (0 == i) { this.configureAST(fieldNode, ctx, initialValue); this.configureAST(propertyNode, ctx, initialValue); } else { this.configureAST(fieldNode, variableExpression, initialValue); this.configureAST(propertyNode, variableExpression, initialValue); } } private void declareField(VariableDeclarationContext ctx, ModifierManager modifierManager, ClassNode variableType, ClassNode classNode, int i, VariableExpression variableExpression, String fieldName, int modifiers, Expression initialValue) { FieldNode existingFieldNode = classNode.getDeclaredField(fieldName); if (null != existingFieldNode && !existingFieldNode.isSynthetic()) { throw createParsingFailedException("The field '" + fieldName + "' is declared multiple times", ctx); } FieldNode fieldNode; PropertyNode propertyNode = classNode.getProperty(fieldName); if (null != propertyNode && propertyNode.getField().isSynthetic()) { classNode.getFields().remove(propertyNode.getField()); fieldNode = new FieldNode(fieldName, modifiers, variableType, classNode.redirect(), initialValue); propertyNode.setField(fieldNode); classNode.addField(fieldNode); } else { fieldNode = classNode.addField( fieldName, modifiers, variableType, initialValue); } modifierManager.attachAnnotations(fieldNode); groovydocManager.handle(fieldNode, ctx); if (0 == i) { this.configureAST(fieldNode, ctx, initialValue); } else { this.configureAST(fieldNode, variableExpression, initialValue); } } private boolean isFieldDeclaration(ModifierManager modifierManager, ClassNode classNode) { return classNode.isInterface() || modifierManager.containsVisibilityModifier(); } @Override public List<Expression> visitTypeNamePairs(TypeNamePairsContext ctx) { return ctx.typeNamePair().stream().map(this::visitTypeNamePair).collect(Collectors.toList()); } @Override public VariableExpression visitTypeNamePair(TypeNamePairContext ctx) { return this.configureAST( new VariableExpression( this.visitVariableDeclaratorId(ctx.variableDeclaratorId()).getName(), this.visitType(ctx.type())), ctx); } @Override public List<DeclarationExpression> visitVariableDeclarators(VariableDeclaratorsContext ctx) { ClassNode variableType = ctx.getNodeMetaData(VARIABLE_DECLARATION_VARIABLE_TYPE); Objects.requireNonNull(variableType, "variableType should not be null"); return ctx.variableDeclarator().stream() .map(e -> { e.putNodeMetaData(VARIABLE_DECLARATION_VARIABLE_TYPE, variableType); return this.visitVariableDeclarator(e); // return this.configureAST(this.visitVariableDeclarator(e), ctx); }) .collect(Collectors.toList()); } @Override public DeclarationExpression visitVariableDeclarator(VariableDeclaratorContext ctx) { ClassNode variableType = ctx.getNodeMetaData(VARIABLE_DECLARATION_VARIABLE_TYPE); Objects.requireNonNull(variableType, "variableType should not be null"); org.codehaus.groovy.syntax.Token token; if (asBoolean(ctx.ASSIGN())) { token = createGroovyTokenByType(ctx.ASSIGN().getSymbol(), Types.ASSIGN); } else { token = new org.codehaus.groovy.syntax.Token(Types.ASSIGN, ASSIGN_STR, ctx.start.getLine(), 1); } return this.configureAST( new DeclarationExpression( this.configureAST( new VariableExpression( this.visitVariableDeclaratorId(ctx.variableDeclaratorId()).getName(), variableType ), ctx.variableDeclaratorId()), token, this.visitVariableInitializer(ctx.variableInitializer())), ctx); } @Override public Expression visitVariableInitializer(VariableInitializerContext ctx) { if (!asBoolean(ctx)) { return EmptyExpression.INSTANCE; } return this.configureAST( this.visitEnhancedStatementExpression(ctx.enhancedStatementExpression()), ctx); } @Override public List<Expression> visitVariableInitializers(VariableInitializersContext ctx) { if (!asBoolean(ctx)) { return Collections.emptyList(); } return ctx.variableInitializer().stream() .map(this::visitVariableInitializer) .collect(Collectors.toList()); } @Override public List<Expression> visitArrayInitializer(ArrayInitializerContext ctx) { if (!asBoolean(ctx)) { return Collections.emptyList(); } return this.visitVariableInitializers(ctx.variableInitializers()); } @Override public Statement visitBlock(BlockContext ctx) { if (!asBoolean(ctx)) { return this.createBlockStatement(); } return this.configureAST( this.visitBlockStatementsOpt(ctx.blockStatementsOpt()), ctx); } @Override public ExpressionStatement visitNormalExprAlt(NormalExprAltContext ctx) { return this.configureAST(new ExpressionStatement((Expression) this.visit(ctx.expression())), ctx); } @Override public ExpressionStatement visitCommandExprAlt(CommandExprAltContext ctx) { return this.configureAST(new ExpressionStatement(this.visitCommandExpression(ctx.commandExpression())), ctx); } @Override public Expression visitCommandExpression(CommandExpressionContext ctx) { Expression baseExpr = this.visitPathExpression(ctx.pathExpression()); Expression arguments = this.visitEnhancedArgumentList(ctx.enhancedArgumentList()); MethodCallExpression methodCallExpression; if (baseExpr instanceof PropertyExpression) { // e.g. obj.a 1, 2 methodCallExpression = this.configureAST( this.createMethodCallExpression( (PropertyExpression) baseExpr, arguments), arguments); } else if (baseExpr instanceof MethodCallExpression && !isInsideParentheses(baseExpr)) { // e.g. m {} a, b OR m(...) a, b if (asBoolean(arguments)) { // The error should never be thrown. throw new GroovyBugError("When baseExpr is a instance of MethodCallExpression, which should follow NO argumentList"); } methodCallExpression = (MethodCallExpression) baseExpr; } else if ( !isInsideParentheses(baseExpr) && (baseExpr instanceof VariableExpression /* e.g. m 1, 2 */ || baseExpr instanceof GStringExpression /* e.g. "$m" 1, 2 */ || (baseExpr instanceof ConstantExpression && isTrue(baseExpr, IS_STRING)) /* e.g. "m" 1, 2 */) ) { methodCallExpression = this.configureAST( this.createMethodCallExpression(baseExpr, arguments), arguments); } else { // e.g. a[x] b, new A() b, etc. methodCallExpression = this.configureAST( new MethodCallExpression( baseExpr, CALL_STR, arguments ), arguments ); methodCallExpression.setImplicitThis(false); } if (!asBoolean(ctx.commandArgument())) { return this.configureAST(methodCallExpression, ctx); } return this.configureAST( (Expression) ctx.commandArgument().stream() .map(e -> (Object) e) .reduce(methodCallExpression, (r, e) -> { CommandArgumentContext commandArgumentContext = (CommandArgumentContext) e; commandArgumentContext.putNodeMetaData(CMD_EXPRESSION_BASE_EXPR, r); return this.visitCommandArgument(commandArgumentContext); } ), ctx); } @Override public Expression visitCommandArgument(CommandArgumentContext ctx) { // e.g. x y a b we call "x y" as the base expression Expression baseExpr = ctx.getNodeMetaData(CMD_EXPRESSION_BASE_EXPR); Expression primaryExpr = (Expression) this.visit(ctx.primary()); if (asBoolean(ctx.enhancedArgumentList())) { // e.g. x y a b if (baseExpr instanceof PropertyExpression) { // the branch should never reach, because a.b.c will be parsed as a path expression, not a method call throw createParsingFailedException("Unsupported command argument: " + ctx.getText(), ctx); } // the following code will process "a b" of "x y a b" MethodCallExpression methodCallExpression = new MethodCallExpression( baseExpr, this.createConstantExpression(primaryExpr), this.visitEnhancedArgumentList(ctx.enhancedArgumentList()) ); methodCallExpression.setImplicitThis(false); return this.configureAST(methodCallExpression, ctx); } else if (asBoolean(ctx.pathElement())) { // e.g. x y a.b Expression pathExpression = this.createPathExpression( this.configureAST( new PropertyExpression(baseExpr, this.createConstantExpression(primaryExpr)), primaryExpr ), ctx.pathElement() ); return this.configureAST(pathExpression, ctx); } // e.g. x y a return this.configureAST( new PropertyExpression( baseExpr, primaryExpr instanceof VariableExpression ? this.createConstantExpression(primaryExpr) : primaryExpr ), primaryExpr ); } // expression { -------------------------------------------------------------------- @Override public ClassNode visitCastParExpression(CastParExpressionContext ctx) { return this.visitType(ctx.type()); } @Override public Expression visitParExpression(ParExpressionContext ctx) { Expression expression = this.visitExpressionInPar(ctx.expressionInPar()); Integer insideParenLevel = expression.getNodeMetaData(INSIDE_PARENTHESES_LEVEL); if (null != insideParenLevel) { insideParenLevel++; } else { insideParenLevel = 1; } expression.putNodeMetaData(INSIDE_PARENTHESES_LEVEL, insideParenLevel); return this.configureAST(expression, ctx); } @Override public Expression visitExpressionInPar(ExpressionInParContext ctx) { return this.visitEnhancedStatementExpression(ctx.enhancedStatementExpression()); } @Override public Expression visitEnhancedStatementExpression(EnhancedStatementExpressionContext ctx) { Expression expression; if (asBoolean(ctx.statementExpression())) { expression = ((ExpressionStatement) this.visit(ctx.statementExpression())).getExpression(); } else if (asBoolean(ctx.standardLambdaExpression())) { expression = this.visitStandardLambdaExpression(ctx.standardLambdaExpression()); } else { throw createParsingFailedException("Unsupported enhanced statement expression: " + ctx.getText(), ctx); } return this.configureAST(expression, ctx); } @Override public Expression visitPathExpression(PathExpressionContext ctx) { return this.configureAST( this.createPathExpression((Expression) this.visit(ctx.primary()), ctx.pathElement()), ctx); } @Override public Expression visitPathElement(PathElementContext ctx) { Expression baseExpr = ctx.getNodeMetaData(PATH_EXPRESSION_BASE_EXPR); Objects.requireNonNull(baseExpr, "baseExpr is required!"); if (asBoolean(ctx.namePart())) { Expression namePartExpr = this.visitNamePart(ctx.namePart()); GenericsType[] genericsTypes = this.visitNonWildcardTypeArguments(ctx.nonWildcardTypeArguments()); if (asBoolean(ctx.DOT())) { if (asBoolean(ctx.AT())) { // e.g. obj.@a return this.configureAST(new AttributeExpression(baseExpr, namePartExpr), ctx); } else { // e.g. obj.p PropertyExpression propertyExpression = new PropertyExpression(baseExpr, namePartExpr); propertyExpression.putNodeMetaData(PATH_EXPRESSION_BASE_EXPR_GENERICS_TYPES, genericsTypes); return this.configureAST(propertyExpression, ctx); } } else if (asBoolean(ctx.SAFE_DOT())) { if (asBoolean(ctx.AT())) { // e.g. obj?.@a return this.configureAST(new AttributeExpression(baseExpr, namePartExpr, true), ctx); } else { // e.g. obj?.p PropertyExpression propertyExpression = new PropertyExpression(baseExpr, namePartExpr, true); propertyExpression.putNodeMetaData(PATH_EXPRESSION_BASE_EXPR_GENERICS_TYPES, genericsTypes); return this.configureAST(propertyExpression, ctx); } } else if (asBoolean(ctx.METHOD_POINTER())) { // e.g. obj.&m return this.configureAST(new MethodPointerExpression(baseExpr, namePartExpr), ctx); } else if (asBoolean(ctx.METHOD_REFERENCE())) { // e.g. obj::m return this.configureAST(new MethodReferenceExpression(baseExpr, namePartExpr), ctx); } else if (asBoolean(ctx.SPREAD_DOT())) { if (asBoolean(ctx.AT())) { // e.g. obj*.@a AttributeExpression attributeExpression = new AttributeExpression(baseExpr, namePartExpr, true); attributeExpression.setSpreadSafe(true); return this.configureAST(attributeExpression, ctx); } else { // e.g. obj*.p PropertyExpression propertyExpression = new PropertyExpression(baseExpr, namePartExpr, true); propertyExpression.putNodeMetaData(PATH_EXPRESSION_BASE_EXPR_GENERICS_TYPES, genericsTypes); propertyExpression.setSpreadSafe(true); return this.configureAST(propertyExpression, ctx); } } } if (asBoolean(ctx.indexPropertyArgs())) { // e.g. list[1, 3, 5] Pair<Token, Expression> pair = this.visitIndexPropertyArgs(ctx.indexPropertyArgs()); return this.configureAST( new BinaryExpression(baseExpr, createGroovyToken(pair.getKey()), pair.getValue(), asBoolean(ctx.indexPropertyArgs().QUESTION())), ctx); } if (asBoolean(ctx.namedPropertyArgs())) { // this is a special way to new instance, e.g. Person(name: 'Daniel.Sun', location: 'Shanghai') List<MapEntryExpression> mapEntryExpressionList = this.visitNamedPropertyArgs(ctx.namedPropertyArgs()); Expression right; if (mapEntryExpressionList.size() == 1) { MapEntryExpression mapEntryExpression = mapEntryExpressionList.get(0); if (mapEntryExpression.getKeyExpression() instanceof SpreadMapExpression) { right = mapEntryExpression.getKeyExpression(); } else { right = mapEntryExpression; } } else { ListExpression listExpression = this.configureAST( new ListExpression( mapEntryExpressionList.stream() .map( e -> { if (e.getKeyExpression() instanceof SpreadMapExpression) { return e.getKeyExpression(); } return e; } ) .collect(Collectors.toList())), ctx.namedPropertyArgs() ); listExpression.setWrapped(true); right = listExpression; } return this.configureAST( new BinaryExpression(baseExpr, createGroovyToken(ctx.namedPropertyArgs().LBRACK().getSymbol()), right), ctx); } if (asBoolean(ctx.arguments())) { Expression argumentsExpr = this.visitArguments(ctx.arguments()); this.configureAST(argumentsExpr, ctx); if (isInsideParentheses(baseExpr)) { // e.g. (obj.x)(), (obj.@x)() MethodCallExpression methodCallExpression = new MethodCallExpression( baseExpr, CALL_STR, argumentsExpr ); methodCallExpression.setImplicitThis(false); return this.configureAST(methodCallExpression, ctx); } if (baseExpr instanceof AttributeExpression) { // e.g. obj.@a(1, 2) AttributeExpression attributeExpression = (AttributeExpression) baseExpr; attributeExpression.setSpreadSafe(false); // whether attributeExpression is spread safe or not, we must reset it as false MethodCallExpression methodCallExpression = new MethodCallExpression( attributeExpression, CALL_STR, argumentsExpr ); return this.configureAST(methodCallExpression, ctx); } if (baseExpr instanceof PropertyExpression) { // e.g. obj.a(1, 2) MethodCallExpression methodCallExpression = this.createMethodCallExpression((PropertyExpression) baseExpr, argumentsExpr); return this.configureAST(methodCallExpression, ctx); } if (baseExpr instanceof VariableExpression) { // void and primitive type AST node must be an instance of VariableExpression String baseExprText = baseExpr.getText(); if (VOID_STR.equals(baseExprText)) { // e.g. void() MethodCallExpression methodCallExpression = new MethodCallExpression( this.createConstantExpression(baseExpr), CALL_STR, argumentsExpr ); methodCallExpression.setImplicitThis(false); return this.configureAST(methodCallExpression, ctx); } else if (PRIMITIVE_TYPE_SET.contains(baseExprText)) { // e.g. int(), long(), float(), etc. throw createParsingFailedException("Primitive type literal: " + baseExprText + " cannot be used as a method name", ctx); } } if (baseExpr instanceof VariableExpression || baseExpr instanceof GStringExpression || (baseExpr instanceof ConstantExpression && isTrue(baseExpr, IS_STRING))) { // e.g. m(), "$m"(), "m"() String baseExprText = baseExpr.getText(); if (SUPER_STR.equals(baseExprText) || THIS_STR.equals(baseExprText)) { // e.g. this(...), super(...) // class declaration is not allowed in the closure, // so if this and super is inside the closure, it will not be constructor call. // e.g. src/test/org/codehaus/groovy/transform/MapConstructorTransformTest.groovy: // @MapConstructor(pre={ super(args?.first, args?.last); args = args ?: [:] }, post = { first = first?.toUpperCase() }) if (ctx.isInsideClosure) { return this.configureAST( new MethodCallExpression( baseExpr, baseExprText, argumentsExpr ), ctx); } return this.configureAST( new ConstructorCallExpression( SUPER_STR.equals(baseExprText) ? ClassNode.SUPER : ClassNode.THIS, argumentsExpr ), ctx); } MethodCallExpression methodCallExpression = this.createMethodCallExpression(baseExpr, argumentsExpr); return this.configureAST(methodCallExpression, ctx); } // e.g. 1(), 1.1(), ((int) 1 / 2)(1, 2), {a, b -> a + b }(1, 2), m()() MethodCallExpression methodCallExpression = new MethodCallExpression(baseExpr, CALL_STR, argumentsExpr); methodCallExpression.setImplicitThis(false); return this.configureAST(methodCallExpression, ctx); } if (asBoolean(ctx.closure())) { ClosureExpression closureExpression = this.visitClosure(ctx.closure()); if (baseExpr instanceof MethodCallExpression) { MethodCallExpression methodCallExpression = (MethodCallExpression) baseExpr; Expression argumentsExpression = methodCallExpression.getArguments(); if (argumentsExpression instanceof ArgumentListExpression) { // normal arguments, e.g. 1, 2 ArgumentListExpression argumentListExpression = (ArgumentListExpression) argumentsExpression; argumentListExpression.getExpressions().add(closureExpression); return this.configureAST(methodCallExpression, ctx); } if (argumentsExpression instanceof TupleExpression) { // named arguments, e.g. x: 1, y: 2 TupleExpression tupleExpression = (TupleExpression) argumentsExpression; NamedArgumentListExpression namedArgumentListExpression = (NamedArgumentListExpression) tupleExpression.getExpression(0); if (asBoolean(tupleExpression.getExpressions())) { methodCallExpression.setArguments( this.configureAST( new ArgumentListExpression( Stream.of( this.configureAST( new MapExpression(namedArgumentListExpression.getMapEntryExpressions()), namedArgumentListExpression ), closureExpression ).collect(Collectors.toList()) ), tupleExpression ) ); } else { // the branch should never reach, because named arguments must not be empty methodCallExpression.setArguments( this.configureAST( new ArgumentListExpression(closureExpression), tupleExpression)); } return this.configureAST(methodCallExpression, ctx); } } // e.g. 1 {}, 1.1 {} if (baseExpr instanceof ConstantExpression && isTrue(baseExpr, IS_NUMERIC)) { MethodCallExpression methodCallExpression = new MethodCallExpression( baseExpr, CALL_STR, this.configureAST( new ArgumentListExpression(closureExpression), closureExpression ) ); methodCallExpression.setImplicitThis(false); return this.configureAST(methodCallExpression, ctx); } if (baseExpr instanceof PropertyExpression) { // e.g. obj.m { } PropertyExpression propertyExpression = (PropertyExpression) baseExpr; MethodCallExpression methodCallExpression = this.createMethodCallExpression( propertyExpression, this.configureAST( new ArgumentListExpression(closureExpression), closureExpression ) ); return this.configureAST(methodCallExpression, ctx); } // e.g. m { return 1; } MethodCallExpression methodCallExpression = new MethodCallExpression( VariableExpression.THIS_EXPRESSION, (baseExpr instanceof VariableExpression) ? this.createConstantExpression(baseExpr) : baseExpr, this.configureAST( new ArgumentListExpression(closureExpression), closureExpression) ); return this.configureAST(methodCallExpression, ctx); } throw createParsingFailedException("Unsupported path element: " + ctx.getText(), ctx); } @Override public GenericsType[] visitNonWildcardTypeArguments(NonWildcardTypeArgumentsContext ctx) { if (!asBoolean(ctx)) { return null; } return Arrays.stream(this.visitTypeList(ctx.typeList())) .map(this::createGenericsType) .toArray(GenericsType[]::new); } @Override public ClassNode[] visitTypeList(TypeListContext ctx) { if (!asBoolean(ctx)) { return new ClassNode[0]; } return ctx.type().stream() .map(this::visitType) .toArray(ClassNode[]::new); } @Override public Expression visitArguments(ArgumentsContext ctx) { if (!asBoolean(ctx) || !asBoolean(ctx.enhancedArgumentList())) { return new ArgumentListExpression(); } return this.configureAST(this.visitEnhancedArgumentList(ctx.enhancedArgumentList()), ctx); } @Override public Expression visitEnhancedArgumentList(EnhancedArgumentListContext ctx) { if (!asBoolean(ctx)) { return null; } List<Expression> expressionList = new LinkedList<>(); List<MapEntryExpression> mapEntryExpressionList = new LinkedList<>(); ctx.enhancedArgumentListElement().stream() .map(this::visitEnhancedArgumentListElement) .forEach(e -> { if (e instanceof MapEntryExpression) { MapEntryExpression mapEntryExpression = (MapEntryExpression) e; validateDuplicatedNamedParameter(mapEntryExpressionList, mapEntryExpression); mapEntryExpressionList.add(mapEntryExpression); } else { expressionList.add(e); } }); if (!asBoolean(mapEntryExpressionList)) { // e.g. arguments like 1, 2 OR someArg, e -> e return this.configureAST( new ArgumentListExpression(expressionList), ctx); } if (!asBoolean(expressionList)) { // e.g. arguments like x: 1, y: 2 return this.configureAST( new TupleExpression( this.configureAST( new NamedArgumentListExpression(mapEntryExpressionList), ctx)), ctx); } if (asBoolean(mapEntryExpressionList) && asBoolean(expressionList)) { // e.g. arguments like x: 1, 'a', y: 2, 'b', z: 3 ArgumentListExpression argumentListExpression = new ArgumentListExpression(expressionList); argumentListExpression.getExpressions().add(0, new MapExpression(mapEntryExpressionList)); // TODO: confirm BUG OR NOT? All map entries will be put at first, which is not friendly to Groovy developers return this.configureAST(argumentListExpression, ctx); } throw createParsingFailedException("Unsupported argument list: " + ctx.getText(), ctx); } private void validateDuplicatedNamedParameter(List<MapEntryExpression> mapEntryExpressionList, MapEntryExpression mapEntryExpression) { Expression keyExpression = mapEntryExpression.getKeyExpression(); if (null == keyExpression) { return; } String parameterName = keyExpression.getText(); boolean isDuplicatedNamedParameter = mapEntryExpressionList.stream().anyMatch(m -> m.getKeyExpression().getText().equals(parameterName)); if (!isDuplicatedNamedParameter) { return; } throw createParsingFailedException("Duplicated named parameter '" + parameterName + "' found", mapEntryExpression); } @Override public Expression visitEnhancedArgumentListElement(EnhancedArgumentListElementContext ctx) { if (asBoolean(ctx.expressionListElement())) { return this.configureAST(this.visitExpressionListElement(ctx.expressionListElement()), ctx); } if (asBoolean(ctx.standardLambdaExpression())) { return this.configureAST(this.visitStandardLambdaExpression(ctx.standardLambdaExpression()), ctx); } if (asBoolean(ctx.mapEntry())) { return this.configureAST(this.visitMapEntry(ctx.mapEntry()), ctx); } throw createParsingFailedException("Unsupported enhanced argument list element: " + ctx.getText(), ctx); } @Override public ConstantExpression visitStringLiteral(StringLiteralContext ctx) { String text = ctx.StringLiteral().getText(); int slashyType = text.startsWith("/") ? StringUtils.SLASHY : text.startsWith("$/") ? StringUtils.DOLLAR_SLASHY : StringUtils.NONE_SLASHY; if (text.startsWith("'''") || text.startsWith("\"\"\"")) { text = StringUtils.removeCR(text); // remove CR in the multiline string text = text.length() == 6 ? "" : text.substring(3, text.length() - 3); } else if (text.startsWith("'") || text.startsWith("/") || text.startsWith("\"")) { if (text.startsWith("/")) { // the slashy string can span rows, so we have to remove CR for it text = StringUtils.removeCR(text); // remove CR in the multiline string } text = text.length() == 2 ? "" : text.substring(1, text.length() - 1); } else if (text.startsWith("$/")) { text = StringUtils.removeCR(text); text = text.length() == 4 ? "" : text.substring(2, text.length() - 2); } //handle escapes. text = StringUtils.replaceEscapes(text, slashyType); ConstantExpression constantExpression = new ConstantExpression(text, true); constantExpression.putNodeMetaData(IS_STRING, true); return this.configureAST(constantExpression, ctx); } @Override public Pair<Token, Expression> visitIndexPropertyArgs(IndexPropertyArgsContext ctx) { List<Expression> expressionList = this.visitExpressionList(ctx.expressionList()); if (expressionList.size() == 1) { Expression expr = expressionList.get(0); Expression indexExpr; if (expr instanceof SpreadExpression) { // e.g. a[*[1, 2]] ListExpression listExpression = new ListExpression(expressionList); listExpression.setWrapped(false); indexExpr = listExpression; } else { // e.g. a[1] indexExpr = expr; } return new Pair<>(ctx.LBRACK().getSymbol(), indexExpr); } // e.g. a[1, 2] ListExpression listExpression = new ListExpression(expressionList); listExpression.setWrapped(true); return new Pair<>(ctx.LBRACK().getSymbol(), this.configureAST(listExpression, ctx)); } @Override public List<MapEntryExpression> visitNamedPropertyArgs(NamedPropertyArgsContext ctx) { return this.visitMapEntryList(ctx.mapEntryList()); } @Override public Expression visitNamePart(NamePartContext ctx) { if (asBoolean(ctx.identifier())) { return this.configureAST(new ConstantExpression(this.visitIdentifier(ctx.identifier())), ctx); } else if (asBoolean(ctx.stringLiteral())) { return this.configureAST(this.visitStringLiteral(ctx.stringLiteral()), ctx); } else if (asBoolean(ctx.dynamicMemberName())) { return this.configureAST(this.visitDynamicMemberName(ctx.dynamicMemberName()), ctx); } else if (asBoolean(ctx.keywords())) { return this.configureAST(new ConstantExpression(ctx.keywords().getText()), ctx); } throw createParsingFailedException("Unsupported name part: " + ctx.getText(), ctx); } @Override public Expression visitDynamicMemberName(DynamicMemberNameContext ctx) { if (asBoolean(ctx.parExpression())) { return this.configureAST(this.visitParExpression(ctx.parExpression()), ctx); } else if (asBoolean(ctx.gstring())) { return this.configureAST(this.visitGstring(ctx.gstring()), ctx); } throw createParsingFailedException("Unsupported dynamic member name: " + ctx.getText(), ctx); } @Override public Expression visitPostfixExpression(PostfixExpressionContext ctx) { Expression pathExpr = this.visitPathExpression(ctx.pathExpression()); if (asBoolean(ctx.op)) { PostfixExpression postfixExpression = new PostfixExpression(pathExpr, createGroovyToken(ctx.op)); if (ctx.isInsideAssert) { // powerassert requires different column for values, so we have to copy the location of op return this.configureAST(postfixExpression, ctx.op); } else { return this.configureAST(postfixExpression, ctx); } } return this.configureAST(pathExpr, ctx); } @Override public Expression visitPostfixExprAlt(PostfixExprAltContext ctx) { return this.visitPostfixExpression(ctx.postfixExpression()); } @Override public Expression visitUnaryNotExprAlt(UnaryNotExprAltContext ctx) { if (asBoolean(ctx.NOT())) { return this.configureAST( new NotExpression((Expression) this.visit(ctx.expression())), ctx); } if (asBoolean(ctx.BITNOT())) { return this.configureAST( new BitwiseNegationExpression((Expression) this.visit(ctx.expression())), ctx); } throw createParsingFailedException("Unsupported unary expression: " + ctx.getText(), ctx); } @Override public CastExpression visitCastExprAlt(CastExprAltContext ctx) { return this.configureAST( new CastExpression( this.visitCastParExpression(ctx.castParExpression()), (Expression) this.visit(ctx.expression()) ), ctx ); } @Override public BinaryExpression visitPowerExprAlt(PowerExprAltContext ctx) { return this.createBinaryExpression(ctx.left, ctx.op, ctx.right, ctx); } @Override public Expression visitUnaryAddExprAlt(UnaryAddExprAltContext ctx) { ExpressionContext expressionCtx = ctx.expression(); Expression expression = (Expression) this.visit(expressionCtx); Boolean insidePar = isInsideParentheses(expression); switch (ctx.op.getType()) { case ADD: { if (expression instanceof ConstantExpression && !insidePar) { return this.configureAST(expression, ctx); } return this.configureAST(new UnaryPlusExpression(expression), ctx); } case SUB: { if (expression instanceof ConstantExpression && !insidePar) { ConstantExpression constantExpression = (ConstantExpression) expression; String integerLiteralText = constantExpression.getNodeMetaData(INTEGER_LITERAL_TEXT); if (null != integerLiteralText) { return this.configureAST(new ConstantExpression(Numbers.parseInteger(null, SUB_STR + integerLiteralText)), ctx); } String floatingPointLiteralText = constantExpression.getNodeMetaData(FLOATING_POINT_LITERAL_TEXT); if (null != floatingPointLiteralText) { return this.configureAST(new ConstantExpression(Numbers.parseDecimal(SUB_STR + floatingPointLiteralText)), ctx); } throw new GroovyBugError("Failed to find the original number literal text: " + constantExpression.getText()); } return this.configureAST(new UnaryMinusExpression(expression), ctx); } case INC: case DEC: return this.configureAST(new PrefixExpression(this.createGroovyToken(ctx.op), expression), ctx); default: throw createParsingFailedException("Unsupported unary operation: " + ctx.getText(), ctx); } } @Override public BinaryExpression visitMultiplicativeExprAlt(MultiplicativeExprAltContext ctx) { return this.createBinaryExpression(ctx.left, ctx.op, ctx.right, ctx); } @Override public BinaryExpression visitAdditiveExprAlt(AdditiveExprAltContext ctx) { return this.createBinaryExpression(ctx.left, ctx.op, ctx.right, ctx); } @Override public Expression visitShiftExprAlt(ShiftExprAltContext ctx) { Expression left = (Expression) this.visit(ctx.left); Expression right = (Expression) this.visit(ctx.right); if (asBoolean(ctx.rangeOp)) { return this.configureAST(new RangeExpression(left, right, !ctx.rangeOp.getText().endsWith("<")), ctx); } org.codehaus.groovy.syntax.Token op = null; Token antlrToken = null; if (asBoolean(ctx.dlOp)) { op = this.createGroovyToken(ctx.dlOp, 2); antlrToken = ctx.dlOp; } else if (asBoolean(ctx.dgOp)) { op = this.createGroovyToken(ctx.dgOp, 2); antlrToken = ctx.dgOp; } else if (asBoolean(ctx.tgOp)) { op = this.createGroovyToken(ctx.tgOp, 3); antlrToken = ctx.tgOp; } else { throw createParsingFailedException("Unsupported shift expression: " + ctx.getText(), ctx); } BinaryExpression binaryExpression = new BinaryExpression(left, op, right); if (isTrue(ctx, IS_INSIDE_CONDITIONAL_EXPRESSION)) { return this.configureAST(binaryExpression, antlrToken); } return this.configureAST(binaryExpression, ctx); } @Override public Expression visitRelationalExprAlt(RelationalExprAltContext ctx) { switch (ctx.op.getType()) { case AS: return this.configureAST( CastExpression.asExpression(this.visitType(ctx.type()), (Expression) this.visit(ctx.left)), ctx); case INSTANCEOF: case NOT_INSTANCEOF: ctx.type().putNodeMetaData(IS_INSIDE_INSTANCEOF_EXPR, true); return this.configureAST( new BinaryExpression((Expression) this.visit(ctx.left), this.createGroovyToken(ctx.op), this.configureAST(new ClassExpression(this.visitType(ctx.type())), ctx.type())), ctx); case LE: case GE: case GT: case LT: case IN: case NOT_IN: { if (ctx.op.getType() == IN || ctx.op.getType() == NOT_IN ) { return this.createBinaryExpression(ctx.left, ctx.op, ctx.right, ctx); } return this.configureAST( this.createBinaryExpression(ctx.left, ctx.op, ctx.right), ctx); } default: throw createParsingFailedException("Unsupported relational expression: " + ctx.getText(), ctx); } } @Override public BinaryExpression visitEqualityExprAlt(EqualityExprAltContext ctx) { return this.configureAST( this.createBinaryExpression(ctx.left, ctx.op, ctx.right), ctx); } @Override public BinaryExpression visitRegexExprAlt(RegexExprAltContext ctx) { return this.configureAST( this.createBinaryExpression(ctx.left, ctx.op, ctx.right), ctx); } @Override public BinaryExpression visitAndExprAlt(AndExprAltContext ctx) { return this.createBinaryExpression(ctx.left, ctx.op, ctx.right, ctx); } @Override public BinaryExpression visitExclusiveOrExprAlt(ExclusiveOrExprAltContext ctx) { return this.createBinaryExpression(ctx.left, ctx.op, ctx.right, ctx); } @Override public BinaryExpression visitInclusiveOrExprAlt(InclusiveOrExprAltContext ctx) { return this.createBinaryExpression(ctx.left, ctx.op, ctx.right, ctx); } @Override public BinaryExpression visitLogicalAndExprAlt(LogicalAndExprAltContext ctx) { return this.configureAST( this.createBinaryExpression(ctx.left, ctx.op, ctx.right), ctx); } @Override public BinaryExpression visitLogicalOrExprAlt(LogicalOrExprAltContext ctx) { return this.configureAST( this.createBinaryExpression(ctx.left, ctx.op, ctx.right), ctx); } @Override public Expression visitConditionalExprAlt(ConditionalExprAltContext ctx) { ctx.fb.putNodeMetaData(IS_INSIDE_CONDITIONAL_EXPRESSION, true); if (asBoolean(ctx.ELVIS())) { // e.g. a == 6 ?: 0 return this.configureAST( new ElvisOperatorExpression((Expression) this.visit(ctx.con), (Expression) this.visit(ctx.fb)), ctx); } ctx.tb.putNodeMetaData(IS_INSIDE_CONDITIONAL_EXPRESSION, true); return this.configureAST( new TernaryExpression( this.configureAST(new BooleanExpression((Expression) this.visit(ctx.con)), ctx.con), (Expression) this.visit(ctx.tb), (Expression) this.visit(ctx.fb)), ctx); } @Override public BinaryExpression visitMultipleAssignmentExprAlt(MultipleAssignmentExprAltContext ctx) { return this.configureAST( new BinaryExpression( this.visitVariableNames(ctx.left), this.createGroovyToken(ctx.op), ((ExpressionStatement) this.visit(ctx.right)).getExpression()), ctx); } @Override public BinaryExpression visitAssignmentExprAlt(AssignmentExprAltContext ctx) { Expression leftExpr = (Expression) this.visit(ctx.left); if (leftExpr instanceof VariableExpression && isInsideParentheses(leftExpr)) { // it is a special multiple assignment whose variable count is only one, e.g. (a) = [1] if ((Integer) leftExpr.getNodeMetaData(INSIDE_PARENTHESES_LEVEL) > 1) { throw createParsingFailedException("Nested parenthesis is not allowed in multiple assignment, e.g. ((a)) = b", ctx); } return this.configureAST( new BinaryExpression( this.configureAST(new TupleExpression(leftExpr), ctx.left), this.createGroovyToken(ctx.op), this.visitEnhancedStatementExpression(ctx.enhancedStatementExpression())), ctx); } // the LHS expression should be a variable which is not inside any parentheses if ( !( (leftExpr instanceof VariableExpression // && !(THIS_STR.equals(leftExpr.getText()) || SUPER_STR.equals(leftExpr.getText())) // commented, e.g. this = value // this will be transformed to $this && !isInsideParentheses(leftExpr)) // e.g. p = 123 || leftExpr instanceof PropertyExpression // e.g. obj.p = 123 || (leftExpr instanceof BinaryExpression // && !(((BinaryExpression) leftExpr).getRightExpression() instanceof ListExpression) // commented, e.g. list[1, 2] = [11, 12] && Types.LEFT_SQUARE_BRACKET == ((BinaryExpression) leftExpr).getOperation().getType()) // e.g. map[a] = 123 OR map['a'] = 123 OR map["$a"] = 123 ) ) { throw createParsingFailedException("The LHS of an assignment should be a variable or a field accessing expression", ctx); } return this.configureAST( new BinaryExpression( leftExpr, this.createGroovyToken(ctx.op), this.visitEnhancedStatementExpression(ctx.enhancedStatementExpression())), ctx); } // } expression -------------------------------------------------------------------- // primary { -------------------------------------------------------------------- @Override public VariableExpression visitIdentifierPrmrAlt(IdentifierPrmrAltContext ctx) { return this.configureAST(new VariableExpression(this.visitIdentifier(ctx.identifier())), ctx); } @Override public ConstantExpression visitLiteralPrmrAlt(LiteralPrmrAltContext ctx) { return this.configureAST((ConstantExpression) this.visit(ctx.literal()), ctx); } @Override public GStringExpression visitGstringPrmrAlt(GstringPrmrAltContext ctx) { return this.configureAST((GStringExpression) this.visit(ctx.gstring()), ctx); } @Override public Expression visitNewPrmrAlt(NewPrmrAltContext ctx) { return this.configureAST(this.visitCreator(ctx.creator()), ctx); } @Override public VariableExpression visitThisPrmrAlt(ThisPrmrAltContext ctx) { return this.configureAST(new VariableExpression(ctx.THIS().getText()), ctx); } @Override public VariableExpression visitSuperPrmrAlt(SuperPrmrAltContext ctx) { return this.configureAST(new VariableExpression(ctx.SUPER().getText()), ctx); } @Override public Expression visitParenPrmrAlt(ParenPrmrAltContext ctx) { return this.configureAST(this.visitParExpression(ctx.parExpression()), ctx); } @Override public ClosureExpression visitClosurePrmrAlt(ClosurePrmrAltContext ctx) { return this.configureAST(this.visitClosure(ctx.closure()), ctx); } @Override public ClosureExpression visitLambdaPrmrAlt(LambdaPrmrAltContext ctx) { return this.configureAST(this.visitStandardLambdaExpression(ctx.standardLambdaExpression()), ctx); } @Override public ListExpression visitListPrmrAlt(ListPrmrAltContext ctx) { return this.configureAST( this.visitList(ctx.list()), ctx); } @Override public MapExpression visitMapPrmrAlt(MapPrmrAltContext ctx) { return this.configureAST(this.visitMap(ctx.map()), ctx); } @Override public VariableExpression visitTypePrmrAlt(TypePrmrAltContext ctx) { return this.configureAST( this.visitBuiltInType(ctx.builtInType()), ctx); } // } primary -------------------------------------------------------------------- @Override public Expression visitCreator(CreatorContext ctx) { ClassNode classNode = this.visitCreatedName(ctx.createdName()); Expression arguments = this.visitArguments(ctx.arguments()); if (asBoolean(ctx.arguments())) { // create instance of class if (asBoolean(ctx.anonymousInnerClassDeclaration())) { ctx.anonymousInnerClassDeclaration().putNodeMetaData(ANONYMOUS_INNER_CLASS_SUPER_CLASS, classNode); InnerClassNode anonymousInnerClassNode = this.visitAnonymousInnerClassDeclaration(ctx.anonymousInnerClassDeclaration()); List<InnerClassNode> anonymousInnerClassList = anonymousInnerClassesDefinedInMethodStack.peek(); if (null != anonymousInnerClassList) { // if the anonymous class is created in a script, no anonymousInnerClassList is available. anonymousInnerClassList.add(anonymousInnerClassNode); } ConstructorCallExpression constructorCallExpression = new ConstructorCallExpression(anonymousInnerClassNode, arguments); constructorCallExpression.setUsingAnonymousInnerClass(true); return this.configureAST(constructorCallExpression, ctx); } return this.configureAST( new ConstructorCallExpression(classNode, arguments), ctx); } if (asBoolean(ctx.LBRACK()) || asBoolean(ctx.dims())) { // create array ArrayExpression arrayExpression; List<List<AnnotationNode>> allDimList; if (asBoolean(ctx.arrayInitializer())) { ClassNode elementType = classNode; allDimList = this.visitDims(ctx.dims()); for (int i = 0, n = allDimList.size() - 1; i < n; i++) { elementType = elementType.makeArray(); } arrayExpression = new ArrayExpression( elementType, this.visitArrayInitializer(ctx.arrayInitializer())); } else { Expression[] empties; List<List<AnnotationNode>> emptyDimList = this.visitDimsOpt(ctx.dimsOpt()); if (asBoolean(emptyDimList)) { empties = new Expression[emptyDimList.size()]; Arrays.setAll(empties, i -> ConstantExpression.EMPTY_EXPRESSION); } else { empties = new Expression[0]; } arrayExpression = new ArrayExpression( classNode, null, Stream.concat( ctx.expression().stream() .map(e -> (Expression) this.visit(e)), Arrays.stream(empties) ).collect(Collectors.toList())); List<List<AnnotationNode>> exprDimList = ctx.annotationsOpt().stream().map(this::visitAnnotationsOpt).collect(Collectors.toList()); allDimList = new ArrayList<>(exprDimList); Collections.reverse(emptyDimList); allDimList.addAll(emptyDimList); Collections.reverse(allDimList); } arrayExpression.setType(createArrayType(classNode, allDimList)); return this.configureAST(arrayExpression, ctx); } throw createParsingFailedException("Unsupported creator: " + ctx.getText(), ctx); } private ClassNode createArrayType(ClassNode classNode, List<List<AnnotationNode>> dimList) { ClassNode arrayType = classNode; for (int i = 0, n = dimList.size(); i < n; i++) { arrayType = arrayType.makeArray(); arrayType.addAnnotations(dimList.get(i)); } return arrayType; } private String genAnonymousClassName(String outerClassName) { return outerClassName + "$" + this.anonymousInnerClassCounter++; } @Override public InnerClassNode visitAnonymousInnerClassDeclaration(AnonymousInnerClassDeclarationContext ctx) { ClassNode superClass = ctx.getNodeMetaData(ANONYMOUS_INNER_CLASS_SUPER_CLASS); Objects.requireNonNull(superClass, "superClass should not be null"); InnerClassNode anonymousInnerClass; ClassNode outerClass = this.classNodeStack.peek(); outerClass = asBoolean(outerClass) ? outerClass : moduleNode.getScriptClassDummy(); String fullName = this.genAnonymousClassName(outerClass.getName()); if (1 == ctx.t) { // anonymous enum anonymousInnerClass = new EnumConstantClassNode(outerClass, fullName, superClass.getModifiers() | Opcodes.ACC_FINAL, superClass.getPlainNodeReference()); // and remove the final modifier from classNode to allow the sub class superClass.setModifiers(superClass.getModifiers() & ~Opcodes.ACC_FINAL); } else { // anonymous inner class anonymousInnerClass = new InnerClassNode(outerClass, fullName, Opcodes.ACC_PUBLIC, superClass); } anonymousInnerClass.setUsingGenerics(false); anonymousInnerClass.setAnonymous(true); anonymousInnerClass.putNodeMetaData(CLASS_NAME, fullName); this.configureAST(anonymousInnerClass, ctx); classNodeStack.push(anonymousInnerClass); ctx.classBody().putNodeMetaData(CLASS_DECLARATION_CLASS_NODE, anonymousInnerClass); this.visitClassBody(ctx.classBody()); classNodeStack.pop(); classNodeList.add(anonymousInnerClass); return anonymousInnerClass; } @Override public ClassNode visitCreatedName(CreatedNameContext ctx) { ClassNode classNode = null; if (asBoolean(ctx.qualifiedClassName())) { classNode = this.visitQualifiedClassName(ctx.qualifiedClassName()); if (asBoolean(ctx.typeArgumentsOrDiamond())) { classNode.setGenericsTypes( this.visitTypeArgumentsOrDiamond(ctx.typeArgumentsOrDiamond())); } classNode = this.configureAST(classNode, ctx); } else if (asBoolean(ctx.primitiveType())) { classNode = this.configureAST( this.visitPrimitiveType(ctx.primitiveType()), ctx); } if (!asBoolean(classNode)) { throw createParsingFailedException("Unsupported created name: " + ctx.getText(), ctx); } classNode.addAnnotations(this.visitAnnotationsOpt(ctx.annotationsOpt())); return classNode; } @Override public MapExpression visitMap(MapContext ctx) { return this.configureAST( new MapExpression(this.visitMapEntryList(ctx.mapEntryList())), ctx); } @Override public List<MapEntryExpression> visitMapEntryList(MapEntryListContext ctx) { if (!asBoolean(ctx)) { return Collections.emptyList(); } return this.createMapEntryList(ctx.mapEntry()); } private List<MapEntryExpression> createMapEntryList(List<? extends MapEntryContext> mapEntryContextList) { if (!asBoolean(mapEntryContextList)) { return Collections.emptyList(); } return mapEntryContextList.stream() .map(this::visitMapEntry) .collect(Collectors.toList()); } @Override public MapEntryExpression visitMapEntry(MapEntryContext ctx) { Expression keyExpr; Expression valueExpr = (Expression) this.visit(ctx.expression()); if (asBoolean(ctx.MUL())) { keyExpr = this.configureAST(new SpreadMapExpression(valueExpr), ctx); } else if (asBoolean(ctx.mapEntryLabel())) { keyExpr = this.visitMapEntryLabel(ctx.mapEntryLabel()); } else { throw createParsingFailedException("Unsupported map entry: " + ctx.getText(), ctx); } return this.configureAST( new MapEntryExpression(keyExpr, valueExpr), ctx); } @Override public Expression visitMapEntryLabel(MapEntryLabelContext ctx) { if (asBoolean(ctx.keywords())) { return this.configureAST(this.visitKeywords(ctx.keywords()), ctx); } else if (asBoolean(ctx.primary())) { Expression expression = (Expression) this.visit(ctx.primary()); // if the key is variable and not inside parentheses, convert it to a constant, e.g. [a:1, b:2] if (expression instanceof VariableExpression && !isInsideParentheses(expression)) { expression = this.configureAST( new ConstantExpression(((VariableExpression) expression).getName()), expression); } return this.configureAST(expression, ctx); } throw createParsingFailedException("Unsupported map entry label: " + ctx.getText(), ctx); } @Override public ConstantExpression visitKeywords(KeywordsContext ctx) { return this.configureAST(new ConstantExpression(ctx.getText()), ctx); } /* @Override public VariableExpression visitIdentifier(IdentifierContext ctx) { return this.configureAST(new VariableExpression(ctx.getText()), ctx); } */ @Override public VariableExpression visitBuiltInType(BuiltInTypeContext ctx) { String text; if (asBoolean(ctx.VOID())) { text = ctx.VOID().getText(); } else if (asBoolean(ctx.BuiltInPrimitiveType())) { text = ctx.BuiltInPrimitiveType().getText(); } else { throw createParsingFailedException("Unsupported built-in type: " + ctx, ctx); } return this.configureAST(new VariableExpression(text), ctx); } @Override public ListExpression visitList(ListContext ctx) { return this.configureAST( new ListExpression( this.visitExpressionList(ctx.expressionList())), ctx); } @Override public List<Expression> visitExpressionList(ExpressionListContext ctx) { if (!asBoolean(ctx)) { return Collections.emptyList(); } return this.createExpressionList(ctx.expressionListElement()); } private List<Expression> createExpressionList(List<? extends ExpressionListElementContext> expressionListElementContextList) { if (!asBoolean(expressionListElementContextList)) { return Collections.emptyList(); } return expressionListElementContextList.stream() .map(this::visitExpressionListElement) .collect(Collectors.toList()); } @Override public Expression visitExpressionListElement(ExpressionListElementContext ctx) { Expression expression = (Expression) this.visit(ctx.expression()); if (asBoolean(ctx.MUL())) { return this.configureAST(new SpreadExpression(expression), ctx); } return this.configureAST(expression, ctx); } // literal { -------------------------------------------------------------------- @Override public ConstantExpression visitIntegerLiteralAlt(IntegerLiteralAltContext ctx) { String text = ctx.IntegerLiteral().getText(); ConstantExpression constantExpression = new ConstantExpression(Numbers.parseInteger(null, text), !text.startsWith(SUB_STR)); constantExpression.putNodeMetaData(IS_NUMERIC, true); constantExpression.putNodeMetaData(INTEGER_LITERAL_TEXT, text); return this.configureAST(constantExpression, ctx); } @Override public ConstantExpression visitFloatingPointLiteralAlt(FloatingPointLiteralAltContext ctx) { String text = ctx.FloatingPointLiteral().getText(); ConstantExpression constantExpression = new ConstantExpression(Numbers.parseDecimal(text), !text.startsWith(SUB_STR)); constantExpression.putNodeMetaData(IS_NUMERIC, true); constantExpression.putNodeMetaData(FLOATING_POINT_LITERAL_TEXT, text); return this.configureAST(constantExpression, ctx); } @Override public ConstantExpression visitStringLiteralAlt(StringLiteralAltContext ctx) { return this.configureAST( this.visitStringLiteral(ctx.stringLiteral()), ctx); } @Override public ConstantExpression visitBooleanLiteralAlt(BooleanLiteralAltContext ctx) { return this.configureAST(new ConstantExpression("true".equals(ctx.BooleanLiteral().getText()), true), ctx); } @Override public ConstantExpression visitNullLiteralAlt(NullLiteralAltContext ctx) { return this.configureAST(new ConstantExpression(null), ctx); } // } literal -------------------------------------------------------------------- // gstring { -------------------------------------------------------------------- @Override public GStringExpression visitGstring(GstringContext ctx) { List<ConstantExpression> strings = new LinkedList<>(); String begin = ctx.GStringBegin().getText(); final int slashyType = begin.startsWith("/") ? StringUtils.SLASHY : begin.startsWith("$/") ? StringUtils.DOLLAR_SLASHY : StringUtils.NONE_SLASHY; { String it = begin; if (it.startsWith("\"\"\"")) { it = StringUtils.removeCR(it); it = it.substring(2); // translate leading """ to " } else if (it.startsWith("$/")) { it = StringUtils.removeCR(it); it = "\"" + it.substring(2); // translate leading $/ to " } else if (it.startsWith("/")) { it = StringUtils.removeCR(it); } it = StringUtils.replaceEscapes(it, slashyType); it = (it.length() == 2) ? "" : StringGroovyMethods.getAt(it, new IntRange(true, 1, -2)); strings.add(this.configureAST(new ConstantExpression(it), ctx.GStringBegin())); } List<ConstantExpression> partStrings = ctx.GStringPart().stream() .map(e -> { String it = e.getText(); it = StringUtils.removeCR(it); it = StringUtils.replaceEscapes(it, slashyType); it = it.length() == 1 ? "" : StringGroovyMethods.getAt(it, new IntRange(true, 0, -2)); return this.configureAST(new ConstantExpression(it), e); }).collect(Collectors.toList()); strings.addAll(partStrings); { String it = ctx.GStringEnd().getText(); if (it.endsWith("\"\"\"")) { it = StringUtils.removeCR(it); it = StringGroovyMethods.getAt(it, new IntRange(true, 0, -3)); // translate tailing """ to " } else if (it.endsWith("/$")) { it = StringUtils.removeCR(it); it = StringGroovyMethods.getAt(it, new IntRange(false, 0, -2)) + "\""; // translate tailing /$ to " } else if (it.endsWith("/")) { it = StringUtils.removeCR(it); } it = StringUtils.replaceEscapes(it, slashyType); it = (it.length() == 1) ? "" : StringGroovyMethods.getAt(it, new IntRange(true, 0, -2)); strings.add(this.configureAST(new ConstantExpression(it), ctx.GStringEnd())); } List<Expression> values = ctx.gstringValue().stream() .map(e -> { Expression expression = this.visitGstringValue(e); if (expression instanceof ClosureExpression && !asBoolean(e.closure().ARROW())) { List<Statement> statementList = ((BlockStatement) ((ClosureExpression) expression).getCode()).getStatements(); if (statementList.stream().allMatch(x -> !asBoolean(x))) { return this.configureAST(new ConstantExpression(null), e); } return this.configureAST(new MethodCallExpression(expression, CALL_STR, new ArgumentListExpression()), e); } return expression; }) .collect(Collectors.toList()); StringBuilder verbatimText = new StringBuilder(ctx.getText().length()); for (int i = 0, n = strings.size(), s = values.size(); i < n; i++) { verbatimText.append(strings.get(i).getValue()); if (i == s) { continue; } Expression value = values.get(i); if (!asBoolean(value)) { continue; } verbatimText.append(DOLLAR_STR); verbatimText.append(value.getText()); } return this.configureAST(new GStringExpression(verbatimText.toString(), strings, values), ctx); } @Override public Expression visitGstringValue(GstringValueContext ctx) { if (asBoolean(ctx.gstringPath())) { return this.configureAST(this.visitGstringPath(ctx.gstringPath()), ctx); } if (asBoolean(ctx.LBRACE())) { if (asBoolean(ctx.statementExpression())) { return this.configureAST(((ExpressionStatement) this.visit(ctx.statementExpression())).getExpression(), ctx.statementExpression()); } else { // e.g. "${}" return this.configureAST(new ConstantExpression(null), ctx); } } if (asBoolean(ctx.closure())) { return this.configureAST(this.visitClosure(ctx.closure()), ctx); } throw createParsingFailedException("Unsupported gstring value: " + ctx.getText(), ctx); } @Override public Expression visitGstringPath(GstringPathContext ctx) { VariableExpression variableExpression = new VariableExpression(this.visitIdentifier(ctx.identifier())); if (asBoolean(ctx.GStringPathPart())) { Expression propertyExpression = ctx.GStringPathPart().stream() .map(e -> this.configureAST((Expression) new ConstantExpression(e.getText().substring(1)), e)) .reduce(this.configureAST(variableExpression, ctx.identifier()), (r, e) -> this.configureAST(new PropertyExpression(r, e), e)); return this.configureAST(propertyExpression, ctx); } return this.configureAST(variableExpression, ctx); } // } gstring -------------------------------------------------------------------- @Override public LambdaExpression visitStandardLambdaExpression(StandardLambdaExpressionContext ctx) { return this.configureAST(this.createLambda(ctx.standardLambdaParameters(), ctx.lambdaBody()), ctx); } private LambdaExpression createLambda(StandardLambdaParametersContext standardLambdaParametersContext, LambdaBodyContext lambdaBodyContext) { return new LambdaExpression( this.visitStandardLambdaParameters(standardLambdaParametersContext), this.visitLambdaBody(lambdaBodyContext)); } @Override public Parameter[] visitStandardLambdaParameters(StandardLambdaParametersContext ctx) { if (asBoolean(ctx.variableDeclaratorId())) { return new Parameter[]{ this.configureAST( new Parameter( ClassHelper.OBJECT_TYPE, this.visitVariableDeclaratorId(ctx.variableDeclaratorId()).getName() ), ctx.variableDeclaratorId() ) }; } Parameter[] parameters = this.visitFormalParameters(ctx.formalParameters()); if (0 == parameters.length) { return null; } return parameters; } @Override public Statement visitLambdaBody(LambdaBodyContext ctx) { if (asBoolean(ctx.statementExpression())) { return this.configureAST((ExpressionStatement) this.visit(ctx.statementExpression()), ctx); } if (asBoolean(ctx.block())) { return this.configureAST(this.visitBlock(ctx.block()), ctx); } throw createParsingFailedException("Unsupported lambda body: " + ctx.getText(), ctx); } @Override public ClosureExpression visitClosure(ClosureContext ctx) { Parameter[] parameters = asBoolean(ctx.formalParameterList()) ? this.visitFormalParameterList(ctx.formalParameterList()) : null; if (!asBoolean(ctx.ARROW())) { parameters = Parameter.EMPTY_ARRAY; } Statement code = this.visitBlockStatementsOpt(ctx.blockStatementsOpt()); return this.configureAST(new ClosureExpression(parameters, code), ctx); } @Override public Parameter[] visitFormalParameters(FormalParametersContext ctx) { if (!asBoolean(ctx)) { return new Parameter[0]; } return this.visitFormalParameterList(ctx.formalParameterList()); } @Override public Parameter[] visitFormalParameterList(FormalParameterListContext ctx) { if (!asBoolean(ctx)) { return new Parameter[0]; } List<Parameter> parameterList = new LinkedList<>(); if (asBoolean(ctx.thisFormalParameter())) { parameterList.add(this.visitThisFormalParameter(ctx.thisFormalParameter())); } if (asBoolean(ctx.formalParameter())) { parameterList.addAll( ctx.formalParameter().stream() .map(this::visitFormalParameter) .collect(Collectors.toList())); } if (asBoolean(ctx.lastFormalParameter())) { parameterList.add(this.visitLastFormalParameter(ctx.lastFormalParameter())); } validateParameterList(parameterList); return parameterList.toArray(new Parameter[0]); } private void validateParameterList(List<Parameter> parameterList) { for (int n = parameterList.size(), i = n - 1; i >= 0; i--) { Parameter parameter = parameterList.get(i); for (Parameter otherParameter : parameterList) { if (otherParameter == parameter) { continue; } if (otherParameter.getName().equals(parameter.getName())) { throw createParsingFailedException("Duplicated parameter '" + parameter.getName() + "' found.", parameter); } } } } @Override public Parameter visitFormalParameter(FormalParameterContext ctx) { return this.processFormalParameter(ctx, ctx.variableModifiersOpt(), ctx.type(), null, ctx.variableDeclaratorId(), ctx.expression()); } @Override public Parameter visitThisFormalParameter(ThisFormalParameterContext ctx) { return this.configureAST(new Parameter(this.visitType(ctx.type()), THIS_STR), ctx); } @Override public Parameter visitLastFormalParameter(LastFormalParameterContext ctx) { return this.processFormalParameter(ctx, ctx.variableModifiersOpt(), ctx.type(), ctx.ELLIPSIS(), ctx.variableDeclaratorId(), ctx.expression()); } @Override public List<ModifierNode> visitClassOrInterfaceModifiersOpt(ClassOrInterfaceModifiersOptContext ctx) { if (asBoolean(ctx.classOrInterfaceModifiers())) { return this.visitClassOrInterfaceModifiers(ctx.classOrInterfaceModifiers()); } return Collections.emptyList(); } @Override public List<ModifierNode> visitClassOrInterfaceModifiers(ClassOrInterfaceModifiersContext ctx) { return ctx.classOrInterfaceModifier().stream() .map(this::visitClassOrInterfaceModifier) .collect(Collectors.toList()); } @Override public ModifierNode visitClassOrInterfaceModifier(ClassOrInterfaceModifierContext ctx) { if (asBoolean(ctx.annotation())) { return this.configureAST(new ModifierNode(this.visitAnnotation(ctx.annotation()), ctx.getText()), ctx); } if (asBoolean(ctx.m)) { return this.configureAST(new ModifierNode(ctx.m.getType(), ctx.getText()), ctx); } throw createParsingFailedException("Unsupported class or interface modifier: " + ctx.getText(), ctx); } @Override public ModifierNode visitModifier(ModifierContext ctx) { if (asBoolean(ctx.classOrInterfaceModifier())) { return this.configureAST(this.visitClassOrInterfaceModifier(ctx.classOrInterfaceModifier()), ctx); } if (asBoolean(ctx.m)) { return this.configureAST(new ModifierNode(ctx.m.getType(), ctx.getText()), ctx); } throw createParsingFailedException("Unsupported modifier: " + ctx.getText(), ctx); } @Override public List<ModifierNode> visitModifiers(ModifiersContext ctx) { return ctx.modifier().stream() .map(this::visitModifier) .collect(Collectors.toList()); } @Override public List<ModifierNode> visitModifiersOpt(ModifiersOptContext ctx) { if (asBoolean(ctx.modifiers())) { return this.visitModifiers(ctx.modifiers()); } return Collections.emptyList(); } @Override public ModifierNode visitVariableModifier(VariableModifierContext ctx) { if (asBoolean(ctx.annotation())) { return this.configureAST(new ModifierNode(this.visitAnnotation(ctx.annotation()), ctx.getText()), ctx); } if (asBoolean(ctx.m)) { return this.configureAST(new ModifierNode(ctx.m.getType(), ctx.getText()), ctx); } throw createParsingFailedException("Unsupported variable modifier", ctx); } @Override public List<ModifierNode> visitVariableModifiersOpt(VariableModifiersOptContext ctx) { if (asBoolean(ctx.variableModifiers())) { return this.visitVariableModifiers(ctx.variableModifiers()); } return Collections.emptyList(); } @Override public List<ModifierNode> visitVariableModifiers(VariableModifiersContext ctx) { return ctx.variableModifier().stream() .map(this::visitVariableModifier) .collect(Collectors.toList()); } @Override public List<List<AnnotationNode>> visitDims(DimsContext ctx) { List<List<AnnotationNode>> dimList = ctx.annotationsOpt().stream() .map(this::visitAnnotationsOpt) .collect(Collectors.toList()); Collections.reverse(dimList); return dimList; } @Override public List<List<AnnotationNode>> visitDimsOpt(DimsOptContext ctx) { if (!asBoolean(ctx.dims())) { return Collections.emptyList(); } return this.visitDims(ctx.dims()); } // type { -------------------------------------------------------------------- @Override public ClassNode visitType(TypeContext ctx) { if (!asBoolean(ctx)) { return ClassHelper.OBJECT_TYPE; } ClassNode classNode = null; if (asBoolean(ctx.classOrInterfaceType())) { ctx.classOrInterfaceType().putNodeMetaData(IS_INSIDE_INSTANCEOF_EXPR, ctx.getNodeMetaData(IS_INSIDE_INSTANCEOF_EXPR)); classNode = this.visitClassOrInterfaceType(ctx.classOrInterfaceType()); } else if (asBoolean(ctx.primitiveType())) { classNode = this.visitPrimitiveType(ctx.primitiveType()); } if (!asBoolean(classNode)) { throw createParsingFailedException("Unsupported type: " + ctx.getText(), ctx); } classNode.addAnnotations(this.visitAnnotationsOpt(ctx.annotationsOpt())); List<List<AnnotationNode>> dimList = this.visitDimsOpt(ctx.dimsOpt()); if (asBoolean(dimList)) { // clear array's generics type info. Groovy's bug? array's generics type will be ignored. e.g. List<String>[]... p classNode.setGenericsTypes(null); classNode.setUsingGenerics(false); classNode = this.createArrayType(classNode, dimList); } return this.configureAST(classNode, ctx); } @Override public ClassNode visitClassOrInterfaceType(ClassOrInterfaceTypeContext ctx) { ClassNode classNode; if (asBoolean(ctx.qualifiedClassName())) { ctx.qualifiedClassName().putNodeMetaData(IS_INSIDE_INSTANCEOF_EXPR, ctx.getNodeMetaData(IS_INSIDE_INSTANCEOF_EXPR)); classNode = this.visitQualifiedClassName(ctx.qualifiedClassName()); } else { ctx.qualifiedStandardClassName().putNodeMetaData(IS_INSIDE_INSTANCEOF_EXPR, ctx.getNodeMetaData(IS_INSIDE_INSTANCEOF_EXPR)); classNode = this.visitQualifiedStandardClassName(ctx.qualifiedStandardClassName()); } if (asBoolean(ctx.typeArguments())) { classNode.setGenericsTypes( this.visitTypeArguments(ctx.typeArguments())); } return this.configureAST(classNode, ctx); } @Override public GenericsType[] visitTypeArgumentsOrDiamond(TypeArgumentsOrDiamondContext ctx) { if (asBoolean(ctx.typeArguments())) { return this.visitTypeArguments(ctx.typeArguments()); } if (asBoolean(ctx.LT())) { // e.g. <> return new GenericsType[0]; } throw createParsingFailedException("Unsupported type arguments or diamond: " + ctx.getText(), ctx); } @Override public GenericsType[] visitTypeArguments(TypeArgumentsContext ctx) { return ctx.typeArgument().stream().map(this::visitTypeArgument).toArray(GenericsType[]::new); } @Override public GenericsType visitTypeArgument(TypeArgumentContext ctx) { if (asBoolean(ctx.QUESTION())) { ClassNode baseType = this.configureAST(ClassHelper.makeWithoutCaching(QUESTION_STR), ctx.QUESTION()); baseType.addAnnotations(this.visitAnnotationsOpt(ctx.annotationsOpt())); if (!asBoolean(ctx.type())) { GenericsType genericsType = new GenericsType(baseType); genericsType.setWildcard(true); genericsType.setName(QUESTION_STR); return this.configureAST(genericsType, ctx); } ClassNode[] upperBounds = null; ClassNode lowerBound = null; ClassNode classNode = this.visitType(ctx.type()); if (asBoolean(ctx.EXTENDS())) { upperBounds = new ClassNode[]{classNode}; } else if (asBoolean(ctx.SUPER())) { lowerBound = classNode; } GenericsType genericsType = new GenericsType(baseType, upperBounds, lowerBound); genericsType.setWildcard(true); genericsType.setName(QUESTION_STR); return this.configureAST(genericsType, ctx); } else if (asBoolean(ctx.type())) { return this.configureAST( this.createGenericsType( this.visitType(ctx.type())), ctx); } throw createParsingFailedException("Unsupported type argument: " + ctx.getText(), ctx); } @Override public ClassNode visitPrimitiveType(PrimitiveTypeContext ctx) { return this.configureAST(ClassHelper.make(ctx.getText()), ctx); } // } type -------------------------------------------------------------------- @Override public VariableExpression visitVariableDeclaratorId(VariableDeclaratorIdContext ctx) { return this.configureAST(new VariableExpression(this.visitIdentifier(ctx.identifier())), ctx); } @Override public TupleExpression visitVariableNames(VariableNamesContext ctx) { return this.configureAST( new TupleExpression( ctx.variableDeclaratorId().stream() .map(this::visitVariableDeclaratorId) .collect(Collectors.toList()) ), ctx); } @Override public BlockStatement visitBlockStatementsOpt(BlockStatementsOptContext ctx) { if (asBoolean(ctx.blockStatements())) { return this.configureAST(this.visitBlockStatements(ctx.blockStatements()), ctx); } return this.configureAST(this.createBlockStatement(), ctx); } @Override public BlockStatement visitBlockStatements(BlockStatementsContext ctx) { return this.configureAST( this.createBlockStatement( ctx.blockStatement().stream() .map(this::visitBlockStatement) .filter(e -> asBoolean(e)) .collect(Collectors.toList())), ctx); } @Override public Statement visitBlockStatement(BlockStatementContext ctx) { if (asBoolean(ctx.localVariableDeclaration())) { return this.configureAST(this.visitLocalVariableDeclaration(ctx.localVariableDeclaration()), ctx); } if (asBoolean(ctx.statement())) { Object astNode = this.visit(ctx.statement()); //this.configureAST((Statement) this.visit(ctx.statement()), ctx); if (astNode instanceof MethodNode) { throw createParsingFailedException("Method definition not expected here", ctx); } else { return (Statement) astNode; } } throw createParsingFailedException("Unsupported block statement: " + ctx.getText(), ctx); } @Override public List<AnnotationNode> visitAnnotationsOpt(AnnotationsOptContext ctx) { if (!asBoolean(ctx)) { return Collections.emptyList(); } return ctx.annotation().stream() .map(this::visitAnnotation) .collect(Collectors.toList()); } @Override public AnnotationNode visitAnnotation(AnnotationContext ctx) { String annotationName = this.visitAnnotationName(ctx.annotationName()); AnnotationNode annotationNode = new AnnotationNode(ClassHelper.make(annotationName)); List<Pair<String, Expression>> annotationElementValues = this.visitElementValues(ctx.elementValues()); annotationElementValues.forEach(e -> annotationNode.addMember(e.getKey(), e.getValue())); return this.configureAST(annotationNode, ctx); } @Override public List<Pair<String, Expression>> visitElementValues(ElementValuesContext ctx) { if (!asBoolean(ctx)) { return Collections.emptyList(); } List<Pair<String, Expression>> annotationElementValues = new LinkedList<>(); if (asBoolean(ctx.elementValuePairs())) { this.visitElementValuePairs(ctx.elementValuePairs()).entrySet().forEach(e -> { annotationElementValues.add(new Pair<>(e.getKey(), e.getValue())); }); } else if (asBoolean(ctx.elementValue())) { annotationElementValues.add(new Pair<>(VALUE_STR, this.visitElementValue(ctx.elementValue()))); } return annotationElementValues; } @Override public String visitAnnotationName(AnnotationNameContext ctx) { return this.visitQualifiedClassName(ctx.qualifiedClassName()).getName(); } @Override public Map<String, Expression> visitElementValuePairs(ElementValuePairsContext ctx) { return ctx.elementValuePair().stream() .map(this::visitElementValuePair) .collect(Collectors.toMap( Pair::getKey, Pair::getValue, (k, v) -> { throw new IllegalStateException(String.format("Duplicate key %s", k)); }, LinkedHashMap::new )); } @Override public Pair<String, Expression> visitElementValuePair(ElementValuePairContext ctx) { return new Pair<>(ctx.elementValuePairName().getText(), this.visitElementValue(ctx.elementValue())); } @Override public Expression visitElementValue(ElementValueContext ctx) { if (asBoolean(ctx.expression())) { return this.configureAST((Expression) this.visit(ctx.expression()), ctx); } if (asBoolean(ctx.annotation())) { return this.configureAST(new AnnotationConstantExpression(this.visitAnnotation(ctx.annotation())), ctx); } if (asBoolean(ctx.elementValueArrayInitializer())) { return this.configureAST(this.visitElementValueArrayInitializer(ctx.elementValueArrayInitializer()), ctx); } throw createParsingFailedException("Unsupported element value: " + ctx.getText(), ctx); } @Override public ListExpression visitElementValueArrayInitializer(ElementValueArrayInitializerContext ctx) { return this.configureAST(new ListExpression(ctx.elementValue().stream().map(this::visitElementValue).collect(Collectors.toList())), ctx); } @Override public String visitClassName(ClassNameContext ctx) { String text = ctx.getText(); if (!text.contains("\\")) { return text; } return StringUtils.replaceHexEscapes(text); } @Override public String visitIdentifier(IdentifierContext ctx) { String text = ctx.getText(); if (!text.contains("\\")) { return text; } return StringUtils.replaceHexEscapes(text); } @Override public String visitQualifiedName(QualifiedNameContext ctx) { return ctx.qualifiedNameElement().stream() .map(ParseTree::getText) .collect(Collectors.joining(DOT_STR)); } @Override public ClassNode visitAnnotatedQualifiedClassName(AnnotatedQualifiedClassNameContext ctx) { ClassNode classNode = this.visitQualifiedClassName(ctx.qualifiedClassName()); classNode.addAnnotations(this.visitAnnotationsOpt(ctx.annotationsOpt())); return classNode; } @Override public ClassNode[] visitQualifiedClassNameList(QualifiedClassNameListContext ctx) { if (!asBoolean(ctx)) { return new ClassNode[0]; } return ctx.annotatedQualifiedClassName().stream() .map(this::visitAnnotatedQualifiedClassName) .toArray(ClassNode[]::new); } @Override public ClassNode visitQualifiedClassName(QualifiedClassNameContext ctx) { return this.createClassNode(ctx); } @Override public ClassNode visitQualifiedStandardClassName(QualifiedStandardClassNameContext ctx) { return this.createClassNode(ctx); } private ClassNode createClassNode(GroovyParserRuleContext ctx) { ClassNode result = ClassHelper.make(ctx.getText()); if (!isTrue(ctx, IS_INSIDE_INSTANCEOF_EXPR)) { // type in the "instanceof" expression should not have proxy to redirect to it result = this.proxyClassNode(result); } return this.configureAST(result, ctx); } private ClassNode proxyClassNode(ClassNode classNode) { if (!classNode.isUsingGenerics()) { return classNode; } ClassNode cn = ClassHelper.makeWithoutCaching(classNode.getName()); cn.setRedirect(classNode); return cn; } /** * Visit tree safely, no NPE occurred when the tree is null. * * @param tree an AST node * @return the visiting result */ @Override public Object visit(ParseTree tree) { if (!asBoolean(tree)) { return null; } return super.visit(tree); } // e.g. obj.a(1, 2) or obj.a 1, 2 private MethodCallExpression createMethodCallExpression(PropertyExpression propertyExpression, Expression arguments) { MethodCallExpression methodCallExpression = new MethodCallExpression( propertyExpression.getObjectExpression(), propertyExpression.getProperty(), arguments ); methodCallExpression.setImplicitThis(false); methodCallExpression.setSafe(propertyExpression.isSafe()); methodCallExpression.setSpreadSafe(propertyExpression.isSpreadSafe()); // method call obj*.m(): "safe"(false) and "spreadSafe"(true) // property access obj*.p: "safe"(true) and "spreadSafe"(true) // so we have to reset safe here. if (propertyExpression.isSpreadSafe()) { methodCallExpression.setSafe(false); } // if the generics types meta data is not empty, it is a generic method call, e.g. obj.<Integer>a(1, 2) methodCallExpression.setGenericsTypes( propertyExpression.getNodeMetaData(PATH_EXPRESSION_BASE_EXPR_GENERICS_TYPES)); return methodCallExpression; } // e.g. m(1, 2) or m 1, 2 private MethodCallExpression createMethodCallExpression(Expression baseExpr, Expression arguments) { MethodCallExpression methodCallExpression = new MethodCallExpression( VariableExpression.THIS_EXPRESSION, (baseExpr instanceof VariableExpression) ? this.createConstantExpression(baseExpr) : baseExpr, arguments ); return methodCallExpression; } private Parameter processFormalParameter(GroovyParserRuleContext ctx, VariableModifiersOptContext variableModifiersOptContext, TypeContext typeContext, TerminalNode ellipsis, VariableDeclaratorIdContext variableDeclaratorIdContext, ExpressionContext expressionContext) { ClassNode classNode = this.visitType(typeContext); if (asBoolean(ellipsis)) { classNode = this.configureAST(classNode.makeArray(), classNode); } Parameter parameter = new ModifierManager(this, this.visitVariableModifiersOpt(variableModifiersOptContext)) .processParameter( this.configureAST( new Parameter( classNode, this.visitVariableDeclaratorId(variableDeclaratorIdContext).getName() ), ctx ) ); if (asBoolean(expressionContext)) { parameter.setInitialExpression((Expression) this.visit(expressionContext)); } return parameter; } private Expression createPathExpression(Expression primaryExpr, List<? extends PathElementContext> pathElementContextList) { return (Expression) pathElementContextList.stream() .map(e -> (Object) e) .reduce(primaryExpr, (r, e) -> { PathElementContext pathElementContext = (PathElementContext) e; pathElementContext.putNodeMetaData(PATH_EXPRESSION_BASE_EXPR, r); return this.visitPathElement(pathElementContext); } ); } private GenericsType createGenericsType(ClassNode classNode) { return this.configureAST(new GenericsType(classNode), classNode); } private ConstantExpression createConstantExpression(Expression expression) { if (expression instanceof ConstantExpression) { return (ConstantExpression) expression; } return this.configureAST(new ConstantExpression(expression.getText()), expression); } private BinaryExpression createBinaryExpression(ExpressionContext left, Token op, ExpressionContext right) { return new BinaryExpression((Expression) this.visit(left), this.createGroovyToken(op), (Expression) this.visit(right)); } private BinaryExpression createBinaryExpression(ExpressionContext left, Token op, ExpressionContext right, ExpressionContext ctx) { BinaryExpression binaryExpression = this.createBinaryExpression(left, op, right); if (isTrue(ctx, IS_INSIDE_CONDITIONAL_EXPRESSION)) { return this.configureAST(binaryExpression, op); } return this.configureAST(binaryExpression, ctx); } private Statement unpackStatement(Statement statement) { if (statement instanceof DeclarationListStatement) { List<ExpressionStatement> expressionStatementList = ((DeclarationListStatement) statement).getDeclarationStatements(); if (1 == expressionStatementList.size()) { return expressionStatementList.get(0); } return this.configureAST(this.createBlockStatement(statement), statement); // if DeclarationListStatement contains more than 1 declarations, maybe it's better to create a block to hold them } return statement; } public BlockStatement createBlockStatement(Statement... statements) { return this.createBlockStatement(Arrays.asList(statements)); } private BlockStatement createBlockStatement(List<Statement> statementList) { return this.appendStatementsToBlockStatement(new BlockStatement(), statementList); } public BlockStatement appendStatementsToBlockStatement(BlockStatement bs, Statement... statements) { return this.appendStatementsToBlockStatement(bs, Arrays.asList(statements)); } private BlockStatement appendStatementsToBlockStatement(BlockStatement bs, List<Statement> statementList) { return (BlockStatement) statementList.stream() .reduce(bs, (r, e) -> { BlockStatement blockStatement = (BlockStatement) r; if (e instanceof DeclarationListStatement) { ((DeclarationListStatement) e).getDeclarationStatements().forEach(blockStatement::addStatement); } else { blockStatement.addStatement(e); } return blockStatement; }); } private boolean isAnnotationDeclaration(ClassNode classNode) { return asBoolean(classNode) && classNode.isAnnotationDefinition(); } private boolean isSyntheticPublic( boolean isAnnotationDeclaration, boolean isAnonymousInnerEnumDeclaration, boolean hasReturnType, ModifierManager modifierManager ) { return this.isSyntheticPublic( isAnnotationDeclaration, isAnonymousInnerEnumDeclaration, modifierManager.containsAnnotations(), modifierManager.containsVisibilityModifier(), modifierManager.containsNonVisibilityModifier(), hasReturnType, modifierManager.contains(DEF)); } /** * @param isAnnotationDeclaration whether the method is defined in an annotation * @param isAnonymousInnerEnumDeclaration whether the method is defined in an anonymous inner enum * @param hasAnnotation whether the method declaration has annotations * @param hasVisibilityModifier whether the method declaration contains visibility modifier(e.g. public, protected, private) * @param hasModifier whether the method declaration has modifier(e.g. visibility modifier, final, static and so on) * @param hasReturnType whether the method declaration has an return type(e.g. String, generic types) * @param hasDef whether the method declaration using def keyword * @return the result */ private boolean isSyntheticPublic( boolean isAnnotationDeclaration, boolean isAnonymousInnerEnumDeclaration, boolean hasAnnotation, boolean hasVisibilityModifier, boolean hasModifier, boolean hasReturnType, boolean hasDef) { if (hasVisibilityModifier) { return false; } if (isAnnotationDeclaration) { return true; } if (hasDef && hasReturnType) { return true; } if (hasModifier || hasAnnotation || !hasReturnType) { return true; } return isAnonymousInnerEnumDeclaration; } // the mixins of interface and annotation should be null private void hackMixins(ClassNode classNode) { try { // FIXME Hack with visibility. Field field = ClassNode.class.getDeclaredField("mixins"); field.setAccessible(true); field.set(classNode, null); } catch (IllegalAccessException | NoSuchFieldException e) { throw new GroovyBugError("Failed to access mixins field", e); } } private static final Map<ClassNode, Object> TYPE_DEFAULT_VALUE_MAP = Maps.of( ClassHelper.int_TYPE, 0, ClassHelper.long_TYPE, 0L, ClassHelper.double_TYPE, 0.0D, ClassHelper.float_TYPE, 0.0F, ClassHelper.short_TYPE, (short) 0, ClassHelper.byte_TYPE, (byte) 0, ClassHelper.char_TYPE, (char) 0, ClassHelper.boolean_TYPE, Boolean.FALSE ); private Object findDefaultValueByType(ClassNode type) { return TYPE_DEFAULT_VALUE_MAP.get(type); } private boolean isPackageInfoDeclaration() { String name = this.sourceUnit.getName(); return null != name && name.endsWith(PACKAGE_INFO_FILE_NAME); } private boolean isBlankScript(CompilationUnitContext ctx) { return moduleNode.getStatementBlock().isEmpty() && moduleNode.getMethods().isEmpty() && moduleNode.getClasses().isEmpty(); } private boolean isInsideParentheses(NodeMetaDataHandler nodeMetaDataHandler) { Integer insideParenLevel = nodeMetaDataHandler.getNodeMetaData(INSIDE_PARENTHESES_LEVEL); if (null != insideParenLevel) { return insideParenLevel > 0; } return false; } private void addEmptyReturnStatement() { moduleNode.addStatement(ReturnStatement.RETURN_NULL_OR_VOID); } private void addPackageInfoClassNode() { List<ClassNode> classNodeList = moduleNode.getClasses(); ClassNode packageInfoClassNode = ClassHelper.make(moduleNode.getPackageName() + PACKAGE_INFO); if (!classNodeList.contains(packageInfoClassNode)) { moduleNode.addClass(packageInfoClassNode); } } private org.codehaus.groovy.syntax.Token createGroovyTokenByType(Token token, int type) { if (null == token) { throw new IllegalArgumentException("token should not be null"); } return new org.codehaus.groovy.syntax.Token(type, token.getText(), token.getLine(), token.getCharPositionInLine()); } private org.codehaus.groovy.syntax.Token createGroovyToken(Token token) { return this.createGroovyToken(token, 1); } private org.codehaus.groovy.syntax.Token createGroovyToken(Token token, int cardinality) { String text = StringGroovyMethods.multiply((CharSequence) token.getText(), cardinality); return new org.codehaus.groovy.syntax.Token( "..<".equals(token.getText()) || "..".equals(token.getText()) ? Types.RANGE_OPERATOR : Types.lookup(text, Types.ANY), text, token.getLine(), token.getCharPositionInLine() + 1 ); } /* private org.codehaus.groovy.syntax.Token createGroovyToken(String text, int startLine, int startColumn) { return new org.codehaus.groovy.syntax.Token( Types.lookup(text, Types.ANY), text, startLine, startColumn ); } */ /** * set the script source position */ private void configureScriptClassNode() { ClassNode scriptClassNode = moduleNode.getScriptClassDummy(); if (!asBoolean(scriptClassNode)) { return; } List<Statement> statements = moduleNode.getStatementBlock().getStatements(); if (!statements.isEmpty()) { Statement firstStatement = statements.get(0); Statement lastStatement = statements.get(statements.size() - 1); scriptClassNode.setSourcePosition(firstStatement); scriptClassNode.setLastColumnNumber(lastStatement.getLastColumnNumber()); scriptClassNode.setLastLineNumber(lastStatement.getLastLineNumber()); } } /** * Sets location(lineNumber, colNumber, lastLineNumber, lastColumnNumber) for node using standard context information. * Note: this method is implemented to be closed over ASTNode. It returns same node as it received in arguments. * * @param astNode Node to be modified. * @param ctx Context from which information is obtained. * @return Modified astNode. */ private <T extends ASTNode> T configureAST(T astNode, GroovyParserRuleContext ctx) { Token start = ctx.getStart(); Token stop = ctx.getStop(); astNode.setLineNumber(start.getLine()); astNode.setColumnNumber(start.getCharPositionInLine() + 1); Pair<Integer, Integer> stopTokenEndPosition = endPosition(stop); astNode.setLastLineNumber(stopTokenEndPosition.getKey()); astNode.setLastColumnNumber(stopTokenEndPosition.getValue()); return astNode; } private Pair<Integer, Integer> endPosition(Token token) { String stopText = token.getText(); int stopTextLength = 0; int newLineCnt = 0; if (null != stopText) { stopTextLength = stopText.length(); newLineCnt = (int) StringUtils.countChar(stopText, '\n'); } if (0 == newLineCnt) { return new Pair<Integer, Integer>(token.getLine(), token.getCharPositionInLine() + 1 + token.getText().length()); } else { // e.g. GStringEnd contains newlines, we should fix the location info return new Pair<Integer, Integer>(token.getLine() + newLineCnt, stopTextLength - stopText.lastIndexOf('\n')); } } private <T extends ASTNode> T configureAST(T astNode, TerminalNode terminalNode) { return this.configureAST(astNode, terminalNode.getSymbol()); } private <T extends ASTNode> T configureAST(T astNode, Token token) { astNode.setLineNumber(token.getLine()); astNode.setColumnNumber(token.getCharPositionInLine() + 1); astNode.setLastLineNumber(token.getLine()); astNode.setLastColumnNumber(token.getCharPositionInLine() + 1 + token.getText().length()); return astNode; } private <T extends ASTNode> T configureAST(T astNode, ASTNode source) { astNode.setLineNumber(source.getLineNumber()); astNode.setColumnNumber(source.getColumnNumber()); astNode.setLastLineNumber(source.getLastLineNumber()); astNode.setLastColumnNumber(source.getLastColumnNumber()); return astNode; } private <T extends ASTNode> T configureAST(T astNode, GroovyParserRuleContext ctx, ASTNode stop) { Token start = ctx.getStart(); astNode.setLineNumber(start.getLine()); astNode.setColumnNumber(start.getCharPositionInLine() + 1); if (asBoolean(stop)) { astNode.setLastLineNumber(stop.getLastLineNumber()); astNode.setLastColumnNumber(stop.getLastColumnNumber()); } else { Pair<Integer, Integer> endPosition = endPosition(start); astNode.setLastLineNumber(endPosition.getKey()); astNode.setLastColumnNumber(endPosition.getValue()); } return astNode; } private <T extends ASTNode> T configureAST(T astNode, ASTNode start, ASTNode stop) { astNode.setLineNumber(start.getLineNumber()); astNode.setColumnNumber(start.getColumnNumber()); if (asBoolean(stop)) { astNode.setLastLineNumber(stop.getLastLineNumber()); astNode.setLastColumnNumber(stop.getLastColumnNumber()); } else { astNode.setLastLineNumber(start.getLastLineNumber()); astNode.setLastColumnNumber(start.getLastColumnNumber()); } return astNode; } private boolean isTrue(NodeMetaDataHandler nodeMetaDataHandler, String key) { Object nmd = nodeMetaDataHandler.getNodeMetaData(key); if (null == nmd) { return false; } if (!(nmd instanceof Boolean)) { throw new GroovyBugError(nodeMetaDataHandler + " node meta data[" + key + "] is not an instance of Boolean"); } return (Boolean) nmd; } private CompilationFailedException createParsingFailedException(String msg, GroovyParserRuleContext ctx) { return createParsingFailedException( new SyntaxException(msg, ctx.start.getLine(), ctx.start.getCharPositionInLine() + 1, ctx.stop.getLine(), ctx.stop.getCharPositionInLine() + 1 + ctx.stop.getText().length())); } public CompilationFailedException createParsingFailedException(String msg, ASTNode node) { Objects.requireNonNull(node, "node passed into createParsingFailedException should not be null"); return createParsingFailedException( new SyntaxException(msg, node.getLineNumber(), node.getColumnNumber(), node.getLastLineNumber(), node.getLastColumnNumber())); } /* private CompilationFailedException createParsingFailedException(String msg, Token token) { return createParsingFailedException( new SyntaxException(msg, token.getLine(), token.getCharPositionInLine() + 1, token.getLine(), token.getCharPositionInLine() + 1 + token.getText().length())); } */ private CompilationFailedException createParsingFailedException(Throwable t) { if (t instanceof SyntaxException) { this.collectSyntaxError((SyntaxException) t); } else if (t instanceof GroovySyntaxError) { GroovySyntaxError groovySyntaxError = (GroovySyntaxError) t; this.collectSyntaxError( new SyntaxException( groovySyntaxError.getMessage(), groovySyntaxError, groovySyntaxError.getLine(), groovySyntaxError.getColumn())); } else if (t instanceof Exception) { this.collectException((Exception) t); } return new CompilationFailedException( CompilePhase.PARSING.getPhaseNumber(), this.sourceUnit, t); } private void collectSyntaxError(SyntaxException e) { sourceUnit.getErrorCollector().addFatalError(new SyntaxErrorMessage(e, sourceUnit)); } private void collectException(Exception e) { sourceUnit.getErrorCollector().addException(e, this.sourceUnit); } private String readSourceCode(SourceUnit sourceUnit) { String text = null; try { text = IOGroovyMethods.getText(sourceUnit.getSource().getReader()); } catch (IOException e) { LOGGER.severe(createExceptionMessage(e)); throw new RuntimeException("Error occurred when reading source code.", e); } return text; } private ANTLRErrorListener createANTLRErrorListener() { return new ANTLRErrorListener() { @Override public void syntaxError( Recognizer recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) { collectSyntaxError(new SyntaxException(msg, line, charPositionInLine + 1)); } }; } private void removeErrorListeners() { lexer.removeErrorListeners(); parser.removeErrorListeners(); } private void addErrorListeners() { lexer.removeErrorListeners(); lexer.addErrorListener(this.createANTLRErrorListener()); parser.removeErrorListeners(); parser.addErrorListener(this.createANTLRErrorListener()); } private String createExceptionMessage(Throwable t) { StringWriter sw = new StringWriter(); try (PrintWriter pw = new PrintWriter(sw)) { t.printStackTrace(pw); } return sw.toString(); } private class DeclarationListStatement extends Statement { private List<ExpressionStatement> declarationStatements; public DeclarationListStatement(DeclarationExpression... declarations) { this(Arrays.asList(declarations)); } public DeclarationListStatement(List<DeclarationExpression> declarations) { this.declarationStatements = declarations.stream() .map(e -> configureAST(new ExpressionStatement(e), e)) .collect(Collectors.toList()); } public List<ExpressionStatement> getDeclarationStatements() { List<String> declarationListStatementLabels = this.getStatementLabels(); this.declarationStatements.forEach(e -> { if (null != declarationListStatementLabels) { // clear existing statement labels before setting labels if (null != e.getStatementLabels()) { e.getStatementLabels().clear(); } declarationListStatementLabels.forEach(e::addStatementLabel); } }); return this.declarationStatements; } public List<DeclarationExpression> getDeclarationExpressions() { return this.declarationStatements.stream() .map(e -> (DeclarationExpression) e.getExpression()) .collect(Collectors.toList()); } } private static class Pair<K, V> { private K key; private V value; public Pair(K key, V value) { this.key = key; this.value = value; } public K getKey() { return key; } public void setKey(K key) { this.key = key; } public V getValue() { return value; } public void setValue(V value) { this.value = value; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pair<?, ?> pair = (Pair<?, ?>) o; return Objects.equals(key, pair.key) && Objects.equals(value, pair.value); } @Override public int hashCode() { return Objects.hash(key, value); } } private final ModuleNode moduleNode; private final SourceUnit sourceUnit; private final ClassLoader classLoader; // Our ClassLoader, which provides information on external types private final GroovyLangLexer lexer; private final GroovyLangParser parser; private final TryWithResourcesASTTransformation tryWithResourcesASTTransformation; private final GroovydocManager groovydocManager; private final List<ClassNode> classNodeList = new LinkedList<>(); private final Deque<ClassNode> classNodeStack = new ArrayDeque<>(); private final Deque<List<InnerClassNode>> anonymousInnerClassesDefinedInMethodStack = new ArrayDeque<>(); private int anonymousInnerClassCounter = 1; private static final String QUESTION_STR = "?"; private static final String DOT_STR = "."; private static final String SUB_STR = "-"; private static final String ASSIGN_STR = "="; private static final String VALUE_STR = "value"; private static final String DOLLAR_STR = "$"; private static final String CALL_STR = "call"; private static final String THIS_STR = "this"; private static final String SUPER_STR = "super"; private static final String VOID_STR = "void"; private static final String PACKAGE_INFO = "package-info"; private static final String PACKAGE_INFO_FILE_NAME = PACKAGE_INFO + ".groovy"; private static final String GROOVY_TRANSFORM_TRAIT = "groovy.transform.Trait"; private static final Set<String> PRIMITIVE_TYPE_SET = Collections.unmodifiableSet(new HashSet<>(Arrays.asList("boolean", "char", "byte", "short", "int", "long", "float", "double"))); private static final Logger LOGGER = Logger.getLogger(AstBuilder.class.getName()); private static final String INSIDE_PARENTHESES_LEVEL = "_INSIDE_PARENTHESES_LEVEL"; private static final String IS_INSIDE_INSTANCEOF_EXPR = "_IS_INSIDE_INSTANCEOF_EXPR"; private static final String IS_SWITCH_DEFAULT = "_IS_SWITCH_DEFAULT"; private static final String IS_NUMERIC = "_IS_NUMERIC"; private static final String IS_STRING = "_IS_STRING"; private static final String IS_INTERFACE_WITH_DEFAULT_METHODS = "_IS_INTERFACE_WITH_DEFAULT_METHODS"; private static final String IS_INSIDE_CONDITIONAL_EXPRESSION = "_IS_INSIDE_CONDITIONAL_EXPRESSION"; private static final String PATH_EXPRESSION_BASE_EXPR = "_PATH_EXPRESSION_BASE_EXPR"; private static final String PATH_EXPRESSION_BASE_EXPR_GENERICS_TYPES = "_PATH_EXPRESSION_BASE_EXPR_GENERICS_TYPES"; private static final String CMD_EXPRESSION_BASE_EXPR = "_CMD_EXPRESSION_BASE_EXPR"; private static final String TYPE_DECLARATION_MODIFIERS = "_TYPE_DECLARATION_MODIFIERS"; private static final String CLASS_DECLARATION_CLASS_NODE = "_CLASS_DECLARATION_CLASS_NODE"; private static final String VARIABLE_DECLARATION_VARIABLE_TYPE = "_VARIABLE_DECLARATION_VARIABLE_TYPE"; private static final String ANONYMOUS_INNER_CLASS_SUPER_CLASS = "_ANONYMOUS_INNER_CLASS_SUPER_CLASS"; private static final String INTEGER_LITERAL_TEXT = "_INTEGER_LITERAL_TEXT"; private static final String FLOATING_POINT_LITERAL_TEXT = "_FLOATING_POINT_LITERAL_TEXT"; private static final String CLASS_NAME = "_CLASS_NAME"; }
Refine the node position of path expression
src/main/java/org/apache/groovy/parser/antlr4/AstBuilder.java
Refine the node position of path expression
Java
apache-2.0
ad6732179291b8f14c70c5a2220762371206cc58
0
BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH
package de.naoth.rc.tools; import de.naoth.rc.RobotControl; import de.naoth.rc.RobotControlImpl; import de.naoth.rc.core.manager.ObjectListener; import de.naoth.rc.core.manager.SwingCommandExecutor; import de.naoth.rc.core.server.Command; import de.naoth.rc.core.server.ConnectionStatusEvent; import de.naoth.rc.core.server.ConnectionStatusListener; import de.naoth.rc.core.server.ResponseListener; import static de.naoth.rc.statusbar.StatusbarPluginImpl.rc; import java.awt.Component; import java.awt.event.ActionEvent; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.Box; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.SwingConstants; import net.xeoh.plugins.base.Plugin; import net.xeoh.plugins.base.annotations.PluginImplementation; import net.xeoh.plugins.base.annotations.events.PluginLoaded; import net.xeoh.plugins.base.annotations.injections.InjectPlugin; /** * @author Philipp Strobel <[email protected]> */ @PluginImplementation public class CommandRecorder implements Plugin, ConnectionStatusListener, ObjectListener<Command> { @InjectPlugin public static RobotControl robotControl; @InjectPlugin public static SwingCommandExecutor commandExecutor; private static final String REC_PREFIX = "recording_"; private static final String REC_SUFFIX = ".bin"; private static final String MENU_TOOLTIP = "Not connected to robot"; private static final String MENU_REC_START = "Start Recording"; private static final String MENU_REC_STOP = "Stop Recording"; private boolean isRecording = false; private final List<Command> log = new LinkedList<>(); private final JMenu menuMacros = new javax.swing.JMenu("Macros"); private final JMenuItem menuStartRecording = new JMenuItem(MENU_REC_START); /** * Gets called, when the RC plugin was loaded. * Adds the "Macros" menu item to the RC menubar and registers itself as connection listener. * * @param robotControl the RC instance (JFrame) */ @PluginLoaded public void loaded(RobotControl robotControl) { rc.getMessageServer().addConnectionStatusListener(this); menuMacros.setEnabled(false); menuMacros.setToolTipText(MENU_TOOLTIP); menuMacros.setHorizontalTextPosition(SwingConstants.LEADING); menuMacros.add(menuStartRecording); menuMacros.addSeparator(); menuStartRecording.addActionListener((ActionEvent e) -> { toggleRecording(); }); addRecordingsToMenu(); insertMacrosMenuToMenuBar(); } /** * Inserts the "Macros" menu item to the end of the left menubar part. */ private void insertMacrosMenuToMenuBar() { JMenuBar menu = ((RobotControlImpl)robotControl).getJMenuBar(); // find the index of the 'Filler', in order to insert the menu before it int idx = menu.getComponentCount(); for (Component component : menu.getComponents()) { if (component instanceof Box.Filler) { idx = menu.getComponentIndex(component); } } menu.add(menuMacros, idx); } /** * Searches for recoding files and adds them to the macro menu. */ private void addRecordingsToMenu() { Arrays.asList((new File(robotControl.getConfigPath())).listFiles((dir, name) -> { return name.startsWith(REC_PREFIX) && name.endsWith(REC_SUFFIX); })).forEach((f) -> { String name = f.getName().substring(REC_PREFIX.length(), f.getName().length() - REC_SUFFIX.length()); addMenuItem(name); }); } /** * Adds a recording to the macros menu. * Also sets the tooltip and handles the click events. * * @param name the recording name */ private void addMenuItem(String name) { JMenuItem item = new JMenuItem(name); item.setToolTipText("<html>Replays the recorded commands.<br>Use <i>Ctrl+Click</i> to delete this recording.</html>"); item.addActionListener((e) -> { JMenuItem source = (JMenuItem) e.getSource(); if((e.getModifiers() & ActionEvent.CTRL_MASK) == ActionEvent.CTRL_MASK) { // delete requested if(JOptionPane.showConfirmDialog( ((RobotControlImpl)robotControl), "Do you want to remove the recording '"+name+"'?", "Remove recording", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { if(recordingFileName(name).delete()) { menuMacros.remove(source); } } } else { // restore dialog configuration File f = recordingFileName(source.getText()); if(f.isFile()) { try { loadRecording(f); } catch (IOException ex) { Logger.getLogger(RobotControlImpl.class.getName()).log(Level.SEVERE, null, ex); } } else { JOptionPane.showMessageDialog( ((RobotControlImpl)robotControl), "The '"+source.getText()+"' recording file doesn't exists!?", "Missing recording file", JOptionPane.ERROR_MESSAGE); } } }); menuMacros.add(item); } /** * Starts or stops the recording, based on the current state (helper method). */ private void toggleRecording() { if (isRecording) { stopRecording(); } else { startRecording(); } } /** * Starts the recording. * Registers to the message server and updates the ui. */ private void startRecording() { isRecording = true; rc.getMessageServer().addListener(this); menuMacros.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/naoth/rc/res/media-record.png"))); menuStartRecording.setText(MENU_REC_STOP); } /** * Stops the recording. * Unregisters from the message server, updates the ui and saves the recording. */ private void stopRecording() { isRecording = false; rc.getMessageServer().removeListener(this); menuMacros.setIcon(null); menuStartRecording.setText(MENU_REC_START); saveRecording(); } /** * Returns the File for a given recording name (helper method). * * @param name the name of the recording * @return the file object pointing to the file where the recording is/should be saved */ private File recordingFileName(String name) { return new File(robotControl.getConfigPath() + "/" + REC_PREFIX + name + REC_SUFFIX); } /** * Actually saves the recorded commands. * Therefore checks whether commands were recorded and ask for a name for this * recording. The recorded commands are written as serialized java objects to the file. */ private void saveRecording() { // check if something was recorded if (log.isEmpty()) { JOptionPane.showMessageDialog( ((RobotControlImpl)robotControl), "No commands were recorded.", "Nothing recorded", JOptionPane.WARNING_MESSAGE); return; } // Ask for a name for this dialog configuration String inputName = JOptionPane.showInputDialog( ((RobotControlImpl)robotControl), "<html>Set a name for the recorded commands<br>" + "<small>Only alphanumerical characters are allowed and " + "whitespaces are replaced with '_'.</small></html>", "Name of recording", JOptionPane.QUESTION_MESSAGE); // ignore canceled inputs if(inputName == null) { return; } // replace whitespaces with "_" and remove all other "invalid" characters String name = inputName.trim() .replaceAll("[\\s+]", "_") .replaceAll("[^A-Za-z0-9_-]", ""); // ignore empty inputs if(name.isEmpty()) { return; } // create record file File file = recordingFileName(name); // if recording name already exists - ask to overwrite if(file.isFile() && JOptionPane.showConfirmDialog( ((RobotControlImpl)robotControl), "This dialog layout name already exists. Overwrite?", "Overwrite", JOptionPane.YES_NO_OPTION) != JOptionPane.YES_OPTION) { // don't overwrite! return; } // write the logged commands to the record file try { FileOutputStream stream = new FileOutputStream(file); ObjectOutputStream o = new ObjectOutputStream(stream); o.writeObject(log); o.close(); stream.close(); // add the new recording to the macro menu addMenuItem(name); } catch (FileNotFoundException ex) { Logger.getLogger(CommandRecorder.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(CommandRecorder.class.getName()).log(Level.SEVERE, null, ex); } log.clear(); } /** * Loads the recorded commands from the given file. * * @param f * @throws IOException */ private void loadRecording(File f) throws IOException { // if not connect, do not replay commands if (!rc.getMessageServer().isConnected()) { return; } FileInputStream stream = new FileInputStream(f); ObjectInputStream oi = new ObjectInputStream(stream); try { List<Command> commands = (List<Command>) oi.readObject(); for (Command command : commands) { rc.getMessageServer().executeCommand(new ResponseListener() { @Override public void handleResponse(byte[] result, Command command) { System.out.println("Successfully executed command: " + command.getName()); } @Override public void handleError(int code) { System.out.println("Error during command execution, error code: " + code); } }, command); } } catch (ClassNotFoundException ex) { Logger.getLogger(CommandRecorder.class.getName()).log(Level.SEVERE, null, ex); } oi.close(); stream.close(); } /** * Enables the macros menu. * * @param event */ @Override public void connected(ConnectionStatusEvent event) { menuMacros.setEnabled(true); menuMacros.setToolTipText(null); } /** * Disables the macros menu and sets the tooltip. * @param event */ @Override public void disconnected(ConnectionStatusEvent event) { menuMacros.setEnabled(false); menuMacros.setToolTipText(MENU_TOOLTIP); } /** * Records all 'set' commands. * * @param cmd */ @Override public void newObjectReceived(Command cmd) { // only store the 'set' commands if (cmd.getName().endsWith(":set") || cmd.getName().endsWith(":set_agent")) { log.add(cmd); Logger.getLogger(CommandRecorder.class.getName()).log(Level.INFO, "Command logged: " + cmd.getName()); } } /** * Ignore any errors. * * @param cause */ @Override public void errorOccured(String cause) { /* should never happen! */ } }
RobotControl/src/de/naoth/rc/tools/CommandRecorder.java
package de.naoth.rc.tools; import de.naoth.rc.RobotControl; import de.naoth.rc.RobotControlImpl; import de.naoth.rc.core.manager.ObjectListener; import de.naoth.rc.core.manager.SwingCommandExecutor; import de.naoth.rc.core.server.Command; import de.naoth.rc.core.server.ConnectionStatusEvent; import de.naoth.rc.core.server.ConnectionStatusListener; import de.naoth.rc.core.server.ResponseListener; import static de.naoth.rc.statusbar.StatusbarPluginImpl.rc; import java.awt.Component; import java.awt.event.ActionEvent; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.Box; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.SwingConstants; import net.xeoh.plugins.base.Plugin; import net.xeoh.plugins.base.annotations.PluginImplementation; import net.xeoh.plugins.base.annotations.events.PluginLoaded; import net.xeoh.plugins.base.annotations.injections.InjectPlugin; /** * @author Philipp Strobel <[email protected]> */ @PluginImplementation public class CommandRecorder implements Plugin, ConnectionStatusListener, ObjectListener<Command> { @InjectPlugin public static RobotControl robotControl; @InjectPlugin public static SwingCommandExecutor commandExecutor; private static final String REC_PREFIX = "recording_"; private static final String REC_SUFFIX = ".bin"; private static final String MENU_TOOLTIP = "Not connected to robot"; private static final String MENU_REC_START = "Start Recording"; private static final String MENU_REC_STOP = "Stop Recording"; private boolean isRecording = false; private final List<Command> log = new LinkedList<>(); private final JMenu menuMacros = new javax.swing.JMenu("Macros"); private final JMenuItem menuStartRecording = new JMenuItem(MENU_REC_START); /** * Gets called, when the RC plugin was loaded. * Adds the "Macros" menu item to the RC menubar and registers itself as connection listener. * * @param robotControl the RC instance (JFrame) */ @PluginLoaded public void loaded(RobotControl robotControl) { rc.getMessageServer().addConnectionStatusListener(this); menuMacros.setEnabled(false); menuMacros.setToolTipText(MENU_TOOLTIP); menuMacros.setHorizontalTextPosition(SwingConstants.LEADING); menuMacros.add(menuStartRecording); menuMacros.addSeparator(); menuStartRecording.addActionListener((ActionEvent e) -> { toggleRecording(); }); addRecordingsToMenu(); insertMacrosMenuToMenuBar(); } /** * Inserts the "Macros" menu item to the end of the left menubar part. */ private void insertMacrosMenuToMenuBar() { JMenuBar menu = ((RobotControlImpl)robotControl).getJMenuBar(); // find the index of the 'Filler', in order to insert the menu before it int idx = menu.getComponentCount(); for (Component component : menu.getComponents()) { if (component instanceof Box.Filler) { idx = menu.getComponentIndex(component); } } menu.add(menuMacros, idx); } /** * Searches for recoding files and adds them to the macro menu. */ private void addRecordingsToMenu() { Arrays.asList((new File(robotControl.getConfigPath())).listFiles((dir, name) -> { return name.startsWith(REC_PREFIX) && name.endsWith(REC_SUFFIX); })).forEach((f) -> { String name = f.getName().substring(REC_PREFIX.length(), f.getName().length() - REC_SUFFIX.length()); addMenuItem(name); }); } /** * Adds a recording to the macros menu. * Also sets the tooltip and handles the click events. * * @param name the recording name */ private void addMenuItem(String name) { JMenuItem item = new JMenuItem(name); item.setToolTipText("<html>Replays the recorded commands.<br>Use <i>Ctrl+Click</i> to delete this recording.</html>"); item.addActionListener((e) -> { JMenuItem source = (JMenuItem) e.getSource(); if((e.getModifiers() & ActionEvent.CTRL_MASK) == ActionEvent.CTRL_MASK) { // delete requested if(JOptionPane.showConfirmDialog( ((RobotControlImpl)robotControl), "Do you want to remove the recording '"+name+"'?", "Remove recording", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { if(recordingFileName(name).delete()) { menuMacros.remove(source); } } } else { // restore dialog configuration File f = recordingFileName(source.getText()); if(f.isFile()) { try { loadRecording(f); } catch (IOException ex) { Logger.getLogger(RobotControlImpl.class.getName()).log(Level.SEVERE, null, ex); } } else { JOptionPane.showMessageDialog( ((RobotControlImpl)robotControl), "The '"+source.getText()+"' recording file doesn't exists!?", "Missing recording file", JOptionPane.ERROR_MESSAGE); } } }); menuMacros.add(item); } /** * Starts or stops the recording, based on the current state (helper method). */ private void toggleRecording() { if (isRecording) { stopRecording(); } else { startRecording(); } } /** * Starts the recording. * Registers to the message server and updates the ui. */ private void startRecording() { isRecording = true; rc.getMessageServer().addListener(this); menuMacros.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/naoth/rc/res/media-record.png"))); menuStartRecording.setText(MENU_REC_STOP); } /** * Stops the recording. * Unregisters from the message server, updates the ui and saves the recording. */ private void stopRecording() { isRecording = false; rc.getMessageServer().removeListener(this); menuMacros.setIcon(null); menuStartRecording.setText(MENU_REC_START); saveRecording(); } /** * Returns the File for a given recording name (helper method). * * @param name the name of the recording * @return the file object pointing to the file where the recording is/should be saved */ private File recordingFileName(String name) { return new File(robotControl.getConfigPath() + "/" + REC_PREFIX + name + REC_SUFFIX); } /** * Actually saves the recorded commands. * Therefore checks whether commands were recorded and ask for a name for this * recording. The recorded commands are written as serialized java objects to the file. */ private void saveRecording() { // check if something was recorded if (log.isEmpty()) { JOptionPane.showMessageDialog( ((RobotControlImpl)robotControl), "No commands were recorded.", "Nothing recorded", JOptionPane.WARNING_MESSAGE); return; } // Ask for a name for this dialog configuration String inputName = JOptionPane.showInputDialog("Set a name for the recorded commands"); // ignore canceled inputs if(inputName == null) { return; } // replace "invalid" characters String name = inputName.trim().replaceAll("[^A-Za-z0-9_-]", ""); // ignore empty inputs if(name.isEmpty()) { return; } // create record file File file = recordingFileName(name); // if recording name already exists - ask to overwrite if(file.isFile() && JOptionPane.showConfirmDialog( ((RobotControlImpl)robotControl), "This dialog layout name already exists. Overwrite?", "Overwrite", JOptionPane.YES_NO_OPTION) != JOptionPane.YES_OPTION) { // don't overwrite! return; } // write the logged commands to the record file try { FileOutputStream stream = new FileOutputStream(file); ObjectOutputStream o = new ObjectOutputStream(stream); o.writeObject(log); o.close(); stream.close(); // add the new recording to the macro menu addMenuItem(name); } catch (FileNotFoundException ex) { Logger.getLogger(CommandRecorder.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(CommandRecorder.class.getName()).log(Level.SEVERE, null, ex); } log.clear(); } /** * Loads the recorded commands from the given file. * * @param f * @throws IOException */ private void loadRecording(File f) throws IOException { // if not connect, do not replay commands if (!rc.getMessageServer().isConnected()) { return; } FileInputStream stream = new FileInputStream(f); ObjectInputStream oi = new ObjectInputStream(stream); try { List<Command> commands = (List<Command>) oi.readObject(); for (Command command : commands) { rc.getMessageServer().executeCommand(new ResponseListener() { @Override public void handleResponse(byte[] result, Command command) { System.out.println("Successfully executed command: " + command.getName()); } @Override public void handleError(int code) { System.out.println("Error during command execution, error code: " + code); } }, command); } } catch (ClassNotFoundException ex) { Logger.getLogger(CommandRecorder.class.getName()).log(Level.SEVERE, null, ex); } oi.close(); stream.close(); } /** * Enables the macros menu. * * @param event */ @Override public void connected(ConnectionStatusEvent event) { menuMacros.setEnabled(true); menuMacros.setToolTipText(null); } /** * Disables the macros menu and sets the tooltip. * @param event */ @Override public void disconnected(ConnectionStatusEvent event) { menuMacros.setEnabled(false); menuMacros.setToolTipText(MENU_TOOLTIP); } /** * Records all 'set' commands. * * @param cmd */ @Override public void newObjectReceived(Command cmd) { // only store the 'set' commands if (cmd.getName().endsWith(":set") || cmd.getName().endsWith(":set_agent")) { log.add(cmd); Logger.getLogger(CommandRecorder.class.getName()).log(Level.INFO, "Command logged: " + cmd.getName()); } } /** * Ignore any errors. * * @param cause */ @Override public void errorOccured(String cause) { /* should never happen! */ } }
added description to input dialog, which characters are allowed and replace whitespaces with underscores before removing "invalid" chars
RobotControl/src/de/naoth/rc/tools/CommandRecorder.java
added description to input dialog, which characters are allowed and replace whitespaces with underscores before removing "invalid" chars
Java
bsd-3-clause
5b06adbc92044fdb2f73702ae79407282ded9281
0
f97one/android_Car-Kei-Bo
package net.formula97.andorid.car_kei_bo; import android.app.Activity; import android.content.Intent; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; //import android.view.Menu; //import android.view.MenuInflater; //import android.view.MenuItem; import android.text.SpannableStringBuilder; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.CheckBox; import android.widget.TextView; /** * 「クルマを追加」画面を扱うクラス。 * @author kazutoshi * */ public class AddMyCar extends Activity { private DbManager dbman = new DbManager(this); public static SQLiteDatabase db; private static final boolean FLAG_DEFAULT_ON = true; private static final boolean FLAG_DEFAULT_OFF = false; // ウィジェットを扱うための定義 TextView textview_addCarName; CheckBox checkbox_setDefault; Button button_addCar; Button button_cancel_addCar; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.addcar); // ウィジェットを扱うための定義 // プログラムから扱うための定数を検索してセット textview_addCarName = (TextView)findViewById(R.id.textview_addCarName); checkbox_setDefault = (CheckBox)findViewById(R.id.checkBox_SetDefault); button_addCar = (Button)findViewById(R.id.button_addCar); button_cancel_addCar = (Button)findViewById(R.id.button_cancel_addCar); } /** * ほかのActivityへ遷移するなどで一時的に処理を停止するときに、システムからコールされる。 * DBの閉じ忘れを防止するため、一律ここでDBをクローズしている。 * @see android.app.Activity#onPause() */ @Override protected void onPause() { // TODO 自動生成されたメソッド・スタブ super.onPause(); dbman.close(); } /** * 画面描画を行うときに必ずシステムからコールされる。 * 上記特徴を利用し、ボタン幅を画面サイズから計算して再設定している。 * @see android.app.Activity#onResume() */ @Override protected void onResume() { // TODO 自動生成されたメソッド・スタブ super.onResume(); /* * ボタンの配置を画面幅の1/2にする処理 * * onCreate()ではなくこちらに書くのは、最終的な画面設定が行われるのがこちらという * Androidのくせによるものである。 */ // 画面幅を取得 int displayWidth = getWindowManager().getDefaultDisplay().getWidth(); // ボタンの幅を、取得した画面幅の1/2にセット button_addCar.setWidth(displayWidth / 2); button_cancel_addCar.setWidth(displayWidth / 2); } /** * 「クルマを追加」ボタンを押したときの処理。 * OnClickListenerをインターフェース実装していない関係で、GUIに紐付けしてボタン処理を書いている。 * ただ、このやり方だとpublicメソッドにしなきゃいけないようだ。 * @param v View型、ボタンを押されたときのId? */ public void onClickAddCar(View v) { String carName; boolean defaultFlags; db = dbman.getWritableDatabase(); // TextViewに入力された値を取得 // getText()はCaheSequence型になるので、Stringにキャストする SpannableStringBuilder sp = (SpannableStringBuilder) textview_addCarName.getText(); carName = sp.toString(); Log.w("CarList", "New Car name = " + carName); // チェックボックスの状態を取得 if (checkbox_setDefault.isChecked()) { /* * チェックボックスにチェックがあれば、 * 1.デフォルトフラグがすでにセットされているかを調べ、 * 2.セットされていればいったんすべてのデフォルトフラグを下げる */ if (dbman.isExistDefaultCarFlag(db)) { int iRet = dbman.clearAllDefaultFlags(db); // デフォルトフラグを下げたことをログに出力する Log.w("CAR_MASTER", "Default Car flags cleared, " + String.valueOf(iRet) + "rows updated."); } defaultFlags = FLAG_DEFAULT_ON; } else { defaultFlags = FLAG_DEFAULT_OFF; } // クルマデータをCAR_MASTERに追加 long lRet = dbman.addNewCar(db, carName, defaultFlags); Log.i("CAR_MASTER", "Car record inserted, New Car Name = " + carName + " , New row ID = " + String.valueOf(lRet) ); dbman.close(); } /** * 「キャンセル」を押したときの処理。 * onClickAddCar()同様、OnClickListenerをインターフェース実装していない関係で、 * GUIに紐付けしてボタン処理を書いている。 * ただ、このやり方だとpublicメソッドにしなきゃいけないようだ。 * @param v View型、ボタンを押されたときのId? */ public void onClickCancel(View v) { // 入力されている値を消す // 「消す」=「空の値をセット」ということらしい textview_addCarName.setText(""); // チェックされていない状態にする checkbox_setDefault.setChecked(false); } }
src/net/formula97/andorid/car_kei_bo/AddMyCar.java
package net.formula97.andorid.car_kei_bo; import android.app.Activity; import android.content.Intent; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; //import android.view.Menu; //import android.view.MenuInflater; //import android.view.MenuItem; import android.text.SpannableStringBuilder; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.CheckBox; import android.widget.TextView; public class AddMyCar extends Activity { private DbManager dbman = new DbManager(this); public static SQLiteDatabase db; private static final boolean FLAG_DEFAULT_ON = true; private static final boolean FLAG_DEFAULT_OFF = false; // ウィジェットを扱うための定義 TextView textview_addCarName; CheckBox checkbox_setDefault; Button button_addCar; Button button_cancel_addCar; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.addcar); // ウィジェットを扱うための定義 // プログラムから扱うための定数を検索してセット textview_addCarName = (TextView)findViewById(R.id.textview_addCarName); checkbox_setDefault = (CheckBox)findViewById(R.id.checkBox_SetDefault); button_addCar = (Button)findViewById(R.id.button_addCar); button_cancel_addCar = (Button)findViewById(R.id.button_cancel_addCar); } /* (非 Javadoc) * @see android.app.Activity#onPause() */ @Override protected void onPause() { // TODO 自動生成されたメソッド・スタブ super.onPause(); dbman.close(); } /* (非 Javadoc) * @see android.app.Activity#onResume() */ @Override protected void onResume() { // TODO 自動生成されたメソッド・スタブ super.onResume(); /* * ボタンの配置を画面幅の1/2にする処理 * * onCreate()ではなくこちらに書くのは、最終的な画面設定が行われるのがこちらという * Androidのくせによるものである。 */ // 画面幅を取得 int displayWidth = getWindowManager().getDefaultDisplay().getWidth(); // ボタンの幅を、取得した画面幅の1/2にセット button_addCar.setWidth(displayWidth / 2); button_cancel_addCar.setWidth(displayWidth / 2); } /* * 「クルマを追加」ボタンを押したときの処理 * GUIに紐付けるときは、publicメソッドにしなきゃいけないようだ */ public void onClickAddCar(View v) { String carName; boolean defaultFlags; db = dbman.getWritableDatabase(); // TextViewに入力された値を取得 // getText()はCaheSequence型になるので、Stringにキャストする SpannableStringBuilder sp = (SpannableStringBuilder) textview_addCarName.getText(); carName = sp.toString(); Log.w("CarList", "New Car name = " + carName); // チェックボックスの状態を取得 if (checkbox_setDefault.isChecked()) { /* * チェックボックスにチェックがあれば、 * 1.デフォルトフラグがすでにセットされているかを調べ、 * 2.セットされていればいったんすべてのデフォルトフラグを下げる */ if (dbman.isExistDefaultCarFlag(db)) { int iRet = dbman.clearAllDefaultFlags(db); // デフォルトフラグを下げたことをログに出力する Log.w("CAR_MASTER", "Default Car flags cleared, " + String.valueOf(iRet) + "rows updated."); } defaultFlags = FLAG_DEFAULT_ON; } else { defaultFlags = FLAG_DEFAULT_OFF; } // クルマデータをCAR_MASTERに追加 long lRet = dbman.addNewCar(db, carName, defaultFlags); Log.i("CAR_MASTER", "Car record inserted, New Car Name = " + carName + " , New row ID = " + String.valueOf(lRet) ); dbman.close(); } /* * 「キャンセル」を押したときの処理 */ public void onClickCancel(View v) { // 入力されている値を消す // 「消す」=「空の値をセット」ということらしい textview_addCarName.setText(""); // チェックされていない状態にする checkbox_setDefault.setChecked(false); } }
コメントをJavadocコメントに準拠。 git-svn-id: 5cc0fdd97a60f6b20e357a0c972366e6570488ae@69 c8498cfa-7e64-e111-b453-021fc611399b
src/net/formula97/andorid/car_kei_bo/AddMyCar.java
コメントをJavadocコメントに準拠。
Java
bsd-3-clause
c538d9b5f82f4024dc005306a2a74672133befa5
0
versionone/VersionOne.Integration.Eclipse,versionone/VersionOne.Integration.Eclipse,versionone/VersionOne.Integration.Eclipse
package com.versionone.common.sdk; import java.math.BigDecimal; import java.text.NumberFormat; import java.util.ArrayList; import com.versionone.Oid; import com.versionone.apiclient.APIException; import com.versionone.apiclient.Asset; import com.versionone.apiclient.Attribute; import com.versionone.apiclient.IAttributeDefinition; import com.versionone.apiclient.V1Exception; import com.versionone.apiclient.IAttributeDefinition.AttributeType; import com.versionone.common.Activator; public class Workitem { public static final String TASK_PREFIX = "Task"; public static final String STORY_PREFIX = "Story"; public static final String DEFECT_PREFIX = "Defect"; public static final String TEST_PREFIX = "Test"; public static final String PROJECT_PREFIX = "Scope"; public static final String ID_PROPERTY = "Number"; public static final String DETAIL_ESTIMATE_PROPERTY = "DetailEstimate"; public static final String NAME_PROPERTY = "Name"; public static final String STATUS_PROPERTY = "Status"; public static final String EFFORT_PROPERTY = "Actuals"; public static final String DONE_PROPERTY = "Actuals.Value.@Sum"; public static final String SCHEDULE_NAME_PROPERTY = "Schedule.Name"; public static final String OWNERS_PROPERTY = "Owners"; public static final String TODO_PROPERTY = "ToDo"; public static final String DESCRIPTION_PROPERTY = "Description"; public static final String CHECK_QUICK_CLOSE_PROPERTY = "CheckQuickClose"; public static final String CHECK_QUICK_SIGNUP_PROPERTY = "CheckQuickSignup"; protected ApiDataLayer dataLayer = ApiDataLayer.getInstance(); protected Asset asset; public Workitem parent; /** * List of child Workitems. */ public final ArrayList<Workitem> children; public Workitem(Asset asset, Workitem parent) { this.parent = parent; this.asset = asset; children = new ArrayList<Workitem>(asset.getChildren().size()); for (Asset childAsset : asset.getChildren()) { if (dataLayer.isAssetSuspended(childAsset)) { continue; } if (getTypePrefix().equals(PROJECT_PREFIX) || dataLayer.showAllTasks || dataLayer.isCurrentUserOwnerAsset(childAsset)) { children.add(new Workitem(childAsset, this)); } } children.trimToSize(); } public String getTypePrefix() { return asset.getAssetType().getToken(); } public String getId() { if (asset == null) {// temporary return "NULL"; } return asset.getOid().getMomentless().getToken(); } public boolean hasChanges() { return asset.hasChanged(); } public boolean isPropertyReadOnly(String propertyName) { String fullName = getTypePrefix() + '.' + propertyName; try { if (dataLayer.isEffortTrackingRelated(propertyName)) { return isEffortTrackingPropertyReadOnly(propertyName); } return false; } catch (Exception e) { ApiDataLayer.warning("Cannot get property: " + fullName, e); return true; } } public boolean isPropertyDefinitionReadOnly(String propertyName) { String fullName = getTypePrefix() + '.' + propertyName; try { Attribute attribute = asset.getAttributes().get(fullName); return attribute.getDefinition().isReadOnly(); } catch (Exception e) { ApiDataLayer.warning("Cannot get property: " + fullName, e); return true; } } private boolean isEffortTrackingPropertyReadOnly(String propertyName) { if (!dataLayer.isEffortTrackingRelated(propertyName)) { throw new IllegalArgumentException("This property is not related to effort tracking."); } EffortTrackingLevel storyLevel = dataLayer.storyTrackingLevel; EffortTrackingLevel defectLevel = dataLayer.defectTrackingLevel; if (getTypePrefix().equals(STORY_PREFIX)) { return storyLevel != EffortTrackingLevel.PRIMARY_WORKITEM && storyLevel != EffortTrackingLevel.BOTH; } else if (getTypePrefix().equals(DEFECT_PREFIX)) { return defectLevel != EffortTrackingLevel.PRIMARY_WORKITEM && defectLevel != EffortTrackingLevel.BOTH; } else if (getTypePrefix().equals(TASK_PREFIX) || getTypePrefix().equals(TEST_PREFIX)) { EffortTrackingLevel parentLevel; if (parent.getTypePrefix().equals(STORY_PREFIX)) { parentLevel = storyLevel; } else if (parent.getTypePrefix().equals(DEFECT_PREFIX)) { parentLevel = defectLevel; } else { throw new IllegalStateException("Unexpected parent asset type."); } return parentLevel != EffortTrackingLevel.SECONDARY_WORKITEM && parentLevel != EffortTrackingLevel.BOTH; } else { throw new IllegalStateException("Unexpected asset type."); } } private PropertyValues getPropertyValues(String propertyName) { return dataLayer.getListPropertyValues(getTypePrefix(), propertyName); } /** * Checks if property value has changed. * * @param propertyName * Name of the property to get, e.g. "Status" * @return true if property has changed; false - otherwise. */ public boolean isPropertyChanged(String propertyName) throws IllegalArgumentException { if (propertyName.equals(EFFORT_PROPERTY)) { return dataLayer.getEffort(asset) != null; } final String fullName = getTypePrefix() + '.' + propertyName; Attribute attribute = asset.getAttributes().get(fullName); if (attribute == null) { throw new IllegalArgumentException("There is no property: " + fullName); } return attribute.hasChanged(); } /** * Resets property value if it was changed. * * @param propertyName * Name of the property to get, e.g. "Status" */ public void resetProperty(String propertyName) throws IllegalArgumentException { if (propertyName.equals(EFFORT_PROPERTY)) { dataLayer.setEffort(asset, null); } final String fullName = getTypePrefix() + '.' + propertyName; Attribute attribute = asset.getAttributes().get(fullName); if (attribute == null) { throw new IllegalArgumentException("There is no property: " + fullName); } attribute.rejectChanges(); } /** * Gets property value. * * @param propertyName * Name of the property to get, e.g. "Status" * @return String, Double, ValueId or PropertyValues. * @throws IllegalArgumentException * If property cannot be got or there is no such one. * @see #NAME_PROPERTY * @see #STATUS_PROPERTY * @see #EFFORT_PROPERTY * @see #DONE_PROPERTY * @see #SCHEDULE_NAME_PROPERTY * @see #OWNERS_PROPERTY * @see #TODO_PROPERTY */ public Object getProperty(String propertyName) throws IllegalArgumentException { if (propertyName.equals(EFFORT_PROPERTY)) { return dataLayer.getEffort(asset); } final String fullName = getTypePrefix() + '.' + propertyName; Attribute attribute = asset.getAttributes().get(fullName); if (attribute == null) { throw new IllegalArgumentException("There is no property: " + fullName); } if (attribute.getDefinition().isMultiValue()) { return getPropertyValues(propertyName).subset(attribute.getValues()); } try { Object val = attribute.getValue(); if (val instanceof Oid) { return getPropertyValues(propertyName).find((Oid) val); } if (val instanceof Double) { return BigDecimal.valueOf((Double) val).setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString(); } return val; } catch (APIException e) { throw new IllegalArgumentException("Cannot get property: " + propertyName, e); } } public String getPropertyAsString(String propertyName) throws IllegalArgumentException { Object value = getProperty(propertyName); if (value == null) { return ""; } else if (value instanceof Double) { // return numberFormat.format(value); return BigDecimal.valueOf((Double) value).setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString(); } return value.toString(); } /** * Sets property value. * * @param propertyName * Short name of the property to set, e.g. "Name". * @param newValue * String, Double, null, ValueId, PropertyValues accepted. */ public void setProperty(String propertyName, Object newValue) { final boolean isEffort = propertyName.equals(EFFORT_PROPERTY); try { if ("".equals(newValue)) { newValue = null; } if ((isEffort || isNumeric(propertyName))) { setNumericProperty(propertyName, newValue); } else if (isMultiValue(propertyName)) { setMultiValueProperty(propertyName, (PropertyValues) newValue); } else {// List & String types if (newValue instanceof ValueId) { newValue = ((ValueId) newValue).oid; } setPropertyInternal(propertyName, newValue); } } catch (Exception ex) { ApiDataLayer.warning("Cannot set property " + propertyName + " of " + this, ex); } } private boolean isMultiValue(String propertyName) { final IAttributeDefinition attrDef = asset.getAssetType().getAttributeDefinition(propertyName); return attrDef.isMultiValue(); } private boolean isNumeric(String propertyName) { final IAttributeDefinition attrDef = asset.getAssetType().getAttributeDefinition(propertyName); return attrDef.getAttributeType() == AttributeType.Numeric; } private void setNumericProperty(String propertyName, Object newValue) throws APIException { Double doubleValue = null; if (newValue != null) { // newValue = numberFormat.parse((String) newValue); doubleValue = Double.parseDouble(BigDecimal.valueOf(Double.parseDouble((String) newValue)).setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()); } if (propertyName.equals(EFFORT_PROPERTY)) { dataLayer.setEffort(asset, doubleValue); } else { if (doubleValue < 0) { throw new IllegalArgumentException("The field cannot be negative"); } setPropertyInternal(propertyName, doubleValue); } } private void setPropertyInternal(String propertyName, Object newValue) throws APIException { final Attribute attribute = asset.getAttributes().get(getTypePrefix() + '.' + propertyName); final Object oldValue = attribute.getValue(); if ((oldValue == null && newValue != null) || !oldValue.equals(newValue)) { asset.setAttributeValue(asset.getAssetType().getAttributeDefinition(propertyName), newValue); } } private void setMultiValueProperty(String propertyName, PropertyValues newValues) throws APIException { final Attribute attribute = asset.getAttributes().get(getTypePrefix() + '.' + propertyName); final Object[] oldValues = attribute.getValues(); final IAttributeDefinition attrDef = asset.getAssetType().getAttributeDefinition(propertyName); for (Object oldOid : oldValues) { if (!newValues.containsOid((Oid) oldOid)) { asset.removeAttributeValue(attrDef, oldOid); } } for (ValueId newValue : newValues) { if (!checkContains(oldValues, newValue.oid)) { asset.addAttributeValue(attrDef, newValue.oid); } } } private boolean checkContains(Object[] array, Object value) { for (Object item : array) { if (item.equals(value)) return true; } return false; } public boolean propertyChanged(String propertyName) { IAttributeDefinition attrDef = asset.getAssetType().getAttributeDefinition(propertyName); return asset.getAttribute(attrDef).hasChanged(); } public void commitChanges() throws DataLayerException { try { dataLayer.commitAsset(asset); } catch (V1Exception e) { throw ApiDataLayer.warning("Failed to commit changes of workitem: " + this, e); } } public boolean isMine() { PropertyValues owners = (PropertyValues) getProperty(OWNERS_PROPERTY); return owners.containsOid(dataLayer.memberOid); } public boolean canQuickClose() { try { return (Boolean) getProperty("CheckQuickClose"); } catch (IllegalArgumentException e) { ApiDataLayer.warning("QuickClose not supported.", e); return false; } catch (NullPointerException e) { ApiDataLayer.warning("QuickClose not supported.", e); return false; } } /** * Performs 'QuickClose' operation. * * @throws DataLayerException */ public void quickClose() throws DataLayerException { commitChanges(); try { dataLayer.executeOperation(asset, asset.getAssetType().getOperation(ApiDataLayer.OP_QUICK_CLOSE)); dataLayer.addIgnoreRecursively(this); } catch (V1Exception e) { throw ApiDataLayer.warning("Failed to QuickClose workitem: " + this, e); } } public boolean canSignup() { try { return (Boolean) getProperty("CheckQuickSignup"); } catch (IllegalArgumentException e) { ApiDataLayer.warning("QuickSignup not supported.", e); return false; } catch (NullPointerException e) { ApiDataLayer.warning("QuickClose not supported.", e); return false; } } /** * Performs 'QuickSignup' operation. * * @throws DataLayerException */ public void signup() throws DataLayerException { try { dataLayer.executeOperation(asset, asset.getAssetType().getOperation(ApiDataLayer.OP_SIGNUP)); dataLayer.refreshAsset(this); } catch (V1Exception e) { throw ApiDataLayer.warning("Failed to QuickSignup workitem: " + this, e); } } /** * Perform 'Inactivate' operation. * * @throws DataLayerException */ public void close() throws DataLayerException { try { dataLayer.executeOperation(asset, asset.getAssetType().getOperation(ApiDataLayer.OP_CLOSE)); dataLayer.addIgnoreRecursively(this); } catch (V1Exception e) { throw ApiDataLayer.warning("Failed to Close workitem: " + this, e); } } public void revertChanges() { dataLayer.revertAsset(asset); } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (!(obj instanceof Workitem)) { return false; } Workitem other = (Workitem) obj; if (!other.asset.getOid().equals(asset.getOid())) { return false; } return true; } @Override public int hashCode() { return asset.getOid().hashCode(); } @Override public String toString() { return getId() + (asset.hasChanged() ? " (Changed)" : ""); } }
com.versionone.common/src/com/versionone/common/sdk/Workitem.java
package com.versionone.common.sdk; import java.math.BigDecimal; import java.text.NumberFormat; import java.util.ArrayList; import com.versionone.Oid; import com.versionone.apiclient.APIException; import com.versionone.apiclient.Asset; import com.versionone.apiclient.Attribute; import com.versionone.apiclient.IAttributeDefinition; import com.versionone.apiclient.V1Exception; import com.versionone.apiclient.IAttributeDefinition.AttributeType; import com.versionone.common.Activator; public class Workitem { public static final String TASK_PREFIX = "Task"; public static final String STORY_PREFIX = "Story"; public static final String DEFECT_PREFIX = "Defect"; public static final String TEST_PREFIX = "Test"; public static final String PROJECT_PREFIX = "Scope"; public static final String ID_PROPERTY = "Number"; public static final String DETAIL_ESTIMATE_PROPERTY = "DetailEstimate"; public static final String NAME_PROPERTY = "Name"; public static final String STATUS_PROPERTY = "Status"; public static final String EFFORT_PROPERTY = "Actuals"; public static final String DONE_PROPERTY = "Actuals.Value.@Sum"; public static final String SCHEDULE_NAME_PROPERTY = "Schedule.Name"; public static final String OWNERS_PROPERTY = "Owners"; public static final String TODO_PROPERTY = "ToDo"; public static final String DESCRIPTION_PROPERTY = "Description"; public static final String CHECK_QUICK_CLOSE_PROPERTY = "CheckQuickClose"; public static final String CHECK_QUICK_SIGNUP_PROPERTY = "CheckQuickSignup"; protected ApiDataLayer dataLayer = ApiDataLayer.getInstance(); protected Asset asset; public Workitem parent; /** * List of child Workitems. */ public final ArrayList<Workitem> children; public Workitem(Asset asset, Workitem parent) { this.parent = parent; this.asset = asset; children = new ArrayList<Workitem>(asset.getChildren().size()); for (Asset childAsset : asset.getChildren()) { if (dataLayer.isAssetSuspended(childAsset)) { continue; } if (getTypePrefix().equals(PROJECT_PREFIX) || dataLayer.showAllTasks || dataLayer.isCurrentUserOwnerAsset(childAsset)) { children.add(new Workitem(childAsset, this)); } } children.trimToSize(); } public String getTypePrefix() { return asset.getAssetType().getToken(); } public String getId() { if (asset == null) {// temporary return "NULL"; } return asset.getOid().getMomentless().getToken(); } public boolean hasChanges() { return asset.hasChanged(); } public boolean isPropertyReadOnly(String propertyName) { String fullName = getTypePrefix() + '.' + propertyName; try { if (dataLayer.isEffortTrackingRelated(propertyName)) { return isEffortTrackingPropertyReadOnly(propertyName); } return false; } catch (Exception e) { ApiDataLayer.warning("Cannot get property: " + fullName, e); return true; } } public boolean isPropertyDefinitionReadOnly(String propertyName) { String fullName = getTypePrefix() + '.' + propertyName; try { Attribute attribute = asset.getAttributes().get(fullName); return attribute.getDefinition().isReadOnly(); } catch (Exception e) { ApiDataLayer.warning("Cannot get property: " + fullName, e); return true; } } private boolean isEffortTrackingPropertyReadOnly(String propertyName) { if (!dataLayer.isEffortTrackingRelated(propertyName)) { throw new IllegalArgumentException("This property is not related to effort tracking."); } EffortTrackingLevel storyLevel = dataLayer.storyTrackingLevel; EffortTrackingLevel defectLevel = dataLayer.defectTrackingLevel; if (getTypePrefix().equals(STORY_PREFIX)) { return storyLevel != EffortTrackingLevel.PRIMARY_WORKITEM && storyLevel != EffortTrackingLevel.BOTH; } else if (getTypePrefix().equals(DEFECT_PREFIX)) { return defectLevel != EffortTrackingLevel.PRIMARY_WORKITEM && defectLevel != EffortTrackingLevel.BOTH; } else if (getTypePrefix().equals(TASK_PREFIX) || getTypePrefix().equals(TEST_PREFIX)) { EffortTrackingLevel parentLevel; if (parent.getTypePrefix().equals(STORY_PREFIX)) { parentLevel = storyLevel; } else if (parent.getTypePrefix().equals(DEFECT_PREFIX)) { parentLevel = defectLevel; } else { throw new IllegalStateException("Unexpected parent asset type."); } return parentLevel != EffortTrackingLevel.SECONDARY_WORKITEM && parentLevel != EffortTrackingLevel.BOTH; } else { throw new IllegalStateException("Unexpected asset type."); } } private PropertyValues getPropertyValues(String propertyName) { return dataLayer.getListPropertyValues(getTypePrefix(), propertyName); } /** * Checks if property value has changed. * * @param propertyName * Name of the property to get, e.g. "Status" * @return true if property has changed; false - otherwise. */ public boolean isPropertyChanged(String propertyName) throws IllegalArgumentException { if (propertyName.equals(EFFORT_PROPERTY)) { return dataLayer.getEffort(asset) != null; } final String fullName = getTypePrefix() + '.' + propertyName; Attribute attribute = asset.getAttributes().get(fullName); if (attribute == null) { throw new IllegalArgumentException("There is no property: " + fullName); } return attribute.hasChanged(); } /** * Resets property value if it was changed. * * @param propertyName * Name of the property to get, e.g. "Status" */ public void resetProperty(String propertyName) throws IllegalArgumentException { if (propertyName.equals(EFFORT_PROPERTY)) { dataLayer.setEffort(asset, null); } final String fullName = getTypePrefix() + '.' + propertyName; Attribute attribute = asset.getAttributes().get(fullName); if (attribute == null) { throw new IllegalArgumentException("There is no property: " + fullName); } attribute.rejectChanges(); } /** * Gets property value. * * @param propertyName * Name of the property to get, e.g. "Status" * @return String, Double, ValueId or PropertyValues. * @throws IllegalArgumentException * If property cannot be got or there is no such one. * @see #NAME_PROPERTY * @see #STATUS_PROPERTY * @see #EFFORT_PROPERTY * @see #DONE_PROPERTY * @see #SCHEDULE_NAME_PROPERTY * @see #OWNERS_PROPERTY * @see #TODO_PROPERTY */ public Object getProperty(String propertyName) throws IllegalArgumentException { if (propertyName.equals(EFFORT_PROPERTY)) { return dataLayer.getEffort(asset); } final String fullName = getTypePrefix() + '.' + propertyName; Attribute attribute = asset.getAttributes().get(fullName); if (attribute == null) { throw new IllegalArgumentException("There is no property: " + fullName); } if (attribute.getDefinition().isMultiValue()) { return getPropertyValues(propertyName).subset(attribute.getValues()); } try { Object val = attribute.getValue(); if (val instanceof Oid) { return getPropertyValues(propertyName).find((Oid) val); } if (val instanceof Double) { return BigDecimal.valueOf((Double) val).setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString(); } return val; } catch (APIException e) { throw new IllegalArgumentException("Cannot get property: " + propertyName, e); } } public String getPropertyAsString(String propertyName) throws IllegalArgumentException { Object value = getProperty(propertyName); if (value == null) { return ""; } else if (value instanceof Double) { // return numberFormat.format(value); return BigDecimal.valueOf((Double) value).setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString(); } return value.toString(); } /** * Sets property value. * * @param propertyName * Short name of the property to set, e.g. "Name". * @param newValue * String, Double, null, ValueId, PropertyValues accepted. */ public void setProperty(String propertyName, Object newValue) { if ((propertyName.equals(Workitem.TODO_PROPERTY) || propertyName.equals(Workitem.DETAIL_ESTIMATE_PROPERTY)) && Double.parseDouble(newValue.toString()) < 0) { throw new IllegalArgumentException("The field cannot be negative"); } try { if (propertyName.equals(EFFORT_PROPERTY)) { final Double effort; if ("".equals(newValue)) effort = null; else //effort = numberFormat.parse((String) newValue).doubleValue(); effort = Double.parseDouble(BigDecimal.valueOf(Double.parseDouble((String)newValue)).setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()); dataLayer.setEffort(asset, effort); return; } IAttributeDefinition attrDef = asset.getAssetType().getAttributeDefinition(propertyName); if (newValue == null || newValue.equals("")) { asset.setAttributeValue(attrDef, null); return; } Attribute attribute = asset.getAttributes().get(getTypePrefix() + '.' + propertyName); if (attrDef.isMultiValue()) { updateValues(propertyName, attribute.getValues(), (PropertyValues) newValue); return; } if (newValue instanceof ValueId) { newValue = ((ValueId) newValue).oid; } else if (attrDef.getAttributeType() == AttributeType.Numeric) { //newValue = numberFormat.parse((String) newValue); newValue = Double.parseDouble(BigDecimal.valueOf(Double.parseDouble((String)newValue)).setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()); } if (!newValue.equals(attribute.getValue())) { asset.setAttributeValue(attrDef, newValue); } } catch (Exception ex) { ApiDataLayer.warning("Cannot set property " + propertyName + " of " + this, ex); } } private void updateValues(String propertyName, Object[] oldValues, PropertyValues newValues) throws APIException { IAttributeDefinition attrDef = asset.getAssetType().getAttributeDefinition(propertyName); for (Object oldOid : oldValues) { if (!newValues.containsOid((Oid) oldOid)) { asset.removeAttributeValue(attrDef, oldOid); } } for (ValueId newValue : newValues) { if (!checkContains(oldValues, newValue.oid)) { asset.addAttributeValue(attrDef, newValue.oid); } } } private boolean checkContains(Object[] array, Object value) { for (Object item : array) { if (item.equals(value)) return true; } return false; } public boolean propertyChanged(String propertyName) { IAttributeDefinition attrDef = asset.getAssetType().getAttributeDefinition(propertyName); return asset.getAttribute(attrDef).hasChanged(); } public void commitChanges() throws DataLayerException { try { dataLayer.commitAsset(asset); } catch (V1Exception e) { throw ApiDataLayer.warning("Failed to commit changes of workitem: " + this, e); } } public boolean isMine() { PropertyValues owners = (PropertyValues) getProperty(OWNERS_PROPERTY); return owners.containsOid(dataLayer.memberOid); } public boolean canQuickClose() { try { return (Boolean) getProperty("CheckQuickClose"); } catch (IllegalArgumentException e) { ApiDataLayer.warning("QuickClose not supported.", e); return false; } catch (NullPointerException e) { ApiDataLayer.warning("QuickClose not supported.", e); return false; } } /** * Performs 'QuickClose' operation. * * @throws DataLayerException */ public void quickClose() throws DataLayerException { commitChanges(); try { dataLayer.executeOperation(asset, asset.getAssetType().getOperation(ApiDataLayer.OP_QUICK_CLOSE)); dataLayer.addIgnoreRecursively(this); } catch (V1Exception e) { throw ApiDataLayer.warning("Failed to QuickClose workitem: " + this, e); } } public boolean canSignup() { try { return (Boolean) getProperty("CheckQuickSignup"); } catch (IllegalArgumentException e) { ApiDataLayer.warning("QuickSignup not supported.", e); return false; } catch (NullPointerException e) { ApiDataLayer.warning("QuickClose not supported.", e); return false; } } /** * Performs 'QuickSignup' operation. * * @throws DataLayerException */ public void signup() throws DataLayerException { try { dataLayer.executeOperation(asset, asset.getAssetType().getOperation(ApiDataLayer.OP_SIGNUP)); dataLayer.refreshAsset(this); } catch (V1Exception e) { throw ApiDataLayer.warning("Failed to QuickSignup workitem: " + this, e); } } /** * Perform 'Inactivate' operation. * * @throws DataLayerException */ public void close() throws DataLayerException { try { dataLayer.executeOperation(asset, asset.getAssetType().getOperation(ApiDataLayer.OP_CLOSE)); dataLayer.addIgnoreRecursively(this); } catch (V1Exception e) { throw ApiDataLayer.warning("Failed to Close workitem: " + this, e); } } public void revertChanges() { dataLayer.revertAsset(asset); } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (!(obj instanceof Workitem)) { return false; } Workitem other = (Workitem) obj; if (!other.asset.getOid().equals(asset.getOid())) { return false; } return true; } @Override public int hashCode() { return asset.getOid().hashCode(); } @Override public String toString() { return getId() + (asset.hasChanged() ? " (Changed)" : ""); } }
Workitem.setProperty refactored git-svn-id: 592068d3f7448375e6a51a56d75d72ced1077744@29202 542498e7-56f8-f544-a0f2-a85913ac812a
com.versionone.common/src/com/versionone/common/sdk/Workitem.java
Workitem.setProperty refactored
Java
bsd-3-clause
6dd59d9fc2308c80f64fa850e2b037fb760cc8fb
0
oci-pronghorn/GreenLightning,oci-pronghorn/GreenLightning,oci-pronghorn/GreenLightning
package ${package}; import static org.junit.Assert.assertTrue; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import com.ociweb.gl.api.GreenRuntime; public class WebTest { static GreenRuntime runtime; static int port = 8050; static int telemetryPort = 8097; static String host = "127.0.0.1"; static int timeoutMS = 60_000; static boolean telemetry = false; static int cyclesPerTrack = 100; static boolean useTLS = true; static int parallelTracks = 2; @BeforeClass public static void startServer() { runtime = GreenRuntime.run(new ${mainClass}()); } @AfterClass public static void stopServer() { runtime.shutdownRuntime(); runtime = null; } // @Test // public void getExampleTest() { // // StringBuilder results = LoadTester.runClient( // ()-> null, // (r)->{ // return (HTTPContentTypeDefaults.PLAIN==r.contentType()) // && "beginning of text file\n".equals(r.structured().readPayload().readUTFFully()); // }, // "/testPageB", // useTLS, telemetry, // parallelTracks, cyclesPerTrack, // host, port, timeoutMS); // // assertTrue(results.toString(), results.indexOf("Responses invalid: 0 out of "+(cyclesPerTrack*parallelTracks))>=0); // // } // @Test // public void postExampleTest() { // // Writable testData = new Writable() { // @Override // public void write(ChannelWriter writer) { // writer.append("{\"person\":{\"name\":\"bob\",\"age\":42}}"); // } // }; // // StringBuilder results = LoadTester.runClient( // ()->testData, // (r)->{ // String readUTFFully = r.structured().readPayload().readUTFFully(); // boolean isMatch = "{\"name\":\"bob\",\"isLegal\":true}".equals(readUTFFully); // if (!isMatch) { // System.out.println("bad response: "+readUTFFully); // } // return isMatch && (HTTPContentTypeDefaults.JSON == r.contentType()); // }, // "/testJSON", // useTLS, telemetry, // parallelTracks, cyclesPerTrack, // host, port, timeoutMS); // // assertTrue(results.toString(), results.indexOf("Responses invalid: 0 out of "+(cyclesPerTrack*parallelTracks))>=0); // // } // @Test // public void jsonExampleTest() { // // Person person = new Person("bob",42); // JSONRenderer<Person> renderer = new JSONRenderer<Person>() // .beginObject() // .beginObject("person") // .string("name", (o,t)->t.append(o.name)) // .integer("age", o->o.age) // .endObject() // .endObject(); // // StringBuilder results = LoadTester.runClient( // renderer, // ()->person, // (r)->{ // return "{\"name\":\"bob\",\"isLegal\":true}".equals(r.structured().readPayload().readUTFFully()) // && (HTTPContentTypeDefaults.JSON == r.contentType()); // }, // "/testJSON", // useTLS, telemetry, // parallelTracks, cyclesPerTrack, // host, port, timeoutMS); // // assertTrue(results.toString(), results.indexOf("Responses invalid: 0 out of "+(cyclesPerTrack*parallelTracks))>=0); // // } }
src/main/resources/archetype-resources/src/test/java/WebTest.java
package ${package}; import static org.junit.Assert.assertTrue; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import com.ociweb.gl.api.GreenRuntime; import com.ociweb.gl.api.Writable; import com.ociweb.gl.test.LoadTester; import com.ociweb.json.encode.JSONRenderer; import com.ociweb.oe.greenlightning.api.HTTPServer; import com.ociweb.oe.greenlightning.api.ExampleAppTest.Person; import com.ociweb.pronghorn.network.config.HTTPContentTypeDefaults; import com.ociweb.pronghorn.pipe.ChannelWriter; public class WebTest { GreenRuntime runtime; static int port = 8050; static int telemetryPort = 8097; static String host = "127.0.0.1"; static int timeoutMS = 60_000; static bboolean telemetry = false; static int cyclesPerTrack = 100; static boolean useTLS = true; static int parallelTracks = 2; @BeforeClass public static void startServer() { runtime = GreenRuntime.run(new ${mainClass}()); } @AfterClass public static void stopServer() { runtime.shutdownRuntime(); runtime = null; } // @Test // public void getExampleTest() { // // StringBuilder results = LoadTester.runClient( // ()-> null, // (r)->{ // return (HTTPContentTypeDefaults.PLAIN==r.contentType()) // && "beginning of text file\n".equals(r.structured().readPayload().readUTFFully()); // }, // "/testPageB", // useTLS, telemetry, // parallelTracks, cyclesPerTrack, // host, port, timeoutMS); // // assertTrue(results.toString(), results.indexOf("Responses invalid: 0 out of "+(cyclesPerTrack*parallelTracks))>=0); // // } // @Test // public void postExampleTest() { // // Writable testData = new Writable() { // @Override // public void write(ChannelWriter writer) { // writer.append("{\"person\":{\"name\":\"bob\",\"age\":42}}"); // } // }; // // StringBuilder results = LoadTester.runClient( // ()->testData, // (r)->{ // String readUTFFully = r.structured().readPayload().readUTFFully(); // boolean isMatch = "{\"name\":\"bob\",\"isLegal\":true}".equals(readUTFFully); // if (!isMatch) { // System.out.println("bad response: "+readUTFFully); // } // return isMatch && (HTTPContentTypeDefaults.JSON == r.contentType()); // }, // "/testJSON", // useTLS, telemetry, // parallelTracks, cyclesPerTrack, // host, port, timeoutMS); // // assertTrue(results.toString(), results.indexOf("Responses invalid: 0 out of "+(cyclesPerTrack*parallelTracks))>=0); // // } // @Test // public void jsonExampleTest() { // // Person person = new Person("bob",42); // JSONRenderer<Person> renderer = new JSONRenderer<Person>() // .beginObject() // .beginObject("person") // .string("name", (o,t)->t.append(o.name)) // .integer("age", o->o.age) // .endObject() // .endObject(); // // StringBuilder results = LoadTester.runClient( // renderer, // ()->person, // (r)->{ // return "{\"name\":\"bob\",\"isLegal\":true}".equals(r.structured().readPayload().readUTFFully()) // && (HTTPContentTypeDefaults.JSON == r.contentType()); // }, // "/testJSON", // useTLS, telemetry, // parallelTracks, cyclesPerTrack, // host, port, timeoutMS); // // assertTrue(results.toString(), results.indexOf("Responses invalid: 0 out of "+(cyclesPerTrack*parallelTracks))>=0); // // } }
cleanup
src/main/resources/archetype-resources/src/test/java/WebTest.java
cleanup
Java
bsd-3-clause
628fa7e71d0a7ca3fc9da05a76b55d20689b4c10
0
compgen-io/ngsutilsj,compgen-io/ngsutilsj
package io.compgen.ngsutils.cli.vcf; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.apache.commons.math3.distribution.PoissonDistribution; import io.compgen.cmdline.annotation.Command; import io.compgen.cmdline.annotation.Exec; import io.compgen.cmdline.annotation.Option; import io.compgen.cmdline.annotation.UnnamedArg; import io.compgen.cmdline.exceptions.CommandArgumentException; import io.compgen.cmdline.impl.AbstractOutputCommand; import io.compgen.common.IterUtils; import io.compgen.common.Pair; import io.compgen.common.TabWriter; import io.compgen.common.progress.ProgressUtils; import io.compgen.ngsutils.NGSUtils; import io.compgen.ngsutils.bed.BedReader; import io.compgen.ngsutils.bed.BedRecord; import io.compgen.ngsutils.vcf.VCFReader; import io.compgen.ngsutils.vcf.VCFRecord; @Command(name="vcf-bedcount", desc="For a given BED file, count the number of variants present in the BED region", doc="Note: this expects both the BED and VCF files to be sorted.", category="vcf") public class VCFBedCount extends AbstractOutputCommand { private String vcfFilename=null; private String bedFilename=null; private String sampleName=null; private double tmb=-1; private boolean onlyPassing=false; private boolean altOnly=false; @Option(desc = "Given a genome-wide TMB value (variants per megabase), calculate a p-value for the given count (Poisson test, P(X >= count, lambda=tmb)); Note: If you use this, your bin sizes should be larger than 1Mb", name = "tmb") public void setTMB(double tmb) { this.tmb = tmb; } @Option(desc = "Only count alt variants (requires GT FORMAT field, exports all non GT:0/0)", name = "alt") public void setAltOnly(boolean altOnly) { this.altOnly = altOnly; } @Option(desc="Only count passing variants", name="passing") public void setOnlyOutputPass(boolean onlyPassing) { this.onlyPassing = onlyPassing; } @Option(desc="Sample to use for vcf-counts (if VCF file has more than one sample, default: first sample)", name="sample") public void setSampleName(String sampleName) { this.sampleName = sampleName; } @UnnamedArg(name = "input.bed input.vcf", required=true) public void setFilename(String[] filenames) throws CommandArgumentException { if (filenames.length!=2) { throw new CommandArgumentException("You must include a BED file and a VCF file."); } bedFilename = filenames[0]; vcfFilename = filenames[1]; } @Exec public void exec() throws Exception { VCFReader reader; if (vcfFilename.equals("-")) { reader = new VCFReader(System.in); } else { reader = new VCFReader(vcfFilename); } int sampleIdx = 0; if (sampleName != null) { sampleIdx = reader.getHeader().getSamplePosByName(sampleName); } Map<String, Map<Pair<Integer, Integer>, Integer>> counts = new HashMap<String, Map<Pair<Integer, Integer>, Integer>>(); Iterator<BedRecord> bedIt = BedReader.readFile(bedFilename); for (BedRecord bedRecord: IterUtils.wrap(bedIt)) { if (!counts.containsKey(bedRecord.getCoord().ref)) { counts.put(bedRecord.getCoord().ref, new HashMap<Pair<Integer, Integer>, Integer>()); } counts.get(bedRecord.getCoord().ref).put(new Pair<Integer, Integer>(bedRecord.getCoord().start, bedRecord.getCoord().end), 0); } for (VCFRecord record: IterUtils.wrap(ProgressUtils.getIterator(vcfFilename.equals("-") ? "variants <stdin>": vcfFilename, reader.iterator(), null))) { if (onlyPassing && record.isFiltered()) { continue; } String ref = record.getChrom(); int pos = record.getPos()-1; // zero-based if (altOnly) { if (record.getSampleAttributes() == null || record.getSampleAttributes().get(sampleIdx) == null || !record.getSampleAttributes().get(sampleIdx).contains("GT")) { throw new CommandArgumentException("Missing GT field"); } String val = record.getSampleAttributes().get(sampleIdx).get("GT").asString(null); // if 0/0 or 1/1, etc -- skip if (val.indexOf('/')>-1) { String[] v2 = val.split("/"); if (v2.length == 2 && v2[0].equals("0") && v2[1].equals("0")) { continue; } } else if (val.indexOf('|')>-1) { String[] v2 = val.split("\\|"); if (v2.length == 2 && v2[0].equals("0") && v2[1].equals("0")) { continue; } } } if (counts.containsKey(ref)) { for (Pair<Integer, Integer> coord: counts.get(ref).keySet()) { if (coord.one <= pos && coord.two > pos) { counts.get(ref).put(coord, counts.get(ref).get(coord)+1); } } } } reader.close(); TabWriter writer = new TabWriter(); writer.write_line("## program: " + NGSUtils.getVersion()); writer.write_line("## cmd: " + NGSUtils.getArgs()); writer.write_line("## vcf-input: " + vcfFilename); writer.write_line("## bed-input: " + bedFilename); if (tmb > 0) { writer.write_line("## TMB: "+tmb); } writer.write("chrom"); writer.write("start"); writer.write("end"); writer.write("varcount"); writer.write("variants_per_mb"); if (tmb > 0) { writer.write("poisson_pvalue"); } writer.eol(); Map<Integer, PoissonDistribution> ppois = new HashMap<Integer, PoissonDistribution>(); Iterator<BedRecord> bedIt2 = BedReader.readFile(bedFilename); for (BedRecord bedRecord: IterUtils.wrap(bedIt2)) { String ref = bedRecord.getCoord().ref; int start = bedRecord.getCoord().start; int end = bedRecord.getCoord().end; int count = -1; for (Pair<Integer, Integer> pair: counts.get(ref).keySet()) { if (pair.one == start && pair.two == end) { count = counts.get(ref).get(pair); break; } } writer.write(ref); writer.write(start); writer.write(end); writer.write(count); int length = end - start; writer.write(count / (length / 1000000.0)); if (tmb > 0) { if (!ppois.containsKey(length)) { double lambda = tmb * length / 1000000; ppois.put(length, new PoissonDistribution(lambda)); } writer.write(1-ppois.get(length).cumulativeProbability(count-1)); } writer.eol(); } writer.close(); } }
src/java/io/compgen/ngsutils/cli/vcf/VCFBedCount.java
package io.compgen.ngsutils.cli.vcf; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.apache.commons.math3.distribution.PoissonDistribution; import io.compgen.cmdline.annotation.Command; import io.compgen.cmdline.annotation.Exec; import io.compgen.cmdline.annotation.Option; import io.compgen.cmdline.annotation.UnnamedArg; import io.compgen.cmdline.exceptions.CommandArgumentException; import io.compgen.cmdline.impl.AbstractOutputCommand; import io.compgen.common.IterUtils; import io.compgen.common.Pair; import io.compgen.common.TabWriter; import io.compgen.common.progress.ProgressUtils; import io.compgen.ngsutils.NGSUtils; import io.compgen.ngsutils.bed.BedReader; import io.compgen.ngsutils.bed.BedRecord; import io.compgen.ngsutils.vcf.VCFReader; import io.compgen.ngsutils.vcf.VCFRecord; @Command(name="vcf-bedcount", desc="For a given BED file, count the number of variants present in the BED region", doc="Note: this expects both the BED and VCF files to be sorted.", category="vcf") public class VCFBedCount extends AbstractOutputCommand { private String vcfFilename=null; private String bedFilename=null; private String sampleName=null; private double tmb=-1; private boolean onlyPassing=false; private boolean altOnly=false; @Option(desc = "Given a genome-wide TMB value (variants per megabase), calculate a p-value for the given count (Poisson test, P(X >= count, lambda=tmb)); Note: If you use this, your bin sizes should be larger than 1Mb", name = "tmb") public void setTMB(double tmb) { this.tmb = tmb; } @Option(desc = "Only count alt variants (requires GT FORMAT field, exports all non GT:0/0)", name = "alt") public void setAltOnly(boolean altOnly) { this.altOnly = altOnly; } @Option(desc="Only count passing variants", name="passing") public void setOnlyOutputPass(boolean onlyPassing) { this.onlyPassing = onlyPassing; } @Option(desc="Sample to use for vcf-counts (if VCF file has more than one sample, default: first sample)", name="sample") public void setSampleName(String sampleName) { this.sampleName = sampleName; } @UnnamedArg(name = "input.bed input.vcf", required=true) public void setFilename(String[] filenames) throws CommandArgumentException { if (filenames.length!=2) { throw new CommandArgumentException("You must include a BED file and a VCF file."); } bedFilename = filenames[0]; vcfFilename = filenames[1]; } @Exec public void exec() throws Exception { VCFReader reader; if (vcfFilename.equals("-")) { reader = new VCFReader(System.in); } else { reader = new VCFReader(vcfFilename); } int sampleIdx = 0; if (sampleName != null) { sampleIdx = reader.getHeader().getSamplePosByName(sampleName); } Map<String, Map<Pair<Integer, Integer>, Integer>> counts = new HashMap<String, Map<Pair<Integer, Integer>, Integer>>(); Iterator<BedRecord> bedIt = BedReader.readFile(bedFilename); for (BedRecord bedRecord: IterUtils.wrap(bedIt)) { if (!counts.containsKey(bedRecord.getCoord().ref)) { counts.put(bedRecord.getCoord().ref, new HashMap<Pair<Integer, Integer>, Integer>()); } counts.get(bedRecord.getCoord().ref).put(new Pair<Integer, Integer>(bedRecord.getCoord().start, bedRecord.getCoord().end), 0); } for (VCFRecord record: IterUtils.wrap(ProgressUtils.getIterator(vcfFilename.equals("-") ? "variants <stdin>": vcfFilename, reader.iterator(), null))) { if (onlyPassing && record.isFiltered()) { continue; } String ref = record.getChrom(); int pos = record.getPos()-1; // zero-based if (altOnly) { if (record.getSampleAttributes() == null || record.getSampleAttributes().get(sampleIdx) == null || !record.getSampleAttributes().get(sampleIdx).contains("GT")) { throw new CommandArgumentException("Missing GT field"); } String val = record.getSampleAttributes().get(sampleIdx).get("GT").asString(null); // if 0/0 or 1/1, etc -- skip if (val.indexOf('/')>-1) { String[] v2 = val.split("/"); if (v2.length == 2 && v2[0].equals("0") && v2[1].equals("0")) { continue; } } else if (val.indexOf('|')>-1) { String[] v2 = val.split("\\|"); if (v2.length == 2 && v2[0].equals("0") && v2[1].equals("0")) { continue; } } } if (counts.containsKey(ref)) { for (Pair<Integer, Integer> coord: counts.get(ref).keySet()) { if (coord.one <= pos && coord.two > pos) { counts.get(ref).put(coord, counts.get(ref).get(coord)+1); } } } } reader.close(); TabWriter writer = new TabWriter(); writer.write_line("## program: " + NGSUtils.getVersion()); writer.write_line("## cmd: " + NGSUtils.getArgs()); writer.write_line("## vcf-input: " + vcfFilename); writer.write_line("## bed-input: " + bedFilename); writer.write("chrom"); writer.write("start"); writer.write("end"); writer.write("varcount"); writer.write("variants_per_mb"); if (tmb > 0) { writer.write("poisson_pvalue"); } writer.eol(); Map<Integer, PoissonDistribution> ppois = new HashMap<Integer, PoissonDistribution>(); Iterator<BedRecord> bedIt2 = BedReader.readFile(bedFilename); for (BedRecord bedRecord: IterUtils.wrap(bedIt2)) { String ref = bedRecord.getCoord().ref; int start = bedRecord.getCoord().start; int end = bedRecord.getCoord().end; int count = -1; for (Pair<Integer, Integer> pair: counts.get(ref).keySet()) { if (pair.one == start && pair.two == end) { count = counts.get(ref).get(pair); break; } } writer.write(ref); writer.write(start); writer.write(end); writer.write(count); int length = end - start; writer.write(count / (length / 1000000.0)); if (tmb > 0) { if (!ppois.containsKey(length)) { double lambda = tmb * length / 1000000; ppois.put(length, new PoissonDistribution(lambda)); } writer.write(1-ppois.get(length).cumulativeProbability(count-1)); } writer.eol(); } writer.close(); } }
added extra header to vcf-bedcount
src/java/io/compgen/ngsutils/cli/vcf/VCFBedCount.java
added extra header to vcf-bedcount
Java
bsd-3-clause
37aeea1d57f30e9302c8d61f2d7e0b4df33221c0
0
rodel-talampas/dfs-datastores,jf87/dfs-datastores,embedcard/dfs-datastores,abolibibelot/dfs-datastores,spadala/dfs-datastores,nathanmarz/dfs-datastores,amazari/dfs-datastores,criteo-forks/dfs-datastores,ind9/dfs-datastores
package backtype.hadoop.pail; import backtype.hadoop.formats.RecordOutputStream; import backtype.support.Utils; import java.io.IOException; import java.util.HashMap; import java.util.Map; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.io.BytesWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapred.FileOutputFormat; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.mapred.RecordWriter; import org.apache.hadoop.mapred.Reporter; import org.apache.hadoop.util.Progressable; import org.apache.log4j.Logger; import org.apache.hadoop.mapred.FileOutputCommitter; public class PailOutputFormat extends FileOutputFormat<Text, BytesWritable> { public static Logger LOG = Logger.getLogger(PailOutputFormat.class); public static final String SPEC_ARG = "pail_spec_arg"; // we limit the size of outputted files because of s3 file limits public static final long FILE_LIMIT_SIZE_BYTES = 1L * 1024 * 1024 * 1024; // 1GB /** * Change this to just use Pail#writeObject - auatomically fix up BytesWritable */ public static class PailRecordWriter implements RecordWriter<Text, BytesWritable> { private Pail _pail; private String _unique; protected static class OpenAttributeFile { public String attr; public String filename; public RecordOutputStream os; public long numBytesWritten = 0; public OpenAttributeFile(String attr, String filename, RecordOutputStream os) { this.attr = attr; this.filename = filename; this.os = os; } } private Map<String, OpenAttributeFile> _outputters = new HashMap<String, OpenAttributeFile>(); private int writtenRecords = 0; private int numFilesOpened = 0; public PailRecordWriter(JobConf conf, String unique, Progressable p) throws IOException { PailSpec spec = (PailSpec) Utils.getObject(conf, SPEC_ARG); Pail.create(getOutputPath(conf).toString(), spec, false); // this is a hack to get the work output directory since it's not exposed directly. instead it only // provides a path to a particular file. _pail = Pail.create(FileOutputFormat.getTaskOutputPath(conf, unique).getParent().toString(), spec, false); _unique = unique; } public void write(Text k, BytesWritable v) throws IOException { String attr = k.toString(); OpenAttributeFile oaf = _outputters.get(attr); if(oaf!=null && oaf.numBytesWritten >= FILE_LIMIT_SIZE_BYTES) { closeAttributeFile(oaf); oaf = null; _outputters.remove(attr); } if(oaf==null) { String filename; if(!attr.isEmpty()) { filename = attr + "/" + _unique + numFilesOpened; } else { filename = _unique + numFilesOpened; } numFilesOpened++; LOG.info("Opening " + filename + " for attribute " + attr); //need overwrite for situations where regular FileOutputCommitter isn't used (like S3) oaf = new OpenAttributeFile(attr, filename, _pail.openWrite(filename, true)); _outputters.put(attr, oaf); } oaf.os.writeRaw(v.getBytes(), 0, v.getLength()); oaf.numBytesWritten+=v.getLength(); logProgress(); } protected void logProgress() { writtenRecords++; if(writtenRecords%100000 == 0) { for(OpenAttributeFile oaf: _outputters.values()) { LOG.info("Attr:" + oaf.attr + " Filename:" + oaf.filename + " Bytes written:" + oaf.numBytesWritten); } } } protected void closeAttributeFile(OpenAttributeFile oaf) throws IOException { LOG.info("Closing " + oaf.filename + " for attr " + oaf.attr); //print out the size of the file here oaf.os.close(); LOG.info("Closed " + oaf.filename + " for attr " + oaf.attr); } public void close(Reporter rprtr) throws IOException { for(String key: _outputters.keySet()) { closeAttributeFile(_outputters.get(key)); rprtr.progress(); } _outputters.clear(); } } public RecordWriter<Text, BytesWritable> getRecordWriter(FileSystem ignored, JobConf jc, String string, Progressable p) throws IOException { return new PailRecordWriter(jc, string, p); } @Override public void checkOutputSpecs(FileSystem fs, JobConf conf) throws IOException { // because this outputs multiple files, doesn't work with speculative execution on something like EMR with S3 if(!(conf.getOutputCommitter() instanceof FileOutputCommitter)) { if(conf.getMapSpeculativeExecution() && conf.getNumReduceTasks()==0 || conf.getReduceSpeculativeExecution()) { throw new IllegalArgumentException("Cannot use speculative execution with PailOutputFormat unless FileOutputCommitter is enabled"); } } } }
src/jvm/backtype/hadoop/pail/PailOutputFormat.java
package backtype.hadoop.pail; import backtype.hadoop.formats.RecordOutputStream; import backtype.support.Utils; import java.io.IOException; import java.util.HashMap; import java.util.Map; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.io.BytesWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapred.FileOutputFormat; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.mapred.RecordWriter; import org.apache.hadoop.mapred.Reporter; import org.apache.hadoop.util.Progressable; import org.apache.log4j.Logger; public class PailOutputFormat extends FileOutputFormat<Text, BytesWritable> { public static Logger LOG = Logger.getLogger(PailOutputFormat.class); public static final String SPEC_ARG = "pail_spec_arg"; // we limit the size of outputted files because of s3 file limits public static final long FILE_LIMIT_SIZE_BYTES = 1L * 1024 * 1024 * 1024; // 1GB /** * Change this to just use Pail#writeObject - auatomically fix up BytesWritable */ public static class PailRecordWriter implements RecordWriter<Text, BytesWritable> { private Pail _pail; private String _unique; protected static class OpenAttributeFile { public String attr; public String filename; public RecordOutputStream os; public long numBytesWritten = 0; public OpenAttributeFile(String attr, String filename, RecordOutputStream os) { this.attr = attr; this.filename = filename; this.os = os; } } private Map<String, OpenAttributeFile> _outputters = new HashMap<String, OpenAttributeFile>(); private int writtenRecords = 0; private int numFilesOpened = 0; public PailRecordWriter(JobConf conf, String unique, Progressable p) throws IOException { PailSpec spec = (PailSpec) Utils.getObject(conf, SPEC_ARG); Pail.create(getOutputPath(conf).toString(), spec, false); // this is a hack to get the work output directory since it's not exposed directly. instead it only // provides a path to a particular file. _pail = Pail.create(FileOutputFormat.getTaskOutputPath(conf, unique).getParent().toString(), spec, false); _unique = unique; } public void write(Text k, BytesWritable v) throws IOException { String attr = k.toString(); OpenAttributeFile oaf = _outputters.get(attr); if(oaf!=null && oaf.numBytesWritten >= FILE_LIMIT_SIZE_BYTES) { closeAttributeFile(oaf); oaf = null; _outputters.remove(attr); } if(oaf==null) { String filename; if(!attr.isEmpty()) { filename = attr + "/" + _unique + numFilesOpened; } else { filename = _unique + numFilesOpened; } numFilesOpened++; LOG.info("Opening " + filename + " for attribute " + attr); oaf = new OpenAttributeFile(attr, filename, _pail.openWrite(filename, true)); _outputters.put(attr, oaf); } oaf.os.writeRaw(v.getBytes(), 0, v.getLength()); oaf.numBytesWritten+=v.getLength(); logProgress(); } protected void logProgress() { writtenRecords++; if(writtenRecords%100000 == 0) { for(OpenAttributeFile oaf: _outputters.values()) { LOG.info("Attr:" + oaf.attr + " Filename:" + oaf.filename + " Bytes written:" + oaf.numBytesWritten); } } } protected void closeAttributeFile(OpenAttributeFile oaf) throws IOException { LOG.info("Closing " + oaf.filename + " for attr " + oaf.attr); //print out the size of the file here oaf.os.close(); LOG.info("Closed " + oaf.filename + " for attr " + oaf.attr); } public void close(Reporter rprtr) throws IOException { for(String key: _outputters.keySet()) { closeAttributeFile(_outputters.get(key)); rprtr.progress(); } _outputters.clear(); } } public RecordWriter<Text, BytesWritable> getRecordWriter(FileSystem ignored, JobConf jc, String string, Progressable p) throws IOException { return new PailRecordWriter(jc, string, p); } @Override public void checkOutputSpecs(FileSystem fs, JobConf conf) throws IOException { } }
make pailoutputformat throw exception if paired with speculative execution incorrectly
src/jvm/backtype/hadoop/pail/PailOutputFormat.java
make pailoutputformat throw exception if paired with speculative execution incorrectly
Java
bsd-3-clause
f457bf296f05ad483ca1cdb580ff628fef79c4f6
0
LWJGL/lwjgl3,TheMrMilchmann/lwjgl3,LWJGL-CI/lwjgl3,bsmr-java/lwjgl3,code-disaster/lwjgl3,code-disaster/lwjgl3,bsmr-java/lwjgl3,bsmr-java/lwjgl3,code-disaster/lwjgl3,TheMrMilchmann/lwjgl3,LWJGL/lwjgl3,LWJGL-CI/lwjgl3,TheMrMilchmann/lwjgl3,bsmr-java/lwjgl3,LWJGL-CI/lwjgl3,LWJGL/lwjgl3,LWJGL-CI/lwjgl3,TheMrMilchmann/lwjgl3,code-disaster/lwjgl3,LWJGL/lwjgl3
/* * Copyright LWJGL. All rights reserved. * License terms: http://lwjgl.org/license.php */ package org.lwjgl.system; import org.lwjgl.BufferUtils; import org.lwjgl.PointerBuffer; import java.nio.*; import java.util.Arrays; import static org.lwjgl.system.Checks.*; import static org.lwjgl.system.MathUtil.*; import static org.lwjgl.system.MemoryUtil.*; import static org.lwjgl.system.Pointer.*; import static org.lwjgl.system.ThreadLocalUtil.*; /** * An off-heap memory stack. * * <p>This class should be used in a thread-local manner for stack allocations.</p> */ public class MemoryStack { private static final int DEFAULT_STACK_SIZE = Configuration.STACK_SIZE.get(32) * 1024; static { if ( DEFAULT_STACK_SIZE < 0 ) throw new IllegalStateException("Invalid stack size."); } private final ByteBuffer buffer; private final long address; private final int size; private int pointer; private int[] frames; private int frameIndex; /** Creates a new {@link MemoryStack} with the default size. */ public MemoryStack() { this(DEFAULT_STACK_SIZE); } /** * Creates a new {@link MemoryStack} with the specified size. * * @param size the maximum number of bytes that may be allocated on the stack */ public MemoryStack(int size) { this.buffer = BufferUtils.createByteBuffer(size); this.address = memAddress(buffer); this.size = size; this.pointer = size; this.frames = new int[16]; } /** Returns the stack of the current thread. */ public static MemoryStack stackGet() { return tlsGet().stack; } /** * Calls {@link #push} on the stack of the current thread. * * @return the stack of the current thread. */ public static MemoryStack stackPush() { return tlsGet().stack.push(); } /** * Calls {@link #pop} on the stack of the current thread. * * @return the stack of the current thread. */ public static MemoryStack stackPop() { return tlsGet().stack.pop(); } /** * Stores the current stack pointer and pushes a new frame to the stack. * * <p>This method should be called when entering a method, before doing any stack allocations. When exiting a method, call the {@link #pop} method to * restore the previous stack frame.</p> * * <p>Pairs of push/pop calls may be nested. Care must be taken to:</p> * <ul> * <li>match every push with a pop</li> * <li>not call pop before push has been called at least once</li> * <li>not nest push calls to more than the maximum supported depth</li> * </ul> * * @return this stack */ public MemoryStack push() { if ( frameIndex == frames.length ) frames = Arrays.copyOf(frames, frames.length * 2); frames[frameIndex++] = pointer; return this; } /** * Pops the current stack frame and moves the stack pointer to the end of the previous stack frame. * * @return this stack */ public MemoryStack pop() { pointer = frames[--frameIndex]; return this; } /** * Returns the address of the backing off-heap memory. * * <p>The stack grows "downwards", so the bottom of the stack is at {@code address + size}, while the top is at {@code address}.</p> */ public long getAddress() { return address; } /** * Returns the size of the backing off-heap memory. * * <p>This is the maximum number of bytes that may be allocated on the stack.</p> */ public int getSize() { return size; } /** * Returns the current frame index. * * <p>This is the current number of nested {@link #push} calls.</p> */ public int getFrameIndex() { return frameIndex; } /** * Returns the current stack pointer. * * <p>The stack grows "downwards", so when the stack is empty {@code pointer} is equal to {@code size}. On every allocation {@code pointer} is reduced by * the allocated size (after alignment) and {@code address + pointers} points to the last byte of the last allocation.</p> * * <p>Effectively, this methods returns how many more bytes may be allocated on the stack.</p> */ public int getPointer() { return pointer; } private static void checkAlignment(int alignment) { if ( !mathIsPoT(alignment) ) throw new IllegalArgumentException("Alignment must be a power-of-two value."); } private static void checkPointer(int offset) { if ( offset < 0 ) throw new OutOfMemoryError("Out of stack space."); } /** * Calls {@link #nmalloc(int, int)} with {@code alignment} equal to 1. * * @param size the allocation size * * @return the memory address on the stack for the requested allocation */ public long nmalloc(int size) { return nmalloc(1, size); } /** * Allocates a block of {@code size} bytes of memory on the stack. The content of the newly allocated block of memory is not initialized, remaining with * indeterminate values. * * @param alignment the required alignment * @param size the allocation size * * @return the memory address on the stack for the requested allocation */ public long nmalloc(int alignment, int size) { if ( frameIndex == 0 ) throw new IllegalStateException("A frame has not been pushed to the stack yet."); int newPointer = pointer - size; if ( CHECKS ) { checkAlignment(alignment); checkPointer(newPointer); } // Align pointer to the specified alignment newPointer &= ~(alignment - 1); pointer = newPointer; return this.address + newPointer; } /** * Allocates a block of memory on the stack for an array of {@code num} elements, each of them {@code size} bytes long, and initializes all its bits to * zero. * * @param alignment the required element alignment * @param num num the number of elements to allocate * @param size the size of each element * * @return the memory address on the stack for the requested allocation */ public long ncalloc(int alignment, int num, int size) { int bytes = num * size; long address = nmalloc(alignment, bytes); memSet(address, 0, bytes); return address; } /** * Allocates a {@link ByteBuffer} on the stack. * * @param size the number of elements in the buffer * * @return the allocated buffer */ public ByteBuffer malloc(int size) { return memByteBuffer(nmalloc(size), size); } /** Calloc version of {@link #malloc(int)}. */ public ByteBuffer calloc(int size) { return memByteBuffer(ncalloc(1, size, 1), size); } /** Short version of {@link #malloc(int)}. */ public ShortBuffer mallocShort(int size) { return memShortBuffer(nmalloc(2, size << 1), size); } /** Short version of {@link #calloc(int)}. */ public ShortBuffer callocShort(int size) { return memShortBuffer(ncalloc(2, size, 2), size); } /** Int version of {@link #malloc(int)}. */ public IntBuffer mallocInt(int size) { return memIntBuffer(nmalloc(4, size << 2), size); } /** Int version of {@link #calloc(int)}. */ public IntBuffer callocInt(int size) { return memIntBuffer(ncalloc(4, size, 4), size); } /** Long version of {@link #malloc(int)}. */ public LongBuffer mallocLong(int size) { return memLongBuffer(nmalloc(8, size << 3), size); } /** Long version of {@link #calloc(int)}. */ public LongBuffer callocLong(int size) { return memLongBuffer(ncalloc(8, size, 8), size); } /** Float version of {@link #malloc(int)}. */ public FloatBuffer mallocFloat(int size) { return memFloatBuffer(nmalloc(4, size << 2), size); } /** Float version of {@link #calloc(int)}. */ public FloatBuffer callocFloat(int size) { return memFloatBuffer(ncalloc(4, size, 4), size); } /** Double version of {@link #malloc(int)}. */ public DoubleBuffer mallocDouble(int size) { return memDoubleBuffer(nmalloc(8, size << 3), size); } /** Double version of {@link #calloc(int)}. */ public DoubleBuffer callocDouble(int size) { return memDoubleBuffer(ncalloc(8, size, 8), size); } /** Pointer version of {@link #malloc(int)}. */ public PointerBuffer mallocPointer(int size) { return memPointerBuffer(nmalloc(POINTER_SIZE, size << POINTER_SHIFT), size); } /** Pointer version of {@link #calloc(int)}. */ public PointerBuffer callocPointer(int size) { return memPointerBuffer(ncalloc(POINTER_SIZE, size, POINTER_SHIFT), size); } }
modules/core/src/main/java/org/lwjgl/system/MemoryStack.java
/* * Copyright LWJGL. All rights reserved. * License terms: http://lwjgl.org/license.php */ package org.lwjgl.system; import org.lwjgl.BufferUtils; import org.lwjgl.PointerBuffer; import java.nio.*; import java.util.Arrays; import static org.lwjgl.system.Checks.*; import static org.lwjgl.system.MathUtil.*; import static org.lwjgl.system.MemoryUtil.*; import static org.lwjgl.system.Pointer.*; import static org.lwjgl.system.ThreadLocalUtil.*; /** * An off-heap memory stack. * * <p>This class should be used in a thread-local manner for stack allocations.</p> */ public class MemoryStack { private static final int DEFAULT_STACK_SIZE = Configuration.STACK_SIZE.get(32) * 1024; static { if ( DEFAULT_STACK_SIZE < 0 ) throw new IllegalStateException("Invalid stack size."); } private final ByteBuffer buffer; private final long address; private final int size; private int pointer; private int[] frames; private int frameIndex; /** Creates a new {@link MemoryStack} with the default size. */ public MemoryStack() { this(DEFAULT_STACK_SIZE); } /** * Creates a new {@link MemoryStack} with the specified size. * * @param size the maximum number of bytes that may be allocated on the stack */ public MemoryStack(int size) { this.buffer = BufferUtils.createByteBuffer(size); this.address = memAddress(buffer); this.size = size; this.pointer = size; this.frames = new int[16]; } /** Returns the stack of the current thread. */ public static MemoryStack stackGet() { return tlsGet().stack; } /** * Calls {@link #push} on the stack of the current thread. * * @return the stack of the current thread. */ public static MemoryStack stackPush() { return tlsGet().stack.push(); } /** * Calls {@link #pop} on the stack of the current thread. * * @return the stack of the current thread. */ public static MemoryStack stackPop() { return tlsGet().stack.pop(); } /** * Stores the current stack pointer and pushes a new frame to the stack. * * <p>This method should be called when entering a method, before doing any stack allocations. When exiting a method, call the {@link #pop} method to * restore the previous stack frame.</p> * * <p>Pairs of push/pop calls may be nested. Care must be taken to:</p> * <ul> * <li>match every push with a pop</li> * <li>not call pop before push has been called at least once</li> * <li>not nest push calls to more than the maximum supported depth</li> * </ul> * * @return this stack */ public MemoryStack push() { if ( frameIndex == frames.length ) frames = Arrays.copyOf(frames, frames.length * 2); frames[frameIndex++] = pointer; return this; } /** * Pops the current stack frame and moves the stack pointer to the end of the previous stack frame. * * @return this stack */ public MemoryStack pop() { pointer = frames[--frameIndex]; return this; } /** * Returns the address of the backing off-heap memory. * * <p>The stack grows "downwards", so the bottom of the stack is at {@code address + size}, while the top is at {@code address}.</p> */ public long getAddress() { return address; } /** * Returns the size of the backing off-heap memory. * * <p>This is the maximum number of bytes that may be allocated on the stack.</p> */ public int getSize() { return size; } /** * Returns the current frame index. * * <p>This is the current number of nested {@link #push} calls.</p> */ public int getFrameIndex() { return frameIndex; } /** * Returns the current stack pointer. * * <p>The stack grows "downwards", so when the stack is empty {@code pointer} is equal to {@code size}. On every allocation {@code pointer} is reduced by * the allocated size (after alignment) and {@code address + pointers} points to the last byte of the last allocation.</p> * * <p>Effectively, this methods returns how many more bytes may be allocated on the stack.</p> */ public int getPointer() { return pointer; } private static void checkAlignment(int alignment) { if ( !mathIsPoT(alignment) ) throw new IllegalArgumentException("Alignment must be a power-of-two value."); } private static void checkOffset(int offset) { if ( offset < 0 ) throw new OutOfMemoryError("Out of stack space."); } /** * Calls {@link #nmalloc(int, int)} with {@code alignment} equal to 1. * * @param size the allocation size * * @return the memory address on the stack for the requested allocation */ public long nmalloc(int size) { return nmalloc(1, size); } /** * Allocates a block of {@code size} bytes of memory on the stack. The content of the newly allocated block of memory is not initialized, remaining with * indeterminate values. * * @param alignment the required alignment * @param size the allocation size * * @return the memory address on the stack for the requested allocation */ public long nmalloc(int alignment, int size) { if ( frameIndex == 0 ) throw new IllegalStateException("A frame has not been pushed to the stack yet."); int newOffset = pointer - size; if ( CHECKS ) { checkAlignment(alignment); checkOffset(newOffset); } // Align the new offset to the specified alignment newOffset &= ~(alignment - 1); pointer = newOffset; return this.address + newOffset; } /** * Allocates a block of memory on the stack for an array of {@code num} elements, each of them {@code size} bytes long, and initializes all its bits to * zero. * * @param alignment the required element alignment * @param num num the number of elements to allocate * @param size the size of each element * * @return the memory address on the stack for the requested allocation */ public long ncalloc(int alignment, int num, int size) { int bytes = num * size; long address = nmalloc(alignment, bytes); memSet(address, 0, bytes); return address; } /** * Allocates a {@link ByteBuffer} on the stack. * * @param size the number of elements in the buffer * * @return the allocated buffer */ public ByteBuffer malloc(int size) { return memByteBuffer(nmalloc(size), size); } /** Calloc version of {@link #malloc(int)}. */ public ByteBuffer calloc(int size) { return memByteBuffer(ncalloc(1, size, 1), size); } /** Short version of {@link #malloc(int)}. */ public ShortBuffer mallocShort(int size) { return memShortBuffer(nmalloc(2, size << 1), size); } /** Short version of {@link #calloc(int)}. */ public ShortBuffer callocShort(int size) { return memShortBuffer(ncalloc(2, size, 2), size); } /** Int version of {@link #malloc(int)}. */ public IntBuffer mallocInt(int size) { return memIntBuffer(nmalloc(4, size << 2), size); } /** Int version of {@link #calloc(int)}. */ public IntBuffer callocInt(int size) { return memIntBuffer(ncalloc(4, size, 4), size); } /** Long version of {@link #malloc(int)}. */ public LongBuffer mallocLong(int size) { return memLongBuffer(nmalloc(8, size << 3), size); } /** Long version of {@link #calloc(int)}. */ public LongBuffer callocLong(int size) { return memLongBuffer(ncalloc(8, size, 8), size); } /** Float version of {@link #malloc(int)}. */ public FloatBuffer mallocFloat(int size) { return memFloatBuffer(nmalloc(4, size << 2), size); } /** Float version of {@link #calloc(int)}. */ public FloatBuffer callocFloat(int size) { return memFloatBuffer(ncalloc(4, size, 4), size); } /** Double version of {@link #malloc(int)}. */ public DoubleBuffer mallocDouble(int size) { return memDoubleBuffer(nmalloc(8, size << 3), size); } /** Double version of {@link #calloc(int)}. */ public DoubleBuffer callocDouble(int size) { return memDoubleBuffer(ncalloc(8, size, 8), size); } /** Pointer version of {@link #malloc(int)}. */ public PointerBuffer mallocPointer(int size) { return memPointerBuffer(nmalloc(POINTER_SIZE, size << POINTER_SHIFT), size); } /** Pointer version of {@link #calloc(int)}. */ public PointerBuffer callocPointer(int size) { return memPointerBuffer(ncalloc(POINTER_SIZE, size, POINTER_SHIFT), size); } }
More terminology fixes
modules/core/src/main/java/org/lwjgl/system/MemoryStack.java
More terminology fixes
Java
mpl-2.0
367a234490671384c51a03546e3f3b7c75082194
0
Wurst-Imperium/Wurst-MC-1.10
src/net/wurstclient/features/mods/TemplateToolMod.java
/* * Copyright 2014 - 2017 | Wurst-Imperium | All rights reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package net.wurstclient.features.mods; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.TreeSet; import org.lwjgl.input.Keyboard; import org.lwjgl.opengl.GL11; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import net.minecraft.client.gui.GuiButton; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.gui.GuiTextField; import net.minecraft.client.gui.ScaledResolution; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; import net.minecraft.util.text.TextComponentString; import net.minecraft.util.text.event.ClickEvent; import net.wurstclient.compatibility.WBlock; import net.wurstclient.compatibility.WMath; import net.wurstclient.compatibility.WMinecraft; import net.wurstclient.events.listeners.GUIRenderListener; import net.wurstclient.events.listeners.RenderListener; import net.wurstclient.events.listeners.UpdateListener; import net.wurstclient.features.Feature; import net.wurstclient.files.WurstFolders; import net.wurstclient.font.Fonts; import net.wurstclient.utils.ChatUtils; import net.wurstclient.utils.JsonUtils; import net.wurstclient.utils.RenderUtils; @Mod.Info( description = "Allows you to create custom templates for AutoBuild by scanning existing buildings.", name = "TemplateTool") @Mod.Bypasses public final class TemplateToolMod extends Mod implements UpdateListener, RenderListener, GUIRenderListener { private Step step; private BlockPos posLookingAt; private Area area; private Template template; private File file; @Override public Feature[] getSeeAlso() { return new Feature[]{wurst.mods.autoBuildMod}; } @Override public void onEnable() { // disable BowAimbot because it displays its status in the same location // as TemplateTool if(wurst.mods.bowAimbotMod.isEnabled()) wurst.mods.bowAimbotMod.setEnabled(false); step = Step.START_POS; wurst.events.add(UpdateListener.class, this); wurst.events.add(RenderListener.class, this); wurst.events.add(GUIRenderListener.class, this); } @Override public void onDisable() { wurst.events.remove(UpdateListener.class, this); wurst.events.remove(RenderListener.class, this); wurst.events.remove(GUIRenderListener.class, this); for(Step step : Step.values()) step.pos = null; posLookingAt = null; area = null; template = null; file = null; } @Override public void onUpdate() { // select position steps if(step.selectPos) { // continue with next step if(step.pos != null && Keyboard.isKeyDown(Keyboard.KEY_RETURN)) { step = Step.values()[step.ordinal() + 1]; // delete posLookingAt if(!step.selectPos) posLookingAt = null; return; } if(mc.objectMouseOver != null && mc.objectMouseOver.getBlockPos() != null) { // set posLookingAt posLookingAt = mc.objectMouseOver.getBlockPos(); // offset if sneaking if(mc.gameSettings.keyBindSneak.pressed) posLookingAt = posLookingAt.offset(mc.objectMouseOver.sideHit); }else posLookingAt = null; // set selected position if(posLookingAt != null && mc.gameSettings.keyBindUseItem.pressed) step.pos = posLookingAt; // scanning area step }else if(step == Step.SCAN_AREA) { // initialize area if(area == null) { area = new Area(Step.START_POS.pos, Step.END_POS.pos); Step.START_POS.pos = null; Step.END_POS.pos = null; } // scan area for(int i = 0; i < area.scanSpeed && area.iterator.hasNext(); i++) { area.scannedBlocks++; BlockPos pos = area.iterator.next(); if(!WBlock.getMaterial(pos).isReplaceable()) area.blocksFound.add(pos); } // update progress area.progress = (float)area.scannedBlocks / (float)area.totalBlocks; // continue with next step if(!area.iterator.hasNext()) step = Step.values()[step.ordinal() + 1]; // creating template step }else if(step == Step.CREATE_TEMPLATE) { // initialize template if(template == null) template = new Template(Step.FIRST_BLOCK.pos, area.blocksFound.size()); // sort blocks by distance if(!area.blocksFound.isEmpty()) { // move blocks to TreeSet int min = Math.max(0, area.blocksFound.size() - template.scanSpeed); for(int i = area.blocksFound.size() - 1; i >= min; i--) { BlockPos pos = area.blocksFound.get(i); template.remainingBlocks.add(pos); area.blocksFound.remove(i); } // update progress template.progress = (float)template.remainingBlocks.size() / (float)template.totalBlocks; return; } // add closest block to queue if(template.queue.isEmpty() && !template.remainingBlocks.isEmpty()) { BlockPos next = template.remainingBlocks.first(); template.queue.add(next); template.sortedBlocks.add(next); template.remainingBlocks.remove(next); } // add queued blocks to template for(int i = 0; i < template.scanSpeed && !template.queue.isEmpty(); i++) { BlockPos current = template.queue.pop(); for(EnumFacing facing : EnumFacing.values()) { BlockPos next = current.offset(facing); if(template.sortedBlocks.contains(next) || !template.remainingBlocks.contains(next)) continue; template.queue.add(next); template.sortedBlocks.add(next); template.remainingBlocks.remove(next); } } // update progress template.progress = (float)template.remainingBlocks.size() / (float)template.totalBlocks; // continue with next step if(template.sortedBlocks.size() == template.totalBlocks) { step = Step.values()[step.ordinal() + 1]; mc.displayGuiScreen(new GuiChooseName()); } } } @Override public void onRender(float partialTicks) { // scale and offset double scale = 7D / 8D; double offset = (1D - scale) / 2D; // GL settings GL11.glEnable(GL11.GL_BLEND); GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); GL11.glEnable(GL11.GL_LINE_SMOOTH); GL11.glLineWidth(2F); GL11.glDisable(GL11.GL_TEXTURE_2D); GL11.glDisable(GL11.GL_CULL_FACE); GL11.glDisable(GL11.GL_DEPTH_TEST); GL11.glPushMatrix(); GL11.glTranslated(-mc.getRenderManager().renderPosX, -mc.getRenderManager().renderPosY, -mc.getRenderManager().renderPosZ); // area if(area != null) { GL11.glEnable(GL11.GL_DEPTH_TEST); // recently scanned blocks if(step == Step.SCAN_AREA && area.progress < 1) for(int i = Math.max(0, area.blocksFound.size() - area.scanSpeed); i < area.blocksFound.size(); i++) { BlockPos pos = area.blocksFound.get(i); GL11.glPushMatrix(); GL11.glTranslated(pos.getX(), pos.getY(), pos.getZ()); GL11.glTranslated(-0.005, -0.005, -0.005); GL11.glScaled(1.01, 1.01, 1.01); GL11.glColor4f(0F, 1F, 0F, 0.15F); RenderUtils.drawSolidBox(); GL11.glColor4f(0F, 0F, 0F, 0.5F); RenderUtils.drawOutlinedBox(); GL11.glPopMatrix(); } GL11.glPushMatrix(); GL11.glTranslated(area.minX + offset, area.minY + offset, area.minZ + offset); GL11.glScaled(area.sizeX + scale, area.sizeY + scale, area.sizeZ + scale); // area scanner if(area.progress < 1) { GL11.glPushMatrix(); GL11.glTranslated(0, 0, area.progress); GL11.glScaled(1, 1, 0); GL11.glColor4f(0F, 1F, 0F, 0.3F); RenderUtils.drawSolidBox(); GL11.glColor4f(0F, 0F, 0F, 0.5F); RenderUtils.drawOutlinedBox(); GL11.glPopMatrix(); // template scanner }else if(template != null && template.progress > 0) { GL11.glPushMatrix(); GL11.glTranslated(0, 0, template.progress); GL11.glScaled(1, 1, 0); GL11.glColor4f(0F, 1F, 0F, 0.3F); RenderUtils.drawSolidBox(); GL11.glColor4f(0F, 0F, 0F, 0.5F); RenderUtils.drawOutlinedBox(); GL11.glPopMatrix(); } // area box GL11.glColor4f(0F, 0F, 0F, 0.5F); RenderUtils.drawOutlinedBox(); GL11.glPopMatrix(); GL11.glDisable(GL11.GL_DEPTH_TEST); } // sorted blocks if(template != null) for(BlockPos pos : template.sortedBlocks) { GL11.glPushMatrix(); GL11.glTranslated(pos.getX(), pos.getY(), pos.getZ()); GL11.glTranslated(offset, offset, offset); GL11.glScaled(scale, scale, scale); GL11.glColor4f(0F, 0F, 0F, 0.5F); RenderUtils.drawOutlinedBox(); GL11.glPopMatrix(); } // selected positions for(Step step : Step.SELECT_POSITION_STEPS) { BlockPos pos = step.pos; if(pos == null) continue; GL11.glPushMatrix(); GL11.glTranslated(pos.getX(), pos.getY(), pos.getZ()); GL11.glTranslated(offset, offset, offset); GL11.glScaled(scale, scale, scale); GL11.glColor4f(0F, 1F, 0F, 0.15F); RenderUtils.drawSolidBox(); GL11.glColor4f(0F, 0F, 0F, 0.5F); RenderUtils.drawOutlinedBox(); GL11.glPopMatrix(); } // posLookingAt if(posLookingAt != null) { GL11.glPushMatrix(); GL11.glTranslated(posLookingAt.getX(), posLookingAt.getY(), posLookingAt.getZ()); GL11.glTranslated(offset, offset, offset); GL11.glScaled(scale, scale, scale); GL11.glColor4f(0.25F, 0.25F, 0.25F, 0.15F); RenderUtils.drawSolidBox(); GL11.glColor4f(0F, 0F, 0F, 0.5F); RenderUtils.drawOutlinedBox(); GL11.glPopMatrix(); } GL11.glPopMatrix(); // GL resets GL11.glEnable(GL11.GL_DEPTH_TEST); GL11.glEnable(GL11.GL_TEXTURE_2D); GL11.glDisable(GL11.GL_BLEND); GL11.glDisable(GL11.GL_LINE_SMOOTH); } @Override public void onRenderGUI() { // GL settings GL11.glEnable(GL11.GL_BLEND); GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); GL11.glDisable(GL11.GL_TEXTURE_2D); GL11.glDisable(GL11.GL_CULL_FACE); GL11.glPushMatrix(); String message; if(step.selectPos && step.pos != null) message = "Press enter to confirm, or select a different position."; else if(step == Step.FILE_NAME && file != null && file.exists()) message = "WARNING: This file already exists."; else message = step.message; // translate to center ScaledResolution sr = new ScaledResolution(mc); int msgWidth = Fonts.segoe15.getStringWidth(message); GL11.glTranslated(sr.getScaledWidth() / 2 - msgWidth / 2, sr.getScaledHeight() / 2 + 1, 0); // background GL11.glColor4f(0, 0, 0, 0.5F); GL11.glBegin(GL11.GL_QUADS); { GL11.glVertex2d(0, 0); GL11.glVertex2d(msgWidth + 2, 0); GL11.glVertex2d(msgWidth + 2, 10); GL11.glVertex2d(0, 10); } GL11.glEnd(); // text GL11.glEnable(GL11.GL_TEXTURE_2D); Fonts.segoe15.drawString(message, 2, -1, 0xffffffff); GL11.glPopMatrix(); // GL resets GL11.glEnable(GL11.GL_CULL_FACE); GL11.glDisable(GL11.GL_BLEND); } private void saveFile() { step = Step.values()[step.ordinal() + 1]; new Thread(() -> { JsonObject json = new JsonObject(); // get facings EnumFacing front = EnumFacing.getHorizontal(4 - WMinecraft .getPlayer().getHorizontalFacing().getHorizontalIndex()); EnumFacing left = front.rotateYCCW(); // add sorted blocks JsonArray jsonBlocks = new JsonArray(); for(BlockPos pos : template.sortedBlocks) { // translate pos = pos.subtract(Step.FIRST_BLOCK.pos); // rotate pos = new BlockPos(0, pos.getY(), 0).offset(front, pos.getZ()) .offset(left, pos.getX()); // add to json jsonBlocks.add(JsonUtils.gson.toJsonTree( new int[]{pos.getX(), pos.getY(), pos.getZ()}, int[].class)); } json.add("blocks", jsonBlocks); try(PrintWriter save = new PrintWriter(new FileWriter(file))) { // save file save.print(JsonUtils.prettyGson.toJson(json)); // show success message TextComponentString message = new TextComponentString("Saved template as "); TextComponentString link = new TextComponentString(file.getName()); ClickEvent event = new ClickEvent(ClickEvent.Action.OPEN_FILE, file.getParentFile().getAbsolutePath()); link.getStyle().setUnderlined(true).setClickEvent(event); message.appendSibling(link); ChatUtils.component(message); }catch(IOException e) { e.printStackTrace(); // show error message ChatUtils.error("File could not be saved."); } // update AutoBuild wurst.files.loadAutoBuildTemplates(); // disable TemplateTool setEnabled(false); }, "TemplateTool").start(); } private static enum Step { START_POS("Select start position.", true), END_POS("Select end position.", true), SCAN_AREA("Scanning area...", false), FIRST_BLOCK("Select the first block to be placed by AutoBuild.", true), CREATE_TEMPLATE("Creating template...", false), FILE_NAME("Choose a name for this template.", false), SAVE_FILE("Saving file...", false); private static final Step[] SELECT_POSITION_STEPS = {START_POS, END_POS, FIRST_BLOCK}; private final String message; private boolean selectPos; private BlockPos pos; private Step(String message, boolean selectPos) { this.message = message; this.selectPos = selectPos; } } private static class Area { private final int minX, minY, minZ; private final int sizeX, sizeY, sizeZ; private final int totalBlocks, scanSpeed; private final Iterator<BlockPos> iterator; private int scannedBlocks; private float progress; private final ArrayList<BlockPos> blocksFound = new ArrayList<>(); private Area(BlockPos start, BlockPos end) { int startX = start.getX(); int startY = start.getY(); int startZ = start.getZ(); int endX = end.getX(); int endY = end.getY(); int endZ = end.getZ(); minX = Math.min(startX, endX); minY = Math.min(startY, endY); minZ = Math.min(startZ, endZ); sizeX = Math.abs(startX - endX); sizeY = Math.abs(startY - endY); sizeZ = Math.abs(startZ - endZ); totalBlocks = (sizeX + 1) * (sizeY + 1) * (sizeZ + 1); scanSpeed = WMath.clamp(totalBlocks / 30, 1, 1024); iterator = BlockPos.getAllInBox(start, end).iterator(); } } private static class Template { private final int totalBlocks, scanSpeed; private float progress; private final TreeSet<BlockPos> remainingBlocks; private final ArrayDeque<BlockPos> queue = new ArrayDeque<>(); private final LinkedHashSet<BlockPos> sortedBlocks = new LinkedHashSet<>(); public Template(BlockPos firstBlock, int blocksFound) { totalBlocks = blocksFound; scanSpeed = WMath.clamp(blocksFound / 15, 1, 1024); remainingBlocks = new TreeSet<>((o1, o2) -> { // compare distance to start pos int distanceDiff = Double.compare(o1.distanceSq(firstBlock), o2.distanceSq(firstBlock)); if(distanceDiff != 0) return distanceDiff; else return o1.compareTo(o2); }); } } private static class GuiChooseName extends GuiScreen { private final GuiTextField nameField = new GuiTextField(0, Fonts.segoe15, 0, 0, 198, 16); private final GuiButton doneButton = new GuiButton(0, 0, 0, 150, 20, "Done"); private final GuiButton cancelButton = new GuiButton(1, 0, 0, 100, 15, "Cancel"); @Override public void initGui() { // middle int middleX = width / 2; int middleY = height / 2; // name field nameField.xPosition = middleX - 99; nameField.yPosition = middleY + 16; nameField.setEnableBackgroundDrawing(false); nameField.setMaxStringLength(32); nameField.setFocused(true); nameField.setTextColor(0xffffff); // done button doneButton.xPosition = middleX - 75; doneButton.yPosition = middleY + 38; buttonList.add(doneButton); // cancel button cancelButton.xPosition = middleX - 50; cancelButton.yPosition = middleY + 62; buttonList.add(cancelButton); } @Override protected void actionPerformed(GuiButton button) throws IOException { switch(button.id) { case 0: if(nameField.getText().isEmpty() || wurst.mods.templateToolMod.file == null) return; mc.displayGuiScreen(null); wurst.mods.templateToolMod.saveFile(); break; case 1: mc.displayGuiScreen(null); wurst.mods.templateToolMod.setEnabled(false); break; } } @Override public void updateScreen() { nameField.updateCursorCounter(); if(!nameField.getText().isEmpty()) wurst.mods.templateToolMod.file = new File(WurstFolders.AUTOBUILD.toFile(), nameField.getText() + ".json"); } @Override protected void keyTyped(char typedChar, int keyCode) throws IOException { if(keyCode == 1) { actionPerformed(cancelButton); return; } if(keyCode == 28) { actionPerformed(doneButton); return; } nameField.textboxKeyTyped(typedChar, keyCode); } @Override public void drawScreen(int mouseX, int mouseY, float partialTicks) { // middle int middleX = width / 2; int middleY = height / 2; // background positions int x1 = middleX - 100; int y1 = middleY + 15; int x2 = middleX + 100; int y2 = middleY + 26; // background GL11.glDisable(GL11.GL_TEXTURE_2D); GL11.glDisable(GL11.GL_CULL_FACE); GL11.glColor4f(0, 0, 0, 0.5F); GL11.glBegin(GL11.GL_QUADS); { GL11.glVertex2d(x1, y1); GL11.glVertex2d(x2, y1); GL11.glVertex2d(x2, y2); GL11.glVertex2d(x1, y2); } GL11.glEnd(); GL11.glColor4f(1, 1, 1, 1); GL11.glEnable(GL11.GL_TEXTURE_2D); GL11.glEnable(GL11.GL_CULL_FACE); // name field nameField.drawTextBox(); // buttons super.drawScreen(mouseX, mouseY, partialTicks); } @Override public boolean doesGuiPauseGame() { return false; } } }
Move TemplateToolMod
src/net/wurstclient/features/mods/TemplateToolMod.java
Move TemplateToolMod
Java
isc
7a06c439f03c86ecf229167471e1db6b45a0852a
0
yswang0927/simplemagic,j256/simplemagic,yswang0927/simplemagic,j256/simplemagic,yswang0927/simplemagic,yswang0927/simplemagic,j256/simplemagic,j256/simplemagic
package com.j256.simplemagic; import java.util.HashMap; import java.util.Map; /** * Enumerated type of the content if it is known by SimpleMagic matched from the mime-type. This information is _not_ * processed from the magic files. * * @author graywatson */ public enum ContentType { /** AIFF audio format */ AIFF("audio/x-aiff", "aiff", "aif", "aiff", "aifc"), /** Apple Quicktime image */ APPLE_QUICKTIME_IMAGE("image/x-quicktime", null), /** Apple Quicktime movie */ APPLE_QUICKTIME_MOVIE("video/quicktime", "quicktime", "qt", "mov"), /** ARC archive data */ ARC("application/x-arc", "arc", "arc"), /** MPEG audio file */ AUDIO_MPEG("audio/mpeg", "mpeg", "mpeg", "mpg", "mpga", "mp2", "mp2a", "mp3", "m2a", "m3a"), /** Microsoft AVI video file */ AVI("video/x-msvideo", "avi", "avi"), /** Unix AWK command script */ AWK("text/x-awk", "awk", "awk"), /** Macintosh BinHex file */ BINHEX("application/mac-binhex40", "binhex", "hqx"), /** Bittorrent file */ BITTORRENT("application/x-bittorrent", "bittorrent", "torrent"), /** Microsoft PC bitmap image */ BMP("image/x-ms-bmp", "bmp", "bmp"), /** Bzip2 compressed file */ BZIP2("application/x-bzip2", "bzip2", "bz2", "boz"), /** Unix compress file */ COMPRESS("application/x-compress", "compress", "Z"), /** Corel Draw image file */ COREL_DRAW("image/x-coreldraw", "corel-draw"), /** Unix core dump output */ CORE_DUMP("application/x-coredump", "core-dump"), /** Unix CPIO archive data */ CPIO("application/x-cpio", "cpio"), /** Berkeley database file */ DBM("application/x-dbm", "dbm"), /** Debian installation package */ DEBIAN_PACKAGE("application/x-debian-package", "debian-pkg", "pkg", "deb", "udeb"), /** Unix diff output */ DIFF("text/x-diff", "diff"), /** TeX DVI output file */ DVI("application/x-dvi", "dvi", "dvi"), /** Macromedia Flash data */ FLASH("application/x-shockwave-flash", "flash"), /** Macromedia Flash movie file */ FLASH_VIDEO("video/x-flv", "flash-video", "flv"), /** FORTRAN program */ FORTRAN("text/x-fortran", "fortran", "f", "for", "f77", "f90"), /** FrameMaker document */ FRAMEMAKER("application/x-mif", "framemaker", "fm", "frame", "maker", "book"), /** GNU awk script */ GAWK("text/x-gawk", "gawk"), /** GNU database file */ GDBM("application/x-gdbm", "gdbm"), /** GIF image file */ GIF("image/gif", "gif", "gif"), /** GNU Numeric file */ GNUMERIC("application/x-gnumeric", "gnumeric"), /** GPG keyring file */ GNUPG_KEYRING("application/x-gnupg-keyring", "gnupg-keyring"), /** GNU Info file */ GNU_INFO("text/x-info", "gnu-info", "info"), /** Gzip compressed data */ GZIP("application/x-gzip", "gzip", "gz"), /** H264 video encoded file */ H264("video/h264", "h264", "h264"), /** HTML document */ HTML("text/html", "html", "html", "htm"), /** MS Windows icon resource */ ICO("image/x-ico", "ico", "ico"), /** ISO 9660 CD-ROM filesystem data */ ISO_9660("application/x-iso9660-image", "iso9660"), /** Java applet */ JAVA_APPLET("application/x-java-applet", "applet"), /** Java keystore file */ JAVA_KEYSTORE("application/x-java-keystore", "java-keystore"), /** JPEG image */ JPEG("image/jpeg", "jpeg", "jpeg", "jpg", "jpe"), /** JPEG 2000 image */ JPEG_2000("image/jp2", "jp2", "jp2"), /** LHA archive data */ LHA("application/x-lha", "lha", "lha", "lzh"), /** Lisp program */ LISP("text/x-lisp", "lisp"), /** Lotus 123 spreadsheet */ LOTUS_123("application/x-123", "lotus-123", "123"), /** Microsoft access database */ MICROSOFT_ACCESS("application/x-msaccess", "access"), /** Microsoft excel spreadsheet */ MICROSOFT_EXCEL("application/vnd.ms-excel", "excel", "xls", "xlm", "xla", "xlc", "xlt", "xlw"), /** Microsoft word document */ MICROSOFT_WORD("application/msword", "word", "doc", "dot"), /** MIDI audio */ MIDI("audio/midi", "midi", "mid", "midi", "kar", "rmi"), /** MNG video */ MNG("video/x-mng", "mng", "mng"), /** MP4 encoded video */ MP4A("video/mp4", "mp4a", "mp4", "mp4a"), /** MP4V encoded video */ MP4V("video/mp4v-es", "mp4v", "mp4v"), /** New Awk script */ NAWK("text/x-nawk", "nawk"), /** Network news message */ NEWS("message/news", "news"), /** OGG file container */ OGG("application/ogg", "ogg", "ogg", "oga", "spx"), /** PBM image */ PBM("image/x-portable-bitmap", "pbm", "pbm"), /** PDF document */ PDF("application/pdf", "pdf", "pbm"), /** Perl script */ PERL("text/x-perl", "perl", "pl"), /** PGM image */ PGM("image/x-portable-greymap", "pgm", "pgm"), /** PGP encrypted message */ PGP("application/pgp-encrypted", "pgp", "pgp"), /** PGP keyring */ PGP_KEYRING("application/x-pgp-keyring", "pgp-keyring"), /** PGP signature */ PGP_SIGNATURE("application/pgp-signature", "pgp-signature"), /** Photoshop image */ PHOTOSHOP("image/vnd.adobe.photoshop", "photoshop"), /** PHP script */ PHP("text/x-php", "php", "php"), /** PNG image */ PNG("image/png", "png", "png"), /** Postscript file */ POSTSCRIPT("application/postscript", "postscript", "ps", "eps"), /** PPM image */ PPM("image/x-portable-pixmap", "ppm", "ppm"), /** RAR archive data */ RAR("application/x-rar", "rar", "rar"), /** Real-audio file */ REAL_AUDIO("audio/x-pn-realaudio", "real-audio", "ram", "ra"), /** Real-media file */ REAL_MEDIA("application/vnd.rn-realmedia", "real-media"), /** RFC822 news message */ RFC822("message/rfc822", "rfc822"), /** RedHat package file */ RPM("application/x-rpm", "rpm", "rpm"), /** Rich text format document */ RTF("text/rtf", "rtf", "rtf"), /** Shared library file */ SHARED_LIBRARY("application/x-sharedlib", "shared-lib"), /** Unix shell script */ SHELL_SCRIPT("text/x-shellscript", "shell-script", "sh"), /** Mac Stuffit archive data */ STUFFIT("application/x-stuffit", "stuffit"), /** SVG image */ SVG("image/svg+xml", "svg", "svg", "svgz"), /** TAR archive data */ TAR("application/x-tar", "tar", "tar"), /** TeX document */ TEX("text/x-tex", "tex", "tex"), /** TeXinfo document */ TEXINFO("text/x-texinfo", "texinfo", "texinfo", "texi"), /** TIFF image */ TIFF("image/tiff", "tiff", "tiff", "tif"), /** Troff document */ TROFF("text/troff", "troff", "t", "tr", "roff", "man", "me", "ms"), /** vCard visiting card */ VCARD("text/x-vcard", "vcard"), /** Mpeg video */ VIDEO_MPEG("video/mpeg", "mpeg", "mpeg", "mpg", "mpe", "m1v", "m2v"), /** VRML modeling file */ VRML("model/vrml", "vrml", "wrl", "vrml"), /** WAV audio */ WAV("audio/x-wav", "wav", "wav"), /** X3D modeling file */ X3D("model/x3d", "x3d", "x3d"), /** XML document */ XML("application/xml", "xml", "xml", "xsl"), /** Zip archive data */ ZIP("application/zip", "zip", "zip"), /** Zoo archive data */ ZOO("application/x-zoo", "zoo", "zoo"), /** * Copied from http://svn.apache.org/viewvc/httpd/httpd/trunk/docs/conf/mime.types?view=co */ ANDREW_INSERT("application/andrew-inset", "andrew-insert", "ez"), APPLIXWARE("application/applixware", "applixware", "aw", "aw"), ATOM("application/atom+xml", "atom", "atom"), CU_SEEME("application/cu-seeme", "cu-seeme", "cu"), DOCBOOK("application/docbook+xml", "docbook", "dbk"), DSSC("application/dssc+der", "dssc", "dssc"), ECMA_SCRIPT("application/ecmascript", "ecma", "ecma"), EMMA("application/emma+xml", "emma", "emma"), EPUB("application/epub+zip", "epub", "epub"), EXI("application/exi", "exi", "exi"), FONT_TDPFR("application/font-tdpfr", "pfr", "pfr"), GML("application/gml+xml", "gml", "gml"), GPX("application/gpx+xml", "gpx", "gpx"), GXF("application/gxf", "gxf", "gxf"), HYPER_STUDIO("application/hyperstudio", "hyper-studio", "stk"), INKML("application/inkml+xml", "inkml", "ink", "inkml"), IPFIX("application/ipfix", "ipfix", "ipfix"), JAVA_ARCHIVE("application/java-archive", "java-archive", "jar"), JAVA_SERIALIZED("application/java-serialized-object", "java-serialized", "ser"), JAVA_CLASS("application/java-vm", "java-class", "class"), JAVASCRIPT("application/javascript", "javascript", "js"), JSON("application/json", "json", "json"), JSON_ML("application/jsonml+json", "jsonml", "jsonml"), LOST_XML("application/lost+xml", "lostxml", "lostxml"), COMPACT_PRO("application/mac-compactpro", "compact-pro", "cpt"), MADS("application/mads+xml", "mads", "mads"), MARC("application/marc", "marc", "mrc"), MARC_XML("application/marcxml+xml", "marc-xml", "mrcx"), MATHEMATICA("application/mathematica", "mathematica", "ma", "nb", "mb"), MATH_ML("application/mathml+xml", "mathml", "mathml"), MBOX("application/mbox", "mbox", "mbox"), META4("application/metalink4+xml", "meta4", "meta4"), METS("application/mets+xml", "mets", "mets"), MODS("application/mods+xml", "mods", "mods"), MP21("application/mp21", "mp21", "m21", "mp21"), MXF("application/mxf", "mxf", "mxf"), ODA("application/oda", "oda", "oda"), OEBPS_PACKAGE("application/oebps-package+xml", "oebps-package", "opf"), OMDOC("application/omdoc+xml", "omdoc", "omdoc"), ONE_NOTE("application/onenote", "one-note", "onetoc", "onetoc2", "onetmp", "onepkg"), OXPS("application/oxps", "oxps", "oxps"), PICS_RULES("application/pics-rules", "pics-rules", "prf"), PKCS10("application/pkcs10", "pkcs10", "p10"), PKCS7_MIME("application/pkcs7-mime", "pkcs7-mime", "p7m", "p7c"), PKCS7_SIGNATURE("application/pkcs7-signature", "pkcs7-signature", "p7s"), PKCS8("application/pkcs8", "pkcs8", "p8"), PKIX_ATTR_CERT("application/pkix-attr-cert", "ac", "ac"), PKIX_CERT("application/pkix-cert", "pkix-cert", "cer"), PKIX_CRL("application/pkix-crl", "pkix-crl", "crl"), PKIX_PKIPATH("application/pkix-pkipath", "pkix-pkipath", "pkipath"), PKIXCMP("application/pkixcmp", "pkixcmp", "pki"), PLS("application/pls+xml", "pls-xml", "pls"), PRS_CWW("application/prs.cww", "prs-cww", "cww"), PSKC("application/pskc+xml", "pskc", "pskcxml"), RDF("application/rdf+xml", "rdf", "rdf"), REGINFO("application/reginfo+xml", "reginfo", "rif"), RELAX_NG_COMPACT("application/relax-ng-compact-syntax", "relax-ng-compact", "rnc"), RESOURCE_LISTS("application/resource-lists+xml", "resource-lists", "rl"), RESOURCE_LISTS_DIFF("application/resource-lists-diff+xml", "resource-lists-diff", "rld"), RLS_SERVICES("application/rls-services+xml", "rls-services", "rs"), RPKI_GHOSTBUSTERS("application/rpki-ghostbusters", "rpki-ghostbusters", "gbr"), RPKI_MANIFEST("application/rpki-manifest", "rpki-manifest", "mft"), RPKI_ROA("application/rpki-roa", "rpki-roa", "roa"), RSD("application/rsd+xml", "rsd", "rsd"), RSS("application/rss+xml", "rss", "rss"), SBML("application/sbml+xml", "sbml", "sbml"), SCVP_CV_REQUEST("application/scvp-cv-request", "scvp-cv-request", "scq"), SCVP_CV_RESPONSE("application/scvp-cv-response", "scvp-cv-response", "scs"), SCVP_VP_REQUEST("application/scvp-vp-request", "scvp-vp-request", "spq"), SCVP_VP_RESPONSE("application/scvp-vp-response", "scvp-vp-response", "spp"), SDP("application/sdp", "sdp", "sdp"), SHF("application/shf+xml", "shf", "shf"), SMIL("application/smil+xml", "smil", "smi", "smil"), SPARQL_QUERY("application/sparql-query", "sparql-query", "rq"), SPARQL_RESULTS("application/sparql-results+xml", "sparql-results", "srx"), SRGS("application/srgs", "srgs", "gram"), SRGS_XML("application/srgs+xml", "srgs-xml", "grxml"), SRU("application/sru+xml", "sru", "sru"), SSDL("application/ssdl+xml", "ssdl", "ssdl"), SSML("application/ssml+xml", "ssml", "ssml"), TEI("application/tei+xml", "tei", "tei"), TFI("application/thraud+xml", "tfi", "tfi"), TIMESTAMPED_DATA("application/timestamped-data", "timestamped-data", "tsd"), PLB("application/vnd.3gpp.pic-bw-large", "plb", "plb"), PSB("application/vnd.3gpp.pic-bw-small", "psb", "psb"), PVB("application/vnd.3gpp.pic-bw-var", "pvb", "pvb"), TCAP("application/vnd.3gpp2.tcap", "tcap", "tcap"), PWN("application/vnd.3m.post-it-notes", "pwn", "pwn"), ASO("application/vnd.accpac.simply.aso", "aso", "aso"), IMP("application/vnd.accpac.simply.imp", "imp", "imp"), ACU("application/vnd.acucobol", "acu", "acu"), ACU_CORP("application/vnd.acucorp", "acu-corp", "atc", "acutc"), AIR("application/vnd.adobe.air-application-installer-package+zip", "air", "air"), FCDT("application/vnd.adobe.formscentral.fcdt", "fcdt", "fcdt"), ADOBE_FXP("application/vnd.adobe.fxp", "adobe-fxp", "fxp", "fxpl"), XDP("application/vnd.adobe.xdp+xml", "xdp", "xdp"), XFDF("application/vnd.adobe.xfdf", "xfdf", "xfdf"), AHEAD("application/vnd.ahead.space", "ahead", "ahead"), AZF("application/vnd.airzip.filesecure.azf", "azf", "azf"), AZS("application/vnd.airzip.filesecure.azs", "azs", "azs"), AZW("application/vnd.amazon.ebook", "azw", "azw"), ACC("application/vnd.americandynamics.acc", "acc", "acc"), AMI("application/vnd.amiga.ami", "ami", "ami"), APK("application/vnd.android.package-archive", "apk", "apk"), CII("application/vnd.anser-web-certificate-issue-initiation", "cii", "cii"), FTI("application/vnd.anser-web-funds-transfer-initiation", "fti", "fti"), ATX("application/vnd.antix.game-component", "atx", "atx"), MPKG("application/vnd.apple.installer+xml", "mpkg", "mpkg"), M3U8("application/vnd.apple.mpegurl", "m3u8", "m3u8"), SWI("application/vnd.aristanetworks.swi", "swi", "swi"), IOTA("application/vnd.astraea-software.iota", "iota", "iota"), AEP("application/vnd.audiograph", "aep", "aep"), MPM("application/vnd.blueice.multipass", "mpm", "mpm"), BMI("application/vnd.bmi", "bmi", "bmi"), REP("application/vnd.businessobjects", "rep", "rep"), CDXML("application/vnd.chemdraw+xml", "cdxml", "cdxml"), MMD("application/vnd.chipnuts.karaoke-mmd", "mmd", "mmd"), CDY("application/vnd.cinderella", "cdy", "cdy"), CLA("application/vnd.claymore", "cla", "cla"), RP9("application/vnd.cloanto.rp9", "rp9", "rp9"), CLONK_C4GROUP("application/vnd.clonk.c4group", "clonk-c4group", "c4g", "c4d", "c4f", "c4p", "c4u"), C11AMC("application/vnd.cluetrust.cartomobile-config", "c11amc", "c11amc"), C11AMZ("application/vnd.cluetrust.cartomobile-config-pkg", "c11amz", "c11amz"), CSP("application/vnd.commonspace", "csp", "csp"), CDBCMSG("application/vnd.contact.cmsg", "cdbcmsg", "cdbcmsg"), CMC("application/vnd.cosmocaller", "cmc", "cmc"), CLKX("application/vnd.crick.clicker", "clkx", "clkx"), CLKK("application/vnd.crick.clicker.keyboard", "clkk", "clkk"), CLKP("application/vnd.crick.clicker.palette", "clkp", "clkp"), CLKT("application/vnd.crick.clicker.template", "clkt", "clkt"), CLKW("application/vnd.crick.clicker.wordbank", "clkw", "clkw"), WBS("application/vnd.criticaltools.wbs+xml", "wbs", "wbs"), PML("application/vnd.ctc-posml", "pml", "pml"), PPD("application/vnd.cups-ppd", "ppd", "ppd"), CAR("application/vnd.curl.car", "car", "car"), PCURL("application/vnd.curl.pcurl", "pcurl", "pcurl"), DART("application/vnd.dart", "dart", "dart"), RDZ("application/vnd.data-vision.rdz", "rdz", "rdz"), DECE_DATA("application/vnd.dece.data", "dece-data", "uvf", "uvvf", "uvd", "uvvd"), DECE_TTML("application/vnd.dece.ttml+xml", "dece-ttml", "uvt uvvt"), DECE_UNSPECIFIED("application/vnd.dece.unspecified", "dece-unspecified", "uvx uvvx"), DECE_ZIP("application/vnd.dece.zip", "dece-zip", "uvz", "uvvz"), FE_LAUNCH("application/vnd.denovo.fcselayout-link", "fe_launch", "fe_launch"), DNA("application/vnd.dna", "dna", "dna"), MLP("application/vnd.dolby.mlp", "mlp", "mlp"), DPG("application/vnd.dpgraph", "dpg", "dpg"), DFAC("application/vnd.dreamfactory", "dfac", "dfac"), KPXX("application/vnd.ds-keypoint", "kpxx", "kpxx"), AIT("application/vnd.dvb.ait", "ait", "ait"), SVC("application/vnd.dvb.service", "svc", "svc"), GEO("application/vnd.dynageo", "geo", "geo"), MAG("application/vnd.ecowin.chart", "mag", "mag"), NML("application/vnd.enliven", "nml", "nml"), ESF("application/vnd.epson.esf", "esf", "esf"), MSF("application/vnd.epson.msf", "msf", "msf"), QAM("application/vnd.epson.quickanime", "qam", "qam"), SLT("application/vnd.epson.salt", "slt", "slt"), SSF("application/vnd.epson.ssf", "ssf", "ssf"), ESZIGNO3("application/vnd.eszigno3+xml", "eszigno3", "es3", "et3"), EZ2("application/vnd.ezpix-album", "ez2", "ez2"), EZ3("application/vnd.ezpix-package", "ez3", "ez3"), FDF("application/vnd.fdf", "fdf", "fdf"), MSEED("application/vnd.fdsn.mseed", "mseed", "mseed"), FDSN_SEED("application/vnd.fdsn.seed", "fdns-seed", "seed"), GPH("application/vnd.flographit", "gph", "gph"), FTC("application/vnd.fluxtime.clip", "ftc", "ftc"), FNC("application/vnd.frogans.fnc", "fnc", "fnc"), LTF("application/vnd.frogans.ltf", "ltf", "ltf"), FSC("application/vnd.fsc.weblaunch", "fsc", "fsc"), OAS("application/vnd.fujitsu.oasys", "oas", "oas"), OA2("application/vnd.fujitsu.oasys2", "oa2", "oa2"), OA3("application/vnd.fujitsu.oasys3", "oa3", "oa3"), FG5("application/vnd.fujitsu.oasysgp", "fg5", "fg5"), BH2("application/vnd.fujitsu.oasysprs", "bh2", "bh2"), DDD("application/vnd.fujixerox.ddd", "ddd", "ddd"), XDW("application/vnd.fujixerox.docuworks", "xdw", "xdw"), XBD("application/vnd.fujixerox.docuworks.binder", "xbd", "xbd"), FZS("application/vnd.fuzzysheet", "fzs", "fzs"), TXD("application/vnd.genomatix.tuxedo", "txd", "txd"), GGB("application/vnd.geogebra.file", "ggb", "ggb"), GGT("application/vnd.geogebra.tool", "ggt", "ggt"), GEOMETRY_EXPLORER("application/vnd.geometry-explorer", "geometry-explorer", "gex gre"), GXT("application/vnd.geonext", "gxt", "gxt"), G2W("application/vnd.geoplan", "g2w", "g2w"), G3W("application/vnd.geospace", "g3w", "g3w"), GMX("application/vnd.gmx", "gmx", "gmx"), KML("application/vnd.google-earth.kml+xml", "kml", "kml"), KMZ("application/vnd.google-earth.kmz", "kmz", "kmz"), GRAFEQ("application/vnd.grafeq", "grafeq", "gqf gqs"), GAC("application/vnd.groove-account", "gac", "gac"), GHF("application/vnd.groove-help", "ghf", "ghf"), GIM("application/vnd.groove-identity-message", "gim", "gim"), GRV("application/vnd.groove-injector", "grv", "grv"), GTM("application/vnd.groove-tool-message", "gtm", "gtm"), TPL("application/vnd.groove-tool-template", "tpl", "tpl"), VCG("application/vnd.groove-vcard", "vcg", "vcg"), HAL("application/vnd.hal+xml", "hal", "hal"), ZMM("application/vnd.handheld-entertainment+xml", "zmm", "zmm"), HBCI("application/vnd.hbci", "hbci", "hbci"), LES("application/vnd.hhe.lesson-player", "les", "les"), HPGL("application/vnd.hp-hpgl", "hpgl", "hpgl"), HPID("application/vnd.hp-hpid", "hpid", "hpid"), HPS("application/vnd.hp-hps", "hps", "hps"), JLT("application/vnd.hp-jlyt", "jlt", "jlt"), PCL("application/vnd.hp-pcl", "pcl", "pcl"), PCLXL("application/vnd.hp-pclxl", "pclxl", "pclxl"), HYDROSTATIX_SOF("application/vnd.hydrostatix.sof-data", "hydrostatix-sof", "sfd-hdstx"), MPY("application/vnd.ibm.minipay", "mpy", "mpy"), MODCAP("application/vnd.ibm.modcap", "modcap", "afp", "listafp", "list3820"), IRM("application/vnd.ibm.rights-management", "irm", "irm"), SC("application/vnd.ibm.secure-container", "sc", "sc"), ICC_PROFILE("application/vnd.iccprofile", "icc-profile", "icc", "icm"), IGL("application/vnd.igloader", "igl", "igl"), IVP("application/vnd.immervision-ivp", "ivp", "ivp"), IVU("application/vnd.immervision-ivu", "ivu", "ivu"), IGM("application/vnd.insors.igm", "igm", "igm"), INTERCON("application/vnd.intercon.formnet", "intercon", "xpw", "xpx"), I2G("application/vnd.intergeo", "i2g", "i2g"), QBO("application/vnd.intu.qbo", "qbo", "qbo"), QFX("application/vnd.intu.qfx", "qfx", "qfx"), RCPROFILE("application/vnd.ipunplugged.rcprofile", "rcprofile", "rcprofile"), IRP("application/vnd.irepository.package+xml", "irp", "irp"), XPR("application/vnd.is-xpr", "xpr", "xpr"), FCS("application/vnd.isac.fcs", "fcs", "fcs"), JAM("application/vnd.jam", "jam", "jam"), RMS("application/vnd.jcp.javame.midlet-rms", "rms", "rms"), JISP("application/vnd.jisp", "jisp", "jisp"), JODA("application/vnd.joost.joda-archive", "joda", "joda"), KAHOOTZ("application/vnd.kahootz", "kahootz", "ktz", "ktr"), KARBON("application/vnd.kde.karbon", "karbon", "karbon"), CHRT("application/vnd.kde.kchart", "chrt", "chrt"), KFO("application/vnd.kde.kformula", "kfo", "kfo"), FLW("application/vnd.kde.kivio", "flw", "flw"), KON("application/vnd.kde.kontour", "kon", "kon"), KDE_KPRESENTER("application/vnd.kde.kpresenter", "kde-kpresenter", "kpr", "kpt"), KSP("application/vnd.kde.kspread", "ksp", "ksp"), KDE_WORD("application/vnd.kde.kword", "kde-word", "kwd", "kwt"), HTKE("application/vnd.kenameaapp", "htke", "htke"), KIA("application/vnd.kidspiration", "kia", "kia"), KINAR("application/vnd.kinar", "kinar", "kne", "knp"), KOAN("application/vnd.koan", "koan", "skp skd skt skm"), SSE("application/vnd.kodak-descriptor", "sse", "sse"), LASXML("application/vnd.las.las+xml", "lasxml", "lasxml"), LBD("application/vnd.llamagraphics.life-balance.desktop", "lbd", "lbd"), LBE("application/vnd.llamagraphics.life-balance.exchange+xml", "lbe", "lbe"), APR("application/vnd.lotus-approach", "apr", "apr"), PRE("application/vnd.lotus-freelance", "pre", "pre"), NSF("application/vnd.lotus-notes", "nsf", "nsf"), ORG("application/vnd.lotus-organizer", "org", "org"), SCM("application/vnd.lotus-screencam", "scm", "scm"), LWP("application/vnd.lotus-wordpro", "lwp", "lwp"), PORTPKG("application/vnd.macports.portpkg", "portpkg", "portpkg"), MCD("application/vnd.mcd", "mcd", "mcd"), MC1("application/vnd.medcalcdata", "mc1", "mc1"), CDKEY("application/vnd.mediastation.cdkey", "cdkey", "cdkey"), MWF("application/vnd.mfer", "mwf", "mwf"), MFM("application/vnd.mfmp", "mfm", "mfm"), FLO("application/vnd.micrografx.flo", "flo", "flo"), IGX("application/vnd.micrografx.igx", "igx", "igx"), MIF("application/vnd.mif", "mif", "mif"), DAF("application/vnd.mobius.daf", "daf", "daf"), DIS("application/vnd.mobius.dis", "dis", "dis"), MBK("application/vnd.mobius.mbk", "mbk", "mbk"), MQY("application/vnd.mobius.mqy", "mqy", "mqy"), MSL("application/vnd.mobius.msl", "msl", "msl"), PLC("application/vnd.mobius.plc", "plc", "plc"), TXF("application/vnd.mobius.txf", "txf", "txf"), MPN("application/vnd.mophun.application", "mpn", "mpn"), MPC("application/vnd.mophun.certificate", "mpc", "mpc"), XUL("application/vnd.mozilla.xul+xml", "xul", "xul"), CIL("application/vnd.ms-artgalry", "cil", "cil"), CAB("application/vnd.ms-cab-compressed", "cab", "cab"), FONT_OBJECT("application/vnd.ms-fontobject", "font-object", "eot"), CHM("application/vnd.ms-htmlhelp", "chm", "chm"), IMS("application/vnd.ms-ims", "ims", "ims"), LRM("application/vnd.ms-lrm", "lrm", "lrm"), THMX("application/vnd.ms-officetheme", "thmx", "thmx"), CAT("application/vnd.ms-pki.seccat", "cat", "cat"), STL("application/vnd.ms-pki.stl", "stl", "stl"), MICROSOFT_POWERPOINT("application/vnd.ms-powerpoint", "powerpoint", "ppt", "pps", "pot"), PPAM("application/vnd.ms-powerpoint.addin.macroenabled.12", "ppam", "ppam"), PPTM("application/vnd.ms-powerpoint.presentation.macroenabled.12", "pptm", "pptm"), SLDM("application/vnd.ms-powerpoint.slide.macroenabled.12", "sldm", "sldm"), PPSM("application/vnd.ms-powerpoint.slideshow.macroenabled.12", "ppsm", "ppsm"), POTM("application/vnd.ms-powerpoint.template.macroenabled.12", "potm", "potm"), MICROSOFT_PROJECT("application/vnd.ms-project", "project", "mpp", "mpt"), DOCM("application/vnd.ms-word.document.macroenabled.12", "docm", "docm"), DOTM("application/vnd.ms-word.template.macroenabled.12", "dotm", "dotm"), MICROSOFT_WORKS("application/vnd.ms-works", "works", "wps", "wks", "wcm", "wdb"), WPL("application/vnd.ms-wpl", "wpl", "wpl"), XPS("application/vnd.ms-xpsdocument", "xps", "xps"), MSEQ("application/vnd.mseq", "mseq", "mseq"), MUS("application/vnd.musician", "mus", "mus"), MSTY("application/vnd.muvee.style", "msty", "msty"), TAGLET("application/vnd.mynfc", "taglet", "taglet"), NLU("application/vnd.neurolanguage.nlu", "nlu", "nlu"), NITF("application/vnd.nitf", "nitf", "ntf", "nitf"), NND("application/vnd.noblenet-directory", "nnd", "nnd"), NNS("application/vnd.noblenet-sealer", "nns", "nns"), NNW("application/vnd.noblenet-web", "nnw", "nnw"), NGDAT("application/vnd.nokia.n-gage.data", "ngdat", "ngdat"), N_GAGE("application/vnd.nokia.n-gage.symbian.install", "n-gage", "n-gage"), RPST("application/vnd.nokia.radio-preset", "rpst", "rpst"), RPSS("application/vnd.nokia.radio-presets", "rpss", "rpss"), EDM("application/vnd.novadigm.edm", "edm", "edm"), EDX("application/vnd.novadigm.edx", "edx", "edx"), EXT("application/vnd.novadigm.ext", "ext", "ext"), OPENDOCUMENT_CHART("application/vnd.oasis.opendocument.chart", "odc", "odc"), OPENDOCUMENT_CHART_TEMPLATE("application/vnd.oasis.opendocument.chart-template", "otc", "otc"), OPENDOCUMENT_DATABASE("application/vnd.oasis.opendocument.database", "odb", "odb"), OPENDOCUMENT_FORMULA("application/vnd.oasis.opendocument.formula", "odf", "odf"), OPENDOCUMENT_FORMULA_TEMPLATE("application/vnd.oasis.opendocument.formula-template", "odft", "odft"), OPENDOCUMENT_GRAPHICS("application/vnd.oasis.opendocument.graphics", "odg", "odg"), OPENDOCUMENT_GRAPHICS_TEMPLATE("application/vnd.oasis.opendocument.graphics-template", "otg", "otg"), OPENDOCUMENT_IMAGE("application/vnd.oasis.opendocument.image", "odi", "odi"), OPENDOCUMENT_IMAGE_TEMPLATE("application/vnd.oasis.opendocument.image-template", "oti", "oti"), OPENDOCUMENT_PRESENTATION("application/vnd.oasis.opendocument.presentation", "odp", "odp"), OPENDOCUMENT_PRESENTATION_TEMPLATE("application/vnd.oasis.opendocument.presentation-template", "otp", "otp"), OPENDOCUMENT_SPREADSHEET("application/vnd.oasis.opendocument.spreadsheet", "opendocument-spreadsheet", "ods"), OPENDOCUMENT_SPREADSHEET_TEMPLATE("application/vnd.oasis.opendocument.spreadsheet-template", "ots", "ots"), OPENDOCUMENT_TEXT("application/vnd.oasis.opendocument.text", "opendocument-text", "odt"), OPENDOCUMENT_TEXT_MASTER("application/vnd.oasis.opendocument.text-master", "opendocument-text-master", "odm"), OPENDOCUMENT_TEXT_TEMPLATE("application/vnd.oasis.opendocument.text-template", "opendocument-text-template", "ott"), OTH("application/vnd.oasis.opendocument.text-web", "oth", "oth"), XO("application/vnd.olpc-sugar", "xo", "xo"), DD2("application/vnd.oma.dd2+xml", "dd2", "dd2"), OXT("application/vnd.openofficeorg.extension", "oxt", "oxt"), PPTX("application/vnd.openxmlformats-officedocument.presentationml.presentation", "pptx", "pptx"), SLDX("application/vnd.openxmlformats-officedocument.presentationml.slide", "sldx", "sldx"), PPSX("application/vnd.openxmlformats-officedocument.presentationml.slideshow", "ppsx", "ppsx"), POTX("application/vnd.openxmlformats-officedocument.presentationml.template", "potx", "potx"), XLSX("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "xlsx", "xlsx"), XLTX("application/vnd.openxmlformats-officedocument.spreadsheetml.template", "xltx", "xltx"), DOCX("application/vnd.openxmlformats-officedocument.wordprocessingml.document", "docx", "docx"), DOTX("application/vnd.openxmlformats-officedocument.wordprocessingml.template", "dotx", "dotx"), MGP("application/vnd.osgeo.mapguide.package", "mgp", "mgp"), DP("application/vnd.osgi.dp", "dp", "dp"), ESA("application/vnd.osgi.subsystem", "esa", "esa"), PALM("application/vnd.palm", "palm", "pdb", "pqa", "oprc"), PAW("application/vnd.pawaafile", "paw", "paw"), STR("application/vnd.pg.format", "str", "str"), EI6("application/vnd.pg.osasli", "ei6", "ei6"), EFIF("application/vnd.picsel", "efif", "efif"), WG("application/vnd.pmi.widget", "wg", "wg"), PLF("application/vnd.pocketlearn", "plf", "plf"), PBD("application/vnd.powerbuilder6", "pbd", "pbd"), BOX("application/vnd.previewsystems.box", "box", "box"), MGZ("application/vnd.proteus.magazine", "mgz", "mgz"), QPS("application/vnd.publishare-delta-tree", "qps", "qps"), PTID("application/vnd.pvi.ptid1", "ptid", "ptid"), QUARK_XPRESS("application/vnd.quark.quarkxpress", "quark-xpress", "qxd", "qxt", "qwd", "qwt", "qxl", "qxb"), BED("application/vnd.realvnc.bed", "bed", "bed"), MXL("application/vnd.recordare.musicxml", "mxl", "mxl"), MUSICXML("application/vnd.recordare.musicxml+xml", "musicxml", "musicxml"), CRYPTONOTE("application/vnd.rig.cryptonote", "cryptonote", "cryptonote"), COD("application/vnd.rim.cod", "cod", "cod"), RM("application/vnd.rn-realmedia", "rm", "rm"), RMVB("application/vnd.rn-realmedia-vbr", "rmvb", "rmvb"), LINK66("application/vnd.route66.link66+xml", "link66", "link66"), ST("application/vnd.sailingtracker.track", "st", "st"), SEE("application/vnd.seemail", "see", "see"), SEMA("application/vnd.sema", "sema", "sema"), SEMD("application/vnd.semd", "semd", "semd"), SEMF("application/vnd.semf", "semf", "semf"), IFM("application/vnd.shana.informed.formdata", "ifm", "ifm"), ITP("application/vnd.shana.informed.formtemplate", "itp", "itp"), IIF("application/vnd.shana.informed.interchange", "iif", "iif"), IPK("application/vnd.shana.informed.package", "ipk", "ipk"), MIND_MAPPER("application/vnd.simtech-mindmapper", "mind-mapper", "twd", "twds"), MMF("application/vnd.smaf", "mmf", "mmf"), TEACHER("application/vnd.smart.teacher", "teacher", "teacher"), SOLENT("application/vnd.solent.sdkm+xml", "solent", "sdkm", "sdkd"), DXP("application/vnd.spotfire.dxp", "dxp", "dxp"), SFS("application/vnd.spotfire.sfs", "sfs", "sfs"), SDC("application/vnd.stardivision.calc", "sdc", "sdc"), SDA("application/vnd.stardivision.draw", "sda", "sda"), SDD("application/vnd.stardivision.impress", "sdd", "sdd"), SMF("application/vnd.stardivision.math", "smf", "smf"), STARDIVISION_WRITER("application/vnd.stardivision.writer", "stardivision-writer", "sdw", "vor"), STARDIVISION_WRITER_GLOBAL("application/vnd.stardivision.writer-global", "stardivision-writer-global", "sgl"), SMZIP("application/vnd.stepmania.package", "smzip", "smzip"), SM("application/vnd.stepmania.stepchart", "sm", "sm"), SXC("application/vnd.sun.xml.calc", "sxc", "sxc"), STC("application/vnd.sun.xml.calc.template", "stc", "stc"), SXD("application/vnd.sun.xml.draw", "sxd", "sxd"), STD("application/vnd.sun.xml.draw.template", "std", "std"), SXI("application/vnd.sun.xml.impress", "sxi", "sxi"), STI("application/vnd.sun.xml.impress.template", "sti", "sti"), SXM("application/vnd.sun.xml.math", "sxm", "sxm"), SXW("application/vnd.sun.xml.writer", "sxw", "sxw"), SXG("application/vnd.sun.xml.writer.global", "sxg", "sxg"), STW("application/vnd.sun.xml.writer.template", "stw", "stw"), SUS_CALENDAR("application/vnd.sus-calendar", "sus-calendar", "sus", "susp"), SVD("application/vnd.svd", "svd", "svd"), SYMBIAN("application/vnd.symbian.install", "symbian", "sis", "sisx"), XSM("application/vnd.syncml+xml", "xsm", "xsm"), BDM("application/vnd.syncml.dm+wbxml", "bdm", "bdm"), XDM("application/vnd.syncml.dm+xml", "xdm", "xdm"), TAO("application/vnd.tao.intent-module-archive", "tao", "tao"), TCPDUMP("application/vnd.tcpdump.pcap", "tcpdump", "pcap", "cap", "dmp"), TMO("application/vnd.tmobile-livetv", "tmo", "tmo"), TPT("application/vnd.trid.tpt", "tpt", "tpt"), MXS("application/vnd.triscape.mxs", "mxs", "mxs"), TRA("application/vnd.trueapp", "tra", "tra"), UFDL("application/vnd.ufdl", "ufdl", "ufd", "ufdl"), UTZ("application/vnd.uiq.theme", "utz", "utz"), UMJ("application/vnd.umajin", "umj", "umj"), UNITYWEB("application/vnd.unity", "unityweb", "unityweb"), UOML("application/vnd.uoml+xml", "uoml", "uoml"), VCX("application/vnd.vcx", "vcx", "vcx"), VISIO("application/vnd.visio", "visio", "vsd", "vst", "vss", "vsw"), VIS("application/vnd.visionary", "vis", "vis"), VSF("application/vnd.vsf", "vsf", "vsf"), WBXML("application/vnd.wap.wbxml", "wbxml", "wbxml"), WMLC("application/vnd.wap.wmlc", "wmlc", "wmlc"), WMLSC("application/vnd.wap.wmlscriptc", "wmlsc", "wmlsc"), WTB("application/vnd.webturbo", "wtb", "wtb"), NBP("application/vnd.wolfram.player", "nbp", "nbp"), WPD("application/vnd.wordperfect", "wpd", "wpd"), WQD("application/vnd.wqd", "wqd", "wqd"), STF("application/vnd.wt.stf", "stf", "stf"), XAR("application/vnd.xara", "xar", "xar"), XFDL("application/vnd.xfdl", "xfdl", "xfdl"), HVD("application/vnd.yamaha.hv-dic", "hvd", "hvd"), HVS("application/vnd.yamaha.hv-script", "hvs", "hvs"), HVP("application/vnd.yamaha.hv-voice", "hvp", "hvp"), OSF("application/vnd.yamaha.openscoreformat", "osf", "osf"), OSFPVG("application/vnd.yamaha.openscoreformat.osfpvg+xml", "osfpvg", "osfpvg"), SAF("application/vnd.yamaha.smaf-audio", "saf", "saf"), SPF("application/vnd.yamaha.smaf-phrase", "spf", "spf"), CMP("application/vnd.yellowriver-custom-menu", "cmp", "cmp"), ZUL("application/vnd.zul", "zul", "zir", "zirz"), ZAZ("application/vnd.zzazz.deck+xml", "zaz", "zaz"), VXML("application/voicexml+xml", "vxml", "vxml"), WGT("application/widget", "wgt", "wgt"), HLP("application/winhlp", "hlp", "hlp"), WSDL("application/wsdl+xml", "wsdl", "wsdl"), WSPOLICY("application/wspolicy+xml", "wspolicy", "wspolicy"), SEVEN_Z("application/x-7z-compressed", "7z", "7z"), ABW("application/x-abiword", "abw", "abw"), ACE("application/x-ace-compressed", "ace", "ace"), DMG("application/x-apple-diskimage", "dmg", "dmg"), AUTHORWARE("application/x-authorware-bin", "authorware", "aab", "x32", "u32", "vox"), AAM("application/x-authorware-map", "aam", "aam"), AAS("application/x-authorware-seg", "aas", "aas"), BCPIO("application/x-bcpio", "bcpio", "bcpio"), BLORB("application/x-blorb", "blb blorb", "blb blorb"), BZ("application/x-bzip", "bz", "bz"), CBR("application/x-cbr", "cbr", "cbr", "cba", "cbt", "cbz", "cb7"), VCD("application/x-cdlink", "vcd", "vcd"), CFS("application/x-cfs-compressed", "cfs", "cfs"), CHAT("application/x-chat", "chat", "chat"), PGN("application/x-chess-pgn", "pgn", "pgn"), NSC("application/x-conference", "nsc", "nsc"), CSH("application/x-csh", "csh", "csh"), DGC("application/x-dgc-compressed", "dgc", "dgc"), X_DIRCTOR("application/x-director", "x-director", "dir", "dcr", "dxr", "cst", "cct", "cxt", "w3d", "fgd", "swa"), WAD("application/x-doom", "wad", "wad"), NCX("application/x-dtbncx+xml", "ncx", "ncx"), DTB("application/x-dtbook+xml", "dtb", "dtb"), RES("application/x-dtbresource+xml", "res", "res"), EVY("application/x-envoy", "evy", "evy"), EVA("application/x-eva", "eva", "eva"), BDF("application/x-font-bdf", "bdf", "bdf"), GSF("application/x-font-ghostscript", "gsf", "gsf"), PSF("application/x-font-linux-psf", "psf", "psf"), OTF("application/x-font-otf", "otf", "otf"), PCF("application/x-font-pcf", "pcf", "pcf"), SNF("application/x-font-snf", "snf", "snf"), FONT_TTF("application/x-font-ttf", "font-ttf", "ttf", "ttc"), FONT_TYPE1("application/x-font-type1", "font-type1", "pfa", "pfb", "pfm", "afm"), WOFF("application/x-font-woff", "woff", "woff"), SPL("application/x-futuresplash", "spl", "spl"), GCA("application/x-gca-compressed", "gca", "gca"), ULX("application/x-glulx", "ulx", "ulx"), GRAMPS("application/x-gramps-xml", "gramps", "gramps"), GTAR("application/x-gtar", "gtar", "gtar"), HDF("application/x-hdf", "hdf", "hdf"), INSTALL("application/x-install-instructions", "install", "install"), ISO("application/x-iso9660-image", "iso", "iso"), JNLP("application/x-java-jnlp-file", "jnlp", "jnlp"), LATEX("application/x-latex", "latex", "latex"), MIE("application/x-mie", "mie", "mie"), MOBIPOCKET_EBOOK("application/x-mobipocket-ebook", "mobipocket-ebook", "prc", "mobi"), APPLICATION("application/x-ms-application", "application", "application"), LNK("application/x-ms-shortcut", "lnk", "lnk"), WMD("application/x-ms-wmd", "wmd", "wmd"), WMZ("application/x-ms-wmz", "wmz", "wmz"), XBAP("application/x-ms-xbap", "xbap", "xbap"), MDB("application/x-msaccess", "mdb", "mdb"), OBD("application/x-msbinder", "obd", "obd"), CRD("application/x-mscardfile", "crd", "crd"), CLP("application/x-msclip", "clp", "clp"), MICROSOFT_MONEY("application/x-msmoney", "money", "mny"), PUB("application/x-mspublisher", "pub", "pub"), SCD("application/x-msschedule", "scd", "scd"), TRM("application/x-msterminal", "trm", "trm"), MICROSOFT_WRITE("application/x-mswrite", "write", "wri"), NETCDF("application/x-netcdf", "netcdf", "nc", "cdf"), NZB("application/x-nzb", "nzb", "nzb"), PKCS12("application/x-pkcs12", "pkcs12", "p12", "pfx"), PKCS7_CERTIFICATES("application/x-pkcs7-certificates", "pkcs7-certificates", "p7b", "spc"), P7R("application/x-pkcs7-certreqresp", "p7r", "p7r"), RIS("application/x-research-info-systems", "ris", "ris"), SH("application/x-sh", "sh", "sh"), SHAR("application/x-shar", "shar", "shar"), SWF("application/x-shockwave-flash", "swf", "swf"), XAP("application/x-silverlight-app", "xap", "xap"), SQL("application/x-sql", "sql", "sql"), SIT("application/x-stuffit", "sit", "sit"), SITX("application/x-stuffitx", "sitx", "sitx"), SRT("application/x-subrip", "srt", "srt"), SV4CPIO("application/x-sv4cpio", "sv4cpio", "sv4cpio"), SV4CRC("application/x-sv4crc", "sv4crc", "sv4crc"), T3("application/x-t3vm-image", "t3", "t3"), GAM("application/x-tads", "gam", "gam"), TCL("application/x-tcl", "tcl", "tcl"), TFM("application/x-tex-tfm", "tfm", "tfm"), OBJ("application/x-tgif", "obj", "obj"), USTAR("application/x-ustar", "ustar", "ustar"), SRC("application/x-wais-source", "src", "src"), X509_CA_CERT("application/x-x509-ca-cert", "x509-ca-cert", "der", "crt"), XFIG("application/x-xfig", "xfig", "fig"), XLIFF("application/x-xliff+xml", "xliff", "xlf"), XP_INSTALL("application/x-xpinstall", "xp-install", "xpi"), XZ("application/x-xz", "xz", "xz"), ZMACHINE("application/x-zmachine", "zmachine", "z1", "z2", "z3", "z4", "z5", "z6", "z7", "z8"), XAML("application/xaml+xml", "xaml", "xaml"), XDF("application/xcap-diff+xml", "xdf", "xdf"), XENC("application/xenc+xml", "xenc", "xenc"), XHTML("application/xhtml+xml", "xhtml", "xhtml", "xht"), DTD("application/xml-dtd", "dtd", "dtd"), XOP("application/xop+xml", "xop", "xop"), XPL("application/xproc+xml", "xpl", "xpl"), XSLT("application/xslt+xml", "xslt", "xslt"), XSPF("application/xspf+xml", "xspf", "xspf"), XV("application/xv+xml", "xv", "mxml", "xhvml", "xvml", "xvm"), YANG("application/yang", "yang", "yang"), YIN("application/yin+xml", "yin", "yin"), ADP("audio/adpcm", "adp", "adp"), SND("audio/basic", "audio-basic", "au", "snd"), S3M("audio/s3m", "s3m", "s3m"), SIL("audio/silk", "silk", "sil"), DECE_AUDIO("audio/vnd.dece.audio", "dece-audio", "uva", "uvva"), EOL("audio/vnd.digital-winds", "eol", "eol"), DRA("audio/vnd.dra", "dra", "dra"), DTS("audio/vnd.dts", "dts", "dts"), DTSHD("audio/vnd.dts.hd", "dtshd", "dtshd"), LVP("audio/vnd.lucent.voice", "lvp", "lvp"), PYA("audio/vnd.ms-playready.media.pya", "pya", "pya"), ECELP4800("audio/vnd.nuera.ecelp4800", "ecelp4800", "ecelp4800"), ECELP7470("audio/vnd.nuera.ecelp7470", "ecelp7470", "ecelp7470"), ECELP9600("audio/vnd.nuera.ecelp9600", "ecelp9600", "ecelp9600"), RIP("audio/vnd.rip", "rip", "rip"), WEBA("audio/webm", "weba", "weba"), AAC("audio/x-aac", "aac", "aac"), CAF("audio/x-caf", "caf", "caf"), FLAC("audio/x-flac", "flac", "flac"), MKA("audio/x-matroska", "mka", "mka"), M3U("audio/x-mpegurl", "m3u", "m3u"), WAX("audio/x-ms-wax", "wax", "wax"), WMA("audio/x-ms-wma", "wma", "wma"), RMP("audio/x-pn-realaudio-plugin", "rmp", "rmp"), XM("audio/xm", "xm", "xm"), CDX("chemical/x-cdx", "cdx", "cdx"), CIF("chemical/x-cif", "cif", "cif"), CMDF("chemical/x-cmdf", "cmdf", "cmdf"), CML("chemical/x-cml", "cml", "cml"), CSML("chemical/x-csml", "csml", "csml"), XYZ("chemical/x-xyz", "xyz", "xyz"), CGM("image/cgm", "cgm", "cgm"), G3("image/g3fax", "g3", "g3"), IEF("image/ief", "ief", "ief"), KTX("image/ktx", "ktx", "ktx"), BTIF("image/prs.btif", "btif", "btif"), SGI("image/sgi", "sgi", "sgi"), PSD("image/vnd.adobe.photoshop", "psd", "psd"), DECE_GRAPHIC("image/vnd.dece.graphic", "dece-graphic", "uvi", "uvvi", "uvg", "uvvg"), SUB("image/vnd.dvb.subtitle", "sub", "sub"), DJVU("image/vnd.djvu", "djvu", "djvu", "djv"), DWG("image/vnd.dwg", "dwg", "dwg"), DXF("image/vnd.dxf", "dxf", "dxf"), FBS("image/vnd.fastbidsheet", "fbs", "fbs"), FPX("image/vnd.fpx", "fpx", "fpx"), FST("image/vnd.fst", "fst", "fst"), MMR("image/vnd.fujixerox.edmics-mmr", "mmr", "mmr"), RLC("image/vnd.fujixerox.edmics-rlc", "rlc", "rlc"), MDI("image/vnd.ms-modi", "mdi", "mdi"), WDP("image/vnd.ms-photo", "wdp", "wdp"), NPX("image/vnd.net-fpx", "npx", "npx"), WBMP("image/vnd.wap.wbmp", "wbmp", "wbmp"), XIF("image/vnd.xiff", "xif", "xif"), WEBP("image/webp", "webp", "webp"), RAS("image/x-cmu-raster", "ras", "ras"), CMX("image/x-cmx", "cmx", "cmx"), FREEHAND("image/x-freehand", "freehand", "fh", "fhc", "fh4", "fh5", "fh7"), SID("image/x-mrsid-image", "sid", "sid"), PCX("image/x-pcx", "pcx", "pcx"), PICT("image/x-pict", "pict", "pic", "pct"), PNM("image/x-portable-anymap", "pnm", "pnm"), RGB("image/x-rgb", "rgb", "rgb"), TGA("image/x-tga", "tga", "tga"), XBM("image/x-xbitmap", "xbm", "xbm"), XPM("image/x-xpixmap", "xpm", "xpm"), XWD("image/x-xwindowdump", "xwd", "xwd"), MIME("message/rfc822", "mime", "eml", "mime"), IGES("model/iges", "iges", "igs", "iges"), MESH("model/mesh", "mesh", "msh", "mesh", "silo"), DAE("model/vnd.collada+xml", "dae", "dae"), DWF("model/vnd.dwf", "dwf", "dwf"), GDL("model/vnd.gdl", "gdl", "gdl"), GTW("model/vnd.gtw", "gtw", "gtw"), MTS("model/vnd.mts", "mts", "mts"), VTU("model/vnd.vtu", "vtu", "vtu"), X3D_BINARY("model/x3d+binary", "x3d-binary", "x3db", "x3dbz"), X3D_VRML("model/x3d+vrml", "x3d-vrml", "x3dv", "x3dvz"), X3D_XML("model/x3d+xml", "x3d-xml", "x3d", "x3dz"), CALENDAR("text/calendar", "calendar", "ics", "ifb"), CSS("text/css", "css", "css"), CSV("text/csv", "csv", "csv"), N3("text/n3", "n3", "n3"), TEXT("text/plain", "text", "txt", "text"), DSC("text/prs.lines.tag", "dsc", "dsc"), RTX("text/richtext", "rtx", "rtx"), SGML("text/sgml", "sgml", "sgml", "sgm"), TSV("text/tab-separated-values", "tsv", "tsv"), TTL("text/turtle", "ttl", "ttl"), CURL("text/vnd.curl", "curl", "curl"), DCURL("text/vnd.curl.dcurl", "dcurl", "dcurl"), SCURL("text/vnd.curl.scurl", "scurl", "scurl"), MCURL("text/vnd.curl.mcurl", "mcurl", "mcurl"), DVB_SUBTITLE("text/vnd.dvb.subtitle", "dvb-subtitle", "sub"), FLY("text/vnd.fly", "fly", "fly"), FLX("text/vnd.fmi.flexstor", "flx", "flx"), GV("text/vnd.graphviz", "gv", "gv"), SPOT("text/vnd.in3d.spot", "spot", "spot"), JAD("text/vnd.sun.j2me.app-descriptor", "jad", "jad"), WML("text/vnd.wap.wml", "wml", "wml"), WMLS("text/vnd.wap.wmlscript", "wmls", "wmls"), ASSEMBLY("text/x-asm", "assembly", "s asm"), C_SOURCE("text/x-c", "c-source", "c", "cc", "cxx", "cpp", "h", "hh", "dic"), JAVA("text/x-java-source", "java", "java"), OPML("text/x-opml", "opml", "opml"), PASCAL("text/x-pascal", "pascal", "p", "pas"), NFO("text/x-nfo", "nfo", "nfo"), ETX("text/x-setext", "etx", "etx"), SFV("text/x-sfv", "sfv", "sfv"), UU("text/x-uuencode", "uu", "uu"), VCS("text/x-vcalendar", "vcs", "vcs"), VCF("text/x-vcard", "vcf", "vcf"), THREE_GP("video/3gpp", "3gp", "3gp"), THREE_G2("video/3gpp2", "3g2", "3g2"), H261("video/h261", "h261", "h261"), H263("video/h263", "h263", "h263"), JPGV("video/jpeg", "jpgv", "jpgv"), JPM("video/jpm", "jpm", "jpm", "jpgm"), MJ2("video/mj2", "mj2", "mj2", "mjp2"), MP4("video/mp4", "mp4 mp4v mpg4", "mp4", "mp4v", "mpg4"), OGV("video/ogg", "ogv", "ogv"), DECE_HD("video/vnd.dece.hd", "dece-hd", "uvh", "uvvh"), DECE_MOBILE("video/vnd.dece.mobile", "dece-mobile", "uvm", "uvvm"), DECE_PD("video/vnd.dece.pd", "dece-pd", "uvp", "uvvp"), DECE_SD("video/vnd.dece.sd", "dece-sd", "uvs", "uvvs"), DECE_VIDEO("video/vnd.dece.video", "dece-video", "uvv", "uvvv"), DVB("video/vnd.dvb.file", "dvb", "dvb"), FVT("video/vnd.fvt", "fvt", "fvt"), MPEG_URL("video/vnd.mpegurl", "mpeg-url", "mxu", "m4u"), PYV("video/vnd.ms-playready.media.pyv", "pyv", "pyv"), UVVU_MP4("video/vnd.uvvu.mp4", "uvvu-mp4", "uvu", "uvvu"), VIV("video/vnd.vivo", "viv", "viv"), WEBM("video/webm", "webm", "webm"), F4V("video/x-f4v", "f4v", "f4v"), FLI("video/x-fli", "fli", "fli"), FLV("video/x-flv", "flv", "flv"), M4V("video/x-m4v", "m4v", "m4v"), MATROSKA("video/x-matroska", "matroska", "mkv", "mk3d", "mks"), MICROSOFT_ASF("video/x-ms-asf", "asf", "asf", "asx"), VOB("video/x-ms-vob", "vob", "vob"), WM("video/x-ms-wm", "wm", "wm"), WMV("video/x-ms-wmv", "wmv", "wmv"), WMX("video/x-ms-wmx", "wmx", "wmx"), WVX("video/x-ms-wvx", "wvx", "wvx"), MOVIE("video/x-sgi-movie", "movie", "movie"), SMV("video/x-smv", "smv", "smv"), ICE("x-conference/x-cooltalk", "ice", "ice"), /** default if no specific match to the mime-type */ OTHER("application/octet-stream", "other"), // end ; private final static Map<String, ContentType> mimeTypeMap = new HashMap<String, ContentType>(); private final static Map<String, ContentType> fileExtensionMap = new HashMap<String, ContentType>(); static { for (ContentType type : values()) { if (type.mimeType != null) { mimeTypeMap.put(type.mimeType.toLowerCase(), type); } if (type.fileExtensions != null) { for (String fileExtension : type.fileExtensions) { fileExtensionMap.put(fileExtension, type); } } } } private final String mimeType; private final String simpleName; private final String[] fileExtensions; private ContentType(String mimeType, String simpleName, String... fileExtensions) { this.mimeType = mimeType; this.simpleName = simpleName; this.fileExtensions = fileExtensions; } /** * Get simple name of the type. */ public String getSimpleName() { return simpleName; } /** * Return the type associated with the mime-type string or {@link #OTHER} if not found. */ public static ContentType fromMimeType(String mimeType) { // NOTE: mimeType can be null if (mimeType != null) { mimeType = mimeType.toLowerCase(); } ContentType type = mimeTypeMap.get(mimeType); if (type == null) { return OTHER; } else { return type; } } /** * Return the type associated with the file-extension string or {@link #OTHER} if not found. */ public static ContentType fromFileExtension(String fileExtension) { // NOTE: mimeType can be null ContentType type = fileExtensionMap.get(fileExtension.toLowerCase()); if (type == null) { return OTHER; } else { return type; } } }
src/main/java/com/j256/simplemagic/ContentType.java
package com.j256.simplemagic; import java.util.HashMap; import java.util.Map; /** * Enumerated type of the content if it is known by SimpleMagic matched from the mime-type. This information is _not_ * processed from the magic files. * * @author graywatson */ public enum ContentType { /** AIFF audio format */ AIFF("audio/x-aiff", "aiff"), /** Apple Quicktime image */ APPLE_QUICKTIME_IMAGE("image/x-quicktime", null), /** Apple Quicktime movie */ APPLE_QUICKTIME_MOVIE("video/quicktime", "quicktime", "qt"), /** ARC archive data */ ARC("application/x-arc", "arc", "arc"), /** MPEG audio file */ AUDIO_MPEG("audio/mpeg", "mpeg", "mpeg", "mpg"), /** Microsoft AVI video file */ AVI("video/x-msvideo", "avi", "avi"), /** Unix AWK command script */ AWK("text/x-awk", "awk", "awk"), /** Macintosh BinHex file */ BINHEX("application/mac-binhex40", "binhex"), /** Bittorrent file */ BITTORRENT("application/x-bittorrent", "bittorrent"), /** Microsoft PC bitmap image */ BMP("image/x-ms-bmp", "bmp", "bmp"), /** Bzip2 compressed file */ BZIP2("application/x-bzip2", "bzip2", "bz2"), /** Unix compress file */ COMPRESS("application/x-compress", "compress", "Z"), /** Corel Draw image file */ COREL_DRAW("image/x-coreldraw", "corel-draw"), /** Unix core dump output */ CORE_DUMP("application/x-coredump", "core-dump"), /** Unix CPIO archive data */ CPIO("application/x-cpio", "cpio"), /** Berkeley database file */ DBM("application/x-dbm", "dbm"), /** Debian installation package */ DEBIAN_PACKAGE("application/x-debian-package", "pkg", "pkg"), /** Unix diff output */ DIFF("text/x-diff", "diff"), /** TeX DVI output file */ DVI("application/x-dvi", "dvi", "dvi"), /** Macromedia Flash data */ FLASH("application/x-shockwave-flash", "flash"), /** Macromedia Flash movie file */ FLASH_VIDEO("video/x-flv", "flash-video", "flv"), /** FORTRAN program */ FORTRAN("text/x-fortran", "fortran"), /** FrameMaker document */ FRAMEMAKER("application/x-mif", "framemaker"), /** GNU awk script */ GAWK("text/x-gawk", "gawk"), /** GNU database file */ GDBM("application/x-gdbm", "gdbm"), /** GIF image file */ GIF("image/gif", "gif", "gif"), /** GNU Numeric file */ GNUMERIC("application/x-gnumeric", "gnumeric"), /** GPG keyring file */ GNUPG_KEYRING("application/x-gnupg-keyring", "gnupg-keyring"), /** GNU Info file */ GNU_INFO("text/x-info", "gnu-info", "info"), /** Gzip compressed data */ GZIP("application/x-gzip", "gzip", "gz"), /** H264 video encoded file */ H264("video/h264", "h264"), /** HTML document */ HTML("text/html", "html"), /** MS Windows icon resource */ ICO("image/x-ico", "ico", "ico"), /** ISO 9660 CD-ROM filesystem data */ ISO_9660("application/x-iso9660-image", "iso9660"), /** Java applet */ JAVA_APPLET("application/x-java-applet", "applet"), /** Java keystore file */ JAVA_KEYSTORE("application/x-java-keystore", "java-keystore"), /** JPEG image */ JPEG("image/jpeg", "jpeg", "jpeg", "jpg"), /** JPEG 2000 image */ JPEG_2000("image/jp2", "jp2", "jp2"), /** LHA archive data */ LHA("application/x-lha", "lha", "lha"), /** Lisp program */ LISP("text/x-lisp", "lisp"), /** Lotus 123 spreadsheet */ LOTUS_123("application/x-123", "lotus-123"), /** Microsoft access database */ MICROSOFT_ACCESS("application/x-msaccess", "access"), /** Microsoft excel spreadsheet */ MICROSOFT_EXCEL("application/vnd.ms-excel", "excel", "xls"), /** Microsoft word document */ MICROSOFT_WORD("application/msword", "word", "doc"), /** MIDI audio */ MIDI("audio/midi", "midi"), /** MNG video */ MNG("video/x-mng", "mng", "mng"), /** MP4 encoded video */ MP4("video/mp4", "mp4", "mp4"), /** MP4V encoded video */ MP4V("video/mp4v-es", "mp4v", "mp4v"), /** New Awk script */ NAWK("text/x-nawk", "nawk"), /** Network news message */ NEWS("message/news", "news"), /** OGG file container */ OGG("application/ogg", "ogg", "ogg"), /** PBM image */ PBM("image/x-portable-bitmap", "pbm", "pbm"), /** PDF document */ PDF("application/pdf", "pdf", "pbm"), /** Perl script */ PERL("text/x-perl", "perl", "pl"), /** PGM image */ PGM("image/x-portable-greymap", "pgm", "pgm"), /** PGP encrypted message */ PGP("text/PGP", "pgp", "pgp"), /** PGP keyring */ PGP_KEYRING("application/x-pgp-keyring", "pgp-keyring"), /** PGP signature */ PGP_SIGNATURE("application/pgp-signature", "pgp-signature"), /** Photoshop image */ PHOTOSHOP("image/vnd.adobe.photoshop", "photoshop"), /** PHP script */ PHP("text/x-php", "php", "php"), /** PNG image */ PNG("image/png", "png", "png"), /** Postscript file */ POSTSCRIPT("application/postscript", "postscript", "ps"), /** PPM image */ PPM("image/x-portable-pixmap", "ppm", "ppm"), /** RAR archive data */ RAR("application/x-rar", "rar", "rar"), /** Real-audio file */ REAL_AUDIO("audio/x-pn-realaudio", "real-audio"), /** Real-media file */ REAL_MEDIA("application/vnd.rn-realmedia", "real-media"), /** RFC822 news message */ RFC822("message/rfc822", "rfc822"), /** RedHat package file */ RPM("application/x-rpm", "rpm", "rpm"), /** Rich text format document */ RTF("text/rtf", "rtf", "rtf"), /** Shared library file */ SHARED_LIBRARY("application/x-sharedlib", "shared-lib"), /** Unix shell script */ SHELL_SCRIPT("text/x-shellscript", "shell-script", "sh"), /** Mac Stuffit archive data */ STUFFIT("application/x-stuffit", "stuffit"), /** SVG image */ SVG("image/svg+xml", "svg", "svg"), /** TAR archive data */ TAR("application/x-tar", "tar", "tar"), /** TeX document */ TEX("text/x-tex", "tex", "tex"), /** TeXinfo document */ TEXINFO("text/x-texinfo", "texinfo", "texinfo"), /** TIFF image */ TIFF("image/tiff", "tiff", "tiff"), /** Troff document */ TROFF("text/troff", "troff"), /** vCard visiting card */ VCARD("text/x-vcard", "vcard"), /** Mpeg video */ VIDEO_MPEG("video/mpeg", "mpeg", "mpeg", "mpg"), /** VRML modeling file */ VRML("model/vrml", "vrml"), /** WAV audio */ WAV("audio/x-wav", "wav", "wav"), /** X3D modeling file */ X3D("model/x3d", "x3d", "x3d"), /** XML document */ XML("application/xml", "xml", "xml"), /** Zip archive data */ ZIP("application/zip", "zip", "zip"), /** Zoo archive data */ ZOO("application/x-zoo", "zoo", "zoo"), /** default if no specific match to the mime-type */ OTHER("application/octet-stream", "other"), // end ; private final static Map<String, ContentType> mimeTypeMap = new HashMap<String, ContentType>(); private final static Map<String, ContentType> fileExtensionMap = new HashMap<String, ContentType>(); static { for (ContentType type : values()) { if (type.mimeType != null) { mimeTypeMap.put(type.mimeType.toLowerCase(), type); } if (type.fileExtensions != null) { for (String fileExtension : type.fileExtensions) { fileExtensionMap.put(fileExtension, type); } } } } private final String mimeType; private final String simpleName; private final String[] fileExtensions; private ContentType(String mimeType, String simpleName, String... fileExtensions) { this.mimeType = mimeType; this.simpleName = simpleName; this.fileExtensions = fileExtensions; } /** * Get simple name of the type. */ public String getSimpleName() { return simpleName; } /** * Return the type associated with the mime-type string or {@link #OTHER} if not found. */ public static ContentType fromMimeType(String mimeType) { // NOTE: mimeType can be null if (mimeType != null) { mimeType = mimeType.toLowerCase(); } ContentType type = mimeTypeMap.get(mimeType); if (type == null) { return OTHER; } else { return type; } } /** * Return the type associated with the file-extension string or {@link #OTHER} if not found. */ public static ContentType fromFileExtension(String fileExtension) { // NOTE: mimeType can be null ContentType type = fileExtensionMap.get(fileExtension.toLowerCase()); if (type == null) { return OTHER; } else { return type; } } }
Added shit-ton of mime-types and extensions.
src/main/java/com/j256/simplemagic/ContentType.java
Added shit-ton of mime-types and extensions.
Java
mit
65222be40c8048e945fc39f98da2486252caf669
0
flurgle/CameraKit-Android,gogopop/CameraKit-Android,wonderkiln/CameraKit-Android,wonderkiln/CameraKit-Android,wonderkiln/CameraKit-Android,wonderkiln/CameraKit-Android
package com.wonderkiln.camerakit; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.BitmapRegionDecoder; import android.graphics.Rect; import android.support.media.ExifInterface; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import static com.wonderkiln.camerakit.CameraKit.Constants.FACING_FRONT; public class PostProcessor { private byte[] picture; private int jpegQuality; private int facing; private AspectRatio cropAspectRatio; public PostProcessor(byte[] picture) { this.picture = picture; } public void setJpegQuality(int jpegQuality) { this.jpegQuality = jpegQuality; } public void setFacing(int facing) { this.facing = facing; } public void setCropOutput(AspectRatio aspectRatio) { this.cropAspectRatio = aspectRatio; } public byte[] getJpeg() { Bitmap bitmap; try { bitmap = getBitmap(); } catch (IOException e) { return null; } int width = bitmap.getWidth(); int height = bitmap.getHeight(); BitmapOperator bitmapOperator = new BitmapOperator(bitmap); bitmap.recycle(); ExifPostProcessor exifPostProcessor = new ExifPostProcessor(picture); exifPostProcessor.apply(bitmapOperator); if (facing == FACING_FRONT) { bitmapOperator.flipBitmapHorizontal(); } if (cropAspectRatio != null) { int cropWidth = width; int cropHeight = height; if (exifPostProcessor.areDimensionsFlipped()) { cropWidth = height; cropHeight = width; } new CenterCrop(cropWidth, cropHeight, cropAspectRatio).apply(bitmapOperator); } bitmap = bitmapOperator.getBitmapAndFree(); ByteArrayOutputStream out = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, jpegQuality, out); return out.toByteArray(); } private Bitmap getBitmap() throws IOException { BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeByteArray(picture, 0, picture.length, options); return BitmapRegionDecoder.newInstance( picture, 0, picture.length, true ).decodeRegion(new Rect(0, 0, options.outWidth, options.outHeight), null); } private static class ExifPostProcessor { private int orientation = ExifInterface.ORIENTATION_UNDEFINED; public ExifPostProcessor(byte[] picture) { try { orientation = getExifOrientation(new ByteArrayInputStream(picture)); } catch (IOException e) { e.printStackTrace(); } } public void apply(BitmapOperator bitmapOperator) { switch (orientation) { case ExifInterface.ORIENTATION_FLIP_HORIZONTAL: bitmapOperator.flipBitmapHorizontal(); break; case ExifInterface.ORIENTATION_ROTATE_180: bitmapOperator.rotateBitmap(180); break; case ExifInterface.ORIENTATION_FLIP_VERTICAL: bitmapOperator.flipBitmapVertical(); break; case ExifInterface.ORIENTATION_TRANSPOSE: bitmapOperator.rotateBitmap(90); bitmapOperator.flipBitmapHorizontal(); break; case ExifInterface.ORIENTATION_ROTATE_90: bitmapOperator.rotateBitmap(90); break; case ExifInterface.ORIENTATION_TRANSVERSE: bitmapOperator.rotateBitmap(270); bitmapOperator.flipBitmapHorizontal(); break; case ExifInterface.ORIENTATION_ROTATE_270: bitmapOperator.rotateBitmap(270); break; case ExifInterface.ORIENTATION_NORMAL: case ExifInterface.ORIENTATION_UNDEFINED: break; } } public boolean areDimensionsFlipped() { switch (orientation) { case ExifInterface.ORIENTATION_TRANSPOSE: case ExifInterface.ORIENTATION_ROTATE_90: case ExifInterface.ORIENTATION_TRANSVERSE: case ExifInterface.ORIENTATION_ROTATE_270: return true; case ExifInterface.ORIENTATION_FLIP_HORIZONTAL: case ExifInterface.ORIENTATION_ROTATE_180: case ExifInterface.ORIENTATION_FLIP_VERTICAL: case ExifInterface.ORIENTATION_NORMAL: case ExifInterface.ORIENTATION_UNDEFINED: return false; } return false; } private static int getExifOrientation(InputStream inputStream) throws IOException { ExifInterface exif = new ExifInterface(inputStream); return exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL); } } private static class CenterCrop { private int width; private int height; private AspectRatio aspectRatio; public CenterCrop(int width, int height, AspectRatio aspectRatio) { this.width = width; this.height = height; this.aspectRatio = aspectRatio; } public void apply(BitmapOperator bitmapOperator) { Rect crop = getCrop(width, height, aspectRatio); bitmapOperator.cropBitmap(crop.left, crop.top, crop.right, crop.bottom); } private static Rect getCrop(int currentWidth, int currentHeight, AspectRatio targetRatio) { AspectRatio currentRatio = AspectRatio.of(currentWidth, currentHeight); Rect crop; if (currentRatio.toFloat() > targetRatio.toFloat()) { int width = (int) (currentHeight * targetRatio.toFloat()); int widthOffset = (currentWidth - width) / 2; crop = new Rect(widthOffset, 0, currentWidth - widthOffset, currentHeight); } else { int height = (int) (currentWidth * targetRatio.inverse().toFloat()); int heightOffset = (currentHeight - height) / 2; crop = new Rect(0, heightOffset, currentWidth, currentHeight - heightOffset); } return crop; } } }
camerakit/src/main/utils/com/wonderkiln/camerakit/PostProcessor.java
package com.wonderkiln.camerakit; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.BitmapRegionDecoder; import android.graphics.Rect; import android.support.media.ExifInterface; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import static com.wonderkiln.camerakit.CameraKit.Constants.FACING_FRONT; public class PostProcessor { private byte[] picture; private int jpegQuality; private int facing; private AspectRatio cropAspectRatio; public PostProcessor(byte[] picture) { this.picture = picture; } public void setJpegQuality(int jpegQuality) { this.jpegQuality = jpegQuality; } public void setFacing(int facing) { this.facing = facing; } public void setCropOutput(AspectRatio aspectRatio) { this.cropAspectRatio = aspectRatio; } public byte[] getJpeg() { Bitmap bitmap; try { bitmap = getBitmap(); } catch (IOException e) { return null; } BitmapOperator bitmapOperator = new BitmapOperator(bitmap); new ExifPostProcessor(picture).apply(bitmapOperator); if (facing == FACING_FRONT) { bitmapOperator.flipBitmapHorizontal(); } bitmap = bitmapOperator.getBitmap(); if (cropAspectRatio != null) { new CenterCrop(bitmap.getWidth(), bitmap.getHeight(), cropAspectRatio).apply(bitmapOperator); } bitmap = bitmapOperator.getBitmapAndFree(); ByteArrayOutputStream out = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, jpegQuality, out); return out.toByteArray(); } private Bitmap getBitmap() throws IOException { BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeByteArray(picture, 0, picture.length, options); return BitmapRegionDecoder.newInstance( picture, 0, picture.length, true ).decodeRegion(new Rect(0, 0, options.outWidth, options.outHeight), null); } private static class ExifPostProcessor { private int orientation = ExifInterface.ORIENTATION_UNDEFINED; public ExifPostProcessor(byte[] picture) { try { orientation = getExifOrientation(new ByteArrayInputStream(picture)); } catch (IOException e) { e.printStackTrace(); } } public void apply(BitmapOperator bitmapOperator) { switch (orientation) { case ExifInterface.ORIENTATION_FLIP_HORIZONTAL: bitmapOperator.flipBitmapHorizontal(); break; case ExifInterface.ORIENTATION_ROTATE_180: bitmapOperator.rotateBitmap(180); break; case ExifInterface.ORIENTATION_FLIP_VERTICAL: bitmapOperator.flipBitmapVertical(); break; case ExifInterface.ORIENTATION_TRANSPOSE: bitmapOperator.rotateBitmap(90); bitmapOperator.flipBitmapHorizontal(); break; case ExifInterface.ORIENTATION_ROTATE_90: bitmapOperator.rotateBitmap(90); break; case ExifInterface.ORIENTATION_TRANSVERSE: bitmapOperator.rotateBitmap(270); bitmapOperator.flipBitmapHorizontal(); break; case ExifInterface.ORIENTATION_ROTATE_270: bitmapOperator.rotateBitmap(270); break; case ExifInterface.ORIENTATION_NORMAL: case ExifInterface.ORIENTATION_UNDEFINED: break; } } private static int getExifOrientation(InputStream inputStream) throws IOException { ExifInterface exif = new ExifInterface(inputStream); return exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL); } } private static class CenterCrop { private int width; private int height; private AspectRatio aspectRatio; public CenterCrop(int width, int height, AspectRatio aspectRatio) { this.width = width; this.height = height; this.aspectRatio = aspectRatio; } public void apply(BitmapOperator bitmapOperator) { Rect crop = getCrop(width, height, aspectRatio); bitmapOperator.cropBitmap(crop.left, crop.top, crop.right, crop.bottom); } private static Rect getCrop(int currentWidth, int currentHeight, AspectRatio targetRatio) { AspectRatio currentRatio = AspectRatio.of(currentWidth, currentHeight); Rect crop; if (currentRatio.toFloat() > targetRatio.toFloat()) { int width = (int) (currentHeight * targetRatio.toFloat()); int widthOffset = (currentWidth - width) / 2; crop = new Rect(widthOffset, 0, currentWidth - widthOffset, currentHeight); } else { int height = (int) (currentWidth * targetRatio.inverse().toFloat()); int heightOffset = (currentHeight - height) / 2; crop = new Rect(0, heightOffset, currentWidth, currentHeight - heightOffset); } return crop; } } }
Don't encode bitmap just to check new width/height after exif processing
camerakit/src/main/utils/com/wonderkiln/camerakit/PostProcessor.java
Don't encode bitmap just to check new width/height after exif processing
Java
mit
5c1c19c492f243524a5750d339d6869e4566a5bf
0
mtolk/jbake,HuguesH/jbake,rajmahendra/jbake,Vad1mo/JBake,uli-heller/jbake,haumacher/jbake,haumacher/jbake,mohitkanwar/jbake,xuyanxiang/jbake,Vad1mo/JBake,uli-heller/jbake,mohitkanwar/jbake,ancho/jbake,leonac/jbake,ancho/jbake,xuyanxiang/jbake,leonac/jbake,rajmahendra/jbake,danielgrycman/jbake,mtolk/jbake,uli-heller/jbake,haumacher/jbake,kaulkie/jbake,danielgrycman/jbake,leonac/jbake,jbake-org/jbake,ineiros/jbake,jonbullock/jbake,ineiros/jbake,kaulkie/jbake,mohitkanwar/jbake,HuguesH/jbake,ineiros/jbake,jbake-org/jbake,HuguesH/jbake,haumacher/jbake,xuyanxiang/jbake,mtolk/jbake,danielgrycman/jbake,jonbullock/jbake,kaulkie/jbake,Vad1mo/JBake,rajmahendra/jbake
package org.jbake.launcher; import java.io.File; import org.kohsuke.args4j.Argument; import org.kohsuke.args4j.Option; public class LaunchOptions { @Argument(index = 0, usage = "source folder of site content (with templates and assets), if not supplied will default to current working directory", metaVar = "source_folder") private File source = new File("."); @Argument(index = 1, usage = "destination folder for output, if not supplied will default to a folder called \"output\" in the current working directory", metaVar = "destination_folder") private File destination = null; @Option(name = "-i", aliases = {"--init"}, usage="initialises required folder structure with default templates") private boolean init; @Option(name = "-s", aliases = {"--server"}, usage="runs HTTP server to serve out destination folder") private boolean runServer; @Option(name = "-h", aliases = {"--help"}, usage="prints this message") private boolean helpNeeded; public File getSource() { return source; } public File getDestination() { return destination; } public boolean isHelpNeeded() { return helpNeeded; } public boolean isRunServer() { return runServer; } public boolean isInit() { return init; } }
src/main/java/org/jbake/launcher/LaunchOptions.java
package org.jbake.launcher; import java.io.File; import org.kohsuke.args4j.Argument; import org.kohsuke.args4j.Option; public class LaunchOptions { @Argument(index = 0, usage = "source folder of site content (with templates and assets), if not supplied will default to current working directory", metaVar = "source_folder") private File source = new File("."); @Argument(index = 1, usage = "destination folder for output, if not supplied will default to a folder called \"output\" in the current working directory", metaVar = "destination_folder") private File destination = null; @Option(name = "-i", aliases = {"--init"}, usage="initialises required folder structure with default templates") private boolean init; @Option(name = "-s", aliases = {"--server"}, usage="runs HTTP server to serve out destination folder (defaults to port 8080)") private boolean runServer; @Option(name = "-h", aliases = {"--help"}, usage="prints this message") private boolean helpNeeded; public File getSource() { return source; } public File getDestination() { return destination; } public boolean isHelpNeeded() { return helpNeeded; } public boolean isRunServer() { return runServer; } public boolean isInit() { return init; } }
Removed port from usage text.
src/main/java/org/jbake/launcher/LaunchOptions.java
Removed port from usage text.
Java
mit
13eb1ca0a716de65e1da7ea1d64ceb7be0b88ed0
0
shunjikonishi/flectSql
package jp.co.flect.sql; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import java.util.Date; import java.text.SimpleDateFormat; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Types; import jp.co.flect.sql.Condition.LogicalOp; import jp.co.flect.sql.Condition.ComparisionOp; import jp.co.flect.sql.Condition.CompoundCondition; import jp.co.flect.sql.Condition.Combine; /** * SELECT文を構築するクラス<br> * 各種メソッドでテーブル(Selectable)を指定する場合はそのインスタンスは * コンストラクタまたはjoinで指定されていなければなりません。 */ public class SelectBuilder implements Selectable { /** offsetにパラメータを使用することを示す定数 */ public static final int OFFSET_PARAM = -1; /** limitにパラメータを使用することを示す定数 */ public static final int LIMIT_PARAM = -1; private SelectBuilder parent; private String aliasPrefix = ""; private char quoteChar = 0; private TableInfo mainTable; private List<Select> selects = new ArrayList<Select>(); private List<Join> joins = null; private Where where = null; private List<OrderByEntry> orderBy = null; private List<Column> groupBy = null; private ForUpdate forUpdate = null; private boolean distinct = false; private int limit = 0; private int offset = 0; /** ResultSetのデータ型 */ private int[] rsTypes = null; /** * FROM句に指定する主となるテーブルを引数としてSelectBuilderを構築します */ public SelectBuilder(Selectable table) { this.mainTable = new TableInfo(table, "A"); } /** * FROM句に指定された主となるテーブルを返します */ public Selectable getMainTable() { return mainTable.getTable(); } /** * SELECT DISTINCTにします */ public SelectBuilder distinct() { return distinct(true); } /** * SELECT DISTINCTにするかどうかを設定します */ public SelectBuilder distinct(boolean b) { this.distinct = b; return this; } /** * SELECT句にフィールドを追加します<br> * @param field フィールド名 または任意のリテラル */ public SelectBuilder select(String field) { Selectable t = searchTable(field); return select(new Column(t, field)); } /** * SELECT句にフィールドを追加します<br> * @param table フィールドを保持するテーブル。 * @param field フィールド名 */ public SelectBuilder select(Selectable table, String field) { return select(new Column(table, field)); } /** * SELECT句にフィールドを追加します<br> * @param sel フィールド */ public SelectBuilder select(Select sel) { this.selects.add(sel); this.rsTypes = null; return this; } /** * ORDER BY句にフィールドを追加します(昇順)<br> * @param field フィールド名 または任意のリテラル */ public SelectBuilder orderByAsc(String field) { return orderBy(field, true); } /** * ORDER BY句にフィールドを追加します(降順)<br> * @param field フィールド名 または任意のリテラル */ public SelectBuilder orderByDesc(String field) { return orderBy(field, false); } /** * ORDER BY句にフィールドを追加します<br> * @param field フィールド名 または任意のリテラル * @param asc 昇順の場合true */ public SelectBuilder orderBy(String field, boolean asc) { Selectable t = searchTable(field); return orderBy(new Column(t, field), asc); } /** * ORDER BY句にフィールドを追加します(昇順)<br> * @param table フィールドを保持するテーブル。 * @param field フィールド名 */ public SelectBuilder orderByAsc(Selectable t, String field) { return orderBy(t, field, true); } /** * ORDER BY句にフィールドを追加します(降順)<br> * @param table フィールドを保持するテーブル。 * @param field フィールド名 */ public SelectBuilder orderByDesc(Selectable t, String field) { return orderBy(t, field, false); } /** * ORDER BY句にフィールドを追加します<br> * @param table フィールドを保持するテーブル。 * @param field フィールド名 * @param asc 昇順の場合true */ public SelectBuilder orderBy(Selectable t, String field, boolean asc) { return orderBy(new Column(t, field), asc); } /** * ORDER BY句にフィールド番号を追加します(昇順)<br> * @param colNo SELECT句のフィールド番号 */ public SelectBuilder orderByAsc(int colNo) { return orderBy(colNo, true); } /** * ORDER BY句にフィールド番号を追加します(降順)<br> * @param colNo SELECT句のフィールド番号 */ public SelectBuilder orderByDesc(int colNo) { return orderBy(colNo, false); } /** * ORDER BY句にフィールド番号を追加します<br> * @param colNo SELECT句のフィールド番号 * @param asc 昇順の場合true */ public SelectBuilder orderBy(int colNo, boolean asc) { return orderBy(new Column(null, Integer.toString(colNo)), asc); } /** * ORDER BY句にフィールドを追加します(昇順)<br> * @param sel フィールド */ public SelectBuilder orderByAsc(Select sel) { return orderBy(sel, true); } /** * ORDER BY句にフィールドを追加します(降順)<br> * @param sel フィールド */ public SelectBuilder orderByDesc(Select sel) { return orderBy(sel, false); } /** * ORDER BY句にフィールドを追加します<br> * @param sel フィールド * @param asc 昇順の場合true */ public SelectBuilder orderBy(Select sel, boolean asc) { if (this.orderBy == null) { this.orderBy = new ArrayList<OrderByEntry>(); } this.orderBy.add(new OrderByEntry(sel, asc)); return this; } /** * GROUP BY句にフィールドを追加します<br> * @param sel フィールド */ public SelectBuilder groupBy(String field) { Selectable t = searchTable(field); return groupBy(new Column(t, field)); } /** * GROUP BY句にフィールドを追加します<br> * @param table フィールドを保持するテーブル。 * @param sel フィールド */ public SelectBuilder groupBy(Selectable table, String field) { return groupBy(new Column(table, field)); } /** * GROUP BY句にフィールドを追加します<br> * @param col フィールド */ public SelectBuilder groupBy(Column col) { if (this.groupBy == null) { this.groupBy = new ArrayList<Column>(); } this.groupBy.add(col); return this; } /** * OFFSET句にパラメータを使用します */ public SelectBuilder offset() { return offset(OFFSET_PARAM); } /** * OFFSET句を設定します */ public SelectBuilder offset(int n) { this.offset = n; return this; } /** * LIMIT句にパラメータを使用します */ public SelectBuilder limit() { return limit(LIMIT_PARAM); } /** * LIMIT句を設定します */ public SelectBuilder limit(int n) { this.limit = n; return this; } /** * 引数のtableとINNER JOINします * @param table テーブル */ public SelectBuilder innerJoin(Selectable table) { return addJoin(new InnerJoin(table, calcTableAlias())); } /** public SelectBuilder innerJoin(Selectable table, String alias) { return addJoin(new InnerJoin(table, alias)); } */ /** * 引数のtableとLEFT JOINします * @param table テーブル */ public SelectBuilder leftJoin(Selectable table) { return addJoin(new LeftJoin(table, calcTableAlias())); } /* public SelectBuilder leftJoin(Selectable table, String alias) { return addJoin(new LeftJoin(table, alias)); } */ /** * 引数のtableとRIGHT JOINします * @param table テーブル */ public SelectBuilder rightJoin(Selectable table) { return addJoin(new RightJoin(table, calcTableAlias())); } /* public SelectBuilder rightJoin(Selectable table, String alias) { return addJoin(new RightJoin(table, alias)); } */ private SelectBuilder addJoin(Join join) { if (this.joins == null) { this.joins = new ArrayList<Join>(); } this.joins.add(join); return this; } /** * 最後に結合されたJoinを返します。 */ public Join getCurrentJoin() { return joins == null ? null : joins.get(joins.size()-1); } /** * 指定のフィールド名で最後に結合されたJoinのON句を設定します。<br> * フィールド名は新たに結合されたテーブルと既存のテーブルの * 両方に含まれている必要があります。<br> * @param field フィールド名 */ public SelectBuilder on(String field) { return getCurrentJoin().on(field); } /** * 指定のフィールド名で最後に結合されたJoinのON句を設定します。<br> * @param field1 新たに結合されたテーブルのフィールド名 * @param field2 既存のテーブルのフィールド名 */ public SelectBuilder on(String field1, String field2) { return getCurrentJoin().on(field1, field2); } /** * 指定のフィールド名で最後に結合されたJoinのON句を設定します。<br> * @param table1 結合に使用するテーブル1 * @param field1 テーブル1のフィールド名 * @param table2 結合に使用するテーブル2 * @param field2 テーブル2のフィールド名 */ public SelectBuilder on(Selectable table1, String field1, Selectable table2, String field2) { return getCurrentJoin().on(table1, field1, table2, field2); } /** * 指定のフィールド名で最後に結合されたJoinのON句を設定します。<br> * @param table1 結合に使用するテーブル1 * @param field1 テーブル1のフィールド名 * @param table2 結合に使用するテーブル2 * @param field2 テーブル2のフィールド名 * @param op 結合に使用する比較演算子 */ public SelectBuilder on(Selectable table1, String field1, Selectable table2, String field2, ComparisionOp op) { return getCurrentJoin().on(table1, field1, table2, field2, op); } /** * AND条件でWHERE句に条件を追加します。<br> * (andメソッドと処理内容は同じです。) * @param cond 条件 */ public SelectBuilder where(Condition cond) { if (where == null) { where = new Where(cond); } else { where.and(cond); } return this; } /** * AND条件でWHERE句に条件を追加します。<br> * @param cond 条件 */ public SelectBuilder and(Condition cond) { if (where == null) { where = new Where(cond); } else { where.and(cond); } return this; } /** * OR条件でWHERE句に条件を追加します。<br> * @param cond 条件 */ public SelectBuilder or(Condition cond) { if (where == null) { where = new Where(cond); } else { where.or(cond); } return this; } /** * FOR UPDATE を指定します。 */ public SelectBuilder forUpdate() { this.forUpdate = new ForUpdate(false); return this; } /** * FOR UPDATE NOWAIT を指定します。 */ public SelectBuilder forUpdateNoWait() { this.forUpdate = new ForUpdate(true); return this; } /** * テーブル名やフィールド名をクォートする場合そのクォート文字を返します。 */ public char getQuoteChar() { return this.quoteChar;} /** * テーブル名やフィールド名をクォートする場合そのクォート文字を設定します。 */ public void setQuoteChar(char c) { this.quoteChar = c;} /** * SQLを返します。<br> * 設定内容が不正な場合はIllegalArgumentExceptionとなります。 */ public String toSQL() { return toSQL(false); } /** * 改行されたSQLを返します。<br> * 設定内容が不正な場合はIllegalArgumentExceptionとなります。 */ public String toSQL(boolean newLine) { StringBuilder buf = new StringBuilder(); build(buf, newLine); return buf.toString(); } /** * 改行されたSQLを返します。<br> * 設定内容が不正な場合は構築できたところまでのSQL文を返します。 */ @Override public String toString() { StringBuilder buf = new StringBuilder(); try { build(buf, true); return buf.toString(); } catch (Exception e) { e.printStackTrace(); return "Invalid SELECT: " + buf; } } /** * ResultSetの現在の行の内容をMapにコピーします。 */ public Map<String, Object> map(ResultSet rs) throws SQLException { if (this.rsTypes == null) { ResultSetMetaData meta = rs.getMetaData(); if (meta.getColumnCount() < selects.size()) { throw new IllegalArgumentException("Invalid resultSet"); } int[] temp = new int[selects.size()]; for (int i=0; i<selects.size(); i++) { temp[i] = meta.getColumnType(i+1); } this.rsTypes = temp; } Map<String, Object> map = new HashMap<String, Object>(); for (int i=0; i<selects.size(); i++) { Select sel = selects.get(i); int sqlType = rsTypes[i]; Object value = null; switch (sqlType) { case Types.BIGINT: case Types.ROWID: value = rs.getLong(i+1); break; case Types.BLOB: case Types.BINARY: value = rs.getBytes(i+1); break; case Types.BIT: case Types.BOOLEAN: value = rs.getBoolean(i+1); break; case Types.CHAR: case Types.CLOB: case Types.NCHAR: case Types.NCLOB: case Types.NVARCHAR: case Types.SQLXML: case Types.VARCHAR: value = rs.getString(i+1); break; case Types.DATE: value = rs.getDate(i+1); break; case Types.DECIMAL: case Types.NUMERIC: value = rs.getBigDecimal(i+1); break; case Types.DOUBLE: case Types.FLOAT: case Types.REAL: value = rs.getDouble(i+1); break; case Types.INTEGER: case Types.SMALLINT: case Types.TINYINT: value = rs.getInt(i+1); break; case Types.NULL: value = null; break; case Types.TIME: value = rs.getTime(i+1); break; case Types.TIMESTAMP: value = rs.getTimestamp(i+1); break; case Types.OTHER: case Types.REF: case Types.STRUCT: case Types.VARBINARY: break; case Types.ARRAY: case Types.DATALINK: case Types.DISTINCT: case Types.JAVA_OBJECT: case Types.LONGNVARCHAR: case Types.LONGVARBINARY: case Types.LONGVARCHAR: default: throw new IllegalArgumentException("UnsupportedType: " + sqlType); } if (rs.wasNull()) { value = null; } map.put(sel.getFieldName(), value); } return map; } /** * 指定のフィールド名がSELECT句に含まれているかどうかを返します。 */ public boolean hasField(String field) { for (Select sel : this.selects) { if (sel.getFieldName().equals(field)) { return true; } } return false; } SelectBuilder getParent() { return this.parent;} void setParent(SelectBuilder builder) { this.parent = builder;} protected String getAliasPrefix() { return this.aliasPrefix;} void setAliasPrefix(String s) { this.aliasPrefix = s;} Selectable searchTable(String field) { Selectable ret = null; List<Column> checkList = null; if (mainTable.getTable().hasField(field)) { ret = mainTable.getTable(); } if (joins != null) { for (int i=0; i<joins.size(); i++) { TableInfo info = joins.get(i).getTableInfo(); if (info.getTable().hasField(field)) { if (ret == null) { ret = info.getTable(); } else { if (checkList == null) { checkList = new ArrayList<Column>(); checkList.add(new Column(ret, field)); } checkList.add(new Column(info.getTable(), field)); } } } } if (ret == null) { return this.parent != null ? this.parent.searchTable(field) : null; } if (checkList != null) { for (Column col : checkList) { if (!isJoinedColumn(col)) { throw new IllegalArgumentException("Ambiguous reference: " + field); } } } return ret; } List<Condition> getConditions() { if (this.where == null) { return null; } List<Condition> list = new ArrayList<Condition>(); for (WhereEntry entry : where.getList()) { list.add(entry.cond); } return list; } private boolean isJoinedColumn(Column col) { if (joins != null) { for (Join join : joins) { if (join.isJoinedColumn(col)) { return true; } } } return false; } private boolean contains(Selectable t) { if (mainTable.getTable() == t) { return true; } if (joins != null) { for (Join join : joins) { TableInfo info = join.getTableInfo(); if (info.getTable() == t) { return true; } } } return false; } private String getTableAlias(Selectable t) { if (t == mainTable.getTable()) { return mainTable.getAlias(); } if (joins != null) { for (int i=0; i<joins.size(); i++) { TableInfo info = joins.get(i).getTableInfo(); if (info.getTable() == t) { return info.getAlias(); } } } if (parent != null) { return parent.getTableAlias(t); } return null; } /* private Selectable getTable(String alias) { if (alias.equals(mainTable.getAlias())) { return mainTable.getTable(); } if (joins != null) { for (int i=0; i<joins.size(); i++) { TableInfo info = joins.get(i).getTableInfo(); if (alias.equals(info.getAlias())) { return info.getTable(); } } } if (parent != null) { return parent.getTable(alias); } return null; } */ private String calcTableAlias() { int prefixLen = aliasPrefix.length(); char c = 0; String alias = mainTable.getAlias().substring(prefixLen); if (alias.length() == 1) { c = alias.charAt(0); } if (joins != null) { for (Join join : joins) { alias = join.getTableInfo().getAlias().substring(prefixLen); if (alias.length() == 1) { char c2 = alias.charAt(0); if (c2 > c) { c = c2; } } } } return c == 0 ? "A" : "" + (char)(c + 1); } private Selectable getTableByFieldName(String field) { if (mainTable.getTable().hasField(field)) { return mainTable.getTable(); } if (joins != null) { for (Join join : joins) { TableInfo info = join.getTableInfo(); if (info.getTable().hasField(field)) { return info.getTable(); } } } return null; } private void quote(StringBuilder buf, String str) { if (quoteChar == 0) { buf.append(str); } else { buf.append(quoteChar); buf.append(str); buf.append(quoteChar); } } private void build(StringBuilder buf, boolean newLine) { if (selects.size() == 0) { throw new IllegalArgumentException("No select clause"); } boolean bGroup = groupBy != null && groupBy.size() > 0; buf.append("SELECT "); if (distinct) { buf.append("DISTINCT "); } boolean first = true; for (Select sel : selects) { if (first) { first = false; } else { buf.append(", "); } if (newLine) { buf.append("\n "); } sel.build(buf, this); if (sel instanceof Aggregate) { bGroup = true; } } if (newLine) { buf.append("\n"); } else { buf.append(" "); } buf.append("FROM "); mainTable.build(buf); if (joins != null) { for (Join join : joins) { if (newLine) { buf.append("\n"); } else { buf.append(" "); } join.build(buf); } } if (where != null) { where.build(buf, newLine); } if (bGroup) { List<Column> gList = groupBy != null ? groupBy : getGroupByColumn(selects); if (gList.size() > 0) { if (newLine) { buf.append("\n"); } else { buf.append(" "); } buf.append("GROUP BY "); first = true; for (Column col : gList) { if (first) { first = false; } else { buf.append(", "); } if (newLine) { buf.append("\n "); } col.doBuild(buf, this); } } } if (orderBy != null) { if (newLine) { buf.append("\n"); } else { buf.append(" "); } buf.append("ORDER BY "); first = true; for (OrderByEntry entry : orderBy) { if (first) { first = false; } else { buf.append(", "); } if (newLine) { buf.append("\n "); } entry.sel.doBuild(buf, this); if (!entry.asc) { buf.append(" DESC"); } } } if (offset != 0) { if (newLine) { buf.append("\n"); } else { buf.append(" "); } buf.append("OFFSET ").append(offset == OFFSET_PARAM ? "?" : Integer.toString(offset)); } if (limit != 0) { if (newLine) { buf.append("\n"); } else { buf.append(" "); } buf.append("LIMIT ").append(limit == LIMIT_PARAM ? "?" : limit == 0 ? "ALL" : Integer.toString(limit)); } if (forUpdate != null) { buf.append(forUpdate); } } private List<Column> getGroupByColumn(List<Select> list) { List<Column> ret = new ArrayList<Column>(); for (Select sel : list) { if (sel instanceof Column) { ret.add((Column)sel); } } return ret; } /** * SELECT句の抽象クラス */ public static abstract class Select { private String alias; public Select alias(String s) { this.alias = s; return this; } public String alias() { return this.alias;} public Select as(String s) { return alias(s); } public String as() { return alias();} public String getFieldName() { if (this.alias != null) { return this.alias; } return doGetFieldName(); } protected abstract String doGetFieldName(); public final void build(StringBuilder buf, SelectBuilder builder) { doBuild(buf, builder); String a = alias(); if (a != null) { buf.append(" AS "); builder.quote(buf, a); } } protected abstract void doBuild(StringBuilder buf, SelectBuilder builder); } /** * SELECT句で使用する任意のリテラル */ public static class Literal extends Select { private Object literal; public Literal(Object literal) { this.literal = literal; } protected String doGetFieldName() { return literal.toString(); } protected void doBuild(StringBuilder buf, SelectBuilder builder) { buf.append(this.literal); } public static final Literal TRUE = new Literal(true); public static final Literal FALSE = new Literal(false); } /** * SELECT句で使用するフィールド */ public static class Column extends Select { private Selectable table; private String field; public Column(String f) { this(null, f); } public Column(Selectable t, String f) { this.table = t; this.field = f; } protected String doGetFieldName() { return field; } protected void doBuild(StringBuilder buf, SelectBuilder builder) { Selectable t = this.table; String ta = null; if (t == null) { t = builder.searchTable(this.field); } if (t != null) { ta = builder.getTableAlias(t); if (ta == null) { throw new IllegalArgumentException("Unknown table: " + t); } } if (ta != null) { builder.quote(buf, ta); buf.append("."); } builder.quote(buf, field); } public Selectable getTable() { return this.table;} void setTable(Selectable t) { this.table = t;} public String getField() { return this.field;} void setField(String s) { this.field = s;} } /** * 関数 */ public static class Function extends Select { private String functionName; private Object[] args; public Function(String functionName, Object... args) { this.functionName = functionName; this.args = args; } protected String doGetFieldName() { return this.functionName; } protected void doBuild(StringBuilder buf, SelectBuilder builder) { buf.append(this.functionName) .append("("); if (this.args != null) { boolean first = true; for (Object o : args) { if (first) { first = false; } else { buf.append(", "); } appendObject(buf, builder, o); } } buf.append(")"); } } /** * 集合関数 */ public static class Aggregate extends Function { public Aggregate(String functionName, Object... args) { super(functionName, args); } } /** * Case */ public static class Case extends Select { private List<CaseEntry> list = new ArrayList<CaseEntry>(); private Select elseValue; public Case when(Condition cond, Select value) { this.list.add(new CaseEntry(cond, value)); return this; } public Case caseElse(Select value) { elseValue = value; return this; } @Override protected String doGetFieldName() { return "CASE"; } @Override protected void doBuild(StringBuilder buf, SelectBuilder builder) { buf.append("CASE "); for (CaseEntry entry : list) { buf.append("WHEN "); entry.cond.build(buf, builder); buf.append(" THEN "); entry.value.build(buf, builder); } if (elseValue != null) { buf.append(" ELSE "); elseValue.build(buf, builder); } buf.append(" END"); } } /** * JOIN句の抽象クラス */ public abstract class Join { private TableInfo info; private CompoundCondition on = new CompoundCondition(LogicalOp.AND); public Join(Selectable t, String a) { if (a == null) { a = calcTableAlias(); } this.info = new TableInfo(t, a); } public SelectBuilder on(String field) { return on(field, field); } public SelectBuilder on(String field1, String field2) { if (!info.getTable().hasField(field1)) { if (!info.getTable().hasField(field2)) { throw new IllegalArgumentException("Both " + field1 + " and " + field2 + " are not field of " + info.getTable()); } else { return on(field2, field1); } } Selectable table1 = info.getTable(); Selectable table2 = getTableByFieldName(field2); if (table2 == null || table2 == table1) { throw new IllegalArgumentException("Invalid field: " + field2); } return on(table1, field1, table2, field2, ComparisionOp.Equal); } public SelectBuilder on(Selectable table1, String field1, Selectable table2, String field2) { return on(table1, field1, table2, field2, ComparisionOp.Equal); } public SelectBuilder on(Selectable table1, String field1, Selectable table2, String field2, ComparisionOp op) { Column col1 = new Column(table1, field1); Column col2 = new Column(table2, field2); on.add(new Combine(col1, col2, op)); return SelectBuilder.this; } //同一のフィールド名で他のテーブルとJoinしてる場合true public boolean isJoinedColumn(Column col) { for (Condition c : on.getList()) { if (c instanceof Combine) { Combine combi = (Combine)c; if (combi.getOp() == ComparisionOp.Equal && combi.getCol1() instanceof Column && combi.getCol2() instanceof Column) { Column cc1 = (Column)combi.getCol1(); Column cc2 = (Column)combi.getCol2(); if ((cc1.getTable() == col.getTable() || cc2.getTable() == col.getTable()) && cc1.getField().equals(col.getField()) && cc2.getField().equals(col.getField())) { return true; } } } } return false; } public abstract String getJoinString(); public TableInfo getTableInfo() { return this.info; } public void build(StringBuilder buf) { buf.append(getJoinString()).append(" "); info.build(buf); if (on.size() > 0) { buf.append(" ON "); on.build(buf, SelectBuilder.this, false); } } } private class InnerJoin extends Join { public InnerJoin(Selectable t, String a) { super(t, a); } public String getJoinString() { return "INNER JOIN"; } } private class LeftJoin extends Join { public LeftJoin(Selectable t, String a) { super(t, a); } public String getJoinString() { return "LEFT JOIN"; } } private class RightJoin extends Join { public RightJoin(Selectable t, String a) { super(t, a); } public String getJoinString() { return "RIGHT JOIN"; } } private class TableInfo { private Selectable table; private String alias; public TableInfo (Selectable t, String a) { this.table = t; this.alias = a; } public void build(StringBuilder buf) { if (table instanceof Table) { quote(buf, ((Table)table).getTableName()); } else if (table instanceof SelectBuilder) { buf.append("(").append(((SelectBuilder)table).toSQL()).append(")"); } else { throw new IllegalStateException(); } buf.append(" "); quote(buf, getAlias()); } public Selectable getTable() { return this.table;} public String getAlias() { return SelectBuilder.this.aliasPrefix + this.alias;} } private class Where { private List<WhereEntry> list = new ArrayList<WhereEntry>(); public Where(Condition cond) { and(cond); } public List<WhereEntry> getList() { return this.list;} public SelectBuilder and(Condition cond) { return doAdd(cond, LogicalOp.AND); } public SelectBuilder or(Condition cond) { return doAdd(cond, LogicalOp.OR); } private SelectBuilder doAdd(Condition cond, LogicalOp op) { list.add(new WhereEntry(cond, op)); return SelectBuilder.this; } public void build(StringBuilder buf, boolean newLine) { for (int i=0; i<list.size(); i++) { WhereEntry entry = list.get(i); if (newLine) { buf.append("\n"); } else { buf.append(" "); } if (i == 0) { buf.append("WHERE "); } else { buf.append(entry.op).append(" "); } entry.cond.build(buf, SelectBuilder.this); } } } private static class WhereEntry { private Condition cond; private LogicalOp op; public WhereEntry(Condition cond, LogicalOp op) { this.cond = cond; this.op = op; } } private static class OrderByEntry { private Select sel; private boolean asc; public OrderByEntry(Select sel, boolean asc) { this.sel = sel; this.asc = asc; } } public static class CaseEntry { public Condition cond; public Select value; public CaseEntry(Condition cond, Select value) { this.cond = cond; this.value = value; } } private static class ForUpdate { private boolean nowait; public ForUpdate(boolean nowait) { this.nowait = nowait; } public String toString() { String ret = " FOR UPDATE"; if (nowait) { ret += " NOWAIT"; } return ret; } } static void appendObject(StringBuilder buf, SelectBuilder builder, Object value) { if (value instanceof String) { String str = value.toString(); buf.append("'"); for (int i=0; i<str.length(); i++) { char c = str.charAt(i); if (c == '\'') { buf.append("''"); } else { buf.append(c); } } buf.append("'"); } else if (value instanceof Date) { buf.append("'") .append(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format((Date)value)) .append("'"); } else if (value instanceof Select) { ((Select)value).build(buf, builder); } else { buf.append(value); } } }
src/main/java/jp/co/flect/sql/SelectBuilder.java
package jp.co.flect.sql; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import java.util.Date; import java.text.SimpleDateFormat; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Types; import jp.co.flect.sql.Condition.LogicalOp; import jp.co.flect.sql.Condition.ComparisionOp; import jp.co.flect.sql.Condition.CompoundCondition; import jp.co.flect.sql.Condition.Combine; /** * SELECT文を構築するクラス<br> * 各種メソッドでテーブル(Selectable)を指定する場合はそのインスタンスは * コンストラクタまたはjoinで指定されていなければなりません。 */ public class SelectBuilder implements Selectable { /** offsetにパラメータを使用することを示す定数 */ public static final int OFFSET_PARAM = -1; /** limitにパラメータを使用することを示す定数 */ public static final int LIMIT_PARAM = -1; private SelectBuilder parent; private String aliasPrefix = ""; private char quoteChar = 0; private TableInfo mainTable; private List<Select> selects = new ArrayList<Select>(); private List<Join> joins = null; private Where where = null; private List<OrderByEntry> orderBy = null; private List<Column> groupBy = null; private ForUpdate forUpdate = null; private boolean distinct = false; private int limit = 0; private int offset = 0; /** ResultSetのデータ型 */ private int[] rsTypes = null; /** * FROM句に指定する主となるテーブルを引数としてSelectBuilderを構築します */ public SelectBuilder(Selectable table) { this.mainTable = new TableInfo(table, "A"); } /** * FROM句に指定された主となるテーブルを返します */ public Selectable getMainTable() { return mainTable.getTable(); } /** * SELECT DISTINCTにします */ public SelectBuilder distinct() { return distinct(true); } /** * SELECT DISTINCTにするかどうかを設定します */ public SelectBuilder distinct(boolean b) { this.distinct = b; return this; } /** * SELECT句にフィールドを追加します<br> * @param field フィールド名 または任意のリテラル */ public SelectBuilder select(String field) { Selectable t = searchTable(field); return select(new Column(t, field)); } /** * SELECT句にフィールドを追加します<br> * @param table フィールドを保持するテーブル。 * @param field フィールド名 */ public SelectBuilder select(Selectable table, String field) { return select(new Column(table, field)); } /** * SELECT句にフィールドを追加します<br> * @param sel フィールド */ public SelectBuilder select(Select sel) { this.selects.add(sel); this.rsTypes = null; return this; } /** * ORDER BY句にフィールドを追加します(昇順)<br> * @param field フィールド名 または任意のリテラル */ public SelectBuilder orderByAsc(String field) { return orderBy(field, true); } /** * ORDER BY句にフィールドを追加します(降順)<br> * @param field フィールド名 または任意のリテラル */ public SelectBuilder orderByDesc(String field) { return orderBy(field, false); } /** * ORDER BY句にフィールドを追加します<br> * @param field フィールド名 または任意のリテラル * @param asc 昇順の場合true */ public SelectBuilder orderBy(String field, boolean asc) { Selectable t = searchTable(field); return orderBy(new Column(t, field), asc); } /** * ORDER BY句にフィールドを追加します(昇順)<br> * @param table フィールドを保持するテーブル。 * @param field フィールド名 */ public SelectBuilder orderByAsc(Selectable t, String field) { return orderBy(t, field, true); } /** * ORDER BY句にフィールドを追加します(降順)<br> * @param table フィールドを保持するテーブル。 * @param field フィールド名 */ public SelectBuilder orderByDesc(Selectable t, String field) { return orderBy(t, field, false); } /** * ORDER BY句にフィールドを追加します<br> * @param table フィールドを保持するテーブル。 * @param field フィールド名 * @param asc 昇順の場合true */ public SelectBuilder orderBy(Selectable t, String field, boolean asc) { return orderBy(new Column(t, field), asc); } /** * ORDER BY句にフィールド番号を追加します(昇順)<br> * @param colNo SELECT句のフィールド番号 */ public SelectBuilder orderByAsc(int colNo) { return orderBy(colNo, true); } /** * ORDER BY句にフィールド番号を追加します(降順)<br> * @param colNo SELECT句のフィールド番号 */ public SelectBuilder orderByDesc(int colNo) { return orderBy(colNo, false); } /** * ORDER BY句にフィールド番号を追加します<br> * @param colNo SELECT句のフィールド番号 * @param asc 昇順の場合true */ public SelectBuilder orderBy(int colNo, boolean asc) { return orderBy(new Column(null, Integer.toString(colNo)), asc); } /** * ORDER BY句にフィールドを追加します(昇順)<br> * @param sel フィールド */ public SelectBuilder orderByAsc(Select sel) { return orderBy(sel, true); } /** * ORDER BY句にフィールドを追加します(降順)<br> * @param sel フィールド */ public SelectBuilder orderByDesc(Select sel) { return orderBy(sel, false); } /** * ORDER BY句にフィールドを追加します<br> * @param sel フィールド * @param asc 昇順の場合true */ public SelectBuilder orderBy(Select sel, boolean asc) { if (this.orderBy == null) { this.orderBy = new ArrayList<OrderByEntry>(); } this.orderBy.add(new OrderByEntry(sel, asc)); return this; } /** * GROUP BY句にフィールドを追加します<br> * @param sel フィールド */ public SelectBuilder groupBy(String field) { Selectable t = searchTable(field); return groupBy(new Column(t, field)); } /** * GROUP BY句にフィールドを追加します<br> * @param table フィールドを保持するテーブル。 * @param sel フィールド */ public SelectBuilder groupBy(Selectable table, String field) { return groupBy(new Column(table, field)); } /** * GROUP BY句にフィールドを追加します<br> * @param col フィールド */ public SelectBuilder groupBy(Column col) { if (this.groupBy == null) { this.groupBy = new ArrayList<Column>(); } this.groupBy.add(col); return this; } /** * OFFSET句を設定します<br> * @param n Offset。Offsetにパラメータを使用する場合はOFFSET_PARAMを設定してください */ public SelectBuilder offset(int n) { this.offset = n; return this; } /** * LIMIT句を設定します<br> * @param n Limit。Limitにパラメータを使用する場合はLIMIT_PARAMを設定してください */ public SelectBuilder limit(int n) { this.limit = n; return this; } /** * 引数のtableとINNER JOINします * @param table テーブル */ public SelectBuilder innerJoin(Selectable table) { return addJoin(new InnerJoin(table, calcTableAlias())); } /** public SelectBuilder innerJoin(Selectable table, String alias) { return addJoin(new InnerJoin(table, alias)); } */ /** * 引数のtableとLEFT JOINします * @param table テーブル */ public SelectBuilder leftJoin(Selectable table) { return addJoin(new LeftJoin(table, calcTableAlias())); } /* public SelectBuilder leftJoin(Selectable table, String alias) { return addJoin(new LeftJoin(table, alias)); } */ /** * 引数のtableとRIGHT JOINします * @param table テーブル */ public SelectBuilder rightJoin(Selectable table) { return addJoin(new RightJoin(table, calcTableAlias())); } /* public SelectBuilder rightJoin(Selectable table, String alias) { return addJoin(new RightJoin(table, alias)); } */ private SelectBuilder addJoin(Join join) { if (this.joins == null) { this.joins = new ArrayList<Join>(); } this.joins.add(join); return this; } /** * 最後に結合されたJoinを返します。 */ public Join getCurrentJoin() { return joins == null ? null : joins.get(joins.size()-1); } /** * 指定のフィールド名で最後に結合されたJoinのON句を設定します。<br> * フィールド名は新たに結合されたテーブルと既存のテーブルの * 両方に含まれている必要があります。<br> * @param field フィールド名 */ public SelectBuilder on(String field) { return getCurrentJoin().on(field); } /** * 指定のフィールド名で最後に結合されたJoinのON句を設定します。<br> * @param field1 新たに結合されたテーブルのフィールド名 * @param field2 既存のテーブルのフィールド名 */ public SelectBuilder on(String field1, String field2) { return getCurrentJoin().on(field1, field2); } /** * 指定のフィールド名で最後に結合されたJoinのON句を設定します。<br> * @param table1 結合に使用するテーブル1 * @param field1 テーブル1のフィールド名 * @param table2 結合に使用するテーブル2 * @param field2 テーブル2のフィールド名 */ public SelectBuilder on(Selectable table1, String field1, Selectable table2, String field2) { return getCurrentJoin().on(table1, field1, table2, field2); } /** * 指定のフィールド名で最後に結合されたJoinのON句を設定します。<br> * @param table1 結合に使用するテーブル1 * @param field1 テーブル1のフィールド名 * @param table2 結合に使用するテーブル2 * @param field2 テーブル2のフィールド名 * @param op 結合に使用する比較演算子 */ public SelectBuilder on(Selectable table1, String field1, Selectable table2, String field2, ComparisionOp op) { return getCurrentJoin().on(table1, field1, table2, field2, op); } /** * AND条件でWHERE句に条件を追加します。<br> * (andメソッドと処理内容は同じです。) * @param cond 条件 */ public SelectBuilder where(Condition cond) { if (where == null) { where = new Where(cond); } else { where.and(cond); } return this; } /** * AND条件でWHERE句に条件を追加します。<br> * @param cond 条件 */ public SelectBuilder and(Condition cond) { if (where == null) { where = new Where(cond); } else { where.and(cond); } return this; } /** * OR条件でWHERE句に条件を追加します。<br> * @param cond 条件 */ public SelectBuilder or(Condition cond) { if (where == null) { where = new Where(cond); } else { where.or(cond); } return this; } /** * FOR UPDATE を指定します。 */ public SelectBuilder forUpdate() { this.forUpdate = new ForUpdate(false); return this; } /** * FOR UPDATE NOWAIT を指定します。 */ public SelectBuilder forUpdateNoWait() { this.forUpdate = new ForUpdate(true); return this; } /** * テーブル名やフィールド名をクォートする場合そのクォート文字を返します。 */ public char getQuoteChar() { return this.quoteChar;} /** * テーブル名やフィールド名をクォートする場合そのクォート文字を設定します。 */ public void setQuoteChar(char c) { this.quoteChar = c;} /** * SQLを返します。<br> * 設定内容が不正な場合はIllegalArgumentExceptionとなります。 */ public String toSQL() { return toSQL(false); } /** * 改行されたSQLを返します。<br> * 設定内容が不正な場合はIllegalArgumentExceptionとなります。 */ public String toSQL(boolean newLine) { StringBuilder buf = new StringBuilder(); build(buf, newLine); return buf.toString(); } /** * 改行されたSQLを返します。<br> * 設定内容が不正な場合は構築できたところまでのSQL文を返します。 */ @Override public String toString() { StringBuilder buf = new StringBuilder(); try { build(buf, true); return buf.toString(); } catch (Exception e) { e.printStackTrace(); return "Invalid SELECT: " + buf; } } /** * ResultSetの現在の行の内容をMapにコピーします。 */ public Map<String, Object> map(ResultSet rs) throws SQLException { if (this.rsTypes == null) { ResultSetMetaData meta = rs.getMetaData(); if (meta.getColumnCount() < selects.size()) { throw new IllegalArgumentException("Invalid resultSet"); } int[] temp = new int[selects.size()]; for (int i=0; i<selects.size(); i++) { temp[i] = meta.getColumnType(i+1); } this.rsTypes = temp; } Map<String, Object> map = new HashMap<String, Object>(); for (int i=0; i<selects.size(); i++) { Select sel = selects.get(i); int sqlType = rsTypes[i]; Object value = null; switch (sqlType) { case Types.BIGINT: case Types.ROWID: value = rs.getLong(i+1); break; case Types.BLOB: case Types.BINARY: value = rs.getBytes(i+1); break; case Types.BIT: case Types.BOOLEAN: value = rs.getBoolean(i+1); break; case Types.CHAR: case Types.CLOB: case Types.NCHAR: case Types.NCLOB: case Types.NVARCHAR: case Types.SQLXML: case Types.VARCHAR: value = rs.getString(i+1); break; case Types.DATE: value = rs.getDate(i+1); break; case Types.DECIMAL: case Types.NUMERIC: value = rs.getBigDecimal(i+1); break; case Types.DOUBLE: case Types.FLOAT: case Types.REAL: value = rs.getDouble(i+1); break; case Types.INTEGER: case Types.SMALLINT: case Types.TINYINT: value = rs.getInt(i+1); break; case Types.NULL: value = null; break; case Types.TIME: value = rs.getTime(i+1); break; case Types.TIMESTAMP: value = rs.getTimestamp(i+1); break; case Types.OTHER: case Types.REF: case Types.STRUCT: case Types.VARBINARY: break; case Types.ARRAY: case Types.DATALINK: case Types.DISTINCT: case Types.JAVA_OBJECT: case Types.LONGNVARCHAR: case Types.LONGVARBINARY: case Types.LONGVARCHAR: default: throw new IllegalArgumentException("UnsupportedType: " + sqlType); } if (rs.wasNull()) { value = null; } map.put(sel.getFieldName(), value); } return map; } /** * 指定のフィールド名がSELECT句に含まれているかどうかを返します。 */ public boolean hasField(String field) { for (Select sel : this.selects) { if (sel.getFieldName().equals(field)) { return true; } } return false; } SelectBuilder getParent() { return this.parent;} void setParent(SelectBuilder builder) { this.parent = builder;} protected String getAliasPrefix() { return this.aliasPrefix;} void setAliasPrefix(String s) { this.aliasPrefix = s;} Selectable searchTable(String field) { Selectable ret = null; List<Column> checkList = null; if (mainTable.getTable().hasField(field)) { ret = mainTable.getTable(); } if (joins != null) { for (int i=0; i<joins.size(); i++) { TableInfo info = joins.get(i).getTableInfo(); if (info.getTable().hasField(field)) { if (ret == null) { ret = info.getTable(); } else { if (checkList == null) { checkList = new ArrayList<Column>(); checkList.add(new Column(ret, field)); } checkList.add(new Column(info.getTable(), field)); } } } } if (ret == null) { return this.parent != null ? this.parent.searchTable(field) : null; } if (checkList != null) { for (Column col : checkList) { if (!isJoinedColumn(col)) { throw new IllegalArgumentException("Ambiguous reference: " + field); } } } return ret; } List<Condition> getConditions() { if (this.where == null) { return null; } List<Condition> list = new ArrayList<Condition>(); for (WhereEntry entry : where.getList()) { list.add(entry.cond); } return list; } private boolean isJoinedColumn(Column col) { if (joins != null) { for (Join join : joins) { if (join.isJoinedColumn(col)) { return true; } } } return false; } private boolean contains(Selectable t) { if (mainTable.getTable() == t) { return true; } if (joins != null) { for (Join join : joins) { TableInfo info = join.getTableInfo(); if (info.getTable() == t) { return true; } } } return false; } private String getTableAlias(Selectable t) { if (t == mainTable.getTable()) { return mainTable.getAlias(); } if (joins != null) { for (int i=0; i<joins.size(); i++) { TableInfo info = joins.get(i).getTableInfo(); if (info.getTable() == t) { return info.getAlias(); } } } if (parent != null) { return parent.getTableAlias(t); } return null; } /* private Selectable getTable(String alias) { if (alias.equals(mainTable.getAlias())) { return mainTable.getTable(); } if (joins != null) { for (int i=0; i<joins.size(); i++) { TableInfo info = joins.get(i).getTableInfo(); if (alias.equals(info.getAlias())) { return info.getTable(); } } } if (parent != null) { return parent.getTable(alias); } return null; } */ private String calcTableAlias() { int prefixLen = aliasPrefix.length(); char c = 0; String alias = mainTable.getAlias().substring(prefixLen); if (alias.length() == 1) { c = alias.charAt(0); } if (joins != null) { for (Join join : joins) { alias = join.getTableInfo().getAlias().substring(prefixLen); if (alias.length() == 1) { char c2 = alias.charAt(0); if (c2 > c) { c = c2; } } } } return c == 0 ? "A" : "" + (char)(c + 1); } private Selectable getTableByFieldName(String field) { if (mainTable.getTable().hasField(field)) { return mainTable.getTable(); } if (joins != null) { for (Join join : joins) { TableInfo info = join.getTableInfo(); if (info.getTable().hasField(field)) { return info.getTable(); } } } return null; } private void quote(StringBuilder buf, String str) { if (quoteChar == 0) { buf.append(str); } else { buf.append(quoteChar); buf.append(str); buf.append(quoteChar); } } private void build(StringBuilder buf, boolean newLine) { if (selects.size() == 0) { throw new IllegalArgumentException("No select clause"); } boolean bGroup = groupBy != null && groupBy.size() > 0; buf.append("SELECT "); if (distinct) { buf.append("DISTINCT "); } boolean first = true; for (Select sel : selects) { if (first) { first = false; } else { buf.append(", "); } if (newLine) { buf.append("\n "); } sel.build(buf, this); if (sel instanceof Aggregate) { bGroup = true; } } if (newLine) { buf.append("\n"); } else { buf.append(" "); } buf.append("FROM "); mainTable.build(buf); if (joins != null) { for (Join join : joins) { if (newLine) { buf.append("\n"); } else { buf.append(" "); } join.build(buf); } } if (where != null) { where.build(buf, newLine); } if (bGroup) { List<Column> gList = groupBy != null ? groupBy : getGroupByColumn(selects); if (gList.size() > 0) { if (newLine) { buf.append("\n"); } else { buf.append(" "); } buf.append("GROUP BY "); first = true; for (Column col : gList) { if (first) { first = false; } else { buf.append(", "); } if (newLine) { buf.append("\n "); } col.doBuild(buf, this); } } } if (orderBy != null) { if (newLine) { buf.append("\n"); } else { buf.append(" "); } buf.append("ORDER BY "); first = true; for (OrderByEntry entry : orderBy) { if (first) { first = false; } else { buf.append(", "); } if (newLine) { buf.append("\n "); } entry.sel.doBuild(buf, this); if (!entry.asc) { buf.append(" DESC"); } } } if (offset != 0) { if (newLine) { buf.append("\n"); } else { buf.append(" "); } buf.append("OFFSET ").append(offset == OFFSET_PARAM ? "?" : Integer.toString(offset)); } if (limit != 0) { if (newLine) { buf.append("\n"); } else { buf.append(" "); } buf.append("LIMIT ").append(limit == LIMIT_PARAM ? "?" : limit == 0 ? "ALL" : Integer.toString(limit)); } if (forUpdate != null) { buf.append(forUpdate); } } private List<Column> getGroupByColumn(List<Select> list) { List<Column> ret = new ArrayList<Column>(); for (Select sel : list) { if (sel instanceof Column) { ret.add((Column)sel); } } return ret; } /** * SELECT句の抽象クラス */ public static abstract class Select { private String alias; public Select alias(String s) { this.alias = s; return this; } public String alias() { return this.alias;} public Select as(String s) { return alias(s); } public String as() { return alias();} public String getFieldName() { if (this.alias != null) { return this.alias; } return doGetFieldName(); } protected abstract String doGetFieldName(); public final void build(StringBuilder buf, SelectBuilder builder) { doBuild(buf, builder); String a = alias(); if (a != null) { buf.append(" AS "); builder.quote(buf, a); } } protected abstract void doBuild(StringBuilder buf, SelectBuilder builder); } /** * SELECT句で使用する任意のリテラル */ public static class Literal extends Select { private Object literal; public Literal(Object literal) { this.literal = literal; } protected String doGetFieldName() { return literal.toString(); } protected void doBuild(StringBuilder buf, SelectBuilder builder) { buf.append(this.literal); } public static final Literal TRUE = new Literal(true); public static final Literal FALSE = new Literal(false); } /** * SELECT句で使用するフィールド */ public static class Column extends Select { private Selectable table; private String field; public Column(String f) { this(null, f); } public Column(Selectable t, String f) { this.table = t; this.field = f; } protected String doGetFieldName() { return field; } protected void doBuild(StringBuilder buf, SelectBuilder builder) { Selectable t = this.table; String ta = null; if (t == null) { t = builder.searchTable(this.field); } if (t != null) { ta = builder.getTableAlias(t); if (ta == null) { throw new IllegalArgumentException("Unknown table: " + t); } } if (ta != null) { builder.quote(buf, ta); buf.append("."); } builder.quote(buf, field); } public Selectable getTable() { return this.table;} void setTable(Selectable t) { this.table = t;} public String getField() { return this.field;} void setField(String s) { this.field = s;} } /** * 関数 */ public static class Function extends Select { private String functionName; private Object[] args; public Function(String functionName, Object... args) { this.functionName = functionName; this.args = args; } protected String doGetFieldName() { return this.functionName; } protected void doBuild(StringBuilder buf, SelectBuilder builder) { buf.append(this.functionName) .append("("); if (this.args != null) { boolean first = true; for (Object o : args) { if (first) { first = false; } else { buf.append(", "); } appendObject(buf, builder, o); } } buf.append(")"); } } /** * 集合関数 */ public static class Aggregate extends Function { public Aggregate(String functionName, Object... args) { super(functionName, args); } } /** * Case */ public static class Case extends Select { private List<CaseEntry> list = new ArrayList<CaseEntry>(); private Select elseValue; public Case when(Condition cond, Select value) { this.list.add(new CaseEntry(cond, value)); return this; } public Case caseElse(Select value) { elseValue = value; return this; } @Override protected String doGetFieldName() { return "CASE"; } @Override protected void doBuild(StringBuilder buf, SelectBuilder builder) { buf.append("CASE "); for (CaseEntry entry : list) { buf.append("WHEN "); entry.cond.build(buf, builder); buf.append(" THEN "); entry.value.build(buf, builder); } if (elseValue != null) { buf.append(" ELSE "); elseValue.build(buf, builder); } buf.append(" END"); } } /** * JOIN句の抽象クラス */ public abstract class Join { private TableInfo info; private CompoundCondition on = new CompoundCondition(LogicalOp.AND); public Join(Selectable t, String a) { if (a == null) { a = calcTableAlias(); } this.info = new TableInfo(t, a); } public SelectBuilder on(String field) { return on(field, field); } public SelectBuilder on(String field1, String field2) { if (!info.getTable().hasField(field1)) { if (!info.getTable().hasField(field2)) { throw new IllegalArgumentException("Both " + field1 + " and " + field2 + " are not field of " + info.getTable()); } else { return on(field2, field1); } } Selectable table1 = info.getTable(); Selectable table2 = getTableByFieldName(field2); if (table2 == null || table2 == table1) { throw new IllegalArgumentException("Invalid field: " + field2); } return on(table1, field1, table2, field2, ComparisionOp.Equal); } public SelectBuilder on(Selectable table1, String field1, Selectable table2, String field2) { return on(table1, field1, table2, field2, ComparisionOp.Equal); } public SelectBuilder on(Selectable table1, String field1, Selectable table2, String field2, ComparisionOp op) { Column col1 = new Column(table1, field1); Column col2 = new Column(table2, field2); on.add(new Combine(col1, col2, op)); return SelectBuilder.this; } //同一のフィールド名で他のテーブルとJoinしてる場合true public boolean isJoinedColumn(Column col) { for (Condition c : on.getList()) { if (c instanceof Combine) { Combine combi = (Combine)c; if (combi.getOp() == ComparisionOp.Equal && combi.getCol1() instanceof Column && combi.getCol2() instanceof Column) { Column cc1 = (Column)combi.getCol1(); Column cc2 = (Column)combi.getCol2(); if ((cc1.getTable() == col.getTable() || cc2.getTable() == col.getTable()) && cc1.getField().equals(col.getField()) && cc2.getField().equals(col.getField())) { return true; } } } } return false; } public abstract String getJoinString(); public TableInfo getTableInfo() { return this.info; } public void build(StringBuilder buf) { buf.append(getJoinString()).append(" "); info.build(buf); if (on.size() > 0) { buf.append(" ON "); on.build(buf, SelectBuilder.this, false); } } } private class InnerJoin extends Join { public InnerJoin(Selectable t, String a) { super(t, a); } public String getJoinString() { return "INNER JOIN"; } } private class LeftJoin extends Join { public LeftJoin(Selectable t, String a) { super(t, a); } public String getJoinString() { return "LEFT JOIN"; } } private class RightJoin extends Join { public RightJoin(Selectable t, String a) { super(t, a); } public String getJoinString() { return "RIGHT JOIN"; } } private class TableInfo { private Selectable table; private String alias; public TableInfo (Selectable t, String a) { this.table = t; this.alias = a; } public void build(StringBuilder buf) { if (table instanceof Table) { quote(buf, ((Table)table).getTableName()); } else if (table instanceof SelectBuilder) { buf.append("(").append(((SelectBuilder)table).toSQL()).append(")"); } else { throw new IllegalStateException(); } buf.append(" "); quote(buf, getAlias()); } public Selectable getTable() { return this.table;} public String getAlias() { return SelectBuilder.this.aliasPrefix + this.alias;} } private class Where { private List<WhereEntry> list = new ArrayList<WhereEntry>(); public Where(Condition cond) { and(cond); } public List<WhereEntry> getList() { return this.list;} public SelectBuilder and(Condition cond) { return doAdd(cond, LogicalOp.AND); } public SelectBuilder or(Condition cond) { return doAdd(cond, LogicalOp.OR); } private SelectBuilder doAdd(Condition cond, LogicalOp op) { list.add(new WhereEntry(cond, op)); return SelectBuilder.this; } public void build(StringBuilder buf, boolean newLine) { for (int i=0; i<list.size(); i++) { WhereEntry entry = list.get(i); if (newLine) { buf.append("\n"); } else { buf.append(" "); } if (i == 0) { buf.append("WHERE "); } else { buf.append(entry.op).append(" "); } entry.cond.build(buf, SelectBuilder.this); } } } private static class WhereEntry { private Condition cond; private LogicalOp op; public WhereEntry(Condition cond, LogicalOp op) { this.cond = cond; this.op = op; } } private static class OrderByEntry { private Select sel; private boolean asc; public OrderByEntry(Select sel, boolean asc) { this.sel = sel; this.asc = asc; } } public static class CaseEntry { public Condition cond; public Select value; public CaseEntry(Condition cond, Select value) { this.cond = cond; this.value = value; } } private static class ForUpdate { private boolean nowait; public ForUpdate(boolean nowait) { this.nowait = nowait; } public String toString() { String ret = " FOR UPDATE"; if (nowait) { ret += " NOWAIT"; } return ret; } } static void appendObject(StringBuilder buf, SelectBuilder builder, Object value) { if (value instanceof String) { String str = value.toString(); buf.append("'"); for (int i=0; i<str.length(); i++) { char c = str.charAt(i); if (c == '\'') { buf.append("''"); } else { buf.append(c); } } buf.append("'"); } else if (value instanceof Date) { buf.append("'") .append(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format((Date)value)) .append("'"); } else if (value instanceof Select) { ((Select)value).build(buf, builder); } else { buf.append(value); } } }
modify SQLBuilder#limit and offset
src/main/java/jp/co/flect/sql/SelectBuilder.java
modify SQLBuilder#limit and offset
Java
mit
088fa27bd3b5688ad15436856f902f9e0f9a2c70
0
xemime-lang/xemime,xemime-lang/xemime
package net.zero918nobita.Xemime; import java.io.BufferedReader; import java.io.FileReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.TreeMap; /** * エントリーポイント * @author Kodai Matsumoto */ public class Main { private static Parser parser; private static HashMap<X_Symbol, X_Address> globalSymbols = new HashMap<>(); private static TreeMap<X_Address, X_Code> entities = new TreeMap<X_Address, X_Code>() {{ put(new X_Address(0,0), X_Bool.T); }}; static Frame frame = new Frame(); static void loadLocalFrame(HashMap<X_Symbol, X_Address> table) { frame.loadLocalFrame(table); } static void unloadLocalFrame() { frame.unloadLocalFrame(); } static boolean hasSymbol(X_Symbol sym) { return frame.hasSymbol(sym) || globalSymbols.containsKey(sym); } /** * シンボルの参照先アドレスを取得する * @param sym シンボル * @return 参照 */ static X_Address getAddressOfSymbol(X_Symbol sym) { return (frame.hasSymbol(sym)) ? frame.getAddressOfSymbol(sym) : globalSymbols.get(sym); } /** * シンボルの値を取得する * @param sym シンボル * @return 値 */ static X_Code getValueOfSymbol(X_Symbol sym) { if (frame.hasSymbol(sym)) { return frame.getValueOfSymbol(sym, entities); } else { return (globalSymbols.containsKey(sym)) ? globalSymbols.get(sym).fetch(entities) : null; } } /** * 参照先の実体を取得する * @param address アドレス * @return 実体 */ static X_Code getValueOfReference(X_Address address) { return entities.get(address); } /** * シンボルに参照をセットする * @param sym シンボル * @param ref 参照 */ static void setAddress(X_Symbol sym, X_Address ref) throws Exception { if (frame.hasSymbol(sym)) { frame.setAddress(sym, ref); return; } if (!globalSymbols.containsKey(sym)) throw new Exception(parser.getLocation() + ": 変数 `" + sym.getName() + "` は宣言されていません"); globalSymbols.put(sym, ref); } /** * 宣言済みの変数に値をセットします。 * @param sym シンボル * @param obj 値 * @throws Exception 変数が宣言されていなかった場合に例外を発生させます。 */ static void setValue(X_Symbol sym, X_Code obj) throws Exception { if (frame.hasSymbol(sym)) { frame.setValue(sym, obj); return; } X_Address ref = register(obj); if (!globalSymbols.containsKey(sym)) throw new Exception(parser.getLocation() + ": 変数 `" + sym.getName() + "` は宣言されていません"); globalSymbols.put(sym, ref); } /** * 変数を参照で宣言します。 * @param sym 変数 * @param ref 参照 */ static void defAddress(X_Symbol sym, X_Address ref) throws Exception { if (frame.numberOfLayers() != 0) { frame.defAddress(sym, ref); return; } globalSymbols.put(sym, ref); } /** * 変数を値で宣言します。 * @param sym 変数 * @param obj 値 */ static void defValue(X_Symbol sym, X_Code obj) throws Exception { if (frame.numberOfLayers() != 0) { frame.defValue(sym, obj); return; } X_Address ref = register(obj); globalSymbols.put(sym, ref); } static X_Address register(X_Code obj) { entities.put(new X_Address(0,entities.lastKey().getAddress() + 1), obj); return new X_Address(0, entities.lastKey().getAddress()); } public static void main(String[] args) { if (args.length >= 2) { usage(); System.out.println(System.lineSeparator() + "Usage: java -jar Xemime.jar [source file name]"); return; } globalSymbols.put(X_Symbol.intern(0, "Core"), register(new X_Core(0))); globalSymbols.put(X_Symbol.intern(0, "Object"), register(new X_Object(0))); try { parser = new Parser(); BufferedReader in; if (args.length == 0) { usage(); in = new BufferedReader(new InputStreamReader(System.in)); System.out.print(System.lineSeparator() + "[1]> "); String line; while (true) { line = in.readLine(); if (line != null && !line.equals("")) { X_Code obj = parser.parse(line); if (obj == null) break; System.out.println(obj.run().toString()); System.out.print("[" + (obj.getLocation() + 1) + "]> "); parser.goDown(1); } else if (line == null) { break; } } } else { in = new BufferedReader(new FileReader(args[0])); StringBuilder stringBuilder = new StringBuilder(); String line; while ((line = in.readLine()) != null) { stringBuilder.append(line); stringBuilder.append('\n'); } X_Code code = parser.parse("{" + stringBuilder.toString() + "};"); code.run(); } in.close(); } catch(Exception e) { e.printStackTrace(); } } private static void usage() { System.out.println(" _ __ _ \n" + " | |/ /__ ____ ___ (_)___ ___ ___ \n" + " | / _ \\/ __ `__ \\/ / __ `__ \\/ _ \\\n" + " / / __/ / / / / / / / / / / / __/\n" + "/_/|_\\___/_/ /_/ /_/_/_/ /_/ /_/\\___/ \n\n" + "Xemime Version 1.0.0 2017-08-07"); } private static class X_Object extends X_Handler { X_Object(int n) { super(n); setMember(X_Symbol.intern(0, "clone"), new X_Clone()); } private static class X_Clone extends X_Native { X_Clone() { super(0, 0); } @Override protected X_Address exec(ArrayList<X_Code> params) throws Exception { return Main.register(params.get(0).run()); } } } private static class X_Core extends X_Handler { X_Core(int n) { super(n); setMember(X_Symbol.intern(0, "if"), new X_If()); setMember(X_Symbol.intern(0, "print"), new X_Print()); setMember(X_Symbol.intern(0, "println"), new X_Println()); setMember(X_Symbol.intern(0, "exit"), new X_Exit()); } private static class X_Exit extends X_Native { X_Exit() { super(0, 0); } @Override protected X_Code exec(ArrayList<X_Code> params) throws Exception { System.exit(0); return new X_Int(0, 0); } } private static class X_Print extends X_Native { X_Print() { super(0, 1); } @Override protected X_Code exec(ArrayList<X_Code> params) throws Exception { X_Code o = params.get(1).run(); System.out.print(o); return o; } } private static class X_Println extends X_Native { X_Println() { super(0, 1); } @Override protected X_Code exec(ArrayList<X_Code> params) throws Exception { X_Code o = params.get(1).run(); System.out.println(o); return o; } } private static class X_If extends X_Native { X_If(){ super(0, 3); } @Override protected X_Code exec(ArrayList<X_Code> params) throws Exception { return (params.get(1).run().equals(X_Bool.Nil)) ? params.get(3).run() : params.get(2).run(); } } } }
src/main/java/net/zero918nobita/Xemime/Main.java
package net.zero918nobita.Xemime; import java.io.BufferedReader; import java.io.FileReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.TreeMap; /** * エントリーポイント * @author Kodai Matsumoto */ public class Main { private static Parser parser; private static HashMap<X_Symbol, X_Address> globalSymbols = new HashMap<>(); private static TreeMap<X_Address, X_Code> entities = new TreeMap<X_Address, X_Code>() {{ put(new X_Address(0,0), X_Bool.T); }}; static Frame frame = new Frame(); static void loadLocalFrame(HashMap<X_Symbol, X_Address> table) { frame.loadLocalFrame(table); } static void unloadLocalFrame() { frame.unloadLocalFrame(); } static boolean hasSymbol(X_Symbol sym) { return frame.hasSymbol(sym) || globalSymbols.containsKey(sym); } /** * シンボルの参照先アドレスを取得する * @param sym シンボル * @return 参照 */ static X_Address getAddressOfSymbol(X_Symbol sym) { return (frame.hasSymbol(sym)) ? frame.getAddressOfSymbol(sym) : globalSymbols.get(sym); } /** * シンボルの値を取得する * @param sym シンボル * @return 値 */ static X_Code getValueOfSymbol(X_Symbol sym) { if (frame.hasSymbol(sym)) { return frame.getValueOfSymbol(sym, entities); } else { return (globalSymbols.containsKey(sym)) ? globalSymbols.get(sym).fetch(entities) : null; } } /** * 参照先の実体を取得する * @param address アドレス * @return 実体 */ static X_Code getValueOfReference(X_Address address) { return entities.get(address); } /** * シンボルに参照をセットする * @param sym シンボル * @param ref 参照 */ static void setAddress(X_Symbol sym, X_Address ref) throws Exception { if (frame.hasSymbol(sym)) { frame.setAddress(sym, ref); return; } if (!globalSymbols.containsKey(sym)) throw new Exception(parser.getLocation() + ": 変数 `" + sym.getName() + "` は宣言されていません"); globalSymbols.put(sym, ref); } /** * 宣言済みの変数に値をセットします。 * @param sym シンボル * @param obj 値 * @throws Exception 変数が宣言されていなかった場合に例外を発生させます。 */ static void setValue(X_Symbol sym, X_Code obj) throws Exception { if (frame.hasSymbol(sym)) { frame.setValue(sym, obj); return; } X_Address ref = register(obj); if (!globalSymbols.containsKey(sym)) throw new Exception(parser.getLocation() + ": 変数 `" + sym.getName() + "` は宣言されていません"); globalSymbols.put(sym, ref); } /** * 変数を参照で宣言します。 * @param sym 変数 * @param ref 参照 */ static void defAddress(X_Symbol sym, X_Address ref) throws Exception { if (frame.numberOfLayers() != 0) { frame.defAddress(sym, ref); return; } globalSymbols.put(sym, ref); } /** * 変数を値で宣言します。 * @param sym 変数 * @param obj 値 */ static void defValue(X_Symbol sym, X_Code obj) throws Exception { if (frame.numberOfLayers() != 0) { frame.defValue(sym, obj); return; } X_Address ref = register(obj); globalSymbols.put(sym, ref); } static X_Address register(X_Code obj) { entities.put(new X_Address(0,entities.lastKey().getAddress() + 1), obj); return new X_Address(0, entities.lastKey().getAddress()); } public static void main(String[] args) { if (args.length >= 2) { usage(); System.out.println(System.lineSeparator() + "Usage: java -jar Xemime.jar [source file name]"); return; } globalSymbols.put(X_Symbol.intern(0, "Core"), register(new X_Core(0))); globalSymbols.put(X_Symbol.intern(0, "Object"), register(new X_Object(0))); try { parser = new Parser(); BufferedReader in; if (args.length == 0) { usage(); in = new BufferedReader(new InputStreamReader(System.in)); System.out.print(System.lineSeparator() + "[1]> "); String line; while (true) { line = in.readLine(); if (line != null && !line.equals("")) { X_Code obj = parser.parse(line); if (obj == null) break; System.out.println(obj.run().toString()); System.out.print("[" + (obj.getLocation() + 1) + "]> "); parser.goDown(1); } else if (line == null) { break; } } } else { in = new BufferedReader(new FileReader(args[0])); StringBuilder stringBuilder = new StringBuilder(); String line; while ((line = in.readLine()) != null) { stringBuilder.append(line); stringBuilder.append('\n'); } X_Code obj; String[] statements = stringBuilder.toString().split(";", 0); for (String statement : statements) { obj = parser.parse(statement + ";"); if (obj != null) obj.run(); } } in.close(); } catch(Exception e) { e.printStackTrace(); } } private static void usage() { System.out.println(" _ __ _ \n" + " | |/ /__ ____ ___ (_)___ ___ ___ \n" + " | / _ \\/ __ `__ \\/ / __ `__ \\/ _ \\\n" + " / / __/ / / / / / / / / / / / __/\n" + "/_/|_\\___/_/ /_/ /_/_/_/ /_/ /_/\\___/ \n\n" + "Xemime Version 1.0.0 2017-08-07"); } private static class X_Object extends X_Handler { X_Object(int n) { super(n); setMember(X_Symbol.intern(0, "clone"), new X_Clone()); } private static class X_Clone extends X_Native { X_Clone() { super(0, 0); } @Override protected X_Address exec(ArrayList<X_Code> params) throws Exception { return Main.register(params.get(0).run()); } } } private static class X_Core extends X_Handler { X_Core(int n) { super(n); setMember(X_Symbol.intern(0, "if"), new X_If()); setMember(X_Symbol.intern(0, "print"), new X_Print()); setMember(X_Symbol.intern(0, "println"), new X_Println()); setMember(X_Symbol.intern(0, "exit"), new X_Exit()); } private static class X_Exit extends X_Native { X_Exit() { super(0, 0); } @Override protected X_Code exec(ArrayList<X_Code> params) throws Exception { System.exit(0); return new X_Int(0, 0); } } private static class X_Print extends X_Native { X_Print() { super(0, 1); } @Override protected X_Code exec(ArrayList<X_Code> params) throws Exception { X_Code o = params.get(1).run(); System.out.print(o); return o; } } private static class X_Println extends X_Native { X_Println() { super(0, 1); } @Override protected X_Code exec(ArrayList<X_Code> params) throws Exception { X_Code o = params.get(1).run(); System.out.println(o); return o; } } private static class X_If extends X_Native { X_If(){ super(0, 3); } @Override protected X_Code exec(ArrayList<X_Code> params) throws Exception { return (params.get(1).run().equals(X_Bool.Nil)) ? params.get(3).run() : params.get(2).run(); } } } }
Fix the problem where program is not executed properly when it contains block
src/main/java/net/zero918nobita/Xemime/Main.java
Fix the problem where program is not executed properly when it contains block
Java
mit
8fcb89a3e26403cf8996d911a6a0c6198ff5852f
0
spacedog-io/spacedog-server,spacedog-io/spacedog-server,spacedog-io/spacedog-server
package io.spacedog.sdk; import java.util.Iterator; import java.util.List; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import com.google.common.base.Strings; import com.google.common.collect.Lists; import io.spacedog.rest.SpaceRequest; import io.spacedog.sdk.elastic.ESSearchSourceBuilder; import io.spacedog.utils.Exceptions; import io.spacedog.utils.Json7; import io.spacedog.utils.JsonBuilder; import io.spacedog.utils.SpaceFields; import io.spacedog.utils.SpaceParams; public class DataEndpoint implements SpaceFields, SpaceParams { SpaceDog dog; DataEndpoint(SpaceDog session) { this.dog = session; } // // new data object methods // public DataObject<?> object(String type) { return new DataObject<>(dog, type); } public DataObject<?> object(String type, String id) { return new DataObject<>(dog, type, id); } public <K extends DataObject<K>> K object(Class<K> dataClass) { try { K object = dataClass.newInstance(); object.dog = dog; return object; } catch (InstantiationException | IllegalAccessException e) { throw Exceptions.runtime(e); } } public <K extends DataObject<K>> K object(Class<K> dataClass, String id) { K object = object(dataClass); object.id(id); return object; } // // Simple CRUD methods // public ObjectNode get(String type, String id) { return get(type, id, ObjectNode.class); } public <K extends DataObject<K>> K get(Class<K> dataClass, String id) { K object = object(dataClass, id); object.fetch(); return object; } public <K> K get(String type, String id, Class<K> dataClass) { return dog.get("/1/data/{type}/{id}")// .routeParam("type", type)// .routeParam("id", id)// .go(200).toPojo(dataClass); } @SuppressWarnings("unchecked") public <K extends Datable<K>> K reload(K object) { return dog.get("/1/data/{type}/{id}")// .routeParam("type", object.type())// .routeParam("id", object.id())// .go(200).toPojo((Class<K>) object.getClass()); } public String create(String type, Object object) { return dog.post("/1/data/{type}").routeParam("type", type)// .bodyPojo(object).go(201).getString("id"); } public long save(String type, String id, Object object) { return save(type, id, object, true); } public long save(String type, String id, Object object, boolean strict) { return dog.put("/1/data/{type}/{id}").routeParam("id", id)// .routeParam("type", type).queryParam("strict", String.valueOf(strict))// .bodyPojo(object).go(200, 201).get("version").asLong(); } public <K extends Datable<K>> K save(K object) { SpaceRequest request = object.id() == null // ? dog.post("/1/data/{type}")// : dog.put("/1/data/{type}/{id}").routeParam("id", object.id()); ObjectNode result = request.routeParam("type", object.type())// .bodyPojo(object).go(200, 201).asJsonObject(); object.id(result.get("id").asText()); object.version(result.get("version").asLong()); return object; } public void delete(String type, String id) { delete(type, id, true); } public void delete(String type, String id, boolean throwNotFound) { SpaceRequest request = dog.delete("/1/data/{type}/{id}")// .routeParam("type", type)// .routeParam("id", id); if (throwNotFound) request.go(200); else request.go(200, 404); } public void delete(Datable<?> object) { delete(object.type(), object.id()); } // // Get/Delete All methods // public GetAllRequest getAll() { return new GetAllRequest(); } public class GetAllRequest { private String type; private Integer from; private Integer size; private Boolean refresh; public GetAllRequest type(String type) { this.type = type; return this; } public GetAllRequest from(int from) { this.from = from; return this; } public GetAllRequest size(int size) { this.size = size; return this; } public GetAllRequest refresh() { this.refresh = true; return this; } @SuppressWarnings("rawtypes") public List<DataObject> get() { return get(DataObject.class); } // TODO how to return objects in the right pojo form? // add registerPojoType(String type, Class<K extends DataObject> clazz) // methods?? // TODO rename this method with get public <K> List<K> get(Class<K> dataClass) { SpaceRequest request = type == null // ? dog.get("/1/data") // : dog.get("/1/data/{type}").routeParam("type", type); if (refresh != null) request.queryParam(PARAM_REFRESH, Boolean.toString(refresh)); if (from != null) request.queryParam(PARAM_FROM, Integer.toString(from)); if (size != null) request.queryParam(PARAM_SIZE, Integer.toString(size)); ObjectNode result = request.go(200).asJsonObject(); return toList(result, dataClass); } } public DataEndpoint deleteAll(String type) { dog.delete("/1/data/{type}").routeParam("type", type).go(200); return this; } // // Search // public <K> SearchResults<K> search(ESSearchSourceBuilder builder, Class<K> dataClass) { return search(null, builder, dataClass, false); } public <K> SearchResults<K> search(String type, ESSearchSourceBuilder builder, Class<K> dataClass) { return search(type, builder, dataClass, false); } public <K> SearchResults<K> search(String type, ESSearchSourceBuilder builder, Class<K> dataClass, boolean refresh) { String path = "/1/search"; if (!Strings.isNullOrEmpty(type)) path = path + "/" + type; ObjectNode results = dog.post(path)// .queryParam(PARAM_REFRESH, Boolean.toString(refresh))// .bodyJson(builder.toString()).go(200).asJsonObject(); return new SearchResults<>(results, dataClass); } public class SearchResults<K> { private long total; private List<K> objects; public SearchResults(ObjectNode results, Class<K> dataClass) { this.total = results.get("total").asLong(); this.objects = toList((ArrayNode) results.get("results"), dataClass); } public long total() { return total; } public List<K> objects() { return objects; } } // // Old search methods // @Deprecated public static class SimpleQuery { public int from = 0; public int size = 10; public boolean refresh = false; public String query; public String type; } @Deprecated public <K> List<K> search(SimpleQuery query, Class<K> dataClass) { ObjectNode result = SpaceRequest.get("/1/search/{type}")// .auth(dog)// .routeParam("type", query.type)// .queryParam(PARAM_REFRESH, Boolean.toString(query.refresh))// .queryParam(PARAM_FROM, Integer.toString(query.from))// .queryParam(PARAM_SIZE, Integer.toString(query.size))// .queryParam(PARAM_Q, query.query)// .go(200).asJsonObject(); return toList(result, dataClass); } @Deprecated public static class ComplexQuery { public boolean refresh = false; public ObjectNode query; public String type; } @Deprecated public <K> SearchResults<K> search(ComplexQuery query, Class<K> dataClass) { ObjectNode results = dog.post("/1/search/{type}")// .routeParam("type", query.type)// .queryParam(PARAM_REFRESH, Boolean.toString(query.refresh))// .bodyJson(query.query).go(200).asJsonObject(); return new SearchResults<>(results, dataClass); } @Deprecated public static class TermQuery { public int from = 0; public int size = 10; public boolean refresh = false; public List<Object> terms; public String type; public String sort; public boolean ascendant = true; } @Deprecated public <K> SearchResults<K> search(TermQuery query, Class<K> dataClass) { JsonBuilder<ObjectNode> builder = Json7.objectBuilder()// .put("size", query.size)// .put("from", query.from)// .object("query")// .object("bool")// .array("filter"); for (int i = 0; i < query.terms.size(); i = i + 2) { Object field = query.terms.get(i); Object value = query.terms.get(i + 1); if (value instanceof String) builder.object().object("term"); else if (value instanceof List) builder.object().object("terms"); else throw Exceptions.illegalArgument("term value [%s] is invalid", value); builder.node(field.toString(), Json7.toNode(value))// .end().end(); } builder.end().end().end(); if (query.sort != null) builder.array("sort")// .object()// .object(query.sort)// .put("order", query.ascendant ? "asc" : "desc")// .end()// .end()// .end(); ComplexQuery complex = new ComplexQuery(); complex.refresh = query.refresh; complex.type = query.type; complex.query = builder.build(); return search(complex, dataClass); } // // Implementation // private <K> List<K> toList(ObjectNode resultNode, Class<K> dataClass) { return toList((ArrayNode) resultNode.get("results"), dataClass); } private <K> List<K> toList(ArrayNode arrayNode, Class<K> dataClass) { List<K> results = Lists.newArrayList(); Iterator<JsonNode> elements = arrayNode.elements(); while (elements.hasNext()) { try { JsonNode node = elements.next(); K object = Json7.mapper().treeToValue(node, dataClass); results.add(object); if (object instanceof DataObject<?>) enhance((DataObject<?>) object, (ObjectNode) node); } catch (JsonProcessingException e) { throw Exceptions.runtime(e); } } return results; } private void enhance(DataObject<?> dataObject, ObjectNode node) { dataObject.session(dog); dataObject.node(node); } }
sdk/src/main/java/io/spacedog/sdk/DataEndpoint.java
package io.spacedog.sdk; import java.util.Iterator; import java.util.List; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import com.google.common.base.Strings; import com.google.common.collect.Lists; import io.spacedog.rest.SpaceRequest; import io.spacedog.sdk.elastic.ESSearchSourceBuilder; import io.spacedog.utils.Exceptions; import io.spacedog.utils.Json7; import io.spacedog.utils.JsonBuilder; import io.spacedog.utils.SpaceFields; import io.spacedog.utils.SpaceParams; public class DataEndpoint implements SpaceFields, SpaceParams { SpaceDog dog; DataEndpoint(SpaceDog session) { this.dog = session; } // // new data object methods // public DataObject<?> object(String type) { return new DataObject<>(dog, type); } public DataObject<?> object(String type, String id) { return new DataObject<>(dog, type, id); } public <K extends DataObject<K>> K object(Class<K> dataClass) { try { K object = dataClass.newInstance(); object.dog = dog; return object; } catch (InstantiationException | IllegalAccessException e) { throw Exceptions.runtime(e); } } public <K extends DataObject<K>> K object(Class<K> dataClass, String id) { K object = object(dataClass); object.id(id); return object; } // // Simple CRUD methods // public ObjectNode get(String type, String id) { return get(type, id, ObjectNode.class); } public <K extends DataObject<K>> K get(Class<K> dataClass, String id) { K object = object(dataClass, id); object.fetch(); return object; } public <K> K get(String type, String id, Class<K> dataClass) { return dog.get("/1/data/{type}/{id}")// .routeParam("type", type)// .routeParam("id", id)// .go(200).toPojo(dataClass); } @SuppressWarnings("unchecked") public <K extends Datable<K>> K reload(K object) { return dog.get("/1/data/{type}/{id}")// .routeParam("type", object.type())// .routeParam("id", object.id())// .go(200).toPojo((Class<K>) object.getClass()); } public String create(String type, Object object) { return dog.post("/1/data/{type}").routeParam("type", type)// .bodyPojo(object).go(201).getString("id"); } public long save(String type, String id, Object object) { return save(type, id, object, true); } public long save(String type, String id, Object object, boolean strict) { return dog.put("/1/data/{type}/{id}").routeParam("id", id)// .routeParam("type", type).queryParam("strict", String.valueOf(strict))// .bodyPojo(object).go(200, 201).get("version").asLong(); } public <K extends Datable<K>> K save(K object) { SpaceRequest request = object.id() == null // ? dog.post("/1/data/{type}")// : dog.put("/1/data/{type}/{id}").routeParam("id", object.id()); ObjectNode result = request.routeParam("type", object.type())// .bodyPojo(object).go(200, 201).asJsonObject(); object.id(result.get("id").asText()); object.version(result.get("version").asLong()); return object; } public void delete(String type, String id) { dog.delete("/1/data/{type}/{id}")// .routeParam("type", type)// .routeParam("id", id)// .go(200); } public void delete(Datable<?> object) { delete(object.type(), object.id()); } // // Get/Delete All methods // public GetAllRequest getAll() { return new GetAllRequest(); } public class GetAllRequest { private String type; private Integer from; private Integer size; private Boolean refresh; public GetAllRequest type(String type) { this.type = type; return this; } public GetAllRequest from(int from) { this.from = from; return this; } public GetAllRequest size(int size) { this.size = size; return this; } public GetAllRequest refresh() { this.refresh = true; return this; } @SuppressWarnings("rawtypes") public List<DataObject> get() { return get(DataObject.class); } // TODO how to return objects in the right pojo form? // add registerPojoType(String type, Class<K extends DataObject> clazz) // methods?? // TODO rename this method with get public <K> List<K> get(Class<K> dataClass) { SpaceRequest request = type == null // ? dog.get("/1/data") // : dog.get("/1/data/{type}").routeParam("type", type); if (refresh != null) request.queryParam(PARAM_REFRESH, Boolean.toString(refresh)); if (from != null) request.queryParam(PARAM_FROM, Integer.toString(from)); if (size != null) request.queryParam(PARAM_SIZE, Integer.toString(size)); ObjectNode result = request.go(200).asJsonObject(); return toList(result, dataClass); } } public DataEndpoint deleteAll(String type) { dog.delete("/1/data/{type}").routeParam("type", type).go(200); return this; } // // Search // public <K> SearchResults<K> search(ESSearchSourceBuilder builder, Class<K> dataClass) { return search(null, builder, dataClass, false); } public <K> SearchResults<K> search(String type, ESSearchSourceBuilder builder, Class<K> dataClass) { return search(type, builder, dataClass, false); } public <K> SearchResults<K> search(String type, ESSearchSourceBuilder builder, Class<K> dataClass, boolean refresh) { String path = "/1/search"; if (!Strings.isNullOrEmpty(type)) path = path + "/" + type; ObjectNode results = dog.post(path)// .queryParam(PARAM_REFRESH, Boolean.toString(refresh))// .bodyJson(builder.toString()).go(200).asJsonObject(); return new SearchResults<>(results, dataClass); } public class SearchResults<K> { private long total; private List<K> objects; public SearchResults(ObjectNode results, Class<K> dataClass) { this.total = results.get("total").asLong(); this.objects = toList((ArrayNode) results.get("results"), dataClass); } public long total() { return total; } public List<K> objects() { return objects; } } // // Old search methods // @Deprecated public static class SimpleQuery { public int from = 0; public int size = 10; public boolean refresh = false; public String query; public String type; } @Deprecated public <K> List<K> search(SimpleQuery query, Class<K> dataClass) { ObjectNode result = SpaceRequest.get("/1/search/{type}")// .auth(dog)// .routeParam("type", query.type)// .queryParam(PARAM_REFRESH, Boolean.toString(query.refresh))// .queryParam(PARAM_FROM, Integer.toString(query.from))// .queryParam(PARAM_SIZE, Integer.toString(query.size))// .queryParam(PARAM_Q, query.query)// .go(200).asJsonObject(); return toList(result, dataClass); } @Deprecated public static class ComplexQuery { public boolean refresh = false; public ObjectNode query; public String type; } @Deprecated public <K> SearchResults<K> search(ComplexQuery query, Class<K> dataClass) { ObjectNode results = dog.post("/1/search/{type}")// .routeParam("type", query.type)// .queryParam(PARAM_REFRESH, Boolean.toString(query.refresh))// .bodyJson(query.query).go(200).asJsonObject(); return new SearchResults<>(results, dataClass); } @Deprecated public static class TermQuery { public int from = 0; public int size = 10; public boolean refresh = false; public List<Object> terms; public String type; public String sort; public boolean ascendant = true; } @Deprecated public <K> SearchResults<K> search(TermQuery query, Class<K> dataClass) { JsonBuilder<ObjectNode> builder = Json7.objectBuilder()// .put("size", query.size)// .put("from", query.from)// .object("query")// .object("bool")// .array("filter"); for (int i = 0; i < query.terms.size(); i = i + 2) { Object field = query.terms.get(i); Object value = query.terms.get(i + 1); if (value instanceof String) builder.object().object("term"); else if (value instanceof List) builder.object().object("terms"); else throw Exceptions.illegalArgument("term value [%s] is invalid", value); builder.node(field.toString(), Json7.toNode(value))// .end().end(); } builder.end().end().end(); if (query.sort != null) builder.array("sort")// .object()// .object(query.sort)// .put("order", query.ascendant ? "asc" : "desc")// .end()// .end()// .end(); ComplexQuery complex = new ComplexQuery(); complex.refresh = query.refresh; complex.type = query.type; complex.query = builder.build(); return search(complex, dataClass); } // // Implementation // private <K> List<K> toList(ObjectNode resultNode, Class<K> dataClass) { return toList((ArrayNode) resultNode.get("results"), dataClass); } private <K> List<K> toList(ArrayNode arrayNode, Class<K> dataClass) { List<K> results = Lists.newArrayList(); Iterator<JsonNode> elements = arrayNode.elements(); while (elements.hasNext()) { try { JsonNode node = elements.next(); K object = Json7.mapper().treeToValue(node, dataClass); results.add(object); if (object instanceof DataObject<?>) enhance((DataObject<?>) object, (ObjectNode) node); } catch (JsonProcessingException e) { throw Exceptions.runtime(e); } } return results; } private void enhance(DataObject<?> dataObject, ObjectNode node) { dataObject.session(dog); dataObject.node(node); } }
Adds DataEndpoint.delete(String, String, boolean)
sdk/src/main/java/io/spacedog/sdk/DataEndpoint.java
Adds DataEndpoint.delete(String, String, boolean)
Java
mit
f1860591d2773142ffe6816287233f17981e29cf
0
usmansaleem/vert.x.blog,usmansaleem/vert.x.blog,usmansaleem/vert.x.blog
package info.usmans.blog.vertx; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import info.usmans.blog.model.BlogItem; import io.vertx.core.AbstractVerticle; import io.vertx.core.buffer.Buffer; import io.vertx.core.http.HttpClient; import io.vertx.core.http.HttpClientOptions; import io.vertx.core.http.HttpServerResponse; import io.vertx.ext.web.Router; import io.vertx.ext.web.RoutingContext; import io.vertx.ext.web.handler.BodyHandler; import io.vertx.ext.web.handler.StaticHandler; import java.util.ArrayList; import java.util.List; /** * Sets up vert.x routes and start the server. * * @author Usman Saleem */ public class ServerVerticle extends AbstractVerticle { public static final int ITEMS_PER_PAGE = 10; private List<BlogItem> blogItems; private Gson gson = new Gson(); private int totalPages; private int itemsOnLastPage; private HttpClient client; @Override public void start() { HttpClientOptions options = new HttpClientOptions().setDefaultHost("raw.githubusercontent.com") .setDefaultPort(443).setSsl(true).setLogActivity(true); client = vertx.createHttpClient(options); client.getNow("/usmansaleem/vert.x.blog/master/src/main/resources/data.json", response -> response.bodyHandler(totalBuffer -> { if (response.statusCode() == 200) { updateData(totalBuffer); Router router = createRoutes(); vertx.createHttpServer().requestHandler(router::accept). listen(Integer.getInteger("http.port"), System.getProperty("http.address")); } else { throw new RuntimeException("Invalid Status code while reading data." + response.statusCode() + ", " + totalBuffer.toString()); } })); } private Router createRoutes() { Router router = Router.router(vertx); router.route().handler(BodyHandler.create()); router.get("/rest/blog/refresh").handler(this::refreshData); router.get("/rest/blog/highestPage").handler(this::handleGetHighestPage); router.get("/rest/blog/listCategories").handler(this::handleGetListCategories); router.get("/rest/blog/blogCount").handler(this::handleGetBlogCount); router.get("/rest/blog/blogItems/:pageNumber").handler(this::handleGetBlogItemsMainCategoryByPageNumber); router.route("/*").handler(StaticHandler.create()); return router; } private void refreshData(RoutingContext routingContext) { client.getNow("/usmansaleem/vert.x.blog/master/src/main/resources/data.json", response -> response.bodyHandler(totalBuffer -> { if (response.statusCode() == 200) { updateData(totalBuffer); routingContext.response().putHeader("content-type", "text/plain").end("Refreshed!"); } else { routingContext.response().putHeader("content-type", "text/plain").end("Unable to refresh"); } })); } private void updateData(Buffer totalBuffer) { blogItems = gson.fromJson(totalBuffer.toString(), new TypeToken<ArrayList<BlogItem>>() { }.getType()); totalPages = blogItems.size() / ITEMS_PER_PAGE; itemsOnLastPage = blogItems.size() % ITEMS_PER_PAGE; if (itemsOnLastPage != 0) { totalPages++; } } private void handleGetHighestPage(RoutingContext routingContext) { routingContext.response().putHeader("content-type", "text/plain").end(String.valueOf(totalPages)); } private void handleGetListCategories(RoutingContext routingContext) { routingContext.response().putHeader("content-type", "application/json").end("[{\"id\":1,\"name\":\"Java\"},{\"id\":2,\"name\":\"PostgreSQL\"},{\"id\":3,\"name\":\"Linux\"},{\"id\":4,\"name\":\"IT\"},{\"id\":5,\"name\":\"General\"},{\"id\":6,\"name\":\"JBoss\"}]"); } private void handleGetBlogCount(RoutingContext routingContext) { routingContext.response().putHeader("content-type", "text/plain").end(String.valueOf(blogItems.size())); } private void handleGetBlogItemsMainCategoryByPageNumber(RoutingContext routingContext) { String pageNumberParam = routingContext.request().getParam("pageNumber"); HttpServerResponse response = routingContext.response(); if (pageNumberParam == null) { sendBadRequestError(response, "Bad Request - Invalid Page Number"); } else { try { int pageNumber = Integer.parseInt(pageNumberParam); if (pageNumber >= 1 && pageNumber <= totalPages) { int endIdx = pageNumber * ITEMS_PER_PAGE; int startIdx = endIdx - ITEMS_PER_PAGE; if (pageNumber == this.totalPages && itemsOnLastPage != 0) { endIdx = startIdx + itemsOnLastPage; } response.putHeader("content-type", "application/json").end(gson.toJson(blogItems.subList(startIdx, endIdx))); } else { sendBadRequestError(response, "Bad Request - Invalid Page Number"); } } catch (NumberFormatException e) { sendBadRequestError(response, "Bad Request - Invalid Page Number"); } } } private void sendBadRequestError(HttpServerResponse response, String message) { response.setStatusCode(400).end(message); } }
src/main/java/info/usmans/blog/vertx/ServerVerticle.java
package info.usmans.blog.vertx; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import info.usmans.blog.model.BlogItem; import io.vertx.core.AbstractVerticle; import io.vertx.core.buffer.Buffer; import io.vertx.core.http.HttpClient; import io.vertx.core.http.HttpClientOptions; import io.vertx.core.http.HttpServerResponse; import io.vertx.ext.web.Router; import io.vertx.ext.web.RoutingContext; import io.vertx.ext.web.handler.BodyHandler; import io.vertx.ext.web.handler.StaticHandler; import java.util.ArrayList; import java.util.List; /** * Sets up vert.x routes and start the server. * * @author Usman Saleem */ public class ServerVerticle extends AbstractVerticle { public static final int ITEMS_PER_PAGE = 10; private List<BlogItem> blogItems; private Gson gson = new Gson(); private int totalPages; private int itemsOnLastPage; private HttpClient client; @Override public void start() { HttpClientOptions options = new HttpClientOptions().setDefaultHost("raw.githubusercontent.com") .setDefaultPort(443).setSsl(true).setLogActivity(true); client = vertx.createHttpClient(options); client.getNow("/usmansaleem/vert.x.blog/master/src/main/resources/data.json", response -> response.bodyHandler(totalBuffer -> { if (response.statusCode() == 200) { updateData(totalBuffer); Router router = createRoutes(); vertx.createHttpServer().requestHandler(router::accept). listen(Integer.getInteger("http.port"), System.getProperty("http.address")); } else { throw new RuntimeException("Invalid Status code while reading data." + response.statusCode() + ", " + totalBuffer.toString()); } })); } private Router createRoutes() { Router router = Router.router(vertx); router.route().handler(BodyHandler.create()); router.get("/rest/blog/refresh").handler(this::refreshData); router.get("/rest/blog/highestPage").handler(this::handleGetHighestPage); router.get("/rest/blog/listCategories").handler(this::handleGetListCategories); router.get("/rest/blog/blogCount").handler(this::handleGetBlogCount); router.get("/rest/blog/blogItems/:pageNumber").handler(this::handleGetBlogItemsMainCategoryByPageNumber); router.route("/*").handler(StaticHandler.create()); return router; } private void refreshData(RoutingContext ignore) { client.getNow("/usmansaleem/vert.x.blog/master/src/main/resources/data.json", response -> response.bodyHandler(totalBuffer -> { if (response.statusCode() == 200) { updateData(totalBuffer); } })); } private void updateData(Buffer totalBuffer) { blogItems = gson.fromJson(totalBuffer.toString(), new TypeToken<ArrayList<BlogItem>>() { }.getType()); totalPages = blogItems.size() / ITEMS_PER_PAGE; itemsOnLastPage = blogItems.size() % ITEMS_PER_PAGE; if (itemsOnLastPage != 0) { totalPages++; } } private void handleGetHighestPage(RoutingContext routingContext) { routingContext.response().putHeader("content-type", "text/plain").end(String.valueOf(totalPages)); } private void handleGetListCategories(RoutingContext routingContext) { routingContext.response().putHeader("content-type", "application/json").end("[{\"id\":1,\"name\":\"Java\"},{\"id\":2,\"name\":\"PostgreSQL\"},{\"id\":3,\"name\":\"Linux\"},{\"id\":4,\"name\":\"IT\"},{\"id\":5,\"name\":\"General\"},{\"id\":6,\"name\":\"JBoss\"}]"); } private void handleGetBlogCount(RoutingContext routingContext) { routingContext.response().putHeader("content-type", "text/plain").end(String.valueOf(blogItems.size())); } private void handleGetBlogItemsMainCategoryByPageNumber(RoutingContext routingContext) { String pageNumberParam = routingContext.request().getParam("pageNumber"); HttpServerResponse response = routingContext.response(); if (pageNumberParam == null) { sendBadRequestError(response, "Bad Request - Invalid Page Number"); } else { try { int pageNumber = Integer.parseInt(pageNumberParam); if (pageNumber >= 1 && pageNumber <= totalPages) { int endIdx = pageNumber * ITEMS_PER_PAGE; int startIdx = endIdx - ITEMS_PER_PAGE; if (pageNumber == this.totalPages && itemsOnLastPage != 0) { endIdx = startIdx + itemsOnLastPage; } response.putHeader("content-type", "application/json").end(gson.toJson(blogItems.subList(startIdx, endIdx))); } else { sendBadRequestError(response, "Bad Request - Invalid Page Number"); } } catch (NumberFormatException e) { sendBadRequestError(response, "Bad Request - Invalid Page Number"); } } } private void sendBadRequestError(HttpServerResponse response, String message) { response.setStatusCode(400).end(message); } }
Send information that we are successfully refreshed or not.
src/main/java/info/usmans/blog/vertx/ServerVerticle.java
Send information that we are successfully refreshed or not.
Java
mit
25f390adf0114a4a708d56eca6e1992d9bd368ba
0
TrinityTrihawks/2017
package main.java.org.usfirst.frc.team4215.robot; import edu.wpi.first.wpilibj.DigitalInput; import edu.wpi.cscore.AxisCamera; import edu.wpi.cscore.CvSink; import edu.wpi.cscore.CvSource; import edu.wpi.first.wpilibj.CameraServer; import java.util.ArrayList; import edu.wpi.first.wpilibj.IterativeRobot; import edu.wpi.first.wpilibj.Joystick; import main.java.org.usfirst.frc.team4215.robot.steamworks.VisionTest; import edu.wpi.first.wpilibj.smartdashboard.SendableChooser; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import edu.wpi.first.wpilibj.vision.VisionThread; import jaci.pathfinder.Trajectory; import jaci.pathfinder.modifiers.TankModifier; import main.java.org.usfirst.frc.team4215.robot.Arm; import main.java.org.usfirst.frc.team4215.robot.CameraInit; import main.java.org.usfirst.frc.team4215.robot.Drivetrain; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj.Talon; import edu.wpi.first.wpilibj.buttons.Button; import edu.wpi.first.wpilibj.networktables.NetworkTable; import edu.wpi.first.wpilibj.Joystick.AxisType; import com.ctre.CANTalon.FeedbackDevice; import com.ctre.CANTalon.TalonControlMode; import com.ctre.CANTalon; import edu.wpi.first.wpilibj.GenericHID; import edu.wpi.first.wpilibj.IterativeRobot; import edu.wpi.first.wpilibj.Joystick; import main.java.org.usfirst.frc.team4215.robot.WinchTest; import org.opencv.core.Mat; import org.opencv.core.Point; import org.opencv.core.Rect; import org.opencv.core.Scalar; import org.opencv.imgproc.Imgproc; import main.java.prototypes.UltrasonicHub; import com.ctre.CANTalon; /** * The VM is configured to automatically run this class, and to call the * functions corresponding to each mode, as described in the IterativeRobot * documentation. If you change the name of this class or the package after * creating this project, you must also update the manifest file in the resource * directory. */ public class Robot extends IterativeRobot { Arm arm; Joystick leftStick = new Joystick(0); Joystick drivestick = new Joystick(1); Drivetrain drivetrain; WinchTest winch; Thread visionThread; CameraInit cam; UltrasonicHub hub; // ID's int DRIVE_LEFT_JOYSTICK_ID = 3; int DRIVE_RIGHT_JOYSTICK_ID = 1; int STRAFE_ID = 8; int WINCH_ID = 1; int ARM_ID = 4; int STRAFE_DRIVE_ID = 0; int DRIVE_LEFT_TOP_TRIGGER = 5; int DRIVE_LEFT_BOTTOM_TRIGGER = 7; int IMG_WIDTH = 640; int IMG_HEIGHT = 480; AxisCamera cameraBack = CameraServer.getInstance().addAxisCamera("Back", "10.42.15.37"); //AxisCamera cameraFront = CameraServer.getInstance().addAxisCamera("Back", "10.42.15.39"); private double centerX = 0.0; //Creates the variable centerX. private final Object imgLock = new Object(); public void robotInit(){ arm = new Arm(); leftStick = new Joystick(0); drivetrain = Drivetrain.Create(); winch = new WinchTest(); cameraBack = CameraServer.getInstance().addAxisCamera("Back", "10.42.15.37"); cameraBack.setResolution(IMG_WIDTH, IMG_HEIGHT); visionThread = new VisionThread(cameraBack, new Pipeline(), pipeline -> { if (!pipeline.filterContoursOutput().isEmpty()) { Rect r = Imgproc.boundingRect(pipeline.filterContoursOutput().get(0)); synchronized (imgLock) { centerX = r.x + (r.width / 2); //System.out.println(centerX); //if the code is actually working, //System.out.println("Current Center X variable"); //a number should be displayed } } else { System.out.println("No Contours"); } }); visionThread.setDaemon(true); visionThread.start(); System.out.println("Hello World"); //double turnTest = centerX - (IMG_WIDTH/2); //System.out.println("Turn Test"); //System.out.println(turnTest); hub = new UltrasonicHub(); ArrayList<String> devices; hub.addReader("/dev/ttyUSB1"); } public void teleopInit(){ //drivetrain.disableControl(); drivetrain.setTalonControlMode(TalonControlMode.PercentVbus); } public void teleopPeriodic(){ ArrayList<Integer> distances = hub.getDistancefromallPorts(); for (int i=0; i<distances.size(); i++) { System.out.print("d: " + distances.get(i) + "\t"); } System.out.println("\n"); double left = -drivestick.getRawAxis(DRIVE_LEFT_JOYSTICK_ID); double right = -drivestick.getRawAxis(DRIVE_RIGHT_JOYSTICK_ID); double strafe = drivestick.getRawAxis(STRAFE_DRIVE_ID); boolean isStrafing = drivestick.getRawButton(STRAFE_ID); Drivetrain.MotorGranular mode = Drivetrain.MotorGranular.NORMAL; if(drivestick.getRawButton(DRIVE_LEFT_BOTTOM_TRIGGER) && !drivestick.getRawButton(DRIVE_LEFT_TOP_TRIGGER)){ mode = Drivetrain.MotorGranular.FAST; } else if(!drivestick.getRawButton(DRIVE_LEFT_BOTTOM_TRIGGER) && drivestick.getRawButton(DRIVE_LEFT_TOP_TRIGGER)){ mode = Drivetrain.MotorGranular.SLOW; } drivetrain.drive(left, right, strafe,isStrafing,mode); if(leftStick.getRawButton(1)){ arm.armCompress(); } if(leftStick.getRawButton(2)){ arm.armDecompress(); } if(!leftStick.getRawButton(1)&&!leftStick.getRawButton(2)){ arm.armOff(); } arm.setArm(leftStick.getRawAxis(1)); double l = leftStick.getRawAxis(4); winch.set(l); } /** public void autonomousPeriodic(){ double centerX; synchronized (imgLock) { centerX = this.centerX; } double turn = centerX - (IMG_WIDTH / 2); double left = 0; double right = 0; double strafe = turn; boolean IsStrafing = true; Drivetrain.MotorGranular mode = Drivetrain.MotorGranular.SLOW; //drivetrain.drive(left, right, strafe, IsStrafing, mode); } **/ /**public void autonomousInit() { drivetrain.setTalonControlMode(TalonControlMode.Position); drivetrain.resetEncoder(); drivetrain.setPID(.05, 0, 0); drivetrain.enableControl(); drivetrain.Go(24, 24, 24, 24); drivetrain.setPID(.1, 0, 0); } double[] dist = new double[4]; **/ }
src/main/java/org/usfirst/frc/team4215/robot/Robot.java
package main.java.org.usfirst.frc.team4215.robot; import edu.wpi.first.wpilibj.DigitalInput; import edu.wpi.cscore.AxisCamera; import edu.wpi.cscore.CvSink; import edu.wpi.cscore.CvSource; import edu.wpi.first.wpilibj.CameraServer; import java.util.ArrayList; import edu.wpi.first.wpilibj.IterativeRobot; import edu.wpi.first.wpilibj.Joystick; import main.java.org.usfirst.frc.team4215.robot.steamworks.VisionTest; import edu.wpi.first.wpilibj.smartdashboard.SendableChooser; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import edu.wpi.first.wpilibj.vision.VisionThread; import jaci.pathfinder.Trajectory; import jaci.pathfinder.modifiers.TankModifier; import main.java.org.usfirst.frc.team4215.robot.Arm; import main.java.org.usfirst.frc.team4215.robot.CameraInit; import main.java.org.usfirst.frc.team4215.robot.Drivetrain; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj.Talon; import edu.wpi.first.wpilibj.buttons.Button; import edu.wpi.first.wpilibj.networktables.NetworkTable; import edu.wpi.first.wpilibj.Joystick.AxisType; import com.ctre.CANTalon.FeedbackDevice; import com.ctre.CANTalon.TalonControlMode; import com.ctre.CANTalon; import edu.wpi.first.wpilibj.GenericHID; import edu.wpi.first.wpilibj.IterativeRobot; import edu.wpi.first.wpilibj.Joystick; import main.java.org.usfirst.frc.team4215.robot.WinchTest; import org.opencv.core.Mat; import org.opencv.core.Point; import org.opencv.core.Rect; import org.opencv.core.Scalar; import org.opencv.imgproc.Imgproc; import main.java.prototypes.UltrasonicHub; import com.ctre.CANTalon; /** * The VM is configured to automatically run this class, and to call the * functions corresponding to each mode, as described in the IterativeRobot * documentation. If you change the name of this class or the package after * creating this project, you must also update the manifest file in the resource * directory. */ public class Robot extends IterativeRobot { Arm arm; Joystick leftStick = new Joystick(0); Joystick drivestick = new Joystick(1); Drivetrain drivetrain; WinchTest winch; Thread visionThread; CameraInit cam; UltrasonicHub hub; // ID's int DRIVE_LEFT_JOYSTICK_ID = 3; int DRIVE_RIGHT_JOYSTICK_ID = 1; int STRAFE_ID = 8; int WINCH_ID = 1; int ARM_ID = 4; int STRAFE_DRIVE_ID = 0; int DRIVE_LEFT_TOP_TRIGGER = 5; int DRIVE_LEFT_BOTTOM_TRIGGER = 7; int IMG_WIDTH = 640; int IMG_HEIGHT = 480; AxisCamera cameraBack = CameraServer.getInstance().addAxisCamera("Back", "10.42.15.37"); //AxisCamera cameraFront = CameraServer.getInstance().addAxisCamera("Back", "10.42.15.39"); private double centerX = 0.0; //Creates the variable centerX. private final Object imgLock = new Object(); public void robotInit(){ arm = new Arm(); leftStick = new Joystick(0); drivetrain = Drivetrain.Create(); winch = new WinchTest(); cameraBack = CameraServer.getInstance().addAxisCamera("Back", "10.42.15.37"); cameraBack.setResolution(IMG_WIDTH, IMG_HEIGHT); visionThread = new VisionThread(cameraBack, new Pipeline(), pipeline -> { if (!pipeline.filterContoursOutput().isEmpty()) { Rect r = Imgproc.boundingRect(pipeline.filterContoursOutput().get(0)); synchronized (imgLock) { centerX = r.x + (r.width / 2); System.out.println(centerX); //if the code is actually working, System.out.println("Current Center X variable"); //a number should be displayed } } else { System.out.println("No Contours"); } }); visionThread.setDaemon(true); visionThread.start(); System.out.println("Hello World"); double turnTest = centerX - (IMG_WIDTH/2); System.out.println("Turn Test"); System.out.println(turnTest); /* hub = new UltrasonicHub(); ArrayList<String> devices; hub.addReader("/dev/ttyUSB0"); hub.addReader("/dev/ttyUSB1"); */ } public void teleopInit(){ //drivetrain.disableControl(); drivetrain.setTalonControlMode(TalonControlMode.PercentVbus); } public void teleopPeriodic(){ /* ArrayList<Integer> distances = hub.getDistancefromallPorts(); for (int i=0; i<distances.size(); i++) { System.out.print("d: " + distances.get(i) + "\t"); } System.out.println("\n"); */ double left = -drivestick.getRawAxis(DRIVE_LEFT_JOYSTICK_ID); double right = -drivestick.getRawAxis(DRIVE_RIGHT_JOYSTICK_ID); double strafe = drivestick.getRawAxis(STRAFE_DRIVE_ID); boolean isStrafing = drivestick.getRawButton(STRAFE_ID); Drivetrain.MotorGranular mode = Drivetrain.MotorGranular.NORMAL; if(drivestick.getRawButton(DRIVE_LEFT_BOTTOM_TRIGGER) && !drivestick.getRawButton(DRIVE_LEFT_TOP_TRIGGER)){ mode = Drivetrain.MotorGranular.FAST; } else if(!drivestick.getRawButton(DRIVE_LEFT_BOTTOM_TRIGGER) && drivestick.getRawButton(DRIVE_LEFT_TOP_TRIGGER)){ mode = Drivetrain.MotorGranular.SLOW; } drivetrain.drive(left, right, strafe,isStrafing,mode); if(leftStick.getRawButton(1)){ arm.armCompress(); } if(leftStick.getRawButton(2)){ arm.armDecompress(); } if(!leftStick.getRawButton(1)&&!leftStick.getRawButton(2)){ arm.armOff(); } arm.setArm(leftStick.getRawAxis(1)); double l = leftStick.getRawAxis(4); winch.set(l); } /** public void autonomousPeriodic(){ double centerX; synchronized (imgLock) { centerX = this.centerX; } double turn = centerX - (IMG_WIDTH / 2); double left = 0; double right = 0; double strafe = turn; boolean IsStrafing = true; Drivetrain.MotorGranular mode = Drivetrain.MotorGranular.SLOW; //drivetrain.drive(left, right, strafe, IsStrafing, mode); } **/ /**public void autonomousInit() { drivetrain.setTalonControlMode(TalonControlMode.Position); drivetrain.resetEncoder(); drivetrain.setPID(.05, 0, 0); drivetrain.enableControl(); drivetrain.Go(24, 24, 24, 24); drivetrain.setPID(.1, 0, 0); } double[] dist = new double[4]; **/ }
Edited Robot
src/main/java/org/usfirst/frc/team4215/robot/Robot.java
Edited Robot
Java
agpl-3.0
c6aed12e7734f2bc4520216c3ed3b35bfa4f95aa
0
podd/podd-redesign,podd/podd-redesign,podd/podd-redesign,podd/podd-redesign
/** * */ package com.github.podd.utils; import org.openrdf.model.URI; import org.openrdf.model.ValueFactory; import org.openrdf.model.impl.ValueFactoryImpl; import org.openrdf.model.vocabulary.OWL; /** * Interface containing URI constants for the Ontologies needed in PODD. * * @author kutila * */ public interface PoddRdfConstants { public static final ValueFactory VF = ValueFactoryImpl.getInstance(); /** Path to default alias file */ public static final String PATH_DEFAULT_ALIASES_FILE = "/com/github/podd/api/file/default-file-repositories.ttl"; /** Path to dcTerms.owl */ public static final String PATH_PODD_DCTERMS = "/ontologies/dcTerms.owl"; /** Path to foaf.owl */ public static final String PATH_PODD_FOAF = "/ontologies/foaf.owl"; /** Path to poddUser.owl */ public static final String PATH_PODD_USER = "/ontologies/poddUser.owl"; /** Path to poddBase.owl */ public static final String PATH_PODD_BASE = "/ontologies/poddBase.owl"; /** Path to poddScience.owl */ public static final String PATH_PODD_SCIENCE = "/ontologies/poddScience.owl"; /** Path to poddPlant.owl */ public static final String PATH_PODD_PLANT = "/ontologies/poddPlant.owl"; /** Path to poddAnimal.owl */ public static final String PATH_PODD_ANIMAL = "/ontologies/poddAnimal.owl"; /** * Path to poddFileRepository.owl. * * This ontology is NOT part of the standard schema ontologies. It is a separate ontology used * to validate File Repository configurations. */ public static final String PATH_PODD_FILE_REPOSITORY = "/ontologies/poddFileRepository.owl"; public static final String PODD_DCTERMS = "http://purl.org/podd/ns/dcTerms#"; public static final String PODD_FOAF = "http://purl.org/podd/ns/foaf#"; public static final String PODD_USER = "http://purl.org/podd/ns/poddUser#"; public static final String PODD_BASE = "http://purl.org/podd/ns/poddBase#"; public static final String PODD_SCIENCE = "http://purl.org/podd/ns/poddScience#"; public static final String PODD_PLANT = "http://purl.org/podd/ns/poddPlant#"; public static final String FILE_REPOSITORY = "http://purl.org/podd/ns/fileRepository#"; /** * An arbitrary prefix to use for automatically assigning ontology IRIs to inferred ontologies. * There are no versions delegated to inferred ontologies, and the ontology IRI is generated * using the version IRI of the original ontology, which must be unique. */ public static final String INFERRED_PREFIX = "urn:podd:inferred:ontologyiriprefix:"; /** Default value is urn:podd:default:artifactmanagementgraph: */ public static final URI DEFAULT_ARTIFACT_MANAGEMENT_GRAPH = PoddRdfConstants.VF .createURI("urn:podd:default:artifactmanagementgraph:"); /** Default value is urn:podd:default:schemamanagementgraph */ public static final URI DEFAULT_SCHEMA_MANAGEMENT_GRAPH = PoddRdfConstants.VF .createURI("urn:podd:default:schemamanagementgraph"); /** Default value is urn:podd:default:usermanagementgraph: */ public static final URI DEF_USER_MANAGEMENT_GRAPH = PoddRdfConstants.VF .createURI("urn:podd:default:usermanagementgraph:"); public static final URI DEFAULT_FILE_REPOSITORY_MANAGEMENT_GRAPH = PoddRdfConstants.VF .createURI("urn:podd:default:filerepositorymanagementgraph:"); public static final URI OWL_MAX_QUALIFIED_CARDINALITY = PoddRdfConstants.VF .createURI("http://www.w3.org/2002/07/owl#maxQualifiedCardinality"); public static final URI OWL_MIN_QUALIFIED_CARDINALITY = PoddRdfConstants.VF .createURI("http://www.w3.org/2002/07/owl#minQualifiedCardinality"); public static final URI OWL_QUALIFIED_CARDINALITY = PoddRdfConstants.VF .createURI("http://www.w3.org/2002/07/owl#qualifiedCardinality"); public static final URI OWL_VERSION_IRI = PoddRdfConstants.VF.createURI(OWL.NAMESPACE, "versionIRI"); /** * The OMV vocabulary defines a property for the current version of an ontology, so we are * reusing it here. */ public static final URI OMV_CURRENT_VERSION = PoddRdfConstants.VF.createURI("http://omv.ontoware.org/ontology#", "currentVersion"); /** * Creating a property for PODD to track the currentInferredVersion for the inferred axioms * ontology when linking from the ontology IRI. */ public static final URI PODD_BASE_CURRENT_INFERRED_VERSION = PoddRdfConstants.VF.createURI( PoddRdfConstants.PODD_BASE, "currentInferredVersion"); public static final String HTTP = "http://www.w3.org/2011/http#"; /** http://www.w3.org/2011/http#statusCodeValue */ public static final URI HTTP_STATUS_CODE_VALUE = ValueFactoryImpl.getInstance().createURI(PoddRdfConstants.HTTP, "statusCodeValue"); /** http://www.w3.org/2011/http#reasonPhrase */ public static final URI HTTP_REASON_PHRASE = ValueFactoryImpl.getInstance().createURI(PoddRdfConstants.HTTP, "reasonPhrase"); /** * Creating a property for PODD to track the inferredVersion for the inferred axioms ontology of * a particular versioned ontology. */ public static final URI PODD_BASE_INFERRED_VERSION = PoddRdfConstants.VF.createURI(PoddRdfConstants.PODD_BASE, "inferredVersion"); public static final URI PODD_BASE_HAS_PUBLICATION_STATUS = PoddRdfConstants.VF.createURI( PoddRdfConstants.PODD_BASE, "hasPublicationStatus"); public static final URI PODD_BASE_HAS_TOP_OBJECT = PoddRdfConstants.VF.createURI(PoddRdfConstants.PODD_BASE, "artifactHasTopObject"); public static final URI PODD_BASE_PUBLISHED = PoddRdfConstants.VF .createURI(PoddRdfConstants.PODD_BASE, "Published"); public static final URI PODD_BASE_NOT_PUBLISHED = PoddRdfConstants.VF.createURI(PoddRdfConstants.PODD_BASE, "NotPublished"); public static final URI PODD_BASE_WEIGHT = PoddRdfConstants.VF.createURI(PoddRdfConstants.PODD_BASE, "weight"); public static final URI PODD_BASE_DO_NOT_DISPLAY = PoddRdfConstants.VF.createURI(PoddRdfConstants.PODD_BASE, "doNotDisplay"); public static final URI PODD_BASE_CONTAINS = PoddRdfConstants.VF.createURI(PoddRdfConstants.PODD_BASE, "contains"); /** http://purl.org/podd/ns/poddBase#hasDisplayType */ public static final URI PODD_BASE_DISPLAY_TYPE = PoddRdfConstants.VF.createURI(PoddRdfConstants.PODD_BASE, "hasDisplayType"); /** http://purl.org/podd/ns/poddBase#DisplayType_ShortText */ public static final URI PODD_BASE_DISPLAY_TYPE_SHORTTEXT = PoddRdfConstants.VF.createURI( PoddRdfConstants.PODD_BASE, "DisplayType_ShortText"); /** http://purl.org/podd/ns/poddBase#DisplayType_LongText */ public static final URI PODD_BASE_DISPLAY_TYPE_LONGTEXT = PoddRdfConstants.VF.createURI(PoddRdfConstants.PODD_BASE, "DisplayType_LongText"); /** http://purl.org/podd/ns/poddBase#DisplayType_DropDownList */ public static final URI PODD_BASE_DISPLAY_TYPE_DROPDOWN = PoddRdfConstants.VF.createURI(PoddRdfConstants.PODD_BASE, "DisplayType_DropDownList"); /** http://purl.org/podd/ns/poddBase#DisplayType_CheckBox */ public static final URI PODD_BASE_DISPLAY_TYPE_CHECKBOX = PoddRdfConstants.VF.createURI(PoddRdfConstants.PODD_BASE, "DisplayType_CheckBox"); /** http://purl.org/podd/ns/poddBase#DisplayType_Table */ public static final URI PODD_BASE_DISPLAY_TYPE_TABLE = PoddRdfConstants.VF.createURI(PoddRdfConstants.PODD_BASE, "DisplayType_Table"); /** http://purl.org/podd/ns/poddBase#hasAllowedValue */ public static final URI PODD_BASE_ALLOWED_VALUE = ValueFactoryImpl.getInstance().createURI( PoddRdfConstants.PODD_BASE, "hasAllowedValue"); // ----- custom representation of cardinalities ----- /** * http://purl.org/podd/ns/poddBase#hasCardinality. Represents a <b>hasCardinality</b> property. */ public static final URI PODD_BASE_HAS_CARDINALITY = PoddRdfConstants.VF.createURI(PoddRdfConstants.PODD_BASE, "hasCardinality"); /** http://purl.org/podd/ns/poddBase#Cardinality_Exactly_One */ public static final URI PODD_BASE_CARDINALITY_EXACTLY_ONE = PoddRdfConstants.VF.createURI( PoddRdfConstants.PODD_BASE, "Cardinality_Exactly_One"); /** http://purl.org/podd/ns/poddBase#Cardinality_One_Or_Many */ public static final URI PODD_BASE_CARDINALITY_ONE_OR_MANY = PoddRdfConstants.VF.createURI( PoddRdfConstants.PODD_BASE, "Cardinality_One_Or_Many"); /** http://purl.org/podd/ns/poddBase#Cardinality_Zero_Or_One */ public static final URI PODD_BASE_CARDINALITY_ZERO_OR_ONE = PoddRdfConstants.VF.createURI( PoddRdfConstants.PODD_BASE, "Cardinality_Zero_Or_One"); /** http://purl.org/podd/ns/poddBase#Cardinality_Zero_Or_Many */ public static final URI PODD_BASE_CARDINALITY_ZERO_OR_MANY = PoddRdfConstants.VF.createURI( PoddRdfConstants.PODD_BASE, "Cardinality_Zero_Or_Many"); // ----- file reference constants ----- /** http://purl.org/podd/ns/poddBase#hasFileReference */ public static final URI PODD_BASE_HAS_FILE_REFERENCE = PoddRdfConstants.VF.createURI(PoddRdfConstants.PODD_BASE, "hasFileReference"); /** http://purl.org/podd/ns/poddBase#hasFileName */ public static final URI PODD_BASE_HAS_FILENAME = PoddRdfConstants.VF.createURI(PoddRdfConstants.PODD_BASE, "hasFileName"); /** http://purl.org/podd/ns/poddBase#hasPath */ public static final URI PODD_BASE_HAS_FILE_PATH = PoddRdfConstants.VF.createURI(PoddRdfConstants.PODD_BASE, "hasPath"); /** * http://purl.org/podd/ns/poddBase#hasAlias. * * This property is used to specify an "alias" value found inside a FileReference. */ public static final URI PODD_BASE_HAS_ALIAS = PoddRdfConstants.VF.createURI(PoddRdfConstants.PODD_BASE, "hasAlias"); /** http://purl.org/podd/ns/poddBase#FileReference */ public static final URI PODD_BASE_FILE_REFERENCE_TYPE = PoddRdfConstants.VF.createURI(PoddRdfConstants.PODD_BASE, "FileReference"); /** http://purl.org/podd/ns/poddBase#SSHFileReference */ public static final URI PODD_BASE_FILE_REFERENCE_TYPE_SSH = PoddRdfConstants.VF.createURI( PoddRdfConstants.PODD_BASE, "SSHFileReference"); // ----- file repository constants ----- /** http://purl.org/podd/ns/poddBase#FileRepository */ public static final URI PODD_FILE_REPOSITORY = PoddRdfConstants.VF.createURI(PoddRdfConstants.FILE_REPOSITORY, "FileRepository"); /** http://purl.org/podd/ns/poddBase#SSHFileRepository */ public static final URI PODD_SSH_FILE_REPOSITORY = PoddRdfConstants.VF.createURI(PoddRdfConstants.FILE_REPOSITORY, "SSHFileRepository"); /** http://purl.org/podd/ns/poddBase#HTTPFileRepository */ public static final URI PODD_HTTP_FILE_REPOSITORY = PoddRdfConstants.VF.createURI(PoddRdfConstants.FILE_REPOSITORY, "HTTPFileRepository"); /** * http://purl.org/podd/ns/poddBase#hasFileRepositoryAlias * * This property is ONLY used in the File Repository management implementations. */ public static final URI PODD_FILE_REPOSITORY_ALIAS = PoddRdfConstants.VF.createURI( PoddRdfConstants.FILE_REPOSITORY, "hasFileRepositoryAlias"); /** http://purl.org/podd/ns/poddBase#hasFileRepositoryProtocol */ public static final URI PODD_FILE_REPOSITORY_PROTOCOL = PoddRdfConstants.VF.createURI( PoddRdfConstants.FILE_REPOSITORY, "hasFileRepositoryProtocol"); /** http://purl.org/podd/ns/poddBase#hasFileRepositoryHost */ public static final URI PODD_FILE_REPOSITORY_HOST = PoddRdfConstants.VF.createURI(PoddRdfConstants.FILE_REPOSITORY, "hasFileRepositoryHost"); /** http://purl.org/podd/ns/poddBase#hasFileRepositoryPort */ public static final URI PODD_FILE_REPOSITORY_PORT = PoddRdfConstants.VF.createURI(PoddRdfConstants.FILE_REPOSITORY, "hasFileRepositoryPort"); /** http://purl.org/podd/ns/poddBase#hasFileRepositoryFingerprint */ public static final URI PODD_FILE_REPOSITORY_FINGERPRINT = PoddRdfConstants.VF.createURI( PoddRdfConstants.FILE_REPOSITORY, "hasFileRepositoryFingerprint"); /** http://purl.org/podd/ns/poddBase#hasFileRepositoryUsername */ public static final URI PODD_FILE_REPOSITORY_USERNAME = PoddRdfConstants.VF.createURI( PoddRdfConstants.FILE_REPOSITORY, "hasFileRepositoryUsername"); /** http://purl.org/podd/ns/poddBase#hasFileRepositorySecret */ public static final URI PODD_FILE_REPOSITORY_SECRET = PoddRdfConstants.VF.createURI( PoddRdfConstants.FILE_REPOSITORY, "hasFileRepositorySecret"); }
api/src/main/java/com/github/podd/utils/PoddRdfConstants.java
/** * */ package com.github.podd.utils; import org.openrdf.model.URI; import org.openrdf.model.ValueFactory; import org.openrdf.model.impl.ValueFactoryImpl; import org.openrdf.model.vocabulary.OWL; /** * Interface containing URI constants for the Ontologies needed in PODD. * * @author kutila * */ public interface PoddRdfConstants { public static final ValueFactory VF = ValueFactoryImpl.getInstance(); /** Path to default alias file */ public static final String PATH_DEFAULT_ALIASES_FILE = "/com/github/podd/api/file/default-file-repositories.ttl"; /** Path to dcTerms.owl */ public static final String PATH_PODD_DCTERMS = "/ontologies/dcTerms.owl"; /** Path to foaf.owl */ public static final String PATH_PODD_FOAF = "/ontologies/foaf.owl"; /** Path to poddUser.owl */ public static final String PATH_PODD_USER = "/ontologies/poddUser.owl"; /** Path to poddBase.owl */ public static final String PATH_PODD_BASE = "/ontologies/poddBase.owl"; /** Path to poddScience.owl */ public static final String PATH_PODD_SCIENCE = "/ontologies/poddScience.owl"; /** Path to poddPlant.owl */ public static final String PATH_PODD_PLANT = "/ontologies/poddPlant.owl"; /** Path to poddAnimal.owl */ public static final String PATH_PODD_ANIMAL = "/ontologies/poddAnimal.owl"; /** * Path to poddFileRepository.owl. * * This ontology is NOT part of the standard schema ontologies. It is a separate ontology used * to validate File Repository configurations. */ public static final String PATH_PODD_FILE_REPOSITORY = "/ontologies/poddFileRepository.owl"; public static final String PODD_DCTERMS = "http://purl.org/podd/ns/dcTerms#"; public static final String PODD_FOAF = "http://purl.org/podd/ns/foaf#"; public static final String PODD_USER = "http://purl.org/podd/ns/poddUser#"; public static final String PODD_BASE = "http://purl.org/podd/ns/poddBase#"; public static final String PODD_SCIENCE = "http://purl.org/podd/ns/poddScience#"; public static final String PODD_PLANT = "http://purl.org/podd/ns/poddPlant#"; public static final String FILE_REPOSITORY = "http://purl.org/podd/ns/fileRepository#"; /** * Namespace for Ontology used by the Metadata service. */ public static final String PODD_METADATA = "http://purl.org/podd/ns/poddMetadata#"; /** * An arbitrary prefix to use for automatically assigning ontology IRIs to inferred ontologies. * There are no versions delegated to inferred ontologies, and the ontology IRI is generated * using the version IRI of the original ontology, which must be unique. */ public static final String INFERRED_PREFIX = "urn:podd:inferred:ontologyiriprefix:"; /** Default value is urn:podd:default:artifactmanagementgraph: */ public static final URI DEFAULT_ARTIFACT_MANAGEMENT_GRAPH = PoddRdfConstants.VF .createURI("urn:podd:default:artifactmanagementgraph:"); /** Default value is urn:podd:default:schemamanagementgraph */ public static final URI DEFAULT_SCHEMA_MANAGEMENT_GRAPH = PoddRdfConstants.VF .createURI("urn:podd:default:schemamanagementgraph"); /** Default value is urn:podd:default:usermanagementgraph: */ public static final URI DEF_USER_MANAGEMENT_GRAPH = PoddRdfConstants.VF .createURI("urn:podd:default:usermanagementgraph:"); public static final URI DEFAULT_FILE_REPOSITORY_MANAGEMENT_GRAPH = PoddRdfConstants.VF .createURI("urn:podd:default:filerepositorymanagementgraph:"); public static final URI OWL_MAX_QUALIFIED_CARDINALITY = PoddRdfConstants.VF .createURI("http://www.w3.org/2002/07/owl#maxQualifiedCardinality"); public static final URI OWL_MIN_QUALIFIED_CARDINALITY = PoddRdfConstants.VF .createURI("http://www.w3.org/2002/07/owl#minQualifiedCardinality"); public static final URI OWL_QUALIFIED_CARDINALITY = PoddRdfConstants.VF .createURI("http://www.w3.org/2002/07/owl#qualifiedCardinality"); public static final URI OWL_VERSION_IRI = PoddRdfConstants.VF.createURI(OWL.NAMESPACE, "versionIRI"); /** * The OMV vocabulary defines a property for the current version of an ontology, so we are * reusing it here. */ public static final URI OMV_CURRENT_VERSION = PoddRdfConstants.VF.createURI("http://omv.ontoware.org/ontology#", "currentVersion"); /** * Creating a property for PODD to track the currentInferredVersion for the inferred axioms * ontology when linking from the ontology IRI. */ public static final URI PODD_BASE_CURRENT_INFERRED_VERSION = PoddRdfConstants.VF.createURI( PoddRdfConstants.PODD_BASE, "currentInferredVersion"); public static final String HTTP = "http://www.w3.org/2011/http#"; /** http://www.w3.org/2011/http#statusCodeValue */ public static final URI HTTP_STATUS_CODE_VALUE = ValueFactoryImpl.getInstance().createURI(PoddRdfConstants.HTTP, "statusCodeValue"); /** http://www.w3.org/2011/http#reasonPhrase */ public static final URI HTTP_REASON_PHRASE = ValueFactoryImpl.getInstance().createURI(PoddRdfConstants.HTTP, "reasonPhrase"); /** * Creating a property for PODD to track the inferredVersion for the inferred axioms ontology of * a particular versioned ontology. */ public static final URI PODD_BASE_INFERRED_VERSION = PoddRdfConstants.VF.createURI(PoddRdfConstants.PODD_BASE, "inferredVersion"); public static final URI PODD_BASE_HAS_PUBLICATION_STATUS = PoddRdfConstants.VF.createURI( PoddRdfConstants.PODD_BASE, "hasPublicationStatus"); public static final URI PODD_BASE_HAS_TOP_OBJECT = PoddRdfConstants.VF.createURI(PoddRdfConstants.PODD_BASE, "artifactHasTopObject"); public static final URI PODD_BASE_PUBLISHED = PoddRdfConstants.VF .createURI(PoddRdfConstants.PODD_BASE, "Published"); public static final URI PODD_BASE_NOT_PUBLISHED = PoddRdfConstants.VF.createURI(PoddRdfConstants.PODD_BASE, "NotPublished"); public static final URI PODD_BASE_WEIGHT = PoddRdfConstants.VF.createURI(PoddRdfConstants.PODD_BASE, "weight"); public static final URI PODD_BASE_DO_NOT_DISPLAY = PoddRdfConstants.VF.createURI(PoddRdfConstants.PODD_BASE, "doNotDisplay"); public static final URI PODD_BASE_CONTAINS = PoddRdfConstants.VF.createURI(PoddRdfConstants.PODD_BASE, "contains"); /** http://purl.org/podd/ns/poddBase#hasDisplayType */ public static final URI PODD_BASE_DISPLAY_TYPE = PoddRdfConstants.VF.createURI(PoddRdfConstants.PODD_BASE, "hasDisplayType"); /** http://purl.org/podd/ns/poddBase#DisplayType_ShortText */ public static final URI PODD_BASE_DISPLAY_TYPE_SHORTTEXT = PoddRdfConstants.VF.createURI( PoddRdfConstants.PODD_BASE, "DisplayType_ShortText"); /** http://purl.org/podd/ns/poddBase#DisplayType_LongText */ public static final URI PODD_BASE_DISPLAY_TYPE_LONGTEXT = PoddRdfConstants.VF.createURI(PoddRdfConstants.PODD_BASE, "DisplayType_LongText"); /** http://purl.org/podd/ns/poddBase#DisplayType_DropDownList */ public static final URI PODD_BASE_DISPLAY_TYPE_DROPDOWN = PoddRdfConstants.VF.createURI(PoddRdfConstants.PODD_BASE, "DisplayType_DropDownList"); /** http://purl.org/podd/ns/poddBase#DisplayType_CheckBox */ public static final URI PODD_BASE_DISPLAY_TYPE_CHECKBOX = PoddRdfConstants.VF.createURI(PoddRdfConstants.PODD_BASE, "DisplayType_CheckBox"); /** http://purl.org/podd/ns/poddBase#DisplayType_Table */ public static final URI PODD_BASE_DISPLAY_TYPE_TABLE = PoddRdfConstants.VF.createURI(PoddRdfConstants.PODD_BASE, "DisplayType_Table"); /** http://purl.org/podd/ns/poddBase#hasAllowedValue */ public static final URI PODD_BASE_ALLOWED_VALUE = ValueFactoryImpl.getInstance().createURI( PoddRdfConstants.PODD_BASE, "hasAllowedValue"); // ----- custom representation of cardinalities ----- /** * http://purl.org/podd/ns/poddBase#hasCardinality. Represents a <b>hasCardinality</b> property. */ public static final URI PODD_BASE_HAS_CARDINALITY = PoddRdfConstants.VF.createURI(PoddRdfConstants.PODD_BASE, "hasCardinality"); /** http://purl.org/podd/ns/poddBase#Cardinality_Exactly_One */ public static final URI PODD_BASE_CARDINALITY_EXACTLY_ONE = PoddRdfConstants.VF.createURI( PoddRdfConstants.PODD_BASE, "Cardinality_Exactly_One"); /** http://purl.org/podd/ns/poddBase#Cardinality_One_Or_Many */ public static final URI PODD_BASE_CARDINALITY_ONE_OR_MANY = PoddRdfConstants.VF.createURI( PoddRdfConstants.PODD_BASE, "Cardinality_One_Or_Many"); /** http://purl.org/podd/ns/poddBase#Cardinality_Zero_Or_One */ public static final URI PODD_BASE_CARDINALITY_ZERO_OR_ONE = PoddRdfConstants.VF.createURI( PoddRdfConstants.PODD_BASE, "Cardinality_Zero_Or_One"); /** http://purl.org/podd/ns/poddBase#Cardinality_Zero_Or_Many */ public static final URI PODD_BASE_CARDINALITY_ZERO_OR_MANY = PoddRdfConstants.VF.createURI( PoddRdfConstants.PODD_BASE, "Cardinality_Zero_Or_Many"); // ----- file reference constants ----- /** http://purl.org/podd/ns/poddBase#hasFileReference */ public static final URI PODD_BASE_HAS_FILE_REFERENCE = PoddRdfConstants.VF.createURI(PoddRdfConstants.PODD_BASE, "hasFileReference"); /** http://purl.org/podd/ns/poddBase#hasFileName */ public static final URI PODD_BASE_HAS_FILENAME = PoddRdfConstants.VF.createURI(PoddRdfConstants.PODD_BASE, "hasFileName"); /** http://purl.org/podd/ns/poddBase#hasPath */ public static final URI PODD_BASE_HAS_FILE_PATH = PoddRdfConstants.VF.createURI(PoddRdfConstants.PODD_BASE, "hasPath"); /** * http://purl.org/podd/ns/poddBase#hasAlias. * * This property is used to specify an "alias" value found inside a FileReference. */ public static final URI PODD_BASE_HAS_ALIAS = PoddRdfConstants.VF.createURI(PoddRdfConstants.PODD_BASE, "hasAlias"); /** http://purl.org/podd/ns/poddBase#FileReference */ public static final URI PODD_BASE_FILE_REFERENCE_TYPE = PoddRdfConstants.VF.createURI(PoddRdfConstants.PODD_BASE, "FileReference"); /** http://purl.org/podd/ns/poddBase#SSHFileReference */ public static final URI PODD_BASE_FILE_REFERENCE_TYPE_SSH = PoddRdfConstants.VF.createURI( PoddRdfConstants.PODD_BASE, "SSHFileReference"); // ----- file repository constants ----- /** http://purl.org/podd/ns/poddBase#FileRepository */ public static final URI PODD_FILE_REPOSITORY = PoddRdfConstants.VF.createURI(PoddRdfConstants.FILE_REPOSITORY, "FileRepository"); /** http://purl.org/podd/ns/poddBase#SSHFileRepository */ public static final URI PODD_SSH_FILE_REPOSITORY = PoddRdfConstants.VF.createURI(PoddRdfConstants.FILE_REPOSITORY, "SSHFileRepository"); /** http://purl.org/podd/ns/poddBase#HTTPFileRepository */ public static final URI PODD_HTTP_FILE_REPOSITORY = PoddRdfConstants.VF.createURI(PoddRdfConstants.FILE_REPOSITORY, "HTTPFileRepository"); /** * http://purl.org/podd/ns/poddBase#hasFileRepositoryAlias * * This property is ONLY used in the File Repository management implementations. */ public static final URI PODD_FILE_REPOSITORY_ALIAS = PoddRdfConstants.VF.createURI( PoddRdfConstants.FILE_REPOSITORY, "hasFileRepositoryAlias"); /** http://purl.org/podd/ns/poddBase#hasFileRepositoryProtocol */ public static final URI PODD_FILE_REPOSITORY_PROTOCOL = PoddRdfConstants.VF.createURI( PoddRdfConstants.FILE_REPOSITORY, "hasFileRepositoryProtocol"); /** http://purl.org/podd/ns/poddBase#hasFileRepositoryHost */ public static final URI PODD_FILE_REPOSITORY_HOST = PoddRdfConstants.VF.createURI(PoddRdfConstants.FILE_REPOSITORY, "hasFileRepositoryHost"); /** http://purl.org/podd/ns/poddBase#hasFileRepositoryPort */ public static final URI PODD_FILE_REPOSITORY_PORT = PoddRdfConstants.VF.createURI(PoddRdfConstants.FILE_REPOSITORY, "hasFileRepositoryPort"); /** http://purl.org/podd/ns/poddBase#hasFileRepositoryFingerprint */ public static final URI PODD_FILE_REPOSITORY_FINGERPRINT = PoddRdfConstants.VF.createURI( PoddRdfConstants.FILE_REPOSITORY, "hasFileRepositoryFingerprint"); /** http://purl.org/podd/ns/poddBase#hasFileRepositoryUsername */ public static final URI PODD_FILE_REPOSITORY_USERNAME = PoddRdfConstants.VF.createURI( PoddRdfConstants.FILE_REPOSITORY, "hasFileRepositoryUsername"); /** http://purl.org/podd/ns/poddBase#hasFileRepositorySecret */ public static final URI PODD_FILE_REPOSITORY_SECRET = PoddRdfConstants.VF.createURI( PoddRdfConstants.FILE_REPOSITORY, "hasFileRepositorySecret"); public static final URI PODD_METADATA_CLASS = PoddRdfConstants.VF.createURI(PoddRdfConstants.PODD_METADATA, "hasClass"); public static final URI PODD_METADATA_PROPERTY = PoddRdfConstants.VF.createURI(PoddRdfConstants.PODD_METADATA, "hasProperty"); public static final URI PODD_METADATA_RANGE = PoddRdfConstants.VF.createURI(PoddRdfConstants.PODD_METADATA, "hasRange"); }
remove unused constants
api/src/main/java/com/github/podd/utils/PoddRdfConstants.java
remove unused constants
Java
lgpl-2.1
5514bd39c94718f50c02befdcdc5f49f608ea786
0
simon816/MinecraftForge,blay09/MinecraftForge,ThiagoGarciaAlves/MinecraftForge,bonii-xx/MinecraftForge,Vorquel/MinecraftForge,Zaggy1024/MinecraftForge,brubo1/MinecraftForge,RainWarrior/MinecraftForge,luacs1998/MinecraftForge,dmf444/MinecraftForge,karlthepagan/MinecraftForge,Ghostlyr/MinecraftForge,Theerapak/MinecraftForge,mickkay/MinecraftForge,shadekiller666/MinecraftForge,fcjailybo/MinecraftForge,CrafterKina/MinecraftForge,jdpadrnos/MinecraftForge,Mathe172/MinecraftForge
package net.minecraftforge.common; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.logging.Level; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.BiMap; import com.google.common.collect.HashBiMap; import com.google.common.collect.HashMultimap; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSetMultimap; import com.google.common.collect.LinkedHashMultimap; import com.google.common.collect.ListMultimap; import com.google.common.collect.Lists; import com.google.common.collect.MapMaker; import com.google.common.collect.Maps; import com.google.common.collect.Multimap; import com.google.common.collect.Multiset; import com.google.common.collect.SetMultimap; import com.google.common.collect.Sets; import com.google.common.collect.TreeMultiset; import cpw.mods.fml.common.FMLLog; import cpw.mods.fml.common.Loader; import cpw.mods.fml.common.ModContainer; import net.minecraft.src.Chunk; import net.minecraft.src.ChunkCoordIntPair; import net.minecraft.src.CompressedStreamTools; import net.minecraft.src.Entity; import net.minecraft.src.EntityPlayer; import net.minecraft.src.MathHelper; import net.minecraft.src.NBTBase; import net.minecraft.src.NBTTagCompound; import net.minecraft.src.NBTTagList; import net.minecraft.src.World; import net.minecraft.src.WorldServer; import net.minecraftforge.common.ForgeChunkManager.Ticket; /** * Manages chunkloading for mods. * * The basic principle is a ticket based system. * 1. Mods register a callback {@link #setForcedChunkLoadingCallback(Object, LoadingCallback)} * 2. Mods ask for a ticket {@link #requestTicket(Object, World, Type)} and then hold on to that ticket. * 3. Mods request chunks to stay loaded {@link #forceChunk(Ticket, ChunkCoordIntPair)} or remove chunks from force loading {@link #unforceChunk(Ticket, ChunkCoordIntPair)}. * 4. When a world unloads, the tickets associated with that world are saved by the chunk manager. * 5. When a world loads, saved tickets are offered to the mods associated with the tickets. The {@link Ticket#getModData()} that is set by the mod should be used to re-register * chunks to stay loaded (and maybe take other actions). * * The chunkloading is configurable at runtime. The file "config/forgeChunkLoading.cfg" contains both default configuration for chunkloading, and a sample individual mod * specific override section. * * @author cpw * */ public class ForgeChunkManager { private static int defaultMaxCount; private static int defaultMaxChunks; private static boolean overridesEnabled; private static Map<World, Multimap<String, Ticket>> tickets = new MapMaker().weakKeys().makeMap(); private static Map<String, Integer> ticketConstraints = Maps.newHashMap(); private static Map<String, Integer> chunkConstraints = Maps.newHashMap(); private static SetMultimap<String, Ticket> playerTickets = HashMultimap.create(); private static Map<String, LoadingCallback> callbacks = Maps.newHashMap(); private static Map<World, SetMultimap<ChunkCoordIntPair,Ticket>> forcedChunks = new MapMaker().weakKeys().makeMap(); private static BiMap<UUID,Ticket> pendingEntities = HashBiMap.create(); private static Map<World,Cache<Long, Chunk>> dormantChunkCache = new MapMaker().weakKeys().makeMap(); private static File cfgFile; private static Configuration config; private static int playerTicketLength; private static int dormantChunkCacheSize; /** * All mods requiring chunkloading need to implement this to handle the * re-registration of chunk tickets at world loading time * * @author cpw * */ public interface LoadingCallback { /** * Called back when tickets are loaded from the world to allow the * mod to re-register the chunks associated with those tickets. The list supplied * here is truncated to length prior to use. Tickets unwanted by the * mod must be disposed of manually unless the mod is an OrderedLoadingCallback instance * in which case, they will have been disposed of by the earlier callback. * * @param tickets The tickets to re-register. The list is immutable and cannot be manipulated directly. Copy it first. * @param world the world */ public void ticketsLoaded(List<Ticket> tickets, World world); } /** * This is a special LoadingCallback that can be implemented as well as the * LoadingCallback to provide access to additional behaviour. * Specifically, this callback will fire prior to Forge dropping excess * tickets. Tickets in the returned list are presumed ordered and excess will * be truncated from the returned list. * This allows the mod to control not only if they actually <em>want</em> a ticket but * also their preferred ticket ordering. * * @author cpw * */ public interface OrderedLoadingCallback extends LoadingCallback { /** * Called back when tickets are loaded from the world to allow the * mod to decide if it wants the ticket still, and prioritise overflow * based on the ticket count. * WARNING: You cannot force chunks in this callback, it is strictly for allowing the mod * to be more selective in which tickets it wishes to preserve in an overflow situation * * @param tickets The tickets that you will want to select from. The list is immutable and cannot be manipulated directly. Copy it first. * @param world The world * @param maxTicketCount The maximum number of tickets that will be allowed. * @return A list of the tickets this mod wishes to continue using. This list will be truncated * to "maxTicketCount" size after the call returns and then offered to the other callback * method */ public List<Ticket> ticketsLoaded(List<Ticket> tickets, World world, int maxTicketCount); } public enum Type { /** * For non-entity registrations */ NORMAL, /** * For entity registrations */ ENTITY } public static class Ticket { private String modId; private Type ticketType; private LinkedHashSet<ChunkCoordIntPair> requestedChunks; private NBTTagCompound modData; private World world; private int maxDepth; private String entityClazz; private int entityChunkX; private int entityChunkZ; private Entity entity; private String player; Ticket(String modId, Type type, World world) { this.modId = modId; this.ticketType = type; this.world = world; this.maxDepth = getMaxChunkDepthFor(modId); this.requestedChunks = Sets.newLinkedHashSet(); } Ticket(String modId, Type type, World world, EntityPlayer player) { this(modId, type, world); if (player != null) { this.player = player.getEntityName(); } else { FMLLog.log(Level.SEVERE, "Attempt to create a player ticket without a valid player"); throw new RuntimeException(); } } /** * The chunk list depth can be manipulated up to the maximal grant allowed for the mod. This value is configurable. Once the maximum is reached, * the least recently forced chunk, by original registration time, is removed from the forced chunk list. * * @param depth The new depth to set */ public void setChunkListDepth(int depth) { if (depth > getMaxChunkDepthFor(modId) || (depth <= 0 && getMaxChunkDepthFor(modId) > 0)) { FMLLog.warning("The mod %s tried to modify the chunk ticket depth to: %d, its allowed maximum is: %d", modId, depth, getMaxChunkDepthFor(modId)); } else { this.maxDepth = depth; } } /** * Gets the current max depth for this ticket. * Should be the same as getMaxChunkListDepth() * unless setChunkListDepth has been called. * * @return Current max depth */ public int getChunkListDepth() { return maxDepth; } /** * Get the maximum chunk depth size * * @return The maximum chunk depth size */ public int getMaxChunkListDepth() { return getMaxChunkDepthFor(modId); } /** * Bind the entity to the ticket for {@link Type#ENTITY} type tickets. Other types will throw a runtime exception. * * @param entity The entity to bind */ public void bindEntity(Entity entity) { if (ticketType!=Type.ENTITY) { throw new RuntimeException("Cannot bind an entity to a non-entity ticket"); } this.entity = entity; } /** * Retrieve the {@link NBTTagCompound} that stores mod specific data for the chunk ticket. * Example data to store would be a TileEntity or Block location. This is persisted with the ticket and * provided to the {@link LoadingCallback} for the mod. It is recommended to use this to recover * useful state information for the forced chunks. * * @return The custom compound tag for mods to store additional chunkloading data */ public NBTTagCompound getModData() { if (this.modData == null) { this.modData = new NBTTagCompound(); } return modData; } /** * Get the entity associated with this {@link Type#ENTITY} type ticket * @return */ public Entity getEntity() { return entity; } /** * Is this a player associated ticket rather than a mod associated ticket? */ public boolean isPlayerTicket() { return player != null; } /** * Get the player associated with this ticket */ public String getPlayerName() { return player; } /** * Get the associated mod id */ public String getModId() { return modId; } /** * Gets the ticket type */ public Type getType() { return ticketType; } /** * Gets a list of requested chunks for this ticket. */ public ImmutableSet getChunkList() { return ImmutableSet.copyOf(requestedChunks); } } static void loadWorld(World world) { ArrayListMultimap<String, Ticket> newTickets = ArrayListMultimap.<String, Ticket>create(); tickets.put(world, newTickets); SetMultimap<ChunkCoordIntPair,Ticket> forcedChunkMap = LinkedHashMultimap.create(); forcedChunks.put(world, forcedChunkMap); if (!(world instanceof WorldServer)) { return; } dormantChunkCache.put(world, CacheBuilder.newBuilder().maximumSize(dormantChunkCacheSize).<Long, Chunk>build()); WorldServer worldServer = (WorldServer) world; File chunkDir = worldServer.getChunkSaveLocation(); File chunkLoaderData = new File(chunkDir, "forcedchunks.dat"); if (chunkLoaderData.exists() && chunkLoaderData.isFile()) { ArrayListMultimap<String, Ticket> loadedTickets = ArrayListMultimap.<String, Ticket>create(); ArrayListMultimap<String, Ticket> playerLoadedTickets = ArrayListMultimap.<String, Ticket>create(); NBTTagCompound forcedChunkData; try { forcedChunkData = CompressedStreamTools.read(chunkLoaderData); } catch (IOException e) { FMLLog.log(Level.WARNING, e, "Unable to read forced chunk data at %s - it will be ignored", chunkLoaderData.getAbsolutePath()); return; } NBTTagList ticketList = forcedChunkData.getTagList("TicketList"); for (int i = 0; i < ticketList.tagCount(); i++) { NBTTagCompound ticketHolder = (NBTTagCompound) ticketList.tagAt(i); String modId = ticketHolder.getString("Owner"); boolean isPlayer = "Forge".equals(modId); if (!isPlayer && !Loader.isModLoaded(modId)) { FMLLog.warning("Found chunkloading data for mod %s which is currently not available or active - it will be removed from the world save", modId); continue; } if (!isPlayer && !callbacks.containsKey(modId)) { FMLLog.warning("The mod %s has registered persistent chunkloading data but doesn't seem to want to be called back with it - it will be removed from the world save", modId); continue; } NBTTagList tickets = ticketHolder.getTagList("Tickets"); for (int j = 0; j < tickets.tagCount(); j++) { NBTTagCompound ticket = (NBTTagCompound) tickets.tagAt(j); modId = ticket.hasKey("ModId") ? ticket.getString("ModId") : modId; Type type = Type.values()[ticket.getByte("Type")]; byte ticketChunkDepth = ticket.getByte("ChunkListDepth"); Ticket tick = new Ticket(modId, type, world); if (ticket.hasKey("ModData")) { tick.modData = ticket.getCompoundTag("ModData"); } if (ticket.hasKey("Player")) { tick.player = ticket.getString("Player"); playerLoadedTickets.put(tick.modId, tick); playerTickets.put(tick.player, tick); } else { loadedTickets.put(modId, tick); } if (type == Type.ENTITY) { tick.entityChunkX = ticket.getInteger("chunkX"); tick.entityChunkZ = ticket.getInteger("chunkZ"); UUID uuid = new UUID(ticket.getLong("PersistentIDMSB"), ticket.getLong("PersistentIDLSB")); // add the ticket to the "pending entity" list pendingEntities.put(uuid, tick); } } } for (Ticket tick : ImmutableSet.copyOf(pendingEntities.values())) { if (tick.ticketType == Type.ENTITY && tick.entity == null) { // force the world to load the entity's chunk // the load will come back through the loadEntity method and attach the entity // to the ticket world.getChunkFromChunkCoords(tick.entityChunkX, tick.entityChunkZ); } } for (Ticket tick : ImmutableSet.copyOf(pendingEntities.values())) { if (tick.ticketType == Type.ENTITY && tick.entity == null) { FMLLog.warning("Failed to load persistent chunkloading entity %s from store.", pendingEntities.inverse().get(tick)); loadedTickets.remove(tick.modId, tick); } } pendingEntities.clear(); // send callbacks for (String modId : loadedTickets.keySet()) { LoadingCallback loadingCallback = callbacks.get(modId); int maxTicketLength = getMaxTicketLengthFor(modId); List<Ticket> tickets = loadedTickets.get(modId); if (loadingCallback instanceof OrderedLoadingCallback) { OrderedLoadingCallback orderedLoadingCallback = (OrderedLoadingCallback) loadingCallback; tickets = orderedLoadingCallback.ticketsLoaded(ImmutableList.copyOf(tickets), world, maxTicketLength); } if (tickets.size() > maxTicketLength) { FMLLog.warning("The mod %s has too many open chunkloading tickets %d. Excess will be dropped", modId, tickets.size()); tickets.subList(maxTicketLength, tickets.size()).clear(); } ForgeChunkManager.tickets.get(world).putAll(modId, tickets); loadingCallback.ticketsLoaded(ImmutableList.copyOf(tickets), world); } for (String modId : playerLoadedTickets.keySet()) { LoadingCallback loadingCallback = callbacks.get(modId); List<Ticket> tickets = playerLoadedTickets.get(modId); ForgeChunkManager.tickets.get(world).putAll("Forge", tickets); loadingCallback.ticketsLoaded(ImmutableList.copyOf(tickets), world); } } } /** * Set a chunkloading callback for the supplied mod object * * @param mod The mod instance registering the callback * @param callback The code to call back when forced chunks are loaded */ public static void setForcedChunkLoadingCallback(Object mod, LoadingCallback callback) { ModContainer container = getContainer(mod); if (container == null) { FMLLog.warning("Unable to register a callback for an unknown mod %s (%s : %x)", mod, mod.getClass().getName(), System.identityHashCode(mod)); return; } callbacks.put(container.getModId(), callback); } /** * Discover the available tickets for the mod in the world * * @param mod The mod that will own the tickets * @param world The world * @return The count of tickets left for the mod in the supplied world */ public static int ticketCountAvailableFor(Object mod, World world) { ModContainer container = getContainer(mod); if (container!=null) { String modId = container.getModId(); int allowedCount = getMaxTicketLengthFor(modId); return allowedCount - tickets.get(world).get(modId).size(); } else { return 0; } } private static ModContainer getContainer(Object mod) { ModContainer container = Loader.instance().getModObjectList().inverse().get(mod); return container; } private static int getMaxTicketLengthFor(String modId) { int allowedCount = ticketConstraints.containsKey(modId) && overridesEnabled ? ticketConstraints.get(modId) : defaultMaxCount; return allowedCount; } private static int getMaxChunkDepthFor(String modId) { int allowedCount = chunkConstraints.containsKey(modId) && overridesEnabled ? chunkConstraints.get(modId) : defaultMaxChunks; return allowedCount; } public static Ticket requestPlayerTicket(Object mod, EntityPlayer player, World world, Type type) { ModContainer mc = getContainer(mod); if (mc == null) { FMLLog.log(Level.SEVERE, "Failed to locate the container for mod instance %s (%s : %x)", mod, mod.getClass().getName(), System.identityHashCode(mod)); return null; } if (playerTickets.get(player.getEntityName()).size()>playerTicketLength) { FMLLog.warning("Unable to assign further chunkloading tickets to player %s (on behalf of mod %s)", player.getEntityName(), mc.getModId()); return null; } Ticket ticket = new Ticket(mc.getModId(),type,world,player); playerTickets.put(player.getEntityName(), ticket); tickets.get(world).put("Forge", ticket); return ticket; } /** * Request a chunkloading ticket of the appropriate type for the supplied mod * * @param mod The mod requesting a ticket * @param world The world in which it is requesting the ticket * @param type The type of ticket * @return A ticket with which to register chunks for loading, or null if no further tickets are available */ public static Ticket requestTicket(Object mod, World world, Type type) { ModContainer container = getContainer(mod); if (container == null) { FMLLog.log(Level.SEVERE, "Failed to locate the container for mod instance %s (%s : %x)", mod, mod.getClass().getName(), System.identityHashCode(mod)); return null; } String modId = container.getModId(); if (!callbacks.containsKey(modId)) { FMLLog.severe("The mod %s has attempted to request a ticket without a listener in place", modId); throw new RuntimeException("Invalid ticket request"); } int allowedCount = ticketConstraints.containsKey(modId) ? ticketConstraints.get(modId) : defaultMaxCount; if (tickets.get(world).get(modId).size() >= allowedCount) { FMLLog.info("The mod %s has attempted to allocate a chunkloading ticket beyond it's currently allocated maximum : %d", modId, allowedCount); return null; } Ticket ticket = new Ticket(modId, type, world); tickets.get(world).put(modId, ticket); return ticket; } /** * Release the ticket back to the system. This will also unforce any chunks held by the ticket so that they can be unloaded and/or stop ticking. * * @param ticket The ticket to release */ public static void releaseTicket(Ticket ticket) { if (ticket == null) { return; } if (ticket.isPlayerTicket() ? !playerTickets.containsValue(ticket) : !tickets.get(ticket.world).containsEntry(ticket.modId, ticket)) { return; } if (ticket.requestedChunks!=null) { for (ChunkCoordIntPair chunk : ImmutableSet.copyOf(ticket.requestedChunks)) { unforceChunk(ticket, chunk); } } if (ticket.isPlayerTicket()) { playerTickets.remove(ticket.player, ticket); tickets.get(ticket.world).remove("Forge",ticket); } else { tickets.get(ticket.world).remove(ticket.modId, ticket); } } /** * Force the supplied chunk coordinate to be loaded by the supplied ticket. If the ticket's {@link Ticket#maxDepth} is exceeded, the least * recently registered chunk is unforced and may be unloaded. * It is safe to force the chunk several times for a ticket, it will not generate duplication or change the ordering. * * @param ticket The ticket registering the chunk * @param chunk The chunk to force */ public static void forceChunk(Ticket ticket, ChunkCoordIntPair chunk) { if (ticket == null || chunk == null) { return; } if (ticket.ticketType == Type.ENTITY && ticket.entity == null) { throw new RuntimeException("Attempted to use an entity ticket to force a chunk, without an entity"); } if (ticket.isPlayerTicket() ? !playerTickets.containsValue(ticket) : !tickets.get(ticket.world).containsEntry(ticket.modId, ticket)) { FMLLog.severe("The mod %s attempted to force load a chunk with an invalid ticket. This is not permitted.", ticket.modId); return; } ticket.requestedChunks.add(chunk); forcedChunks.get(ticket.world).put(chunk, ticket); if (ticket.maxDepth > 0 && ticket.requestedChunks.size() > ticket.maxDepth) { ChunkCoordIntPair removed = ticket.requestedChunks.iterator().next(); unforceChunk(ticket,removed); } } /** * Reorganize the internal chunk list so that the chunk supplied is at the *end* of the list * This helps if you wish to guarantee a certain "automatic unload ordering" for the chunks * in the ticket list * * @param ticket The ticket holding the chunk list * @param chunk The chunk you wish to push to the end (so that it would be unloaded last) */ public static void reorderChunk(Ticket ticket, ChunkCoordIntPair chunk) { if (ticket == null || chunk == null || !ticket.requestedChunks.contains(chunk)) { return; } ticket.requestedChunks.remove(chunk); ticket.requestedChunks.add(chunk); } /** * Unforce the supplied chunk, allowing it to be unloaded and stop ticking. * * @param ticket The ticket holding the chunk * @param chunk The chunk to unforce */ public static void unforceChunk(Ticket ticket, ChunkCoordIntPair chunk) { if (ticket == null || chunk == null) { return; } ticket.requestedChunks.remove(chunk); forcedChunks.get(ticket.world).remove(chunk, ticket); } static void loadConfiguration() { for (String mod : config.categories.keySet()) { if (mod.equals("Forge") || mod.equals("defaults")) { continue; } Property modTC = config.get(mod, "maximumTicketCount", 200); Property modCPT = config.get(mod, "maximumChunksPerTicket", 25); ticketConstraints.put(mod, modTC.getInt(200)); chunkConstraints.put(mod, modCPT.getInt(25)); } config.save(); } /** * The list of persistent chunks in the world. This set is immutable. * @param world * @return */ public static SetMultimap<ChunkCoordIntPair, Ticket> getPersistentChunksFor(World world) { return forcedChunks.containsKey(world) ? ImmutableSetMultimap.copyOf(forcedChunks.get(world)) : ImmutableSetMultimap.<ChunkCoordIntPair,Ticket>of(); } static void saveWorld(World world) { // only persist persistent worlds if (!(world instanceof WorldServer)) { return; } WorldServer worldServer = (WorldServer) world; File chunkDir = worldServer.getChunkSaveLocation(); File chunkLoaderData = new File(chunkDir, "forcedchunks.dat"); NBTTagCompound forcedChunkData = new NBTTagCompound(); NBTTagList ticketList = new NBTTagList(); forcedChunkData.setTag("TicketList", ticketList); Multimap<String, Ticket> ticketSet = tickets.get(worldServer); for (String modId : ticketSet.keySet()) { NBTTagCompound ticketHolder = new NBTTagCompound(); ticketList.appendTag(ticketHolder); ticketHolder.setString("Owner", modId); NBTTagList tickets = new NBTTagList(); ticketHolder.setTag("Tickets", tickets); for (Ticket tick : ticketSet.get(modId)) { NBTTagCompound ticket = new NBTTagCompound(); ticket.setByte("Type", (byte) tick.ticketType.ordinal()); ticket.setByte("ChunkListDepth", (byte) tick.maxDepth); if (tick.isPlayerTicket()) { ticket.setString("ModId", tick.modId); ticket.setString("Player", tick.player); } if (tick.modData != null) { ticket.setCompoundTag("ModData", tick.modData); } if (tick.ticketType == Type.ENTITY && tick.entity != null) { ticket.setInteger("chunkX", MathHelper.floor_double(tick.entity.chunkCoordX)); ticket.setInteger("chunkZ", MathHelper.floor_double(tick.entity.chunkCoordZ)); ticket.setLong("PersistentIDMSB", tick.entity.getPersistentID().getMostSignificantBits()); ticket.setLong("PersistentIDLSB", tick.entity.getPersistentID().getLeastSignificantBits()); tickets.appendTag(ticket); } else if (tick.ticketType != Type.ENTITY) { tickets.appendTag(ticket); } } } try { CompressedStreamTools.write(forcedChunkData, chunkLoaderData); } catch (IOException e) { FMLLog.log(Level.WARNING, e, "Unable to write forced chunk data to %s - chunkloading won't work", chunkLoaderData.getAbsolutePath()); return; } } static void loadEntity(Entity entity) { UUID id = entity.getPersistentID(); Ticket tick = pendingEntities.get(id); if (tick != null) { tick.bindEntity(entity); pendingEntities.remove(id); } } public static void putDormantChunk(long coords, Chunk chunk) { Cache<Long, Chunk> cache = dormantChunkCache.get(chunk.worldObj); if (cache != null) { cache.put(coords, chunk); } } public static Chunk fetchDormantChunk(long coords, World world) { Cache<Long, Chunk> cache = dormantChunkCache.get(world); return cache == null ? null : cache.getIfPresent(coords); } static void captureConfig(File configDir) { cfgFile = new File(configDir,"forgeChunkLoading.cfg"); config = new Configuration(cfgFile, true); config.categories.clear(); try { config.load(); } catch (Exception e) { File dest = new File(cfgFile.getParentFile(),"forgeChunkLoading.cfg.bak"); if (dest.exists()) { dest.delete(); } cfgFile.renameTo(dest); FMLLog.log(Level.SEVERE, e, "A critical error occured reading the forgeChunkLoading.cfg file, defaults will be used - the invalid file is backed up at forgeChunkLoading.cfg.bak"); } config.addCustomCategoryComment("defaults", "Default configuration for forge chunk loading control"); Property maxTicketCount = config.get("defaults", "maximumTicketCount", 200); maxTicketCount.comment = "The default maximum ticket count for a mod which does not have an override\n" + "in this file. This is the number of chunk loading requests a mod is allowed to make."; defaultMaxCount = maxTicketCount.getInt(200); Property maxChunks = config.get("defaults", "maximumChunksPerTicket", 25); maxChunks.comment = "The default maximum number of chunks a mod can force, per ticket, \n" + "for a mod without an override. This is the maximum number of chunks a single ticket can force."; defaultMaxChunks = maxChunks.getInt(25); Property playerTicketCount = config.get("defaults", "playetTicketCount", 500); playerTicketCount.comment = "The number of tickets a player can be assigned instead of a mod. This is shared across all mods and it is up to the mods to use it."; playerTicketLength = playerTicketCount.getInt(500); Property dormantChunkCacheSizeProperty = config.get("defaults", "dormantChunkCacheSize", 0); dormantChunkCacheSizeProperty.comment = "Unloaded chunks can first be kept in a dormant cache for quicker\n" + "loading times. Specify the size of that cache here"; dormantChunkCacheSize = dormantChunkCacheSizeProperty.getInt(0); FMLLog.info("Configured a dormant chunk cache size of %d", dormantChunkCacheSizeProperty.getInt(0)); Property modOverridesEnabled = config.get("defaults", "enabled", true); modOverridesEnabled.comment = "Are mod overrides enabled?"; overridesEnabled = modOverridesEnabled.getBoolean(true); config.addCustomCategoryComment("Forge", "Sample mod specific control section.\n" + "Copy this section and rename the with the modid for the mod you wish to override.\n" + "A value of zero in either entry effectively disables any chunkloading capabilities\n" + "for that mod"); Property sampleTC = config.get("Forge", "maximumTicketCount", 200); sampleTC.comment = "Maximum ticket count for the mod. Zero disables chunkloading capabilities."; sampleTC = config.get("Forge", "maximumChunksPerTicket", 25); sampleTC.comment = "Maximum chunks per ticket for the mod."; for (String mod : config.categories.keySet()) { if (mod.equals("Forge") || mod.equals("defaults")) { continue; } Property modTC = config.get(mod, "maximumTicketCount", 200); Property modCPT = config.get(mod, "maximumChunksPerTicket", 25); } } public static Map<String,Property> getConfigMapFor(Object mod) { ModContainer container = getContainer(mod); if (container != null) { Map<String, Property> map = config.categories.get(container.getModId()); if (map == null) { map = Maps.newHashMap(); config.categories.put(container.getModId(), map); } return map; } return null; } public static void addConfigProperty(Object mod, String propertyName, String value, Property.Type type) { ModContainer container = getContainer(mod); if (container != null) { Map<String, Property> props = config.categories.get(container.getModId()); props.put(propertyName, new Property(propertyName, value, type)); } } }
common/net/minecraftforge/common/ForgeChunkManager.java
package net.minecraftforge.common; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.logging.Level; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.BiMap; import com.google.common.collect.HashBiMap; import com.google.common.collect.HashMultimap; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSetMultimap; import com.google.common.collect.LinkedHashMultimap; import com.google.common.collect.ListMultimap; import com.google.common.collect.Lists; import com.google.common.collect.MapMaker; import com.google.common.collect.Maps; import com.google.common.collect.Multimap; import com.google.common.collect.Multiset; import com.google.common.collect.SetMultimap; import com.google.common.collect.Sets; import com.google.common.collect.TreeMultiset; import cpw.mods.fml.common.FMLLog; import cpw.mods.fml.common.Loader; import cpw.mods.fml.common.ModContainer; import net.minecraft.src.Chunk; import net.minecraft.src.ChunkCoordIntPair; import net.minecraft.src.CompressedStreamTools; import net.minecraft.src.Entity; import net.minecraft.src.EntityPlayer; import net.minecraft.src.MathHelper; import net.minecraft.src.NBTBase; import net.minecraft.src.NBTTagCompound; import net.minecraft.src.NBTTagList; import net.minecraft.src.World; import net.minecraft.src.WorldServer; import net.minecraftforge.common.ForgeChunkManager.Ticket; /** * Manages chunkloading for mods. * * The basic principle is a ticket based system. * 1. Mods register a callback {@link #setForcedChunkLoadingCallback(Object, LoadingCallback)} * 2. Mods ask for a ticket {@link #requestTicket(Object, World, Type)} and then hold on to that ticket. * 3. Mods request chunks to stay loaded {@link #forceChunk(Ticket, ChunkCoordIntPair)} or remove chunks from force loading {@link #unforceChunk(Ticket, ChunkCoordIntPair)}. * 4. When a world unloads, the tickets associated with that world are saved by the chunk manager. * 5. When a world loads, saved tickets are offered to the mods associated with the tickets. The {@link Ticket#getModData()} that is set by the mod should be used to re-register * chunks to stay loaded (and maybe take other actions). * * The chunkloading is configurable at runtime. The file "config/forgeChunkLoading.cfg" contains both default configuration for chunkloading, and a sample individual mod * specific override section. * * @author cpw * */ public class ForgeChunkManager { private static int defaultMaxCount; private static int defaultMaxChunks; private static boolean overridesEnabled; private static Map<World, Multimap<String, Ticket>> tickets = new MapMaker().weakKeys().makeMap(); private static Map<String, Integer> ticketConstraints = Maps.newHashMap(); private static Map<String, Integer> chunkConstraints = Maps.newHashMap(); private static SetMultimap<String, Ticket> playerTickets = HashMultimap.create(); private static Map<String, LoadingCallback> callbacks = Maps.newHashMap(); private static Map<World, SetMultimap<ChunkCoordIntPair,Ticket>> forcedChunks = new MapMaker().weakKeys().makeMap(); private static BiMap<UUID,Ticket> pendingEntities = HashBiMap.create(); private static Map<World,Cache<Long, Chunk>> dormantChunkCache = new MapMaker().weakKeys().makeMap(); private static File cfgFile; private static Configuration config; private static int playerTicketLength; private static int dormantChunkCacheSize; /** * All mods requiring chunkloading need to implement this to handle the * re-registration of chunk tickets at world loading time * * @author cpw * */ public interface LoadingCallback { /** * Called back when tickets are loaded from the world to allow the * mod to re-register the chunks associated with those tickets. The list supplied * here is truncated to length prior to use. Tickets unwanted by the * mod must be disposed of manually unless the mod is an OrderedLoadingCallback instance * in which case, they will have been disposed of by the earlier callback. * * @param tickets The tickets to re-register. The list is immutable and cannot be manipulated directly. Copy it first. * @param world the world */ public void ticketsLoaded(List<Ticket> tickets, World world); } /** * This is a special LoadingCallback that can be implemented as well as the * LoadingCallback to provide access to additional behaviour. * Specifically, this callback will fire prior to Forge dropping excess * tickets. Tickets in the returned list are presumed ordered and excess will * be truncated from the returned list. * This allows the mod to control not only if they actually <em>want</em> a ticket but * also their preferred ticket ordering. * * @author cpw * */ public interface OrderedLoadingCallback extends LoadingCallback { /** * Called back when tickets are loaded from the world to allow the * mod to decide if it wants the ticket still, and prioritise overflow * based on the ticket count. * WARNING: You cannot force chunks in this callback, it is strictly for allowing the mod * to be more selective in which tickets it wishes to preserve in an overflow situation * * @param tickets The tickets that you will want to select from. The list is immutable and cannot be manipulated directly. Copy it first. * @param world The world * @param maxTicketCount The maximum number of tickets that will be allowed. * @return A list of the tickets this mod wishes to continue using. This list will be truncated * to "maxTicketCount" size after the call returns and then offered to the other callback * method */ public List<Ticket> ticketsLoaded(List<Ticket> tickets, World world, int maxTicketCount); } public enum Type { /** * For non-entity registrations */ NORMAL, /** * For entity registrations */ ENTITY } public static class Ticket { private String modId; private Type ticketType; private LinkedHashSet<ChunkCoordIntPair> requestedChunks; private NBTTagCompound modData; private World world; private int maxDepth; private String entityClazz; private int entityChunkX; private int entityChunkZ; private Entity entity; private String player; Ticket(String modId, Type type, World world) { this.modId = modId; this.ticketType = type; this.world = world; this.maxDepth = getMaxChunkDepthFor(modId); this.requestedChunks = Sets.newLinkedHashSet(); } Ticket(String modId, Type type, World world, EntityPlayer player) { this(modId, type, world); if (player != null) { this.player = player.getEntityName(); } else { FMLLog.log(Level.SEVERE, "Attempt to create a player ticket without a valid player"); throw new RuntimeException(); } } /** * The chunk list depth can be manipulated up to the maximal grant allowed for the mod. This value is configurable. Once the maximum is reached, * the least recently forced chunk, by original registration time, is removed from the forced chunk list. * * @param depth The new depth to set */ public void setChunkListDepth(int depth) { if (depth > getMaxChunkDepthFor(modId) || (depth <= 0 && getMaxChunkDepthFor(modId) > 0)) { FMLLog.warning("The mod %s tried to modify the chunk ticket depth to: %d, its allowed maximum is: %d", modId, depth, getMaxChunkDepthFor(modId)); } else { this.maxDepth = depth; } } /** * Get the maximum chunk depth size * * @return The maximum chunk depth size */ public int getMaxChunkListDepth() { return getMaxChunkDepthFor(modId); } /** * Bind the entity to the ticket for {@link Type#ENTITY} type tickets. Other types will throw a runtime exception. * * @param entity The entity to bind */ public void bindEntity(Entity entity) { if (ticketType!=Type.ENTITY) { throw new RuntimeException("Cannot bind an entity to a non-entity ticket"); } this.entity = entity; } /** * Retrieve the {@link NBTTagCompound} that stores mod specific data for the chunk ticket. * Example data to store would be a TileEntity or Block location. This is persisted with the ticket and * provided to the {@link LoadingCallback} for the mod. It is recommended to use this to recover * useful state information for the forced chunks. * * @return The custom compound tag for mods to store additional chunkloading data */ public NBTTagCompound getModData() { if (this.modData == null) { this.modData = new NBTTagCompound(); } return modData; } /** * Get the entity associated with this {@link Type#ENTITY} type ticket * @return */ public Entity getEntity() { return entity; } /** * Is this a player associated ticket rather than a mod associated ticket? * * @return */ public boolean isPlayerTicket() { return player != null; } /** * Get the player associated with this ticket * @return */ public String getPlayerName() { return player; } } static void loadWorld(World world) { ArrayListMultimap<String, Ticket> newTickets = ArrayListMultimap.<String, Ticket>create(); tickets.put(world, newTickets); SetMultimap<ChunkCoordIntPair,Ticket> forcedChunkMap = LinkedHashMultimap.create(); forcedChunks.put(world, forcedChunkMap); if (!(world instanceof WorldServer)) { return; } dormantChunkCache.put(world, CacheBuilder.newBuilder().maximumSize(dormantChunkCacheSize).<Long, Chunk>build()); WorldServer worldServer = (WorldServer) world; File chunkDir = worldServer.getChunkSaveLocation(); File chunkLoaderData = new File(chunkDir, "forcedchunks.dat"); if (chunkLoaderData.exists() && chunkLoaderData.isFile()) { ArrayListMultimap<String, Ticket> loadedTickets = ArrayListMultimap.<String, Ticket>create(); ArrayListMultimap<String, Ticket> playerLoadedTickets = ArrayListMultimap.<String, Ticket>create(); NBTTagCompound forcedChunkData; try { forcedChunkData = CompressedStreamTools.read(chunkLoaderData); } catch (IOException e) { FMLLog.log(Level.WARNING, e, "Unable to read forced chunk data at %s - it will be ignored", chunkLoaderData.getAbsolutePath()); return; } NBTTagList ticketList = forcedChunkData.getTagList("TicketList"); for (int i = 0; i < ticketList.tagCount(); i++) { NBTTagCompound ticketHolder = (NBTTagCompound) ticketList.tagAt(i); String modId = ticketHolder.getString("Owner"); boolean isPlayer = "Forge".equals(modId); if (!isPlayer && !Loader.isModLoaded(modId)) { FMLLog.warning("Found chunkloading data for mod %s which is currently not available or active - it will be removed from the world save", modId); continue; } if (!isPlayer && !callbacks.containsKey(modId)) { FMLLog.warning("The mod %s has registered persistent chunkloading data but doesn't seem to want to be called back with it - it will be removed from the world save", modId); continue; } NBTTagList tickets = ticketHolder.getTagList("Tickets"); for (int j = 0; j < tickets.tagCount(); j++) { NBTTagCompound ticket = (NBTTagCompound) tickets.tagAt(j); modId = ticket.hasKey("ModId") ? ticket.getString("ModId") : modId; Type type = Type.values()[ticket.getByte("Type")]; byte ticketChunkDepth = ticket.getByte("ChunkListDepth"); Ticket tick = new Ticket(modId, type, world); if (ticket.hasKey("ModData")) { tick.modData = ticket.getCompoundTag("ModData"); } if (ticket.hasKey("Player")) { tick.player = ticket.getString("Player"); playerLoadedTickets.put(tick.modId, tick); playerTickets.put(tick.player, tick); } else { loadedTickets.put(modId, tick); } if (type == Type.ENTITY) { tick.entityChunkX = ticket.getInteger("chunkX"); tick.entityChunkZ = ticket.getInteger("chunkZ"); UUID uuid = new UUID(ticket.getLong("PersistentIDMSB"), ticket.getLong("PersistentIDLSB")); // add the ticket to the "pending entity" list pendingEntities.put(uuid, tick); } } } for (Ticket tick : ImmutableSet.copyOf(pendingEntities.values())) { if (tick.ticketType == Type.ENTITY && tick.entity == null) { // force the world to load the entity's chunk // the load will come back through the loadEntity method and attach the entity // to the ticket world.getChunkFromChunkCoords(tick.entityChunkX, tick.entityChunkZ); } } for (Ticket tick : ImmutableSet.copyOf(pendingEntities.values())) { if (tick.ticketType == Type.ENTITY && tick.entity == null) { FMLLog.warning("Failed to load persistent chunkloading entity %s from store.", pendingEntities.inverse().get(tick)); loadedTickets.remove(tick.modId, tick); } } pendingEntities.clear(); // send callbacks for (String modId : loadedTickets.keySet()) { LoadingCallback loadingCallback = callbacks.get(modId); int maxTicketLength = getMaxTicketLengthFor(modId); List<Ticket> tickets = loadedTickets.get(modId); if (loadingCallback instanceof OrderedLoadingCallback) { OrderedLoadingCallback orderedLoadingCallback = (OrderedLoadingCallback) loadingCallback; tickets = orderedLoadingCallback.ticketsLoaded(ImmutableList.copyOf(tickets), world, maxTicketLength); } if (tickets.size() > maxTicketLength) { FMLLog.warning("The mod %s has too many open chunkloading tickets %d. Excess will be dropped", modId, tickets.size()); tickets.subList(maxTicketLength, tickets.size()).clear(); } ForgeChunkManager.tickets.get(world).putAll(modId, tickets); loadingCallback.ticketsLoaded(ImmutableList.copyOf(tickets), world); } for (String modId : playerLoadedTickets.keySet()) { LoadingCallback loadingCallback = callbacks.get(modId); List<Ticket> tickets = playerLoadedTickets.get(modId); ForgeChunkManager.tickets.get(world).putAll("Forge", tickets); loadingCallback.ticketsLoaded(ImmutableList.copyOf(tickets), world); } } } /** * Set a chunkloading callback for the supplied mod object * * @param mod The mod instance registering the callback * @param callback The code to call back when forced chunks are loaded */ public static void setForcedChunkLoadingCallback(Object mod, LoadingCallback callback) { ModContainer container = getContainer(mod); if (container == null) { FMLLog.warning("Unable to register a callback for an unknown mod %s (%s : %x)", mod, mod.getClass().getName(), System.identityHashCode(mod)); return; } callbacks.put(container.getModId(), callback); } /** * Discover the available tickets for the mod in the world * * @param mod The mod that will own the tickets * @param world The world * @return The count of tickets left for the mod in the supplied world */ public static int ticketCountAvailableFor(Object mod, World world) { ModContainer container = getContainer(mod); if (container!=null) { String modId = container.getModId(); int allowedCount = getMaxTicketLengthFor(modId); return allowedCount - tickets.get(world).get(modId).size(); } else { return 0; } } private static ModContainer getContainer(Object mod) { ModContainer container = Loader.instance().getModObjectList().inverse().get(mod); return container; } private static int getMaxTicketLengthFor(String modId) { int allowedCount = ticketConstraints.containsKey(modId) && overridesEnabled ? ticketConstraints.get(modId) : defaultMaxCount; return allowedCount; } private static int getMaxChunkDepthFor(String modId) { int allowedCount = chunkConstraints.containsKey(modId) && overridesEnabled ? chunkConstraints.get(modId) : defaultMaxChunks; return allowedCount; } public static Ticket requestPlayerTicket(Object mod, EntityPlayer player, World world, Type type) { ModContainer mc = getContainer(mod); if (mc == null) { FMLLog.log(Level.SEVERE, "Failed to locate the container for mod instance %s (%s : %x)", mod, mod.getClass().getName(), System.identityHashCode(mod)); return null; } if (playerTickets.get(player.getEntityName()).size()>playerTicketLength) { FMLLog.warning("Unable to assign further chunkloading tickets to player %s (on behalf of mod %s)", player.getEntityName(), mc.getModId()); return null; } Ticket ticket = new Ticket(mc.getModId(),type,world,player); playerTickets.put(player.getEntityName(), ticket); tickets.get(world).put("Forge", ticket); return ticket; } /** * Request a chunkloading ticket of the appropriate type for the supplied mod * * @param mod The mod requesting a ticket * @param world The world in which it is requesting the ticket * @param type The type of ticket * @return A ticket with which to register chunks for loading, or null if no further tickets are available */ public static Ticket requestTicket(Object mod, World world, Type type) { ModContainer container = getContainer(mod); if (container == null) { FMLLog.log(Level.SEVERE, "Failed to locate the container for mod instance %s (%s : %x)", mod, mod.getClass().getName(), System.identityHashCode(mod)); return null; } String modId = container.getModId(); if (!callbacks.containsKey(modId)) { FMLLog.severe("The mod %s has attempted to request a ticket without a listener in place", modId); throw new RuntimeException("Invalid ticket request"); } int allowedCount = ticketConstraints.containsKey(modId) ? ticketConstraints.get(modId) : defaultMaxCount; if (tickets.get(world).get(modId).size() >= allowedCount) { FMLLog.info("The mod %s has attempted to allocate a chunkloading ticket beyond it's currently allocated maximum : %d", modId, allowedCount); return null; } Ticket ticket = new Ticket(modId, type, world); tickets.get(world).put(modId, ticket); return ticket; } /** * Release the ticket back to the system. This will also unforce any chunks held by the ticket so that they can be unloaded and/or stop ticking. * * @param ticket The ticket to release */ public static void releaseTicket(Ticket ticket) { if (ticket == null) { return; } if (ticket.isPlayerTicket() ? !playerTickets.containsValue(ticket) : !tickets.get(ticket.world).containsEntry(ticket.modId, ticket)) { return; } if (ticket.requestedChunks!=null) { for (ChunkCoordIntPair chunk : ImmutableSet.copyOf(ticket.requestedChunks)) { unforceChunk(ticket, chunk); } } if (ticket.isPlayerTicket()) { playerTickets.remove(ticket.player, ticket); tickets.get(ticket.world).remove("Forge",ticket); } else { tickets.get(ticket.world).remove(ticket.modId, ticket); } } /** * Force the supplied chunk coordinate to be loaded by the supplied ticket. If the ticket's {@link Ticket#maxDepth} is exceeded, the least * recently registered chunk is unforced and may be unloaded. * It is safe to force the chunk several times for a ticket, it will not generate duplication or change the ordering. * * @param ticket The ticket registering the chunk * @param chunk The chunk to force */ public static void forceChunk(Ticket ticket, ChunkCoordIntPair chunk) { if (ticket == null || chunk == null) { return; } if (ticket.ticketType == Type.ENTITY && ticket.entity == null) { throw new RuntimeException("Attempted to use an entity ticket to force a chunk, without an entity"); } if (ticket.isPlayerTicket() ? !playerTickets.containsValue(ticket) : !tickets.get(ticket.world).containsEntry(ticket.modId, ticket)) { FMLLog.severe("The mod %s attempted to force load a chunk with an invalid ticket. This is not permitted.", ticket.modId); return; } ticket.requestedChunks.add(chunk); forcedChunks.get(ticket.world).put(chunk, ticket); if (ticket.maxDepth > 0 && ticket.requestedChunks.size() > ticket.maxDepth) { ChunkCoordIntPair removed = ticket.requestedChunks.iterator().next(); unforceChunk(ticket,removed); } } /** * Reorganize the internal chunk list so that the chunk supplied is at the *end* of the list * This helps if you wish to guarantee a certain "automatic unload ordering" for the chunks * in the ticket list * * @param ticket The ticket holding the chunk list * @param chunk The chunk you wish to push to the end (so that it would be unloaded last) */ public static void reorderChunk(Ticket ticket, ChunkCoordIntPair chunk) { if (ticket == null || chunk == null || !ticket.requestedChunks.contains(chunk)) { return; } ticket.requestedChunks.remove(chunk); ticket.requestedChunks.add(chunk); } /** * Unforce the supplied chunk, allowing it to be unloaded and stop ticking. * * @param ticket The ticket holding the chunk * @param chunk The chunk to unforce */ public static void unforceChunk(Ticket ticket, ChunkCoordIntPair chunk) { if (ticket == null || chunk == null) { return; } ticket.requestedChunks.remove(chunk); forcedChunks.get(ticket.world).remove(chunk, ticket); } static void loadConfiguration() { for (String mod : config.categories.keySet()) { if (mod.equals("Forge") || mod.equals("defaults")) { continue; } Property modTC = config.get(mod, "maximumTicketCount", 200); Property modCPT = config.get(mod, "maximumChunksPerTicket", 25); ticketConstraints.put(mod, modTC.getInt(200)); chunkConstraints.put(mod, modCPT.getInt(25)); } config.save(); } /** * The list of persistent chunks in the world. This set is immutable. * @param world * @return */ public static SetMultimap<ChunkCoordIntPair, Ticket> getPersistentChunksFor(World world) { return forcedChunks.containsKey(world) ? ImmutableSetMultimap.copyOf(forcedChunks.get(world)) : ImmutableSetMultimap.<ChunkCoordIntPair,Ticket>of(); } static void saveWorld(World world) { // only persist persistent worlds if (!(world instanceof WorldServer)) { return; } WorldServer worldServer = (WorldServer) world; File chunkDir = worldServer.getChunkSaveLocation(); File chunkLoaderData = new File(chunkDir, "forcedchunks.dat"); NBTTagCompound forcedChunkData = new NBTTagCompound(); NBTTagList ticketList = new NBTTagList(); forcedChunkData.setTag("TicketList", ticketList); Multimap<String, Ticket> ticketSet = tickets.get(worldServer); for (String modId : ticketSet.keySet()) { NBTTagCompound ticketHolder = new NBTTagCompound(); ticketList.appendTag(ticketHolder); ticketHolder.setString("Owner", modId); NBTTagList tickets = new NBTTagList(); ticketHolder.setTag("Tickets", tickets); for (Ticket tick : ticketSet.get(modId)) { NBTTagCompound ticket = new NBTTagCompound(); ticket.setByte("Type", (byte) tick.ticketType.ordinal()); ticket.setByte("ChunkListDepth", (byte) tick.maxDepth); if (tick.isPlayerTicket()) { ticket.setString("ModId", tick.modId); ticket.setString("Player", tick.player); } if (tick.modData != null) { ticket.setCompoundTag("ModData", tick.modData); } if (tick.ticketType == Type.ENTITY && tick.entity != null) { ticket.setInteger("chunkX", MathHelper.floor_double(tick.entity.chunkCoordX)); ticket.setInteger("chunkZ", MathHelper.floor_double(tick.entity.chunkCoordZ)); ticket.setLong("PersistentIDMSB", tick.entity.getPersistentID().getMostSignificantBits()); ticket.setLong("PersistentIDLSB", tick.entity.getPersistentID().getLeastSignificantBits()); tickets.appendTag(ticket); } else if (tick.ticketType != Type.ENTITY) { tickets.appendTag(ticket); } } } try { CompressedStreamTools.write(forcedChunkData, chunkLoaderData); } catch (IOException e) { FMLLog.log(Level.WARNING, e, "Unable to write forced chunk data to %s - chunkloading won't work", chunkLoaderData.getAbsolutePath()); return; } } static void loadEntity(Entity entity) { UUID id = entity.getPersistentID(); Ticket tick = pendingEntities.get(id); if (tick != null) { tick.bindEntity(entity); pendingEntities.remove(id); } } public static void putDormantChunk(long coords, Chunk chunk) { Cache<Long, Chunk> cache = dormantChunkCache.get(chunk.worldObj); if (cache != null) { cache.put(coords, chunk); } } public static Chunk fetchDormantChunk(long coords, World world) { Cache<Long, Chunk> cache = dormantChunkCache.get(world); return cache == null ? null : cache.getIfPresent(coords); } static void captureConfig(File configDir) { cfgFile = new File(configDir,"forgeChunkLoading.cfg"); config = new Configuration(cfgFile, true); config.categories.clear(); try { config.load(); } catch (Exception e) { File dest = new File(cfgFile.getParentFile(),"forgeChunkLoading.cfg.bak"); if (dest.exists()) { dest.delete(); } cfgFile.renameTo(dest); FMLLog.log(Level.SEVERE, e, "A critical error occured reading the forgeChunkLoading.cfg file, defaults will be used - the invalid file is backed up at forgeChunkLoading.cfg.bak"); } config.addCustomCategoryComment("defaults", "Default configuration for forge chunk loading control"); Property maxTicketCount = config.get("defaults", "maximumTicketCount", 200); maxTicketCount.comment = "The default maximum ticket count for a mod which does not have an override\n" + "in this file. This is the number of chunk loading requests a mod is allowed to make."; defaultMaxCount = maxTicketCount.getInt(200); Property maxChunks = config.get("defaults", "maximumChunksPerTicket", 25); maxChunks.comment = "The default maximum number of chunks a mod can force, per ticket, \n" + "for a mod without an override. This is the maximum number of chunks a single ticket can force."; defaultMaxChunks = maxChunks.getInt(25); Property playerTicketCount = config.get("defaults", "playetTicketCount", 500); playerTicketCount.comment = "The number of tickets a player can be assigned instead of a mod. This is shared across all mods and it is up to the mods to use it."; playerTicketLength = playerTicketCount.getInt(500); Property dormantChunkCacheSizeProperty = config.get("defaults", "dormantChunkCacheSize", 0); dormantChunkCacheSizeProperty.comment = "Unloaded chunks can first be kept in a dormant cache for quicker\n" + "loading times. Specify the size of that cache here"; dormantChunkCacheSize = dormantChunkCacheSizeProperty.getInt(0); FMLLog.info("Configured a dormant chunk cache size of %d", dormantChunkCacheSizeProperty.getInt(0)); Property modOverridesEnabled = config.get("defaults", "enabled", true); modOverridesEnabled.comment = "Are mod overrides enabled?"; overridesEnabled = modOverridesEnabled.getBoolean(true); config.addCustomCategoryComment("Forge", "Sample mod specific control section.\n" + "Copy this section and rename the with the modid for the mod you wish to override.\n" + "A value of zero in either entry effectively disables any chunkloading capabilities\n" + "for that mod"); Property sampleTC = config.get("Forge", "maximumTicketCount", 200); sampleTC.comment = "Maximum ticket count for the mod. Zero disables chunkloading capabilities."; sampleTC = config.get("Forge", "maximumChunksPerTicket", 25); sampleTC.comment = "Maximum chunks per ticket for the mod."; for (String mod : config.categories.keySet()) { if (mod.equals("Forge") || mod.equals("defaults")) { continue; } Property modTC = config.get(mod, "maximumTicketCount", 200); Property modCPT = config.get(mod, "maximumChunksPerTicket", 25); } } public static Map<String,Property> getConfigMapFor(Object mod) { ModContainer container = getContainer(mod); if (container != null) { Map<String, Property> map = config.categories.get(container.getModId()); if (map == null) { map = Maps.newHashMap(); config.categories.put(container.getModId(), map); } return map; } return null; } public static void addConfigProperty(Object mod, String propertyName, String value, Property.Type type) { ModContainer container = getContainer(mod); if (container != null) { Map<String, Property> props = config.categories.get(container.getModId()); props.put(propertyName, new Property(propertyName, value, type)); } } }
Add some accessors to teh ChunkLoader tickets.
common/net/minecraftforge/common/ForgeChunkManager.java
Add some accessors to teh ChunkLoader tickets.
Java
lgpl-2.1
38f08ceae15d857bc24b8ef605ec60912033aa9e
0
ontometrics/ontokettle,cwarden/kettle,juanmjacobs/kettle,juanmjacobs/kettle,cwarden/kettle,juanmjacobs/kettle,cwarden/kettle,ontometrics/ontokettle,ontometrics/ontokettle
/********************************************************************** ** ** ** This code belongs to the KETTLE project. ** ** ** ** Kettle, from version 2.2 on, is released into the public domain ** ** under the Lesser GNU Public License (LGPL). ** ** ** ** For more details, please read the document LICENSE.txt, included ** ** in this project ** ** ** ** http://www.kettle.be ** ** [email protected] ** ** ** **********************************************************************/ package be.ibridge.kettle.job.entry; import java.util.ArrayList; import org.eclipse.swt.widgets.Shell; import org.w3c.dom.Node; import be.ibridge.kettle.core.Result; import be.ibridge.kettle.core.database.DatabaseMeta; import be.ibridge.kettle.core.exception.KettleException; import be.ibridge.kettle.core.exception.KettleXMLException; import be.ibridge.kettle.job.Job; import be.ibridge.kettle.job.JobMeta; import be.ibridge.kettle.job.entry.createfile.JobEntryCreateFile; import be.ibridge.kettle.job.entry.deletefile.JobEntryDeleteFile; import be.ibridge.kettle.job.entry.eval.JobEntryEval; import be.ibridge.kettle.job.entry.filecompare.JobEntryFileCompare; import be.ibridge.kettle.job.entry.fileexists.JobEntryFileExists; import be.ibridge.kettle.job.entry.ftp.JobEntryFTP; import be.ibridge.kettle.job.entry.http.JobEntryHTTP; import be.ibridge.kettle.job.entry.job.JobEntryJob; import be.ibridge.kettle.job.entry.mail.JobEntryMail; import be.ibridge.kettle.job.entry.mysqlbulkload.JobEntryMysqlBulkLoad; import be.ibridge.kettle.job.entry.mysqlbulkfile.JobEntryMysqlBulkFile; import be.ibridge.kettle.job.entry.msgboxinfo.JobEntryMsgBoxInfo; import be.ibridge.kettle.job.entry.delay.JobEntryDelay; import be.ibridge.kettle.job.entry.zipfile.JobEntryZipFile; import be.ibridge.kettle.job.entry.xslt.JobEntryXSLT; import be.ibridge.kettle.job.entry.sftp.JobEntrySFTP; import be.ibridge.kettle.job.entry.sftpput.JobEntrySFTPPUT; import be.ibridge.kettle.job.entry.shell.JobEntryShell; import be.ibridge.kettle.job.entry.special.JobEntrySpecial; import be.ibridge.kettle.job.entry.sql.JobEntrySQL; import be.ibridge.kettle.job.entry.tableexists.JobEntryTableExists; import be.ibridge.kettle.job.entry.trans.JobEntryTrans; import be.ibridge.kettle.job.entry.waitforfile.JobEntryWaitForFile; import be.ibridge.kettle.job.entry.abort.JobEntryAbort; import be.ibridge.kettle.repository.Repository; /** * Interface for the different JobEntry classes. * * @author Matt * @since 18-06-04 * */ public interface JobEntryInterface { public final static int TYPE_JOBENTRY_NONE = 0; public final static int TYPE_JOBENTRY_TRANSFORMATION = 1; public final static int TYPE_JOBENTRY_JOB = 2; public final static int TYPE_JOBENTRY_SHELL = 3; public final static int TYPE_JOBENTRY_MAIL = 4; public final static int TYPE_JOBENTRY_SQL = 5; public final static int TYPE_JOBENTRY_FTP = 6; public final static int TYPE_JOBENTRY_TABLE_EXISTS = 7; public final static int TYPE_JOBENTRY_FILE_EXISTS = 8; public final static int TYPE_JOBENTRY_EVALUATION = 9; public final static int TYPE_JOBENTRY_SPECIAL = 10; public static final int TYPE_JOBENTRY_SFTP = 11; public static final int TYPE_JOBENTRY_HTTP = 12; public static final int TYPE_JOBENTRY_CREATE_FILE = 13; public static final int TYPE_JOBENTRY_DELETE_FILE = 14; public static final int TYPE_JOBENTRY_WAIT_FOR_FILE = 15; public static final int TYPE_JOBENTRY_SFTPPUT = 16; public static final int TYPE_JOBENTRY_FILE_COMPARE = 17; public static final int TYPE_JOBENTRY_MYSQL_BULK_LOAD= 18; public static final int TYPE_JOBENTRY_MSGBOX_INFO= 19; public static final int TYPE_JOBENTRY_DELAY= 20; public static final int TYPE_JOBENTRY_ZIP_FILE= 21; public static final int TYPE_JOBENTRY_XSLT= 22; public static final int TYPE_JOBENTRY_MYSQL_BULK_FILE= 23; public static final int TYPE_JOBENTRY_ABORT= 24; public final static String typeCode[] = { "-", "TRANS", "JOB", "SHELL", "MAIL", "SQL", "FTP", "TABLE_EXISTS", "FILE_EXISTS", "EVAL", "SPECIAL", "SFTP", "HTTP", "CREATE_FILE", "DELETE_FILE", "WAIT_FOR_FILE", "SFTPPUT", "FILE_COMPARE", "MYSQL_BULK_LOAD", "MSGBOX_INFO", "DELAY", "ZIP_FILE", "XSLT", "MYSQL_BULK_FILE", "ABORT", }; public final static String typeDesc[] = { "-", Messages.getString("JobEntry.Trans.TypeDesc"), Messages.getString("JobEntry.Job.TypeDesc"), Messages.getString("JobEntry.Shell.TypeDesc"), Messages.getString("JobEntry.Mail.TypeDesc"), Messages.getString("JobEntry.SQL.TypeDesc"), Messages.getString("JobEntry.FTP.TypeDesc"), Messages.getString("JobEntry.TableExists.TypeDesc"), Messages.getString("JobEntry.FileExists.TypeDesc"), Messages.getString("JobEntry.Evaluation.TypeDesc"), Messages.getString("JobEntry.Special.TypeDesc"), Messages.getString("JobEntry.SFTP.TypeDesc"), Messages.getString("JobEntry.HTTP.TypeDesc"), Messages.getString("JobEntry.CreateFile.TypeDesc"), Messages.getString("JobEntry.DeleteFile.TypeDesc"), Messages.getString("JobEntry.WaitForFile.TypeDesc"), Messages.getString("JobEntry.SFTPPut.TypeDesc"), Messages.getString("JobEntry.FileCompare.TypeDesc"), Messages.getString("JobEntry.MysqlBulkLoad.TypeDesc"), Messages.getString("JobEntry.MsgBoxInfo.TypeDesc"), Messages.getString("JobEntry.Delay.TypeDesc"), Messages.getString("JobEntry.ZipFile.TypeDesc"), Messages.getString("JobEntry.XSLT.TypeDesc"), Messages.getString("JobEntry.MysqlBulkFile.TypeDesc"), Messages.getString("JobEntry.Abort.TypeDesc"), }; public final static String icon_filename[] = { "", "TRN.png", "JOB.png", "SHL.png", "MAIL.png", "SQL.png", "FTP.png", "TEX.png", "FEX.png", "RES.png", "", "SFT.png", "WEB.png", "CFJ.png", "DFJ.png", "WFF.png", "SFP.png", "BFC.png", "MBL.png", "INF.png", "DLT.png", "ZIP.png", "XSLT.png", "MBF.png", "ABR.png", }; public final static String type_tooltip_desc[] = { "", Messages.getString("JobEntry.Trans.Tooltip"), Messages.getString("JobEntry.Job.Tooltip"), Messages.getString("JobEntry.Shell.Tooltip"), Messages.getString("JobEntry.Mail.Tooltip"), Messages.getString("JobEntry.SQL.Tooltip"), Messages.getString("JobEntry.FTP.Tooltip"), Messages.getString("JobEntry.TableExists.Tooltip"), Messages.getString("JobEntry.FileExists.Tooltip"), Messages.getString("JobEntry.Evaluation.Tooltip"), Messages.getString("JobEntry.Special.Tooltip"), Messages.getString("JobEntry.SFTP.Tooltip"), Messages.getString("JobEntry.HTTP.Tooltip"), Messages.getString("JobEntry.CreateFile.Tooltip"), Messages.getString("JobEntry.DeleteFile.Tooltip"), Messages.getString("JobEntry.WaitForFile.Tooltip"), Messages.getString("JobEntry.SFTPPut.Tooltip"), Messages.getString("JobEntry.FileCompare.Tooltip"), Messages.getString("JobEntry.MysqlBulkLoad.Tooltip"), Messages.getString("JobEntry.MsgBoxInfo.Tooltip"), Messages.getString("JobEntry.Delay.Tooltip"), Messages.getString("JobEntry.ZipFile.Tooltip"), Messages.getString("JobEntry.XSLT.Tooltip"), Messages.getString("JobEntry.MysqlBulkFile.Tooltip"), Messages.getString("JobEntry.Abort.Tooltip"), }; public final static Class type_classname[] = { null, JobEntryTrans.class, JobEntryJob.class, JobEntryShell.class, JobEntryMail.class, JobEntrySQL.class, JobEntryFTP.class, JobEntryTableExists.class, JobEntryFileExists.class, JobEntryEval.class, JobEntrySpecial.class, JobEntrySFTP.class, JobEntryHTTP.class, JobEntryCreateFile.class, JobEntryDeleteFile.class, JobEntryWaitForFile.class, JobEntrySFTPPUT.class, JobEntryFileCompare.class, JobEntryMysqlBulkLoad.class, JobEntryMsgBoxInfo.class, JobEntryDelay.class, JobEntryZipFile.class, JobEntryXSLT.class, JobEntryMysqlBulkFile.class, JobEntryAbort.class, }; public Result execute(Result prev_result, int nr, Repository rep, Job parentJob) throws KettleException; public void clear(); public long getID(); public void setID(long id); public String getName(); public void setName(String name); public String getDescription(); public void setDescription(String description); public void setChanged(); public void setChanged(boolean ch); public boolean hasChanged(); public void loadXML(Node entrynode, ArrayList databases, Repository rep) throws KettleXMLException; public String getXML(); public void loadRep(Repository rep, long id_jobentry, ArrayList databases) throws KettleException; public void saveRep(Repository rep, long id_job) throws KettleException; public int getType(); public String getTypeCode(); public String getPluginID(); public boolean isStart(); public boolean isDummy(); public Object clone(); public boolean resetErrorsBeforeExecution(); public boolean evaluates(); public boolean isUnconditional(); public boolean isEvaluation(); public boolean isTransformation(); public boolean isJob(); public boolean isShell(); public boolean isMail(); public boolean isSpecial(); public ArrayList getSQLStatements(Repository repository) throws KettleException; public JobEntryDialogInterface getDialog(Shell shell,JobEntryInterface jei,JobMeta jobMeta,String jobName,Repository rep); public String getFilename(); public String getRealFilename(); /** * This method returns all the database connections that are used by the job entry. * @return an array of database connections meta-data. * Return an empty array if no connections are used. */ public DatabaseMeta[] getUsedDatabaseConnections(); public void setPluginID(String id); }
src/be/ibridge/kettle/job/entry/JobEntryInterface.java
/********************************************************************** ** ** ** This code belongs to the KETTLE project. ** ** ** ** Kettle, from version 2.2 on, is released into the public domain ** ** under the Lesser GNU Public License (LGPL). ** ** ** ** For more details, please read the document LICENSE.txt, included ** ** in this project ** ** ** ** http://www.kettle.be ** ** [email protected] ** ** ** **********************************************************************/ package be.ibridge.kettle.job.entry; import java.util.ArrayList; import org.eclipse.swt.widgets.Shell; import org.w3c.dom.Node; import be.ibridge.kettle.core.Result; import be.ibridge.kettle.core.database.DatabaseMeta; import be.ibridge.kettle.core.exception.KettleException; import be.ibridge.kettle.core.exception.KettleXMLException; import be.ibridge.kettle.job.Job; import be.ibridge.kettle.job.JobMeta; import be.ibridge.kettle.job.entry.createfile.JobEntryCreateFile; import be.ibridge.kettle.job.entry.deletefile.JobEntryDeleteFile; import be.ibridge.kettle.job.entry.eval.JobEntryEval; import be.ibridge.kettle.job.entry.filecompare.JobEntryFileCompare; import be.ibridge.kettle.job.entry.fileexists.JobEntryFileExists; import be.ibridge.kettle.job.entry.ftp.JobEntryFTP; import be.ibridge.kettle.job.entry.http.JobEntryHTTP; import be.ibridge.kettle.job.entry.job.JobEntryJob; import be.ibridge.kettle.job.entry.mail.JobEntryMail; import be.ibridge.kettle.job.entry.mysqlbulkload.JobEntryMysqlBulkLoad; import be.ibridge.kettle.job.entry.mysqlbulkfile.JobEntryMysqlBulkFile; import be.ibridge.kettle.job.entry.msgboxinfo.JobEntryMsgBoxInfo; import be.ibridge.kettle.job.entry.delay.JobEntryDelay; import be.ibridge.kettle.job.entry.zipfile.JobEntryZipFile; import be.ibridge.kettle.job.entry.xslt.JobEntryXSLT; import be.ibridge.kettle.job.entry.sftp.JobEntrySFTP; import be.ibridge.kettle.job.entry.sftpput.JobEntrySFTPPUT; import be.ibridge.kettle.job.entry.shell.JobEntryShell; import be.ibridge.kettle.job.entry.special.JobEntrySpecial; import be.ibridge.kettle.job.entry.sql.JobEntrySQL; import be.ibridge.kettle.job.entry.tableexists.JobEntryTableExists; import be.ibridge.kettle.job.entry.trans.JobEntryTrans; import be.ibridge.kettle.job.entry.waitforfile.JobEntryWaitForFile; import be.ibridge.kettle.repository.Repository; /** * Interface for the different JobEntry classes. * * @author Matt * @since 18-06-04 * */ public interface JobEntryInterface { public final static int TYPE_JOBENTRY_NONE = 0; public final static int TYPE_JOBENTRY_TRANSFORMATION = 1; public final static int TYPE_JOBENTRY_JOB = 2; public final static int TYPE_JOBENTRY_SHELL = 3; public final static int TYPE_JOBENTRY_MAIL = 4; public final static int TYPE_JOBENTRY_SQL = 5; public final static int TYPE_JOBENTRY_FTP = 6; public final static int TYPE_JOBENTRY_TABLE_EXISTS = 7; public final static int TYPE_JOBENTRY_FILE_EXISTS = 8; public final static int TYPE_JOBENTRY_EVALUATION = 9; public final static int TYPE_JOBENTRY_SPECIAL = 10; public static final int TYPE_JOBENTRY_SFTP = 11; public static final int TYPE_JOBENTRY_HTTP = 12; public static final int TYPE_JOBENTRY_CREATE_FILE = 13; public static final int TYPE_JOBENTRY_DELETE_FILE = 14; public static final int TYPE_JOBENTRY_WAIT_FOR_FILE = 15; public static final int TYPE_JOBENTRY_SFTPPUT = 16; public static final int TYPE_JOBENTRY_FILE_COMPARE = 17; public static final int TYPE_JOBENTRY_MYSQL_BULK_LOAD= 18; public static final int TYPE_JOBENTRY_MSGBOX_INFO= 19; public static final int TYPE_JOBENTRY_DELAY= 20; public static final int TYPE_JOBENTRY_ZIP_FILE= 21; public static final int TYPE_JOBENTRY_XSLT= 22; public static final int TYPE_JOBENTRY_MYSQL_BULK_FILE= 23; public final static String typeCode[] = { "-", "TRANS", "JOB", "SHELL", "MAIL", "SQL", "FTP", "TABLE_EXISTS", "FILE_EXISTS", "EVAL", "SPECIAL", "SFTP", "HTTP", "CREATE_FILE", "DELETE_FILE", "WAIT_FOR_FILE", "SFTPPUT", "FILE_COMPARE", "MYSQL_BULK_LOAD", "MSGBOX_INFO", "DELAY", "ZIP_FILE", "XSLT", "MYSQL_BULK_FILE", }; public final static String typeDesc[] = { "-", Messages.getString("JobEntry.Trans.TypeDesc"), Messages.getString("JobEntry.Job.TypeDesc"), Messages.getString("JobEntry.Shell.TypeDesc"), Messages.getString("JobEntry.Mail.TypeDesc"), Messages.getString("JobEntry.SQL.TypeDesc"), Messages.getString("JobEntry.FTP.TypeDesc"), Messages.getString("JobEntry.TableExists.TypeDesc"), Messages.getString("JobEntry.FileExists.TypeDesc"), Messages.getString("JobEntry.Evaluation.TypeDesc"), Messages.getString("JobEntry.Special.TypeDesc"), Messages.getString("JobEntry.SFTP.TypeDesc"), Messages.getString("JobEntry.HTTP.TypeDesc"), Messages.getString("JobEntry.CreateFile.TypeDesc"), Messages.getString("JobEntry.DeleteFile.TypeDesc"), Messages.getString("JobEntry.WaitForFile.TypeDesc"), Messages.getString("JobEntry.SFTPPut.TypeDesc"), Messages.getString("JobEntry.FileCompare.TypeDesc"), Messages.getString("JobEntry.MysqlBulkLoad.TypeDesc"), Messages.getString("JobEntry.MsgBoxInfo.TypeDesc"), Messages.getString("JobEntry.Delay.TypeDesc"), Messages.getString("JobEntry.ZipFile.TypeDesc"), Messages.getString("JobEntry.XSLT.TypeDesc"), Messages.getString("JobEntry.MysqlBulkFile.TypeDesc"), }; public final static String icon_filename[] = { "", "TRN.png", "JOB.png", "SHL.png", "MAIL.png", "SQL.png", "FTP.png", "TEX.png", "FEX.png", "RES.png", "", "SFT.png", "WEB.png", "CFJ.png", "DFJ.png", "WFF.png", "SFP.png", "BFC.png", "MBL.png", "INF.png", "DLT.png", "ZIP.png", "XSLT.png", "MBF.png", }; public final static String type_tooltip_desc[] = { "", Messages.getString("JobEntry.Trans.Tooltip"), Messages.getString("JobEntry.Job.Tooltip"), Messages.getString("JobEntry.Shell.Tooltip"), Messages.getString("JobEntry.Mail.Tooltip"), Messages.getString("JobEntry.SQL.Tooltip"), Messages.getString("JobEntry.FTP.Tooltip"), Messages.getString("JobEntry.TableExists.Tooltip"), Messages.getString("JobEntry.FileExists.Tooltip"), Messages.getString("JobEntry.Evaluation.Tooltip"), Messages.getString("JobEntry.Special.Tooltip"), Messages.getString("JobEntry.SFTP.Tooltip"), Messages.getString("JobEntry.HTTP.Tooltip"), Messages.getString("JobEntry.CreateFile.Tooltip"), Messages.getString("JobEntry.DeleteFile.Tooltip"), Messages.getString("JobEntry.WaitForFile.Tooltip"), Messages.getString("JobEntry.SFTPPut.Tooltip"), Messages.getString("JobEntry.FileCompare.Tooltip"), Messages.getString("JobEntry.MysqlBulkLoad.Tooltip"), Messages.getString("JobEntry.MsgBoxInfo.Tooltip"), Messages.getString("JobEntry.Delay.Tooltip"), Messages.getString("JobEntry.ZipFile.Tooltip"), Messages.getString("JobEntry.XSLT.Tooltip"), Messages.getString("JobEntry.MysqlBulkFile.Tooltip"), }; public final static Class type_classname[] = { null, JobEntryTrans.class, JobEntryJob.class, JobEntryShell.class, JobEntryMail.class, JobEntrySQL.class, JobEntryFTP.class, JobEntryTableExists.class, JobEntryFileExists.class, JobEntryEval.class, JobEntrySpecial.class, JobEntrySFTP.class, JobEntryHTTP.class, JobEntryCreateFile.class, JobEntryDeleteFile.class, JobEntryWaitForFile.class, JobEntrySFTPPUT.class, JobEntryFileCompare.class, JobEntryMysqlBulkLoad.class, JobEntryMsgBoxInfo.class, JobEntryDelay.class, JobEntryZipFile.class, JobEntryXSLT.class, JobEntryMysqlBulkFile.class, }; public Result execute(Result prev_result, int nr, Repository rep, Job parentJob) throws KettleException; public void clear(); public long getID(); public void setID(long id); public String getName(); public void setName(String name); public String getDescription(); public void setDescription(String description); public void setChanged(); public void setChanged(boolean ch); public boolean hasChanged(); public void loadXML(Node entrynode, ArrayList databases, Repository rep) throws KettleXMLException; public String getXML(); public void loadRep(Repository rep, long id_jobentry, ArrayList databases) throws KettleException; public void saveRep(Repository rep, long id_job) throws KettleException; public int getType(); public String getTypeCode(); public String getPluginID(); public boolean isStart(); public boolean isDummy(); public Object clone(); public boolean resetErrorsBeforeExecution(); public boolean evaluates(); public boolean isUnconditional(); public boolean isEvaluation(); public boolean isTransformation(); public boolean isJob(); public boolean isShell(); public boolean isMail(); public boolean isSpecial(); public ArrayList getSQLStatements(Repository repository) throws KettleException; public JobEntryDialogInterface getDialog(Shell shell,JobEntryInterface jei,JobMeta jobMeta,String jobName,Repository rep); public String getFilename(); public String getRealFilename(); /** * This method returns all the database connections that are used by the job entry. * @return an array of database connections meta-data. * Return an empty array if no connections are used. */ public DatabaseMeta[] getUsedDatabaseConnections(); public void setPluginID(String id); }
CRQ5006 git-svn-id: 9499f031eb5c9fb9d11553a06c92651e5446d292@2939 5fb7f6ec-07c1-534a-b4ca-9155e429e800
src/be/ibridge/kettle/job/entry/JobEntryInterface.java
CRQ5006
Java
apache-2.0
8f32d88a8d7a3a43226dbc536ee5d2f9af6142d1
0
spring-cloud-samples/spring-cloud-contract-samples,spring-cloud-samples/spring-cloud-contract-samples,spring-cloud-samples/spring-cloud-contract-samples,spring-cloud-samples/spring-cloud-contract-samples,spring-cloud-samples/spring-cloud-contract-samples
package com.example; //remove::start[] import javax.annotation.Nullable; import javax.net.ssl.SSLException; import com.github.tomakehurst.wiremock.core.WireMockConfiguration; import io.grpc.CallOptions; import io.grpc.Channel; import io.grpc.ClientCall; import io.grpc.ClientInterceptor; import io.grpc.Metadata; import io.grpc.MethodDescriptor; import io.grpc.Status; import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; import io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder; import io.grpc.netty.shaded.io.netty.handler.ssl.util.InsecureTrustManagerFactory; import net.devh.boot.grpc.client.autoconfigure.GrpcClientAutoConfiguration; import net.devh.boot.grpc.client.channelfactory.GrpcChannelConfigurer; import net.devh.boot.grpc.client.inject.GrpcClient; import org.assertj.core.api.BDDAssertions; import org.junit.jupiter.api.Assumptions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; import org.springframework.boot.autoconfigure.ImportAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.cloud.contract.stubrunner.HttpServerStubConfiguration; import org.springframework.cloud.contract.stubrunner.junit.StubRunnerExtension; import org.springframework.cloud.contract.stubrunner.provider.wiremock.WireMockHttpServerStubConfigurer; import org.springframework.cloud.contract.stubrunner.spring.StubRunnerProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.util.StringUtils; /** * @author Marcin Grzejszczak */ @SpringBootTest(webEnvironment = WebEnvironment.NONE, classes = GrpcTests.TestConfiguration.class, properties = { "grpc.client.beerService.address=static://localhost:5432", "grpc.client.beerService.negotiationType=TLS" }) // remove::end[] public class GrpcTests { //remove::start[] @GrpcClient(value = "beerService", interceptorNames = "fixedStatusSendingClientInterceptor") BeerServiceGrpc.BeerServiceBlockingStub beerServiceBlockingStub; int port; @RegisterExtension static StubRunnerExtension rule = new StubRunnerExtension() .downloadStub("com.example", "beer-api-producer-grpc") // With WireMock PlainText mode // .withPort(5432) .stubsMode(StubRunnerProperties.StubsMode.LOCAL) .withHttpServerStubConfigurer(MyWireMockConfigurer.class); @BeforeAll public static void beforeClass() { Assumptions.assumeTrue(atLeast300(), "Spring Cloud Contract must be in version at least 3.0.0"); Assumptions.assumeTrue(StringUtils.isEmpty(System.getenv("OLD_PRODUCER_TRAIN")), "Env var OLD_PRODUCER_TRAIN must not be set"); } @BeforeEach public void setupPort() { this.port = rule.findStubUrl("beer-api-producer-grpc").getPort(); } private static boolean atLeast300() { try { Class.forName("org.springframework.cloud.contract.verifier.dsl.wiremock.SpringCloudContractRequestMatcher"); } catch (Exception ex) { return false; } return true; } // tag::tests[] @Test public void should_give_me_a_beer_when_im_old_enough() throws Exception { Response response = beerServiceBlockingStub.check(PersonToCheck.newBuilder().setAge(23).build()); BDDAssertions.then(response.getStatus()).isEqualTo(Response.BeerCheckStatus.OK); } @Test public void should_reject_a_beer_when_im_too_young() throws Exception { Response response = beerServiceBlockingStub.check(PersonToCheck.newBuilder().setAge(17).build()); // TODO: If someone knows how to do this properly for default responses that would be helpful response = response == null ? Response.newBuilder().build() : response; BDDAssertions.then(response.getStatus()).isEqualTo(Response.BeerCheckStatus.NOT_OK); } // end::tests[] // Not necessary with WireMock PlainText mode static class MyWireMockConfigurer extends WireMockHttpServerStubConfigurer { @Override public WireMockConfiguration configure(WireMockConfiguration httpStubConfiguration, HttpServerStubConfiguration httpServerStubConfiguration) { return httpStubConfiguration .httpsPort(5432); } } @Configuration @ImportAutoConfiguration(GrpcClientAutoConfiguration.class) static class TestConfiguration { // Not necessary with WireMock PlainText mode @Bean public GrpcChannelConfigurer keepAliveClientConfigurer() { return (channelBuilder, name) -> { if (channelBuilder instanceof NettyChannelBuilder) { try { ((NettyChannelBuilder) channelBuilder) .sslContext(GrpcSslContexts.forClient() .trustManager(InsecureTrustManagerFactory.INSTANCE) .build()); } catch (SSLException e) { throw new IllegalStateException(e); } } }; } /** * GRPC client interceptor that sets the returned status always to OK. * You might want to change the return status depending on the received stub payload. * * Hopefully in the future this will be unnecessary and will be removed. */ @Bean ClientInterceptor fixedStatusSendingClientInterceptor() { return new ClientInterceptor() { @Override public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) { ClientCall<ReqT, RespT> call = next.newCall(method, callOptions); return new ClientCall<ReqT, RespT>() { @Override public void start(Listener<RespT> responseListener, Metadata headers) { Listener<RespT> listener = new Listener<RespT>() { @Override public void onHeaders(Metadata headers) { responseListener.onHeaders(headers); } @Override public void onMessage(RespT message) { responseListener.onMessage(message); } @Override public void onClose(Status status, Metadata trailers) { // TODO: This must be fixed somehow either in Jetty (WireMock) or somewhere else responseListener.onClose(Status.OK, trailers); } @Override public void onReady() { responseListener.onReady(); } }; call.start(listener, headers); } @Override public void request(int numMessages) { call.request(numMessages); } @Override public void cancel(@Nullable String message, @Nullable Throwable cause) { call.cancel(message, cause); } @Override public void halfClose() { call.halfClose(); } @Override public void sendMessage(ReqT message) { call.sendMessage(message); } }; } }; } } //remove::end[] }
consumer_grpc/src/test/java/com/example/GrpcTests.java
package com.example; import javax.annotation.Nullable; import javax.net.ssl.SSLException; import com.github.tomakehurst.wiremock.core.WireMockConfiguration; import io.grpc.CallOptions; import io.grpc.Channel; import io.grpc.ClientCall; import io.grpc.ClientInterceptor; import io.grpc.Metadata; import io.grpc.MethodDescriptor; import io.grpc.Status; import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; import io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder; import io.grpc.netty.shaded.io.netty.handler.ssl.util.InsecureTrustManagerFactory; import net.devh.boot.grpc.client.autoconfigure.GrpcClientAutoConfiguration; import net.devh.boot.grpc.client.channelfactory.GrpcChannelConfigurer; import net.devh.boot.grpc.client.inject.GrpcClient; import org.assertj.core.api.BDDAssertions; import org.junit.jupiter.api.Assumptions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; import org.springframework.boot.autoconfigure.ImportAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.cloud.contract.stubrunner.HttpServerStubConfiguration; import org.springframework.cloud.contract.stubrunner.junit.StubRunnerExtension; import org.springframework.cloud.contract.stubrunner.provider.wiremock.WireMockHttpServerStubConfigurer; import org.springframework.cloud.contract.stubrunner.spring.StubRunnerProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.util.StringUtils; /** * @author Marcin Grzejszczak */ @SpringBootTest(webEnvironment = WebEnvironment.NONE, classes = GrpcTests.TestConfiguration.class, properties = { "grpc.client.beerService.address=static://localhost:5432", "grpc.client.beerService.negotiationType=TLS" }) // @org.junit.Ignore public class GrpcTests { @GrpcClient(value = "beerService", interceptorNames = "fixedStatusSendingClientInterceptor") BeerServiceGrpc.BeerServiceBlockingStub beerServiceBlockingStub; int port; //remove::start[] @RegisterExtension static StubRunnerExtension rule = new StubRunnerExtension() .downloadStub("com.example", "beer-api-producer-grpc") // With WireMock PlainText mode // .withPort(5432) .stubsMode(StubRunnerProperties.StubsMode.LOCAL) .withHttpServerStubConfigurer(MyWireMockConfigurer.class); // remove::end[] @BeforeAll public static void beforeClass() { Assumptions.assumeTrue(atLeast300(), "Spring Cloud Contract must be in version at least 3.0.0"); Assumptions.assumeTrue(StringUtils.isEmpty(System.getenv("OLD_PRODUCER_TRAIN")), "Env var OLD_PRODUCER_TRAIN must not be set"); } @BeforeEach public void setupPort() { //remove::start[] this.port = rule.findStubUrl("beer-api-producer-grpc").getPort(); // remove::end[] } private static boolean atLeast300() { try { Class.forName("org.springframework.cloud.contract.verifier.dsl.wiremock.SpringCloudContractRequestMatcher"); } catch (Exception ex) { return false; } return true; } // remove::end[] // tag::tests[] @Test public void should_give_me_a_beer_when_im_old_enough() throws Exception { //remove::start[] Response response = beerServiceBlockingStub.check(PersonToCheck.newBuilder().setAge(23).build()); BDDAssertions.then(response.getStatus()).isEqualTo(Response.BeerCheckStatus.OK); // remove::end[] } @Test public void should_reject_a_beer_when_im_too_young() throws Exception { //remove::start[] Response response = beerServiceBlockingStub.check(PersonToCheck.newBuilder().setAge(17).build()); // TODO: If someone knows how to do this properly for default responses that would be helpful response = response == null ? Response.newBuilder().build() : response; BDDAssertions.then(response.getStatus()).isEqualTo(Response.BeerCheckStatus.NOT_OK); // remove::end[] } // end::tests[] // Not necessary with WireMock PlainText mode static class MyWireMockConfigurer extends WireMockHttpServerStubConfigurer { @Override public WireMockConfiguration configure(WireMockConfiguration httpStubConfiguration, HttpServerStubConfiguration httpServerStubConfiguration) { return httpStubConfiguration .httpsPort(5432); } } @Configuration @ImportAutoConfiguration(GrpcClientAutoConfiguration.class) static class TestConfiguration { // Not necessary with WireMock PlainText mode @Bean public GrpcChannelConfigurer keepAliveClientConfigurer() { return (channelBuilder, name) -> { if (channelBuilder instanceof NettyChannelBuilder) { try { ((NettyChannelBuilder) channelBuilder) .sslContext(GrpcSslContexts.forClient() .trustManager(InsecureTrustManagerFactory.INSTANCE) .build()); } catch (SSLException e) { throw new IllegalStateException(e); } } }; } /** * GRPC client interceptor that sets the returned status always to OK. * You might want to change the return status depending on the received stub payload. * * Hopefully in the future this will be unnecessary and will be removed. */ @Bean ClientInterceptor fixedStatusSendingClientInterceptor() { return new ClientInterceptor() { @Override public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) { ClientCall<ReqT, RespT> call = next.newCall(method, callOptions); return new ClientCall<ReqT, RespT>() { @Override public void start(Listener<RespT> responseListener, Metadata headers) { Listener<RespT> listener = new Listener<RespT>() { @Override public void onHeaders(Metadata headers) { responseListener.onHeaders(headers); } @Override public void onMessage(RespT message) { responseListener.onMessage(message); } @Override public void onClose(Status status, Metadata trailers) { // TODO: This must be fixed somehow either in Jetty (WireMock) or somewhere else responseListener.onClose(Status.OK, trailers); } @Override public void onReady() { responseListener.onReady(); } }; call.start(listener, headers); } @Override public void request(int numMessages) { call.request(numMessages); } @Override public void cancel(@Nullable String message, @Nullable Throwable cause) { call.cancel(message, cause); } @Override public void halfClose() { call.halfClose(); } @Override public void sendMessage(ReqT message) { call.sendMessage(message); } }; } }; } } }
Fixing wrong comments
consumer_grpc/src/test/java/com/example/GrpcTests.java
Fixing wrong comments
Java
apache-2.0
2f7fd7202cd466638f112c4aca084ea62df5cfa9
0
chanikag/wso2-axis2,wso2/wso2-axis2,chanikag/wso2-axis2,chanikag/wso2-axis2,thusithathilina/wso2-axis2,jsdjayanga/wso2-axis2,chanakaudaya/wso2-axis2,wso2/wso2-axis2,thusithathilina/wso2-axis2,chanakaudaya/wso2-axis2,wso2/wso2-axis2,chanikag/wso2-axis2,callkalpa/wso2-axis2,jsdjayanga/wso2-axis2,thusithathilina/wso2-axis2,thusithathilina/wso2-axis2,chanakaudaya/wso2-axis2,chanakaudaya/wso2-axis2,jsdjayanga/wso2-axis2,callkalpa/wso2-axis2,wso2/wso2-axis2,callkalpa/wso2-axis2,callkalpa/wso2-axis2,jsdjayanga/wso2-axis2
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.axis2.util; import org.apache.axiom.soap.SOAPBody; import org.apache.axiom.soap.SOAPEnvelope; import org.apache.axiom.soap.SOAPFault; import org.apache.axiom.util.UIDGenerator; import org.apache.axis2.AxisFault; import org.apache.axis2.Constants; import org.apache.axis2.ServiceObjectSupplier; import org.apache.axis2.transport.TransportListener; import org.apache.axis2.transport.http.HTTPConstants; import org.apache.axis2.context.ConfigurationContext; import org.apache.axis2.context.ConfigurationContextFactory; import org.apache.axis2.context.MessageContext; import org.apache.axis2.context.ServiceContext; import org.apache.axis2.context.ServiceGroupContext; import org.apache.axis2.description.AxisModule; import org.apache.axis2.description.AxisOperation; import org.apache.axis2.description.AxisService; import org.apache.axis2.description.Flow; import org.apache.axis2.description.HandlerDescription; import org.apache.axis2.description.InOnlyAxisOperation; import org.apache.axis2.description.InOutAxisOperation; import org.apache.axis2.description.OutInAxisOperation; import org.apache.axis2.description.Parameter; import org.apache.axis2.description.PhaseRule; import org.apache.axis2.description.Version; import org.apache.axis2.description.WSDL2Constants; import org.apache.axis2.engine.AxisConfiguration; import org.apache.axis2.engine.AxisError; import org.apache.axis2.engine.Handler; import org.apache.axis2.engine.MessageReceiver; import org.apache.axis2.i18n.Messages; import org.apache.axis2.receivers.RawXMLINOutMessageReceiver; import org.apache.axis2.wsdl.WSDLConstants; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import javax.xml.namespace.QName; import java.io.File; import java.lang.reflect.Modifier; import java.security.AccessController; import java.security.PrivilegedAction; import java.security.PrivilegedExceptionAction; import java.text.ParseException; import java.util.HashMap; import java.util.Iterator; import java.util.Enumeration; import java.util.Map; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.SocketException; import java.net.NetworkInterface; import java.net.InetAddress; public class Utils { private static final Log log = LogFactory.getLog(Utils.class); private static final String LOCAL_TRANSPORT_PREFIX = "local:/"; private static final String AXIS2_SERVICE_PREFIX = "axis2/"; public static void addHandler(Flow flow, Handler handler, String phaseName) { HandlerDescription handlerDesc = new HandlerDescription(handler.getName()); PhaseRule rule = new PhaseRule(phaseName); handlerDesc.setRules(rule); handler.init(handlerDesc); handlerDesc.setHandler(handler); flow.addHandler(handlerDesc); } /** * @see org.apache.axis2.util.MessageContextBuilder:createOutMessageContext() * @deprecated (post1.1branch) */ public static MessageContext createOutMessageContext(MessageContext inMessageContext) throws AxisFault { return MessageContextBuilder.createOutMessageContext(inMessageContext); } public static AxisService createSimpleService(QName serviceName, String className, QName opName) throws AxisFault { return createSimpleService(serviceName, new RawXMLINOutMessageReceiver(), className, opName); } public static AxisService createSimpleServiceforClient(QName serviceName, String className, QName opName) throws AxisFault { return createSimpleServiceforClient(serviceName, new RawXMLINOutMessageReceiver(), className, opName); } public static AxisService createSimpleInOnlyService(QName serviceName, MessageReceiver messageReceiver, QName opName) throws AxisFault { AxisService service = new AxisService(serviceName.getLocalPart()); service.setClassLoader(getContextClassLoader_DoPriv()); AxisOperation axisOp = new InOnlyAxisOperation(opName); axisOp.setMessageReceiver(messageReceiver); axisOp.setStyle(WSDLConstants.STYLE_RPC); service.addOperation(axisOp); service.mapActionToOperation(Constants.AXIS2_NAMESPACE_URI + "/" + opName.getLocalPart(), axisOp); return service; } private static ClassLoader getContextClassLoader_DoPriv() { return (ClassLoader) org.apache.axis2.java.security.AccessController.doPrivileged( new PrivilegedAction<ClassLoader>() { public ClassLoader run() { return Thread.currentThread().getContextClassLoader(); } } ); } public static AxisService createSimpleService(QName serviceName, MessageReceiver messageReceiver, String className, QName opName) throws AxisFault { AxisService service = new AxisService(serviceName.getLocalPart()); service.setClassLoader(getContextClassLoader_DoPriv()); service.addParameter(new Parameter(Constants.SERVICE_CLASS, className)); AxisOperation axisOp = new InOutAxisOperation(opName); axisOp.setMessageReceiver(messageReceiver); axisOp.setStyle(WSDLConstants.STYLE_RPC); service.addOperation(axisOp); service.mapActionToOperation(Constants.AXIS2_NAMESPACE_URI + "/" + opName.getLocalPart(), axisOp); return service; } public static AxisService createSimpleServiceforClient(QName serviceName, MessageReceiver messageReceiver, String className, QName opName) throws AxisFault { AxisService service = new AxisService(serviceName.getLocalPart()); service.setClassLoader(getContextClassLoader_DoPriv()); service.addParameter(new Parameter(Constants.SERVICE_CLASS, className)); AxisOperation axisOp = new OutInAxisOperation(opName); axisOp.setMessageReceiver(messageReceiver); axisOp.setStyle(WSDLConstants.STYLE_RPC); service.addOperation(axisOp); return service; } public static ServiceContext fillContextInformation(AxisService axisService, ConfigurationContext configurationContext) throws AxisFault { // 2. if null, create new opCtxt // fill the service group context and service context info return fillServiceContextAndServiceGroupContext(axisService, configurationContext); } private static ServiceContext fillServiceContextAndServiceGroupContext(AxisService axisService, ConfigurationContext configurationContext) throws AxisFault { String serviceGroupContextId = UIDGenerator.generateURNString(); ServiceGroupContext serviceGroupContext = configurationContext.createServiceGroupContext(axisService.getAxisServiceGroup()); serviceGroupContext.setId(serviceGroupContextId); configurationContext.addServiceGroupContextIntoSoapSessionTable(serviceGroupContext); return serviceGroupContext.getServiceContext(axisService); } /** * Break a full path into pieces * * @return an array where element [0] always contains the service, and element 1, if not null, contains * the path after the first element. all ? parameters are discarded. */ public static String[] parseRequestURLForServiceAndOperation(String path, String servicePath) { if (log.isDebugEnabled()) { log.debug("parseRequestURLForServiceAndOperation : [" + path + "][" + servicePath + "]"); } if (path == null) { return null; } String[] values = new String[2]; // TODO. This is kind of brittle. Any service with the name /services would cause fun. int index = path.lastIndexOf(servicePath); String service; if (-1 != index) { int serviceStart = index + servicePath.length(); if (path.length() > serviceStart + 1) { service = path.substring(serviceStart + 1); int queryIndex = service.indexOf('?'); if (queryIndex > 0) { service = service.substring(0, queryIndex); } int operationIndex = service.indexOf('/'); if (operationIndex > 0) { values[0] = service.substring(0, operationIndex); values[1] = service.substring(operationIndex + 1); operationIndex = values[1].lastIndexOf('/'); if (operationIndex > 0) { values[1] = values[1].substring(operationIndex + 1); } } else { values[0] = service; } } } else { if (log.isDebugEnabled()) { log.debug("Unable to parse request URL [" + path + "][" + servicePath + "]"); } } return values; } /** * Gives the service/operation part from the incoming EPR * Ex: ..services/foo/bar/Version/getVersion -> foo/bar/Version/getVersion * @param path - incoming EPR * @param servicePath - Ex: 'services' * @return - service/operation part */ public static String getServiceAndOperationPart(String path, String servicePath) { if (path == null) { return null; } //with this chances that substring matching a different place in the URL is reduced if(!servicePath.endsWith("/")){ servicePath = servicePath+"/"; } String serviceOpPart = null; if (path.startsWith(servicePath) || path.startsWith(LOCAL_TRANSPORT_PREFIX) || path.startsWith(AXIS2_SERVICE_PREFIX)) { int index = path.lastIndexOf(servicePath); int serviceStart = index + servicePath.length(); //get the string after services path if (path.length() > serviceStart) { serviceOpPart = path.substring(serviceStart); //remove everything after ? int queryIndex = serviceOpPart.indexOf('?'); if (queryIndex > 0) { serviceOpPart = serviceOpPart.substring(0, queryIndex); } } } return serviceOpPart; } /** * Compute the operation path from request URI using the servince name. Service name can be a * normal one or a hierarchical one. * Ex: ../services/Echo/echoString -> echoString * ../services/foo/1.0.0/Echo/echoString -> echoString * ../services/Echo/ -> null * @param path - request URI * @param serviceName - service name * @return - operation name if any, else null */ public static String getOperationName(String path, String serviceName) { if (path == null || serviceName == null) { return null; } String[] temp = path.split(serviceName + "/"); String operationName = null; if (temp.length > 1) { operationName = temp[temp.length - 1]; } else { //this scenario occurs if the endpoint name is there in the URL after service name temp = path.split(serviceName + "\\."); if (temp.length > 1) { operationName = temp[temp.length - 1]; operationName = operationName.substring(operationName.indexOf('/') + 1); } } if (operationName != null) { //remove everyting after '?' int queryIndex = operationName.indexOf('?'); if (queryIndex > 0) { operationName = operationName.substring(0, queryIndex); } //take the part upto / as the operation name if (operationName.indexOf("/") != -1) { operationName = operationName.substring(0, operationName.indexOf("/")); } } return operationName; } public static ConfigurationContext getNewConfigurationContext(String repositry) throws Exception { final File file = new File(repositry); boolean exists = exists(file); if (!exists) { throw new Exception("repository directory " + file.getAbsolutePath() + " does not exists"); } File axis2xml = new File(file, "axis.xml"); String axis2xmlString = null; if (exists(axis2xml)) { axis2xmlString = axis2xml.getName(); } String path = (String) org.apache.axis2.java.security.AccessController.doPrivileged( new PrivilegedAction<String>() { public String run() { return file.getAbsolutePath(); } } ); return ConfigurationContextFactory .createConfigurationContextFromFileSystem(path, axis2xmlString); } private static boolean exists(final File file) { Boolean exists = (Boolean) org.apache.axis2.java.security.AccessController.doPrivileged( new PrivilegedAction<Boolean>() { public Boolean run() { return new Boolean(file.exists()); } } ); return exists.booleanValue(); } public static String getParameterValue(Parameter param) { if (param == null) { return null; } else { return (String) param.getValue(); } } public static String getModuleName(String moduleName, String moduleVersion) { if (moduleVersion != null && !moduleVersion.isEmpty()) { moduleName = moduleName + "-" + moduleVersion; } return moduleName; } private static final String ILLEGAL_CHARACTERS = "/\n\r\t\0\f`?*\\<>|\":"; public static boolean isValidModuleName(String moduleName) { for (int i = 0; i < moduleName.length(); i++) { char c = moduleName.charAt(i); if ((c > 127) || (ILLEGAL_CHARACTERS.indexOf(c) >= 0)) { return false; } } return true; } /** * - if he trying to engage the same module then method will returen false * - else it will return true * */ public static boolean checkVersion(Version module1version, Version module2version) throws AxisFault { if ((module1version !=null && !module1version.equals(module2version)) || module2version !=null && !module2version.equals(module1version)) { throw new AxisFault("trying to engage two different module versions " + module1version + " : " + module2version); } return true; } public static void calculateDefaultModuleVersion(HashMap modules, AxisConfiguration axisConfig) { Iterator allModules = modules.values().iterator(); Map<String,Version> defaultModules = new HashMap<String,Version>(); while (allModules.hasNext()) { AxisModule axisModule = (AxisModule) allModules.next(); String name = axisModule.getName(); Version currentDefaultVersion = defaultModules.get(name); Version version = axisModule.getVersion(); if (currentDefaultVersion == null || (version != null && version.compareTo(currentDefaultVersion) > 0)) { defaultModules.put(name, version); } } Iterator def_mod_itr = defaultModules.keySet().iterator(); while (def_mod_itr.hasNext()) { String moduleName = (String) def_mod_itr.next(); Version version = defaultModules.get(moduleName); axisConfig.addDefaultModuleVersion(moduleName, version == null ? null : version.toString()); } } /** * Check if a MessageContext property is true. * * @param messageContext the MessageContext * @param propertyName the property name * @return true if the property is Boolean.TRUE, "true", 1, etc. or false otherwise * @deprecated please use MessageContext.isTrue(propertyName) instead */ public static boolean isExplicitlyTrue(MessageContext messageContext, String propertyName) { Object flag = messageContext.getProperty(propertyName); return JavaUtils.isTrueExplicitly(flag); } /** * Maps the String URI of the Message exchange pattern to a integer. * Further, in the first lookup, it will cache the looked * up value so that the subsequent method calls are extremely efficient. */ @SuppressWarnings("deprecation") public static int getAxisSpecifMEPConstant(String messageExchangePattern) { int mepConstant = WSDLConstants.MEP_CONSTANT_INVALID; if (WSDL2Constants.MEP_URI_IN_OUT.equals(messageExchangePattern) || WSDLConstants.WSDL20_2006Constants.MEP_URI_IN_OUT.equals(messageExchangePattern) || WSDLConstants.WSDL20_2004_Constants.MEP_URI_IN_OUT.equals(messageExchangePattern)) { mepConstant = WSDLConstants.MEP_CONSTANT_IN_OUT; } else if ( WSDL2Constants.MEP_URI_IN_ONLY.equals(messageExchangePattern) || WSDLConstants.WSDL20_2006Constants.MEP_URI_IN_ONLY.equals(messageExchangePattern) || WSDLConstants.WSDL20_2004_Constants.MEP_URI_IN_ONLY .equals(messageExchangePattern)) { mepConstant = WSDLConstants.MEP_CONSTANT_IN_ONLY; } else if (WSDL2Constants.MEP_URI_IN_OPTIONAL_OUT .equals(messageExchangePattern) || WSDLConstants.WSDL20_2006Constants.MEP_URI_IN_OPTIONAL_OUT .equals(messageExchangePattern) || WSDLConstants.WSDL20_2004_Constants.MEP_URI_IN_OPTIONAL_OUT .equals(messageExchangePattern)) { mepConstant = WSDLConstants.MEP_CONSTANT_IN_OPTIONAL_OUT; } else if (WSDL2Constants.MEP_URI_OUT_IN.equals(messageExchangePattern) || WSDLConstants.WSDL20_2006Constants.MEP_URI_OUT_IN.equals(messageExchangePattern) || WSDLConstants.WSDL20_2004_Constants.MEP_URI_OUT_IN .equals(messageExchangePattern)) { mepConstant = WSDLConstants.MEP_CONSTANT_OUT_IN; } else if (WSDL2Constants.MEP_URI_OUT_ONLY.equals(messageExchangePattern) || WSDLConstants.WSDL20_2006Constants.MEP_URI_OUT_ONLY .equals(messageExchangePattern) || WSDLConstants.WSDL20_2004_Constants .MEP_URI_OUT_ONLY.equals(messageExchangePattern)) { mepConstant = WSDLConstants.MEP_CONSTANT_OUT_ONLY; } else if (WSDL2Constants.MEP_URI_OUT_OPTIONAL_IN.equals(messageExchangePattern) || WSDLConstants.WSDL20_2006Constants.MEP_URI_OUT_OPTIONAL_IN .equals(messageExchangePattern) || WSDLConstants.WSDL20_2004_Constants.MEP_URI_OUT_OPTIONAL_IN .equals(messageExchangePattern)) { mepConstant = WSDLConstants.MEP_CONSTANT_OUT_OPTIONAL_IN; } else if (WSDL2Constants.MEP_URI_ROBUST_IN_ONLY.equals(messageExchangePattern) || WSDLConstants.WSDL20_2006Constants.MEP_URI_ROBUST_IN_ONLY .equals(messageExchangePattern) || WSDLConstants.WSDL20_2004_Constants.MEP_URI_ROBUST_IN_ONLY .equals(messageExchangePattern)) { mepConstant = WSDLConstants.MEP_CONSTANT_ROBUST_IN_ONLY; } else if (WSDL2Constants.MEP_URI_ROBUST_OUT_ONLY.equals(messageExchangePattern) || WSDLConstants.WSDL20_2006Constants.MEP_URI_ROBUST_OUT_ONLY .equals(messageExchangePattern) || WSDLConstants.WSDL20_2004_Constants.MEP_URI_ROBUST_OUT_ONLY .equals(messageExchangePattern)) { mepConstant = WSDLConstants.MEP_CONSTANT_ROBUST_OUT_ONLY; } if (mepConstant == WSDLConstants.MEP_CONSTANT_INVALID) { throw new AxisError(Messages.getMessage("mepmappingerror")); } return mepConstant; } /** * Get an AxisFault object to represent the SOAPFault in the SOAPEnvelope attached * to the provided MessageContext. This first check for an already extracted AxisFault * and otherwise does a simple extract. * <p/> * MUST NOT be passed a MessageContext which does not contain a SOAPFault * * @param messageContext * @return */ public static AxisFault getInboundFaultFromMessageContext(MessageContext messageContext) { // Get the fault if it's already been extracted by a handler AxisFault result = (AxisFault) messageContext.getProperty(Constants.INBOUND_FAULT_OVERRIDE); // Else, extract it from the SOAPBody if (result == null) { SOAPEnvelope envelope = messageContext.getEnvelope(); SOAPFault soapFault; SOAPBody soapBody; if (envelope != null && (soapBody = envelope.getBody()) != null) { if ((soapFault = soapBody.getFault()) != null) { return new AxisFault(soapFault, messageContext); } // If its a REST response the content is not a SOAP envelop and hence we will // Have use the soap body as the exception if (messageContext.isDoingREST() && soapBody.getFirstElement() != null) { AxisFault fault = new AxisFault(soapBody.getFirstElement().toString()); fault.setDetail(soapBody.getFirstElement()); return fault; } // if axis2 receives an rest type fault for an soap message then message context // has not been set to isDoingREST() but in this case we can detect it by using // the message type. so if the message type is application/xml we assum it as an rest call if ((messageContext.getProperty(Constants.Configuration.MESSAGE_TYPE) != null) && messageContext.getProperty(Constants.Configuration.MESSAGE_TYPE).equals(HTTPConstants.MEDIA_TYPE_APPLICATION_XML)){ if (soapBody.getFirstElement() != null){ AxisFault fault = new AxisFault(soapBody.getFirstElement().toString()); fault.setDetail(soapBody.getFirstElement()); return fault; } else { return new AxisFault("application/xml type error received."); } } } // Not going to be able to throw new IllegalArgumentException( "The MessageContext does not have an associated SOAPFault."); } return result; } /** * This method will provide the logic needed to retrieve an Object's classloader * in a Java 2 Security compliant manner. */ public static ClassLoader getObjectClassLoader(final Object object) { if(object == null) { return null; } else { return (ClassLoader) AccessController.doPrivileged(new PrivilegedAction() { public Object run() { return object.getClass().getClassLoader(); } }); } } public static int getMtomThreshold(MessageContext msgCtxt){ Integer value = null; if(!msgCtxt.isServerSide()){ value = (Integer)msgCtxt.getProperty(Constants.Configuration.MTOM_THRESHOLD); }else{ Parameter param = msgCtxt.getParameter(Constants.Configuration.MTOM_THRESHOLD); if(param!=null){ value = (Integer)param.getValue(); } } int threshold = (value!=null)?value.intValue():0; if(log.isDebugEnabled()){ log.debug("MTOM optimized Threshold value ="+threshold); } return threshold; } /** * Returns the ip address to be used for the replyto epr * CAUTION: * This will go through all the available network interfaces and will try to return an ip address. * First this will try to get the first IP which is not loopback address (127.0.0.1). If none is found * then this will return this will return 127.0.0.1. * This will <b>not<b> consider IPv6 addresses. * <p/> * TODO: * - Improve this logic to genaralize it a bit more * - Obtain the ip to be used here from the Call API * * @return Returns String. * @throws java.net.SocketException */ public static String getIpAddress() throws SocketException { Enumeration e = NetworkInterface.getNetworkInterfaces(); String address = "127.0.0.1"; while (e.hasMoreElements()) { NetworkInterface netface = (NetworkInterface) e.nextElement(); Enumeration addresses = netface.getInetAddresses(); while (addresses.hasMoreElements()) { InetAddress ip = (InetAddress) addresses.nextElement(); if (!ip.isLoopbackAddress() && isIP(ip.getHostAddress())) { return ip.getHostAddress(); } } } return address; } /** * First check whether the hostname parameter is there in AxisConfiguration (axis2.xml) , * if it is there then this will retun that as the host name , o.w will return the IP address. */ public static String getIpAddress(AxisConfiguration axisConfiguration) throws SocketException { if(axisConfiguration!=null){ Parameter param = axisConfiguration.getParameter(TransportListener.HOST_ADDRESS); if (param != null) { String hostAddress = ((String) param.getValue()).trim(); if(hostAddress!=null){ return hostAddress; } } } return getIpAddress(); } /** * First check whether the hostname parameter is there in AxisConfiguration (axis2.xml) , * if it is there then this will return that as the host name , o.w will return the IP address. * @param axisConfiguration * @return hostname */ public static String getHostname(AxisConfiguration axisConfiguration) { if(axisConfiguration!=null){ Parameter param = axisConfiguration.getParameter(TransportListener.HOST_ADDRESS); if (param != null) { String hostAddress = ((String) param.getValue()).trim(); if(hostAddress!=null){ return hostAddress; } } } return null; } private static boolean isIP(String hostAddress) { return hostAddress.split("[.]").length == 4; } /** * Get the scheme part from a URI (or URL). * * @param uri the URI * @return the scheme of the URI */ public static String getURIScheme(String uri) { int index = uri.indexOf(':'); return index > 0 ? uri.substring(0, index) : null; } public static String sanitizeWebOutput(String text) { text = text.replaceAll("<", "&lt;"); return text; } /** * Create a service object for a given service. The method first looks for * the {@link Constants#SERVICE_OBJECT_SUPPLIER} service parameter and if * this parameter is present, it will use the specified class to create the * service object. If the parameter is not present, it will create an * instance of the class specified by the {@link Constants#SERVICE_CLASS} * parameter. * * @param service * the service * @return The service object or <code>null</code> if neither the * {@link Constants#SERVICE_OBJECT_SUPPLIER} nor the * {@link Constants#SERVICE_CLASS} parameter was found on the * service, i.e. if the service doesn't specify how to create a * service object. If the return value is non null, it will always * be a newly created instance. * @throws AxisFault * if an error occurred while attempting to instantiate the * service object */ public static Object createServiceObject(final AxisService service) throws AxisFault { try { ClassLoader classLoader = service.getClassLoader(); // allow alternative definition of makeNewServiceObject Parameter serviceObjectSupplierParam = service.getParameter(Constants.SERVICE_OBJECT_SUPPLIER); if (serviceObjectSupplierParam != null) { final Class<?> serviceObjectSupplierClass = Loader.loadClass(classLoader, ((String) serviceObjectSupplierParam.getValue()).trim()); if (ServiceObjectSupplier.class.isAssignableFrom(serviceObjectSupplierClass)) { ServiceObjectSupplier serviceObjectSupplier = org.apache.axis2.java.security.AccessController.doPrivileged( new PrivilegedExceptionAction<ServiceObjectSupplier>() { public ServiceObjectSupplier run() throws InstantiationException, IllegalAccessException { return (ServiceObjectSupplier)serviceObjectSupplierClass.newInstance(); } } ); return serviceObjectSupplier.getServiceObject(service); } else { // Prior to r439555 service object suppliers were actually defined by a static method // with a given signature defined on an arbitrary class. The ServiceObjectSupplier // interface was only introduced by r439555. We still support the old way, but // issue a warning inviting the user to provide a proper ServiceObjectSupplier // implementation. // Find static getServiceObject() method, call it if there final Method method = org.apache.axis2.java.security.AccessController.doPrivileged( new PrivilegedExceptionAction<Method>() { public Method run() throws NoSuchMethodException { return serviceObjectSupplierClass.getMethod("getServiceObject", AxisService.class); } } ); log.warn("The class specified by the " + Constants.SERVICE_OBJECT_SUPPLIER + " property on service " + service.getName() + " does not implement the " + ServiceObjectSupplier.class.getName() + " interface. This is deprecated."); return org.apache.axis2.java.security.AccessController.doPrivileged( new PrivilegedExceptionAction<Object>() { public Object run() throws InvocationTargetException, IllegalAccessException, InstantiationException { return method.invoke(serviceObjectSupplierClass.newInstance(), new Object[]{service}); } } ); } } else { Parameter serviceClassParam = service.getParameter(Constants.SERVICE_CLASS); if (serviceClassParam != null) { final Class<?> serviceClass = Loader.loadClass( classLoader, ((String) serviceClassParam.getValue()).trim()); String className = ((String) serviceClassParam.getValue()).trim(); Class serviceObjectMaker = Loader.loadClass(classLoader, className); if (serviceObjectMaker.getModifiers() != Modifier.PUBLIC) { throw new AxisFault("Service class " + className + " must have public as access Modifier"); } return org.apache.axis2.java.security.AccessController.doPrivileged( new PrivilegedExceptionAction<Object>() { public Object run() throws InstantiationException, IllegalAccessException { return serviceClass.newInstance(); } } ); } else { return null; } } } catch (Exception e) { throw AxisFault.makeFault(e); } } /** * Get the service class for a given service. This method will first check * the {@link Constants#SERVICE_CLASS} service parameter and if that * parameter is not present, inspect the instance returned by the service * object supplier specified by {@link Constants#SERVICE_OBJECT_SUPPLIER}. * * @param service * the service * @return The service class or <code>null</code> if neither the * {@link Constants#SERVICE_CLASS} nor the * {@link Constants#SERVICE_OBJECT_SUPPLIER} parameter was found on * the service, i.e. if the service doesn't specify a service class. * @throws AxisFault * if an error occurred while attempting to load the service * class or to instantiate the service object */ public static Class<?> getServiceClass(AxisService service) throws AxisFault { Parameter serviceClassParam = service.getParameter(Constants.SERVICE_CLASS); if (serviceClassParam != null) { try { return Loader.loadClass(service.getClassLoader(), ((String) serviceClassParam.getValue()).trim()); } catch (Exception e) { throw AxisFault.makeFault(e); } } else { Object serviceObject = createServiceObject(service); return serviceObject == null ? null : serviceObject.getClass(); } } /** * this is to make is backward compatible. Get rid of this at the next major release. * @param messageContext * @return */ public static boolean isClientThreadNonBlockingPropertySet(MessageContext messageContext){ Object val = messageContext.getProperty( MessageContext.CLIENT_API_NON_BLOCKING); if(val != null && ((Boolean)val).booleanValue()){ return true; }else{ //put the string inline as this is to be removed val = messageContext.getProperty("transportNonBlocking"); return val != null && ((Boolean)val).booleanValue(); } } }
modules/kernel/src/org/apache/axis2/util/Utils.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.axis2.util; import org.apache.axiom.soap.SOAPBody; import org.apache.axiom.soap.SOAPEnvelope; import org.apache.axiom.soap.SOAPFault; import org.apache.axiom.util.UIDGenerator; import org.apache.axis2.AxisFault; import org.apache.axis2.Constants; import org.apache.axis2.ServiceObjectSupplier; import org.apache.axis2.transport.TransportListener; import org.apache.axis2.transport.http.HTTPConstants; import org.apache.axis2.context.ConfigurationContext; import org.apache.axis2.context.ConfigurationContextFactory; import org.apache.axis2.context.MessageContext; import org.apache.axis2.context.ServiceContext; import org.apache.axis2.context.ServiceGroupContext; import org.apache.axis2.description.AxisModule; import org.apache.axis2.description.AxisOperation; import org.apache.axis2.description.AxisService; import org.apache.axis2.description.Flow; import org.apache.axis2.description.HandlerDescription; import org.apache.axis2.description.InOnlyAxisOperation; import org.apache.axis2.description.InOutAxisOperation; import org.apache.axis2.description.OutInAxisOperation; import org.apache.axis2.description.Parameter; import org.apache.axis2.description.PhaseRule; import org.apache.axis2.description.Version; import org.apache.axis2.description.WSDL2Constants; import org.apache.axis2.engine.AxisConfiguration; import org.apache.axis2.engine.AxisError; import org.apache.axis2.engine.Handler; import org.apache.axis2.engine.MessageReceiver; import org.apache.axis2.i18n.Messages; import org.apache.axis2.receivers.RawXMLINOutMessageReceiver; import org.apache.axis2.wsdl.WSDLConstants; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import javax.xml.namespace.QName; import java.io.File; import java.lang.reflect.Modifier; import java.security.AccessController; import java.security.PrivilegedAction; import java.security.PrivilegedExceptionAction; import java.text.ParseException; import java.util.HashMap; import java.util.Iterator; import java.util.Enumeration; import java.util.Map; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.SocketException; import java.net.NetworkInterface; import java.net.InetAddress; public class Utils { private static final Log log = LogFactory.getLog(Utils.class); public static void addHandler(Flow flow, Handler handler, String phaseName) { HandlerDescription handlerDesc = new HandlerDescription(handler.getName()); PhaseRule rule = new PhaseRule(phaseName); handlerDesc.setRules(rule); handler.init(handlerDesc); handlerDesc.setHandler(handler); flow.addHandler(handlerDesc); } /** * @see org.apache.axis2.util.MessageContextBuilder:createOutMessageContext() * @deprecated (post1.1branch) */ public static MessageContext createOutMessageContext(MessageContext inMessageContext) throws AxisFault { return MessageContextBuilder.createOutMessageContext(inMessageContext); } public static AxisService createSimpleService(QName serviceName, String className, QName opName) throws AxisFault { return createSimpleService(serviceName, new RawXMLINOutMessageReceiver(), className, opName); } public static AxisService createSimpleServiceforClient(QName serviceName, String className, QName opName) throws AxisFault { return createSimpleServiceforClient(serviceName, new RawXMLINOutMessageReceiver(), className, opName); } public static AxisService createSimpleInOnlyService(QName serviceName, MessageReceiver messageReceiver, QName opName) throws AxisFault { AxisService service = new AxisService(serviceName.getLocalPart()); service.setClassLoader(getContextClassLoader_DoPriv()); AxisOperation axisOp = new InOnlyAxisOperation(opName); axisOp.setMessageReceiver(messageReceiver); axisOp.setStyle(WSDLConstants.STYLE_RPC); service.addOperation(axisOp); service.mapActionToOperation(Constants.AXIS2_NAMESPACE_URI + "/" + opName.getLocalPart(), axisOp); return service; } private static ClassLoader getContextClassLoader_DoPriv() { return (ClassLoader) org.apache.axis2.java.security.AccessController.doPrivileged( new PrivilegedAction<ClassLoader>() { public ClassLoader run() { return Thread.currentThread().getContextClassLoader(); } } ); } public static AxisService createSimpleService(QName serviceName, MessageReceiver messageReceiver, String className, QName opName) throws AxisFault { AxisService service = new AxisService(serviceName.getLocalPart()); service.setClassLoader(getContextClassLoader_DoPriv()); service.addParameter(new Parameter(Constants.SERVICE_CLASS, className)); AxisOperation axisOp = new InOutAxisOperation(opName); axisOp.setMessageReceiver(messageReceiver); axisOp.setStyle(WSDLConstants.STYLE_RPC); service.addOperation(axisOp); service.mapActionToOperation(Constants.AXIS2_NAMESPACE_URI + "/" + opName.getLocalPart(), axisOp); return service; } public static AxisService createSimpleServiceforClient(QName serviceName, MessageReceiver messageReceiver, String className, QName opName) throws AxisFault { AxisService service = new AxisService(serviceName.getLocalPart()); service.setClassLoader(getContextClassLoader_DoPriv()); service.addParameter(new Parameter(Constants.SERVICE_CLASS, className)); AxisOperation axisOp = new OutInAxisOperation(opName); axisOp.setMessageReceiver(messageReceiver); axisOp.setStyle(WSDLConstants.STYLE_RPC); service.addOperation(axisOp); return service; } public static ServiceContext fillContextInformation(AxisService axisService, ConfigurationContext configurationContext) throws AxisFault { // 2. if null, create new opCtxt // fill the service group context and service context info return fillServiceContextAndServiceGroupContext(axisService, configurationContext); } private static ServiceContext fillServiceContextAndServiceGroupContext(AxisService axisService, ConfigurationContext configurationContext) throws AxisFault { String serviceGroupContextId = UIDGenerator.generateURNString(); ServiceGroupContext serviceGroupContext = configurationContext.createServiceGroupContext(axisService.getAxisServiceGroup()); serviceGroupContext.setId(serviceGroupContextId); configurationContext.addServiceGroupContextIntoSoapSessionTable(serviceGroupContext); return serviceGroupContext.getServiceContext(axisService); } /** * Break a full path into pieces * * @return an array where element [0] always contains the service, and element 1, if not null, contains * the path after the first element. all ? parameters are discarded. */ public static String[] parseRequestURLForServiceAndOperation(String path, String servicePath) { if (log.isDebugEnabled()) { log.debug("parseRequestURLForServiceAndOperation : [" + path + "][" + servicePath + "]"); } if (path == null) { return null; } String[] values = new String[2]; // TODO. This is kind of brittle. Any service with the name /services would cause fun. int index = path.lastIndexOf(servicePath); String service; if (-1 != index) { int serviceStart = index + servicePath.length(); if (path.length() > serviceStart + 1) { service = path.substring(serviceStart + 1); int queryIndex = service.indexOf('?'); if (queryIndex > 0) { service = service.substring(0, queryIndex); } int operationIndex = service.indexOf('/'); if (operationIndex > 0) { values[0] = service.substring(0, operationIndex); values[1] = service.substring(operationIndex + 1); operationIndex = values[1].lastIndexOf('/'); if (operationIndex > 0) { values[1] = values[1].substring(operationIndex + 1); } } else { values[0] = service; } } } else { if (log.isDebugEnabled()) { log.debug("Unable to parse request URL [" + path + "][" + servicePath + "]"); } } return values; } /** * Gives the service/operation part from the incoming EPR * Ex: ..services/foo/bar/Version/getVersion -> foo/bar/Version/getVersion * @param path - incoming EPR * @param servicePath - Ex: 'services' * @return - service/operation part */ public static String getServiceAndOperationPart(String path, String servicePath) { if (path == null) { return null; } //with this chances that substring matching a different place in the URL is reduced if(!servicePath.endsWith("/")){ servicePath = servicePath+"/"; } String serviceOpPart = null; if (path.startsWith(servicePath)) { int serviceStart = servicePath.length(); //get the string after services path if (path.length() > serviceStart) { serviceOpPart = path.substring(serviceStart); //remove everything after ? int queryIndex = serviceOpPart.indexOf('?'); if (queryIndex > 0) { serviceOpPart = serviceOpPart.substring(0, queryIndex); } } } return serviceOpPart; } /** * Compute the operation path from request URI using the servince name. Service name can be a * normal one or a hierarchical one. * Ex: ../services/Echo/echoString -> echoString * ../services/foo/1.0.0/Echo/echoString -> echoString * ../services/Echo/ -> null * @param path - request URI * @param serviceName - service name * @return - operation name if any, else null */ public static String getOperationName(String path, String serviceName) { if (path == null || serviceName == null) { return null; } String[] temp = path.split(serviceName + "/"); String operationName = null; if (temp.length > 1) { operationName = temp[temp.length - 1]; } else { //this scenario occurs if the endpoint name is there in the URL after service name temp = path.split(serviceName + "\\."); if (temp.length > 1) { operationName = temp[temp.length - 1]; operationName = operationName.substring(operationName.indexOf('/') + 1); } } if (operationName != null) { //remove everyting after '?' int queryIndex = operationName.indexOf('?'); if (queryIndex > 0) { operationName = operationName.substring(0, queryIndex); } //take the part upto / as the operation name if (operationName.indexOf("/") != -1) { operationName = operationName.substring(0, operationName.indexOf("/")); } } return operationName; } public static ConfigurationContext getNewConfigurationContext(String repositry) throws Exception { final File file = new File(repositry); boolean exists = exists(file); if (!exists) { throw new Exception("repository directory " + file.getAbsolutePath() + " does not exists"); } File axis2xml = new File(file, "axis.xml"); String axis2xmlString = null; if (exists(axis2xml)) { axis2xmlString = axis2xml.getName(); } String path = (String) org.apache.axis2.java.security.AccessController.doPrivileged( new PrivilegedAction<String>() { public String run() { return file.getAbsolutePath(); } } ); return ConfigurationContextFactory .createConfigurationContextFromFileSystem(path, axis2xmlString); } private static boolean exists(final File file) { Boolean exists = (Boolean) org.apache.axis2.java.security.AccessController.doPrivileged( new PrivilegedAction<Boolean>() { public Boolean run() { return new Boolean(file.exists()); } } ); return exists.booleanValue(); } public static String getParameterValue(Parameter param) { if (param == null) { return null; } else { return (String) param.getValue(); } } public static String getModuleName(String moduleName, String moduleVersion) { if (moduleVersion != null && !moduleVersion.isEmpty()) { moduleName = moduleName + "-" + moduleVersion; } return moduleName; } private static final String ILLEGAL_CHARACTERS = "/\n\r\t\0\f`?*\\<>|\":"; public static boolean isValidModuleName(String moduleName) { for (int i = 0; i < moduleName.length(); i++) { char c = moduleName.charAt(i); if ((c > 127) || (ILLEGAL_CHARACTERS.indexOf(c) >= 0)) { return false; } } return true; } /** * - if he trying to engage the same module then method will returen false * - else it will return true * */ public static boolean checkVersion(Version module1version, Version module2version) throws AxisFault { if ((module1version !=null && !module1version.equals(module2version)) || module2version !=null && !module2version.equals(module1version)) { throw new AxisFault("trying to engage two different module versions " + module1version + " : " + module2version); } return true; } public static void calculateDefaultModuleVersion(HashMap modules, AxisConfiguration axisConfig) { Iterator allModules = modules.values().iterator(); Map<String,Version> defaultModules = new HashMap<String,Version>(); while (allModules.hasNext()) { AxisModule axisModule = (AxisModule) allModules.next(); String name = axisModule.getName(); Version currentDefaultVersion = defaultModules.get(name); Version version = axisModule.getVersion(); if (currentDefaultVersion == null || (version != null && version.compareTo(currentDefaultVersion) > 0)) { defaultModules.put(name, version); } } Iterator def_mod_itr = defaultModules.keySet().iterator(); while (def_mod_itr.hasNext()) { String moduleName = (String) def_mod_itr.next(); Version version = defaultModules.get(moduleName); axisConfig.addDefaultModuleVersion(moduleName, version == null ? null : version.toString()); } } /** * Check if a MessageContext property is true. * * @param messageContext the MessageContext * @param propertyName the property name * @return true if the property is Boolean.TRUE, "true", 1, etc. or false otherwise * @deprecated please use MessageContext.isTrue(propertyName) instead */ public static boolean isExplicitlyTrue(MessageContext messageContext, String propertyName) { Object flag = messageContext.getProperty(propertyName); return JavaUtils.isTrueExplicitly(flag); } /** * Maps the String URI of the Message exchange pattern to a integer. * Further, in the first lookup, it will cache the looked * up value so that the subsequent method calls are extremely efficient. */ @SuppressWarnings("deprecation") public static int getAxisSpecifMEPConstant(String messageExchangePattern) { int mepConstant = WSDLConstants.MEP_CONSTANT_INVALID; if (WSDL2Constants.MEP_URI_IN_OUT.equals(messageExchangePattern) || WSDLConstants.WSDL20_2006Constants.MEP_URI_IN_OUT.equals(messageExchangePattern) || WSDLConstants.WSDL20_2004_Constants.MEP_URI_IN_OUT.equals(messageExchangePattern)) { mepConstant = WSDLConstants.MEP_CONSTANT_IN_OUT; } else if ( WSDL2Constants.MEP_URI_IN_ONLY.equals(messageExchangePattern) || WSDLConstants.WSDL20_2006Constants.MEP_URI_IN_ONLY.equals(messageExchangePattern) || WSDLConstants.WSDL20_2004_Constants.MEP_URI_IN_ONLY .equals(messageExchangePattern)) { mepConstant = WSDLConstants.MEP_CONSTANT_IN_ONLY; } else if (WSDL2Constants.MEP_URI_IN_OPTIONAL_OUT .equals(messageExchangePattern) || WSDLConstants.WSDL20_2006Constants.MEP_URI_IN_OPTIONAL_OUT .equals(messageExchangePattern) || WSDLConstants.WSDL20_2004_Constants.MEP_URI_IN_OPTIONAL_OUT .equals(messageExchangePattern)) { mepConstant = WSDLConstants.MEP_CONSTANT_IN_OPTIONAL_OUT; } else if (WSDL2Constants.MEP_URI_OUT_IN.equals(messageExchangePattern) || WSDLConstants.WSDL20_2006Constants.MEP_URI_OUT_IN.equals(messageExchangePattern) || WSDLConstants.WSDL20_2004_Constants.MEP_URI_OUT_IN .equals(messageExchangePattern)) { mepConstant = WSDLConstants.MEP_CONSTANT_OUT_IN; } else if (WSDL2Constants.MEP_URI_OUT_ONLY.equals(messageExchangePattern) || WSDLConstants.WSDL20_2006Constants.MEP_URI_OUT_ONLY .equals(messageExchangePattern) || WSDLConstants.WSDL20_2004_Constants .MEP_URI_OUT_ONLY.equals(messageExchangePattern)) { mepConstant = WSDLConstants.MEP_CONSTANT_OUT_ONLY; } else if (WSDL2Constants.MEP_URI_OUT_OPTIONAL_IN.equals(messageExchangePattern) || WSDLConstants.WSDL20_2006Constants.MEP_URI_OUT_OPTIONAL_IN .equals(messageExchangePattern) || WSDLConstants.WSDL20_2004_Constants.MEP_URI_OUT_OPTIONAL_IN .equals(messageExchangePattern)) { mepConstant = WSDLConstants.MEP_CONSTANT_OUT_OPTIONAL_IN; } else if (WSDL2Constants.MEP_URI_ROBUST_IN_ONLY.equals(messageExchangePattern) || WSDLConstants.WSDL20_2006Constants.MEP_URI_ROBUST_IN_ONLY .equals(messageExchangePattern) || WSDLConstants.WSDL20_2004_Constants.MEP_URI_ROBUST_IN_ONLY .equals(messageExchangePattern)) { mepConstant = WSDLConstants.MEP_CONSTANT_ROBUST_IN_ONLY; } else if (WSDL2Constants.MEP_URI_ROBUST_OUT_ONLY.equals(messageExchangePattern) || WSDLConstants.WSDL20_2006Constants.MEP_URI_ROBUST_OUT_ONLY .equals(messageExchangePattern) || WSDLConstants.WSDL20_2004_Constants.MEP_URI_ROBUST_OUT_ONLY .equals(messageExchangePattern)) { mepConstant = WSDLConstants.MEP_CONSTANT_ROBUST_OUT_ONLY; } if (mepConstant == WSDLConstants.MEP_CONSTANT_INVALID) { throw new AxisError(Messages.getMessage("mepmappingerror")); } return mepConstant; } /** * Get an AxisFault object to represent the SOAPFault in the SOAPEnvelope attached * to the provided MessageContext. This first check for an already extracted AxisFault * and otherwise does a simple extract. * <p/> * MUST NOT be passed a MessageContext which does not contain a SOAPFault * * @param messageContext * @return */ public static AxisFault getInboundFaultFromMessageContext(MessageContext messageContext) { // Get the fault if it's already been extracted by a handler AxisFault result = (AxisFault) messageContext.getProperty(Constants.INBOUND_FAULT_OVERRIDE); // Else, extract it from the SOAPBody if (result == null) { SOAPEnvelope envelope = messageContext.getEnvelope(); SOAPFault soapFault; SOAPBody soapBody; if (envelope != null && (soapBody = envelope.getBody()) != null) { if ((soapFault = soapBody.getFault()) != null) { return new AxisFault(soapFault, messageContext); } // If its a REST response the content is not a SOAP envelop and hence we will // Have use the soap body as the exception if (messageContext.isDoingREST() && soapBody.getFirstElement() != null) { AxisFault fault = new AxisFault(soapBody.getFirstElement().toString()); fault.setDetail(soapBody.getFirstElement()); return fault; } // if axis2 receives an rest type fault for an soap message then message context // has not been set to isDoingREST() but in this case we can detect it by using // the message type. so if the message type is application/xml we assum it as an rest call if ((messageContext.getProperty(Constants.Configuration.MESSAGE_TYPE) != null) && messageContext.getProperty(Constants.Configuration.MESSAGE_TYPE).equals(HTTPConstants.MEDIA_TYPE_APPLICATION_XML)){ if (soapBody.getFirstElement() != null){ AxisFault fault = new AxisFault(soapBody.getFirstElement().toString()); fault.setDetail(soapBody.getFirstElement()); return fault; } else { return new AxisFault("application/xml type error received."); } } } // Not going to be able to throw new IllegalArgumentException( "The MessageContext does not have an associated SOAPFault."); } return result; } /** * This method will provide the logic needed to retrieve an Object's classloader * in a Java 2 Security compliant manner. */ public static ClassLoader getObjectClassLoader(final Object object) { if(object == null) { return null; } else { return (ClassLoader) AccessController.doPrivileged(new PrivilegedAction() { public Object run() { return object.getClass().getClassLoader(); } }); } } public static int getMtomThreshold(MessageContext msgCtxt){ Integer value = null; if(!msgCtxt.isServerSide()){ value = (Integer)msgCtxt.getProperty(Constants.Configuration.MTOM_THRESHOLD); }else{ Parameter param = msgCtxt.getParameter(Constants.Configuration.MTOM_THRESHOLD); if(param!=null){ value = (Integer)param.getValue(); } } int threshold = (value!=null)?value.intValue():0; if(log.isDebugEnabled()){ log.debug("MTOM optimized Threshold value ="+threshold); } return threshold; } /** * Returns the ip address to be used for the replyto epr * CAUTION: * This will go through all the available network interfaces and will try to return an ip address. * First this will try to get the first IP which is not loopback address (127.0.0.1). If none is found * then this will return this will return 127.0.0.1. * This will <b>not<b> consider IPv6 addresses. * <p/> * TODO: * - Improve this logic to genaralize it a bit more * - Obtain the ip to be used here from the Call API * * @return Returns String. * @throws java.net.SocketException */ public static String getIpAddress() throws SocketException { Enumeration e = NetworkInterface.getNetworkInterfaces(); String address = "127.0.0.1"; while (e.hasMoreElements()) { NetworkInterface netface = (NetworkInterface) e.nextElement(); Enumeration addresses = netface.getInetAddresses(); while (addresses.hasMoreElements()) { InetAddress ip = (InetAddress) addresses.nextElement(); if (!ip.isLoopbackAddress() && isIP(ip.getHostAddress())) { return ip.getHostAddress(); } } } return address; } /** * First check whether the hostname parameter is there in AxisConfiguration (axis2.xml) , * if it is there then this will retun that as the host name , o.w will return the IP address. */ public static String getIpAddress(AxisConfiguration axisConfiguration) throws SocketException { if(axisConfiguration!=null){ Parameter param = axisConfiguration.getParameter(TransportListener.HOST_ADDRESS); if (param != null) { String hostAddress = ((String) param.getValue()).trim(); if(hostAddress!=null){ return hostAddress; } } } return getIpAddress(); } /** * First check whether the hostname parameter is there in AxisConfiguration (axis2.xml) , * if it is there then this will return that as the host name , o.w will return the IP address. * @param axisConfiguration * @return hostname */ public static String getHostname(AxisConfiguration axisConfiguration) { if(axisConfiguration!=null){ Parameter param = axisConfiguration.getParameter(TransportListener.HOST_ADDRESS); if (param != null) { String hostAddress = ((String) param.getValue()).trim(); if(hostAddress!=null){ return hostAddress; } } } return null; } private static boolean isIP(String hostAddress) { return hostAddress.split("[.]").length == 4; } /** * Get the scheme part from a URI (or URL). * * @param uri the URI * @return the scheme of the URI */ public static String getURIScheme(String uri) { int index = uri.indexOf(':'); return index > 0 ? uri.substring(0, index) : null; } public static String sanitizeWebOutput(String text) { text = text.replaceAll("<", "&lt;"); return text; } /** * Create a service object for a given service. The method first looks for * the {@link Constants#SERVICE_OBJECT_SUPPLIER} service parameter and if * this parameter is present, it will use the specified class to create the * service object. If the parameter is not present, it will create an * instance of the class specified by the {@link Constants#SERVICE_CLASS} * parameter. * * @param service * the service * @return The service object or <code>null</code> if neither the * {@link Constants#SERVICE_OBJECT_SUPPLIER} nor the * {@link Constants#SERVICE_CLASS} parameter was found on the * service, i.e. if the service doesn't specify how to create a * service object. If the return value is non null, it will always * be a newly created instance. * @throws AxisFault * if an error occurred while attempting to instantiate the * service object */ public static Object createServiceObject(final AxisService service) throws AxisFault { try { ClassLoader classLoader = service.getClassLoader(); // allow alternative definition of makeNewServiceObject Parameter serviceObjectSupplierParam = service.getParameter(Constants.SERVICE_OBJECT_SUPPLIER); if (serviceObjectSupplierParam != null) { final Class<?> serviceObjectSupplierClass = Loader.loadClass(classLoader, ((String) serviceObjectSupplierParam.getValue()).trim()); if (ServiceObjectSupplier.class.isAssignableFrom(serviceObjectSupplierClass)) { ServiceObjectSupplier serviceObjectSupplier = org.apache.axis2.java.security.AccessController.doPrivileged( new PrivilegedExceptionAction<ServiceObjectSupplier>() { public ServiceObjectSupplier run() throws InstantiationException, IllegalAccessException { return (ServiceObjectSupplier)serviceObjectSupplierClass.newInstance(); } } ); return serviceObjectSupplier.getServiceObject(service); } else { // Prior to r439555 service object suppliers were actually defined by a static method // with a given signature defined on an arbitrary class. The ServiceObjectSupplier // interface was only introduced by r439555. We still support the old way, but // issue a warning inviting the user to provide a proper ServiceObjectSupplier // implementation. // Find static getServiceObject() method, call it if there final Method method = org.apache.axis2.java.security.AccessController.doPrivileged( new PrivilegedExceptionAction<Method>() { public Method run() throws NoSuchMethodException { return serviceObjectSupplierClass.getMethod("getServiceObject", AxisService.class); } } ); log.warn("The class specified by the " + Constants.SERVICE_OBJECT_SUPPLIER + " property on service " + service.getName() + " does not implement the " + ServiceObjectSupplier.class.getName() + " interface. This is deprecated."); return org.apache.axis2.java.security.AccessController.doPrivileged( new PrivilegedExceptionAction<Object>() { public Object run() throws InvocationTargetException, IllegalAccessException, InstantiationException { return method.invoke(serviceObjectSupplierClass.newInstance(), new Object[]{service}); } } ); } } else { Parameter serviceClassParam = service.getParameter(Constants.SERVICE_CLASS); if (serviceClassParam != null) { final Class<?> serviceClass = Loader.loadClass( classLoader, ((String) serviceClassParam.getValue()).trim()); String className = ((String) serviceClassParam.getValue()).trim(); Class serviceObjectMaker = Loader.loadClass(classLoader, className); if (serviceObjectMaker.getModifiers() != Modifier.PUBLIC) { throw new AxisFault("Service class " + className + " must have public as access Modifier"); } return org.apache.axis2.java.security.AccessController.doPrivileged( new PrivilegedExceptionAction<Object>() { public Object run() throws InstantiationException, IllegalAccessException { return serviceClass.newInstance(); } } ); } else { return null; } } } catch (Exception e) { throw AxisFault.makeFault(e); } } /** * Get the service class for a given service. This method will first check * the {@link Constants#SERVICE_CLASS} service parameter and if that * parameter is not present, inspect the instance returned by the service * object supplier specified by {@link Constants#SERVICE_OBJECT_SUPPLIER}. * * @param service * the service * @return The service class or <code>null</code> if neither the * {@link Constants#SERVICE_CLASS} nor the * {@link Constants#SERVICE_OBJECT_SUPPLIER} parameter was found on * the service, i.e. if the service doesn't specify a service class. * @throws AxisFault * if an error occurred while attempting to load the service * class or to instantiate the service object */ public static Class<?> getServiceClass(AxisService service) throws AxisFault { Parameter serviceClassParam = service.getParameter(Constants.SERVICE_CLASS); if (serviceClassParam != null) { try { return Loader.loadClass(service.getClassLoader(), ((String) serviceClassParam.getValue()).trim()); } catch (Exception e) { throw AxisFault.makeFault(e); } } else { Object serviceObject = createServiceObject(service); return serviceObject == null ? null : serviceObject.getClass(); } } /** * this is to make is backward compatible. Get rid of this at the next major release. * @param messageContext * @return */ public static boolean isClientThreadNonBlockingPropertySet(MessageContext messageContext){ Object val = messageContext.getProperty( MessageContext.CLIENT_API_NON_BLOCKING); if(val != null && ((Boolean)val).booleanValue()){ return true; }else{ //put the string inline as this is to be removed val = messageContext.getProperty("transportNonBlocking"); return val != null && ((Boolean)val).booleanValue(); } } }
Fixing the test failures for the ESBJAVA_4041 initial fix
modules/kernel/src/org/apache/axis2/util/Utils.java
Fixing the test failures for the ESBJAVA_4041 initial fix
Java
apache-2.0
7d8e6237d6378e59a3d0086386ad599b3fbcd1af
0
PATRIC3/p3_solr,PATRIC3/p3_solr,PATRIC3/p3_solr,PATRIC3/p3_solr,PATRIC3/p3_solr,PATRIC3/p3_solr,PATRIC3/p3_solr
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.lucene.util; import java.io.IOException; import java.util.Arrays; import org.apache.lucene.search.DocIdSet; import org.apache.lucene.search.DocIdSetIterator; // TODO: maybe merge with BitVector? Problem is BitVector // caches its cardinality... /** BitSet of fixed length (numBits), backed by accessible * ({@link #getBits}) long[], accessed with an int index, * implementing Bits and DocIdSet. Unlike {@link * OpenBitSet} this bit set does not auto-expand, cannot * handle long index, and does not have fastXX/XX variants * (just X). * * @lucene.internal **/ public final class FixedBitSet extends DocIdSet implements Bits { private final long[] bits; private int numBits; /** returns the number of 64 bit words it would take to hold numBits */ public static int bits2words(int numBits) { int numLong = numBits >>> 6; if ((numBits & 63) != 0) { numLong++; } return numLong; } public FixedBitSet(int numBits) { this.numBits = numBits; bits = new long[bits2words(numBits)]; } /** Makes full copy. */ public FixedBitSet(FixedBitSet other) { bits = new long[other.bits.length]; System.arraycopy(other.bits, 0, bits, 0, bits.length); numBits = other.numBits; } @Override public DocIdSetIterator iterator() { return new OpenBitSetIterator(bits, bits.length); } @Override public Bits bits() { return this; } @Override public int length() { return numBits; } /** This DocIdSet implementation is cacheable. */ @Override public boolean isCacheable() { return true; } /** Expert. */ public long[] getBits() { return bits; } /** Returns number of set bits. NOTE: this visits every * long in the backing bits array, and the result is not * internally cached! */ public int cardinality() { return (int) BitUtil.pop_array(bits, 0, bits.length); } public boolean get(int index) { assert index >= 0 && index < numBits; int i = index >> 6; // div 64 // signed shift will keep a negative index and force an // array-index-out-of-bounds-exception, removing the need for an explicit check. int bit = index & 0x3f; // mod 64 long bitmask = 1L << bit; return (bits[i] & bitmask) != 0; } public void set(int index) { assert index >= 0 && index < numBits; int wordNum = index >> 6; // div 64 int bit = index & 0x3f; // mod 64 long bitmask = 1L << bit; bits[wordNum] |= bitmask; } public boolean getAndSet(int index) { assert index >= 0 && index < numBits; int wordNum = index >> 6; // div 64 int bit = index & 0x3f; // mod 64 long bitmask = 1L << bit; boolean val = (bits[wordNum] & bitmask) != 0; bits[wordNum] |= bitmask; return val; } public void clear(int index) { assert index >= 0 && index < numBits; int wordNum = index >> 6; int bit = index & 0x03f; long bitmask = 1L << bit; bits[wordNum] &= ~bitmask; } public boolean getAndClear(int index) { assert index >= 0 && index < numBits; int wordNum = index >> 6; // div 64 int bit = index & 0x3f; // mod 64 long bitmask = 1L << bit; boolean val = (bits[wordNum] & bitmask) != 0; bits[wordNum] &= ~bitmask; return val; } /** Returns the index of the first set bit starting at the index specified. * -1 is returned if there are no more set bits. */ public int nextSetBit(int index) { assert index >= 0 && index < numBits; int i = index >> 6; final int subIndex = index & 0x3f; // index within the word long word = bits[i] >> subIndex; // skip all the bits to the right of index if (word!=0) { return (i<<6) + subIndex + BitUtil.ntz(word); } while(++i < bits.length) { word = bits[i]; if (word != 0) { return (i<<6) + BitUtil.ntz(word); } } return -1; } /** Returns the index of the last set bit before or on the index specified. * -1 is returned if there are no more set bits. */ public int prevSetBit(int index) { assert index >= 0 && index < numBits: "index=" + index + " numBits=" + numBits; int i = index >> 6; final int subIndex = index & 0x3f; // index within the word long word = (bits[i] << (63-subIndex)); // skip all the bits to the left of index if (word != 0) { return (i << 6) + subIndex - Long.numberOfLeadingZeros(word); // See LUCENE-3197 } while (--i >= 0) { word = bits[i]; if (word !=0 ) { return (i << 6) + 63 - Long.numberOfLeadingZeros(word); } } return -1; } /** Does in-place OR of the bits provided by the * iterator. */ public void or(DocIdSetIterator iter) throws IOException { if (iter instanceof OpenBitSetIterator && iter.docID() == -1) { final OpenBitSetIterator obs = (OpenBitSetIterator) iter; or(obs.arr, obs.words); // advance after last doc that would be accepted if standard // iteration is used (to exhaust it): obs.advance(numBits); } else { int doc; while ((doc = iter.nextDoc()) < numBits) { set(doc); } } } /** this = this OR other */ public void or(FixedBitSet other) { or(other.bits, other.bits.length); } private void or(final long[] otherArr, final int otherLen) { final long[] thisArr = this.bits; int pos = Math.min(thisArr.length, otherLen); while (--pos >= 0) { thisArr[pos] |= otherArr[pos]; } } /** Does in-place AND of the bits provided by the * iterator. */ public void and(DocIdSetIterator iter) throws IOException { if (iter instanceof OpenBitSetIterator && iter.docID() == -1) { final OpenBitSetIterator obs = (OpenBitSetIterator) iter; and(obs.arr, obs.words); // advance after last doc that would be accepted if standard // iteration is used (to exhaust it): obs.advance(numBits); } else { if (numBits == 0) return; int disiDoc, bitSetDoc = nextSetBit(0); while (bitSetDoc != -1 && (disiDoc = iter.advance(bitSetDoc)) < numBits) { clear(bitSetDoc, disiDoc); disiDoc++; bitSetDoc = (disiDoc < numBits) ? nextSetBit(disiDoc) : -1; } if (bitSetDoc != -1) { clear(bitSetDoc, numBits); } } } /** this = this AND other */ public void and(FixedBitSet other) { and(other.bits, other.bits.length); } private void and(final long[] otherArr, final int otherLen) { final long[] thisArr = this.bits; int pos = Math.min(thisArr.length, otherLen); while(--pos >= 0) { thisArr[pos] &= otherArr[pos]; } if (thisArr.length > otherLen) { Arrays.fill(thisArr, otherLen, thisArr.length, 0L); } } /** Does in-place AND NOT of the bits provided by the * iterator. */ public void andNot(DocIdSetIterator iter) throws IOException { if (iter instanceof OpenBitSetIterator && iter.docID() == -1) { final OpenBitSetIterator obs = (OpenBitSetIterator) iter; andNot(obs.arr, obs.words); // advance after last doc that would be accepted if standard // iteration is used (to exhaust it): obs.advance(numBits); } else { int doc; while ((doc = iter.nextDoc()) < numBits) { clear(doc); } } } /** this = this AND NOT other */ public void andNot(FixedBitSet other) { andNot(other.bits, other.bits.length); } private void andNot(final long[] otherArr, final int otherLen) { final long[] thisArr = this.bits; int pos = Math.min(thisArr.length, otherLen); while(--pos >= 0) { thisArr[pos] &= ~otherArr[pos]; } } // NOTE: no .isEmpty() here because that's trappy (ie, // typically isEmpty is low cost, but this one wouldn't // be) /** Flips a range of bits * * @param startIndex lower index * @param endIndex one-past the last bit to flip */ public void flip(int startIndex, int endIndex) { assert startIndex >= 0 && startIndex < numBits; assert endIndex >= 0 && endIndex <= numBits; if (endIndex <= startIndex) { return; } int startWord = startIndex >> 6; int endWord = (endIndex-1) >> 6; /*** Grrr, java shifting wraps around so -1L>>>64 == -1 * for that reason, make sure not to use endmask if the bits to flip will * be zero in the last word (redefine endWord to be the last changed...) long startmask = -1L << (startIndex & 0x3f); // example: 11111...111000 long endmask = -1L >>> (64-(endIndex & 0x3f)); // example: 00111...111111 ***/ long startmask = -1L << startIndex; long endmask = -1L >>> -endIndex; // 64-(endIndex&0x3f) is the same as -endIndex due to wrap if (startWord == endWord) { bits[startWord] ^= (startmask & endmask); return; } bits[startWord] ^= startmask; for (int i=startWord+1; i<endWord; i++) { bits[i] = ~bits[i]; } bits[endWord] ^= endmask; } /** Sets a range of bits * * @param startIndex lower index * @param endIndex one-past the last bit to set */ public void set(int startIndex, int endIndex) { assert startIndex >= 0 && startIndex < numBits; assert endIndex >= 0 && endIndex <= numBits; if (endIndex <= startIndex) { return; } int startWord = startIndex >> 6; int endWord = (endIndex-1) >> 6; long startmask = -1L << startIndex; long endmask = -1L >>> -endIndex; // 64-(endIndex&0x3f) is the same as -endIndex due to wrap if (startWord == endWord) { bits[startWord] |= (startmask & endmask); return; } bits[startWord] |= startmask; Arrays.fill(bits, startWord+1, endWord, -1L); bits[endWord] |= endmask; } /** Clears a range of bits. * * @param startIndex lower index * @param endIndex one-past the last bit to clear */ public void clear(int startIndex, int endIndex) { assert startIndex >= 0 && startIndex < numBits; assert endIndex >= 0 && endIndex <= numBits; if (endIndex <= startIndex) { return; } int startWord = startIndex >> 6; int endWord = (endIndex-1) >> 6; long startmask = -1L << startIndex; long endmask = -1L >>> -endIndex; // 64-(endIndex&0x3f) is the same as -endIndex due to wrap // invert masks since we are clearing startmask = ~startmask; endmask = ~endmask; if (startWord == endWord) { bits[startWord] &= (startmask | endmask); return; } bits[startWord] &= startmask; Arrays.fill(bits, startWord+1, endWord, 0L); bits[endWord] &= endmask; } @Override public Object clone() { return new FixedBitSet(this); } /** returns true if both sets have the same bits set */ @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof FixedBitSet)) { return false; } FixedBitSet other = (FixedBitSet) o; if (numBits != other.length()) { return false; } return Arrays.equals(bits, other.bits); } @Override public int hashCode() { long h = 0; for (int i = bits.length; --i>=0;) { h ^= bits[i]; h = (h << 1) | (h >>> 63); // rotate left } // fold leftmost bits into right and add a constant to prevent // empty sets from returning 0, which is too common. return (int) ((h>>32) ^ h) + 0x98761234; } }
lucene/src/java/org/apache/lucene/util/FixedBitSet.java
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.lucene.util; import java.io.IOException; import java.util.Arrays; import org.apache.lucene.search.DocIdSet; import org.apache.lucene.search.DocIdSetIterator; // TODO: maybe merge with BitVector? Problem is BitVector // caches its cardinality... /** BitSet of fixed length (numBits), backed by accessible * ({@link #getBits}) long[], accessed with an int index, * implementing Bits and DocIdSet. Unlike {@link * OpenBitSet} this bit set does not auto-expand, cannot * handle long index, and does not have fastXX/XX variants * (just X). * * @lucene.internal **/ public final class FixedBitSet extends DocIdSet implements Bits { private final long[] bits; private int numBits; /** returns the number of 64 bit words it would take to hold numBits */ public static int bits2words(int numBits) { int numLong = numBits >>> 6; if ((numBits & 63) != 0) { numLong++; } return numLong; } public FixedBitSet(int numBits) { this.numBits = numBits; bits = new long[bits2words(numBits)]; } /** Makes full copy. */ public FixedBitSet(FixedBitSet other) { bits = new long[other.bits.length]; System.arraycopy(other.bits, 0, bits, 0, bits.length); numBits = other.numBits; } @Override public DocIdSetIterator iterator() { return new OpenBitSetIterator(bits, bits.length); } @Override public Bits bits() { return this; } @Override public int length() { return numBits; } /** This DocIdSet implementation is cacheable. */ @Override public boolean isCacheable() { return true; } /** Expert. */ public long[] getBits() { return bits; } /** Returns number of set bits. NOTE: this visits every * long in the backing bits array, and the result is not * internally cached! */ public int cardinality() { return (int) BitUtil.pop_array(bits, 0, bits.length); } public boolean get(int index) { assert index >= 0 && index < numBits; int i = index >> 6; // div 64 // signed shift will keep a negative index and force an // array-index-out-of-bounds-exception, removing the need for an explicit check. int bit = index & 0x3f; // mod 64 long bitmask = 1L << bit; return (bits[i] & bitmask) != 0; } public void set(int index) { assert index >= 0 && index < numBits; int wordNum = index >> 6; // div 64 int bit = index & 0x3f; // mod 64 long bitmask = 1L << bit; bits[wordNum] |= bitmask; } public boolean getAndSet(int index) { assert index >= 0 && index < numBits; int wordNum = index >> 6; // div 64 int bit = index & 0x3f; // mod 64 long bitmask = 1L << bit; boolean val = (bits[wordNum] & bitmask) != 0; bits[wordNum] |= bitmask; return val; } public void clear(int index) { assert index >= 0 && index < numBits; int wordNum = index >> 6; int bit = index & 0x03f; long bitmask = 1L << bit; bits[wordNum] &= ~bitmask; } public boolean getAndClear(int index) { assert index >= 0 && index < numBits; int wordNum = index >> 6; // div 64 int bit = index & 0x3f; // mod 64 long bitmask = 1L << bit; boolean val = (bits[wordNum] & bitmask) != 0; bits[wordNum] &= ~bitmask; return val; } /** Returns the index of the first set bit starting at the index specified. * -1 is returned if there are no more set bits. */ public int nextSetBit(int index) { assert index >= 0 && index < numBits; int i = index >> 6; final int subIndex = index & 0x3f; // index within the word long word = bits[i] >> subIndex; // skip all the bits to the right of index if (word!=0) { return (i<<6) + subIndex + BitUtil.ntz(word); } while(++i < bits.length) { word = bits[i]; if (word != 0) { return (i<<6) + BitUtil.ntz(word); } } return -1; } /** Returns the index of the last set bit before or on the index specified. * -1 is returned if there are no more set bits. */ public int prevSetBit(int index) { assert index >= 0 && index < numBits: "index=" + index + " numBits=" + numBits; int i = index >> 6; final int subIndex = index & 0x3f; // index within the word long word = (bits[i] << (63-subIndex)); // skip all the bits to the left of index if (word != 0) { return (i << 6) + subIndex - Long.numberOfLeadingZeros(word); // See LUCENE-3197 } while (--i >= 0) { word = bits[i]; if (word !=0 ) { return (i << 6) + 63 - Long.numberOfLeadingZeros(word); } } return -1; } /** Does in-place OR of the bits provided by the * iterator. */ public void or(DocIdSetIterator iter) throws IOException { if (iter instanceof OpenBitSetIterator && iter.docID() == -1) { final OpenBitSetIterator obs = (OpenBitSetIterator) iter; or(obs.arr, obs.words); } else { int doc; while ((doc = iter.nextDoc()) < numBits) { set(doc); } } } /** this = this OR other */ public void or(FixedBitSet other) { or(other.bits, other.bits.length); } private void or(final long[] otherArr, final int otherLen) { final long[] thisArr = this.bits; int pos = Math.min(thisArr.length, otherLen); while (--pos >= 0) { thisArr[pos] |= otherArr[pos]; } } /** Does in-place AND of the bits provided by the * iterator. */ public void and(DocIdSetIterator iter) throws IOException { if (iter instanceof OpenBitSetIterator && iter.docID() == -1) { final OpenBitSetIterator obs = (OpenBitSetIterator) iter; and(obs.arr, obs.words); } else { if (numBits == 0) return; int disiDoc, bitSetDoc = nextSetBit(0); while (bitSetDoc != -1 && (disiDoc = iter.advance(bitSetDoc)) < numBits) { clear(bitSetDoc, disiDoc); disiDoc++; bitSetDoc = (disiDoc < numBits) ? nextSetBit(disiDoc) : -1; } if (bitSetDoc != -1) { clear(bitSetDoc, numBits); } } } /** this = this AND other */ public void and(FixedBitSet other) { and(other.bits, other.bits.length); } private void and(final long[] otherArr, final int otherLen) { final long[] thisArr = this.bits; int pos = Math.min(thisArr.length, otherLen); while(--pos >= 0) { thisArr[pos] &= otherArr[pos]; } if (thisArr.length > otherLen) { Arrays.fill(thisArr, otherLen, thisArr.length, 0L); } } /** Does in-place AND NOT of the bits provided by the * iterator. */ public void andNot(DocIdSetIterator iter) throws IOException { if (iter instanceof OpenBitSetIterator && iter.docID() == -1) { final OpenBitSetIterator obs = (OpenBitSetIterator) iter; andNot(obs.arr, obs.words); } else { int doc; while ((doc = iter.nextDoc()) < numBits) { clear(doc); } } } /** this = this AND NOT other */ public void andNot(FixedBitSet other) { andNot(other.bits, other.bits.length); } private void andNot(final long[] otherArr, final int otherLen) { final long[] thisArr = this.bits; int pos = Math.min(thisArr.length, otherLen); while(--pos >= 0) { thisArr[pos] &= ~otherArr[pos]; } } // NOTE: no .isEmpty() here because that's trappy (ie, // typically isEmpty is low cost, but this one wouldn't // be) /** Flips a range of bits * * @param startIndex lower index * @param endIndex one-past the last bit to flip */ public void flip(int startIndex, int endIndex) { assert startIndex >= 0 && startIndex < numBits; assert endIndex >= 0 && endIndex <= numBits; if (endIndex <= startIndex) { return; } int startWord = startIndex >> 6; int endWord = (endIndex-1) >> 6; /*** Grrr, java shifting wraps around so -1L>>>64 == -1 * for that reason, make sure not to use endmask if the bits to flip will * be zero in the last word (redefine endWord to be the last changed...) long startmask = -1L << (startIndex & 0x3f); // example: 11111...111000 long endmask = -1L >>> (64-(endIndex & 0x3f)); // example: 00111...111111 ***/ long startmask = -1L << startIndex; long endmask = -1L >>> -endIndex; // 64-(endIndex&0x3f) is the same as -endIndex due to wrap if (startWord == endWord) { bits[startWord] ^= (startmask & endmask); return; } bits[startWord] ^= startmask; for (int i=startWord+1; i<endWord; i++) { bits[i] = ~bits[i]; } bits[endWord] ^= endmask; } /** Sets a range of bits * * @param startIndex lower index * @param endIndex one-past the last bit to set */ public void set(int startIndex, int endIndex) { assert startIndex >= 0 && startIndex < numBits; assert endIndex >= 0 && endIndex <= numBits; if (endIndex <= startIndex) { return; } int startWord = startIndex >> 6; int endWord = (endIndex-1) >> 6; long startmask = -1L << startIndex; long endmask = -1L >>> -endIndex; // 64-(endIndex&0x3f) is the same as -endIndex due to wrap if (startWord == endWord) { bits[startWord] |= (startmask & endmask); return; } bits[startWord] |= startmask; Arrays.fill(bits, startWord+1, endWord, -1L); bits[endWord] |= endmask; } /** Clears a range of bits. * * @param startIndex lower index * @param endIndex one-past the last bit to clear */ public void clear(int startIndex, int endIndex) { assert startIndex >= 0 && startIndex < numBits; assert endIndex >= 0 && endIndex <= numBits; if (endIndex <= startIndex) { return; } int startWord = startIndex >> 6; int endWord = (endIndex-1) >> 6; long startmask = -1L << startIndex; long endmask = -1L >>> -endIndex; // 64-(endIndex&0x3f) is the same as -endIndex due to wrap // invert masks since we are clearing startmask = ~startmask; endmask = ~endmask; if (startWord == endWord) { bits[startWord] &= (startmask | endmask); return; } bits[startWord] &= startmask; Arrays.fill(bits, startWord+1, endWord, 0L); bits[endWord] &= endmask; } @Override public Object clone() { return new FixedBitSet(this); } /** returns true if both sets have the same bits set */ @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof FixedBitSet)) { return false; } FixedBitSet other = (FixedBitSet) o; if (numBits != other.length()) { return false; } return Arrays.equals(bits, other.bits); } @Override public int hashCode() { long h = 0; for (int i = bits.length; --i>=0;) { h ^= bits[i]; h = (h << 1) | (h >>> 63); // rotate left } // fold leftmost bits into right and add a constant to prevent // empty sets from returning 0, which is too common. return (int) ((h>>32) ^ h) + 0x98761234; } }
LUCENE-3448: Make optimization for OpenBitSetIterator correctly exhaust iterator git-svn-id: 308d55f399f3bd9aa0560a10e81a003040006c48@1204416 13f79535-47bb-0310-9956-ffa450edef68
lucene/src/java/org/apache/lucene/util/FixedBitSet.java
LUCENE-3448: Make optimization for OpenBitSetIterator correctly exhaust iterator
Java
apache-2.0
ee4f1a7d3b7ffe73d4d73d32add6d5850a39d1d7
0
realityforge/arez,realityforge/arez,realityforge/arez
package arez.test; import arez.AbstractArezTest; import arez.Arez; import arez.ArezContext; import arez.ArezObserverTestUtil; import arez.ArezTestUtil; import arez.ComputedValue; import arez.Disposable; import arez.Observable; import arez.Observer; import arez.ObserverErrorHandler; import arez.Procedure; import arez.SpyEventHandler; import arez.Zone; import java.util.Objects; import java.util.concurrent.atomic.AtomicInteger; import javax.annotation.Nonnull; import org.realityforge.guiceyloops.shared.ValueUtil; import org.testng.annotations.Test; import static org.testng.Assert.*; /** * This class tests all the public API of Arez and identifies all * the elements that should be visible outside package. */ @SuppressWarnings( "Duplicates" ) public class ExternalApiTest extends AbstractArezTest { @Test public void triggerScheduler() { final ArezContext context = Arez.context(); final AtomicInteger callCount = new AtomicInteger(); context.autorun( ValueUtil.randomString(), false, callCount::incrementAndGet, false ); assertEquals( callCount.get(), 0 ); context.triggerScheduler(); assertEquals( callCount.get(), 1 ); } @Test public void areNamesEnabled() throws Exception { assertTrue( Arez.areNamesEnabled() ); ArezTestUtil.disableNames(); assertFalse( Arez.areNamesEnabled() ); } @Test public void arePropertyIntrospectorsEnabled() { assertTrue( Arez.arePropertyIntrospectorsEnabled() ); ArezTestUtil.disablePropertyIntrospectors(); assertFalse( Arez.arePropertyIntrospectorsEnabled() ); } @Test public void areRepositoryResultsUnmodifiable() { assertTrue( Arez.areCollectionsPropertiesUnmodifiable() ); ArezTestUtil.makeCollectionPropertiesModifiable(); assertFalse( Arez.areCollectionsPropertiesUnmodifiable() ); } @Test public void areSpiesEnabled() { assertTrue( Arez.areSpiesEnabled() ); ArezTestUtil.disableSpies(); assertFalse( Arez.areSpiesEnabled() ); } @Test public void areZonesEnabled() { ArezTestUtil.disableZones(); assertFalse( Arez.areZonesEnabled() ); ArezTestUtil.enableZones(); assertTrue( Arez.areZonesEnabled() ); } @Test public void areNativeComponentsEnabled() { assertTrue( Arez.areNativeComponentsEnabled() ); ArezTestUtil.disableNativeComponents(); assertFalse( Arez.areNativeComponentsEnabled() ); } @Test public void areRegistriesEnabled() { assertTrue( Arez.areRegistriesEnabled() ); ArezTestUtil.disableRegistries(); assertFalse( Arez.areRegistriesEnabled() ); } @Test public void createComputedValue() throws Throwable { final ArezContext context = Arez.context(); final String name = ValueUtil.randomString(); final ComputedValue<String> computedValue = context.createComputedValue( name, () -> "", Objects::equals ); context.action( ValueUtil.randomString(), true, () -> { assertEquals( computedValue.getName(), name ); assertEquals( computedValue.get(), "" ); assertEquals( context.isTransactionActive(), true ); computedValue.dispose(); assertThrows( computedValue::get ); } ); } @Test public void createReactionObserver() throws Exception { final ArezContext context = Arez.context(); final AtomicInteger callCount = new AtomicInteger(); final String name = ValueUtil.randomString(); final Observer observer = context.autorun( name, false, callCount::incrementAndGet, true ); assertEquals( observer.getName(), name ); assertEquals( ArezObserverTestUtil.isActive( observer ), true ); assertEquals( callCount.get(), 1 ); observer.dispose(); assertEquals( ArezObserverTestUtil.isActive( observer ), false ); } @Test public void observerErrorHandler() throws Exception { setIgnoreObserverErrors( true ); setPrintObserverErrors( false ); final ArezContext context = Arez.context(); final AtomicInteger callCount = new AtomicInteger(); final ObserverErrorHandler handler = ( observer, error, throwable ) -> callCount.incrementAndGet(); context.addObserverErrorHandler( handler ); final Procedure reaction = () -> { throw new RuntimeException(); }; // This will run immediately and generate an exception context.autorun( ValueUtil.randomString(), false, reaction, true ); assertEquals( callCount.get(), 1 ); context.removeObserverErrorHandler( handler ); // This will run immediately and generate an exception context.autorun( ValueUtil.randomString(), false, reaction, true ); assertEquals( callCount.get(), 1 ); } @Test public void spyEventHandler() throws Exception { final ArezContext context = Arez.context(); final AtomicInteger callCount = new AtomicInteger(); final SpyEventHandler handler = e -> callCount.incrementAndGet(); context.getSpy().addSpyEventHandler( handler ); // Generate an event context.createObservable(); assertEquals( callCount.get(), 1 ); context.getSpy().removeSpyEventHandler( handler ); // Generate an event context.createObservable(); assertEquals( callCount.get(), 1 ); } @Test public void safeProcedure_interactionWithSingleObservable() throws Exception { final ArezContext context = Arez.context(); final Observable observable = context.createObservable(); final AtomicInteger reactionCount = new AtomicInteger(); final Observer observer = context.autorun( ValueUtil.randomString(), false, () -> { observable.reportObserved(); reactionCount.incrementAndGet(); }, true ); assertEquals( reactionCount.get(), 1 ); assertEquals( ArezObserverTestUtil.isActive( observer ), true ); context.safeAction( ValueUtil.randomString(), true, observable::reportChanged ); assertEquals( reactionCount.get(), 2 ); assertEquals( ArezObserverTestUtil.isActive( observer ), true ); } @Test public void interactionWithSingleObservable() throws Throwable { final ArezContext context = Arez.context(); final Observable observable = context.createObservable(); final AtomicInteger reactionCount = new AtomicInteger(); final Observer observer = context.autorun( ValueUtil.randomString(), false, () -> { observable.reportObserved(); reactionCount.incrementAndGet(); }, true ); assertEquals( reactionCount.get(), 1 ); assertEquals( ArezObserverTestUtil.isActive( observer ), true ); // Run an "action" context.action( ValueUtil.randomString(), true, observable::reportChanged ); assertEquals( reactionCount.get(), 2 ); assertEquals( ArezObserverTestUtil.isActive( observer ), true ); } @Test public void interactionWithMultipleObservable() throws Throwable { final ArezContext context = Arez.context(); final Observable observable1 = context.createObservable(); final Observable observable2 = context.createObservable(); final Observable observable3 = context.createObservable(); final Observable observable4 = context.createObservable(); final AtomicInteger reactionCount = new AtomicInteger(); final Observer observer = context.autorun( ValueUtil.randomString(), false, () -> { observable1.reportObserved(); observable2.reportObserved(); observable3.reportObserved(); reactionCount.incrementAndGet(); }, true ); assertEquals( reactionCount.get(), 1 ); assertEquals( ArezObserverTestUtil.isActive( observer ), true ); // Run an "action" context.action( ValueUtil.randomString(), true, observable1::reportChanged ); assertEquals( reactionCount.get(), 2 ); assertEquals( ArezObserverTestUtil.isActive( observer ), true ); // Update observer1+observer2 in transaction context.action( ValueUtil.randomString(), true, () -> { observable1.reportChanged(); observable2.reportChanged(); } ); assertEquals( reactionCount.get(), 3 ); assertEquals( ArezObserverTestUtil.isActive( observer ), true ); context.action( ValueUtil.randomString(), true, () -> { observable3.reportChanged(); observable4.reportChanged(); } ); assertEquals( reactionCount.get(), 4 ); assertEquals( ArezObserverTestUtil.isActive( observer ), true ); // observable4 should not cause a reaction as not observed context.action( ValueUtil.randomString(), true, observable4::reportChanged ); assertEquals( reactionCount.get(), 4 ); assertEquals( ArezObserverTestUtil.isActive( observer ), true ); } @Test public void action_function() throws Throwable { final ArezContext context = Arez.context(); final Observable observable = context.createObservable(); assertNotInTransaction( context, observable ); final String expectedValue = ValueUtil.randomString(); final String v0 = context.action( ValueUtil.randomString(), false, () -> { assertInTransaction( context, observable ); return expectedValue; } ); assertNotInTransaction( context, observable ); assertEquals( v0, expectedValue ); } @Test public void action_safeFunction() throws Exception { final ArezContext context = Arez.context(); final Observable observable = context.createObservable(); assertNotInTransaction( context, observable ); final String expectedValue = ValueUtil.randomString(); final String v0 = context.safeAction( ValueUtil.randomString(), false, () -> { assertInTransaction( context, observable ); return expectedValue; } ); assertNotInTransaction( context, observable ); assertEquals( v0, expectedValue ); } @Test public void proceduresCanBeNested() throws Throwable { final ArezContext context = Arez.context(); final Observable observable = context.createObservable(); assertNotInTransaction( context, observable ); context.action( ValueUtil.randomString(), false, () -> { assertInTransaction( context, observable ); //First nested exception context.action( ValueUtil.randomString(), false, () -> { assertInTransaction( context, observable ); //Second nested exception context.action( ValueUtil.randomString(), false, () -> assertInTransaction( context, observable ) ); assertInTransaction( context, observable ); } ); assertInTransaction( context, observable ); } ); assertNotInTransaction( context, observable ); } @Test public void action_nestedFunctions() throws Throwable { final ArezContext context = Arez.context(); final Observable observable = context.createObservable(); assertNotInTransaction( context, observable ); final String expectedValue = ValueUtil.randomString(); final String v0 = context.action( ValueUtil.randomString(), false, () -> { assertInTransaction( context, observable ); //First nested exception final String v1 = context.action( ValueUtil.randomString(), false, () -> { assertInTransaction( context, observable ); //Second nested exception final String v2 = context.action( ValueUtil.randomString(), false, () -> { assertInTransaction( context, observable ); return expectedValue; } ); assertInTransaction( context, observable ); return v2; } ); assertInTransaction( context, observable ); return v1; } ); assertNotInTransaction( context, observable ); assertEquals( v0, expectedValue ); } @Test public void supportsMultipleContexts() throws Throwable { final Zone zone1 = Arez.createZone(); final Zone zone2 = Arez.createZone(); final ArezContext context1 = zone1.getContext(); final ArezContext context2 = zone2.getContext(); final Observable observable1 = context1.createObservable(); final Observable observable2 = context2.createObservable(); final AtomicInteger autorunCallCount1 = new AtomicInteger(); final AtomicInteger autorunCallCount2 = new AtomicInteger(); context1.autorun( () -> { observable1.reportObserved(); autorunCallCount1.incrementAndGet(); } ); context2.autorun( () -> { observable2.reportObserved(); autorunCallCount2.incrementAndGet(); } ); assertEquals( autorunCallCount1.get(), 1 ); assertEquals( autorunCallCount2.get(), 1 ); assertNotInTransaction( context1, observable1 ); assertNotInTransaction( context2, observable2 ); context1.action( () -> { assertInTransaction( context1, observable1 ); //First nested exception context1.action( () -> { assertInTransaction( context1, observable1 ); observable1.reportChanged(); //Second nested exception context1.action( () -> assertInTransaction( context1, observable1 ) ); context2.action( () -> { assertNotInTransaction( context1, observable1 ); assertInTransaction( context2, observable2 ); observable2.reportChanged(); context2.action( () -> { assertNotInTransaction( context1, observable1 ); assertInTransaction( context2, observable2 ); observable2.reportChanged(); } ); assertEquals( autorunCallCount1.get(), 1 ); context1.action( () -> assertInTransaction( context1, observable1 ) ); // Still no autorun reaction as it has transaction up the stack assertEquals( autorunCallCount1.get(), 1 ); assertEquals( autorunCallCount2.get(), 1 ); } ); // Second context runs now as it got to it's top level trnsaction assertEquals( autorunCallCount2.get(), 2 ); assertInTransaction( context1, observable1 ); assertNotInTransaction( context2, observable2 ); } ); assertInTransaction( context1, observable1 ); assertNotInTransaction( context2, observable2 ); } ); assertEquals( autorunCallCount1.get(), 2 ); assertEquals( autorunCallCount2.get(), 2 ); assertNotInTransaction( context1, observable1 ); assertNotInTransaction( context2, observable2 ); } @Test public void pauseScheduler() throws Exception { final ArezContext context = Arez.context(); final Disposable lock1 = context.pauseScheduler(); assertEquals( context.isSchedulerPaused(), true ); final AtomicInteger callCount = new AtomicInteger(); // This would normally be scheduled and run now but scheduler should be paused context.autorun( ValueUtil.randomString(), false, callCount::incrementAndGet, false ); context.triggerScheduler(); assertEquals( callCount.get(), 0 ); final Disposable lock2 = context.pauseScheduler(); lock2.dispose(); assertEquals( context.isSchedulerPaused(), true ); // Already disposed so this is a noop lock2.dispose(); assertEquals( callCount.get(), 0 ); lock1.dispose(); assertEquals( callCount.get(), 1 ); assertEquals( context.isSchedulerPaused(), false ); } /** * Test we are in a transaction by trying to observe an observable. */ private void assertInTransaction( @Nonnull final ArezContext context, @Nonnull final Observable observable ) { assertEquals( context.isTransactionActive(), true ); observable.reportObserved(); } /** * Test we are not in a transaction by trying to observe an observable. */ private void assertNotInTransaction( @Nonnull final ArezContext context, @Nonnull final Observable observable ) { assertEquals( context.isTransactionActive(), false ); assertThrows( observable::reportObserved ); } }
core/src/test/java/arez/test/ExternalApiTest.java
package arez.test; import arez.AbstractArezTest; import arez.Arez; import arez.ArezContext; import arez.ArezObserverTestUtil; import arez.ArezTestUtil; import arez.ComputedValue; import arez.Disposable; import arez.Observable; import arez.Observer; import arez.ObserverErrorHandler; import arez.Procedure; import arez.SpyEventHandler; import arez.Zone; import java.util.Objects; import java.util.concurrent.atomic.AtomicInteger; import javax.annotation.Nonnull; import org.realityforge.guiceyloops.shared.ValueUtil; import org.testng.annotations.Test; import static org.testng.Assert.*; /** * This class tests all the public API of Arez and identifies all * the elements that should be visible outside package. */ @SuppressWarnings( "Duplicates" ) public class ExternalApiTest extends AbstractArezTest { @Test public void triggerScheduler() { final ArezContext context = Arez.context(); final AtomicInteger callCount = new AtomicInteger(); context.autorun( ValueUtil.randomString(), false, callCount::incrementAndGet, false ); assertEquals( callCount.get(), 0 ); context.triggerScheduler(); assertEquals( callCount.get(), 1 ); } @Test public void areNamesEnabled() throws Exception { assertTrue( Arez.areNamesEnabled() ); ArezTestUtil.disableNames(); assertFalse( Arez.areNamesEnabled() ); } @Test public void arePropertyIntrospectorsEnabled() { assertTrue( Arez.arePropertyIntrospectorsEnabled() ); ArezTestUtil.disablePropertyIntrospectors(); assertFalse( Arez.arePropertyIntrospectorsEnabled() ); } @Test public void areRepositoryResultsUnmodifiable() { assertFalse( Arez.areCollectionsPropertiesUnmodifiable() ); ArezTestUtil.makeCollectionPropertiesModifiable(); assertTrue( Arez.areCollectionsPropertiesUnmodifiable() ); } @Test public void areSpiesEnabled() { assertTrue( Arez.areSpiesEnabled() ); ArezTestUtil.disableSpies(); assertFalse( Arez.areSpiesEnabled() ); } @Test public void areZonesEnabled() { ArezTestUtil.disableZones(); assertFalse( Arez.areZonesEnabled() ); ArezTestUtil.enableZones(); assertTrue( Arez.areZonesEnabled() ); } @Test public void areNativeComponentsEnabled() { assertTrue( Arez.areNativeComponentsEnabled() ); ArezTestUtil.disableNativeComponents(); assertFalse( Arez.areNativeComponentsEnabled() ); } @Test public void areRegistriesEnabled() { assertTrue( Arez.areRegistriesEnabled() ); ArezTestUtil.disableRegistries(); assertFalse( Arez.areRegistriesEnabled() ); } @Test public void createComputedValue() throws Throwable { final ArezContext context = Arez.context(); final String name = ValueUtil.randomString(); final ComputedValue<String> computedValue = context.createComputedValue( name, () -> "", Objects::equals ); context.action( ValueUtil.randomString(), true, () -> { assertEquals( computedValue.getName(), name ); assertEquals( computedValue.get(), "" ); assertEquals( context.isTransactionActive(), true ); computedValue.dispose(); assertThrows( computedValue::get ); } ); } @Test public void createReactionObserver() throws Exception { final ArezContext context = Arez.context(); final AtomicInteger callCount = new AtomicInteger(); final String name = ValueUtil.randomString(); final Observer observer = context.autorun( name, false, callCount::incrementAndGet, true ); assertEquals( observer.getName(), name ); assertEquals( ArezObserverTestUtil.isActive( observer ), true ); assertEquals( callCount.get(), 1 ); observer.dispose(); assertEquals( ArezObserverTestUtil.isActive( observer ), false ); } @Test public void observerErrorHandler() throws Exception { setIgnoreObserverErrors( true ); setPrintObserverErrors( false ); final ArezContext context = Arez.context(); final AtomicInteger callCount = new AtomicInteger(); final ObserverErrorHandler handler = ( observer, error, throwable ) -> callCount.incrementAndGet(); context.addObserverErrorHandler( handler ); final Procedure reaction = () -> { throw new RuntimeException(); }; // This will run immediately and generate an exception context.autorun( ValueUtil.randomString(), false, reaction, true ); assertEquals( callCount.get(), 1 ); context.removeObserverErrorHandler( handler ); // This will run immediately and generate an exception context.autorun( ValueUtil.randomString(), false, reaction, true ); assertEquals( callCount.get(), 1 ); } @Test public void spyEventHandler() throws Exception { final ArezContext context = Arez.context(); final AtomicInteger callCount = new AtomicInteger(); final SpyEventHandler handler = e -> callCount.incrementAndGet(); context.getSpy().addSpyEventHandler( handler ); // Generate an event context.createObservable(); assertEquals( callCount.get(), 1 ); context.getSpy().removeSpyEventHandler( handler ); // Generate an event context.createObservable(); assertEquals( callCount.get(), 1 ); } @Test public void safeProcedure_interactionWithSingleObservable() throws Exception { final ArezContext context = Arez.context(); final Observable observable = context.createObservable(); final AtomicInteger reactionCount = new AtomicInteger(); final Observer observer = context.autorun( ValueUtil.randomString(), false, () -> { observable.reportObserved(); reactionCount.incrementAndGet(); }, true ); assertEquals( reactionCount.get(), 1 ); assertEquals( ArezObserverTestUtil.isActive( observer ), true ); context.safeAction( ValueUtil.randomString(), true, observable::reportChanged ); assertEquals( reactionCount.get(), 2 ); assertEquals( ArezObserverTestUtil.isActive( observer ), true ); } @Test public void interactionWithSingleObservable() throws Throwable { final ArezContext context = Arez.context(); final Observable observable = context.createObservable(); final AtomicInteger reactionCount = new AtomicInteger(); final Observer observer = context.autorun( ValueUtil.randomString(), false, () -> { observable.reportObserved(); reactionCount.incrementAndGet(); }, true ); assertEquals( reactionCount.get(), 1 ); assertEquals( ArezObserverTestUtil.isActive( observer ), true ); // Run an "action" context.action( ValueUtil.randomString(), true, observable::reportChanged ); assertEquals( reactionCount.get(), 2 ); assertEquals( ArezObserverTestUtil.isActive( observer ), true ); } @Test public void interactionWithMultipleObservable() throws Throwable { final ArezContext context = Arez.context(); final Observable observable1 = context.createObservable(); final Observable observable2 = context.createObservable(); final Observable observable3 = context.createObservable(); final Observable observable4 = context.createObservable(); final AtomicInteger reactionCount = new AtomicInteger(); final Observer observer = context.autorun( ValueUtil.randomString(), false, () -> { observable1.reportObserved(); observable2.reportObserved(); observable3.reportObserved(); reactionCount.incrementAndGet(); }, true ); assertEquals( reactionCount.get(), 1 ); assertEquals( ArezObserverTestUtil.isActive( observer ), true ); // Run an "action" context.action( ValueUtil.randomString(), true, observable1::reportChanged ); assertEquals( reactionCount.get(), 2 ); assertEquals( ArezObserverTestUtil.isActive( observer ), true ); // Update observer1+observer2 in transaction context.action( ValueUtil.randomString(), true, () -> { observable1.reportChanged(); observable2.reportChanged(); } ); assertEquals( reactionCount.get(), 3 ); assertEquals( ArezObserverTestUtil.isActive( observer ), true ); context.action( ValueUtil.randomString(), true, () -> { observable3.reportChanged(); observable4.reportChanged(); } ); assertEquals( reactionCount.get(), 4 ); assertEquals( ArezObserverTestUtil.isActive( observer ), true ); // observable4 should not cause a reaction as not observed context.action( ValueUtil.randomString(), true, observable4::reportChanged ); assertEquals( reactionCount.get(), 4 ); assertEquals( ArezObserverTestUtil.isActive( observer ), true ); } @Test public void action_function() throws Throwable { final ArezContext context = Arez.context(); final Observable observable = context.createObservable(); assertNotInTransaction( context, observable ); final String expectedValue = ValueUtil.randomString(); final String v0 = context.action( ValueUtil.randomString(), false, () -> { assertInTransaction( context, observable ); return expectedValue; } ); assertNotInTransaction( context, observable ); assertEquals( v0, expectedValue ); } @Test public void action_safeFunction() throws Exception { final ArezContext context = Arez.context(); final Observable observable = context.createObservable(); assertNotInTransaction( context, observable ); final String expectedValue = ValueUtil.randomString(); final String v0 = context.safeAction( ValueUtil.randomString(), false, () -> { assertInTransaction( context, observable ); return expectedValue; } ); assertNotInTransaction( context, observable ); assertEquals( v0, expectedValue ); } @Test public void proceduresCanBeNested() throws Throwable { final ArezContext context = Arez.context(); final Observable observable = context.createObservable(); assertNotInTransaction( context, observable ); context.action( ValueUtil.randomString(), false, () -> { assertInTransaction( context, observable ); //First nested exception context.action( ValueUtil.randomString(), false, () -> { assertInTransaction( context, observable ); //Second nested exception context.action( ValueUtil.randomString(), false, () -> assertInTransaction( context, observable ) ); assertInTransaction( context, observable ); } ); assertInTransaction( context, observable ); } ); assertNotInTransaction( context, observable ); } @Test public void action_nestedFunctions() throws Throwable { final ArezContext context = Arez.context(); final Observable observable = context.createObservable(); assertNotInTransaction( context, observable ); final String expectedValue = ValueUtil.randomString(); final String v0 = context.action( ValueUtil.randomString(), false, () -> { assertInTransaction( context, observable ); //First nested exception final String v1 = context.action( ValueUtil.randomString(), false, () -> { assertInTransaction( context, observable ); //Second nested exception final String v2 = context.action( ValueUtil.randomString(), false, () -> { assertInTransaction( context, observable ); return expectedValue; } ); assertInTransaction( context, observable ); return v2; } ); assertInTransaction( context, observable ); return v1; } ); assertNotInTransaction( context, observable ); assertEquals( v0, expectedValue ); } @Test public void supportsMultipleContexts() throws Throwable { final Zone zone1 = Arez.createZone(); final Zone zone2 = Arez.createZone(); final ArezContext context1 = zone1.getContext(); final ArezContext context2 = zone2.getContext(); final Observable observable1 = context1.createObservable(); final Observable observable2 = context2.createObservable(); final AtomicInteger autorunCallCount1 = new AtomicInteger(); final AtomicInteger autorunCallCount2 = new AtomicInteger(); context1.autorun( () -> { observable1.reportObserved(); autorunCallCount1.incrementAndGet(); } ); context2.autorun( () -> { observable2.reportObserved(); autorunCallCount2.incrementAndGet(); } ); assertEquals( autorunCallCount1.get(), 1 ); assertEquals( autorunCallCount2.get(), 1 ); assertNotInTransaction( context1, observable1 ); assertNotInTransaction( context2, observable2 ); context1.action( () -> { assertInTransaction( context1, observable1 ); //First nested exception context1.action( () -> { assertInTransaction( context1, observable1 ); observable1.reportChanged(); //Second nested exception context1.action( () -> assertInTransaction( context1, observable1 ) ); context2.action( () -> { assertNotInTransaction( context1, observable1 ); assertInTransaction( context2, observable2 ); observable2.reportChanged(); context2.action( () -> { assertNotInTransaction( context1, observable1 ); assertInTransaction( context2, observable2 ); observable2.reportChanged(); } ); assertEquals( autorunCallCount1.get(), 1 ); context1.action( () -> assertInTransaction( context1, observable1 ) ); // Still no autorun reaction as it has transaction up the stack assertEquals( autorunCallCount1.get(), 1 ); assertEquals( autorunCallCount2.get(), 1 ); } ); // Second context runs now as it got to it's top level trnsaction assertEquals( autorunCallCount2.get(), 2 ); assertInTransaction( context1, observable1 ); assertNotInTransaction( context2, observable2 ); } ); assertInTransaction( context1, observable1 ); assertNotInTransaction( context2, observable2 ); } ); assertEquals( autorunCallCount1.get(), 2 ); assertEquals( autorunCallCount2.get(), 2 ); assertNotInTransaction( context1, observable1 ); assertNotInTransaction( context2, observable2 ); } @Test public void pauseScheduler() throws Exception { final ArezContext context = Arez.context(); final Disposable lock1 = context.pauseScheduler(); assertEquals( context.isSchedulerPaused(), true ); final AtomicInteger callCount = new AtomicInteger(); // This would normally be scheduled and run now but scheduler should be paused context.autorun( ValueUtil.randomString(), false, callCount::incrementAndGet, false ); context.triggerScheduler(); assertEquals( callCount.get(), 0 ); final Disposable lock2 = context.pauseScheduler(); lock2.dispose(); assertEquals( context.isSchedulerPaused(), true ); // Already disposed so this is a noop lock2.dispose(); assertEquals( callCount.get(), 0 ); lock1.dispose(); assertEquals( callCount.get(), 1 ); assertEquals( context.isSchedulerPaused(), false ); } /** * Test we are in a transaction by trying to observe an observable. */ private void assertInTransaction( @Nonnull final ArezContext context, @Nonnull final Observable observable ) { assertEquals( context.isTransactionActive(), true ); observable.reportObserved(); } /** * Test we are not in a transaction by trying to observe an observable. */ private void assertNotInTransaction( @Nonnull final ArezContext context, @Nonnull final Observable observable ) { assertEquals( context.isTransactionActive(), false ); assertThrows( observable::reportObserved ); } }
Fix test
core/src/test/java/arez/test/ExternalApiTest.java
Fix test
Java
apache-2.0
6ed6f862937b53c8764a0c03e1e7b22699ec0da3
0
kkroid/OnechatSmack,qingsong-xu/Smack,opg7371/Smack,Flowdalic/Smack,Tibo-lg/Smack,vanitasvitae/smack-omemo,cjpx00008/Smack,hy9902/Smack,hy9902/Smack,TTalkIM/Smack,chuangWu/Smack,u20024804/Smack,esl/Smack,vanitasvitae/Smack,magnetsystems/message-smack,Tibo-lg/Smack,annovanvliet/Smack,vito-c/Smack,igorexax3mal/Smack,Tibo-lg/Smack,unisontech/Smack,ayne/Smack,kkroid/OnechatSmack,opg7371/Smack,mar-v-in/Smack,igorexax3mal/Smack,esl/Smack,ishan1604/Smack,igorexax3mal/Smack,kkroid/OnechatSmack,chuangWu/Smack,opg7371/Smack,vito-c/Smack,mar-v-in/Smack,xuIcream/Smack,esl/Smack,vanitasvitae/smack-omemo,magnetsystems/message-smack,magnetsystems/message-smack,andrey42/Smack,qingsong-xu/Smack,andrey42/Smack,andrey42/Smack,xuIcream/Smack,u20024804/Smack,ishan1604/Smack,vanitasvitae/Smack,deeringc/Smack,ayne/Smack,hy9902/Smack,dpr-odoo/Smack,Flowdalic/Smack,lovely3x/Smack,cjpx00008/Smack,TTalkIM/Smack,unisontech/Smack,xuIcream/Smack,TTalkIM/Smack,dpr-odoo/Smack,ayne/Smack,vanitasvitae/Smack,unisontech/Smack,annovanvliet/Smack,igniterealtime/Smack,ishan1604/Smack,lovely3x/Smack,mar-v-in/Smack,lovely3x/Smack,chuangWu/Smack,annovanvliet/Smack,u20024804/Smack,Flowdalic/Smack,qingsong-xu/Smack,cjpx00008/Smack,igniterealtime/Smack,dpr-odoo/Smack,igniterealtime/Smack,deeringc/Smack,deeringc/Smack,vanitasvitae/smack-omemo
/** * $RCSfile$ * $Revision$ * $Date$ * * Copyright 2003-2007 Jive Software. * * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jivesoftware.smack; import org.jivesoftware.smack.compression.XMPPInputOutputStream; import org.jivesoftware.smack.filter.PacketFilter; import org.jivesoftware.smack.packet.Packet; import org.jivesoftware.smack.packet.Presence; import org.jivesoftware.smack.packet.XMPPError; import org.jivesoftware.smack.parsing.ParsingExceptionCallback; import org.jivesoftware.smack.util.StringUtils; import org.jivesoftware.smack.util.dns.HostAddress; import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocket; import javax.security.auth.callback.Callback; import javax.security.auth.callback.CallbackHandler; import javax.security.auth.callback.PasswordCallback; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.ByteArrayInputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.lang.reflect.Constructor; import java.net.Socket; import java.net.UnknownHostException; import java.security.KeyStore; import java.security.Provider; import java.security.Security; import java.util.Collection; import java.util.Iterator; import java.util.LinkedList; import java.util.List; /** * Creates a socket connection to a XMPP server. This is the default connection * to a Jabber server and is specified in the XMPP Core (RFC 3920). * * @see Connection * @author Matt Tucker */ public class XMPPConnection extends Connection { /** * The socket which is used for this connection. */ Socket socket; String connectionID = null; private String user = null; private boolean connected = false; // socketClosed is used concurrent // by XMPPConnection, PacketReader, PacketWriter private volatile boolean socketClosed = false; /** * Flag that indicates if the user is currently authenticated with the server. */ private boolean authenticated = false; /** * Flag that indicates if the user was authenticated with the server when the connection * to the server was closed (abruptly or not). */ private boolean wasAuthenticated = false; private boolean anonymous = false; private boolean usingTLS = false; private ParsingExceptionCallback parsingExceptionCallback = SmackConfiguration.getDefaultParsingExceptionCallback(); PacketWriter packetWriter; PacketReader packetReader; Roster roster = null; /** * Collection of available stream compression methods offered by the server. */ private Collection<String> compressionMethods; /** * Set to true by packet writer if the server acknowledged the compression */ private boolean serverAckdCompression = false; /** * Creates a new connection to the specified XMPP server. A DNS SRV lookup will be * performed to determine the IP address and port corresponding to the * service name; if that lookup fails, it's assumed that server resides at * <tt>serviceName</tt> with the default port of 5222. Encrypted connections (TLS) * will be used if available, stream compression is disabled, and standard SASL * mechanisms will be used for authentication.<p> * <p/> * This is the simplest constructor for connecting to an XMPP server. Alternatively, * you can get fine-grained control over connection settings using the * {@link #XMPPConnection(ConnectionConfiguration)} constructor.<p> * <p/> * Note that XMPPConnection constructors do not establish a connection to the server * and you must call {@link #connect()}.<p> * <p/> * The CallbackHandler will only be used if the connection requires the client provide * an SSL certificate to the server. The CallbackHandler must handle the PasswordCallback * to prompt for a password to unlock the keystore containing the SSL certificate. * * @param serviceName the name of the XMPP server to connect to; e.g. <tt>example.com</tt>. * @param callbackHandler the CallbackHandler used to prompt for the password to the keystore. */ public XMPPConnection(String serviceName, CallbackHandler callbackHandler) { // Create the configuration for this new connection super(new ConnectionConfiguration(serviceName)); config.setCompressionEnabled(false); config.setSASLAuthenticationEnabled(true); config.setDebuggerEnabled(DEBUG_ENABLED); config.setCallbackHandler(callbackHandler); } /** * Creates a new XMPP connection in the same way {@link #XMPPConnection(String,CallbackHandler)} does, but * with no callback handler for password prompting of the keystore. This will work * in most cases, provided the client is not required to provide a certificate to * the server. * * @param serviceName the name of the XMPP server to connect to; e.g. <tt>example.com</tt>. */ public XMPPConnection(String serviceName) { // Create the configuration for this new connection super(new ConnectionConfiguration(serviceName)); config.setCompressionEnabled(false); config.setSASLAuthenticationEnabled(true); config.setDebuggerEnabled(DEBUG_ENABLED); } /** * Creates a new XMPP connection in the same way {@link #XMPPConnection(ConnectionConfiguration,CallbackHandler)} does, but * with no callback handler for password prompting of the keystore. This will work * in most cases, provided the client is not required to provide a certificate to * the server. * * * @param config the connection configuration. */ public XMPPConnection(ConnectionConfiguration config) { super(config); } /** * Creates a new XMPP connection using the specified connection configuration.<p> * <p/> * Manually specifying connection configuration information is suitable for * advanced users of the API. In many cases, using the * {@link #XMPPConnection(String)} constructor is a better approach.<p> * <p/> * Note that XMPPConnection constructors do not establish a connection to the server * and you must call {@link #connect()}.<p> * <p/> * * The CallbackHandler will only be used if the connection requires the client provide * an SSL certificate to the server. The CallbackHandler must handle the PasswordCallback * to prompt for a password to unlock the keystore containing the SSL certificate. * * @param config the connection configuration. * @param callbackHandler the CallbackHandler used to prompt for the password to the keystore. */ public XMPPConnection(ConnectionConfiguration config, CallbackHandler callbackHandler) { super(config); config.setCallbackHandler(callbackHandler); } public String getConnectionID() { if (!isConnected()) { return null; } return connectionID; } public String getUser() { if (!isAuthenticated()) { return null; } return user; } /** * Install a parsing exception callback, which will be invoked once an exception is encountered while parsing a * stanza * * @param callback the callback to install */ public void setParsingExceptionCallback(ParsingExceptionCallback callback) { parsingExceptionCallback = callback; } /** * Get the current active parsing exception callback. * * @return the active exception callback or null if there is none */ public ParsingExceptionCallback getParsingExceptionCallback() { return parsingExceptionCallback; } @Override public synchronized void login(String username, String password, String resource) throws XMPPException { if (!isConnected()) { throw new IllegalStateException("Not connected to server."); } if (authenticated) { throw new IllegalStateException("Already logged in to server."); } // Do partial version of nameprep on the username. username = username.toLowerCase().trim(); String response; if (config.isSASLAuthenticationEnabled() && saslAuthentication.hasNonAnonymousAuthentication()) { // Authenticate using SASL if (password != null) { response = saslAuthentication.authenticate(username, password, resource); } else { response = saslAuthentication .authenticate(username, resource, config.getCallbackHandler()); } } else { // Authenticate using Non-SASL response = new NonSASLAuthentication(this).authenticate(username, password, resource); } // Set the user. if (response != null) { this.user = response; // Update the serviceName with the one returned by the server config.setServiceName(StringUtils.parseServer(response)); } else { this.user = username + "@" + getServiceName(); if (resource != null) { this.user += "/" + resource; } } // If compression is enabled then request the server to use stream compression if (config.isCompressionEnabled()) { useCompression(); } // Indicate that we're now authenticated. authenticated = true; anonymous = false; // Create the roster if it is not a reconnection or roster already created by getRoster() if (this.roster == null) { this.roster = new Roster(this); } if (config.isRosterLoadedAtLogin()) { this.roster.reload(); } // Set presence to online. if (config.isSendPresence()) { packetWriter.sendPacket(new Presence(Presence.Type.available)); } // Stores the authentication for future reconnection config.setLoginInfo(username, password, resource); // If debugging is enabled, change the the debug window title to include the // name we are now logged-in as. // If DEBUG_ENABLED was set to true AFTER the connection was created the debugger // will be null if (config.isDebuggerEnabled() && debugger != null) { debugger.userHasLogged(user); } } @Override public synchronized void loginAnonymously() throws XMPPException { if (!isConnected()) { throw new IllegalStateException("Not connected to server."); } if (authenticated) { throw new IllegalStateException("Already logged in to server."); } String response; if (config.isSASLAuthenticationEnabled() && saslAuthentication.hasAnonymousAuthentication()) { response = saslAuthentication.authenticateAnonymously(); } else { // Authenticate using Non-SASL response = new NonSASLAuthentication(this).authenticateAnonymously(); } // Set the user value. this.user = response; // Update the serviceName with the one returned by the server config.setServiceName(StringUtils.parseServer(response)); // If compression is enabled then request the server to use stream compression if (config.isCompressionEnabled()) { useCompression(); } // Set presence to online. packetWriter.sendPacket(new Presence(Presence.Type.available)); // Indicate that we're now authenticated. authenticated = true; anonymous = true; // If debugging is enabled, change the the debug window title to include the // name we are now logged-in as. // If DEBUG_ENABLED was set to true AFTER the connection was created the debugger // will be null if (config.isDebuggerEnabled() && debugger != null) { debugger.userHasLogged(user); } } public Roster getRoster() { // synchronize against login() synchronized(this) { // if connection is authenticated the roster is already set by login() // or a previous call to getRoster() if (!isAuthenticated() || isAnonymous()) { if (roster == null) { roster = new Roster(this); } return roster; } } if (!config.isRosterLoadedAtLogin()) { roster.reload(); } // If this is the first time the user has asked for the roster after calling // login, we want to wait for the server to send back the user's roster. This // behavior shields API users from having to worry about the fact that roster // operations are asynchronous, although they'll still have to listen for // changes to the roster. Note: because of this waiting logic, internal // Smack code should be wary about calling the getRoster method, and may need to // access the roster object directly. if (!roster.rosterInitialized) { try { synchronized (roster) { long waitTime = SmackConfiguration.getPacketReplyTimeout(); long start = System.currentTimeMillis(); while (!roster.rosterInitialized) { if (waitTime <= 0) { break; } roster.wait(waitTime); long now = System.currentTimeMillis(); waitTime -= now - start; start = now; } } } catch (InterruptedException ie) { // Ignore. } } return roster; } public boolean isConnected() { return connected; } public boolean isSecureConnection() { return isUsingTLS(); } public boolean isSocketClosed() { return socketClosed; } public boolean isAuthenticated() { return authenticated; } public boolean isAnonymous() { return anonymous; } /** * Closes the connection by setting presence to unavailable then closing the stream to * the XMPP server. The shutdown logic will be used during a planned disconnection or when * dealing with an unexpected disconnection. Unlike {@link #disconnect()} the connection's * packet reader, packet writer, and {@link Roster} will not be removed; thus * connection's state is kept. * * @param unavailablePresence the presence packet to send during shutdown. */ protected void shutdown(Presence unavailablePresence) { // Set presence to offline. if (packetWriter != null) { packetWriter.sendPacket(unavailablePresence); } this.setWasAuthenticated(authenticated); authenticated = false; if (packetReader != null) { packetReader.shutdown(); } if (packetWriter != null) { packetWriter.shutdown(); } // Wait 150 ms for processes to clean-up, then shutdown. try { Thread.sleep(150); } catch (Exception e) { // Ignore. } // Set socketClosed to true. This will cause the PacketReader // and PacketWriter to ignore any Exceptions that are thrown // because of a read/write from/to a closed stream. // It is *important* that this is done before socket.close()! socketClosed = true; try { socket.close(); } catch (Exception e) { e.printStackTrace(); } // In most cases the close() should be successful, so set // connected to false here. connected = false; reader = null; writer = null; saslAuthentication.init(); } public synchronized void disconnect(Presence unavailablePresence) { // If not connected, ignore this request. if (packetReader == null || packetWriter == null) { return; } if (!isConnected()) { return; } shutdown(unavailablePresence); if (roster != null) { roster.cleanup(); roster = null; } wasAuthenticated = false; packetWriter.cleanup(); packetReader.cleanup(); } public void sendPacket(Packet packet) { if (!isConnected()) { throw new IllegalStateException("Not connected to server."); } if (packet == null) { throw new NullPointerException("Packet is null."); } packetWriter.sendPacket(packet); } /** * Registers a packet interceptor with this connection. The interceptor will be * invoked every time a packet is about to be sent by this connection. Interceptors * may modify the packet to be sent. A packet filter determines which packets * will be delivered to the interceptor. * * @param packetInterceptor the packet interceptor to notify of packets about to be sent. * @param packetFilter the packet filter to use. * @deprecated replaced by {@link Connection#addPacketInterceptor(PacketInterceptor, PacketFilter)}. */ public void addPacketWriterInterceptor(PacketInterceptor packetInterceptor, PacketFilter packetFilter) { addPacketInterceptor(packetInterceptor, packetFilter); } /** * Removes a packet interceptor. * * @param packetInterceptor the packet interceptor to remove. * @deprecated replaced by {@link Connection#removePacketInterceptor(PacketInterceptor)}. */ public void removePacketWriterInterceptor(PacketInterceptor packetInterceptor) { removePacketInterceptor(packetInterceptor); } /** * Registers a packet listener with this connection. The listener will be * notified of every packet that this connection sends. A packet filter determines * which packets will be delivered to the listener. Note that the thread * that writes packets will be used to invoke the listeners. Therefore, each * packet listener should complete all operations quickly or use a different * thread for processing. * * @param packetListener the packet listener to notify of sent packets. * @param packetFilter the packet filter to use. * @deprecated replaced by {@link #addPacketSendingListener(PacketListener, PacketFilter)}. */ public void addPacketWriterListener(PacketListener packetListener, PacketFilter packetFilter) { addPacketSendingListener(packetListener, packetFilter); } /** * Removes a packet listener for sending packets from this connection. * * @param packetListener the packet listener to remove. * @deprecated replaced by {@link #removePacketSendingListener(PacketListener)}. */ public void removePacketWriterListener(PacketListener packetListener) { removePacketSendingListener(packetListener); } private void connectUsingConfiguration(ConnectionConfiguration config) throws XMPPException { XMPPException exception = null; Iterator<HostAddress> it = config.getHostAddresses().iterator(); List<HostAddress> failedAddresses = new LinkedList<HostAddress>(); boolean xmppIOError = false; while (it.hasNext()) { exception = null; HostAddress hostAddress = it.next(); String host = hostAddress.getFQDN(); int port = hostAddress.getPort(); try { if (config.getSocketFactory() == null) { this.socket = new Socket(host, port); } else { this.socket = config.getSocketFactory().createSocket(host, port); } } catch (UnknownHostException uhe) { String errorMessage = "Could not connect to " + host + ":" + port + "."; exception = new XMPPException(errorMessage, new XMPPError(XMPPError.Condition.remote_server_timeout, errorMessage), uhe); } catch (IOException ioe) { String errorMessage = "XMPPError connecting to " + host + ":" + port + "."; exception = new XMPPException(errorMessage, new XMPPError(XMPPError.Condition.remote_server_error, errorMessage), ioe); xmppIOError = true; } if (exception == null) { // We found a host to connect to, break here config.setUsedHostAddress(hostAddress); break; } hostAddress.setException(exception); failedAddresses.add(hostAddress); if (!it.hasNext()) { // There are no more host addresses to try // throw an exception and report all tried // HostAddresses in the exception StringBuilder sb = new StringBuilder(); for (HostAddress fha : failedAddresses) { sb.append(fha.getErrorMessage()); sb.append("; "); } XMPPError xmppError; if (xmppIOError) { xmppError = new XMPPError(XMPPError.Condition.remote_server_error); } else { xmppError = new XMPPError(XMPPError.Condition.remote_server_timeout); } throw new XMPPException(sb.toString(), xmppError); } } socketClosed = false; initConnection(); } /** * Initializes the connection by creating a packet reader and writer and opening a * XMPP stream to the server. * * @throws XMPPException if establishing a connection to the server fails. */ private void initConnection() throws XMPPException { boolean isFirstInitialization = packetReader == null || packetWriter == null; compressionHandler = null; serverAckdCompression = false; // Set the reader and writer instance variables initReaderAndWriter(); try { if (isFirstInitialization) { packetWriter = new PacketWriter(this); packetReader = new PacketReader(this); // If debugging is enabled, we should start the thread that will listen for // all packets and then log them. if (config.isDebuggerEnabled()) { addPacketListener(debugger.getReaderListener(), null); if (debugger.getWriterListener() != null) { addPacketSendingListener(debugger.getWriterListener(), null); } } } else { packetWriter.init(); packetReader.init(); } // Start the packet writer. This will open a XMPP stream to the server packetWriter.startup(); // Start the packet reader. The startup() method will block until we // get an opening stream packet back from server. packetReader.startup(); // Make note of the fact that we're now connected. connected = true; if (isFirstInitialization) { // Notify listeners that a new connection has been established for (ConnectionCreationListener listener : getConnectionCreationListeners()) { listener.connectionCreated(this); } } else if (!wasAuthenticated) { notifyReconnection(); } } catch (XMPPException ex) { // An exception occurred in setting up the connection. Make sure we shut down the // readers and writers and close the socket. if (packetWriter != null) { try { packetWriter.shutdown(); } catch (Throwable ignore) { /* ignore */ } packetWriter = null; } if (packetReader != null) { try { packetReader.shutdown(); } catch (Throwable ignore) { /* ignore */ } packetReader = null; } if (reader != null) { try { reader.close(); } catch (Throwable ignore) { /* ignore */ } reader = null; } if (writer != null) { try { writer.close(); } catch (Throwable ignore) { /* ignore */} writer = null; } if (socket != null) { try { socket.close(); } catch (Exception e) { /* ignore */ } socket = null; } this.setWasAuthenticated(authenticated); authenticated = false; connected = false; throw ex; // Everything stoppped. Now throw the exception. } } private void initReaderAndWriter() throws XMPPException { try { if (compressionHandler == null) { reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8")); writer = new BufferedWriter( new OutputStreamWriter(socket.getOutputStream(), "UTF-8")); } else { try { OutputStream os = compressionHandler.getOutputStream(socket.getOutputStream()); writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); InputStream is = compressionHandler.getInputStream(socket.getInputStream()); reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); } catch (Exception e) { e.printStackTrace(); compressionHandler = null; reader = new BufferedReader( new InputStreamReader(socket.getInputStream(), "UTF-8")); writer = new BufferedWriter( new OutputStreamWriter(socket.getOutputStream(), "UTF-8")); } } } catch (IOException ioe) { throw new XMPPException( "XMPPError establishing connection with server.", new XMPPError(XMPPError.Condition.remote_server_error, "XMPPError establishing connection with server."), ioe); } // If debugging is enabled, we open a window and write out all network traffic. initDebugger(); } /*********************************************** * TLS code below **********************************************/ /** * Returns true if the connection to the server has successfully negotiated TLS. Once TLS * has been negotiatied the connection has been secured. * * @return true if the connection to the server has successfully negotiated TLS. */ public boolean isUsingTLS() { return usingTLS; } /** * Notification message saying that the server supports TLS so confirm the server that we * want to secure the connection. * * @param required true when the server indicates that TLS is required. */ void startTLSReceived(boolean required) { if (required && config.getSecurityMode() == ConnectionConfiguration.SecurityMode.disabled) { notifyConnectionError(new IllegalStateException( "TLS required by server but not allowed by connection configuration")); return; } if (config.getSecurityMode() == ConnectionConfiguration.SecurityMode.disabled) { // Do not secure the connection using TLS since TLS was disabled return; } try { writer.write("<starttls xmlns=\"urn:ietf:params:xml:ns:xmpp-tls\"/>"); writer.flush(); } catch (IOException e) { notifyConnectionError(e); } } /** * The server has indicated that TLS negotiation can start. We now need to secure the * existing plain connection and perform a handshake. This method won't return until the * connection has finished the handshake or an error occured while securing the connection. * * @throws Exception if an exception occurs. */ void proceedTLSReceived() throws Exception { SSLContext context = this.config.getCustomSSLContext(); KeyStore ks = null; KeyManager[] kms = null; PasswordCallback pcb = null; if(config.getCallbackHandler() == null) { ks = null; } else if (context == null) { //System.out.println("Keystore type: "+configuration.getKeystoreType()); if(config.getKeystoreType().equals("NONE")) { ks = null; pcb = null; } else if(config.getKeystoreType().equals("PKCS11")) { try { Constructor<?> c = Class.forName("sun.security.pkcs11.SunPKCS11").getConstructor(InputStream.class); String pkcs11Config = "name = SmartCard\nlibrary = "+config.getPKCS11Library(); ByteArrayInputStream config = new ByteArrayInputStream(pkcs11Config.getBytes()); Provider p = (Provider)c.newInstance(config); Security.addProvider(p); ks = KeyStore.getInstance("PKCS11",p); pcb = new PasswordCallback("PKCS11 Password: ",false); this.config.getCallbackHandler().handle(new Callback[]{pcb}); ks.load(null,pcb.getPassword()); } catch (Exception e) { ks = null; pcb = null; } } else if(config.getKeystoreType().equals("Apple")) { ks = KeyStore.getInstance("KeychainStore","Apple"); ks.load(null,null); //pcb = new PasswordCallback("Apple Keychain",false); //pcb.setPassword(null); } else { ks = KeyStore.getInstance(config.getKeystoreType()); try { pcb = new PasswordCallback("Keystore Password: ",false); config.getCallbackHandler().handle(new Callback[]{pcb}); ks.load(new FileInputStream(config.getKeystorePath()), pcb.getPassword()); } catch(Exception e) { ks = null; pcb = null; } } KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); try { if(pcb == null) { kmf.init(ks,null); } else { kmf.init(ks,pcb.getPassword()); pcb.clearPassword(); } kms = kmf.getKeyManagers(); } catch (NullPointerException npe) { kms = null; } } // Verify certificate presented by the server if (context == null) { context = SSLContext.getInstance("TLS"); context.init(kms, new javax.net.ssl.TrustManager[] { new ServerTrustManager(getServiceName(), config) }, new java.security.SecureRandom()); } Socket plain = socket; // Secure the plain connection socket = context.getSocketFactory().createSocket(plain, plain.getInetAddress().getHostAddress(), plain.getPort(), true); socket.setSoTimeout(0); socket.setKeepAlive(true); // Initialize the reader and writer with the new secured version initReaderAndWriter(); // Proceed to do the handshake ((SSLSocket) socket).startHandshake(); //if (((SSLSocket) socket).getWantClientAuth()) { // System.err.println("Connection wants client auth"); //} //else if (((SSLSocket) socket).getNeedClientAuth()) { // System.err.println("Connection needs client auth"); //} //else { // System.err.println("Connection does not require client auth"); // } // Set that TLS was successful usingTLS = true; // Set the new writer to use packetWriter.setWriter(writer); // Send a new opening stream to the server packetWriter.openStream(); } /** * Sets the available stream compression methods offered by the server. * * @param methods compression methods offered by the server. */ void setAvailableCompressionMethods(Collection<String> methods) { compressionMethods = methods; } /** * Returns the compression handler that can be used for one compression methods offered by the server. * * @return a instance of XMPPInputOutputStream or null if no suitable instance was found * */ private XMPPInputOutputStream maybeGetCompressionHandler() { if (compressionMethods != null) { for (XMPPInputOutputStream handler : compressionHandlers) { if (!handler.isSupported()) continue; String method = handler.getCompressionMethod(); if (compressionMethods.contains(method)) return handler; } } return null; } public boolean isUsingCompression() { return compressionHandler != null && serverAckdCompression; } /** * Starts using stream compression that will compress network traffic. Traffic can be * reduced up to 90%. Therefore, stream compression is ideal when using a slow speed network * connection. However, the server and the client will need to use more CPU time in order to * un/compress network data so under high load the server performance might be affected.<p> * <p/> * Stream compression has to have been previously offered by the server. Currently only the * zlib method is supported by the client. Stream compression negotiation has to be done * before authentication took place.<p> * <p/> * Note: to use stream compression the smackx.jar file has to be present in the classpath. * * @return true if stream compression negotiation was successful. */ private boolean useCompression() { // If stream compression was offered by the server and we want to use // compression then send compression request to the server if (authenticated) { throw new IllegalStateException("Compression should be negotiated before authentication."); } if ((compressionHandler = maybeGetCompressionHandler()) != null) { requestStreamCompression(compressionHandler.getCompressionMethod()); // Wait until compression is being used or a timeout happened synchronized (this) { try { this.wait(SmackConfiguration.getPacketReplyTimeout() * 5); } catch (InterruptedException e) { // Ignore. } } return isUsingCompression(); } return false; } /** * Request the server that we want to start using stream compression. When using TLS * then negotiation of stream compression can only happen after TLS was negotiated. If TLS * compression is being used the stream compression should not be used. */ private void requestStreamCompression(String method) { try { writer.write("<compress xmlns='http://jabber.org/protocol/compress'>"); writer.write("<method>" + method + "</method></compress>"); writer.flush(); } catch (IOException e) { notifyConnectionError(e); } } /** * Start using stream compression since the server has acknowledged stream compression. * * @throws Exception if there is an exception starting stream compression. */ void startStreamCompression() throws Exception { serverAckdCompression = true; // Initialize the reader and writer with the new secured version initReaderAndWriter(); // Set the new writer to use packetWriter.setWriter(writer); // Send a new opening stream to the server packetWriter.openStream(); // Notify that compression is being used synchronized (this) { this.notify(); } } /** * Notifies the XMPP connection that stream compression was denied so that * the connection process can proceed. */ void streamCompressionDenied() { synchronized (this) { this.notify(); } } /** * Establishes a connection to the XMPP server and performs an automatic login * only if the previous connection state was logged (authenticated). It basically * creates and maintains a socket connection to the server.<p> * <p/> * Listeners will be preserved from a previous connection if the reconnection * occurs after an abrupt termination. * * @throws XMPPException if an error occurs while trying to establish the connection. * Two possible errors can occur which will be wrapped by an XMPPException -- * UnknownHostException (XMPP error code 504), and IOException (XMPP error code * 502). The error codes and wrapped exceptions can be used to present more * appropiate error messages to end-users. */ public void connect() throws XMPPException { // Establishes the connection, readers and writers connectUsingConfiguration(config); // Automatically makes the login if the user was previouslly connected successfully // to the server and the connection was terminated abruptly if (connected && wasAuthenticated) { // Make the login try { if (isAnonymous()) { // Make the anonymous login loginAnonymously(); } else { login(config.getUsername(), config.getPassword(), config.getResource()); } notifyReconnection(); } catch (XMPPException e) { e.printStackTrace(); } } } /** * Sets whether the connection has already logged in the server. * * @param wasAuthenticated true if the connection has already been authenticated. */ private void setWasAuthenticated(boolean wasAuthenticated) { if (!this.wasAuthenticated) { this.wasAuthenticated = wasAuthenticated; } } /** * Sends out a notification that there was an error with the connection * and closes the connection. Also prints the stack trace of the given exception * * @param e the exception that causes the connection close event. */ synchronized void notifyConnectionError(Exception e) { // Listeners were already notified of the exception, return right here. if (packetReader.done && packetWriter.done) return; packetReader.done = true; packetWriter.done = true; // Closes the connection temporary. A reconnection is possible shutdown(new Presence(Presence.Type.unavailable)); // Print the stack trace to help catch the problem e.printStackTrace(); // Notify connection listeners of the error. for (ConnectionListener listener : getConnectionListeners()) { try { listener.connectionClosedOnError(e); } catch (Exception e2) { // Catch and print any exception so we can recover // from a faulty listener e2.printStackTrace(); } } } /** * Sends a notification indicating that the connection was reconnected successfully. */ protected void notifyReconnection() { // Notify connection listeners of the reconnection. for (ConnectionListener listener : getConnectionListeners()) { try { listener.reconnectionSuccessful(); } catch (Exception e) { // Catch and print any exception so we can recover // from a faulty listener e.printStackTrace(); } } } }
source/org/jivesoftware/smack/XMPPConnection.java
/** * $RCSfile$ * $Revision$ * $Date$ * * Copyright 2003-2007 Jive Software. * * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jivesoftware.smack; import org.jivesoftware.smack.compression.XMPPInputOutputStream; import org.jivesoftware.smack.filter.PacketFilter; import org.jivesoftware.smack.packet.Packet; import org.jivesoftware.smack.packet.Presence; import org.jivesoftware.smack.packet.XMPPError; import org.jivesoftware.smack.parsing.ParsingExceptionCallback; import org.jivesoftware.smack.util.StringUtils; import org.jivesoftware.smack.util.dns.HostAddress; import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocket; import javax.security.auth.callback.Callback; import javax.security.auth.callback.CallbackHandler; import javax.security.auth.callback.PasswordCallback; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.ByteArrayInputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.lang.reflect.Constructor; import java.net.Socket; import java.net.UnknownHostException; import java.security.KeyStore; import java.security.Provider; import java.security.Security; import java.util.Collection; import java.util.Iterator; import java.util.LinkedList; import java.util.List; /** * Creates a socket connection to a XMPP server. This is the default connection * to a Jabber server and is specified in the XMPP Core (RFC 3920). * * @see Connection * @author Matt Tucker */ public class XMPPConnection extends Connection { /** * The socket which is used for this connection. */ Socket socket; String connectionID = null; private String user = null; private boolean connected = false; // socketClosed is used concurrent // by XMPPConnection, PacketReader, PacketWriter private volatile boolean socketClosed = false; /** * Flag that indicates if the user is currently authenticated with the server. */ private boolean authenticated = false; /** * Flag that indicates if the user was authenticated with the server when the connection * to the server was closed (abruptly or not). */ private boolean wasAuthenticated = false; private boolean anonymous = false; private boolean usingTLS = false; private ParsingExceptionCallback parsingExceptionCallback = SmackConfiguration.getDefaultParsingExceptionCallback(); PacketWriter packetWriter; PacketReader packetReader; Roster roster = null; /** * Collection of available stream compression methods offered by the server. */ private Collection<String> compressionMethods; /** * Set to true by packet writer if the server acknowledged the compression */ private boolean serverAckdCompression = false; /** * Creates a new connection to the specified XMPP server. A DNS SRV lookup will be * performed to determine the IP address and port corresponding to the * service name; if that lookup fails, it's assumed that server resides at * <tt>serviceName</tt> with the default port of 5222. Encrypted connections (TLS) * will be used if available, stream compression is disabled, and standard SASL * mechanisms will be used for authentication.<p> * <p/> * This is the simplest constructor for connecting to an XMPP server. Alternatively, * you can get fine-grained control over connection settings using the * {@link #XMPPConnection(ConnectionConfiguration)} constructor.<p> * <p/> * Note that XMPPConnection constructors do not establish a connection to the server * and you must call {@link #connect()}.<p> * <p/> * The CallbackHandler will only be used if the connection requires the client provide * an SSL certificate to the server. The CallbackHandler must handle the PasswordCallback * to prompt for a password to unlock the keystore containing the SSL certificate. * * @param serviceName the name of the XMPP server to connect to; e.g. <tt>example.com</tt>. * @param callbackHandler the CallbackHandler used to prompt for the password to the keystore. */ public XMPPConnection(String serviceName, CallbackHandler callbackHandler) { // Create the configuration for this new connection super(new ConnectionConfiguration(serviceName)); config.setCompressionEnabled(false); config.setSASLAuthenticationEnabled(true); config.setDebuggerEnabled(DEBUG_ENABLED); config.setCallbackHandler(callbackHandler); } /** * Creates a new XMPP connection in the same way {@link #XMPPConnection(String,CallbackHandler)} does, but * with no callback handler for password prompting of the keystore. This will work * in most cases, provided the client is not required to provide a certificate to * the server. * * @param serviceName the name of the XMPP server to connect to; e.g. <tt>example.com</tt>. */ public XMPPConnection(String serviceName) { // Create the configuration for this new connection super(new ConnectionConfiguration(serviceName)); config.setCompressionEnabled(false); config.setSASLAuthenticationEnabled(true); config.setDebuggerEnabled(DEBUG_ENABLED); } /** * Creates a new XMPP connection in the same way {@link #XMPPConnection(ConnectionConfiguration,CallbackHandler)} does, but * with no callback handler for password prompting of the keystore. This will work * in most cases, provided the client is not required to provide a certificate to * the server. * * * @param config the connection configuration. */ public XMPPConnection(ConnectionConfiguration config) { super(config); } /** * Creates a new XMPP connection using the specified connection configuration.<p> * <p/> * Manually specifying connection configuration information is suitable for * advanced users of the API. In many cases, using the * {@link #XMPPConnection(String)} constructor is a better approach.<p> * <p/> * Note that XMPPConnection constructors do not establish a connection to the server * and you must call {@link #connect()}.<p> * <p/> * * The CallbackHandler will only be used if the connection requires the client provide * an SSL certificate to the server. The CallbackHandler must handle the PasswordCallback * to prompt for a password to unlock the keystore containing the SSL certificate. * * @param config the connection configuration. * @param callbackHandler the CallbackHandler used to prompt for the password to the keystore. */ public XMPPConnection(ConnectionConfiguration config, CallbackHandler callbackHandler) { super(config); config.setCallbackHandler(callbackHandler); } public String getConnectionID() { if (!isConnected()) { return null; } return connectionID; } public String getUser() { if (!isAuthenticated()) { return null; } return user; } /** * Install a parsing exception callback, which will be invoked once an exception is encountered while parsing a * stanza * * @param callback the callback to install */ public void setParsingExceptionCallback(ParsingExceptionCallback callback) { parsingExceptionCallback = callback; } /** * Get the current active parsing exception callback. * * @return the active exception callback or null if there is none */ public ParsingExceptionCallback getParsingExceptionCallback() { return parsingExceptionCallback; } @Override public synchronized void login(String username, String password, String resource) throws XMPPException { if (!isConnected()) { throw new IllegalStateException("Not connected to server."); } if (authenticated) { throw new IllegalStateException("Already logged in to server."); } // Do partial version of nameprep on the username. username = username.toLowerCase().trim(); String response; if (config.isSASLAuthenticationEnabled() && saslAuthentication.hasNonAnonymousAuthentication()) { // Authenticate using SASL if (password != null) { response = saslAuthentication.authenticate(username, password, resource); } else { response = saslAuthentication .authenticate(username, resource, config.getCallbackHandler()); } } else { // Authenticate using Non-SASL response = new NonSASLAuthentication(this).authenticate(username, password, resource); } // Set the user. if (response != null) { this.user = response; // Update the serviceName with the one returned by the server config.setServiceName(StringUtils.parseServer(response)); } else { this.user = username + "@" + getServiceName(); if (resource != null) { this.user += "/" + resource; } } // If compression is enabled then request the server to use stream compression if (config.isCompressionEnabled()) { useCompression(); } // Indicate that we're now authenticated. authenticated = true; anonymous = false; // Create the roster if it is not a reconnection or roster already created by getRoster() if (this.roster == null) { this.roster = new Roster(this); } if (config.isRosterLoadedAtLogin()) { this.roster.reload(); } // Set presence to online. if (config.isSendPresence()) { packetWriter.sendPacket(new Presence(Presence.Type.available)); } // Stores the authentication for future reconnection config.setLoginInfo(username, password, resource); // If debugging is enabled, change the the debug window title to include the // name we are now logged-in as. // If DEBUG_ENABLED was set to true AFTER the connection was created the debugger // will be null if (config.isDebuggerEnabled() && debugger != null) { debugger.userHasLogged(user); } } @Override public synchronized void loginAnonymously() throws XMPPException { if (!isConnected()) { throw new IllegalStateException("Not connected to server."); } if (authenticated) { throw new IllegalStateException("Already logged in to server."); } String response; if (config.isSASLAuthenticationEnabled() && saslAuthentication.hasAnonymousAuthentication()) { response = saslAuthentication.authenticateAnonymously(); } else { // Authenticate using Non-SASL response = new NonSASLAuthentication(this).authenticateAnonymously(); } // Set the user value. this.user = response; // Update the serviceName with the one returned by the server config.setServiceName(StringUtils.parseServer(response)); // If compression is enabled then request the server to use stream compression if (config.isCompressionEnabled()) { useCompression(); } // Set presence to online. packetWriter.sendPacket(new Presence(Presence.Type.available)); // Indicate that we're now authenticated. authenticated = true; anonymous = true; // If debugging is enabled, change the the debug window title to include the // name we are now logged-in as. // If DEBUG_ENABLED was set to true AFTER the connection was created the debugger // will be null if (config.isDebuggerEnabled() && debugger != null) { debugger.userHasLogged(user); } } public Roster getRoster() { // synchronize against login() synchronized(this) { // if connection is authenticated the roster is already set by login() // or a previous call to getRoster() if (!isAuthenticated() || isAnonymous()) { if (roster == null) { roster = new Roster(this); } return roster; } } if (!config.isRosterLoadedAtLogin()) { roster.reload(); } // If this is the first time the user has asked for the roster after calling // login, we want to wait for the server to send back the user's roster. This // behavior shields API users from having to worry about the fact that roster // operations are asynchronous, although they'll still have to listen for // changes to the roster. Note: because of this waiting logic, internal // Smack code should be wary about calling the getRoster method, and may need to // access the roster object directly. if (!roster.rosterInitialized) { try { synchronized (roster) { long waitTime = SmackConfiguration.getPacketReplyTimeout(); long start = System.currentTimeMillis(); while (!roster.rosterInitialized) { if (waitTime <= 0) { break; } roster.wait(waitTime); long now = System.currentTimeMillis(); waitTime -= now - start; start = now; } } } catch (InterruptedException ie) { // Ignore. } } return roster; } public boolean isConnected() { return connected; } public boolean isSecureConnection() { return isUsingTLS(); } public boolean isSocketClosed() { return socketClosed; } public boolean isAuthenticated() { return authenticated; } public boolean isAnonymous() { return anonymous; } /** * Closes the connection by setting presence to unavailable then closing the stream to * the XMPP server. The shutdown logic will be used during a planned disconnection or when * dealing with an unexpected disconnection. Unlike {@link #disconnect()} the connection's * packet reader, packet writer, and {@link Roster} will not be removed; thus * connection's state is kept. * * @param unavailablePresence the presence packet to send during shutdown. */ protected void shutdown(Presence unavailablePresence) { // Set presence to offline. if (packetWriter != null) { packetWriter.sendPacket(unavailablePresence); } this.setWasAuthenticated(authenticated); authenticated = false; if (packetReader != null) { packetReader.shutdown(); } if (packetWriter != null) { packetWriter.shutdown(); } // Wait 150 ms for processes to clean-up, then shutdown. try { Thread.sleep(150); } catch (Exception e) { // Ignore. } // Set socketClosed to true. This will cause the PacketReader // and PacketWriter to ingore any Exceptions that are thrown // because of a read/write from/to a closed stream. // It is *important* that this is done before socket.close()! socketClosed = true; try { socket.close(); } catch (Exception e) { e.printStackTrace(); } // In most cases the close() should be successful, so set // connected to false here. connected = false; // Close down the readers and writers. if (reader != null) { try { // Should already be closed by the previous // socket.close(). But just in case do it explicitly. reader.close(); } catch (Throwable ignore) { /* ignore */ } reader = null; } if (writer != null) { try { // Should already be closed by the previous // socket.close(). But just in case do it explicitly. writer.close(); } catch (Throwable ignore) { /* ignore */ } writer = null; } // Make sure that the socket is really closed try { // Does nothing if the socket is already closed socket.close(); } catch (Exception e) { // Ignore. } saslAuthentication.init(); } public synchronized void disconnect(Presence unavailablePresence) { // If not connected, ignore this request. if (packetReader == null || packetWriter == null) { return; } if (!isConnected()) { return; } shutdown(unavailablePresence); if (roster != null) { roster.cleanup(); roster = null; } wasAuthenticated = false; packetWriter.cleanup(); packetReader.cleanup(); } public void sendPacket(Packet packet) { if (!isConnected()) { throw new IllegalStateException("Not connected to server."); } if (packet == null) { throw new NullPointerException("Packet is null."); } packetWriter.sendPacket(packet); } /** * Registers a packet interceptor with this connection. The interceptor will be * invoked every time a packet is about to be sent by this connection. Interceptors * may modify the packet to be sent. A packet filter determines which packets * will be delivered to the interceptor. * * @param packetInterceptor the packet interceptor to notify of packets about to be sent. * @param packetFilter the packet filter to use. * @deprecated replaced by {@link Connection#addPacketInterceptor(PacketInterceptor, PacketFilter)}. */ public void addPacketWriterInterceptor(PacketInterceptor packetInterceptor, PacketFilter packetFilter) { addPacketInterceptor(packetInterceptor, packetFilter); } /** * Removes a packet interceptor. * * @param packetInterceptor the packet interceptor to remove. * @deprecated replaced by {@link Connection#removePacketInterceptor(PacketInterceptor)}. */ public void removePacketWriterInterceptor(PacketInterceptor packetInterceptor) { removePacketInterceptor(packetInterceptor); } /** * Registers a packet listener with this connection. The listener will be * notified of every packet that this connection sends. A packet filter determines * which packets will be delivered to the listener. Note that the thread * that writes packets will be used to invoke the listeners. Therefore, each * packet listener should complete all operations quickly or use a different * thread for processing. * * @param packetListener the packet listener to notify of sent packets. * @param packetFilter the packet filter to use. * @deprecated replaced by {@link #addPacketSendingListener(PacketListener, PacketFilter)}. */ public void addPacketWriterListener(PacketListener packetListener, PacketFilter packetFilter) { addPacketSendingListener(packetListener, packetFilter); } /** * Removes a packet listener for sending packets from this connection. * * @param packetListener the packet listener to remove. * @deprecated replaced by {@link #removePacketSendingListener(PacketListener)}. */ public void removePacketWriterListener(PacketListener packetListener) { removePacketSendingListener(packetListener); } private void connectUsingConfiguration(ConnectionConfiguration config) throws XMPPException { XMPPException exception = null; Iterator<HostAddress> it = config.getHostAddresses().iterator(); List<HostAddress> failedAddresses = new LinkedList<HostAddress>(); boolean xmppIOError = false; while (it.hasNext()) { exception = null; HostAddress hostAddress = it.next(); String host = hostAddress.getFQDN(); int port = hostAddress.getPort(); try { if (config.getSocketFactory() == null) { this.socket = new Socket(host, port); } else { this.socket = config.getSocketFactory().createSocket(host, port); } } catch (UnknownHostException uhe) { String errorMessage = "Could not connect to " + host + ":" + port + "."; exception = new XMPPException(errorMessage, new XMPPError(XMPPError.Condition.remote_server_timeout, errorMessage), uhe); } catch (IOException ioe) { String errorMessage = "XMPPError connecting to " + host + ":" + port + "."; exception = new XMPPException(errorMessage, new XMPPError(XMPPError.Condition.remote_server_error, errorMessage), ioe); xmppIOError = true; } if (exception == null) { // We found a host to connect to, break here config.setUsedHostAddress(hostAddress); break; } hostAddress.setException(exception); failedAddresses.add(hostAddress); if (!it.hasNext()) { // There are no more host addresses to try // throw an exception and report all tried // HostAddresses in the exception StringBuilder sb = new StringBuilder(); for (HostAddress fha : failedAddresses) { sb.append(fha.getErrorMessage()); sb.append("; "); } XMPPError xmppError; if (xmppIOError) { xmppError = new XMPPError(XMPPError.Condition.remote_server_error); } else { xmppError = new XMPPError(XMPPError.Condition.remote_server_timeout); } throw new XMPPException(sb.toString(), xmppError); } } socketClosed = false; initConnection(); } /** * Initializes the connection by creating a packet reader and writer and opening a * XMPP stream to the server. * * @throws XMPPException if establishing a connection to the server fails. */ private void initConnection() throws XMPPException { boolean isFirstInitialization = packetReader == null || packetWriter == null; compressionHandler = null; serverAckdCompression = false; // Set the reader and writer instance variables initReaderAndWriter(); try { if (isFirstInitialization) { packetWriter = new PacketWriter(this); packetReader = new PacketReader(this); // If debugging is enabled, we should start the thread that will listen for // all packets and then log them. if (config.isDebuggerEnabled()) { addPacketListener(debugger.getReaderListener(), null); if (debugger.getWriterListener() != null) { addPacketSendingListener(debugger.getWriterListener(), null); } } } else { packetWriter.init(); packetReader.init(); } // Start the packet writer. This will open a XMPP stream to the server packetWriter.startup(); // Start the packet reader. The startup() method will block until we // get an opening stream packet back from server. packetReader.startup(); // Make note of the fact that we're now connected. connected = true; if (isFirstInitialization) { // Notify listeners that a new connection has been established for (ConnectionCreationListener listener : getConnectionCreationListeners()) { listener.connectionCreated(this); } } else if (!wasAuthenticated) { notifyReconnection(); } } catch (XMPPException ex) { // An exception occurred in setting up the connection. Make sure we shut down the // readers and writers and close the socket. if (packetWriter != null) { try { packetWriter.shutdown(); } catch (Throwable ignore) { /* ignore */ } packetWriter = null; } if (packetReader != null) { try { packetReader.shutdown(); } catch (Throwable ignore) { /* ignore */ } packetReader = null; } if (reader != null) { try { reader.close(); } catch (Throwable ignore) { /* ignore */ } reader = null; } if (writer != null) { try { writer.close(); } catch (Throwable ignore) { /* ignore */} writer = null; } if (socket != null) { try { socket.close(); } catch (Exception e) { /* ignore */ } socket = null; } this.setWasAuthenticated(authenticated); authenticated = false; connected = false; throw ex; // Everything stoppped. Now throw the exception. } } private void initReaderAndWriter() throws XMPPException { try { if (compressionHandler == null) { reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8")); writer = new BufferedWriter( new OutputStreamWriter(socket.getOutputStream(), "UTF-8")); } else { try { OutputStream os = compressionHandler.getOutputStream(socket.getOutputStream()); writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); InputStream is = compressionHandler.getInputStream(socket.getInputStream()); reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); } catch (Exception e) { e.printStackTrace(); compressionHandler = null; reader = new BufferedReader( new InputStreamReader(socket.getInputStream(), "UTF-8")); writer = new BufferedWriter( new OutputStreamWriter(socket.getOutputStream(), "UTF-8")); } } } catch (IOException ioe) { throw new XMPPException( "XMPPError establishing connection with server.", new XMPPError(XMPPError.Condition.remote_server_error, "XMPPError establishing connection with server."), ioe); } // If debugging is enabled, we open a window and write out all network traffic. initDebugger(); } /*********************************************** * TLS code below **********************************************/ /** * Returns true if the connection to the server has successfully negotiated TLS. Once TLS * has been negotiatied the connection has been secured. * * @return true if the connection to the server has successfully negotiated TLS. */ public boolean isUsingTLS() { return usingTLS; } /** * Notification message saying that the server supports TLS so confirm the server that we * want to secure the connection. * * @param required true when the server indicates that TLS is required. */ void startTLSReceived(boolean required) { if (required && config.getSecurityMode() == ConnectionConfiguration.SecurityMode.disabled) { notifyConnectionError(new IllegalStateException( "TLS required by server but not allowed by connection configuration")); return; } if (config.getSecurityMode() == ConnectionConfiguration.SecurityMode.disabled) { // Do not secure the connection using TLS since TLS was disabled return; } try { writer.write("<starttls xmlns=\"urn:ietf:params:xml:ns:xmpp-tls\"/>"); writer.flush(); } catch (IOException e) { notifyConnectionError(e); } } /** * The server has indicated that TLS negotiation can start. We now need to secure the * existing plain connection and perform a handshake. This method won't return until the * connection has finished the handshake or an error occured while securing the connection. * * @throws Exception if an exception occurs. */ void proceedTLSReceived() throws Exception { SSLContext context = this.config.getCustomSSLContext(); KeyStore ks = null; KeyManager[] kms = null; PasswordCallback pcb = null; if(config.getCallbackHandler() == null) { ks = null; } else if (context == null) { //System.out.println("Keystore type: "+configuration.getKeystoreType()); if(config.getKeystoreType().equals("NONE")) { ks = null; pcb = null; } else if(config.getKeystoreType().equals("PKCS11")) { try { Constructor<?> c = Class.forName("sun.security.pkcs11.SunPKCS11").getConstructor(InputStream.class); String pkcs11Config = "name = SmartCard\nlibrary = "+config.getPKCS11Library(); ByteArrayInputStream config = new ByteArrayInputStream(pkcs11Config.getBytes()); Provider p = (Provider)c.newInstance(config); Security.addProvider(p); ks = KeyStore.getInstance("PKCS11",p); pcb = new PasswordCallback("PKCS11 Password: ",false); this.config.getCallbackHandler().handle(new Callback[]{pcb}); ks.load(null,pcb.getPassword()); } catch (Exception e) { ks = null; pcb = null; } } else if(config.getKeystoreType().equals("Apple")) { ks = KeyStore.getInstance("KeychainStore","Apple"); ks.load(null,null); //pcb = new PasswordCallback("Apple Keychain",false); //pcb.setPassword(null); } else { ks = KeyStore.getInstance(config.getKeystoreType()); try { pcb = new PasswordCallback("Keystore Password: ",false); config.getCallbackHandler().handle(new Callback[]{pcb}); ks.load(new FileInputStream(config.getKeystorePath()), pcb.getPassword()); } catch(Exception e) { ks = null; pcb = null; } } KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); try { if(pcb == null) { kmf.init(ks,null); } else { kmf.init(ks,pcb.getPassword()); pcb.clearPassword(); } kms = kmf.getKeyManagers(); } catch (NullPointerException npe) { kms = null; } } // Verify certificate presented by the server if (context == null) { context = SSLContext.getInstance("TLS"); context.init(kms, new javax.net.ssl.TrustManager[] { new ServerTrustManager(getServiceName(), config) }, new java.security.SecureRandom()); } Socket plain = socket; // Secure the plain connection socket = context.getSocketFactory().createSocket(plain, plain.getInetAddress().getHostAddress(), plain.getPort(), true); socket.setSoTimeout(0); socket.setKeepAlive(true); // Initialize the reader and writer with the new secured version initReaderAndWriter(); // Proceed to do the handshake ((SSLSocket) socket).startHandshake(); //if (((SSLSocket) socket).getWantClientAuth()) { // System.err.println("Connection wants client auth"); //} //else if (((SSLSocket) socket).getNeedClientAuth()) { // System.err.println("Connection needs client auth"); //} //else { // System.err.println("Connection does not require client auth"); // } // Set that TLS was successful usingTLS = true; // Set the new writer to use packetWriter.setWriter(writer); // Send a new opening stream to the server packetWriter.openStream(); } /** * Sets the available stream compression methods offered by the server. * * @param methods compression methods offered by the server. */ void setAvailableCompressionMethods(Collection<String> methods) { compressionMethods = methods; } /** * Returns the compression handler that can be used for one compression methods offered by the server. * * @return a instance of XMPPInputOutputStream or null if no suitable instance was found * */ private XMPPInputOutputStream maybeGetCompressionHandler() { if (compressionMethods != null) { for (XMPPInputOutputStream handler : compressionHandlers) { if (!handler.isSupported()) continue; String method = handler.getCompressionMethod(); if (compressionMethods.contains(method)) return handler; } } return null; } public boolean isUsingCompression() { return compressionHandler != null && serverAckdCompression; } /** * Starts using stream compression that will compress network traffic. Traffic can be * reduced up to 90%. Therefore, stream compression is ideal when using a slow speed network * connection. However, the server and the client will need to use more CPU time in order to * un/compress network data so under high load the server performance might be affected.<p> * <p/> * Stream compression has to have been previously offered by the server. Currently only the * zlib method is supported by the client. Stream compression negotiation has to be done * before authentication took place.<p> * <p/> * Note: to use stream compression the smackx.jar file has to be present in the classpath. * * @return true if stream compression negotiation was successful. */ private boolean useCompression() { // If stream compression was offered by the server and we want to use // compression then send compression request to the server if (authenticated) { throw new IllegalStateException("Compression should be negotiated before authentication."); } if ((compressionHandler = maybeGetCompressionHandler()) != null) { requestStreamCompression(compressionHandler.getCompressionMethod()); // Wait until compression is being used or a timeout happened synchronized (this) { try { this.wait(SmackConfiguration.getPacketReplyTimeout() * 5); } catch (InterruptedException e) { // Ignore. } } return isUsingCompression(); } return false; } /** * Request the server that we want to start using stream compression. When using TLS * then negotiation of stream compression can only happen after TLS was negotiated. If TLS * compression is being used the stream compression should not be used. */ private void requestStreamCompression(String method) { try { writer.write("<compress xmlns='http://jabber.org/protocol/compress'>"); writer.write("<method>" + method + "</method></compress>"); writer.flush(); } catch (IOException e) { notifyConnectionError(e); } } /** * Start using stream compression since the server has acknowledged stream compression. * * @throws Exception if there is an exception starting stream compression. */ void startStreamCompression() throws Exception { serverAckdCompression = true; // Initialize the reader and writer with the new secured version initReaderAndWriter(); // Set the new writer to use packetWriter.setWriter(writer); // Send a new opening stream to the server packetWriter.openStream(); // Notify that compression is being used synchronized (this) { this.notify(); } } /** * Notifies the XMPP connection that stream compression was denied so that * the connection process can proceed. */ void streamCompressionDenied() { synchronized (this) { this.notify(); } } /** * Establishes a connection to the XMPP server and performs an automatic login * only if the previous connection state was logged (authenticated). It basically * creates and maintains a socket connection to the server.<p> * <p/> * Listeners will be preserved from a previous connection if the reconnection * occurs after an abrupt termination. * * @throws XMPPException if an error occurs while trying to establish the connection. * Two possible errors can occur which will be wrapped by an XMPPException -- * UnknownHostException (XMPP error code 504), and IOException (XMPP error code * 502). The error codes and wrapped exceptions can be used to present more * appropiate error messages to end-users. */ public void connect() throws XMPPException { // Establishes the connection, readers and writers connectUsingConfiguration(config); // Automatically makes the login if the user was previouslly connected successfully // to the server and the connection was terminated abruptly if (connected && wasAuthenticated) { // Make the login try { if (isAnonymous()) { // Make the anonymous login loginAnonymously(); } else { login(config.getUsername(), config.getPassword(), config.getResource()); } notifyReconnection(); } catch (XMPPException e) { e.printStackTrace(); } } } /** * Sets whether the connection has already logged in the server. * * @param wasAuthenticated true if the connection has already been authenticated. */ private void setWasAuthenticated(boolean wasAuthenticated) { if (!this.wasAuthenticated) { this.wasAuthenticated = wasAuthenticated; } } /** * Sends out a notification that there was an error with the connection * and closes the connection. Also prints the stack trace of the given exception * * @param e the exception that causes the connection close event. */ synchronized void notifyConnectionError(Exception e) { // Listeners were already notified of the exception, return right here. if (packetReader.done && packetWriter.done) return; packetReader.done = true; packetWriter.done = true; // Closes the connection temporary. A reconnection is possible shutdown(new Presence(Presence.Type.unavailable)); // Print the stack trace to help catch the problem e.printStackTrace(); // Notify connection listeners of the error. for (ConnectionListener listener : getConnectionListeners()) { try { listener.connectionClosedOnError(e); } catch (Exception e2) { // Catch and print any exception so we can recover // from a faulty listener e2.printStackTrace(); } } } /** * Sends a notification indicating that the connection was reconnected successfully. */ protected void notifyReconnection() { // Notify connection listeners of the reconnection. for (ConnectionListener listener : getConnectionListeners()) { try { listener.reconnectionSuccessful(); } catch (Exception e) { // Catch and print any exception so we can recover // from a faulty listener e.printStackTrace(); } } } }
SMACK-405 Removed redundant code in XMPPConnection.shutdown() git-svn-id: 0d4d1bf2e47502aa0f0957c230a0ec7fa56198fd@13687 b35dd754-fafc-0310-a699-88a17e54d16e
source/org/jivesoftware/smack/XMPPConnection.java
SMACK-405 Removed redundant code in XMPPConnection.shutdown()
Java
apache-2.0
34f61800a807370383df1cafd0d442d69325c648
0
tsmgeek/traccar,jssenyange/traccar,jssenyange/traccar,jon-stumpf/traccar,tananaev/traccar,vipien/traccar,jon-stumpf/traccar,vipien/traccar,ninioe/traccar,stalien/traccar_test,tananaev/traccar,tsmgeek/traccar,renaudallard/traccar,AnshulJain1985/Roadcast-Tracker,ninioe/traccar,jon-stumpf/traccar,orcoliver/traccar,joseant/traccar-1,tananaev/traccar,tsmgeek/traccar,ninioe/traccar,orcoliver/traccar,stalien/traccar_test,duke2906/traccar,renaudallard/traccar,al3x1s/traccar,5of9/traccar,jssenyange/traccar,al3x1s/traccar,AnshulJain1985/Roadcast-Tracker,duke2906/traccar,5of9/traccar,joseant/traccar-1,orcoliver/traccar
/* * Copyright 2013 Anton Tananaev ([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.traccar.protocol; import java.nio.ByteOrder; import java.nio.charset.Charset; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.TimeZone; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelHandlerContext; import org.traccar.BaseProtocolDecoder; import org.traccar.ServerManager; import org.traccar.helper.Log; import org.traccar.model.Position; public class GalileoProtocolDecoder extends BaseProtocolDecoder { public GalileoProtocolDecoder(ServerManager serverManager) { super(serverManager); } private static final Map<Integer, Integer> tagLengthMap = new HashMap<Integer, Integer>(); static { int[] l1 = {0x01,0x02,0x35,0x43,0xc4,0xc5,0xc6,0xc7,0xc8,0xc9,0xca,0xcb,0xcc,0xcd,0xce,0xcf,0xd0,0xd1,0xd2,0xd5}; int[] l2 = {0x04,0x10,0x34,0x40,0x41,0x42,0x45,0x46,0x50,0x51,0x52,0x53,0x58,0x59,0x70,0x71,0x72,0x73,0x74,0x75,0x76,0x77,0xd6,0xd7,0xd8,0xd9,0xda}; int[] l4 = {0x20,0x33,0x44,0x90,0xc0,0xc1,0xc2,0xc3,0xd3,0xd4,0xdb,0xdc,0xdd,0xde,0xdf}; for (int i : l1) { tagLengthMap.put(i, 1); } for (int i : l2) { tagLengthMap.put(i, 2); } for (int i : l4) { tagLengthMap.put(i, 4); } } private static int getTagLength(int tag) { return tagLengthMap.get(tag); } private String readImei(ChannelBuffer buf) { int b = buf.readUnsignedByte(); StringBuilder imei = new StringBuilder(); imei.append(b & 0x0F); for (int i = 0; i < 7; i++) { b = buf.readUnsignedByte(); imei.append((b & 0xF0) >> 4); imei.append(b & 0x0F); } return imei.toString(); } private static final int TAG_IMEI = 0x03; private static final int TAG_DATE = 0x20; private static final int TAG_COORDINATES = 0x30; private static final int TAG_SPEED_COURSE = 0x33; private static final int TAG_ALTITUDE = 0x34; private static final int TAG_STATUS = 0x40; private static final int TAG_POWER = 0x41; private static final int TAG_BATTERY = 0x42; private static final int TAG_MILAGE = 0xd4; private void sendReply(Channel channel, int checksum) { ChannelBuffer reply = ChannelBuffers.directBuffer(ByteOrder.LITTLE_ENDIAN, 3); reply.writeByte(0x02); reply.writeShort((short) checksum); if (channel != null) { channel.write(reply); } } private Long deviceId; @Override protected Object decode( ChannelHandlerContext ctx, Channel channel, Object msg) throws Exception { ChannelBuffer buf = (ChannelBuffer) msg; buf.readUnsignedByte(); // header int length = (buf.readUnsignedShort() & 0x7fff) + 3; // Create new position Position position = new Position(); StringBuilder extendedInfo = new StringBuilder("<protocol>galileo</protocol>"); while (buf.readerIndex() < length) { int tag = buf.readUnsignedByte(); switch (tag) { case TAG_IMEI: String imei = buf.toString(buf.readerIndex(), 15, Charset.defaultCharset()); buf.skipBytes(imei.length()); try { deviceId = getDataManager().getDeviceByImei(imei).getId(); } catch(Exception error) { Log.warning("Unknown device - " + imei); } break; case TAG_DATE: position.setTime(new Date(buf.readUnsignedInt() * 1000)); break; case TAG_COORDINATES: position.setValid((buf.readUnsignedByte() & 0xf0) == 0x00); position.setLatitude(buf.readInt() / 1000000.0); position.setLongitude(buf.readInt() / 1000000.0); break; case TAG_SPEED_COURSE: position.setSpeed(buf.readUnsignedShort() * 0.0539957); position.setCourse(buf.readUnsignedShort() * 0.1); break; case TAG_ALTITUDE: position.setAltitude((double) buf.readShort()); break; case TAG_STATUS: extendedInfo.append("<status>"); extendedInfo.append(buf.readUnsignedShort()); extendedInfo.append("</status>"); break; case TAG_POWER: position.setPower((double) buf.readUnsignedShort()); break; case TAG_BATTERY: extendedInfo.append("<battery>"); extendedInfo.append(buf.readUnsignedShort()); extendedInfo.append("</battery>"); break; case TAG_MILAGE: extendedInfo.append("<milage>"); extendedInfo.append(buf.readUnsignedInt()); extendedInfo.append("</milage>"); break; default: buf.skipBytes(getTagLength(tag)); break; } } if (deviceId == null) { Log.warning("Unknown device"); return null; } position.setDeviceId(deviceId); sendReply(channel, buf.readUnsignedShort()); if (position.getValid() == null || position.getTime() == null || position.getSpeed() == null) { return null; } if (position.getAltitude() == null) { position.setAltitude(0.0); } position.setExtendedInfo(extendedInfo.toString()); return position; } }
src/org/traccar/protocol/GalileoProtocolDecoder.java
/* * Copyright 2013 Anton Tananaev ([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.traccar.protocol; import java.nio.ByteOrder; import java.nio.charset.Charset; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.TimeZone; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelHandlerContext; import org.traccar.BaseProtocolDecoder; import org.traccar.ServerManager; import org.traccar.helper.Log; import org.traccar.model.Position; public class GalileoProtocolDecoder extends BaseProtocolDecoder { public GalileoProtocolDecoder(ServerManager serverManager) { super(serverManager); } private static final Map<Integer, Integer> tagLengthMap = new HashMap<Integer, Integer>(); static { int[] l1 = {0x01,0x02,0x35,0x43,0xc4,0xc5,0xc6,0xc7,0xc8,0xc9,0xca,0xcb,0xcc,0xcd,0xce,0xcf,0xd0,0xd1,0xd2,0xd5}; int[] l2 = {0x04,0x10,0x34,0x40,0x41,0x42,0x45,0x46,0x50,0x51,0x52,0x53,0x58,0x59,0x70,0x71,0x72,0x73,0x74,0x75,0x76,0x77,0xd6,0xd7,0xd8,0xd9,0xda}; int[] l4 = {0x20,0x33,0x44,0x90,0xc0,0xc1,0xc2,0xc3,0xd3,0xd4,0xdb,0xdc,0xdd,0xde,0xdf}; for (int i : l1) { tagLengthMap.put(i, 1); } for (int i : l2) { tagLengthMap.put(i, 2); } for (int i : l4) { tagLengthMap.put(i, 4); } } private static int getTagLength(int tag) { return tagLengthMap.get(tag); } private String readImei(ChannelBuffer buf) { int b = buf.readUnsignedByte(); StringBuilder imei = new StringBuilder(); imei.append(b & 0x0F); for (int i = 0; i < 7; i++) { b = buf.readUnsignedByte(); imei.append((b & 0xF0) >> 4); imei.append(b & 0x0F); } return imei.toString(); } private static final int TAG_IMEI = 0x03; private static final int TAG_DATE = 0x20; private static final int TAG_COORDINATES = 0x30; private static final int TAG_SPEED_COURSE = 0x33; private static final int TAG_ALTITUDE = 0x34; private static final int TAG_STATUS = 0x40; private static final int TAG_POWER = 0x41; private static final int TAG_BATTERY = 0x42; private static final int TAG_MILAGE = 0xd4; private void sendReply(Channel channel, int checksum) { ChannelBuffer reply = ChannelBuffers.directBuffer(ByteOrder.LITTLE_ENDIAN, 3); reply.writeByte(0x02); reply.writeShort((short) checksum); if (channel != null) { channel.write(reply); } } @Override protected Object decode( ChannelHandlerContext ctx, Channel channel, Object msg) throws Exception { ChannelBuffer buf = (ChannelBuffer) msg; buf.readUnsignedByte(); // header int length = (buf.readUnsignedShort() & 0x7fff) + 3; // Create new position Position position = new Position(); StringBuilder extendedInfo = new StringBuilder("<protocol>galileo</protocol>"); while (buf.readerIndex() < length) { int tag = buf.readUnsignedByte(); switch (tag) { case TAG_IMEI: String imei = buf.toString(buf.readerIndex(), 15, Charset.defaultCharset()); buf.skipBytes(imei.length()); try { position.setDeviceId(getDataManager().getDeviceByImei(imei).getId()); } catch(Exception error) { Log.warning("Unknown device - " + imei); return null; } break; case TAG_DATE: position.setTime(new Date(buf.readUnsignedInt() * 1000)); break; case TAG_COORDINATES: position.setValid((buf.readUnsignedByte() & 0xf0) == 0x00); position.setLatitude(buf.readInt() / 1000000.0); position.setLongitude(buf.readInt() / 1000000.0); break; case TAG_SPEED_COURSE: position.setSpeed(buf.readUnsignedShort() * 0.0539957); position.setCourse(buf.readUnsignedShort() * 0.1); break; case TAG_ALTITUDE: position.setAltitude((double) buf.readShort()); break; case TAG_STATUS: extendedInfo.append("<status>"); extendedInfo.append(buf.readUnsignedShort()); extendedInfo.append("</status>"); break; case TAG_POWER: position.setPower((double) buf.readUnsignedShort()); break; case TAG_BATTERY: extendedInfo.append("<battery>"); extendedInfo.append(buf.readUnsignedShort()); extendedInfo.append("</battery>"); break; case TAG_MILAGE: extendedInfo.append("<milage>"); extendedInfo.append(buf.readUnsignedInt()); extendedInfo.append("</milage>"); break; default: buf.skipBytes(getTagLength(tag)); break; } } if (position.getDeviceId() == null || position.getValid() == null || position.getTime() == null || position.getSpeed() == null) { Log.warning("Identifier or location information missing"); return null; } if (position.getAltitude() == null) { position.setAltitude(0.0); } sendReply(channel, buf.readUnsignedShort()); position.setExtendedInfo(extendedInfo.toString()); return position; } }
Another Galileo protocol fix
src/org/traccar/protocol/GalileoProtocolDecoder.java
Another Galileo protocol fix
Java
apache-2.0
2f067d81190815679b5224c190bd9828fb0c853a
0
irfanah/jmeter,d0k1/jmeter,ThiagoGarciaAlves/jmeter,ubikloadpack/jmeter,kschroeder/jmeter,ra0077/jmeter,DoctorQ/jmeter,fj11/jmeter,etnetera/jmeter,ubikloadpack/jmeter,ubikloadpack/jmeter,ubikfsabbe/jmeter,hizhangqi/jmeter-1,kyroskoh/jmeter,ra0077/jmeter,max3163/jmeter,ra0077/jmeter,vherilier/jmeter,hizhangqi/jmeter-1,max3163/jmeter,hemikak/jmeter,max3163/jmeter,max3163/jmeter,thomsonreuters/jmeter,d0k1/jmeter,kschroeder/jmeter,etnetera/jmeter,vherilier/jmeter,liwangbest/jmeter,tuanhq/jmeter,DoctorQ/jmeter,liwangbest/jmeter,hemikak/jmeter,fj11/jmeter,ThiagoGarciaAlves/jmeter,kyroskoh/jmeter,irfanah/jmeter,ThiagoGarciaAlves/jmeter,irfanah/jmeter,etnetera/jmeter,ubikfsabbe/jmeter,kyroskoh/jmeter,liwangbest/jmeter,ra0077/jmeter,DoctorQ/jmeter,kschroeder/jmeter,ubikfsabbe/jmeter,hemikak/jmeter,ubikfsabbe/jmeter,hemikak/jmeter,tuanhq/jmeter,thomsonreuters/jmeter,hizhangqi/jmeter-1,fj11/jmeter,d0k1/jmeter,etnetera/jmeter,thomsonreuters/jmeter,d0k1/jmeter,tuanhq/jmeter,ubikloadpack/jmeter,etnetera/jmeter,vherilier/jmeter,vherilier/jmeter
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.jmeter.gui.util; import java.util.Properties; import org.apache.jmeter.util.JMeterUtils; import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea; import org.fife.ui.rsyntaxtextarea.SyntaxConstants; import org.fife.ui.rtextarea.RUndoManager; /** * Utility class to handle RSyntaxTextArea code */ public class JSyntaxTextArea extends RSyntaxTextArea { private static final long serialVersionUID = 210L; private final Properties languageProperties = JMeterUtils.loadProperties("org/apache/jmeter/gui/util/textarea.properties"); //$NON-NLS-1$; private final boolean disableUndo; private static final boolean WRAP_STYLE_WORD = JMeterUtils.getPropDefault("jsyntaxtextarea.wrapstyleword", true); private static final boolean LINE_WRAP = JMeterUtils.getPropDefault("jsyntaxtextarea.linewrap", true); private static final boolean CODE_FOLDING = JMeterUtils.getPropDefault("jsyntaxtextarea.codefolding", true); private static final int MAX_UNDOS = JMeterUtils.getPropDefault("jsyntaxtextarea.maxundos", 50); @Deprecated public JSyntaxTextArea() { // For use by test code only this(30, 50, false); } /** * Creates the default syntax highlighting text area. * The following are set: * <ul> * <li>setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_JAVA)</li> * <li>setCodeFoldingEnabled(true)</li> * <li>setAntiAliasingEnabled(true)</li> * <li>setLineWrap(true)</li> * <li>setWrapStyleWord(true)</li> * </ul> * @param rows * @param cols */ public JSyntaxTextArea(int rows, int cols) { this(rows, cols, false); } /** * Creates the default syntax highlighting text area. * The following are set: * <ul> * <li>setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_JAVA)</li> * <li>setCodeFoldingEnabled(true)</li> * <li>setAntiAliasingEnabled(true)</li> * <li>setLineWrap(true)</li> * <li>setWrapStyleWord(true)</li> * </ul> * @param rows * @param cols * @param disableUndo true to disable undo manager, defaults to false */ public JSyntaxTextArea(int rows, int cols, boolean disableUndo) { super(rows, cols); super.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_JAVA); super.setCodeFoldingEnabled(CODE_FOLDING); super.setAntiAliasingEnabled(true); super.setLineWrap(LINE_WRAP); super.setWrapStyleWord(WRAP_STYLE_WORD); this.disableUndo = disableUndo; } /** * Sets the language of the text area. * @param language */ public void setLanguage(String language) { final String style = languageProperties.getProperty(language); if (style == null) { super.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_NONE); } else { super.setSyntaxEditingStyle(style); } } /** * Override UndoManager to allow disabling if feature causes issues * See https://github.com/bobbylight/RSyntaxTextArea/issues/19 */ @Override protected RUndoManager createUndoManager() { RUndoManager undoManager = super.createUndoManager(); if(disableUndo) { undoManager.setLimit(0); } else { undoManager.setLimit(MAX_UNDOS); } return undoManager; } /** * Sets initial text resetting undo history * @param string */ public void setInitialText(String string) { setText(string); discardAllEdits(); } }
src/core/org/apache/jmeter/gui/util/JSyntaxTextArea.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.jmeter.gui.util; import java.util.Properties; import org.apache.jmeter.util.JMeterUtils; import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea; import org.fife.ui.rsyntaxtextarea.SyntaxConstants; import org.fife.ui.rtextarea.RUndoManager; /** * Utility class to handle RSyntaxTextArea code */ public class JSyntaxTextArea extends RSyntaxTextArea { private static final long serialVersionUID = 210L; private final Properties languageProperties = JMeterUtils.loadProperties("org/apache/jmeter/gui/util/textarea.properties"); //$NON-NLS-1$; private static final boolean WRAP_STYLE_WORD = JMeterUtils.getPropDefault("jsyntaxtextarea.wrapstyleword", true); private static final boolean LINE_WRAP = JMeterUtils.getPropDefault("jsyntaxtextarea.linewrap", true); private static final boolean CODE_FOLDING = JMeterUtils.getPropDefault("jsyntaxtextarea.codefolding", true); private static final int MAX_UNDOS = JMeterUtils.getPropDefault("jsyntaxtextarea.maxundos", 50); @Deprecated public JSyntaxTextArea() { // For use by test code only } /** * Creates the default syntax highlighting text area. * The following are set: * <ul> * <li>setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_JAVA)</li> * <li>setCodeFoldingEnabled(true)</li> * <li>setAntiAliasingEnabled(true)</li> * <li>setLineWrap(true)</li> * <li>setWrapStyleWord(true)</li> * </ul> * @param rows * @param cols */ public JSyntaxTextArea(int rows, int cols) { super(rows, cols); super.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_JAVA); super.setCodeFoldingEnabled(CODE_FOLDING); super.setAntiAliasingEnabled(true); super.setLineWrap(LINE_WRAP); super.setWrapStyleWord(WRAP_STYLE_WORD); } /** * Sets the language of the text area. * @param language */ public void setLanguage(String language) { final String style = languageProperties.getProperty(language); if (style == null) { super.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_NONE); } else { super.setSyntaxEditingStyle(style); } } /** * Override UndoManager to allow disabling if feature causes issues * See https://github.com/bobbylight/RSyntaxTextArea/issues/19 */ @Override protected RUndoManager createUndoManager() { RUndoManager undoManager = super.createUndoManager(); undoManager.setLimit(MAX_UNDOS); return undoManager; } /** * Sets initial text resetting undo history * @param string */ public void setInitialText(String string) { setText(string); discardAllEdits(); } }
Add constructor parameter to disable undo git-svn-id: 5ccfe34f605a6c2f9041ff2965ab60012c62539a@1531699 13f79535-47bb-0310-9956-ffa450edef68
src/core/org/apache/jmeter/gui/util/JSyntaxTextArea.java
Add constructor parameter to disable undo
Java
apache-2.0
b49e459fb62c75231ade9b2a280dcc9ca5fd83f8
0
hgl888/Pedometer,MilanNz/Pedometer,niyueming/Pedometer,dhootha/Pedometer,j4velin/Pedometer,hibernate2011/Pedometer,luinvacc/pedometer,ayyb1988/Pedometer
/* * Copyright 2013 Thomas Hoffmann * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.j4velin.pedometer.background; import java.util.Calendar; import de.j4velin.pedometer.Database; import de.j4velin.pedometer.Logger; import de.j4velin.pedometer.Util; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; public class NewDayReceiver extends BroadcastReceiver { @Override public void onReceive(final Context context, final Intent intent) { // Save the steps made yesterday and create a new // row for today if (Logger.LOG) { Logger.log("date changed, today is: " + Util.getToday()); Logger.log("Steps: " + SensorListener.steps); } Database db = new Database(context); db.open(); // only update if there is no entry for the new day yet // (might happen if the receiver is called twice) if (db.getSteps(Util.getToday()) == Integer.MIN_VALUE) { final Calendar yesterday = Calendar.getInstance(); yesterday.setTimeInMillis(Util.getToday()); // today yesterday.add(Calendar.DAY_OF_YEAR, -1); // yesterday db.updateSteps(yesterday.getTimeInMillis(), SensorListener.steps); // if - for whatever reason - there still is a // negative value in // yesterdays steps, set it to 0 instead int steps_yesterday = db.getSteps(yesterday.getTimeInMillis()); if (steps_yesterday < 0 && steps_yesterday > Integer.MIN_VALUE) { db.updateSteps(yesterday.getTimeInMillis(), -steps_yesterday); } // start the new days step with the offset of the // current step-value // example: current steps since boot = 5.000 // --> offset for the following day = -5.000 // --> step-value of 5.001 then means there was 1 // step taken today db.insertDay(Util.getToday(), -SensorListener.steps); if (Logger.LOG) { Logger.log("offset for new day: " + (-SensorListener.steps)); db.logState(); } } db.close(); // to update the notification context.startService(new Intent(context, SensorListener.class).putExtra("updateNotificationState", true)); sheduleAlarmForNextDay(context); } /** * Shedules an alarm for tomorrow at midnight, to fire the NewDayReceiver * broadcast again * * @param context * the Context */ @SuppressWarnings("deprecation") public static void sheduleAlarmForNextDay(final Context context) { final Calendar tomorrow = Calendar.getInstance(); tomorrow.setTimeInMillis(Util.getToday()); // today tomorrow.add(Calendar.DAY_OF_YEAR, 1); // tomorrow tomorrow.add(Calendar.SECOND, 1); // tomorrow at 0:00:01 ((AlarmManager) context.getApplicationContext().getSystemService(Context.ALARM_SERVICE)) .setExact(AlarmManager.RTC_WAKEUP, tomorrow.getTimeInMillis(), PendingIntent.getBroadcast( context.getApplicationContext(), 10, new Intent(context.getApplicationContext(), NewDayReceiver.class), PendingIntent.FLAG_UPDATE_CURRENT)); if (Logger.LOG) Logger.log("newDayAlarm sheduled for " + tomorrow.getTime().toLocaleString()); } }
src/de/j4velin/pedometer/background/NewDayReceiver.java
/* * Copyright 2013 Thomas Hoffmann * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.j4velin.pedometer.background; import java.util.Calendar; import de.j4velin.pedometer.Database; import de.j4velin.pedometer.Logger; import de.j4velin.pedometer.Util; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; public class NewDayReceiver extends BroadcastReceiver { @Override public void onReceive(final Context context, final Intent intent) { // Save the steps made yesterday and create a new // row for today if (Logger.LOG) { Logger.log("date changed, today is: " + Util.getToday()); Logger.log("Steps: " + SensorListener.steps); } Database db = new Database(context); db.open(); // only update if there is no entry for the new day yet // (might happen if the receiver is called twice) if (db.getSteps(Util.getToday()) == Integer.MIN_VALUE) { final Calendar yesterday = Calendar.getInstance(); yesterday.setTimeInMillis(Util.getToday()); // today yesterday.add(Calendar.DAY_OF_YEAR, -1); // yesterday db.updateSteps(yesterday.getTimeInMillis(), SensorListener.steps); // if - for whatever reason - there still is a // negative value in // yesterdays steps, set it to 0 instead if (db.getSteps(yesterday.getTimeInMillis()) < 0) { db.updateSteps(yesterday.getTimeInMillis(), -db.getSteps(yesterday.getTimeInMillis())); } // start the new days step with the offset of the // current step-value // example: current steps since boot = 5.000 // --> offset for the following day = -5.000 // --> step-value of 5.001 then means there was 1 // step taken today db.insertDay(Util.getToday(), -SensorListener.steps); if (Logger.LOG) { Logger.log("offset for new day: " + (-SensorListener.steps)); db.logState(); } } db.close(); // to update the notification context.startService(new Intent(context, SensorListener.class).putExtra("updateNotificationState", true)); sheduleAlarmForNextDay(context); } /** * Shedules an alarm for tomorrow at midnight, to fire the NewDayReceiver * broadcast again * * @param context * the Context */ @SuppressWarnings("deprecation") public static void sheduleAlarmForNextDay(final Context context) { final Calendar tomorrow = Calendar.getInstance(); tomorrow.setTimeInMillis(Util.getToday()); // today tomorrow.add(Calendar.DAY_OF_YEAR, 1); // tomorrow tomorrow.add(Calendar.SECOND, 1); // tomorrow at 0:00:01 ((AlarmManager) context.getApplicationContext().getSystemService(Context.ALARM_SERVICE)).setExact( AlarmManager.RTC_WAKEUP, tomorrow.getTimeInMillis(), PendingIntent.getBroadcast(context.getApplicationContext(), 10, new Intent(context, NewDayReceiver.class), PendingIntent.FLAG_UPDATE_CURRENT)); if (Logger.LOG) Logger.log("newDayAlarm sheduled for " + tomorrow.getTime().toLocaleString()); } }
ApplicationContext for broadcast & prevent for inserting -Interger.MIN_VALUE for yesterday
src/de/j4velin/pedometer/background/NewDayReceiver.java
ApplicationContext for broadcast & prevent for inserting -Interger.MIN_VALUE for yesterday
Java
apache-2.0
3514b398295eb9af5e449b472a88171cb62949f4
0
anton-johansson/svn-commit,anton-johansson/svn-commit
package com.antonjohansson.svncommit.svn; import static java.util.stream.Collectors.toList; import static org.apache.commons.io.IOUtils.readLines; import java.io.File; import java.util.Collection; import com.antonjohansson.svncommit.domain.SvnItem; import com.antonjohansson.svncommit.utils.Bash; /** * Provides utility methods for working with SVN. * * @author Anton Johansson */ public final class SVN { private static final String COMPARE_COMMAND_PATTERN = "meld '%F'"; private SVN() {} /** * Gets a collection of all modified files. * * @param directory The directory to get modified files from. * @return Returns the collection of modified files. */ public static Collection<SvnItem> getModifiedItems(File directory) { return Bash.execute(s -> readLines(s), directory, "svn status") .stream() .map(Converter::convertFile) .collect(toList()); } /** * Brings up the Meld compare tool for the given file. * * @param directory The directory which the file to compare is contained in. * @param fileName The file to compare. */ public static void compare(File directory, String fileName) { String command = COMPARE_COMMAND_PATTERN.replace("%F", fileName); Bash.execute(directory, command); } }
src/main/java/com/antonjohansson/svncommit/svn/SVN.java
package com.antonjohansson.svncommit.svn; import static java.util.stream.Collectors.toList; import static org.apache.commons.io.IOUtils.readLines; import java.io.File; import java.util.Collection; import com.antonjohansson.svncommit.domain.SvnItem; import com.antonjohansson.svncommit.utils.Bash; /** * Provides utility methods for working with SVN. * * @author Anton Johansson */ public final class SVN { private SVN() {} /** * Gets a collection of all modified files. * * @param directory The directory to get modified files from. * @return Returns the collection of modified files. */ public static Collection<SvnItem> getModifiedItems(File directory) { Collection<String> statusLines = Bash.execute(s -> readLines(s), directory, "svn status"); return statusLines.stream() .map(Converter::convertFile) .collect(toList()); } /** * Brings up the Meld compare tool for the given file. * * @param directory The directory which the file to compare is contained in. * @param fileName The file to compare. */ public static void compare(File directory, String fileName) { String command = "meld ".concat(fileName); Bash.execute(directory, command); } }
Surround compare command with 's
src/main/java/com/antonjohansson/svncommit/svn/SVN.java
Surround compare command with 's
Java
apache-2.0
308dd6ecd4c9afe14acb362dd7ac4fb595a00837
0
WilliamKoza/JsonPath,jochenberger/JsonPath,lafaspot/JsonPath,WilliamKoza/JsonPath,hunterpayne/JsonPath,jochenberger/JsonPath,json-path/JsonPath,mgreenwood1001/JsonPath,NetNow/JsonPath,NetNow/JsonPath,json-path/JsonPath,jochenberger/JsonPath,jayway/JsonPath,hunterpayne/JsonPath,zline/JsonPath,json-path/JsonPath,trajano/JsonPath,escardin/JsonPath,escardin/JsonPath,lafaspot/JsonPath,trajano/JsonPath,292388900/JsonPath,lafaspot/JsonPath,292388900/JsonPath,WilliamKoza/JsonPath,292388900/JsonPath,jayway/JsonPath,NetNow/JsonPath,mgreenwood1001/JsonPath,mgreenwood1001/JsonPath,trajano/JsonPath,jayway/JsonPath,escardin/JsonPath,hunterpayne/JsonPath,zline/JsonPath,zline/JsonPath,rodoufu/JsonPath,rodoufu/JsonPath,rodoufu/JsonPath
package com.jayway.jsonpath.internal; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.ObjectStreamClass; import java.io.OutputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public final class Utils { public static final String CR = System.getProperty("line.separator"); /** * Creates a range of integers from start (inclusive) to end (exclusive) * * @param start * @param end * @return */ public static List<Integer> createRange(int start, int end) { List<Integer> range = new ArrayList<Integer>(); for (int i = start; i < end; i++) { range.add(i); } return range; } // accept a collection of objects, since all objects have toString() public static String join(String delimiter, String wrap, Iterable<? extends Object> objs) { Iterator<? extends Object> iter = objs.iterator(); if (!iter.hasNext()) { return ""; } StringBuilder buffer = new StringBuilder(); buffer.append(wrap).append(iter.next()).append(wrap); while (iter.hasNext()) { buffer.append(delimiter).append(wrap).append(iter.next()).append(wrap); } return buffer.toString(); } // accept a collection of objects, since all objects have toString() public static String join(String delimiter, Iterable<? extends Object> objs) { return join(delimiter, "", objs); } //--------------------------------------------------------- // // IO // //--------------------------------------------------------- public static void closeQuietly(Closeable closeable) { try { if (closeable != null) { closeable.close(); } } catch (IOException ignore) { } } //--------------------------------------------------------- // // Strings // //--------------------------------------------------------- public static boolean isInt(String str) { if (str == null) { return false; } int sz = str.length(); for (int i = 0; i < sz; i++) { if (Character.isDigit(str.charAt(i)) == false) { return false; } } return true; } public static boolean isNumeric(String str) { if (str == null) { return false; } int sz = str.length(); for (int i = 0; i < sz; i++) { if (Character.isDigit(str.charAt(i)) == false && !(str.charAt(i) == '.')) { return false; } } return true; } /** * <p>Checks if a CharSequence is empty ("") or null.</p> * <p/> * <pre> * StringUtils.isEmpty(null) = true * StringUtils.isEmpty("") = true * StringUtils.isEmpty(" ") = false * StringUtils.isEmpty("bob") = false * StringUtils.isEmpty(" bob ") = false * </pre> * <p/> * <p>NOTE: This method changed in Lang version 2.0. * It no longer trims the CharSequence. * That functionality is available in isBlank().</p> * * @param cs the CharSequence to check, may be null * @return {@code true} if the CharSequence is empty or null * @since 3.0 Changed signature from isEmpty(String) to isEmpty(CharSequence) */ public static boolean isEmpty(CharSequence cs) { return cs == null || cs.length() == 0; } /** * Used by the indexOf(CharSequence methods) as a green implementation of indexOf. * * @param cs the {@code CharSequence} to be processed * @param searchChar the {@code CharSequence} to be searched for * @param start the start index * @return the index where the search sequence was found */ static int indexOf(CharSequence cs, CharSequence searchChar, int start) { return cs.toString().indexOf(searchChar.toString(), start); } /** * <p>Counts how many times the substring appears in the larger string.</p> * <p/> * <p>A {@code null} or empty ("") String input returns {@code 0}.</p> * <p/> * <pre> * StringUtils.countMatches(null, *) = 0 * StringUtils.countMatches("", *) = 0 * StringUtils.countMatches("abba", null) = 0 * StringUtils.countMatches("abba", "") = 0 * StringUtils.countMatches("abba", "a") = 2 * StringUtils.countMatches("abba", "ab") = 1 * StringUtils.countMatches("abba", "xxx") = 0 * </pre> * * @param str the CharSequence to check, may be null * @param sub the substring to count, may be null * @return the number of occurrences, 0 if either CharSequence is {@code null} * @since 3.0 Changed signature from countMatches(String, String) to countMatches(CharSequence, CharSequence) */ public static int countMatches(CharSequence str, CharSequence sub) { if (isEmpty(str) || isEmpty(sub)) { return 0; } int count = 0; int idx = 0; while ((idx = indexOf(str, sub, idx)) != -1) { count++; idx += sub.length(); } return count; } //--------------------------------------------------------- // // Validators // //--------------------------------------------------------- /** * <p>Validate that the specified argument is not {@code null}; * otherwise throwing an exception with the specified message. * <p/> * <pre>Validate.notNull(myObject, "The object must not be null");</pre> * * @param <T> the object type * @param object the object to check * @param message the {@link String#format(String, Object...)} exception message if invalid, not null * @param values the optional values for the formatted exception message * @return the validated object (never {@code null} for method chaining) * @throws NullPointerException if the object is {@code null} */ public static <T> T notNull(T object, String message, Object... values) { if (object == null) { throw new IllegalArgumentException(String.format(message, values)); } return object; } /** * <p>Validate that the argument condition is {@code true}; otherwise * throwing an exception with the specified message. This method is useful when * validating according to an arbitrary boolean expression, such as validating a * primitive number or using your own custom validation expression.</p> * <p/> * <pre>Validate.isTrue(i > 0.0, "The value must be greater than zero: %d", i);</pre> * <p/> * <p>For performance reasons, the long value is passed as a separate parameter and * appended to the exception message only in the case of an error.</p> * * @param expression the boolean expression to check * @param message * @throws IllegalArgumentException if expression is {@code false} */ public static void isTrue(boolean expression, String message) { if (expression == false) { throw new IllegalArgumentException(message); } } /** * <p>Validate that the specified argument character sequence is * neither {@code null} nor a length of zero (no characters); * otherwise throwing an exception with the specified message. * <p/> * <pre>Validate.notEmpty(myString, "The string must not be empty");</pre> * * @param <T> the character sequence type * @param chars the character sequence to check, validated not null by this method * @param message the {@link String#format(String, Object...)} exception message if invalid, not null * @param values the optional values for the formatted exception message, null array not recommended * @return the validated character sequence (never {@code null} method for chaining) * @throws NullPointerException if the character sequence is {@code null} * @throws IllegalArgumentException if the character sequence is empty */ public static <T extends CharSequence> T notEmpty(T chars, String message, Object... values) { if (chars == null) { throw new IllegalArgumentException(String.format(message, values)); } if (chars.length() == 0) { throw new IllegalArgumentException(String.format(message, values)); } return chars; } //--------------------------------------------------------- // // Converters // //--------------------------------------------------------- public static String toString(Object o) { if (null == o) { return null; } return o.toString(); } //--------------------------------------------------------- // // Serialization // //--------------------------------------------------------- /** * <p>Deep clone an {@code Object} using serialization.</p> * <p/> * <p>This is many times slower than writing clone methods by hand * on all objects in your object graph. However, for complex object * graphs, or for those that don't support deep cloning this can * be a simple alternative implementation. Of course all the objects * must be {@code Serializable}.</p> * * @param <T> the type of the object involved * @param object the {@code Serializable} object to clone * @return the cloned object */ public static <T extends Serializable> T clone(T object) { if (object == null) { return null; } byte[] objectData = serialize(object); ByteArrayInputStream bais = new ByteArrayInputStream(objectData); ClassLoaderAwareObjectInputStream in = null; try { // stream closed in the finally in = new ClassLoaderAwareObjectInputStream(bais, object.getClass().getClassLoader()); /* * when we serialize and deserialize an object, * it is reasonable to assume the deserialized object * is of the same type as the original serialized object */ @SuppressWarnings("unchecked") // see above T readObject = (T) in.readObject(); return readObject; } catch (ClassNotFoundException ex) { throw new RuntimeException("ClassNotFoundException while reading cloned object data", ex); } catch (IOException ex) { throw new RuntimeException("IOException while reading cloned object data", ex); } finally { try { if (in != null) { in.close(); } } catch (IOException ex) { throw new RuntimeException("IOException on closing cloned object data InputStream.", ex); } } } /** * <p>Serializes an {@code Object} to the specified stream.</p> * <p/> * <p>The stream will be closed once the object is written. * This avoids the need for a finally clause, and maybe also exception * handling, in the application code.</p> * <p/> * <p>The stream passed in is not buffered internally within this method. * This is the responsibility of your application if desired.</p> * * @param obj the object to serialize to bytes, may be null * @param outputStream the stream to write to, must not be null * @throws IllegalArgumentException if {@code outputStream} is {@code null} * @throws RuntimeException (runtime) if the serialization fails */ public static void serialize(Serializable obj, OutputStream outputStream) { if (outputStream == null) { throw new IllegalArgumentException("The OutputStream must not be null"); } ObjectOutputStream out = null; try { // stream closed in the finally out = new ObjectOutputStream(outputStream); out.writeObject(obj); } catch (IOException ex) { throw new RuntimeException(ex); } finally { try { if (out != null) { out.close(); } } catch (IOException ex) { // NOPMD // ignore close exception } } } /** * <p>Serializes an {@code Object} to a byte array for * storage/serialization.</p> * * @param obj the object to serialize to bytes * @return a byte[] with the converted Serializable * @throws RuntimeException (runtime) if the serialization fails */ public static byte[] serialize(Serializable obj) { ByteArrayOutputStream baos = new ByteArrayOutputStream(512); serialize(obj, baos); return baos.toByteArray(); } // Deserialize //----------------------------------------------------------------------- /** * <p>Deserializes an {@code Object} from the specified stream.</p> * <p/> * <p>The stream will be closed once the object is written. This * avoids the need for a finally clause, and maybe also exception * handling, in the application code.</p> * <p/> * <p>The stream passed in is not buffered internally within this method. * This is the responsibility of your application if desired.</p> * * @param inputStream the serialized object input stream, must not be null * @return the deserialized object * @throws IllegalArgumentException if {@code inputStream} is {@code null} * @throws RuntimeException (runtime) if the serialization fails */ public static Object deserialize(InputStream inputStream) { if (inputStream == null) { throw new IllegalArgumentException("The InputStream must not be null"); } ObjectInputStream in = null; try { // stream closed in the finally in = new ObjectInputStream(inputStream); return in.readObject(); } catch (ClassNotFoundException ex) { throw new RuntimeException(ex); } catch (IOException ex) { throw new RuntimeException(ex); } finally { try { if (in != null) { in.close(); } } catch (IOException ex) { // NOPMD // ignore close exception } } } /** * <p>Deserializes a single {@code Object} from an array of bytes.</p> * * @param objectData the serialized object, must not be null * @return the deserialized object * @throws IllegalArgumentException if {@code objectData} is {@code null} * @throws RuntimeException (runtime) if the serialization fails */ public static Object deserialize(byte[] objectData) { if (objectData == null) { throw new IllegalArgumentException("The byte[] must not be null"); } ByteArrayInputStream bais = new ByteArrayInputStream(objectData); return deserialize(bais); } /** * <p>Custom specialization of the standard JDK {@link java.io.ObjectInputStream} * that uses a custom <code>ClassLoader</code> to resolve a class. * If the specified <code>ClassLoader</code> is not able to resolve the class, * the context classloader of the current thread will be used. * This way, the standard deserialization work also in web-application * containers and application servers, no matter in which of the * <code>ClassLoader</code> the particular class that encapsulates * serialization/deserialization lives. </p> * <p/> * <p>For more in-depth information about the problem for which this * class here is a workaround, see the JIRA issue LANG-626. </p> */ static class ClassLoaderAwareObjectInputStream extends ObjectInputStream { private ClassLoader classLoader; /** * Constructor. * * @param in The <code>InputStream</code>. * @param classLoader classloader to use * @throws IOException if an I/O error occurs while reading stream header. * @see java.io.ObjectInputStream */ public ClassLoaderAwareObjectInputStream(InputStream in, ClassLoader classLoader) throws IOException { super(in); this.classLoader = classLoader; } /** * Overriden version that uses the parametrized <code>ClassLoader</code> or the <code>ClassLoader</code> * of the current <code>Thread</code> to resolve the class. * * @param desc An instance of class <code>ObjectStreamClass</code>. * @return A <code>Class</code> object corresponding to <code>desc</code>. * @throws IOException Any of the usual Input/Output exceptions. * @throws ClassNotFoundException If class of a serialized object cannot be found. */ @Override protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException { String name = desc.getName(); try { return Class.forName(name, false, classLoader); } catch (ClassNotFoundException ex) { return Class.forName(name, false, Thread.currentThread().getContextClassLoader()); } } } private Utils () {} }
json-path/src/main/java/com/jayway/jsonpath/internal/Utils.java
package com.jayway.jsonpath.internal; import com.jayway.jsonpath.InvalidConversionException; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.ObjectStreamClass; import java.io.OutputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class Utils { public static final String CR = System.getProperty("line.separator"); /** * Creates a range of integers from start (inclusive) to end (exclusive) * * @param start * @param end * @return */ public static List<Integer> createRange(int start, int end) { List<Integer> range = new ArrayList<Integer>(); for (int i = start; i < end; i++) { range.add(i); } return range; } // accept a collection of objects, since all objects have toString() public static String join(String delimiter, String wrap, Iterable<? extends Object> objs) { Iterator<? extends Object> iter = objs.iterator(); if (!iter.hasNext()) { return ""; } StringBuilder buffer = new StringBuilder(); buffer.append(wrap).append(iter.next()).append(wrap); while (iter.hasNext()) { buffer.append(delimiter).append(wrap).append(iter.next()).append(wrap); } return buffer.toString(); } // accept a collection of objects, since all objects have toString() public static String join(String delimiter, Iterable<? extends Object> objs) { return join(delimiter, "", objs); } //--------------------------------------------------------- // // IO // //--------------------------------------------------------- public static void closeQuietly(Closeable closeable) { try { if (closeable != null) { closeable.close(); } } catch (IOException ignore) { } } //--------------------------------------------------------- // // Strings // //--------------------------------------------------------- public static boolean isInt(String str) { if (str == null) { return false; } int sz = str.length(); for (int i = 0; i < sz; i++) { if (Character.isDigit(str.charAt(i)) == false) { return false; } } return true; } public static boolean isNumeric(String str) { if (str == null) { return false; } int sz = str.length(); for (int i = 0; i < sz; i++) { if (Character.isDigit(str.charAt(i)) == false && !(str.charAt(i) == '.')) { return false; } } return true; } /** * <p>Checks if a CharSequence is empty ("") or null.</p> * <p/> * <pre> * StringUtils.isEmpty(null) = true * StringUtils.isEmpty("") = true * StringUtils.isEmpty(" ") = false * StringUtils.isEmpty("bob") = false * StringUtils.isEmpty(" bob ") = false * </pre> * <p/> * <p>NOTE: This method changed in Lang version 2.0. * It no longer trims the CharSequence. * That functionality is available in isBlank().</p> * * @param cs the CharSequence to check, may be null * @return {@code true} if the CharSequence is empty or null * @since 3.0 Changed signature from isEmpty(String) to isEmpty(CharSequence) */ public static boolean isEmpty(CharSequence cs) { return cs == null || cs.length() == 0; } /** * Used by the indexOf(CharSequence methods) as a green implementation of indexOf. * * @param cs the {@code CharSequence} to be processed * @param searchChar the {@code CharSequence} to be searched for * @param start the start index * @return the index where the search sequence was found */ static int indexOf(CharSequence cs, CharSequence searchChar, int start) { return cs.toString().indexOf(searchChar.toString(), start); } /** * <p>Counts how many times the substring appears in the larger string.</p> * <p/> * <p>A {@code null} or empty ("") String input returns {@code 0}.</p> * <p/> * <pre> * StringUtils.countMatches(null, *) = 0 * StringUtils.countMatches("", *) = 0 * StringUtils.countMatches("abba", null) = 0 * StringUtils.countMatches("abba", "") = 0 * StringUtils.countMatches("abba", "a") = 2 * StringUtils.countMatches("abba", "ab") = 1 * StringUtils.countMatches("abba", "xxx") = 0 * </pre> * * @param str the CharSequence to check, may be null * @param sub the substring to count, may be null * @return the number of occurrences, 0 if either CharSequence is {@code null} * @since 3.0 Changed signature from countMatches(String, String) to countMatches(CharSequence, CharSequence) */ public static int countMatches(CharSequence str, CharSequence sub) { if (isEmpty(str) || isEmpty(sub)) { return 0; } int count = 0; int idx = 0; while ((idx = indexOf(str, sub, idx)) != -1) { count++; idx += sub.length(); } return count; } //--------------------------------------------------------- // // Validators // //--------------------------------------------------------- /** * <p>Validate that the specified argument is not {@code null}; * otherwise throwing an exception with the specified message. * <p/> * <pre>Validate.notNull(myObject, "The object must not be null");</pre> * * @param <T> the object type * @param object the object to check * @param message the {@link String#format(String, Object...)} exception message if invalid, not null * @param values the optional values for the formatted exception message * @return the validated object (never {@code null} for method chaining) * @throws NullPointerException if the object is {@code null} */ public static <T> T notNull(T object, String message, Object... values) { if (object == null) { throw new IllegalArgumentException(String.format(message, values)); } return object; } /** * <p>Validate that the argument condition is {@code true}; otherwise * throwing an exception with the specified message. This method is useful when * validating according to an arbitrary boolean expression, such as validating a * primitive number or using your own custom validation expression.</p> * <p/> * <pre>Validate.isTrue(i > 0.0, "The value must be greater than zero: %d", i);</pre> * <p/> * <p>For performance reasons, the long value is passed as a separate parameter and * appended to the exception message only in the case of an error.</p> * * @param expression the boolean expression to check * @param message * @throws IllegalArgumentException if expression is {@code false} */ public static void isTrue(boolean expression, String message) { if (expression == false) { throw new IllegalArgumentException(message); } } /** * <p>Validate that the specified argument character sequence is * neither {@code null} nor a length of zero (no characters); * otherwise throwing an exception with the specified message. * <p/> * <pre>Validate.notEmpty(myString, "The string must not be empty");</pre> * * @param <T> the character sequence type * @param chars the character sequence to check, validated not null by this method * @param message the {@link String#format(String, Object...)} exception message if invalid, not null * @param values the optional values for the formatted exception message, null array not recommended * @return the validated character sequence (never {@code null} method for chaining) * @throws NullPointerException if the character sequence is {@code null} * @throws IllegalArgumentException if the character sequence is empty */ public static <T extends CharSequence> T notEmpty(T chars, String message, Object... values) { if (chars == null) { throw new IllegalArgumentException(String.format(message, values)); } if (chars.length() == 0) { throw new IllegalArgumentException(String.format(message, values)); } return chars; } //--------------------------------------------------------- // // Converters // //--------------------------------------------------------- public static String toString(Object o) { if (null == o) { return null; } return o.toString(); } //--------------------------------------------------------- // // Serialization // //--------------------------------------------------------- /** * <p>Deep clone an {@code Object} using serialization.</p> * <p/> * <p>This is many times slower than writing clone methods by hand * on all objects in your object graph. However, for complex object * graphs, or for those that don't support deep cloning this can * be a simple alternative implementation. Of course all the objects * must be {@code Serializable}.</p> * * @param <T> the type of the object involved * @param object the {@code Serializable} object to clone * @return the cloned object */ public static <T extends Serializable> T clone(T object) { if (object == null) { return null; } byte[] objectData = serialize(object); ByteArrayInputStream bais = new ByteArrayInputStream(objectData); ClassLoaderAwareObjectInputStream in = null; try { // stream closed in the finally in = new ClassLoaderAwareObjectInputStream(bais, object.getClass().getClassLoader()); /* * when we serialize and deserialize an object, * it is reasonable to assume the deserialized object * is of the same type as the original serialized object */ @SuppressWarnings("unchecked") // see above T readObject = (T) in.readObject(); return readObject; } catch (ClassNotFoundException ex) { throw new RuntimeException("ClassNotFoundException while reading cloned object data", ex); } catch (IOException ex) { throw new RuntimeException("IOException while reading cloned object data", ex); } finally { try { if (in != null) { in.close(); } } catch (IOException ex) { throw new RuntimeException("IOException on closing cloned object data InputStream.", ex); } } } /** * <p>Serializes an {@code Object} to the specified stream.</p> * <p/> * <p>The stream will be closed once the object is written. * This avoids the need for a finally clause, and maybe also exception * handling, in the application code.</p> * <p/> * <p>The stream passed in is not buffered internally within this method. * This is the responsibility of your application if desired.</p> * * @param obj the object to serialize to bytes, may be null * @param outputStream the stream to write to, must not be null * @throws IllegalArgumentException if {@code outputStream} is {@code null} * @throws RuntimeException (runtime) if the serialization fails */ public static void serialize(Serializable obj, OutputStream outputStream) { if (outputStream == null) { throw new IllegalArgumentException("The OutputStream must not be null"); } ObjectOutputStream out = null; try { // stream closed in the finally out = new ObjectOutputStream(outputStream); out.writeObject(obj); } catch (IOException ex) { throw new RuntimeException(ex); } finally { try { if (out != null) { out.close(); } } catch (IOException ex) { // NOPMD // ignore close exception } } } /** * <p>Serializes an {@code Object} to a byte array for * storage/serialization.</p> * * @param obj the object to serialize to bytes * @return a byte[] with the converted Serializable * @throws RuntimeException (runtime) if the serialization fails */ public static byte[] serialize(Serializable obj) { ByteArrayOutputStream baos = new ByteArrayOutputStream(512); serialize(obj, baos); return baos.toByteArray(); } // Deserialize //----------------------------------------------------------------------- /** * <p>Deserializes an {@code Object} from the specified stream.</p> * <p/> * <p>The stream will be closed once the object is written. This * avoids the need for a finally clause, and maybe also exception * handling, in the application code.</p> * <p/> * <p>The stream passed in is not buffered internally within this method. * This is the responsibility of your application if desired.</p> * * @param inputStream the serialized object input stream, must not be null * @return the deserialized object * @throws IllegalArgumentException if {@code inputStream} is {@code null} * @throws RuntimeException (runtime) if the serialization fails */ public static Object deserialize(InputStream inputStream) { if (inputStream == null) { throw new IllegalArgumentException("The InputStream must not be null"); } ObjectInputStream in = null; try { // stream closed in the finally in = new ObjectInputStream(inputStream); return in.readObject(); } catch (ClassNotFoundException ex) { throw new RuntimeException(ex); } catch (IOException ex) { throw new RuntimeException(ex); } finally { try { if (in != null) { in.close(); } } catch (IOException ex) { // NOPMD // ignore close exception } } } /** * <p>Deserializes a single {@code Object} from an array of bytes.</p> * * @param objectData the serialized object, must not be null * @return the deserialized object * @throws IllegalArgumentException if {@code objectData} is {@code null} * @throws RuntimeException (runtime) if the serialization fails */ public static Object deserialize(byte[] objectData) { if (objectData == null) { throw new IllegalArgumentException("The byte[] must not be null"); } ByteArrayInputStream bais = new ByteArrayInputStream(objectData); return deserialize(bais); } /** * <p>Custom specialization of the standard JDK {@link java.io.ObjectInputStream} * that uses a custom <code>ClassLoader</code> to resolve a class. * If the specified <code>ClassLoader</code> is not able to resolve the class, * the context classloader of the current thread will be used. * This way, the standard deserialization work also in web-application * containers and application servers, no matter in which of the * <code>ClassLoader</code> the particular class that encapsulates * serialization/deserialization lives. </p> * <p/> * <p>For more in-depth information about the problem for which this * class here is a workaround, see the JIRA issue LANG-626. </p> */ static class ClassLoaderAwareObjectInputStream extends ObjectInputStream { private ClassLoader classLoader; /** * Constructor. * * @param in The <code>InputStream</code>. * @param classLoader classloader to use * @throws IOException if an I/O error occurs while reading stream header. * @see java.io.ObjectInputStream */ public ClassLoaderAwareObjectInputStream(InputStream in, ClassLoader classLoader) throws IOException { super(in); this.classLoader = classLoader; } /** * Overriden version that uses the parametrized <code>ClassLoader</code> or the <code>ClassLoader</code> * of the current <code>Thread</code> to resolve the class. * * @param desc An instance of class <code>ObjectStreamClass</code>. * @return A <code>Class</code> object corresponding to <code>desc</code>. * @throws IOException Any of the usual Input/Output exceptions. * @throws ClassNotFoundException If class of a serialized object cannot be found. */ @Override protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException { String name = desc.getName(); try { return Class.forName(name, false, classLoader); } catch (ClassNotFoundException ex) { return Class.forName(name, false, Thread.currentThread().getContextClassLoader()); } } } }
remove unused import, make Utils a real utility class (final and private c'tor)
json-path/src/main/java/com/jayway/jsonpath/internal/Utils.java
remove unused import, make Utils a real utility class (final and private c'tor)
Java
bsd-3-clause
c1d7f35c1c1fa8068737e2a944dff03a4fc2bf13
0
damiancarrillo/agave-framework,damiancarrillo/agave-framework
package co.cdev.agave; import java.text.DateFormatSymbols; import java.text.ParseException; import java.text.ParsePosition; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; import java.util.TimeZone; /** * This class support a profile of the functionality defined in the ISO/FDIS * 8601:2000(E) date format. The international standard describes multiple ways * to specify a date, however this class is only concerned with specifying a date * with a year, month, date, and optionally a time specified as hours, minutes, * and optionall seconds. The time may also have a time zone designator, specified * with a plus or minus and either 4 or 2 digits that follow to represent the * hourly offset along with optional minutes. * * The following examples should sufficiently illustrate the subset of the standard * that this class supports: * * <pre> * YYYYMMDD 19850412 * YYYYDDD 1985123 (123rd day of the year) * YYYYMMDDThh 19850412T10 * YYYYMMDDThhmm 19850412T1015 * YYYYMMDDThhmmZ 19850412T1015Z * YYYYMMDDThhmmss 19850412T101530 * YYYYMMDDThhmmssZ 19850412T101530Z * YYYYMMDDThhmmss±hhmm 19850412T101530+0400 * YYYYMMDDThhmmss±hh 19850412T101530+04 * YYYY-MM-DD 1985-04-12 * YYYY-DDD 1985-123 (123rd day of the year) * YYYY-MM-DDThh 1985-04-12T10 * YYYY-MM-DDThhZ 1985-04-12T10Z * YYYY-MM-DDThh:mm 1985-04-12T10:15 * YYYY-MM-DDThh:mmZ 1985-04-12T10:15Z * YYYY-MM-DDThh:mm:ss 1985-04-12T10:15:30 * YYYY-MM-DDThh:mm:ssZ 1985-04-12T10:15:30Z * YYYY-MM-DDThh:mm:ss±hh:mm 1985-04-12T10:15:30+04:00 * YYYY-MM-DDThh:mm:ss±hhmm 1985-04-12T10:15:30+0400 * YYYY-MM-DDThh:mm:ss±hh 1985-04-12T10:15:30+04</pre> * * The date must be specified in full, and must be exactly 8 digits long, with an * optional dash to separate each component of the date. Optionally specify a date * as a year followed by the ordinal number of the day in the year. Also, you can * specify the date as the year, followed by the week of the year, followed by the * day of the week, were Monday is 1, Tuesday is 2, ..., Sunday is 7. * * A great degree of granularity can be left off in the time designator. Any missing * component indicates 00, eg. 18 implies 6 o'clock PM, with 0 seconds trailing. An * optional colon can denote different components of the time. * * If the time zone is missing, that indicates UTC time (as does a 'Z'). It can * be specified with a plus or a minus, followed by a trailing number of hours * or minutes. The specification is relative to UTC, and the granularity depends * on the number of specified digits. * * Note that this also corresponds to RFC 3339 Timestamps: * * http://www.ietf.org/rfc/rfc3339.txt * * @author <a href="[email protected]">Damian Carrillo</a> */ public class ISO8601DateFormat extends SimpleDateFormat { private static final long serialVersionUID = 1L; private final Locale locale; public ISO8601DateFormat(Locale locale) { super("yyyy-MM-dd'T'HH:mm:ssZ", locale); this.locale = locale; super.setTimeZone(TimeZone.getTimeZone("UTC")); } @Override public Date parse(String input) throws ParseException { return (Date) parseObject(input); } @Override public Object parseObject(String input) throws ParseException { return parseObject(input, null); } @Override public Object parseObject(String input, ParsePosition parsePosition) { Date parsedDate = null; if (input != null && !"".equals(input)) { String formatString = null; String actualInput = null; String[] components = input.split("T"); if (components.length > 0) { components[0] = components[0].replace("-", ""); if (components[0].contains("W")) { // Date as year, week in year, day of week (starting with Monday as 1 // and ending with Sunday as 7 formatString = "yyyy'W'wwEEE"; actualInput = components[0].substring(0, 7); DateFormatSymbols symbols = new DateFormatSymbols(locale); int dayOfWeek = Integer.valueOf(components[0].substring(7, 8)); if (dayOfWeek == 1) { actualInput += symbols.getWeekdays()[Calendar.MONDAY]; } else if (dayOfWeek == 2) { actualInput += symbols.getWeekdays()[Calendar.TUESDAY]; } else if (dayOfWeek == 3) { actualInput += symbols.getWeekdays()[Calendar.WEDNESDAY]; } else if (dayOfWeek == 4) { actualInput += symbols.getWeekdays()[Calendar.THURSDAY]; } else if (dayOfWeek == 5) { actualInput += symbols.getWeekdays()[Calendar.FRIDAY]; } else if (dayOfWeek == 6) { actualInput += symbols.getWeekdays()[Calendar.SATURDAY]; } else if (dayOfWeek == 7) { actualInput += symbols.getWeekdays()[Calendar.SUNDAY]; } } else if (components[0].length() == 8) { // Date as year, month, day formatString = "yyyyMMdd"; actualInput = components[0]; } else if (components[0].length() == 7) { // Date as year and day of year formatString = "yyyyDDD"; actualInput = components[0]; } if (formatString != null && actualInput != null) { // Optional Time and Time Zone if (components.length > 1) { components[1] = components[1].replace(":", ""); components[1] = components[1].replace("Z", ""); String timePart = null; String timeZonePart = null; if (components[1].contains("+")) { String[] timeComponents = components[1].split("\\+"); timePart = timeComponents[0]; timeZonePart = "+" + timeComponents[1]; } else if (components[1].contains("-")) { String[] timeComponents = components[1].split("\\-"); timePart = timeComponents[0]; timeZonePart = "-" + timeComponents[1]; } else { timePart = components[1]; } // Time if (timePart != null) { while (timePart.length() < 4) { timePart += "0"; } if (timePart.length() > 6) { timePart = timePart.substring(0, 6); } actualInput += timePart; if (timePart.length() == 4) { formatString += "HHmm"; } else if (timePart.length() == 6) { formatString += "HHmmss"; } // Time Zone if (timeZonePart != null) { if (timeZonePart.length() == 1) { timeZonePart = null; } else { while (timeZonePart.length() < 5) { timeZonePart += "0"; } actualInput += timeZonePart; formatString += "Z"; } } } } } } SimpleDateFormat format = new SimpleDateFormat(formatString); try { parsedDate = format.parse(actualInput); parsedDate.setTime(parsedDate.getTime() / 1000 * 1000); // shave off milliseconds } catch (ParseException e) { // do nothing on invalid input } } return parsedDate; } }
agave-core/src/main/java/co/cdev/agave/ISO8601DateFormat.java
package co.cdev.agave; import java.text.DateFormatSymbols; import java.text.ParseException; import java.text.ParsePosition; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; import java.util.TimeZone; /** * This class support a profile of the functionality defined in the ISO/FDIS * 8601:2000(E) date format. The international standard describes multiple ways * to specify a date, however this class is only concerned with specifying a date * with a year, month, date, and optionally a time specified as hours, minutes, * and optionall seconds. The time may also have a time zone designator, specified * with a plus or minus and either 4 or 2 digits that follow to represent the * hourly offset along with optional minutes. * * The following examples should sufficiently illustrate the subset of the standard * that this class supports: * * <pre> * YYYYMMDD 19850412 * YYYYDDD 1985123 (123rd day of the year) * YYYYMMDDThh 19850412T10 * YYYYMMDDThhmm 19850412T1015 * YYYYMMDDThhmmZ 19850412T1015Z * YYYYMMDDThhmmss 19850412T101530 * YYYYMMDDThhmmssZ 19850412T101530Z * YYYYMMDDThhmmss±hhmm 19850412T101530+0400 * YYYYMMDDThhmmss±hh 19850412T101530+04 * YYYY-MM-DD 1985-04-12 * YYYY-DDD 1985-123 (123rd day of the year) * YYYY-MM-DDThh 1985-04-12T10 * YYYY-MM-DDThhZ 1985-04-12T10Z * YYYY-MM-DDThh:mm 1985-04-12T10:15 * YYYY-MM-DDThh:mmZ 1985-04-12T10:15Z * YYYY-MM-DDThh:mm:ss 1985-04-12T10:15:30 * YYYY-MM-DDThh:mm:ssZ 1985-04-12T10:15:30Z * YYYY-MM-DDThh:mm:ss±hh:mm 1985-04-12T10:15:30+04:00 * YYYY-MM-DDThh:mm:ss±hhmm 1985-04-12T10:15:30+0400 * YYYY-MM-DDThh:mm:ss±hh 1985-04-12T10:15:30+04</pre> * * The date must be specified in full, and must be exactly 8 digits long, with an * optional dash to separate each component of the date. Optionally specify a date * as a year followed by the ordinal number of the day in the year. Also, you can * specify the date as the year, followed by the week of the year, followed by the * day of the week, were Monday is 1, Tuesday is 2, ..., Sunday is 7. * * A great degree of granularity can be left off in the time designator. Any missing * component indicates 00, eg. 18 implies 6 o'clock PM, with 0 seconds trailing. An * optional colon can denote different components of the time. * * If the time zone is missing, that indicates UTC time (as does a 'Z'). It can * be specified with a plus or a minus, followed by a trailing number of hours * or minutes. The specification is relative to UTC, and the granularity depends * on the number of specified digits. * * @author <a href="[email protected]">Damian Carrillo</a> */ public class ISO8601DateFormat extends SimpleDateFormat { private static final long serialVersionUID = 1L; private final Locale locale; public ISO8601DateFormat(Locale locale) { super("yyyy-MM-dd'T'HH:mm:ssZ", locale); this.locale = locale; super.setTimeZone(TimeZone.getTimeZone("UTC")); } @Override public Date parse(String input) throws ParseException { return (Date) parseObject(input); } @Override public Object parseObject(String input) throws ParseException { return parseObject(input, null); } @Override public Object parseObject(String input, ParsePosition parsePosition) { Date parsedDate = null; if (input != null && !"".equals(input)) { String formatString = null; String actualInput = null; String[] components = input.split("T"); if (components.length > 0) { components[0] = components[0].replace("-", ""); if (components[0].contains("W")) { // Date as year, week in year, day of week (starting with Monday as 1 // and ending with Sunday as 7 formatString = "yyyy'W'wwEEE"; actualInput = components[0].substring(0, 7); DateFormatSymbols symbols = new DateFormatSymbols(locale); int dayOfWeek = Integer.valueOf(components[0].substring(7, 8)); if (dayOfWeek == 1) { actualInput += symbols.getWeekdays()[Calendar.MONDAY]; } else if (dayOfWeek == 2) { actualInput += symbols.getWeekdays()[Calendar.TUESDAY]; } else if (dayOfWeek == 3) { actualInput += symbols.getWeekdays()[Calendar.WEDNESDAY]; } else if (dayOfWeek == 4) { actualInput += symbols.getWeekdays()[Calendar.THURSDAY]; } else if (dayOfWeek == 5) { actualInput += symbols.getWeekdays()[Calendar.FRIDAY]; } else if (dayOfWeek == 6) { actualInput += symbols.getWeekdays()[Calendar.SATURDAY]; } else if (dayOfWeek == 7) { actualInput += symbols.getWeekdays()[Calendar.SUNDAY]; } } else if (components[0].length() == 8) { // Date as year, month, day formatString = "yyyyMMdd"; actualInput = components[0]; } else if (components[0].length() == 7) { // Date as year and day of year formatString = "yyyyDDD"; actualInput = components[0]; } if (formatString != null && actualInput != null) { // Optional Time and Time Zone if (components.length > 1) { components[1] = components[1].replace(":", ""); components[1] = components[1].replace("Z", ""); String timePart = null; String timeZonePart = null; if (components[1].contains("+")) { String[] timeComponents = components[1].split("\\+"); timePart = timeComponents[0]; timeZonePart = "+" + timeComponents[1]; } else if (components[1].contains("-")) { String[] timeComponents = components[1].split("\\-"); timePart = timeComponents[0]; timeZonePart = "-" + timeComponents[1]; } else { timePart = components[1]; } // Time if (timePart != null) { while (timePart.length() < 4) { timePart += "0"; } if (timePart.length() > 6) { timePart = timePart.substring(0, 6); } actualInput += timePart; if (timePart.length() == 4) { formatString += "HHmm"; } else if (timePart.length() == 6) { formatString += "HHmmss"; } // Time Zone if (timeZonePart != null) { if (timeZonePart.length() == 1) { timeZonePart = null; } else { while (timeZonePart.length() < 5) { timeZonePart += "0"; } actualInput += timeZonePart; formatString += "Z"; } } } } } } SimpleDateFormat format = new SimpleDateFormat(formatString); try { parsedDate = format.parse(actualInput); parsedDate.setTime(parsedDate.getTime() / 1000 * 1000); // shave off milliseconds } catch (ParseException e) { // do nothing on invalid input } } return parsedDate; } }
Clarifying documentation
agave-core/src/main/java/co/cdev/agave/ISO8601DateFormat.java
Clarifying documentation
Java
bsd-3-clause
8d40005a577699b02816ed6f8c536d03b37aeb51
0
NCIP/cananolab,NCIP/cananolab,NCIP/cananolab
package gov.nih.nci.calab.service.common; import gov.nih.nci.calab.db.DataAccessProxy; import gov.nih.nci.calab.db.HibernateDataAccess; import gov.nih.nci.calab.db.IDataAccess; import gov.nih.nci.calab.domain.Aliquot; import gov.nih.nci.calab.domain.Instrument; import gov.nih.nci.calab.domain.MeasureUnit; import gov.nih.nci.calab.domain.Protocol; import gov.nih.nci.calab.domain.ProtocolFile; import gov.nih.nci.calab.domain.Sample; import gov.nih.nci.calab.domain.SampleContainer; import gov.nih.nci.calab.domain.StorageElement; import gov.nih.nci.calab.dto.characterization.CharacterizationTypeBean; import gov.nih.nci.calab.dto.common.InstrumentBean; import gov.nih.nci.calab.dto.common.LabFileBean; import gov.nih.nci.calab.dto.common.ProtocolBean; import gov.nih.nci.calab.dto.common.ProtocolFileBean; import gov.nih.nci.calab.dto.common.UserBean; import gov.nih.nci.calab.dto.inventory.AliquotBean; import gov.nih.nci.calab.dto.inventory.ContainerBean; import gov.nih.nci.calab.dto.inventory.ContainerInfoBean; import gov.nih.nci.calab.dto.inventory.SampleBean; import gov.nih.nci.calab.dto.workflow.AssayBean; import gov.nih.nci.calab.service.security.UserService; import gov.nih.nci.calab.service.util.CaNanoLabComparators; import gov.nih.nci.calab.service.util.CaNanoLabConstants; import gov.nih.nci.calab.service.util.StringUtils; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.SortedSet; import java.util.TreeSet; import org.apache.log4j.Logger; import org.apache.struts.util.LabelValueBean; import org.hibernate.Hibernate; import org.hibernate.SQLQuery; import org.hibernate.collection.PersistentSet; /** * The service to return prepopulated data that are shared across different * views. * * @author zengje * */ /* CVS $Id: LookupService.java,v 1.112 2007-06-26 15:17:30 pansu Exp $ */ public class LookupService { private static Logger logger = Logger.getLogger(LookupService.class); /** * Retrieving all unmasked aliquots for use in views create run, use aliquot * and create aliquot. * * @return a Map between sample name and its associated unmasked aliquots * @throws Exception */ public Map<String, SortedSet<AliquotBean>> getUnmaskedSampleAliquots() throws Exception { SortedSet<AliquotBean> aliquots = null; IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); Map<String, SortedSet<AliquotBean>> sampleAliquots = new HashMap<String, SortedSet<AliquotBean>>(); try { ida.open(); String hqlString = "select aliquot.id, aliquot.name, aliquot.sample.name from Aliquot aliquot where aliquot.dataStatus is null order by aliquot.name"; List results = ida.search(hqlString); for (Object obj : results) { Object[] info = (Object[]) obj; AliquotBean aliquot = new AliquotBean(StringUtils .convertToString(info[0]), StringUtils .convertToString(info[1]), CaNanoLabConstants.ACTIVE_STATUS); String sampleName = (String) info[2]; if (sampleAliquots.get(sampleName) != null) { aliquots = (SortedSet<AliquotBean>) sampleAliquots .get(sampleName); } else { aliquots = new TreeSet<AliquotBean>( new CaNanoLabComparators.AliquotBeanComparator()); sampleAliquots.put(sampleName, aliquots); } aliquots.add(aliquot); } } catch (Exception e) { logger.error("Error in retrieving all aliquot Ids and names", e); throw new RuntimeException( "Error in retrieving all aliquot Ids and names"); } finally { ida.close(); } return sampleAliquots; } /** * * @return a map between sample name and its sample containers * @throws Exception */ public Map<String, SortedSet<ContainerBean>> getAllSampleContainers() throws Exception { SortedSet<ContainerBean> containers = null; IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); Map<String, SortedSet<ContainerBean>> sampleContainers = new HashMap<String, SortedSet<ContainerBean>>(); try { ida.open(); String hqlString = "select container, container.sample.name from SampleContainer container"; List results = ida.search(hqlString); for (Object obj : results) { Object[] info = (Object[]) obj; if (!(info[0] instanceof Aliquot)) { ContainerBean container = new ContainerBean( (SampleContainer) info[0]); String sampleName = (String) info[1]; if (sampleContainers.get(sampleName) != null) { containers = (SortedSet<ContainerBean>) sampleContainers .get(sampleName); } else { containers = new TreeSet<ContainerBean>( new CaNanoLabComparators.ContainerBeanComparator()); sampleContainers.put(sampleName, containers); } containers.add(container); } } } catch (Exception e) { logger.error("Error in retrieving all containers", e); throw new RuntimeException("Error in retrieving all containers"); } finally { ida.close(); } return sampleContainers; } /** * Retrieving all sample types. * * @return a list of all sample types */ public List<String> getAllSampleTypes() throws Exception { // Detail here // Retrieve data from Sample_Type table List<String> sampleTypes = new ArrayList<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select sampleType.name from SampleType sampleType order by sampleType.name"; List results = ida.search(hqlString); for (Object obj : results) { sampleTypes.add((String) obj); } } catch (Exception e) { logger.error("Error in retrieving all sample types", e); throw new RuntimeException("Error in retrieving all sample types"); } finally { ida.close(); } return sampleTypes; } /** * * @return the default sample container information in a form of * ContainerInfoBean */ public ContainerInfoBean getSampleContainerInfo() throws Exception { List<MeasureUnit> units = getAllMeasureUnits(); List<StorageElement> storageElements = getAllStorageElements(); List<String> quantityUnits = new ArrayList<String>(); List<String> concentrationUnits = new ArrayList<String>(); List<String> volumeUnits = new ArrayList<String>(); List<String> rooms = new ArrayList<String>(); List<String> freezers = new ArrayList<String>(); List<String> shelves = new ArrayList<String>(); List<String> boxes = new ArrayList<String>(); for (MeasureUnit unit : units) { if (unit.getType().equalsIgnoreCase("Quantity")) { quantityUnits.add(unit.getName()); } else if (unit.getType().equalsIgnoreCase("Volume")) { volumeUnits.add(unit.getName()); } else if (unit.getType().equalsIgnoreCase("Concentration")) { concentrationUnits.add(unit.getName()); } } for (StorageElement storageElement : storageElements) { if (storageElement.getType().equalsIgnoreCase("Room") && !rooms.contains(storageElement.getLocation())) { rooms.add((storageElement.getLocation())); } else if (storageElement.getType().equalsIgnoreCase("Freezer") && !freezers.contains(storageElement.getLocation())) { freezers.add((storageElement.getLocation())); } else if (storageElement.getType().equalsIgnoreCase("Shelf") && !shelves.contains(storageElement.getLocation())) { shelves.add((storageElement.getLocation())); } else if (storageElement.getType().equalsIgnoreCase("Box") && !boxes.contains(storageElement.getLocation())) { boxes.add((storageElement.getLocation())); } } // set labs and racks to null for now ContainerInfoBean containerInfo = new ContainerInfoBean(quantityUnits, concentrationUnits, volumeUnits, null, rooms, freezers, shelves, boxes); return containerInfo; } public List<String> getAllSampleContainerTypes() throws Exception { SortedSet<String> containerTypes = new TreeSet<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct container.containerType from SampleContainer container order by container.containerType"; List results = ida.search(hqlString); for (Object obj : results) { containerTypes.add((String) obj); } } catch (Exception e) { logger.error("Error in retrieving all sample container types", e); throw new RuntimeException( "Error in retrieving all sample container types."); } finally { ida.close(); } containerTypes.addAll(Arrays .asList(CaNanoLabConstants.DEFAULT_CONTAINER_TYPES)); List<String> containerTypeList = new ArrayList<String>(containerTypes); return containerTypeList; } public List<String> getAllAliquotContainerTypes() throws Exception { SortedSet<String> containerTypes = new TreeSet<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct aliquot.containerType from Aliquot aliquot order by aliquot.containerType"; List results = ida.search(hqlString); for (Object obj : results) { containerTypes.add((String) obj); } } catch (Exception e) { logger.error("Error in retrieving all aliquot container types", e); throw new RuntimeException( "Error in retrieving all aliquot container types."); } finally { ida.close(); } containerTypes.addAll(Arrays .asList(CaNanoLabConstants.DEFAULT_CONTAINER_TYPES)); List<String> containerTypeList = new ArrayList<String>(containerTypes); return containerTypeList; } private List<MeasureUnit> getAllMeasureUnits() throws Exception { List<MeasureUnit> units = new ArrayList<MeasureUnit>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "from MeasureUnit"; List results = ida.search(hqlString); for (Object obj : results) { units.add((MeasureUnit) obj); } } catch (Exception e) { logger.error("Error in retrieving all measure units", e); throw new RuntimeException("Error in retrieving all measure units."); } finally { ida.close(); } return units; } private List<StorageElement> getAllStorageElements() throws Exception { List<StorageElement> storageElements = new ArrayList<StorageElement>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "from StorageElement where type in ('Room', 'Freezer', 'Shelf', 'Box') and location!='Other'"; List results = ida.search(hqlString); for (Object obj : results) { storageElements.add((StorageElement) obj); } } catch (Exception e) { logger.error("Error in retrieving all rooms and freezers", e); throw new RuntimeException( "Error in retrieving all rooms and freezers."); } finally { ida.close(); } return storageElements; } /** * * @return the default sample container information in a form of * ContainerInfoBean */ public ContainerInfoBean getAliquotContainerInfo() throws Exception { return getSampleContainerInfo(); } /** * Get all samples in the database * * @return a list of SampleBean containing sample Ids and names DELETE */ public List<SampleBean> getAllSamples() throws Exception { List<SampleBean> samples = new ArrayList<SampleBean>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select sample.id, sample.name from Sample sample"; List results = ida.search(hqlString); for (Object obj : results) { Object[] sampleInfo = (Object[]) obj; samples.add(new SampleBean(StringUtils .convertToString(sampleInfo[0]), StringUtils .convertToString(sampleInfo[1]))); } } catch (Exception e) { logger.error("Error in retrieving all sample IDs and names", e); throw new RuntimeException( "Error in retrieving all sample IDs and names"); } finally { ida.close(); } Collections.sort(samples, new CaNanoLabComparators.SampleBeanComparator()); return samples; } /** * Retrieve all Assay Types from the system * * @return A list of all assay type */ public List getAllAssayTypes() throws Exception { List<String> assayTypes = new ArrayList<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select assayType.name from AssayType assayType order by assayType.executeOrder"; List results = ida.search(hqlString); for (Object obj : results) { assayTypes.add((String) obj); } } catch (Exception e) { logger.error("Error in retrieving all assay types", e); throw new RuntimeException("Error in retrieving all assay types"); } finally { ida.close(); } return assayTypes; } /** * * @return a map between assay type and its assays * @throws Exception */ public Map<String, SortedSet<AssayBean>> getAllAssayTypeAssays() throws Exception { Map<String, SortedSet<AssayBean>> assayTypeAssays = new HashMap<String, SortedSet<AssayBean>>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select assay.id, assay.name, assay.assayType from Assay assay"; List results = ida.search(hqlString); SortedSet<AssayBean> assays = null; for (Object obj : results) { Object[] objArray = (Object[]) obj; AssayBean assay = new AssayBean( ((Long) objArray[0]).toString(), (String) objArray[1], (String) objArray[2]); if (assayTypeAssays.get(assay.getAssayType()) != null) { assays = (SortedSet<AssayBean>) assayTypeAssays.get(assay .getAssayType()); } else { assays = new TreeSet<AssayBean>( new CaNanoLabComparators.AssayBeanComparator()); assayTypeAssays.put(assay.getAssayType(), assays); } assays.add(assay); } } catch (Exception e) { // TODO: temp for debuging use. remove later e.printStackTrace(); logger.error("Error in retrieving all assay beans. ", e); throw new RuntimeException("Error in retrieving all assays beans. "); } finally { ida.close(); } return assayTypeAssays; } /** * * @return all sample sources */ public List<String> getAllSampleSources() throws Exception { List<String> sampleSources = new ArrayList<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select source.organizationName from Source source order by source.organizationName"; List results = ida.search(hqlString); for (Object obj : results) { sampleSources.add((String) obj); } } catch (Exception e) { logger.error("Error in retrieving all sample sources", e); throw new RuntimeException("Error in retrieving all sample sources"); } finally { ida.close(); } return sampleSources; } /** * * @return a map between sample source and samples with unmasked aliquots * @throws Exception */ public Map<String, SortedSet<SampleBean>> getSampleSourceSamplesWithUnmaskedAliquots() throws Exception { Map<String, SortedSet<SampleBean>> sampleSourceSamples = new HashMap<String, SortedSet<SampleBean>>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct aliquot.sample from Aliquot aliquot where aliquot.dataStatus is null"; List results = ida.search(hqlString); SortedSet<SampleBean> samples = null; for (Object obj : results) { SampleBean sample = new SampleBean((Sample) obj); if (sampleSourceSamples.get(sample.getSampleSource()) != null) { // TODO need to make sample source a required field if (sample.getSampleSource().length() > 0) { samples = (SortedSet<SampleBean>) sampleSourceSamples .get(sample.getSampleSource()); } } else { samples = new TreeSet<SampleBean>( new CaNanoLabComparators.SampleBeanComparator()); if (sample.getSampleSource().length() > 0) { sampleSourceSamples.put(sample.getSampleSource(), samples); } } samples.add(sample); } } catch (Exception e) { logger.error( "Error in retrieving sample beans with unmasked aliquots ", e); throw new RuntimeException( "Error in retrieving all sample beans with unmasked aliquots. "); } finally { ida.close(); } return sampleSourceSamples; } public List<String> getAllSampleSOPs() throws Exception { List<String> sampleSOPs = new ArrayList<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select sampleSOP.name from SampleSOP sampleSOP where sampleSOP.description='sample creation'"; List results = ida.search(hqlString); for (Object obj : results) { sampleSOPs.add((String) obj); } } catch (Exception e) { logger.error("Problem to retrieve all Sample SOPs."); throw new RuntimeException("Problem to retrieve all Sample SOPs. "); } finally { ida.close(); } return sampleSOPs; } /** * * @return all methods for creating aliquots */ public List<LabelValueBean> getAliquotCreateMethods() throws Exception { List<LabelValueBean> createMethods = new ArrayList<LabelValueBean>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select sop.name, file.path from SampleSOP sop join sop.sampleSOPFileCollection file where sop.description='aliquot creation'"; List results = ida.search(hqlString); for (Object obj : results) { String sopName = (String) ((Object[]) obj)[0]; String sopURI = (String) ((Object[]) obj)[1]; String sopURL = (sopURI == null) ? "" : sopURI; createMethods.add(new LabelValueBean(sopName, sopURL)); } } catch (Exception e) { logger.error("Error in retrieving all sample sources", e); throw new RuntimeException("Error in retrieving all sample sources"); } finally { ida.close(); } return createMethods; } /** * * @return all source sample IDs */ public List<String> getAllSourceSampleIds() throws Exception { List<String> sourceSampleIds = new ArrayList<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct sample.sourceSampleId from Sample sample order by sample.sourceSampleId"; List results = ida.search(hqlString); for (Object obj : results) { sourceSampleIds.add((String) obj); } } catch (Exception e) { logger.error("Error in retrieving all source sample IDs", e); throw new RuntimeException( "Error in retrieving all source sample IDs"); } finally { ida.close(); } return sourceSampleIds; } public Map<String, SortedSet<String>> getAllParticleTypeParticles() throws Exception { // TODO fill in actual database query. Map<String, SortedSet<String>> particleTypeParticles = new HashMap<String, SortedSet<String>>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); UserService userService = new UserService( CaNanoLabConstants.CSM_APP_NAME); try { ida.open(); // String hqlString = "select particle.type, particle.name from // Nanoparticle particle"; String hqlString = "select particle.type, particle.name from Nanoparticle particle where size(particle.characterizationCollection) = 0"; List results = ida.search(hqlString); SortedSet<String> particleNames = null; for (Object obj : results) { Object[] objArray = (Object[]) obj; String particleType = (String) objArray[0]; String particleName = (String) objArray[1]; if (particleType != null) { // check if the particle already has visibility group // assigned, if yes, do NOT add to the list List<String> groups = userService.getAccessibleGroups( particleName, CaNanoLabConstants.CSM_READ_ROLE); if (groups.size() == 0) { if (particleTypeParticles.get(particleType) != null) { particleNames = (SortedSet<String>) particleTypeParticles .get(particleType); } else { particleNames = new TreeSet<String>( new CaNanoLabComparators.SortableNameComparator()); particleTypeParticles.put(particleType, particleNames); } particleNames.add(particleName); } } } } catch (Exception e) { logger .error("Error in retrieving all particle type particles. ", e); throw new RuntimeException( "Error in retrieving all particle type particles. "); } finally { ida.close(); } return particleTypeParticles; } public String[] getAllDendrimerCores() { String[] cores = new String[] { "Diamine", "Ethyline" }; return cores; } public String[] getAllDendrimerSurfaceGroupNames() throws Exception { SortedSet<String> names = new TreeSet<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct surfaceGroup.name from SurfaceGroup surfaceGroup where surfaceGroup.name is not null"; List results = ida.search(hqlString); for (Object obj : results) { names.add((String) obj); } } catch (Exception e) { logger.error("Problem to retrieve all Surface Group name."); throw new RuntimeException( "Problem to retrieve all Surface Group name. "); } finally { ida.close(); } names.addAll(Arrays .asList(CaNanoLabConstants.DEFAULT_SURFACE_GROUP_NAMES)); return (String[]) names.toArray(new String[0]); } public String[] getAllDendrimerBranches() throws Exception { SortedSet<String> branches = new TreeSet<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct dendrimer.branch from DendrimerComposition dendrimer where dendrimer.branch is not null"; List results = ida.search(hqlString); for (Object obj : results) { branches.add((String) obj); } } catch (Exception e) { logger.error("Problem to retrieve all Dendrimer Branches."); throw new RuntimeException( "Problem to retrieve all Dendrimer Branches. "); } finally { ida.close(); } branches.addAll(Arrays .asList(CaNanoLabConstants.DEFAULT_DENDRIMER_BRANCHES)); return (String[]) branches.toArray(new String[0]); } public String[] getAllDendrimerGenerations() throws Exception { SortedSet<String> generations = new TreeSet<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct dendrimer.generation from DendrimerComposition dendrimer where dendrimer.generation is not null "; List results = ida.search(hqlString); for (Object obj : results) { generations.add(obj.toString()); } } catch (Exception e) { logger.error("Problem to retrieve all Dendrimer Generations."); throw new RuntimeException( "Problem to retrieve all Dendrimer Generations. "); } finally { ida.close(); } generations.addAll(Arrays .asList(CaNanoLabConstants.DEFAULT_DENDRIMER_GENERATIONS)); return (String[]) generations.toArray(new String[0]); } public String[] getAllMetalCompositions() { String[] compositions = new String[] { "Gold", "Sliver", "Iron oxide" }; return compositions; } public String[] getAllPolymerInitiators() throws Exception { SortedSet<String> initiators = new TreeSet<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct polymer.initiator from PolymerComposition polymer where polymer.initiator is not null "; List results = ida.search(hqlString); for (Object obj : results) { initiators.add((String) obj); } } catch (Exception e) { logger.error("Problem to retrieve all Polymer Initiator."); throw new RuntimeException( "Problem to retrieve all Polymer Initiator. "); } finally { ida.close(); } initiators.addAll(Arrays .asList(CaNanoLabConstants.DEFAULT_POLYMER_INITIATORS)); return (String[]) initiators.toArray(new String[0]); } public List<String> getAllParticleSources() throws Exception { // TODO fill in db code return getAllSampleSources(); } public String getParticleClassification(String particleType) { String classification = CaNanoLabConstants.PARTICLE_CLASSIFICATION_MAP .get(particleType); return classification; } /** * * @return a map between a characterization type and its child * characterizations. */ public Map<String, List<String>> getCharacterizationTypeCharacterizations() throws Exception { Map<String, List<String>> charTypeChars = new HashMap<String, List<String>>(); HibernateDataAccess hda = HibernateDataAccess.getInstance(); try { hda.open(); List<String> chars = null; String query = "select distinct a.category, a.name from characterization_category a " + "where a.name not in (select distinct b.category from characterization_category b) " + "order by a.category, a.name"; SQLQuery queryObj = hda.getNativeQuery(query); queryObj.addScalar("CATEGORY", Hibernate.STRING); queryObj.addScalar("NAME", Hibernate.STRING); List results = queryObj.list(); for (Object obj : results) { Object[] objarr = (Object[]) obj; String type = objarr[0].toString(); String name = objarr[1].toString(); if (charTypeChars.get(type) != null) { chars = (List<String>) charTypeChars.get(type); } else { chars = new ArrayList<String>(); charTypeChars.put(type, chars); } chars.add(name); } } catch (Exception e) { logger .error("Problem to retrieve all characterization type characterizations. " + e); throw new RuntimeException( "Problem to retrieve all characteriztaion type characterizations. "); } finally { hda.close(); } return charTypeChars; } public List<LabelValueBean> getAllInstrumentTypeAbbrs() throws Exception { List<LabelValueBean> instrumentTypeAbbrs = new ArrayList<LabelValueBean>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct instrumentType.name, instrumentType.abbreviation from InstrumentType instrumentType where instrumentType.name is not null"; List results = ida.search(hqlString); for (Object obj : results) { if (obj != null) { Object[] objs = (Object[]) obj; String label = ""; if (objs[1] != null) { label = (String) objs[0] + "(" + objs[1] + ")"; } else { label = (String) objs[0]; } instrumentTypeAbbrs.add(new LabelValueBean(label, (String) objs[0])); } } } catch (Exception e) { logger.error("Problem to retrieve all instrumentTypes. " + e); throw new RuntimeException( "Problem to retrieve all intrument types. "); } finally { ida.close(); } instrumentTypeAbbrs.add(new LabelValueBean(CaNanoLabConstants.OTHER, CaNanoLabConstants.OTHER)); return instrumentTypeAbbrs; } public Map<String, SortedSet<String>> getAllInstrumentManufacturers() throws Exception { Map<String, SortedSet<String>> instrumentManufacturers = new HashMap<String, SortedSet<String>>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct instrumentType.name, manufacturer.name from InstrumentType instrumentType join instrumentType.manufacturerCollection manufacturer "; List results = ida.search(hqlString); SortedSet<String> manufacturers = null; for (Object obj : results) { String instrumentType = ((Object[]) obj)[0].toString(); String manufacturer = ((Object[]) obj)[1].toString(); if (instrumentManufacturers.get(instrumentType) != null) { manufacturers = (SortedSet<String>) instrumentManufacturers .get(instrumentType); } else { manufacturers = new TreeSet<String>(); instrumentManufacturers.put(instrumentType, manufacturers); } manufacturers.add(manufacturer); } List allResult = ida .search("select manufacturer.name from Manufacturer manufacturer where manufacturer.name is not null"); SortedSet<String> allManufacturers = null; allManufacturers = new TreeSet<String>(); for (Object obj : allResult) { String name = (String) obj; allManufacturers.add(name); } instrumentManufacturers.put(CaNanoLabConstants.OTHER, allManufacturers); } catch (Exception e) { logger .error("Problem to retrieve manufacturers for intrument types " + e); throw new RuntimeException( "Problem to retrieve manufacturers for intrument types."); } finally { ida.close(); } return instrumentManufacturers; } public String[] getAllMorphologyTypes() throws Exception { SortedSet<String> morphologyTypes = new TreeSet<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct morphology.type from Morphology morphology"; List results = ida.search(hqlString); for (Object obj : results) { morphologyTypes.add((String) obj); } } catch (Exception e) { logger.error("Problem to retrieve all morphology types."); throw new RuntimeException( "Problem to retrieve all morphology types."); } finally { ida.close(); } morphologyTypes.addAll(Arrays .asList(CaNanoLabConstants.DEFAULT_MORPHOLOGY_TYPES)); return (String[]) morphologyTypes.toArray(new String[0]); } public String[] getAllShapeTypes() throws Exception { SortedSet<String> shapeTypes = new TreeSet<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct shape.type from Shape shape where shape.type is not null"; List results = ida.search(hqlString); for (Object obj : results) { shapeTypes.add((String) obj); } } catch (Exception e) { logger.error("Problem to retrieve all shape types."); throw new RuntimeException("Problem to retrieve all shape types."); } finally { ida.close(); } shapeTypes .addAll(Arrays.asList(CaNanoLabConstants.DEFAULT_SHAPE_TYPES)); return (String[]) shapeTypes.toArray(new String[0]); } public Map<ProtocolBean, List<ProtocolFileBean>> getAllProtocolNameVersionByType( String type) throws Exception { Map<ProtocolBean, List<ProtocolFileBean>> nameVersions = new HashMap<ProtocolBean, List<ProtocolFileBean>>(); Map<Protocol, ProtocolBean> keyMap = new HashMap<Protocol, ProtocolBean>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select protocolFile, protocolFile.protocol from ProtocolFile protocolFile" + " where protocolFile.protocol.type = '" + type + "'"; List results = ida.search(hqlString); for (Object obj : results) { Object[] array = (Object[]) obj; Object key = null; Object value = null; for (int i = 0; i < array.length; i++) { if (array[i] instanceof Protocol) { key = array[i]; } else if (array[i] instanceof ProtocolFile) { value = array[i]; } } if (keyMap.containsKey((Protocol) key)) { ProtocolBean pb = keyMap.get((Protocol) key); List<ProtocolFileBean> localList = nameVersions.get(pb); ProtocolFileBean fb = new ProtocolFileBean(); fb.setVersion(((ProtocolFile) value).getVersion()); fb.setId(((ProtocolFile) value).getId().toString()); localList.add(fb); } else { List<ProtocolFileBean> localList = new ArrayList<ProtocolFileBean>(); ProtocolFileBean fb = new ProtocolFileBean(); fb.setVersion(((ProtocolFile) value).getVersion()); fb.setId(((ProtocolFile) value).getId().toString()); localList.add(fb); ProtocolBean protocolBean = new ProtocolBean(); Protocol protocol = (Protocol) key; protocolBean.setId(protocol.getId().toString()); protocolBean.setName(protocol.getName()); protocolBean.setType(protocol.getType()); nameVersions.put(protocolBean, localList); keyMap.put((Protocol) key, protocolBean); } } } catch (Exception e) { logger .error("Problem to retrieve all protocol names and their versions by type " + type); throw new RuntimeException( "Problem to retrieve all protocol names and their versions by type " + type); } finally { ida.close(); } return nameVersions; } public SortedSet<String> getAllProtocolTypes() throws Exception { SortedSet<String> protocolTypes = new TreeSet<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct protocol.type from Protocol protocol where protocol.type is not null"; List results = ida.search(hqlString); for (Object obj : results) { protocolTypes.add((String) obj); } } catch (Exception e) { logger.error("Problem to retrieve all protocol types."); throw new RuntimeException( "Problem to retrieve all protocol types."); } finally { ida.close(); } return protocolTypes; } public SortedSet<ProtocolBean> getAllProtocols(UserBean user) throws Exception { SortedSet<ProtocolBean> protocolBeans = new TreeSet<ProtocolBean>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "from Protocol as protocol left join fetch protocol.protocolFileCollection"; List results = ida.search(hqlString); for (Object obj : results) { Protocol p = (Protocol) obj; ProtocolBean pb = new ProtocolBean(); pb.setId(p.getId().toString()); pb.setName(p.getName()); pb.setType(p.getType()); PersistentSet set = (PersistentSet) p .getProtocolFileCollection(); // HashSet hashSet = set. if (!set.isEmpty()) { List<ProtocolFileBean> list = new ArrayList<ProtocolFileBean>(); for (Iterator it = set.iterator(); it.hasNext();) { ProtocolFile pf = (ProtocolFile) it.next(); ProtocolFileBean pfb = new ProtocolFileBean(); pfb.setId(pf.getId().toString()); pfb.setVersion(pf.getVersion()); list.add(pfb); } pb.setFileBeanList(filterProtocols(list, user)); } if (!pb.getFileBeanList().isEmpty()) protocolBeans.add(pb); } } catch (Exception e) { logger.error("Problem to retrieve all protocol names and types."); throw new RuntimeException( "Problem to retrieve all protocol names and types."); } finally { ida.close(); } return protocolBeans; } private List<ProtocolFileBean> filterProtocols( List<ProtocolFileBean> protocolFiles, UserBean user) throws Exception { UserService userService = new UserService( CaNanoLabConstants.CSM_APP_NAME); List<LabFileBean> tempList = new ArrayList<LabFileBean>(); for (ProtocolFileBean pfb : protocolFiles) { tempList.add((LabFileBean) pfb); } List<LabFileBean> filteredProtocols = userService.getFilteredFiles( user, tempList); protocolFiles.clear(); if (filteredProtocols == null || filteredProtocols.isEmpty()) return protocolFiles; for (LabFileBean lfb : filteredProtocols) { protocolFiles.add((ProtocolFileBean) lfb); } return protocolFiles; } public String[] getAllStressorTypes() { String[] stressorTypes = new String[] { "Thermal", "PH", "Freeze thaw", "Photo", "Centrifugation", "Lyophilization", "Chemical", "Other" }; return stressorTypes; } public String[] getAllAreaMeasureUnits() { String[] areaUnit = new String[] { "sq nm" }; return areaUnit; } public String[] getAllChargeMeasureUnits() { String[] chargeUnit = new String[] { "a.u", "aC", "Ah", "C", "esu", "Fr", "statC" }; return chargeUnit; } public String[] getAllDensityMeasureUnits() { String[] densityUnits = new String[] { "kg/L" }; return densityUnits; } public String[] getAllControlTypes() { String[] controlTypes = new String[] { " ", "Positive", "Negative" }; return controlTypes; } public String[] getAllConditionTypes() { String[] conditionTypes = new String[] { "Particle Concentration", "Temperature", "Time" }; return conditionTypes; } public Map<String, String[]> getAllAgentTypes() { Map<String, String[]> agentTypes = new HashMap<String, String[]>(); String[] therapeuticsAgentTypes = new String[] { "Peptide", "Small Molecule", "Antibody", "DNA", "Probe", "Image Contrast Agent", "Other" }; agentTypes.put("Therapeutic", therapeuticsAgentTypes); String[] targetingAgentTypes = new String[] { "Peptide", "Small Molecule", "Antibody", "DNA", "Probe", "Image Contrast Agent", "Other" }; agentTypes.put("Targeting", targetingAgentTypes); String[] imagingAgentTypes = new String[] { "Peptide", "Small Molecule", "Antibody", "DNA", "Probe", "Image Contrast Agent", "Other" }; agentTypes.put("Imaging", imagingAgentTypes); String[] reportingAgentTypes = new String[] { "Peptide", "Small Molecule", "Antibody", "DNA", "Probe", "Image Contrast Agent", "Other" }; agentTypes.put("Reporting", reportingAgentTypes); return agentTypes; } public Map<String, String[]> getAllAgentTargetTypes() { Map<String, String[]> agentTargetTypes = new HashMap<String, String[]>(); String[] targetTypes = new String[] { "Receptor", "Antigen", "Other" }; String[] targetTypes1 = new String[] { "Receptor", "Other" }; String[] targetTypes2 = new String[] { "Other" }; agentTargetTypes.put("Small Molecule", targetTypes2); agentTargetTypes.put("Peptide", targetTypes1); agentTargetTypes.put("Antibody", targetTypes); agentTargetTypes.put("DNA", targetTypes1); agentTargetTypes.put("Probe", targetTypes1); agentTargetTypes.put("Other", targetTypes2); agentTargetTypes.put("Image Contrast Agent", targetTypes2); return agentTargetTypes; } public String[] getAllTimeUnits() { String[] timeUnits = new String[] { "hours", "days", "months" }; return timeUnits; } public String[] getAllTemperatureUnits() { String[] temperatureUnits = new String[] { "degrees celsius", "degrees fahrenhiet" }; return temperatureUnits; } public String[] getAllConcentrationUnits() { String[] concentrationUnits = new String[] { "g/ml", "mg/ml", "pg/ml", "ug/ml", "ug/ul" }; return concentrationUnits; } public Map<String, String[]> getAllConditionUnits() { Map<String, String[]> conditionTypeUnits = new HashMap<String, String[]>(); String[] concentrationUnits = new String[] { "g/ml", "mg/ml", "pg/ml", "ug/ml", "ug/ul", }; String[] temperatureUnits = new String[] { "degrees celsius", "degrees fahrenhiet" }; String[] timeUnits = new String[] { "hours", "days", "months" }; conditionTypeUnits.put("Particle Concentration", concentrationUnits); conditionTypeUnits.put("Time", timeUnits); conditionTypeUnits.put("Temperature", temperatureUnits); return conditionTypeUnits; } public String[] getAllCellLines() throws Exception { SortedSet<String> cellLines = new TreeSet<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct cellViability.cellLine, caspase.cellLine from CellViability cellViability, Caspase3Activation caspase"; List results = ida.search(hqlString); for (Object obj : results) { // cellLines.add((String) obj); Object[] objects = (Object[]) obj; for (Object object : objects) { if (object != null) { cellLines.add((String) object); } } } } catch (Exception e) { logger.error("Problem to retrieve all Cell lines."); throw new RuntimeException("Problem to retrieve all Cell lines."); } finally { ida.close(); } cellLines.addAll(Arrays.asList(CaNanoLabConstants.DEFAULT_CELLLINES)); return (String[]) cellLines.toArray(new String[0]); } public String[] getAllActivationMethods() { String[] activationMethods = new String[] { "NMR", "MRI", "Radiation", "Ultrasound", "Ultraviolet Light" }; return activationMethods; } public List<LabelValueBean> getAllSpecies() throws Exception { List<LabelValueBean> species = new ArrayList<LabelValueBean>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); species.add(new LabelValueBean("", "")); try { for (int i = 0; i < CaNanoLabConstants.SPECIES_COMMON.length; i++) { String specie = CaNanoLabConstants.SPECIES_COMMON[i]; species.add(new LabelValueBean(specie, specie)); } } catch (Exception e) { logger.error("Problem to retrieve all species. " + e); throw new RuntimeException( "Problem to retrieve all intrument types. "); } finally { ida.close(); } return species; } public String[] getAllReportTypes() { String[] allReportTypes = new String[] { CaNanoLabConstants.REPORT, CaNanoLabConstants.ASSOCIATED_FILE }; return allReportTypes; } /** * Get other particles from the given particle source * * @param particleSource * @param particleName * @param user * @return * @throws Exception */ public SortedSet<String> getOtherParticles(String particleSource, String particleName, UserBean user) throws Exception { IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); UserService userService = new UserService( CaNanoLabConstants.CSM_APP_NAME); SortedSet<String> otherParticleNames = new TreeSet<String>(); try { ida.open(); String hqlString = "select particle.name from Nanoparticle particle where particle.source.organizationName='" + particleSource + "' and particle.name !='" + particleName + "'"; List results = ida.search(hqlString); for (Object obj : results) { String otherParticleName = (String) obj; // check if user can see the particle boolean status = userService.checkReadPermission(user, otherParticleName); if (status) { otherParticleNames.add(otherParticleName); } } } catch (Exception e) { logger .error("Error in retrieving all particle type particles. ", e); throw new RuntimeException( "Error in retrieving all particle type particles. "); } finally { ida.close(); } return otherParticleNames; } public List<InstrumentBean> getAllInstruments() throws Exception { List<InstrumentBean> instruments = new ArrayList<InstrumentBean>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "from Instrument instrument where instrument.type is not null and instrument.manufacturer is not null order by instrument.type"; List results = ida.search(hqlString); for (Object obj : results) { Instrument instrument = (Instrument) obj; instruments.add(new InstrumentBean(instrument)); } } catch (Exception e) { logger.error("Problem to retrieve all instruments. " + e); throw new RuntimeException("Problem to retrieve all intruments. "); } finally { ida.close(); } return instruments; } public List<String> getAllDerivedDataFileTypes() throws Exception { List<String> fileTypes = new ArrayList<String>(); // TODO query from database fileTypes.addAll(Arrays .asList(CaNanoLabConstants.DEFAULT_DERIVED_DATA_FILE_TYPES)); return fileTypes; } public Map<String, List<String>> getAllDerivedDataCategories() throws Exception { Map<String, List<String>> categoryMap = new HashMap<String, List<String>>(); // TODO query from database List<String> categories = new ArrayList<String>(); categories.add("Volume Distribution"); categories.add("Intensity Distribution"); categories.add("Number Distribution"); categoryMap.put("Size", categories); return categoryMap; } public List<String> getAllFunctionTypes() throws Exception { List<String> types = new ArrayList<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select funcType.name from FunctionType funcType order by funcType.name"; List results = ida.search(hqlString); for (Object obj : results) { String type = (String) obj; types.add(type); } } catch (Exception e) { logger.error("Problem to retrieve all function types. " + e); throw new RuntimeException( "Problem to retrieve all function types. "); } finally { ida.close(); } return types; } public List<CharacterizationTypeBean> getAllCharacterizationTypes() throws Exception { List<CharacterizationTypeBean> charTypes = new ArrayList<CharacterizationTypeBean>(); HibernateDataAccess hda = HibernateDataAccess.getInstance(); try { hda.open(); String query = "select distinct category, has_action, indent_level, category_order from characterization_category order by category_order"; SQLQuery queryObj = hda.getNativeQuery(query); queryObj.addScalar("CATEGORY", Hibernate.STRING); queryObj.addScalar("HAS_ACTION", Hibernate.INTEGER); queryObj.addScalar("INDENT_LEVEL", Hibernate.INTEGER); queryObj.addScalar("CATEGORY_ORDER", Hibernate.INTEGER); List results = queryObj.list(); for (Object obj : results) { Object[] objarr = (Object[]) obj; String type = objarr[0].toString(); boolean hasAction = ((Integer) objarr[1] == 0) ? false : true; int indentLevel = (Integer) objarr[2]; CharacterizationTypeBean charType = new CharacterizationTypeBean( type, indentLevel, hasAction); charTypes.add(charType); } } catch (Exception e) { logger .error("Problem to retrieve all characterization types. " + e); throw new RuntimeException( "Problem to retrieve all characteriztaion types. "); } finally { hda.close(); } return charTypes; } public Map<String, SortedSet<String>> getDerivedDataCategoryMap( String characterizationName) throws Exception { Map<String, SortedSet<String>> categoryMap = new HashMap<String, SortedSet<String>>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select category.name, datumName.name from DerivedBioAssayDataCategory category left join category.datumNameCollection datumName where datumName.datumParsed=false and category.characterizationName='" + characterizationName + "'"; List results = ida.search(hqlString); SortedSet<String> datumNames = null; for (Object obj : results) { String categoryName = ((Object[]) obj)[0].toString(); String datumName = ((Object[]) obj)[1].toString(); if (categoryMap.get(categoryName) != null) { datumNames = categoryMap.get(categoryName); } else { datumNames = new TreeSet<String>(); categoryMap.put(categoryName, datumNames); } datumNames.add(datumName); } } catch (Exception e) { logger .error("Problem to retrieve all derived bioassay data categories. " + e); throw new RuntimeException( "Problem to retrieve all derived bioassay data categories."); } finally { ida.close(); } return categoryMap; } }
src/gov/nih/nci/calab/service/common/LookupService.java
package gov.nih.nci.calab.service.common; import gov.nih.nci.calab.db.DataAccessProxy; import gov.nih.nci.calab.db.HibernateDataAccess; import gov.nih.nci.calab.db.IDataAccess; import gov.nih.nci.calab.domain.Aliquot; import gov.nih.nci.calab.domain.Instrument; import gov.nih.nci.calab.domain.MeasureUnit; import gov.nih.nci.calab.domain.Protocol; import gov.nih.nci.calab.domain.ProtocolFile; import gov.nih.nci.calab.domain.Sample; import gov.nih.nci.calab.domain.SampleContainer; import gov.nih.nci.calab.domain.StorageElement; import gov.nih.nci.calab.dto.characterization.CharacterizationTypeBean; import gov.nih.nci.calab.dto.common.InstrumentBean; import gov.nih.nci.calab.dto.common.LabFileBean; import gov.nih.nci.calab.dto.common.ProtocolBean; import gov.nih.nci.calab.dto.common.ProtocolFileBean; import gov.nih.nci.calab.dto.common.UserBean; import gov.nih.nci.calab.dto.inventory.AliquotBean; import gov.nih.nci.calab.dto.inventory.ContainerBean; import gov.nih.nci.calab.dto.inventory.ContainerInfoBean; import gov.nih.nci.calab.dto.inventory.SampleBean; import gov.nih.nci.calab.dto.workflow.AssayBean; import gov.nih.nci.calab.service.security.UserService; import gov.nih.nci.calab.service.util.CaNanoLabComparators; import gov.nih.nci.calab.service.util.CaNanoLabConstants; import gov.nih.nci.calab.service.util.StringUtils; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.SortedSet; import java.util.TreeSet; import org.apache.log4j.Logger; import org.apache.struts.util.LabelValueBean; import org.hibernate.Hibernate; import org.hibernate.SQLQuery; import org.hibernate.collection.PersistentSet; /** * The service to return prepopulated data that are shared across different * views. * * @author zengje * */ /* CVS $Id: LookupService.java,v 1.111 2007-06-19 20:12:53 pansu Exp $ */ public class LookupService { private static Logger logger = Logger.getLogger(LookupService.class); /** * Retrieving all unmasked aliquots for use in views create run, use aliquot * and create aliquot. * * @return a Map between sample name and its associated unmasked aliquots * @throws Exception */ public Map<String, SortedSet<AliquotBean>> getUnmaskedSampleAliquots() throws Exception { SortedSet<AliquotBean> aliquots = null; IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); Map<String, SortedSet<AliquotBean>> sampleAliquots = new HashMap<String, SortedSet<AliquotBean>>(); try { ida.open(); String hqlString = "select aliquot.id, aliquot.name, aliquot.sample.name from Aliquot aliquot where aliquot.dataStatus is null order by aliquot.name"; List results = ida.search(hqlString); for (Object obj : results) { Object[] info = (Object[]) obj; AliquotBean aliquot = new AliquotBean(StringUtils .convertToString(info[0]), StringUtils .convertToString(info[1]), CaNanoLabConstants.ACTIVE_STATUS); String sampleName = (String) info[2]; if (sampleAliquots.get(sampleName) != null) { aliquots = (SortedSet<AliquotBean>) sampleAliquots .get(sampleName); } else { aliquots = new TreeSet<AliquotBean>( new CaNanoLabComparators.AliquotBeanComparator()); sampleAliquots.put(sampleName, aliquots); } aliquots.add(aliquot); } } catch (Exception e) { logger.error("Error in retrieving all aliquot Ids and names", e); throw new RuntimeException( "Error in retrieving all aliquot Ids and names"); } finally { ida.close(); } return sampleAliquots; } /** * * @return a map between sample name and its sample containers * @throws Exception */ public Map<String, SortedSet<ContainerBean>> getAllSampleContainers() throws Exception { SortedSet<ContainerBean> containers = null; IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); Map<String, SortedSet<ContainerBean>> sampleContainers = new HashMap<String, SortedSet<ContainerBean>>(); try { ida.open(); String hqlString = "select container, container.sample.name from SampleContainer container"; List results = ida.search(hqlString); for (Object obj : results) { Object[] info = (Object[]) obj; if (!(info[0] instanceof Aliquot)) { ContainerBean container = new ContainerBean( (SampleContainer) info[0]); String sampleName = (String) info[1]; if (sampleContainers.get(sampleName) != null) { containers = (SortedSet<ContainerBean>) sampleContainers .get(sampleName); } else { containers = new TreeSet<ContainerBean>( new CaNanoLabComparators.ContainerBeanComparator()); sampleContainers.put(sampleName, containers); } containers.add(container); } } } catch (Exception e) { logger.error("Error in retrieving all containers", e); throw new RuntimeException("Error in retrieving all containers"); } finally { ida.close(); } return sampleContainers; } /** * Retrieving all sample types. * * @return a list of all sample types */ public List<String> getAllSampleTypes() throws Exception { // Detail here // Retrieve data from Sample_Type table List<String> sampleTypes = new ArrayList<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select sampleType.name from SampleType sampleType order by sampleType.name"; List results = ida.search(hqlString); for (Object obj : results) { sampleTypes.add((String) obj); } } catch (Exception e) { logger.error("Error in retrieving all sample types", e); throw new RuntimeException("Error in retrieving all sample types"); } finally { ida.close(); } return sampleTypes; } /** * * @return the default sample container information in a form of * ContainerInfoBean */ public ContainerInfoBean getSampleContainerInfo() throws Exception { List<MeasureUnit> units = getAllMeasureUnits(); List<StorageElement> storageElements = getAllStorageElements(); List<String> quantityUnits = new ArrayList<String>(); List<String> concentrationUnits = new ArrayList<String>(); List<String> volumeUnits = new ArrayList<String>(); List<String> rooms = new ArrayList<String>(); List<String> freezers = new ArrayList<String>(); List<String> shelves = new ArrayList<String>(); List<String> boxes = new ArrayList<String>(); for (MeasureUnit unit : units) { if (unit.getType().equalsIgnoreCase("Quantity")) { quantityUnits.add(unit.getName()); } else if (unit.getType().equalsIgnoreCase("Volume")) { volumeUnits.add(unit.getName()); } else if (unit.getType().equalsIgnoreCase("Concentration")) { concentrationUnits.add(unit.getName()); } } for (StorageElement storageElement : storageElements) { if (storageElement.getType().equalsIgnoreCase("Room") && !rooms.contains(storageElement.getLocation())) { rooms.add((storageElement.getLocation())); } else if (storageElement.getType().equalsIgnoreCase("Freezer") && !freezers.contains(storageElement.getLocation())) { freezers.add((storageElement.getLocation())); } else if (storageElement.getType().equalsIgnoreCase("Shelf") && !shelves.contains(storageElement.getLocation())) { shelves.add((storageElement.getLocation())); } else if (storageElement.getType().equalsIgnoreCase("Box") && !boxes.contains(storageElement.getLocation())) { boxes.add((storageElement.getLocation())); } } // set labs and racks to null for now ContainerInfoBean containerInfo = new ContainerInfoBean(quantityUnits, concentrationUnits, volumeUnits, null, rooms, freezers, shelves, boxes); return containerInfo; } public List<String> getAllSampleContainerTypes() throws Exception { SortedSet<String> containerTypes = new TreeSet<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct container.containerType from SampleContainer container order by container.containerType"; List results = ida.search(hqlString); for (Object obj : results) { containerTypes.add((String) obj); } } catch (Exception e) { logger.error("Error in retrieving all sample container types", e); throw new RuntimeException( "Error in retrieving all sample container types."); } finally { ida.close(); } containerTypes.addAll(Arrays .asList(CaNanoLabConstants.DEFAULT_CONTAINER_TYPES)); List<String> containerTypeList = new ArrayList<String>(containerTypes); return containerTypeList; } public List<String> getAllAliquotContainerTypes() throws Exception { SortedSet<String> containerTypes = new TreeSet<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct aliquot.containerType from Aliquot aliquot order by aliquot.containerType"; List results = ida.search(hqlString); for (Object obj : results) { containerTypes.add((String) obj); } } catch (Exception e) { logger.error("Error in retrieving all aliquot container types", e); throw new RuntimeException( "Error in retrieving all aliquot container types."); } finally { ida.close(); } containerTypes.addAll(Arrays .asList(CaNanoLabConstants.DEFAULT_CONTAINER_TYPES)); List<String> containerTypeList = new ArrayList<String>(containerTypes); return containerTypeList; } private List<MeasureUnit> getAllMeasureUnits() throws Exception { List<MeasureUnit> units = new ArrayList<MeasureUnit>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "from MeasureUnit"; List results = ida.search(hqlString); for (Object obj : results) { units.add((MeasureUnit) obj); } } catch (Exception e) { logger.error("Error in retrieving all measure units", e); throw new RuntimeException("Error in retrieving all measure units."); } finally { ida.close(); } return units; } private List<StorageElement> getAllStorageElements() throws Exception { List<StorageElement> storageElements = new ArrayList<StorageElement>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "from StorageElement where type in ('Room', 'Freezer', 'Shelf', 'Box') and location!='Other'"; List results = ida.search(hqlString); for (Object obj : results) { storageElements.add((StorageElement) obj); } } catch (Exception e) { logger.error("Error in retrieving all rooms and freezers", e); throw new RuntimeException( "Error in retrieving all rooms and freezers."); } finally { ida.close(); } return storageElements; } /** * * @return the default sample container information in a form of * ContainerInfoBean */ public ContainerInfoBean getAliquotContainerInfo() throws Exception { return getSampleContainerInfo(); } /** * Get all samples in the database * * @return a list of SampleBean containing sample Ids and names DELETE */ public List<SampleBean> getAllSamples() throws Exception { List<SampleBean> samples = new ArrayList<SampleBean>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select sample.id, sample.name from Sample sample"; List results = ida.search(hqlString); for (Object obj : results) { Object[] sampleInfo = (Object[]) obj; samples.add(new SampleBean(StringUtils .convertToString(sampleInfo[0]), StringUtils .convertToString(sampleInfo[1]))); } } catch (Exception e) { logger.error("Error in retrieving all sample IDs and names", e); throw new RuntimeException( "Error in retrieving all sample IDs and names"); } finally { ida.close(); } Collections.sort(samples, new CaNanoLabComparators.SampleBeanComparator()); return samples; } /** * Retrieve all Assay Types from the system * * @return A list of all assay type */ public List getAllAssayTypes() throws Exception { List<String> assayTypes = new ArrayList<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select assayType.name from AssayType assayType order by assayType.executeOrder"; List results = ida.search(hqlString); for (Object obj : results) { assayTypes.add((String) obj); } } catch (Exception e) { logger.error("Error in retrieving all assay types", e); throw new RuntimeException("Error in retrieving all assay types"); } finally { ida.close(); } return assayTypes; } /** * * @return a map between assay type and its assays * @throws Exception */ public Map<String, SortedSet<AssayBean>> getAllAssayTypeAssays() throws Exception { Map<String, SortedSet<AssayBean>> assayTypeAssays = new HashMap<String, SortedSet<AssayBean>>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select assay.id, assay.name, assay.assayType from Assay assay"; List results = ida.search(hqlString); SortedSet<AssayBean> assays = null; for (Object obj : results) { Object[] objArray = (Object[]) obj; AssayBean assay = new AssayBean( ((Long) objArray[0]).toString(), (String) objArray[1], (String) objArray[2]); if (assayTypeAssays.get(assay.getAssayType()) != null) { assays = (SortedSet<AssayBean>) assayTypeAssays.get(assay .getAssayType()); } else { assays = new TreeSet<AssayBean>( new CaNanoLabComparators.AssayBeanComparator()); assayTypeAssays.put(assay.getAssayType(), assays); } assays.add(assay); } } catch (Exception e) { // TODO: temp for debuging use. remove later e.printStackTrace(); logger.error("Error in retrieving all assay beans. ", e); throw new RuntimeException("Error in retrieving all assays beans. "); } finally { ida.close(); } return assayTypeAssays; } /** * * @return all sample sources */ public List<String> getAllSampleSources() throws Exception { List<String> sampleSources = new ArrayList<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select source.organizationName from Source source order by source.organizationName"; List results = ida.search(hqlString); for (Object obj : results) { sampleSources.add((String) obj); } } catch (Exception e) { logger.error("Error in retrieving all sample sources", e); throw new RuntimeException("Error in retrieving all sample sources"); } finally { ida.close(); } return sampleSources; } /** * * @return a map between sample source and samples with unmasked aliquots * @throws Exception */ public Map<String, SortedSet<SampleBean>> getSampleSourceSamplesWithUnmaskedAliquots() throws Exception { Map<String, SortedSet<SampleBean>> sampleSourceSamples = new HashMap<String, SortedSet<SampleBean>>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct aliquot.sample from Aliquot aliquot where aliquot.dataStatus is null"; List results = ida.search(hqlString); SortedSet<SampleBean> samples = null; for (Object obj : results) { SampleBean sample = new SampleBean((Sample) obj); if (sampleSourceSamples.get(sample.getSampleSource()) != null) { // TODO need to make sample source a required field if (sample.getSampleSource().length() > 0) { samples = (SortedSet<SampleBean>) sampleSourceSamples .get(sample.getSampleSource()); } } else { samples = new TreeSet<SampleBean>( new CaNanoLabComparators.SampleBeanComparator()); if (sample.getSampleSource().length() > 0) { sampleSourceSamples.put(sample.getSampleSource(), samples); } } samples.add(sample); } } catch (Exception e) { logger.error( "Error in retrieving sample beans with unmasked aliquots ", e); throw new RuntimeException( "Error in retrieving all sample beans with unmasked aliquots. "); } finally { ida.close(); } return sampleSourceSamples; } public List<String> getAllSampleSOPs() throws Exception { List<String> sampleSOPs = new ArrayList<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select sampleSOP.name from SampleSOP sampleSOP where sampleSOP.description='sample creation'"; List results = ida.search(hqlString); for (Object obj : results) { sampleSOPs.add((String) obj); } } catch (Exception e) { logger.error("Problem to retrieve all Sample SOPs."); throw new RuntimeException("Problem to retrieve all Sample SOPs. "); } finally { ida.close(); } return sampleSOPs; } /** * * @return all methods for creating aliquots */ public List<LabelValueBean> getAliquotCreateMethods() throws Exception { List<LabelValueBean> createMethods = new ArrayList<LabelValueBean>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select sop.name, file.path from SampleSOP sop join sop.sampleSOPFileCollection file where sop.description='aliquot creation'"; List results = ida.search(hqlString); for (Object obj : results) { String sopName = (String) ((Object[]) obj)[0]; String sopURI = (String) ((Object[]) obj)[1]; String sopURL = (sopURI == null) ? "" : sopURI; createMethods.add(new LabelValueBean(sopName, sopURL)); } } catch (Exception e) { logger.error("Error in retrieving all sample sources", e); throw new RuntimeException("Error in retrieving all sample sources"); } finally { ida.close(); } return createMethods; } /** * * @return all source sample IDs */ public List<String> getAllSourceSampleIds() throws Exception { List<String> sourceSampleIds = new ArrayList<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct sample.sourceSampleId from Sample sample order by sample.sourceSampleId"; List results = ida.search(hqlString); for (Object obj : results) { sourceSampleIds.add((String) obj); } } catch (Exception e) { logger.error("Error in retrieving all source sample IDs", e); throw new RuntimeException( "Error in retrieving all source sample IDs"); } finally { ida.close(); } return sourceSampleIds; } public Map<String, SortedSet<String>> getAllParticleTypeParticles() throws Exception { // TODO fill in actual database query. Map<String, SortedSet<String>> particleTypeParticles = new HashMap<String, SortedSet<String>>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); UserService userService = new UserService( CaNanoLabConstants.CSM_APP_NAME); try { ida.open(); // String hqlString = "select particle.type, particle.name from // Nanoparticle particle"; String hqlString = "select particle.type, particle.name from Nanoparticle particle where size(particle.characterizationCollection) = 0"; List results = ida.search(hqlString); SortedSet<String> particleNames = null; for (Object obj : results) { Object[] objArray = (Object[]) obj; String particleType = (String) objArray[0]; String particleName = (String) objArray[1]; if (particleType != null) { // check if the particle already has visibility group // assigned, if yes, do NOT add to the list List<String> groups = userService.getAccessibleGroups( particleName, CaNanoLabConstants.CSM_READ_ROLE); if (groups.size() == 0) { if (particleTypeParticles.get(particleType) != null) { particleNames = (SortedSet<String>) particleTypeParticles .get(particleType); } else { particleNames = new TreeSet<String>( new CaNanoLabComparators.SortableNameComparator()); particleTypeParticles.put(particleType, particleNames); } particleNames.add(particleName); } } } } catch (Exception e) { logger .error("Error in retrieving all particle type particles. ", e); throw new RuntimeException( "Error in retrieving all particle type particles. "); } finally { ida.close(); } return particleTypeParticles; } public String[] getAllDendrimerCores() { String[] cores = new String[] { "Diamine", "Ethyline" }; return cores; } public String[] getAllDendrimerSurfaceGroupNames() throws Exception { SortedSet<String> names = new TreeSet<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct surfaceGroup.name from SurfaceGroup surfaceGroup where surfaceGroup.name is not null"; List results = ida.search(hqlString); for (Object obj : results) { names.add((String) obj); } } catch (Exception e) { logger.error("Problem to retrieve all Surface Group name."); throw new RuntimeException( "Problem to retrieve all Surface Group name. "); } finally { ida.close(); } names.addAll(Arrays .asList(CaNanoLabConstants.DEFAULT_SURFACE_GROUP_NAMES)); return (String[]) names.toArray(new String[0]); } public String[] getAllDendrimerBranches() throws Exception { SortedSet<String> branches = new TreeSet<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct dendrimer.branch from DendrimerComposition dendrimer where dendrimer.branch is not null"; List results = ida.search(hqlString); for (Object obj : results) { branches.add((String) obj); } } catch (Exception e) { logger.error("Problem to retrieve all Dendrimer Branches."); throw new RuntimeException( "Problem to retrieve all Dendrimer Branches. "); } finally { ida.close(); } branches.addAll(Arrays .asList(CaNanoLabConstants.DEFAULT_DENDRIMER_BRANCHES)); return (String[]) branches.toArray(new String[0]); } public String[] getAllDendrimerGenerations() throws Exception { SortedSet<String> generations = new TreeSet<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct dendrimer.generation from DendrimerComposition dendrimer where dendrimer.generation is not null "; List results = ida.search(hqlString); for (Object obj : results) { generations.add(obj.toString()); } } catch (Exception e) { logger.error("Problem to retrieve all Dendrimer Generations."); throw new RuntimeException( "Problem to retrieve all Dendrimer Generations. "); } finally { ida.close(); } generations.addAll(Arrays .asList(CaNanoLabConstants.DEFAULT_DENDRIMER_GENERATIONS)); return (String[]) generations.toArray(new String[0]); } public String[] getAllMetalCompositions() { String[] compositions = new String[] { "Gold", "Sliver", "Iron oxide" }; return compositions; } public String[] getAllPolymerInitiators() throws Exception { SortedSet<String> initiators = new TreeSet<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct polymer.initiator from PolymerComposition polymer where polymer.initiator is not null "; List results = ida.search(hqlString); for (Object obj : results) { initiators.add((String) obj); } } catch (Exception e) { logger.error("Problem to retrieve all Polymer Initiator."); throw new RuntimeException( "Problem to retrieve all Polymer Initiator. "); } finally { ida.close(); } initiators.addAll(Arrays .asList(CaNanoLabConstants.DEFAULT_POLYMER_INITIATORS)); return (String[]) initiators.toArray(new String[0]); } public List<String> getAllParticleSources() throws Exception { // TODO fill in db code return getAllSampleSources(); } public String getParticleClassification(String particleType) { String classification = CaNanoLabConstants.PARTICLE_CLASSIFICATION_MAP .get(particleType); return classification; } /** * * @return a map between a characterization type and its child * characterizations. */ public Map<String, List<String>> getCharacterizationTypeCharacterizations() throws Exception { Map<String, List<String>> charTypeChars = new HashMap<String, List<String>>(); HibernateDataAccess hda = HibernateDataAccess.getInstance(); try { hda.open(); List<String> chars = null; String query = "select distinct a.category, a.name from characterization_category a " + "where a.name not in (select distinct b.category from characterization_category b) " + "order by a.category, a.name"; SQLQuery queryObj = hda.getNativeQuery(query); queryObj.addScalar("CATEGORY", Hibernate.STRING); queryObj.addScalar("NAME", Hibernate.STRING); List results = queryObj.list(); for (Object obj : results) { Object[] objarr = (Object[]) obj; String type = objarr[0].toString(); String name = objarr[1].toString(); if (charTypeChars.get(type) != null) { chars = (List<String>) charTypeChars.get(type); } else { chars = new ArrayList<String>(); charTypeChars.put(type, chars); } chars.add(name); } } catch (Exception e) { logger .error("Problem to retrieve all characterization type characterizations. " + e); throw new RuntimeException( "Problem to retrieve all characteriztaion type characterizations. "); } finally { hda.close(); } return charTypeChars; } public List<LabelValueBean> getAllInstrumentTypeAbbrs() throws Exception { List<LabelValueBean> instrumentTypeAbbrs = new ArrayList<LabelValueBean>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct instrumentType.name, instrumentType.abbreviation from InstrumentType instrumentType where instrumentType.name is not null"; List results = ida.search(hqlString); for (Object obj : results) { if (obj != null) { Object[] objs = (Object[]) obj; String label = ""; if (objs[1] != null) { label = (String) objs[0] + "(" + objs[1] + ")"; } else { label = (String) objs[0]; } instrumentTypeAbbrs.add(new LabelValueBean(label, (String) objs[0])); } } } catch (Exception e) { logger.error("Problem to retrieve all instrumentTypes. " + e); throw new RuntimeException( "Problem to retrieve all intrument types. "); } finally { ida.close(); } instrumentTypeAbbrs.add(new LabelValueBean(CaNanoLabConstants.OTHER, CaNanoLabConstants.OTHER)); return instrumentTypeAbbrs; } public Map<String, SortedSet<String>> getAllInstrumentManufacturers() throws Exception { Map<String, SortedSet<String>> instrumentManufacturers = new HashMap<String, SortedSet<String>>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct instrumentType.name, manufacturer.name from InstrumentType instrumentType join instrumentType.manufacturerCollection manufacturer "; List results = ida.search(hqlString); SortedSet<String> manufacturers = null; for (Object obj : results) { String instrumentType = ((Object[]) obj)[0].toString(); String manufacturer = ((Object[]) obj)[1].toString(); if (instrumentManufacturers.get(instrumentType) != null) { manufacturers = (SortedSet<String>) instrumentManufacturers .get(instrumentType); } else { manufacturers = new TreeSet<String>(); instrumentManufacturers.put(instrumentType, manufacturers); } manufacturers.add(manufacturer); } List allResult = ida .search("select manufacturer.name from Manufacturer manufacturer where manufacturer.name is not null"); SortedSet<String> allManufacturers = null; allManufacturers = new TreeSet<String>(); for (Object obj : allResult) { String name = (String) obj; allManufacturers.add(name); } instrumentManufacturers.put(CaNanoLabConstants.OTHER, allManufacturers); } catch (Exception e) { logger .error("Problem to retrieve manufacturers for intrument types " + e); throw new RuntimeException( "Problem to retrieve manufacturers for intrument types."); } finally { ida.close(); } return instrumentManufacturers; } public String[] getAllMorphologyTypes() throws Exception { SortedSet<String> morphologyTypes = new TreeSet<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct morphology.type from Morphology morphology"; List results = ida.search(hqlString); for (Object obj : results) { morphologyTypes.add((String) obj); } } catch (Exception e) { logger.error("Problem to retrieve all morphology types."); throw new RuntimeException( "Problem to retrieve all morphology types."); } finally { ida.close(); } morphologyTypes.addAll(Arrays .asList(CaNanoLabConstants.DEFAULT_MORPHOLOGY_TYPES)); return (String[]) morphologyTypes.toArray(new String[0]); } public String[] getAllShapeTypes() throws Exception { SortedSet<String> shapeTypes = new TreeSet<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct shape.type from Shape shape where shape.type is not null"; List results = ida.search(hqlString); for (Object obj : results) { shapeTypes.add((String) obj); } } catch (Exception e) { logger.error("Problem to retrieve all shape types."); throw new RuntimeException("Problem to retrieve all shape types."); } finally { ida.close(); } shapeTypes .addAll(Arrays.asList(CaNanoLabConstants.DEFAULT_SHAPE_TYPES)); return (String[]) shapeTypes.toArray(new String[0]); } public Map<ProtocolBean, List<ProtocolFileBean>> getAllProtocolNameVersionByType( String type) throws Exception { Map<ProtocolBean, List<ProtocolFileBean>> nameVersions = new HashMap<ProtocolBean, List<ProtocolFileBean>>(); Map<Protocol, ProtocolBean> keyMap = new HashMap<Protocol, ProtocolBean>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select protocolFile, protocolFile.protocol from ProtocolFile protocolFile" + " where protocolFile.protocol.type = '" + type + "'"; List results = ida.search(hqlString); for (Object obj : results) { Object[] array = (Object[]) obj; Object key = null; Object value = null; for (int i = 0; i < array.length; i++) { if (array[i] instanceof Protocol) { key = array[i]; } else if (array[i] instanceof ProtocolFile) { value = array[i]; } } if (keyMap.containsKey((Protocol) key)) { ProtocolBean pb = keyMap.get((Protocol) key); List<ProtocolFileBean> localList = nameVersions.get(pb); ProtocolFileBean fb = new ProtocolFileBean(); fb.setVersion(((ProtocolFile) value).getVersion()); fb.setId(((ProtocolFile) value).getId().toString()); localList.add(fb); } else { List<ProtocolFileBean> localList = new ArrayList<ProtocolFileBean>(); ProtocolFileBean fb = new ProtocolFileBean(); fb.setVersion(((ProtocolFile) value).getVersion()); fb.setId(((ProtocolFile) value).getId().toString()); localList.add(fb); ProtocolBean protocolBean = new ProtocolBean(); Protocol protocol = (Protocol) key; protocolBean.setId(protocol.getId().toString()); protocolBean.setName(protocol.getName()); protocolBean.setType(protocol.getType()); nameVersions.put(protocolBean, localList); keyMap.put((Protocol) key, protocolBean); } } } catch (Exception e) { logger .error("Problem to retrieve all protocol names and their versions by type " + type); throw new RuntimeException( "Problem to retrieve all protocol names and their versions by type " + type); } finally { ida.close(); } return nameVersions; } public SortedSet<String> getAllProtocolTypes() throws Exception { SortedSet<String> protocolTypes = new TreeSet<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct protocol.type from Protocol protocol where protocol.type is not null"; List results = ida.search(hqlString); for (Object obj : results) { protocolTypes.add((String) obj); } } catch (Exception e) { logger.error("Problem to retrieve all protocol types."); throw new RuntimeException( "Problem to retrieve all protocol types."); } finally { ida.close(); } return protocolTypes; } public SortedSet<ProtocolBean> getAllProtocols(UserBean user) throws Exception { SortedSet<ProtocolBean> protocolBeans = new TreeSet<ProtocolBean>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "from Protocol as protocol left join fetch protocol.protocolFileCollection"; List results = ida.search(hqlString); for (Object obj : results) { Protocol p = (Protocol) obj; ProtocolBean pb = new ProtocolBean(); pb.setId(p.getId().toString()); pb.setName(p.getName()); pb.setType(p.getType()); PersistentSet set = (PersistentSet) p .getProtocolFileCollection(); // HashSet hashSet = set. if (!set.isEmpty()) { List<ProtocolFileBean> list = new ArrayList<ProtocolFileBean>(); for (Iterator it = set.iterator(); it.hasNext();) { ProtocolFile pf = (ProtocolFile) it.next(); ProtocolFileBean pfb = new ProtocolFileBean(); pfb.setId(pf.getId().toString()); pfb.setVersion(pf.getVersion()); list.add(pfb); } pb.setFileBeanList(filterProtocols(list, user)); } if (!pb.getFileBeanList().isEmpty()) protocolBeans.add(pb); } } catch (Exception e) { logger.error("Problem to retrieve all protocol names and types."); throw new RuntimeException( "Problem to retrieve all protocol names and types."); } finally { ida.close(); } return protocolBeans; } private List<ProtocolFileBean> filterProtocols( List<ProtocolFileBean> protocolFiles, UserBean user) throws Exception { UserService userService = new UserService( CaNanoLabConstants.CSM_APP_NAME); List<LabFileBean> tempList = new ArrayList<LabFileBean>(); for (ProtocolFileBean pfb : protocolFiles) { tempList.add((LabFileBean) pfb); } List<LabFileBean> filteredProtocols = userService.getFilteredFiles( user, tempList); protocolFiles.clear(); if (filteredProtocols == null || filteredProtocols.isEmpty()) return protocolFiles; for (LabFileBean lfb : filteredProtocols) { protocolFiles.add((ProtocolFileBean) lfb); } return protocolFiles; } public String[] getAllStressorTypes() { String[] stressorTypes = new String[] { "Thermal", "PH", "Freeze thaw", "Photo", "Centrifugation", "Lyophilization", "Chemical", "Other" }; return stressorTypes; } public String[] getAllAreaMeasureUnits() { String[] areaUnit = new String[] { "sq nm" }; return areaUnit; } public String[] getAllChargeMeasureUnits() { String[] chargeUnit = new String[] { "a.u", "aC", "Ah", "C", "esu", "Fr", "statC" }; return chargeUnit; } public String[] getAllDensityMeasureUnits() { String[] densityUnits = new String[] { "kg/L" }; return densityUnits; } public String[] getAllControlTypes() { String[] controlTypes = new String[] { " ", "Positive", "Negative" }; return controlTypes; } public String[] getAllConditionTypes() { String[] conditionTypes = new String[] { "Particle Concentration", "Temperature", "Time" }; return conditionTypes; } public Map<String, String[]> getAllAgentTypes() { Map<String, String[]> agentTypes = new HashMap<String, String[]>(); String[] therapeuticsAgentTypes = new String[] { "Peptide", "Small Molecule", "Antibody", "DNA", "Probe", "Image Contrast Agent", "Other" }; agentTypes.put("Therapeutic", therapeuticsAgentTypes); String[] targetingAgentTypes = new String[] { "Peptide", "Small Molecule", "Antibody", "DNA", "Probe", "Image Contrast Agent", "Other" }; agentTypes.put("Targeting", targetingAgentTypes); String[] imagingAgentTypes = new String[] { "Peptide", "Small Molecule", "Antibody", "DNA", "Probe", "Image Contrast Agent", "Other" }; agentTypes.put("Imaging", imagingAgentTypes); String[] reportingAgentTypes = new String[] { "Peptide", "Small Molecule", "Antibody", "DNA", "Probe", "Image Contrast Agent", "Other" }; agentTypes.put("Reporting", reportingAgentTypes); return agentTypes; } public Map<String, String[]> getAllAgentTargetTypes() { Map<String, String[]> agentTargetTypes = new HashMap<String, String[]>(); String[] targetTypes = new String[] { "Receptor", "Antigen", "Other" }; String[] targetTypes1 = new String[] { "Receptor", "Other" }; String[] targetTypes2 = new String[] { "Other" }; agentTargetTypes.put("Small Molecule", targetTypes2); agentTargetTypes.put("Peptide", targetTypes1); agentTargetTypes.put("Antibody", targetTypes); agentTargetTypes.put("DNA", targetTypes1); agentTargetTypes.put("Probe", targetTypes1); agentTargetTypes.put("Other", targetTypes2); agentTargetTypes.put("Image Contrast Agent", targetTypes2); return agentTargetTypes; } public String[] getAllTimeUnits() { String[] timeUnits = new String[] { "hours", "days", "months" }; return timeUnits; } public String[] getAllTemperatureUnits() { String[] temperatureUnits = new String[] { "degrees celsius", "degrees fahrenhiet" }; return temperatureUnits; } public String[] getAllConcentrationUnits() { String[] concentrationUnits = new String[] { "g/ml", "mg/ml", "pg/ml", "ug/ml", "ug/ul" }; return concentrationUnits; } public Map<String, String[]> getAllConditionUnits() { Map<String, String[]> conditionTypeUnits = new HashMap<String, String[]>(); String[] concentrationUnits = new String[] { "g/ml", "mg/ml", "pg/ml", "ug/ml", "ug/ul", }; String[] temperatureUnits = new String[] { "degrees celsius", "degrees fahrenhiet" }; String[] timeUnits = new String[] { "hours", "days", "months" }; conditionTypeUnits.put("Particle Concentration", concentrationUnits); conditionTypeUnits.put("Time", timeUnits); conditionTypeUnits.put("Temperature", temperatureUnits); return conditionTypeUnits; } public String[] getAllCellLines() throws Exception { SortedSet<String> cellLines = new TreeSet<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct cellViability.cellLine, caspase.cellLine from CellViability cellViability, Caspase3Activation caspase"; List results = ida.search(hqlString); for (Object obj : results) { // cellLines.add((String) obj); Object[] objects = (Object[]) obj; for (Object object : objects) { if (object != null) { cellLines.add((String) object); } } } } catch (Exception e) { logger.error("Problem to retrieve all Cell lines."); throw new RuntimeException("Problem to retrieve all Cell lines."); } finally { ida.close(); } cellLines.addAll(Arrays.asList(CaNanoLabConstants.DEFAULT_CELLLINES)); return (String[]) cellLines.toArray(new String[0]); } public String[] getAllActivationMethods() { String[] activationMethods = new String[] { "NMR", "MRI", "Radiation", "Ultrasound", "Ultraviolet Light" }; return activationMethods; } public List<LabelValueBean> getAllSpecies() throws Exception { List<LabelValueBean> species = new ArrayList<LabelValueBean>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); species.add(new LabelValueBean("", "")); try { for (int i = 0; i < CaNanoLabConstants.SPECIES_COMMON.length; i++) { String specie = CaNanoLabConstants.SPECIES_COMMON[i]; species.add(new LabelValueBean(specie, specie)); } } catch (Exception e) { logger.error("Problem to retrieve all species. " + e); throw new RuntimeException( "Problem to retrieve all intrument types. "); } finally { ida.close(); } return species; } public String[] getAllReportTypes() { String[] allReportTypes = new String[] { CaNanoLabConstants.REPORT, CaNanoLabConstants.ASSOCIATED_FILE }; return allReportTypes; } /** * Get other particles from the given particle source * * @param particleSource * @param particleName * @param user * @return * @throws Exception */ public SortedSet<String> getOtherParticles(String particleSource, String particleName, UserBean user) throws Exception { IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); UserService userService = new UserService( CaNanoLabConstants.CSM_APP_NAME); SortedSet<String> otherParticleNames = new TreeSet<String>(); try { ida.open(); String hqlString = "select particle.name from Nanoparticle particle where particle.source.organizationName='" + particleSource + "' and particle.name !='" + particleName + "'"; List results = ida.search(hqlString); for (Object obj : results) { String otherParticleName = (String) obj; // check if user can see the particle boolean status = userService.checkReadPermission(user, otherParticleName); if (status) { otherParticleNames.add(otherParticleName); } } } catch (Exception e) { logger .error("Error in retrieving all particle type particles. ", e); throw new RuntimeException( "Error in retrieving all particle type particles. "); } finally { ida.close(); } return otherParticleNames; } public List<InstrumentBean> getAllInstruments() throws Exception { List<InstrumentBean> instruments = new ArrayList<InstrumentBean>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "from Instrument instrument where instrument.type is not null and instrument.manufacturer is not null order by instrument.type"; List results = ida.search(hqlString); for (Object obj : results) { Instrument instrument = (Instrument) obj; instruments.add(new InstrumentBean(instrument)); } } catch (Exception e) { logger.error("Problem to retrieve all instruments. " + e); throw new RuntimeException("Problem to retrieve all intruments. "); } finally { ida.close(); } return instruments; } public List<String> getAllDerivedDataFileTypes() throws Exception { List<String> fileTypes = new ArrayList<String>(); // TODO query from database fileTypes.addAll(Arrays .asList(CaNanoLabConstants.DEFAULT_DERIVED_DATA_FILE_TYPES)); return fileTypes; } public Map<String, List<String>> getAllDerivedDataCategories() throws Exception { Map<String, List<String>> categoryMap = new HashMap<String, List<String>>(); // TODO query from database List<String> categories = new ArrayList<String>(); categories.add("Volume Distribution"); categories.add("Intensity Distribution"); categories.add("Number Distribution"); categoryMap.put("Size", categories); return categoryMap; } public List<String> getAllFunctionTypes() throws Exception { List<String> types = new ArrayList<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select funcType.name from FunctionType funcType order by funcType.name"; List results = ida.search(hqlString); for (Object obj : results) { String type = (String) obj; types.add(type); } } catch (Exception e) { logger.error("Problem to retrieve all function types. " + e); throw new RuntimeException( "Problem to retrieve all function types. "); } finally { ida.close(); } return types; } public List<CharacterizationTypeBean> getAllCharacterizationTypes() throws Exception { List<CharacterizationTypeBean> charTypes = new ArrayList<CharacterizationTypeBean>(); HibernateDataAccess hda = HibernateDataAccess.getInstance(); try { hda.open(); String query = "select distinct category, has_action, indent_level, category_order from characterization_category order by category_order"; SQLQuery queryObj = hda.getNativeQuery(query); queryObj.addScalar("CATEGORY", Hibernate.STRING); queryObj.addScalar("HAS_ACTION", Hibernate.INTEGER); queryObj.addScalar("INDENT_LEVEL", Hibernate.INTEGER); queryObj.addScalar("CATEGORY_ORDER", Hibernate.INTEGER); List results = queryObj.list(); for (Object obj : results) { Object[] objarr = (Object[]) obj; String type = objarr[0].toString(); boolean hasAction = ((Integer) objarr[1] == 0) ? false : true; int indentLevel = (Integer) objarr[2]; CharacterizationTypeBean charType = new CharacterizationTypeBean( type, indentLevel, hasAction); charTypes.add(charType); } } catch (Exception e) { logger .error("Problem to retrieve all characterization types. " + e); throw new RuntimeException( "Problem to retrieve all characteriztaion types. "); } finally { hda.close(); } return charTypes; } }
added getDerivedDataCategoryMap SVN-Revision: 3371
src/gov/nih/nci/calab/service/common/LookupService.java
added getDerivedDataCategoryMap
Java
isc
e3f4cc251b18792c5387c9d0f2b86b2403728b74
0
TealCube/loot
/* * This file is part of Loot, licensed under the ISC License. * * Copyright (c) 2014 Richard Harrah * * Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, * provided that the above copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF * THIS SOFTWARE. */ package info.faceland.loot.listeners.sockets; import com.kill3rtaco.tacoserialization.SingleItemSerialization; import com.tealcube.minecraft.bukkit.facecore.shade.hilt.HiltItemStack; import com.tealcube.minecraft.bukkit.facecore.utilities.MessageUtils; import com.tealcube.minecraft.bukkit.facecore.utilities.TextUtils; import com.tealcube.minecraft.bukkit.kern.shade.google.common.base.Predicates; import com.tealcube.minecraft.bukkit.kern.shade.google.common.collect.Iterables; import com.tealcube.minecraft.bukkit.kern.shade.google.common.collect.Lists; import info.faceland.loot.LootPlugin; import info.faceland.loot.api.math.Vec3; import info.faceland.loot.api.sockets.SocketGem; import info.faceland.loot.api.sockets.effects.SocketEffect; import org.bukkit.*; import org.bukkit.block.Chest; import org.bukkit.entity.*; import org.bukkit.event.Event; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.ProjectileLaunchEvent; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryCloseEvent; import org.bukkit.event.inventory.InventoryOpenEvent; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.InventoryHolder; import org.bukkit.inventory.ItemStack; import org.bukkit.metadata.FixedMetadataValue; import org.bukkit.metadata.MetadataValue; import java.util.*; public final class SocketsListener implements Listener { private LootPlugin plugin; private final Map<UUID, List<String>> gems; public SocketsListener(LootPlugin plugin) { this.plugin = plugin; this.gems = new HashMap<>(); } @EventHandler(priority = EventPriority.MONITOR) public void onProjectileLaunch(ProjectileLaunchEvent event) { if (event.isCancelled() || !(event.getEntity().getShooter() instanceof Player)) { return; } Set<SocketGem> gems = getGems(((Player) event.getEntity().getShooter()).getItemInHand()); List<String> names = new ArrayList<>(); for (SocketGem gem : gems) { names.add(gem.getName()); } event.getEntity().setMetadata("loot.gems", new FixedMetadataValue(plugin, names.toString())); } @EventHandler(priority = EventPriority.MONITOR) public void onEntityDamageByEntity(EntityDamageByEntityEvent event) { if (event.isCancelled()) { return; } List<SocketGem> attackerGems = new ArrayList<>(); List<SocketGem> defenderGems = new ArrayList<>(); Entity attacker = event.getDamager(); Entity defender = event.getEntity(); if (attacker instanceof Player) { Player attackerP = (Player) attacker; attackerGems.addAll(getGems(attackerP.getEquipment().getItemInHand())); } else if (attacker instanceof Projectile && ((Projectile) attacker).getShooter() instanceof Player) { attacker = (Player) ((Projectile) attacker).getShooter(); if (event.getDamager().hasMetadata("loot.gems")) { for (MetadataValue val : event.getDamager().getMetadata("loot.gems")) { if (!val.getOwningPlugin().equals(plugin)) { continue; } String blah = val.asString().replace("[", "").replace("]", ""); for (String s : blah.split(",")) { SocketGem gem = plugin.getSocketGemManager().getSocketGem(s.trim()); if (gem == null) { continue; } attackerGems.add(gem); } } } } if (defender instanceof Player) { Player defenderP = (Player) defender; for (ItemStack equipment : defenderP.getEquipment().getArmorContents()) { defenderGems.addAll(getGems(equipment)); } } for (SocketGem gem : attackerGems) { for (SocketEffect effect : gem.getSocketEffects()) { switch (effect.getTarget()) { case SELF: if (attacker instanceof LivingEntity) { effect.apply((LivingEntity) attacker); } break; case OTHER: if (defender instanceof LivingEntity) { effect.apply((LivingEntity) defender); } break; case AREA: for (Entity e : defender .getNearbyEntities(effect.getRadius(), effect.getRadius(), effect.getRadius())) { if (e instanceof LivingEntity) { effect.apply((LivingEntity) e); } } if (defender instanceof LivingEntity) { effect.apply((LivingEntity) defender); } break; default: break; } } } for (SocketGem gem : defenderGems) { for (SocketEffect effect : gem.getSocketEffects()) { switch (effect.getTarget()) { case SELF: if (defender instanceof LivingEntity) { effect.apply((LivingEntity) defender); } break; case OTHER: if (attacker instanceof LivingEntity) { effect.apply((LivingEntity) attacker); } break; case AREA: for (Entity e : attacker .getNearbyEntities(effect.getRadius(), effect.getRadius(), effect.getRadius())) { if (e instanceof LivingEntity) { effect.apply((LivingEntity) e); } } if (attacker instanceof LivingEntity) { effect.apply((LivingEntity) attacker); } break; default: break; } } } } @EventHandler public void onInventoryClick(InventoryClickEvent event) { if (!ChatColor.stripColor(event.getInventory().getName()).equals("Socket Gem Combiner")) { return; } if (event.getInventory().getSize() > 9) { return; } if (event.isShiftClick()) { event.setCancelled(true); event.setResult(Event.Result.DENY); } } @EventHandler public void onInventoryOpen(InventoryOpenEvent event) { Inventory inventory = event.getInventory(); InventoryHolder holder = inventory.getHolder(); if (!(holder instanceof Chest)) { return; } Vec3 loc = new Vec3(((Chest) holder).getWorld().getName(), ((Chest) holder).getX(), ((Chest) holder).getY(), ((Chest) holder).getZ()); if (!plugin.getChestManager().getChestLocations().contains(loc)) { return; } event.setCancelled(true); Inventory toShow = Bukkit.createInventory(null, 9, "Socket Gem Combiner"); toShow.setMaxStackSize(1); List<String> toAdd = gems.get(event.getPlayer().getUniqueId()); if (toAdd == null) { toAdd = new ArrayList<>(); } for (String s : toAdd) { toShow.addItem(SingleItemSerialization.getItem(s)); } event.getPlayer().openInventory(toShow); } @EventHandler public void onInventoryClose(InventoryCloseEvent event) { if (!ChatColor.stripColor(event.getInventory().getName()).equals("Socket Gem Combiner")) { return; } if (event.getInventory().getSize() > 9) { return; } List<ItemStack> newResults = new ArrayList<>(); List<ItemStack> contents = Lists.newArrayList(Iterables.filter(Arrays.asList(event.getInventory().getContents()), Predicates.notNull())); while (contents.size() >= 4) { contents = contents.subList(4, contents.size()); newResults.add(plugin.getSocketGemManager().getRandomSocketGemByBonus().toItemStack(1)); } newResults.addAll(contents); List<String> toAdd = new ArrayList<>(); for (ItemStack is : newResults) { toAdd.add(SingleItemSerialization.serializeItemAsString(is)); } if (toAdd.size() > 0) { HumanEntity c = event.getPlayer(); c.getWorld().playEffect(c.getLocation().add(0, 1, 0), Effect.SPELL, 0); c.getWorld().playSound(c.getLocation().add(0, 1, 0), Sound.ENDERMAN_SCREAM, 1.0f, 1.0f); MessageUtils.sendMessage(event.getPlayer(), "<green>Open the chest again to get your new Socket Gems!"); } gems.put(event.getPlayer().getUniqueId(), toAdd); } private Set<SocketGem> getGems(ItemStack itemStack) { if (itemStack == null || itemStack.getType() == Material.AIR) { return new HashSet<>(); } Set<SocketGem> gems = new HashSet<>(); HiltItemStack item = new HiltItemStack(itemStack); List<String> lore = item.getLore(); List<String> strippedLore = stripColor(lore); for (String key : strippedLore) { SocketGem gem = plugin.getSocketGemManager().getSocketGem(key); if (gem == null) { for (SocketGem g : plugin.getSocketGemManager().getSocketGems()) { if (key.equals(ChatColor.stripColor(TextUtils.color( g.getTriggerText() != null ? g.getTriggerText() : "")))) { gem = g; break; } } if (gem == null) { continue; } } gems.add(gem); } return gems; } private List<String> stripColor(List<String> strings) { List<String> ret = new ArrayList<>(); for (String s : strings) { ret.add(ChatColor.stripColor(s)); } return ret; } }
src/main/java/info/faceland/loot/listeners/sockets/SocketsListener.java
/* * This file is part of Loot, licensed under the ISC License. * * Copyright (c) 2014 Richard Harrah * * Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, * provided that the above copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF * THIS SOFTWARE. */ package info.faceland.loot.listeners.sockets; import com.kill3rtaco.tacoserialization.SingleItemSerialization; import com.tealcube.minecraft.bukkit.facecore.shade.hilt.HiltItemStack; import com.tealcube.minecraft.bukkit.facecore.utilities.MessageUtils; import com.tealcube.minecraft.bukkit.facecore.utilities.TextUtils; import com.tealcube.minecraft.bukkit.kern.shade.google.common.base.Predicates; import com.tealcube.minecraft.bukkit.kern.shade.google.common.collect.Iterables; import com.tealcube.minecraft.bukkit.kern.shade.google.common.collect.Lists; import info.faceland.loot.LootPlugin; import info.faceland.loot.api.math.Vec3; import info.faceland.loot.api.sockets.SocketGem; import info.faceland.loot.api.sockets.effects.SocketEffect; import org.bukkit.*; import org.bukkit.block.Chest; import org.bukkit.entity.*; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.ProjectileLaunchEvent; import org.bukkit.event.inventory.InventoryCloseEvent; import org.bukkit.event.inventory.InventoryOpenEvent; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.InventoryHolder; import org.bukkit.inventory.ItemStack; import org.bukkit.metadata.FixedMetadataValue; import org.bukkit.metadata.MetadataValue; import java.util.*; public final class SocketsListener implements Listener { private LootPlugin plugin; private final Map<UUID, List<String>> gems; public SocketsListener(LootPlugin plugin) { this.plugin = plugin; this.gems = new HashMap<>(); } @EventHandler(priority = EventPriority.MONITOR) public void onProjectileLaunch(ProjectileLaunchEvent event) { if (event.isCancelled() || !(event.getEntity().getShooter() instanceof Player)) { return; } Set<SocketGem> gems = getGems(((Player) event.getEntity().getShooter()).getItemInHand()); List<String> names = new ArrayList<>(); for (SocketGem gem : gems) { names.add(gem.getName()); } event.getEntity().setMetadata("loot.gems", new FixedMetadataValue(plugin, names.toString())); } @EventHandler(priority = EventPriority.MONITOR) public void onEntityDamageByEntity(EntityDamageByEntityEvent event) { if (event.isCancelled()) { return; } List<SocketGem> attackerGems = new ArrayList<>(); List<SocketGem> defenderGems = new ArrayList<>(); Entity attacker = event.getDamager(); Entity defender = event.getEntity(); if (attacker instanceof Player) { Player attackerP = (Player) attacker; attackerGems.addAll(getGems(attackerP.getEquipment().getItemInHand())); } else if (attacker instanceof Projectile && ((Projectile) attacker).getShooter() instanceof Player) { attacker = (Player) ((Projectile) attacker).getShooter(); if (event.getDamager().hasMetadata("loot.gems")) { for (MetadataValue val : event.getDamager().getMetadata("loot.gems")) { if (!val.getOwningPlugin().equals(plugin)) { continue; } String blah = val.asString().replace("[", "").replace("]", ""); for (String s : blah.split(",")) { SocketGem gem = plugin.getSocketGemManager().getSocketGem(s.trim()); if (gem == null) { continue; } attackerGems.add(gem); } } } } if (defender instanceof Player) { Player defenderP = (Player) defender; for (ItemStack equipment : defenderP.getEquipment().getArmorContents()) { defenderGems.addAll(getGems(equipment)); } } for (SocketGem gem : attackerGems) { for (SocketEffect effect : gem.getSocketEffects()) { switch (effect.getTarget()) { case SELF: if (attacker instanceof LivingEntity) { effect.apply((LivingEntity) attacker); } break; case OTHER: if (defender instanceof LivingEntity) { effect.apply((LivingEntity) defender); } break; case AREA: for (Entity e : defender .getNearbyEntities(effect.getRadius(), effect.getRadius(), effect.getRadius())) { if (e instanceof LivingEntity) { effect.apply((LivingEntity) e); } } if (defender instanceof LivingEntity) { effect.apply((LivingEntity) defender); } break; default: break; } } } for (SocketGem gem : defenderGems) { for (SocketEffect effect : gem.getSocketEffects()) { switch (effect.getTarget()) { case SELF: if (defender instanceof LivingEntity) { effect.apply((LivingEntity) defender); } break; case OTHER: if (attacker instanceof LivingEntity) { effect.apply((LivingEntity) attacker); } break; case AREA: for (Entity e : attacker .getNearbyEntities(effect.getRadius(), effect.getRadius(), effect.getRadius())) { if (e instanceof LivingEntity) { effect.apply((LivingEntity) e); } } if (attacker instanceof LivingEntity) { effect.apply((LivingEntity) attacker); } break; default: break; } } } } @EventHandler public void onInventoryOpen(InventoryOpenEvent event) { Inventory inventory = event.getInventory(); InventoryHolder holder = inventory.getHolder(); if (!(holder instanceof Chest)) { return; } Vec3 loc = new Vec3(((Chest) holder).getWorld().getName(), ((Chest) holder).getX(), ((Chest) holder).getY(), ((Chest) holder).getZ()); if (!plugin.getChestManager().getChestLocations().contains(loc)) { return; } event.setCancelled(true); Inventory toShow = Bukkit.createInventory(null, 9, "Socket Gem Combiner"); toShow.setMaxStackSize(1); List<String> toAdd = gems.get(event.getPlayer().getUniqueId()); if (toAdd == null) { toAdd = new ArrayList<>(); } for (String s : toAdd) { toShow.addItem(SingleItemSerialization.getItem(s)); } event.getPlayer().openInventory(toShow); } @EventHandler public void onInventoryClose(InventoryCloseEvent event) { if (!ChatColor.stripColor(event.getInventory().getName()).equals("Socket Gem Combiner")) { return; } if (event.getInventory().getSize() > 9) { return; } List<ItemStack> newResults = new ArrayList<>(); List<ItemStack> contents = Lists.newArrayList(Iterables.filter(Arrays.asList(event.getInventory().getContents()), Predicates.notNull())); while (contents.size() >= 4) { contents = contents.subList(4, contents.size()); newResults.add(plugin.getSocketGemManager().getRandomSocketGemByBonus().toItemStack(1)); } newResults.addAll(contents); List<String> toAdd = new ArrayList<>(); for (ItemStack is : newResults) { toAdd.add(SingleItemSerialization.serializeItemAsString(is)); } if (toAdd.size() > 0) { HumanEntity c = event.getPlayer(); c.getWorld().playEffect(c.getLocation().add(0, 1, 0), Effect.SPELL, 0); c.getWorld().playSound(c.getLocation().add(0, 1, 0), Sound.ENDERMAN_SCREAM, 1.0f, 1.0f); MessageUtils.sendMessage(event.getPlayer(), "<green>Open the chest again to get your new Socket Gems!"); } gems.put(event.getPlayer().getUniqueId(), toAdd); } private Set<SocketGem> getGems(ItemStack itemStack) { if (itemStack == null || itemStack.getType() == Material.AIR) { return new HashSet<>(); } Set<SocketGem> gems = new HashSet<>(); HiltItemStack item = new HiltItemStack(itemStack); List<String> lore = item.getLore(); List<String> strippedLore = stripColor(lore); for (String key : strippedLore) { SocketGem gem = plugin.getSocketGemManager().getSocketGem(key); if (gem == null) { for (SocketGem g : plugin.getSocketGemManager().getSocketGems()) { if (key.equals(ChatColor.stripColor(TextUtils.color( g.getTriggerText() != null ? g.getTriggerText() : "")))) { gem = g; break; } } if (gem == null) { continue; } } gems.add(gem); } return gems; } private List<String> stripColor(List<String> strings) { List<String> ret = new ArrayList<>(); for (String s : strings) { ret.add(ChatColor.stripColor(s)); } return ret; } }
blocking shift click in Socket Gem Transmuter
src/main/java/info/faceland/loot/listeners/sockets/SocketsListener.java
blocking shift click in Socket Gem Transmuter
Java
mit
0fda91f5f9e3f058b0e8ac82997815853ef7b54d
0
tstevens/storm-hdfs-spout
package com.github.tstevens.storm.hdfs.spout; import java.io.IOException; import java.net.URI; import java.util.Date; import java.util.Map; import java.util.Objects; import java.util.concurrent.TimeUnit; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hdfs.DFSInotifyEventInputStream; import org.apache.hadoop.hdfs.client.HdfsAdmin; import org.apache.hadoop.hdfs.inotify.Event; import org.apache.hadoop.hdfs.inotify.MissingEventsException; import org.apache.hadoop.hdfs.inotify.Event.CloseEvent; import backtype.storm.spout.ISpoutOutputCollector; import backtype.storm.spout.SpoutOutputCollector; import backtype.storm.task.TopologyContext; import backtype.storm.topology.OutputFieldsDeclarer; import backtype.storm.topology.base.BaseRichSpout; import backtype.storm.tuple.Fields; import backtype.storm.tuple.Values; public class HdfsInotifySpout extends BaseRichSpout { private static final long serialVersionUID = 7252687842097019979L; public static final String STREAM_ID = "hdfs-events"; public static final String EVENT_TYPE_FIELD = "type"; public static final String PATH_FIELD = "path"; public static final String SIZE_FIELD = "size"; public static final String TIME_FIELD = "time"; private ISpoutOutputCollector collector; private String watchedPath; private URI hdfsUri; private HdfsAdmin dfs; private DFSInotifyEventInputStream stream; private long lastReadTxId; public HdfsInotifySpout(URI hdfsUri, String watchedPath){ this.watchedPath = Objects.requireNonNull(watchedPath); this.hdfsUri = Objects.requireNonNull(hdfsUri); } @Override public void open(@SuppressWarnings("rawtypes") Map config, TopologyContext context, SpoutOutputCollector collector) { this.collector = collector; lastReadTxId = 0; Configuration conf = new Configuration(); try { dfs = new HdfsAdmin(hdfsUri, conf); stream = dfs.getInotifyEventStream(); } catch (IOException e) { collector.reportError(e); } } @Override public void nextTuple() { try { // TODO Save last read txid (HDFS-7446) Event raw_event = null; while ((raw_event = stream.poll(100, TimeUnit.MILLISECONDS)) !=null ){ // TODO Add jitter to wait time if(raw_event instanceof CloseEvent){ CloseEvent closeEvent = (CloseEvent) raw_event; if(closeEvent.getPath().startsWith(watchedPath)){ collector.emit(STREAM_ID, new Values(closeEvent.getPath(), closeEvent.getFileSize(), new Date(closeEvent.getTimestamp()), closeEvent.getEventType().toString()), null); } } } } catch (IOException e) { collector.reportError(e); } catch (MissingEventsException e) { // Log? missed updates but able to continue } catch (InterruptedException e){ //Ignore and finish } } @Override public void deactivate() { stream = null; } @Override public void activate() { // TODO Try and restart from last read txid (HDFS-7446) try { stream = lastReadTxId != 0 ? dfs.getInotifyEventStream(lastReadTxId) : dfs.getInotifyEventStream(); } catch (IOException e) { collector.reportError(e); } } @Override public void declareOutputFields(OutputFieldsDeclarer declarer) { declarer.declareStream(STREAM_ID, new Fields( PATH_FIELD, SIZE_FIELD, TIME_FIELD, EVENT_TYPE_FIELD)); } }
src/main/java/com/github/tstevens/storm/hdfs/spout/HdfsInotifySpout.java
package com.github.tstevens.storm.hdfs.spout; import java.io.IOException; import java.net.URI; import java.util.Date; import java.util.Map; import java.util.Objects; import java.util.concurrent.TimeUnit; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hdfs.DFSInotifyEventInputStream; import org.apache.hadoop.hdfs.client.HdfsAdmin; import org.apache.hadoop.hdfs.inotify.Event; import org.apache.hadoop.hdfs.inotify.MissingEventsException; import org.apache.hadoop.hdfs.inotify.Event.CloseEvent; import backtype.storm.spout.ISpoutOutputCollector; import backtype.storm.spout.SpoutOutputCollector; import backtype.storm.task.TopologyContext; import backtype.storm.topology.OutputFieldsDeclarer; import backtype.storm.topology.base.BaseRichSpout; import backtype.storm.tuple.Fields; import backtype.storm.tuple.Values; public class HdfsInotifySpout extends BaseRichSpout { private static final long serialVersionUID = 7252687842097019979L; public static final String STREAM_ID = "hdfs-events"; public static final String EVENT_TYPE_FIELD = "type"; public static final String PATH_FIELD = "path"; public static final String SIZE_FIELD = "size"; public static final String TIME_FIELD = "time"; private ISpoutOutputCollector collector; private String watchedPath; private URI hdfsUri; private HdfsAdmin dfs; private DFSInotifyEventInputStream stream; private long lastReadTxId; public HdfsInotifySpout(URI hdfsUri, String watchedPath){ this.watchedPath = Objects.requireNonNull(watchedPath); this.hdfsUri = Objects.requireNonNull(hdfsUri); } @Override public void open(@SuppressWarnings("rawtypes") Map config, TopologyContext context, SpoutOutputCollector collector) { this.collector = collector; lastReadTxId = 0; Configuration conf = new Configuration(); try { dfs = new HdfsAdmin(hdfsUri, conf); stream = dfs.getInotifyEventStream(); } catch (IOException e) { collector.reportError(e); } } @Override public void nextTuple() { try { // TODO Save last read txid (HDFS-7446) Event raw_event = null; while ((raw_event = this.stream.poll(100, TimeUnit.MILLISECONDS)) !=null ){ // TODO Add jitter to wait time if(raw_event instanceof CloseEvent){ CloseEvent closeEvent = (CloseEvent) raw_event; if(closeEvent.getPath().startsWith(watchedPath)){ collector.emit(STREAM_ID, new Values(closeEvent.getPath(), closeEvent.getFileSize(), new Date(closeEvent.getTimestamp()), closeEvent.getEventType().toString()), null); } } } } catch (IOException e) { collector.reportError(e); } catch (MissingEventsException e) { // Log? missed updates but able to continue } catch (InterruptedException e){ //Ignore and finish } } @Override public void deactivate() { this.stream = null; } @Override public void activate() { // TODO Try and restart from last read txid (HDFS-7446) try { this.stream = lastReadTxId != 0 ? this.dfs.getInotifyEventStream(lastReadTxId) : this.dfs.getInotifyEventStream(); } catch (IOException e) { collector.reportError(e); } } @Override public void declareOutputFields(OutputFieldsDeclarer declarer) { declarer.declareStream(STREAM_ID, new Fields( PATH_FIELD, SIZE_FIELD, TIME_FIELD, EVENT_TYPE_FIELD)); } }
Remove unnecessary this references
src/main/java/com/github/tstevens/storm/hdfs/spout/HdfsInotifySpout.java
Remove unnecessary this references
Java
mit
6d339a4102840b488d43ecc4df1fcbb054a82892
0
foromer4/netdepend
package com.picscout.netdepend.netdepend_graph; import java.security.spec.ECGenParameterSpec; import org.apache.log4j.Logger; import org.apache.xerces.dom.ElementDefinitionImpl; import org.bouncycastle.operator.InputExpanderProvider; import com.google.common.collect.Lists; import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Key; import com.google.inject.Module; import com.google.inject.multibindings.MapBinderBinding; import com.google.inject.multibindings.Multibinder; import com.google.inject.multibindings.MultibinderBinding; import com.google.inject.multibindings.MultibindingsTargetVisitor; import com.google.inject.spi.DefaultBindingTargetVisitor; import com.google.inject.spi.Element; import com.google.inject.spi.Elements; import com.google.inject.util.Modules; import com.picscout.depend.dependency.classes.ProjectBuilder; import com.picscout.depend.dependency.interfaces.IProjectBuilder; import hudson.Extension; import hudson.plugins.depgraph_view.model.graph.DependencyGraphEdgeProvider; import hudson.plugins.depgraph_view.model.graph.DependencyGraphModule; import hudson.plugins.depgraph_view.model.graph.EdgeProvider; /** * Module used to inject new edge provider. still not usable, see: {@link: * https://issues.jenkins-ci.org/browse/JENKINS-28773?jql=project%20%3D%20 * JENKINS * %20AND%20status%20in%20(Open%2C%20%22In%20Progress%22%2C%20Reopened)%20 * AND%20component%20%3D%20%27depgraph-view-plugin%27} * * @author OSchliefer * */ @Extension public class NetDependModule extends AbstractModule { private final static Logger LOG = Logger.getLogger(NetDependModule.class .getName()); public NetDependModule() { LOG.info("NetDependModule override was called. " + Thread.currentThread().getStackTrace()); } @Override protected void configure() { LOG.info("NetDependModule configure was called. " + Thread.currentThread().getStackTrace()); Multibinder<EdgeProvider> edgeProviderMultibinder = Multibinder .newSetBinder(binder(), EdgeProvider.class); edgeProviderMultibinder.addBinding().to(EdgeProviderImpl.class); } }
netdepend_graph/src/main/java/com/picscout/netdepend/netdepend_graph/NetDependModule.java
package com.picscout.netdepend.netdepend_graph; import org.apache.log4j.Logger; import com.google.common.collect.Lists; import com.google.inject.AbstractModule; import com.google.inject.Key; import com.google.inject.Module; import com.google.inject.multibindings.MapBinderBinding; import com.google.inject.multibindings.Multibinder; import com.google.inject.multibindings.MultibinderBinding; import com.google.inject.multibindings.MultibindingsTargetVisitor; import com.google.inject.spi.DefaultBindingTargetVisitor; import com.google.inject.spi.Element; import com.google.inject.spi.Elements; import hudson.Extension; import hudson.plugins.depgraph_view.model.graph.EdgeProvider; @Extension public class NetDependModule extends AbstractModule { private final static Logger LOG = Logger.getLogger(NetDependModule.class .getName()); @Override protected void configure() { LOG.info("NetDependModule configure was called. " + Thread.currentThread().getStackTrace()); Multibinder<EdgeProvider> edgeProviderMultibinder = Multibinder .newSetBinder(binder(), EdgeProvider.class); edgeProviderMultibinder.addBinding().to(EdgeProviderImpl.class); } }
add comment
netdepend_graph/src/main/java/com/picscout/netdepend/netdepend_graph/NetDependModule.java
add comment
Java
mit
86acabf85c54c61f7f442f025199809d16bc5d6e
0
Eluinhost/pluginframework
package com.publicuhc.commands.routing; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.Provider; import com.publicuhc.commands.annotation.CommandMethod; import com.publicuhc.commands.annotation.RouteInfo; import com.publicuhc.commands.annotation.TabCompletion; import com.publicuhc.commands.exceptions.*; import com.publicuhc.commands.proxies.DefaultMethodProxy; import com.publicuhc.commands.proxies.CommandProxy; import com.publicuhc.commands.proxies.ProxyTriggerException; import com.publicuhc.commands.proxies.TabCompleteProxy; import com.publicuhc.commands.requests.CommandRequest; import com.publicuhc.commands.requests.CommandRequestBuilder; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.command.PluginCommand; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; public class DefaultRouter implements Router { /** * Stores all the command proxies */ private final ArrayList<CommandProxy> m_commands = new ArrayList<CommandProxy>(); /** * Stores all the tab complete proxies */ private final ArrayList<TabCompleteProxy> m_tabCompletes = new ArrayList<TabCompleteProxy>(); /** * Stores the message to send a player if a route wasn't found for the given command and parameters */ private final HashMap<Command, List<String>> m_noRouteMessages = new HashMap<Command, List<String>>(); //TODO be able to set the defaults /** * Used to build requests */ private final Provider<CommandRequestBuilder> m_requestProvider; /** * Used to inject all parameters needed to the command classes when added */ private final Injector m_injector; private final Logger m_logger; private static final String ROUTE_INFO_SUFFIX = "Details"; @Inject protected DefaultRouter(Provider<CommandRequestBuilder> requestProvider, Injector injector, Logger logger) { m_requestProvider = requestProvider; m_injector = injector; m_logger = logger; } @Override public List<CommandProxy> getCommandProxy(Command command, String parameters) { List<CommandProxy> proxies = new ArrayList<CommandProxy>(); for (CommandProxy proxy : m_commands) { if (command.getName().equals(proxy.getBaseCommand().getName())) { if (proxy.doParamsMatch(parameters)) { proxies.add(proxy); } } } return proxies; } @Override public List<TabCompleteProxy> getTabCompleteProxy(Command command, String parameters) { List<TabCompleteProxy> proxies = new ArrayList<TabCompleteProxy>(); for (TabCompleteProxy proxy : m_tabCompletes) { if (command.getName().equals(proxy.getBaseCommand().getName())) { if (proxy.doParamsMatch(parameters)) { proxies.add(proxy); } } } return proxies; } @Override public void registerCommands(Class klass) throws CommandClassParseException { registerCommands(m_injector.getInstance(klass), false); } protected void checkParameters(Method method) throws InvalidMethodParametersException { if (method.getParameterTypes().length != 1 || !CommandRequest.class.isAssignableFrom(method.getParameterTypes()[0])) { m_logger.log(Level.SEVERE, "Method " + method.getName() + " has incorrect parameters"); throw new InvalidMethodParametersException(); } } @Override public void registerCommands(Object object, boolean inject) throws CommandClassParseException { if (inject) { m_injector.injectMembers(object); } //the class of our object Class klass = object.getClass(); Method[] methods = klass.getDeclaredMethods(); for (Method method : methods) { boolean isCommandMethod = isCommandMethod(method); boolean isTabComplete = isTabComplete(method); if (isCommandMethod || isTabComplete) { //check the method parameters are correct checkParameters(method); if (isTabComplete) { //TODO check return type is correct } //get the method with the details we need Method routeInfo; try { routeInfo = klass.getMethod(method.getName() + ROUTE_INFO_SUFFIX); } catch (NoSuchMethodException e) { m_logger.log(Level.SEVERE, "No method found with the name " + method.getName() + ROUTE_INFO_SUFFIX); throw new DetailsMethodNotFoundException(); } //throws exceptions if not valid checkRouteInfo(routeInfo); //get the details MethodRoute methodRoute; try { methodRoute = (MethodRoute) routeInfo.invoke(object); } catch (Exception e) { e.printStackTrace(); m_logger.log(Level.SEVERE, "Error getting route info from the method " + routeInfo.getName()); throw new CommandClassParseException(); } //some validation PluginCommand command = Bukkit.getPluginCommand(methodRoute.getBaseCommand()); if (command == null) { m_logger.log(Level.SEVERE, "Couldn't find the command " + methodRoute.getBaseCommand() + " for the method " + method.getName()); throw new BaseCommandNotFoundException(); } //register ourselves command.setExecutor(this); command.setTabCompleter(this); DefaultMethodProxy proxy = null; if (isCommandMethod) { CommandProxy commandProxy = new CommandProxy(); m_commands.add(commandProxy); proxy = commandProxy; } if (isTabComplete) { TabCompleteProxy tabCompleteProxy = new TabCompleteProxy(); m_tabCompletes.add(tabCompleteProxy); proxy = tabCompleteProxy; } proxy.setPattern(methodRoute.getRoute()); proxy.setBaseCommand(command); proxy.setCommandMethod(method); proxy.setInstance(object); proxy.setPermission(methodRoute.getPermission()); proxy.setAllowedSenders(methodRoute.getAllowedTypes()); } } } protected void checkTabCompleteReturn(Method method) throws InvalidReturnTypeException { //only allow list returns if(!List.class.isAssignableFrom(method.getReturnType())){ throw new InvalidReturnTypeException(); } Type type = method.getGenericReturnType(); //only allow generics returned if (!(type instanceof ParameterizedType)) { throw new InvalidReturnTypeException(); } //make sure its a string parameter ParameterizedType ptype = (ParameterizedType) type; Type[] types = ptype.getActualTypeArguments(); if (types.length != 1 || !String.class.isAssignableFrom((Class) types[0])) { throw new InvalidReturnTypeException(); } } /** * @param method the method to check * @return true if has commandmethod annotation */ protected boolean isCommandMethod(Method method) { return method.getAnnotation(CommandMethod.class) != null; } /** * @param method the method to check * @return true if has tabcompletion annotation */ protected boolean isTabComplete(Method method) { return method.getAnnotation(TabCompletion.class) != null; } /** * Check the method to see if it is a valid routeinfo method * * @param method the method to check * @throws com.publicuhc.commands.exceptions.AnnotationMissingException if the method doesn't have the @RouteInfo annotation * @throws com.publicuhc.commands.exceptions.InvalidReturnTypeException if the method doesn't return a MethodRoute */ protected void checkRouteInfo(Method method) throws CommandClassParseException { if (null == method.getAnnotation(RouteInfo.class)) { m_logger.log(Level.SEVERE, "Route info method " + method.getName() + " does not have the @RouteInfo annotation"); throw new AnnotationMissingException(); } if (MethodRoute.class.isAssignableFrom(method.getReturnType())) { m_logger.log(Level.SEVERE, "Route info method " + method.getName() + " does not have the correct return type"); throw new InvalidReturnTypeException(); } } @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { //Put all of the arguments into a string to match StringBuilder stringBuilder = new StringBuilder(); for (String arg : args) { stringBuilder.append(arg).append(" "); } //get all the proxies that match the route List<CommandProxy> proxies = getCommandProxy(command, stringBuilder.toString()); //no proxies found that matched the route if (proxies.isEmpty()) { List<String> messages = m_noRouteMessages.get(command); //if there isn't any messages send the usage message if (messages.isEmpty()) { return false; } for (String message : messages) { sender.sendMessage(message); } return true; } //trigger all the proxies for (CommandProxy proxy : proxies) { CommandRequestBuilder builder = m_requestProvider.get(); CommandRequest request = builder.setCommand(command) .setArguments(args) .setSender(sender) .build(); try { proxy.trigger(request); } catch (ProxyTriggerException e) { e.getActualException().printStackTrace(); sender.sendMessage(ChatColor.RED + "Error running command, check console for more information"); //TODO translate with API } } //don't print the error message return true; } @Override public List<String> onTabComplete(CommandSender sender, Command command, String label, String[] args) { //Put all of the arguments into a string to match StringBuilder stringBuilder = new StringBuilder(); for (String arg : args) { stringBuilder.append(arg).append(" "); } //get all the proxies that match the route List<TabCompleteProxy> proxies = getTabCompleteProxy(command, stringBuilder.toString()); //no proxies found that matched the route if (proxies == null) { return new ArrayList<String>(0); } //trigger all the proxies and merge them List<String> results = new ArrayList<String>(); for (TabCompleteProxy proxy : proxies) { CommandRequestBuilder builder = m_requestProvider.get(); CommandRequest request = builder.setCommand(command) .setArguments(args) .setSender(sender) //.setMatchResult() TODO .build(); try { results.addAll(proxy.trigger(request)); } catch (ProxyTriggerException e) { e.getActualException().printStackTrace(); sender.sendMessage(ChatColor.RED + "Error with tab completion, check the console for more information"); //TODO translate with API } } return results; } }
src/main/java/com/publicuhc/commands/routing/DefaultRouter.java
package com.publicuhc.commands.routing; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.Provider; import com.publicuhc.commands.annotation.CommandMethod; import com.publicuhc.commands.annotation.RouteInfo; import com.publicuhc.commands.annotation.TabCompletion; import com.publicuhc.commands.exceptions.*; import com.publicuhc.commands.proxies.DefaultMethodProxy; import com.publicuhc.commands.proxies.CommandProxy; import com.publicuhc.commands.proxies.ProxyTriggerException; import com.publicuhc.commands.proxies.TabCompleteProxy; import com.publicuhc.commands.requests.CommandRequest; import com.publicuhc.commands.requests.CommandRequestBuilder; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.command.PluginCommand; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; public class DefaultRouter implements Router { /** * Stores all the command proxies */ private final ArrayList<CommandProxy> m_commands = new ArrayList<CommandProxy>(); /** * Stores all the tab complete proxies */ private final ArrayList<TabCompleteProxy> m_tabCompletes = new ArrayList<TabCompleteProxy>(); /** * Stores the message to send a player if a route wasn't found for the given command and parameters */ private final HashMap<Command, List<String>> m_noRouteMessages = new HashMap<Command, List<String>>(); //TODO be able to set the defaults /** * Used to build requests */ private final Provider<CommandRequestBuilder> m_requestProvider; /** * Used to inject all parameters needed to the command classes when added */ private final Injector m_injector; private final Logger m_logger; private static final String ROUTE_INFO_SUFFIX = "Details"; @Inject protected DefaultRouter(Provider<CommandRequestBuilder> requestProvider, Injector injector, Logger logger) { m_requestProvider = requestProvider; m_injector = injector; m_logger = logger; } @Override public List<CommandProxy> getCommandProxy(Command command, String parameters) { List<CommandProxy> proxies = new ArrayList<CommandProxy>(); for (CommandProxy proxy : m_commands) { if (command.getName().equals(proxy.getBaseCommand().getName())) { if (proxy.doParamsMatch(parameters)) { proxies.add(proxy); } } } return proxies; } @Override public List<TabCompleteProxy> getTabCompleteProxy(Command command, String parameters) { List<TabCompleteProxy> proxies = new ArrayList<TabCompleteProxy>(); for (TabCompleteProxy proxy : m_tabCompletes) { if (command.getName().equals(proxy.getBaseCommand().getName())) { if (proxy.doParamsMatch(parameters)) { proxies.add(proxy); } } } return proxies; } @Override public void registerCommands(Class klass) throws CommandClassParseException { registerCommands(m_injector.getInstance(klass), false); } protected void checkParameters(Method method) throws InvalidMethodParametersException { if (method.getParameterTypes().length != 1 || !CommandRequest.class.isAssignableFrom(method.getParameterTypes()[0])) { m_logger.log(Level.SEVERE, "Method " + method.getName() + " has incorrect parameters"); throw new InvalidMethodParametersException(); } } @Override public void registerCommands(Object object, boolean inject) throws CommandClassParseException { if (inject) { m_injector.injectMembers(object); } //the class of our object Class klass = object.getClass(); Method[] methods = klass.getDeclaredMethods(); for (Method method : methods) { boolean isCommandMethod = isCommandMethod(method); boolean isTabComplete = isTabComplete(method); if (isCommandMethod || isTabComplete) { //check the method parameters are correct checkParameters(method); if (isTabComplete) { //TODO check return type is correct } //get the method with the details we need Method routeInfo; try { routeInfo = klass.getMethod(method.getName() + ROUTE_INFO_SUFFIX); } catch (NoSuchMethodException e) { m_logger.log(Level.SEVERE, "No method found with the name " + method.getName() + ROUTE_INFO_SUFFIX); throw new DetailsMethodNotFoundException(); } //throws exceptions if not valid checkRouteInfo(routeInfo); //get the details MethodRoute methodRoute; try { methodRoute = (MethodRoute) routeInfo.invoke(object); } catch (Exception e) { e.printStackTrace(); m_logger.log(Level.SEVERE, "Error getting route info from the method " + routeInfo.getName()); throw new CommandClassParseException(); } //some validation PluginCommand command = Bukkit.getPluginCommand(methodRoute.getBaseCommand()); if (command == null) { m_logger.log(Level.SEVERE, "Couldn't find the command " + methodRoute.getBaseCommand() + " for the method " + method.getName()); throw new BaseCommandNotFoundException(); } //register ourselves command.setExecutor(this); command.setTabCompleter(this); DefaultMethodProxy proxy = null; if (isCommandMethod) { CommandProxy commandProxy = new CommandProxy(); m_commands.add(commandProxy); proxy = commandProxy; } if (isTabComplete) { TabCompleteProxy tabCompleteProxy = new TabCompleteProxy(); m_tabCompletes.add(tabCompleteProxy); proxy = tabCompleteProxy; } proxy.setPattern(methodRoute.getRoute()); proxy.setBaseCommand(command); proxy.setCommandMethod(method); proxy.setInstance(object); proxy.setPermission(methodRoute.getPermission()); proxy.setAllowedSenders(methodRoute.getAllowedTypes()); } } } protected void checkTabCompleteReturn(Method method) throws InvalidReturnTypeException { //only allow list returns if(!List.class.isAssignableFrom(method.getReturnType())){ throw new InvalidReturnTypeException(); } Type type = method.getGenericReturnType(); //only allow generics returned if (!(type instanceof ParameterizedType)) { throw new InvalidReturnTypeException(); } //make sure its a string parameter ParameterizedType ptype = (ParameterizedType) type; Type[] types = ptype.getActualTypeArguments(); if (types.length != 1 || !String.class.isAssignableFrom((Class) types[0])) { throw new InvalidReturnTypeException(); } } /** * @param method the method to check * @return true if has commandmethod annotation */ protected boolean isCommandMethod(Method method) { return method.getAnnotation(CommandMethod.class) != null; } /** * @param method the method to check * @return true if has tabcompletion annotation */ protected boolean isTabComplete(Method method) { return method.getAnnotation(TabCompletion.class) != null; } /** * @param method the method to check */ protected void checkRouteInfo(Method method) throws CommandClassParseException { if (null == method.getAnnotation(RouteInfo.class)) { m_logger.log(Level.SEVERE, "Route info method " + method.getName() + " does not have the @RouteInfo annotation"); throw new AnnotationMissingException(); } if (MethodRoute.class.isAssignableFrom(method.getReturnType())) { m_logger.log(Level.SEVERE, "Route info method " + method.getName() + " does not have the correct return type"); throw new InvalidReturnTypeException(); } if (method.getParameterTypes().length != 1 || !CommandRequest.class.isAssignableFrom(method.getParameterTypes()[0])) { m_logger.log(Level.SEVERE, "Route info method " + method.getName() + " does not have the correct parameters"); throw new InvalidMethodParametersException(); } } @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { //Put all of the arguments into a string to match StringBuilder stringBuilder = new StringBuilder(); for (String arg : args) { stringBuilder.append(arg).append(" "); } //get all the proxies that match the route List<CommandProxy> proxies = getCommandProxy(command, stringBuilder.toString()); //no proxies found that matched the route if (proxies.isEmpty()) { List<String> messages = m_noRouteMessages.get(command); //if there isn't any messages send the usage message if (messages.isEmpty()) { return false; } for (String message : messages) { sender.sendMessage(message); } return true; } //trigger all the proxies for (CommandProxy proxy : proxies) { CommandRequestBuilder builder = m_requestProvider.get(); CommandRequest request = builder.setCommand(command) .setArguments(args) .setSender(sender) .build(); try { proxy.trigger(request); } catch (ProxyTriggerException e) { e.getActualException().printStackTrace(); sender.sendMessage(ChatColor.RED + "Error running command, check console for more information"); //TODO translate with API } } //don't print the error message return true; } @Override public List<String> onTabComplete(CommandSender sender, Command command, String label, String[] args) { //Put all of the arguments into a string to match StringBuilder stringBuilder = new StringBuilder(); for (String arg : args) { stringBuilder.append(arg).append(" "); } //get all the proxies that match the route List<TabCompleteProxy> proxies = getTabCompleteProxy(command, stringBuilder.toString()); //no proxies found that matched the route if (proxies == null) { return new ArrayList<String>(0); } //trigger all the proxies and merge them List<String> results = new ArrayList<String>(); for (TabCompleteProxy proxy : proxies) { CommandRequestBuilder builder = m_requestProvider.get(); CommandRequest request = builder.setCommand(command) .setArguments(args) .setSender(sender) //.setMatchResult() TODO .build(); try { results.addAll(proxy.trigger(request)); } catch (ProxyTriggerException e) { e.getActualException().printStackTrace(); sender.sendMessage(ChatColor.RED + "Error with tab completion, check the console for more information"); //TODO translate with API } } return results; } }
remove parameter from routeinfo and add docs
src/main/java/com/publicuhc/commands/routing/DefaultRouter.java
remove parameter from routeinfo and add docs
Java
mit
48f9c9aaa05badfd460d839e7400f25fa96f093b
0
raphydaphy/Vitality
package com.raphydaphy.vitality.block; import java.util.List; import java.util.Random; import javax.annotation.Nullable; import com.raphydaphy.vitality.api.essence.Essence; import com.raphydaphy.vitality.api.essence.MiscEssence; import com.raphydaphy.vitality.registry.ModItems; import com.raphydaphy.vitality.util.ParticleHelper; import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; import net.minecraft.block.properties.PropertyInteger; import net.minecraft.block.state.BlockStateContainer; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.SoundEvents; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumHand; import net.minecraft.util.EnumParticleTypes; import net.minecraft.util.SoundCategory; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.MathHelper; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; public class BlockExtractionCrucible extends BlockBase { public static final PropertyInteger LEVEL = PropertyInteger.create("level", 0, 3); protected static final AxisAlignedBB AABB_LEGS = new AxisAlignedBB(0.0D, 0.0D, 0.0D, 1.0D, 0.3125D, 1.0D); protected static final AxisAlignedBB AABB_WALL_NORTH = new AxisAlignedBB(0.0D, 0.0D, 0.0D, 1.0D, 1.0D, 0.125D); protected static final AxisAlignedBB AABB_WALL_SOUTH = new AxisAlignedBB(0.0D, 0.0D, 0.875D, 1.0D, 1.0D, 1.0D); protected static final AxisAlignedBB AABB_WALL_EAST = new AxisAlignedBB(0.875D, 0.0D, 0.0D, 1.0D, 1.0D, 1.0D); protected static final AxisAlignedBB AABB_WALL_WEST = new AxisAlignedBB(0.0D, 0.0D, 0.0D, 0.125D, 1.0D, 1.0D); public BlockExtractionCrucible() { super(Material.IRON, "life_extraction_crucible"); this.setHardness(3F); this.setResistance(8F); this.setDefaultState(this.blockState.getBaseState().withProperty(LEVEL, Integer.valueOf(0))); } public void addCollisionBoxToList(IBlockState state, World worldIn, BlockPos pos, AxisAlignedBB entityBox, List<AxisAlignedBB> collidingBoxes, @Nullable Entity entityIn) { addCollisionBoxToList(pos, entityBox, collidingBoxes, AABB_LEGS); addCollisionBoxToList(pos, entityBox, collidingBoxes, AABB_WALL_WEST); addCollisionBoxToList(pos, entityBox, collidingBoxes, AABB_WALL_NORTH); addCollisionBoxToList(pos, entityBox, collidingBoxes, AABB_WALL_EAST); addCollisionBoxToList(pos, entityBox, collidingBoxes, AABB_WALL_SOUTH); } public AxisAlignedBB getBoundingBox(IBlockState state, IBlockAccess source, BlockPos pos) { return FULL_BLOCK_AABB; } /** * Used to determine ambient occlusion and culling when rebuilding chunks * for render */ public boolean isOpaqueCube(IBlockState state) { return false; } public boolean isFullCube(IBlockState state) { return false; } public void setWaterLevel(World worldIn, BlockPos pos, IBlockState state, int level) { worldIn.setBlockState(pos, state.withProperty(LEVEL, Integer.valueOf(MathHelper.clamp_int(level, 0, 3))), 2); worldIn.updateComparatorOutputLevel(pos, this); } public boolean onBlockActivated(World worldIn, BlockPos pos, IBlockState state, EntityPlayer playerIn, EnumHand hand, @Nullable ItemStack heldItem, EnumFacing side, float hitX, float hitY, float hitZ) { if (heldItem == null) { return true; } else { int i = ((Integer) state.getValue(LEVEL)); Item item = heldItem.getItem(); if (item == ModItems.VIAL_ATMOSPHERIC) { if (i > 0) { MiscEssence.addEssence(heldItem, 25, true, playerIn, Essence.ATMOSPHERIC, 0); playerIn.swingArm(hand); if (!worldIn.isRemote) { this.setWaterLevel(worldIn, pos, state, i - 1); ParticleHelper.spawnParticles(EnumParticleTypes.DAMAGE_INDICATOR, worldIn, true, pos, 5, 1); worldIn.playSound(null, pos, SoundEvents.ITEM_BUCKET_FILL, SoundCategory.BLOCKS, 1, 1); } } return true; } else if (item == ModItems.VIAL_EMPTY) { if (i > 0) { MiscEssence.addEssence(heldItem, 25, true, playerIn, Essence.ATMOSPHERIC, 0); playerIn.swingArm(hand); if (!worldIn.isRemote) { //playerIn.setHeldItem(hand, vialStack); this.setWaterLevel(worldIn, pos, state, i - 1); ParticleHelper.spawnParticles(EnumParticleTypes.DAMAGE_INDICATOR, worldIn, true, pos, 5, 1); worldIn.playSound(null, pos, SoundEvents.ITEM_BUCKET_FILL, SoundCategory.BLOCKS, 1, 1); } } return true; } } return false; } public void fillWithRain(World worldIn, BlockPos pos) { if (worldIn.rand.nextInt(10) == 1) { float f = worldIn.getBiome(pos).getFloatTemperature(pos); if (worldIn.getBiomeProvider().getTemperatureAtHeight(f, pos.getY()) >= 0.15F) { IBlockState iblockstate = worldIn.getBlockState(pos); if (((Integer) iblockstate.getValue(LEVEL)).intValue() < 3) { worldIn.setBlockState(pos, iblockstate.cycleProperty(LEVEL), 2); } } } } @Nullable public Item getItemDropped(IBlockState state, Random rand, int fortune) { return Item.getItemFromBlock(this); } public ItemStack getItem(World worldIn, BlockPos pos, IBlockState state) { return new ItemStack(this); } public boolean hasComparatorInputOverride(IBlockState state) { return true; } public int getComparatorInputOverride(IBlockState blockState, World worldIn, BlockPos pos) { return ((Integer) blockState.getValue(LEVEL)).intValue(); } /** * Convert the given metadata into a BlockState for this Block */ public IBlockState getStateFromMeta(int meta) { return this.getDefaultState().withProperty(LEVEL, Integer.valueOf(meta)); } /** * Convert the BlockState into the correct metadata value */ public int getMetaFromState(IBlockState state) { return ((Integer) state.getValue(LEVEL)).intValue(); } protected BlockStateContainer createBlockState() { return new BlockStateContainer(this, new IProperty[] { LEVEL }); } public boolean isPassable(IBlockAccess worldIn, BlockPos pos) { return true; } }
src/main/java/com/raphydaphy/vitality/block/BlockExtractionCrucible.java
package com.raphydaphy.vitality.block; import java.util.List; import java.util.Random; import javax.annotation.Nullable; import com.raphydaphy.vitality.api.essence.Essence; import com.raphydaphy.vitality.api.essence.MiscEssence; import com.raphydaphy.vitality.registry.ModItems; import com.raphydaphy.vitality.util.ParticleHelper; import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; import net.minecraft.block.properties.PropertyInteger; import net.minecraft.block.state.BlockStateContainer; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.SoundEvents; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumHand; import net.minecraft.util.EnumParticleTypes; import net.minecraft.util.SoundCategory; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.MathHelper; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; public class BlockExtractionCrucible extends BlockBase { public static final PropertyInteger LEVEL = PropertyInteger.create("level", 0, 3); protected static final AxisAlignedBB AABB_LEGS = new AxisAlignedBB(0.0D, 0.0D, 0.0D, 1.0D, 0.3125D, 1.0D); protected static final AxisAlignedBB AABB_WALL_NORTH = new AxisAlignedBB(0.0D, 0.0D, 0.0D, 1.0D, 1.0D, 0.125D); protected static final AxisAlignedBB AABB_WALL_SOUTH = new AxisAlignedBB(0.0D, 0.0D, 0.875D, 1.0D, 1.0D, 1.0D); protected static final AxisAlignedBB AABB_WALL_EAST = new AxisAlignedBB(0.875D, 0.0D, 0.0D, 1.0D, 1.0D, 1.0D); protected static final AxisAlignedBB AABB_WALL_WEST = new AxisAlignedBB(0.0D, 0.0D, 0.0D, 0.125D, 1.0D, 1.0D); public BlockExtractionCrucible() { super(Material.IRON, "life_extraction_crucible"); this.setHardness(3F); this.setResistance(8F); this.setDefaultState(this.blockState.getBaseState().withProperty(LEVEL, Integer.valueOf(0))); } public void addCollisionBoxToList(IBlockState state, World worldIn, BlockPos pos, AxisAlignedBB entityBox, List<AxisAlignedBB> collidingBoxes, @Nullable Entity entityIn) { addCollisionBoxToList(pos, entityBox, collidingBoxes, AABB_LEGS); addCollisionBoxToList(pos, entityBox, collidingBoxes, AABB_WALL_WEST); addCollisionBoxToList(pos, entityBox, collidingBoxes, AABB_WALL_NORTH); addCollisionBoxToList(pos, entityBox, collidingBoxes, AABB_WALL_EAST); addCollisionBoxToList(pos, entityBox, collidingBoxes, AABB_WALL_SOUTH); } public AxisAlignedBB getBoundingBox(IBlockState state, IBlockAccess source, BlockPos pos) { return FULL_BLOCK_AABB; } /** * Used to determine ambient occlusion and culling when rebuilding chunks * for render */ public boolean isOpaqueCube(IBlockState state) { return false; } public boolean isFullCube(IBlockState state) { return false; } public void setWaterLevel(World worldIn, BlockPos pos, IBlockState state, int level) { worldIn.setBlockState(pos, state.withProperty(LEVEL, Integer.valueOf(MathHelper.clamp_int(level, 0, 3))), 2); worldIn.updateComparatorOutputLevel(pos, this); } public boolean onBlockActivated(World worldIn, BlockPos pos, IBlockState state, EntityPlayer playerIn, EnumHand hand, @Nullable ItemStack heldItem, EnumFacing side, float hitX, float hitY, float hitZ) { if (heldItem == null) { return true; } else { int i = ((Integer) state.getValue(LEVEL)); Item item = heldItem.getItem(); if (item == ModItems.VIAL_ATMOSPHERIC) { if (i > 0) { MiscEssence.addEssence(heldItem, 25, true, playerIn, Essence.ATMOSPHERIC, 0); playerIn.swingArm(hand); if (!worldIn.isRemote) { this.setWaterLevel(worldIn, pos, state, i - 1); ParticleHelper.spawnParticles(EnumParticleTypes.DAMAGE_INDICATOR, worldIn, true, pos, 5, 1); worldIn.playSound(null, pos, SoundEvents.ITEM_BUCKET_FILL, SoundCategory.BLOCKS, 1, 1); } } return true; } else if (item == ModItems.VIAL_EMPTY) { if (i > 0) { ItemStack vialStack = new ItemStack(ModItems.VIAL_ATMOSPHERIC); MiscEssence.addEssence(vialStack, 25, true, playerIn, Essence.ATMOSPHERIC, 0); playerIn.swingArm(hand); if (!worldIn.isRemote) { playerIn.setHeldItem(hand, vialStack); this.setWaterLevel(worldIn, pos, state, i - 1); ParticleHelper.spawnParticles(EnumParticleTypes.DAMAGE_INDICATOR, worldIn, true, pos, 5, 1); worldIn.playSound(null, pos, SoundEvents.ITEM_BUCKET_FILL, SoundCategory.BLOCKS, 1, 1); } } return true; } } return false; } public void fillWithRain(World worldIn, BlockPos pos) { if (worldIn.rand.nextInt(10) == 1) { float f = worldIn.getBiome(pos).getFloatTemperature(pos); if (worldIn.getBiomeProvider().getTemperatureAtHeight(f, pos.getY()) >= 0.15F) { IBlockState iblockstate = worldIn.getBlockState(pos); if (((Integer) iblockstate.getValue(LEVEL)).intValue() < 3) { worldIn.setBlockState(pos, iblockstate.cycleProperty(LEVEL), 2); } } } } @Nullable public Item getItemDropped(IBlockState state, Random rand, int fortune) { return Item.getItemFromBlock(this); } public ItemStack getItem(World worldIn, BlockPos pos, IBlockState state) { return new ItemStack(this); } public boolean hasComparatorInputOverride(IBlockState state) { return true; } public int getComparatorInputOverride(IBlockState blockState, World worldIn, BlockPos pos) { return ((Integer) blockState.getValue(LEVEL)).intValue(); } /** * Convert the given metadata into a BlockState for this Block */ public IBlockState getStateFromMeta(int meta) { return this.getDefaultState().withProperty(LEVEL, Integer.valueOf(meta)); } /** * Convert the BlockState into the correct metadata value */ public int getMetaFromState(IBlockState state) { return ((Integer) state.getValue(LEVEL)).intValue(); } protected BlockStateContainer createBlockState() { return new BlockStateContainer(this, new IProperty[] { LEVEL }); } public boolean isPassable(IBlockAccess worldIn, BlockPos pos) { return true; } }
tocched stuff
src/main/java/com/raphydaphy/vitality/block/BlockExtractionCrucible.java
tocched stuff
Java
mit
3cc8703b6d3c6fea32e123ae43c4cc4ead3ae4e2
0
tfiskgul/mux2fs,tfiskgul/mux2fs
/* MIT License Copyright (c) 2017 Carl-Frederik Hallberg Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package se.tfiskgul.mux2fs.fs.mirror; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; import static org.mockito.AdditionalMatchers.gt; import static org.mockito.Matchers.any; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import static se.tfiskgul.mux2fs.Constants.SUCCESS; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import org.junit.Test; import org.mockito.ArgumentCaptor; import ru.serce.jnrfuse.ErrorCodes; import se.tfiskgul.mux2fs.fs.base.DirectoryFiller; import se.tfiskgul.mux2fs.fs.base.FileHandleFiller; import se.tfiskgul.mux2fs.fs.base.StatFiller; public class MirrorFsTest extends MirrorFsFixture { @Test public void testGetAttr() throws Exception { // Given StatFiller stat = mock(StatFiller.class); when(fileSystem.getPath(mirrorRoot.toString(), "/")).thenReturn(mirrorRoot); // When int result = fs.getattr("/", stat); // Then assertThat(result).isEqualTo(SUCCESS); verify(stat).stat(mirrorRoot); } @Test public void testGetAttrSubDir() throws Exception { // Given StatFiller stat = mock(StatFiller.class); Path foo = mockPath("/foo"); // When int result = fs.getattr("/foo", stat); // Then assertThat(result).isEqualTo(SUCCESS); verify(stat).stat(foo); } @Test public void testAllErrorsForGetAttr() throws Exception { testAllErrors(this::getAttr); } private void getAttr(ExpectedResult expected) throws Exception { // Given StatFiller stat = mock(StatFiller.class); Path foo = mockPath("/foo"); when(stat.stat(foo)).thenThrow(expected.exception()); // When int result = fs.getattr("/foo", stat); // Then assertThat(result).isEqualTo(expected.value()); } @Test public void testReadDir() throws Exception { // Given Path foo = mockPath("foo"); Path bar = mockPath("bar"); mockDirectoryStream(mirrorRoot, foo, bar); DirectoryFiller filler = mock(DirectoryFiller.class); // When int result = fs.readdir("/", filler); // Then assertThat(result).isEqualTo(SUCCESS); verify(fileSystem.provider()).newDirectoryStream(eq(mirrorRoot), any()); verify(filler).add(".", mirrorRoot); verify(filler).add("..", mirrorRoot); verify(filler).add("foo", foo); verify(filler).add("bar", bar); verifyNoMoreInteractions(filler); } @Test public void testAllErrorsForReadDir() throws Exception { testAllErrors(this::readDir); } @Test public void testReadDirStopsEnumerationOnResourceExhaustion() throws Exception { // Given Path foo = mockPath("foo"); Path bar = mockPath("bar"); mockDirectoryStream(mirrorRoot, foo, bar); DirectoryFiller filler = mock(DirectoryFiller.class); when(filler.add("foo", foo)).thenReturn(1); // Signify out of buffer memory, stop enumeration please // When int result = fs.readdir("/", filler); // Then assertThat(result).isEqualTo(SUCCESS); verify(fileSystem.provider()).newDirectoryStream(eq(mirrorRoot), any()); verify(filler).add(".", mirrorRoot); verify(filler).add("..", mirrorRoot); verify(filler).add("foo", foo); verifyNoMoreInteractions(filler); // No bar is added, enumeration stopped } @Test public void testReadDirErrorOnFillDot() throws Exception { // Given mockDirectoryStream(mirrorRoot); DirectoryFiller filler = mock(DirectoryFiller.class); when(filler.add(eq("."), any())).thenThrow(new IOException()); // When int result = fs.readdir("/", filler); // Then assertThat(result).isEqualTo(SUCCESS); verify(fileSystem.provider()).newDirectoryStream(eq(mirrorRoot), any()); verify(filler).add(".", mirrorRoot); verify(filler).add("..", mirrorRoot); verifyNoMoreInteractions(filler); } @Test public void testReadDirErrorOnFillDotDot() throws Exception { // Given mockDirectoryStream(mirrorRoot); DirectoryFiller filler = mock(DirectoryFiller.class); when(filler.add(eq(".."), any())).thenThrow(new IOException()); // When int result = fs.readdir("/", filler); // Then assertThat(result).isEqualTo(SUCCESS); verify(fileSystem.provider()).newDirectoryStream(eq(mirrorRoot), any()); verify(filler).add(".", mirrorRoot); verify(filler).add("..", mirrorRoot); verifyNoMoreInteractions(filler); } @Test public void testGetFileNameOnNullPathIsEmpty() throws Exception { assertThat(new MirrorFs(mirrorRoot).getFileName(null)).isEmpty(); } @Test public void testGetFileNameOnNullFileNameIsEmpty() throws Exception { assertThat(new MirrorFs(mirrorRoot).getFileName(mock(Path.class))).isEmpty(); } @Test public void testReadDirContinuesEnumerationOnError() throws Exception { // Given Path foo = mockPath("foo"); Path bar = mockPath("bar"); mockDirectoryStream(mirrorRoot, foo, bar); DirectoryFiller filler = mock(DirectoryFiller.class); when(filler.add("foo", foo)).thenThrow(new IOException()); // When int result = fs.readdir("/", filler); // Then assertThat(result).isEqualTo(SUCCESS); verify(fileSystem.provider()).newDirectoryStream(eq(mirrorRoot), any()); verify(filler).add(".", mirrorRoot); verify(filler).add("..", mirrorRoot); verify(filler).add("foo", foo); verify(filler).add("bar", bar); verifyNoMoreInteractions(filler); } private void readDir(ExpectedResult expected) throws IOException { // Given when(fileSystem.provider().newDirectoryStream(eq(mirrorRoot), any())).thenThrow(expected.exception()); DirectoryFiller filler = mock(DirectoryFiller.class); // When int result = fs.readdir("/", filler); // Then assertThat(result).isEqualTo(expected.value()); } @Test public void testOpen() throws Exception { // Given FileHandleFiller filler = mock(FileHandleFiller.class); Path fooBar = mockPath("foo.bar"); when(fileSystem.provider().newFileChannel(eq(fooBar), eq(set(StandardOpenOption.READ)))).thenReturn(mock(FileChannel.class)); // When int result = fs.open("foo.bar", filler); // Then assertThat(result).isEqualTo(SUCCESS); verify(filler).setFileHandle(gt(0)); verifyNoMoreInteractions(filler); verify(fileSystem.provider()).newFileChannel(eq(fooBar), eq(set(StandardOpenOption.READ))); verifyNoMoreInteractions(fileSystem.provider()); } @Test public void testOpenFileHandleIsUnique() throws Exception { // Given FileHandleFiller filler = mock(FileHandleFiller.class); ArgumentCaptor<Integer> handleCaptor = ArgumentCaptor.forClass(Integer.class); doNothing().when(filler).setFileHandle(handleCaptor.capture()); Path fooBar = mockPath("foo.bar"); when(fileSystem.provider().newFileChannel(eq(fooBar), eq(set(StandardOpenOption.READ)))).thenReturn(mock(FileChannel.class)); // When int result = fs.open("foo.bar", filler); result += fs.open("foo.bar", filler); result += fs.open("foo.bar", filler); // Then assertThat(result).isEqualTo(SUCCESS); verify(filler, times(3)).setFileHandle(gt(0)); verifyNoMoreInteractions(filler); verify(fileSystem.provider(), times(3)).newFileChannel(eq(fooBar), eq(set(StandardOpenOption.READ))); verifyNoMoreInteractions(fileSystem.provider()); assertThat(handleCaptor.getAllValues()).hasSize(3).doesNotHaveDuplicates(); } @Test public void testAllErrorsForOpen() throws Exception { testAllErrors(this::open); } private void open(ExpectedResult expected) throws IOException { // Given reset(fileSystem.provider()); FileHandleFiller filler = mock(FileHandleFiller.class); when(fileSystem.provider().newFileChannel(any(), eq(set(StandardOpenOption.READ)))).thenThrow(expected.exception()); // When int result = fs.open("/", filler); // Then assertThat(result).isEqualTo(expected.value()); verifyNoMoreInteractions(filler); verify(fileSystem.provider()).newFileChannel(any(), eq(set(StandardOpenOption.READ))); verifyNoMoreInteractions(fileSystem.provider()); } @Test public void testReleaseNegativeFileHandle() { // Given // When int result = fs.release("foo.bar", -23); // Then assertThat(result).isEqualTo(-ErrorCodes.EBADF()); } @Test public void testReleaseNonOpenedFileHandle() { // Given // When int result = fs.release("foo.bar", 23); // Then assertThat(result).isEqualTo(-ErrorCodes.EBADF()); } @Test public void testReadBadFileDescriptor() { // Given // When int result = fs.read("foo.bar", empty(), 10, 1234, 567); // Then assertThat(result).isEqualTo(-ErrorCodes.EBADF()); } @Test public void testRead() throws Exception { // Given FileHandleFiller filler = mock(FileHandleFiller.class); ArgumentCaptor<Integer> handleCaptor = ArgumentCaptor.forClass(Integer.class); doNothing().when(filler).setFileHandle(handleCaptor.capture()); Path fooBar = mockPath("foo.bar"); FileChannel fileChannel = mock(FileChannel.class); when(fileSystem.provider().newFileChannel(eq(fooBar), eq(set(StandardOpenOption.READ)))).thenReturn(fileChannel); fs.open("foo.bar", filler); Integer fileHandle = handleCaptor.getValue(); ArgumentCaptor<ByteBuffer> bufferCaptor = ArgumentCaptor.forClass(ByteBuffer.class); when(fileChannel.read(bufferCaptor.capture(), eq(1234L))).thenReturn(10); // When int result = fs.read("foo.bar", (data) -> assertThat(data).hasSize(10), 10, 1234L, fileHandle); // Then assertThat(result).isEqualTo(10); verify(fileChannel).read(any(), eq(1234L)); verifyNoMoreInteractions(fileChannel); assertThat(bufferCaptor.getValue().limit()).isEqualTo(10); } @Test public void testReadEndOfFile() throws Exception { // Given FileHandleFiller filler = mock(FileHandleFiller.class); ArgumentCaptor<Integer> handleCaptor = ArgumentCaptor.forClass(Integer.class); doNothing().when(filler).setFileHandle(handleCaptor.capture()); Path fooBar = mockPath("foo.bar"); FileChannel fileChannel = mock(FileChannel.class); when(fileSystem.provider().newFileChannel(eq(fooBar), eq(set(StandardOpenOption.READ)))).thenReturn(fileChannel); fs.open("foo.bar", filler); Integer fileHandle = handleCaptor.getValue(); ArgumentCaptor<ByteBuffer> bufferCaptor = ArgumentCaptor.forClass(ByteBuffer.class); when(fileChannel.read(bufferCaptor.capture(), eq(1234L))).thenReturn(0); // When int result = fs.read("foo.bar", (data) -> fail("No data should be read"), 10, 1234L, fileHandle); // Then assertThat(result).isEqualTo(SUCCESS); verify(fileChannel).read(any(), eq(1234L)); verifyNoMoreInteractions(fileChannel); assertThat(bufferCaptor.getValue().limit()).isEqualTo(10); } @Test public void testAllErrorsForRead() throws Exception { testAllErrors(this::read); } private void read(ExpectedResult expectedResult) throws Exception { // Given FileHandleFiller filler = mock(FileHandleFiller.class); ArgumentCaptor<Integer> handleCaptor = ArgumentCaptor.forClass(Integer.class); doNothing().when(filler).setFileHandle(handleCaptor.capture()); Path fooBar = mockPath("foo.bar"); FileChannel fileChannel = mock(FileChannel.class); when(fileSystem.provider().newFileChannel(eq(fooBar), eq(set(StandardOpenOption.READ)))).thenReturn(fileChannel); fs.open("foo.bar", filler); Integer fileHandle = handleCaptor.getValue(); ArgumentCaptor<ByteBuffer> bufferCaptor = ArgumentCaptor.forClass(ByteBuffer.class); when(fileChannel.read(bufferCaptor.capture(), eq(1234L))).thenThrow(expectedResult.exception()); // When int result = fs.read("foo.bar", (data) -> fail("No data should be read"), 10, 1234L, fileHandle); // Then assertThat(result).isEqualTo(expectedResult.value()); verify(fileChannel).read(any(), eq(1234L)); verifyNoMoreInteractions(fileChannel); assertThat(bufferCaptor.getValue().limit()).isEqualTo(10); } @Test public void testDestroy() { fs.destroy(); } @Test public void testReadLink() throws Exception { // Given Path fooBar = mockPath("foo.bar"); Path target = mockPath("bar.foo"); when(fileSystem.provider().readSymbolicLink(fooBar)).thenReturn(target); // When int result = fs.readLink("foo.bar", (name) -> assertThat(name).isEqualTo("bar.foo"), 1024); // Then assertThat(result).isEqualTo(SUCCESS); } @Test public void testAllErrorsForReadLink() throws Exception { testAllErrors(this::readLink); } private void readLink(ExpectedResult expectedResult) throws Exception { // Given Path fooBar = mockPath("foo.bar"); when(fileSystem.provider().readSymbolicLink(fooBar)).thenThrow(expectedResult.exception()); // When int result = fs.readLink("foo.bar", (name) -> fail(), 1024); // Then assertThat(result).isEqualTo(expectedResult.value()); } @Test public void testReadLinkLongNameIsTruncated() throws Exception { // Given Path fooBar = mockPath("foo.bar"); Path target = mockPath("ThisIsALongName"); when(fileSystem.provider().readSymbolicLink(fooBar)).thenReturn(target); // When int result = fs.readLink("foo.bar", (name) -> assertThat(name).isEqualTo("ThisI"), 5); // Then assertThat(result).isEqualTo(SUCCESS); } @Test public void testReleaseClosesOpenFileChannel() throws Exception { // Given FileHandleFiller filler = mock(FileHandleFiller.class); ArgumentCaptor<Integer> handleCaptor = ArgumentCaptor.forClass(Integer.class); doNothing().when(filler).setFileHandle(handleCaptor.capture()); Path fooBar = mockPath(mirrorRoot, "foo.bar"); FileChannel fileChannel = mock(FileChannel.class); when(fileSystem.provider().newFileChannel(eq(fooBar), eq(set(StandardOpenOption.READ)))).thenReturn(fileChannel); fs.open("foo.bar", filler); // When int result = fs.release("foo.bar", handleCaptor.getValue()); // Then assertThat(result).isEqualTo(SUCCESS); verify(fileChannelCloser).close(fileChannel); verifyNoMoreInteractions(fileChannel); } @Test public void testRelease() throws Exception { // Given FileHandleFiller filler = mock(FileHandleFiller.class); ArgumentCaptor<Integer> handleCaptor = ArgumentCaptor.forClass(Integer.class); doNothing().when(filler).setFileHandle(handleCaptor.capture()); Path fooBar = mockPath(mirrorRoot, "foo.bar"); when(fileSystem.provider().newFileChannel(eq(fooBar), eq(set(StandardOpenOption.READ)))).thenReturn(mock(FileChannel.class)); fs.open("foo.bar", filler); // When int result = fs.release("foo.bar", handleCaptor.getValue()); // Then assertThat(result).isEqualTo(SUCCESS); } @Test public void testReleaseTwice() throws Exception { // Given FileHandleFiller filler = mock(FileHandleFiller.class); ArgumentCaptor<Integer> handleCaptor = ArgumentCaptor.forClass(Integer.class); doNothing().when(filler).setFileHandle(handleCaptor.capture()); Path fooBar = mockPath(mirrorRoot, "foo.bar"); when(fileSystem.provider().newFileChannel(eq(fooBar), eq(set(StandardOpenOption.READ)))).thenReturn(mock(FileChannel.class)); fs.open("foo.bar", filler); fs.release("foo.bar", handleCaptor.getValue()); // When int result = fs.release("foo.bar", handleCaptor.getValue()); // Then assertThat(result).isEqualTo(-ErrorCodes.EBADF()); } @Test public void testDestroyClosesFileChannels() throws Exception { // Given FileChannel foo = mockAndOpen("foo"); FileChannel bar = mockAndOpen("bar"); // When fs.destroy(); // Then verify(fileChannelCloser).close(foo); verifyNoMoreInteractions(foo); verify(fileChannelCloser).close(bar); verifyNoMoreInteractions(bar); } }
core/src/test/java/se/tfiskgul/mux2fs/fs/mirror/MirrorFsTest.java
/* MIT License Copyright (c) 2017 Carl-Frederik Hallberg Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package se.tfiskgul.mux2fs.fs.mirror; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; import static org.mockito.AdditionalMatchers.gt; import static org.mockito.Matchers.any; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import static se.tfiskgul.mux2fs.Constants.SUCCESS; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.file.AccessDeniedException; import java.nio.file.NoSuchFileException; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import org.junit.Test; import org.mockito.ArgumentCaptor; import ru.serce.jnrfuse.ErrorCodes; import se.tfiskgul.mux2fs.fs.base.DirectoryFiller; import se.tfiskgul.mux2fs.fs.base.FileHandleFiller; import se.tfiskgul.mux2fs.fs.base.StatFiller; public class MirrorFsTest extends MirrorFsFixture { @Test public void testGetAttr() throws Exception { // Given StatFiller stat = mock(StatFiller.class); when(fileSystem.getPath(mirrorRoot.toString(), "/")).thenReturn(mirrorRoot); // When int result = fs.getattr("/", stat); // Then assertThat(result).isEqualTo(SUCCESS); verify(stat).stat(mirrorRoot); } @Test public void testGetAttrSubDir() throws Exception { // Given StatFiller stat = mock(StatFiller.class); Path foo = mockPath("/foo"); // When int result = fs.getattr("/foo", stat); // Then assertThat(result).isEqualTo(SUCCESS); verify(stat).stat(foo); } @Test public void testAllErrorsForGetAttr() throws Exception { testAllErrors(this::getAttr); } private void getAttr(ExpectedResult expected) throws Exception { // Given StatFiller stat = mock(StatFiller.class); Path foo = mockPath("/foo"); when(stat.stat(foo)).thenThrow(expected.exception()); // When int result = fs.getattr("/foo", stat); // Then assertThat(result).isEqualTo(expected.value()); } @Test public void testReadDir() throws Exception { // Given Path foo = mockPath("foo"); Path bar = mockPath("bar"); mockDirectoryStream(mirrorRoot, foo, bar); DirectoryFiller filler = mock(DirectoryFiller.class); // When int result = fs.readdir("/", filler); // Then assertThat(result).isEqualTo(SUCCESS); verify(fileSystem.provider()).newDirectoryStream(eq(mirrorRoot), any()); verify(filler).add(".", mirrorRoot); verify(filler).add("..", mirrorRoot); verify(filler).add("foo", foo); verify(filler).add("bar", bar); verifyNoMoreInteractions(filler); } @Test public void testAllErrorsForReadDir() throws Exception { testAllErrors(this::readDir); } @Test public void testReadDirStopsEnumerationOnResourceExhaustion() throws Exception { // Given Path foo = mockPath("foo"); Path bar = mockPath("bar"); mockDirectoryStream(mirrorRoot, foo, bar); DirectoryFiller filler = mock(DirectoryFiller.class); when(filler.add("foo", foo)).thenReturn(1); // Signify out of buffer memory, stop enumeration please // When int result = fs.readdir("/", filler); // Then assertThat(result).isEqualTo(SUCCESS); verify(fileSystem.provider()).newDirectoryStream(eq(mirrorRoot), any()); verify(filler).add(".", mirrorRoot); verify(filler).add("..", mirrorRoot); verify(filler).add("foo", foo); verifyNoMoreInteractions(filler); // No bar is added, enumeration stopped } @Test public void testReadDirErrorOnFillDot() throws Exception { // Given mockDirectoryStream(mirrorRoot); DirectoryFiller filler = mock(DirectoryFiller.class); when(filler.add(eq("."), any())).thenThrow(new IOException()); // When int result = fs.readdir("/", filler); // Then assertThat(result).isEqualTo(SUCCESS); verify(fileSystem.provider()).newDirectoryStream(eq(mirrorRoot), any()); verify(filler).add(".", mirrorRoot); verify(filler).add("..", mirrorRoot); verifyNoMoreInteractions(filler); } @Test public void testReadDirErrorOnFillDotDot() throws Exception { // Given mockDirectoryStream(mirrorRoot); DirectoryFiller filler = mock(DirectoryFiller.class); when(filler.add(eq(".."), any())).thenThrow(new IOException()); // When int result = fs.readdir("/", filler); // Then assertThat(result).isEqualTo(SUCCESS); verify(fileSystem.provider()).newDirectoryStream(eq(mirrorRoot), any()); verify(filler).add(".", mirrorRoot); verify(filler).add("..", mirrorRoot); verifyNoMoreInteractions(filler); } @Test public void testGetFileNameOnNullPathIsEmpty() throws Exception { assertThat(new MirrorFs(mirrorRoot).getFileName(null)).isEmpty(); } @Test public void testGetFileNameOnNullFileNameIsEmpty() throws Exception { assertThat(new MirrorFs(mirrorRoot).getFileName(mock(Path.class))).isEmpty(); } @Test public void testReadDirContinuesEnumerationOnError() throws Exception { // Given Path foo = mockPath("foo"); Path bar = mockPath("bar"); mockDirectoryStream(mirrorRoot, foo, bar); DirectoryFiller filler = mock(DirectoryFiller.class); when(filler.add("foo", foo)).thenThrow(new IOException()); // When int result = fs.readdir("/", filler); // Then assertThat(result).isEqualTo(SUCCESS); verify(fileSystem.provider()).newDirectoryStream(eq(mirrorRoot), any()); verify(filler).add(".", mirrorRoot); verify(filler).add("..", mirrorRoot); verify(filler).add("foo", foo); verify(filler).add("bar", bar); verifyNoMoreInteractions(filler); } private void readDir(ExpectedResult expected) throws IOException { // Given when(fileSystem.provider().newDirectoryStream(eq(mirrorRoot), any())).thenThrow(expected.exception()); DirectoryFiller filler = mock(DirectoryFiller.class); // When int result = fs.readdir("/", filler); // Then assertThat(result).isEqualTo(expected.value()); } @Test public void testOpen() throws Exception { // Given FileHandleFiller filler = mock(FileHandleFiller.class); Path fooBar = mockPath("foo.bar"); when(fileSystem.provider().newFileChannel(eq(fooBar), eq(set(StandardOpenOption.READ)))).thenReturn(mock(FileChannel.class)); // When int result = fs.open("foo.bar", filler); // Then assertThat(result).isEqualTo(SUCCESS); verify(filler).setFileHandle(gt(0)); verifyNoMoreInteractions(filler); verify(fileSystem.provider()).newFileChannel(eq(fooBar), eq(set(StandardOpenOption.READ))); verifyNoMoreInteractions(fileSystem.provider()); } @Test public void testOpenFileHandleIsUnique() throws Exception { // Given FileHandleFiller filler = mock(FileHandleFiller.class); ArgumentCaptor<Integer> handleCaptor = ArgumentCaptor.forClass(Integer.class); doNothing().when(filler).setFileHandle(handleCaptor.capture()); Path fooBar = mockPath("foo.bar"); when(fileSystem.provider().newFileChannel(eq(fooBar), eq(set(StandardOpenOption.READ)))).thenReturn(mock(FileChannel.class)); // When int result = fs.open("foo.bar", filler); result += fs.open("foo.bar", filler); result += fs.open("foo.bar", filler); // Then assertThat(result).isEqualTo(SUCCESS); verify(filler, times(3)).setFileHandle(gt(0)); verifyNoMoreInteractions(filler); verify(fileSystem.provider(), times(3)).newFileChannel(eq(fooBar), eq(set(StandardOpenOption.READ))); verifyNoMoreInteractions(fileSystem.provider()); assertThat(handleCaptor.getAllValues()).hasSize(3).doesNotHaveDuplicates(); } @Test public void testOpenNoPerm() throws Exception { testOpenThrow(-ErrorCodes.EPERM(), new AccessDeniedException(null)); } @Test public void testOpenNoSuchFile() throws Exception { testOpenThrow(-ErrorCodes.ENOENT(), new NoSuchFileException(null)); } @Test public void testOpenIoError() throws Exception { testOpenThrow(-ErrorCodes.EIO(), new IOException()); } private void testOpenThrow(int expected, IOException exception) throws IOException { // Given FileHandleFiller filler = mock(FileHandleFiller.class); when(fileSystem.provider().newFileChannel(any(), eq(set(StandardOpenOption.READ)))).thenThrow(exception); // When int result = fs.open("/", filler); // Then assertThat(result).isEqualTo(expected); verifyNoMoreInteractions(filler); verify(fileSystem.provider()).newFileChannel(any(), eq(set(StandardOpenOption.READ))); verifyNoMoreInteractions(fileSystem.provider()); } @Test public void testReleaseNegativeFileHandle() { // Given // When int result = fs.release("foo.bar", -23); // Then assertThat(result).isEqualTo(-ErrorCodes.EBADF()); } @Test public void testReleaseNonOpenedFileHandle() { // Given // When int result = fs.release("foo.bar", 23); // Then assertThat(result).isEqualTo(-ErrorCodes.EBADF()); } @Test public void testReadBadFileDescriptor() { // Given // When int result = fs.read("foo.bar", empty(), 10, 1234, 567); // Then assertThat(result).isEqualTo(-ErrorCodes.EBADF()); } @Test public void testRead() throws Exception { // Given FileHandleFiller filler = mock(FileHandleFiller.class); ArgumentCaptor<Integer> handleCaptor = ArgumentCaptor.forClass(Integer.class); doNothing().when(filler).setFileHandle(handleCaptor.capture()); Path fooBar = mockPath("foo.bar"); FileChannel fileChannel = mock(FileChannel.class); when(fileSystem.provider().newFileChannel(eq(fooBar), eq(set(StandardOpenOption.READ)))).thenReturn(fileChannel); fs.open("foo.bar", filler); Integer fileHandle = handleCaptor.getValue(); ArgumentCaptor<ByteBuffer> bufferCaptor = ArgumentCaptor.forClass(ByteBuffer.class); when(fileChannel.read(bufferCaptor.capture(), eq(1234L))).thenReturn(10); // When int result = fs.read("foo.bar", (data) -> assertThat(data).hasSize(10), 10, 1234L, fileHandle); // Then assertThat(result).isEqualTo(10); verify(fileChannel).read(any(), eq(1234L)); verifyNoMoreInteractions(fileChannel); assertThat(bufferCaptor.getValue().limit()).isEqualTo(10); } @Test public void testReadEndOfFile() throws Exception { // Given FileHandleFiller filler = mock(FileHandleFiller.class); ArgumentCaptor<Integer> handleCaptor = ArgumentCaptor.forClass(Integer.class); doNothing().when(filler).setFileHandle(handleCaptor.capture()); Path fooBar = mockPath("foo.bar"); FileChannel fileChannel = mock(FileChannel.class); when(fileSystem.provider().newFileChannel(eq(fooBar), eq(set(StandardOpenOption.READ)))).thenReturn(fileChannel); fs.open("foo.bar", filler); Integer fileHandle = handleCaptor.getValue(); ArgumentCaptor<ByteBuffer> bufferCaptor = ArgumentCaptor.forClass(ByteBuffer.class); when(fileChannel.read(bufferCaptor.capture(), eq(1234L))).thenReturn(0); // When int result = fs.read("foo.bar", (data) -> fail("No data should be read"), 10, 1234L, fileHandle); // Then assertThat(result).isEqualTo(SUCCESS); verify(fileChannel).read(any(), eq(1234L)); verifyNoMoreInteractions(fileChannel); assertThat(bufferCaptor.getValue().limit()).isEqualTo(10); } @Test public void testAllErrorsForRead() throws Exception { testAllErrors(this::read); } private void read(ExpectedResult expectedResult) throws Exception { // Given FileHandleFiller filler = mock(FileHandleFiller.class); ArgumentCaptor<Integer> handleCaptor = ArgumentCaptor.forClass(Integer.class); doNothing().when(filler).setFileHandle(handleCaptor.capture()); Path fooBar = mockPath("foo.bar"); FileChannel fileChannel = mock(FileChannel.class); when(fileSystem.provider().newFileChannel(eq(fooBar), eq(set(StandardOpenOption.READ)))).thenReturn(fileChannel); fs.open("foo.bar", filler); Integer fileHandle = handleCaptor.getValue(); ArgumentCaptor<ByteBuffer> bufferCaptor = ArgumentCaptor.forClass(ByteBuffer.class); when(fileChannel.read(bufferCaptor.capture(), eq(1234L))).thenThrow(expectedResult.exception()); // When int result = fs.read("foo.bar", (data) -> fail("No data should be read"), 10, 1234L, fileHandle); // Then assertThat(result).isEqualTo(expectedResult.value()); verify(fileChannel).read(any(), eq(1234L)); verifyNoMoreInteractions(fileChannel); assertThat(bufferCaptor.getValue().limit()).isEqualTo(10); } @Test public void testDestroy() { fs.destroy(); } @Test public void testReadLink() throws Exception { // Given Path fooBar = mockPath("foo.bar"); Path target = mockPath("bar.foo"); when(fileSystem.provider().readSymbolicLink(fooBar)).thenReturn(target); // When int result = fs.readLink("foo.bar", (name) -> assertThat(name).isEqualTo("bar.foo"), 1024); // Then assertThat(result).isEqualTo(SUCCESS); } @Test public void testAllErrorsForReadLink() throws Exception { testAllErrors(this::readLink); } private void readLink(ExpectedResult expectedResult) throws Exception { // Given Path fooBar = mockPath("foo.bar"); when(fileSystem.provider().readSymbolicLink(fooBar)).thenThrow(expectedResult.exception()); // When int result = fs.readLink("foo.bar", (name) -> fail(), 1024); // Then assertThat(result).isEqualTo(expectedResult.value()); } @Test public void testReadLinkLongNameIsTruncated() throws Exception { // Given Path fooBar = mockPath("foo.bar"); Path target = mockPath("ThisIsALongName"); when(fileSystem.provider().readSymbolicLink(fooBar)).thenReturn(target); // When int result = fs.readLink("foo.bar", (name) -> assertThat(name).isEqualTo("ThisI"), 5); // Then assertThat(result).isEqualTo(SUCCESS); } @Test public void testReleaseClosesOpenFileChannel() throws Exception { // Given FileHandleFiller filler = mock(FileHandleFiller.class); ArgumentCaptor<Integer> handleCaptor = ArgumentCaptor.forClass(Integer.class); doNothing().when(filler).setFileHandle(handleCaptor.capture()); Path fooBar = mockPath(mirrorRoot, "foo.bar"); FileChannel fileChannel = mock(FileChannel.class); when(fileSystem.provider().newFileChannel(eq(fooBar), eq(set(StandardOpenOption.READ)))).thenReturn(fileChannel); fs.open("foo.bar", filler); // When int result = fs.release("foo.bar", handleCaptor.getValue()); // Then assertThat(result).isEqualTo(SUCCESS); verify(fileChannelCloser).close(fileChannel); verifyNoMoreInteractions(fileChannel); } @Test public void testRelease() throws Exception { // Given FileHandleFiller filler = mock(FileHandleFiller.class); ArgumentCaptor<Integer> handleCaptor = ArgumentCaptor.forClass(Integer.class); doNothing().when(filler).setFileHandle(handleCaptor.capture()); Path fooBar = mockPath(mirrorRoot, "foo.bar"); when(fileSystem.provider().newFileChannel(eq(fooBar), eq(set(StandardOpenOption.READ)))).thenReturn(mock(FileChannel.class)); fs.open("foo.bar", filler); // When int result = fs.release("foo.bar", handleCaptor.getValue()); // Then assertThat(result).isEqualTo(SUCCESS); } @Test public void testReleaseTwice() throws Exception { // Given FileHandleFiller filler = mock(FileHandleFiller.class); ArgumentCaptor<Integer> handleCaptor = ArgumentCaptor.forClass(Integer.class); doNothing().when(filler).setFileHandle(handleCaptor.capture()); Path fooBar = mockPath(mirrorRoot, "foo.bar"); when(fileSystem.provider().newFileChannel(eq(fooBar), eq(set(StandardOpenOption.READ)))).thenReturn(mock(FileChannel.class)); fs.open("foo.bar", filler); fs.release("foo.bar", handleCaptor.getValue()); // When int result = fs.release("foo.bar", handleCaptor.getValue()); // Then assertThat(result).isEqualTo(-ErrorCodes.EBADF()); } @Test public void testDestroyClosesFileChannels() throws Exception { // Given FileChannel foo = mockAndOpen("foo"); FileChannel bar = mockAndOpen("bar"); // When fs.destroy(); // Then verify(fileChannelCloser).close(foo); verifyNoMoreInteractions(foo); verify(fileChannelCloser).close(bar); verifyNoMoreInteractions(bar); } }
MirrorFs: Compacted negative open() tests.
core/src/test/java/se/tfiskgul/mux2fs/fs/mirror/MirrorFsTest.java
MirrorFs: Compacted negative open() tests.
Java
mit
10e7d58f5df2dad67c3a93abd9d82d89d99fa3d0
0
ganddev/breminale_android_mvvm,ganddev/breminale_android_mvvm
package de.ahlfeld.breminale.viewmodel; import android.content.Context; import android.databinding.ObservableBoolean; import android.databinding.ObservableField; import android.databinding.ObservableInt; import android.media.AudioManager; import android.media.MediaPlayer; import android.os.Handler; import android.util.Log; import android.view.View; import java.io.IOException; import java.util.List; import java.util.concurrent.TimeUnit; import de.ahlfeld.breminale.R; import de.ahlfeld.breminale.models.SoundcloudTrack; import de.ahlfeld.breminale.models.SoundcloudUser; import de.ahlfeld.breminale.networking.SoundcloudService; import rx.Observable; import rx.Subscriber; import rx.Subscription; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; /** * Created by bjornahlfeld on 03.05.16. */ public class SoundcloudViewModel implements ViewModel, MediaPlayer.OnCompletionListener { private static final String TAG = SoundcloudViewModel.class.getSimpleName(); private final Context mContext; public ObservableField<String> soundCloudArtist; public ObservableField<String> currentTrack; public ObservableBoolean isPlaying; public ObservableInt max; private Subscription mSoundclouduserSubscription; private SoundcloudUser mSoundcloudUser; private Subscription mSoundcloudTracksSusbcriptions; private Subscription progressSubscription; private List<SoundcloudTrack> mSoundcloudTracks; private MediaPlayer mPlayer; private Handler myHandler; private static final String CLIENT_ID = "?client_id=469443570702bcc59666de5950139327"; private int currentPlayingTrack; public ObservableInt progress; public SoundcloudViewModel(Context ctx, long soundcloudUserId) { mContext = ctx.getApplicationContext(); soundCloudArtist = new ObservableField<>(""); currentTrack = new ObservableField<>(""); getSoundcloudUsername(soundcloudUserId); getTracksForSoundcloudUser(soundcloudUserId); mPlayer = new MediaPlayer(); mPlayer.setOnCompletionListener(this); mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); currentPlayingTrack = 0; max = new ObservableInt(0); progress = new ObservableInt(0); isPlaying = new ObservableBoolean(false); myHandler = new Handler(); } public void prepareProgress() { Observable.interval(16, TimeUnit.MILLISECONDS) .map(y -> { Log.d(TAG, "tick: " + y); progress.set(mPlayer.getCurrentPosition()); return null; }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<Object>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { } @Override public void onNext(Object o) { Log.d(TAG, "object" + o.toString()); } }); } private void getTracksForSoundcloudUser(long soundcloudUserId) { Observable<List<SoundcloudTrack>> call = SoundcloudService.Factory.build().getTracksForUser(soundcloudUserId); mSoundcloudTracksSusbcriptions = call.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()) .subscribe(new Subscriber<List<SoundcloudTrack>>() { @Override public void onCompleted() { if (!mSoundcloudTracks.isEmpty()) { currentTrack.set(mSoundcloudTracks.get(0).getTitle()); setDataSourceAndPreparePlayer(); } else { currentTrack.set(mContext.getString(R.string.empty_soundcloud_sounds)); } } @Override public void onError(Throwable e) { Log.e(TAG, "Error loading sounds from soundcloud", e); } @Override public void onNext(List<SoundcloudTrack> soundcloudTracks) { Log.d(TAG, "Size of soundcloud tracks: " + soundcloudTracks.size()); mSoundcloudTracks = soundcloudTracks; } }); } private void getSoundcloudUsername(long soundcloudUserId) { Observable<SoundcloudUser> call = SoundcloudService.Factory.build().getUser(soundcloudUserId); mSoundclouduserSubscription = call.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()) .subscribe(new Subscriber<SoundcloudUser>() { @Override public void onCompleted() { soundCloudArtist.set(mSoundcloudUser.getUsername()); } @Override public void onError(Throwable e) { Log.e(TAG, "Error loading soundcloud user information", e); } @Override public void onNext(SoundcloudUser soundcloudUser) { SoundcloudViewModel.this.mSoundcloudUser = soundcloudUser; } }); } public void onForwardClick(View view) { currentPlayingTrack++; if(currentPlayingTrack > mSoundcloudTracks.size()-1) { currentPlayingTrack-= mSoundcloudTracks.size(); } stopAndResetPlayer(); setDataSourceAndPreparePlayer(); } private void setDataSourceAndPreparePlayer() { try { currentTrack.set(mSoundcloudTracks.get(currentPlayingTrack % mSoundcloudTracks.size()).getTitle()); mPlayer.setDataSource(mSoundcloudTracks.get(currentPlayingTrack).getStreamUrl() + CLIENT_ID); mPlayer.prepare(); } catch (IOException e) { Log.e(TAG, e.getMessage()); } } private void stopAndResetPlayer() { if (mPlayer != null) { mPlayer.reset(); mPlayer.stop(); } } public void onRewindClick(View view) { currentPlayingTrack--; if(currentPlayingTrack < 0) { currentPlayingTrack+=mSoundcloudTracks.size(); } stopAndResetPlayer(); setDataSourceAndPreparePlayer(); } public void onPlayClick(View view) { startOrStopPlayer(); } private void startOrStopPlayer() { if (mPlayer != null) { if (mPlayer.isPlaying()) { mPlayer.pause(); isPlaying.set(false); } else { progress.set(0); max.set(mPlayer.getDuration()); myHandler.postDelayed(UpdateSongTime,16); mPlayer.start(); isPlaying.set(true); } } } @Override public void destroy() { if (mSoundclouduserSubscription != null && !mSoundclouduserSubscription.isUnsubscribed()) { mSoundclouduserSubscription.unsubscribe(); } if (mSoundcloudTracksSusbcriptions != null && !mSoundcloudTracksSusbcriptions.isUnsubscribed()) { mSoundcloudTracksSusbcriptions.unsubscribe(); } if (mPlayer != null) { mPlayer.stop(); mPlayer.release(); } mPlayer = null; mSoundcloudTracksSusbcriptions = null; mSoundclouduserSubscription = null; } @Override public void onCompletion(MediaPlayer mediaPlayer) { isPlaying.set(false); progress.set(0); } private Runnable UpdateSongTime = new Runnable() { @Override public void run() { if(mPlayer != null && mPlayer.isPlaying()) { progress.set(mPlayer.getCurrentPosition()); myHandler.postDelayed(this, 16); } } }; }
app/src/main/java/de/ahlfeld/breminale/viewmodel/SoundcloudViewModel.java
package de.ahlfeld.breminale.viewmodel; import android.content.Context; import android.databinding.ObservableBoolean; import android.databinding.ObservableField; import android.databinding.ObservableInt; import android.media.AudioManager; import android.media.MediaPlayer; import android.os.Handler; import android.util.Log; import android.view.View; import java.io.IOException; import java.util.List; import java.util.concurrent.TimeUnit; import de.ahlfeld.breminale.R; import de.ahlfeld.breminale.models.SoundcloudTrack; import de.ahlfeld.breminale.models.SoundcloudUser; import de.ahlfeld.breminale.networking.SoundcloudService; import rx.Observable; import rx.Subscriber; import rx.Subscription; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; /** * Created by bjornahlfeld on 03.05.16. */ public class SoundcloudViewModel implements ViewModel, MediaPlayer.OnCompletionListener { private static final String TAG = SoundcloudViewModel.class.getSimpleName(); private final Context mContext; public ObservableField<String> soundCloudArtist; public ObservableField<String> currentTrack; public ObservableBoolean isPlaying; public ObservableInt max; private Subscription mSoundclouduserSubscription; private SoundcloudUser mSoundcloudUser; private Subscription mSoundcloudTracksSusbcriptions; private Subscription progressSubscription; private List<SoundcloudTrack> mSoundcloudTracks; private MediaPlayer mPlayer; private Handler myHandler; private static final String CLIENT_ID = "?client_id=469443570702bcc59666de5950139327"; private int currentPlayingTrack; public ObservableInt progress; public SoundcloudViewModel(Context ctx, long soundcloudUserId) { mContext = ctx.getApplicationContext(); soundCloudArtist = new ObservableField<>(""); currentTrack = new ObservableField<>(""); getSoundcloudUsername(soundcloudUserId); getTracksForSoundcloudUser(soundcloudUserId); mPlayer = new MediaPlayer(); mPlayer.setOnCompletionListener(this); mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); currentPlayingTrack = 0; max = new ObservableInt(0); progress = new ObservableInt(0); isPlaying = new ObservableBoolean(false); myHandler = new Handler(); } public void prepareProgress() { Observable.interval(16, TimeUnit.MILLISECONDS) .map(y -> { Log.d(TAG, "tick: " + y); progress.set(mPlayer.getCurrentPosition()); return null; }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<Object>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { } @Override public void onNext(Object o) { Log.d(TAG, "object" + o.toString()); } }); } private void getTracksForSoundcloudUser(long soundcloudUserId) { Observable<List<SoundcloudTrack>> call = SoundcloudService.Factory.build().getTracksForUser(soundcloudUserId); mSoundcloudTracksSusbcriptions = call.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()) .subscribe(new Subscriber<List<SoundcloudTrack>>() { @Override public void onCompleted() { if (!mSoundcloudTracks.isEmpty()) { currentTrack.set(mSoundcloudTracks.get(0).getTitle()); setDataSourceAndPreparePlayer(); } else { currentTrack.set(mContext.getString(R.string.empty_soundcloud_sounds)); } } @Override public void onError(Throwable e) { Log.e(TAG, "Error loading sounds from soundcloud", e); } @Override public void onNext(List<SoundcloudTrack> soundcloudTracks) { Log.d(TAG, "Size of soundcloud tracks: " + soundcloudTracks.size()); mSoundcloudTracks = soundcloudTracks; } }); } private void getSoundcloudUsername(long soundcloudUserId) { Observable<SoundcloudUser> call = SoundcloudService.Factory.build().getUser(soundcloudUserId); mSoundclouduserSubscription = call.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()) .subscribe(new Subscriber<SoundcloudUser>() { @Override public void onCompleted() { soundCloudArtist.set(mSoundcloudUser.getUsername()); } @Override public void onError(Throwable e) { Log.e(TAG, "Error loading soundcloud user information", e); } @Override public void onNext(SoundcloudUser soundcloudUser) { SoundcloudViewModel.this.mSoundcloudUser = soundcloudUser; } }); } public void onForwardClick(View view) { currentPlayingTrack++; currentTrack.set(mSoundcloudTracks.get(currentPlayingTrack).getTitle()); stopAndResetPlayer(); setDataSourceAndPreparePlayer(); } private void setDataSourceAndPreparePlayer() { try { mPlayer.setDataSource(mSoundcloudTracks.get(currentPlayingTrack).getStreamUrl() + CLIENT_ID); mPlayer.prepare(); } catch (IOException e) { Log.e(TAG, e.getMessage()); } } private void stopAndResetPlayer() { if (mPlayer != null) { mPlayer.reset(); mPlayer.stop(); } } public void onRewindClick(View view) { currentPlayingTrack--; currentTrack.set(mSoundcloudTracks.get(currentPlayingTrack).getTitle()); stopAndResetPlayer(); setDataSourceAndPreparePlayer(); } public void onPlayClick(View view) { startOrStopPlayer(); } private void startOrStopPlayer() { if (mPlayer != null) { if (mPlayer.isPlaying()) { mPlayer.pause(); isPlaying.set(false); } else { progress.set(0); max.set(mPlayer.getDuration()); myHandler.postDelayed(UpdateSongTime,16); mPlayer.start(); isPlaying.set(true); } } } @Override public void destroy() { if (mSoundclouduserSubscription != null && !mSoundclouduserSubscription.isUnsubscribed()) { mSoundclouduserSubscription.unsubscribe(); } if (mSoundcloudTracksSusbcriptions != null && !mSoundcloudTracksSusbcriptions.isUnsubscribed()) { mSoundcloudTracksSusbcriptions.unsubscribe(); } if (mPlayer != null) { mPlayer.stop(); mPlayer.release(); } mPlayer = null; mSoundcloudTracksSusbcriptions = null; mSoundclouduserSubscription = null; } @Override public void onCompletion(MediaPlayer mediaPlayer) { isPlaying.set(false); } private Runnable UpdateSongTime = new Runnable() { @Override public void run() { if(mPlayer != null && mPlayer.isPlaying()) { progress.set(mPlayer.getCurrentPosition()); myHandler.postDelayed(this, 16); } } }; }
Soundcloud fragment is working
app/src/main/java/de/ahlfeld/breminale/viewmodel/SoundcloudViewModel.java
Soundcloud fragment is working
Java
mit
391d7c8eb73f5df965b9a52895fe895932f623bf
0
scoot-software/sms-server
/* * Author: Scott Ware <[email protected]> * Copyright (c) 2015 Scott Ware * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.scooter1556.sms.server.controller; import com.scooter1556.sms.server.dao.JobDao; import com.scooter1556.sms.server.dao.MediaDao; import com.scooter1556.sms.server.domain.AudioTranscode.AudioQuality; import com.scooter1556.sms.server.domain.Job; import com.scooter1556.sms.server.domain.Job.JobType; import com.scooter1556.sms.server.domain.MediaElement; import com.scooter1556.sms.server.domain.MediaElement.MediaElementType; import com.scooter1556.sms.server.domain.TranscodeProfile; import com.scooter1556.sms.server.domain.TranscodeProfile.StreamType; import com.scooter1556.sms.server.domain.VideoTranscode.VideoQuality; import com.scooter1556.sms.server.io.AdaptiveStreamingProcess; import com.scooter1556.sms.server.io.FileDownloadProcess; import com.scooter1556.sms.server.io.SMSProcess; import com.scooter1556.sms.server.service.AdaptiveStreamingService; import com.scooter1556.sms.server.service.JobService; import com.scooter1556.sms.server.service.LogService; import com.scooter1556.sms.server.service.NetworkService; import com.scooter1556.sms.server.service.SessionService; import com.scooter1556.sms.server.service.SessionService.Session; import com.scooter1556.sms.server.service.SettingsService; import com.scooter1556.sms.server.service.TranscodeService; import com.scooter1556.sms.server.utilities.FileUtils; import com.scooter1556.sms.server.utilities.NetworkUtils; import com.scooter1556.sms.server.utilities.TranscodeUtils; import java.io.File; import java.io.IOException; import java.net.InetAddress; import java.net.InterfaceAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.net.UnknownHostException; import java.nio.file.Paths; import java.util.Enumeration; import java.util.List; import java.util.UUID; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; @Controller @RequestMapping(value="/stream") public class StreamController { private static final String CLASS_NAME = "StreamController"; @Autowired private MediaDao mediaDao; @Autowired private JobDao jobDao; @Autowired private JobService jobService; @Autowired private NetworkService networkService; @Autowired private TranscodeService transcodeService; @Autowired private AdaptiveStreamingService adaptiveStreamingService; @Autowired private SessionService sessionService; @CrossOrigin @RequestMapping(value="/initialise/{session}/{id}", method=RequestMethod.GET) @ResponseBody public ResponseEntity<TranscodeProfile> initialiseStream(@PathVariable("session") UUID sessionId, @PathVariable("id") Long id, @RequestParam(value = "client", required = false) String client, @RequestParam(value = "files", required = false) String files, @RequestParam(value = "codecs", required = true) String codecs, @RequestParam(value = "mchcodecs", required = false) String mchCodecs, @RequestParam(value = "format", required = false) String format, @RequestParam(value = "quality", required = true) Integer quality, @RequestParam(value = "samplerate", required = false) Integer maxSampleRate, @RequestParam(value = "bitrate", required = false) Integer maxBitRate, @RequestParam(value = "atrack", required = false) Integer audioTrack, @RequestParam(value = "strack", required = false) Integer subtitleTrack, @RequestParam(value = "direct", required = false) Boolean directPlay, @RequestParam(value = "update", required = false) Boolean update, HttpServletRequest request) { MediaElement mediaElement; Session session; Job job; Byte jobType; TranscodeProfile profile; Boolean transcodeRequired = true; // Check session is valid session = sessionService.getSessionById(sessionId); if(session == null) { LogService.getInstance().addLogEntry(LogService.Level.WARN, CLASS_NAME, "Session invalid with ID: " + sessionId, null); return new ResponseEntity<>(HttpStatus.BAD_GATEWAY); } // Check media element mediaElement = mediaDao.getMediaElementByID(id); if(mediaElement == null || codecs == null || quality == null) { LogService.getInstance().addLogEntry(LogService.Level.WARN, CLASS_NAME, "Invalid transcode request.", null); return new ResponseEntity<>(HttpStatus.NOT_FOUND); } // Check physical file is available if(!new File(mediaElement.getPath()).exists()) { LogService.getInstance().addLogEntry(LogService.Level.WARN, CLASS_NAME, "File not found for media element with ID " + id + ".", null); return new ResponseEntity<>(HttpStatus.NO_CONTENT); } // Validate codecs for(String codec : codecs.split(",")) { if(!TranscodeUtils.isSupported(TranscodeService.getSupportedCodecs(), codec)) { LogService.getInstance().addLogEntry(LogService.Level.WARN, CLASS_NAME, "Codec '" + codec + "' not recognised.", null); return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } } // Validate format if(format != null) { if(!TranscodeUtils.isSupported(TranscodeUtils.FORMATS, format)) { LogService.getInstance().addLogEntry(LogService.Level.WARN, CLASS_NAME, "Format '" + format + "' is not recognised.", null); return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } } // Determine job type & validate quality if(mediaElement.getType() == MediaElementType.AUDIO && AudioQuality.isValid(quality)) { jobType = JobType.AUDIO_STREAM; } else if(mediaElement.getType() == MediaElementType.VIDEO && VideoQuality.isValid(quality)) { jobType = JobType.VIDEO_STREAM; } else { LogService.getInstance().addLogEntry(LogService.Level.WARN, CLASS_NAME, "Invalid transcode request.", null); return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } // Ensure our metadata update flag is set if(update == null) { update = true; } // Create a new job job = jobService.createJob(jobType, session.getUsername(), mediaElement, update); if(job == null) { LogService.getInstance().addLogEntry(LogService.Level.ERROR, CLASS_NAME, "Failed to create job for trancode request.", null); return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); } // Determine if the device is on the local network boolean isLocal = false; try { InetAddress local = InetAddress.getByName(request.getLocalAddr()); InetAddress remote = InetAddress.getByName(request.getRemoteAddr()); NetworkInterface networkInterface = NetworkInterface.getByInetAddress(local); LogService.getInstance().addLogEntry(LogService.Level.INFO, CLASS_NAME, "Client connected with IP " + remote.toString(), null); // Check if the remote device is on the same subnet as the server for (InterfaceAddress address : networkInterface.getInterfaceAddresses()) { if(address.getAddress().equals(local)) { int mask = address.getNetworkPrefixLength(); isLocal = NetworkUtils.isLocalIP(local, remote, mask); } } // Check if request came from public IP if subnet check was false if(!isLocal) { String ip = networkService.getPublicIP(); if(ip != null) { isLocal = remote.toString().contains(ip); } } } catch (UnknownHostException | SocketException ex) { LogService.getInstance().addLogEntry(LogService.Level.WARN, CLASS_NAME, "Failed to check IP adress of client.", ex); } // Direct Play if(directPlay == null) { directPlay = false; } else if(directPlay) { directPlay = isLocal; } // // Create transcode profile for job // profile = new TranscodeProfile(job.getID()); // Set stream type if(isLocal) { profile.setType(TranscodeProfile.StreamType.LOCAL); } else { profile.setType(TranscodeProfile.StreamType.REMOTE); } profile.setMediaElement(mediaElement); profile.setUrl(request.getRequestURL().toString().replaceFirst("/stream(.*)", "")); if(files != null) { profile.setFiles(files.split(",")); } profile.setCodecs(codecs.split(",")); if(client != null) { profile.setClient(client); } if(format != null) { profile.setFormat(format); } profile.setQuality(quality); if(maxSampleRate != null) { profile.setMaxSampleRate(maxSampleRate); } if(mchCodecs != null) { profile.setMchCodecs(mchCodecs.split(",")); } if(audioTrack != null) { if(TranscodeUtils.isAudioStreamAvailable(audioTrack, mediaElement)) { profile.setAudioTrack(audioTrack); } else { LogService.getInstance().addLogEntry(LogService.Level.WARN, CLASS_NAME, "Audio stream " + audioTrack + " is not available for media element " + mediaElement.getID() + ".", null); return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } } if(subtitleTrack != null) { if(TranscodeUtils.isSubtitleStreamAvailable(subtitleTrack, mediaElement)) { profile.setSubtitleTrack(subtitleTrack); } else { LogService.getInstance().addLogEntry(LogService.Level.WARN, CLASS_NAME, "Subtitle stream " + subtitleTrack + " is not available for media element " + mediaElement.getID() + ".", null); return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } } profile.setDirectPlayEnabled(directPlay); // Test if we can stream the file directly without transcoding if(profile.getFiles() != null) { // If the file type is supported and all codecs are supported without transcoding stream the file directly if(TranscodeUtils.isSupported(profile.getFiles(), mediaElement.getFormat())) { transcodeRequired = TranscodeService.isTranscodeRequired(profile); if(transcodeRequired == null) { LogService.getInstance().addLogEntry(LogService.Level.ERROR, CLASS_NAME, "Failed to determine trancode parameters for job " + job.getID() + ".", null); return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); } else if(!transcodeRequired) { profile.setType(StreamType.DIRECT); profile.setMimeType(TranscodeUtils.getMimeType(mediaElement.getFormat(), mediaElement.getType())); } } } // Populate max bitrate after determining if direct streaming is possible if(maxBitRate != null) { profile.setMaxBitRate(maxBitRate); } // If necessary process all streams ready for streaming and/or transcoding if(transcodeRequired) { if(mediaElement.getType() == MediaElementType.VIDEO) { // If a suitable format was not given we can't continue if(profile.getFormat() == null) { LogService.getInstance().addLogEntry(LogService.Level.WARN, CLASS_NAME, "No suitable format given for job " + job.getID() + ".", null); return new ResponseEntity<>(HttpStatus.NOT_ACCEPTABLE); } // Process subtitles if(!TranscodeService.processSubtitles(profile)) { LogService.getInstance().addLogEntry(LogService.Level.ERROR, CLASS_NAME, "Failed to process subtitle streams for job " + job.getID() + ".", null); return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); } // Process video if(!TranscodeService.processVideo(profile)) { LogService.getInstance().addLogEntry(LogService.Level.ERROR, CLASS_NAME, "Failed to process video stream for job " + job.getID() + ".", null); return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); } } // Process Audio if(!TranscodeService.processAudio(profile)) { LogService.getInstance().addLogEntry(LogService.Level.ERROR, CLASS_NAME, "Failed to process audio streams for job " + job.getID() + ".", null); return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); } // Set MIME Type if(profile.getFormat() != null) { profile.setMimeType(TranscodeUtils.getMimeType(profile.getFormat(), mediaElement.getType())); } } // If transcode is required start the transcode process if(profile.getType() > StreamType.DIRECT) { if(adaptiveStreamingService.initialise(profile, 0) == null) { LogService.getInstance().addLogEntry(LogService.Level.ERROR, CLASS_NAME, "Failed to intialise adaptive streaming process for job " + job.getID() + ".", null); return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); } } // Add profile to transcode service LogService.getInstance().addLogEntry(LogService.Level.INFO, CLASS_NAME, profile.toString(), null); transcodeService.addTranscodeProfile(profile); return new ResponseEntity<>(profile, HttpStatus.OK); } @ResponseBody @RequestMapping(value="/playlist/{id}/{type}/{extra}", method=RequestMethod.GET) public void getPlaylist(@PathVariable("id") UUID id, @PathVariable("type") String type, @PathVariable("extra") Integer extra, HttpServletRequest request, HttpServletResponse response) { Job job; TranscodeProfile profile; try { // Retrieve Job job = jobDao.getJobByID(id); if(job == null) { LogService.getInstance().addLogEntry(LogService.Level.WARN, CLASS_NAME, "Failed to retrieve job with id " + id + ".", null); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to retrieve job."); return; } // Get transcode profile profile = transcodeService.getTranscodeProfile(id); if(profile == null) { LogService.getInstance().addLogEntry(LogService.Level.ERROR, CLASS_NAME, "Failed to retrieve transcode profile for job " + id + ".", null); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to retrieve transcode profile."); return; } // Check type and transcode profile switch(type) { case "audio": if(profile.getAudioTranscodes() == null || profile.getAudioTranscodes().length <= extra) { LogService.getInstance().addLogEntry(LogService.Level.ERROR, CLASS_NAME, "Audio stream is out of range.", null); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Audio stream is out of range."); return; } break; case "video": if(profile.getVideoTranscodes() == null || extra >= profile.getVideoTranscodes().length) { LogService.getInstance().addLogEntry(LogService.Level.ERROR, CLASS_NAME, "Video stream requested is out of range.", null); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Video stream requested is out of range."); return; } break; case "subtitle": if(profile.getSubtitleTranscodes() == null || profile.getSubtitleTranscodes().length <= extra) { LogService.getInstance().addLogEntry(LogService.Level.ERROR, CLASS_NAME, "Subtitles stream is out of range.", null); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Subtitle stream is out of range."); return; } break; default: LogService.getInstance().addLogEntry(LogService.Level.WARN, CLASS_NAME, "Playlist type is not recognised.", null); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Playlist type is not recognised."); return; } // Return playlist switch (profile.getFormat()) { case "hls": adaptiveStreamingService.sendHLSPlaylist(id, type, extra, request, response); break; default: LogService.getInstance().addLogEntry(LogService.Level.WARN, CLASS_NAME, "Format for job " + id + " is not compatible with adaptive streaming.", null); response.sendError(HttpServletResponse.SC_NO_CONTENT, "Format is not supported for adaptive streaming."); } } catch (IOException ex) { // Called if client closes the connection early. } } @ResponseBody @RequestMapping(value="/segment/{id}/{type}/{extra}/{file}", method=RequestMethod.GET) public void getSegment(@PathVariable("id") UUID id, @PathVariable("type") String type, @PathVariable("extra") Integer extra, @PathVariable("file") String file, HttpServletRequest request, HttpServletResponse response) { Job job = null; TranscodeProfile profile; AdaptiveStreamingProcess transcodeProcess; SMSProcess process = null; File segment; try { // Retrieve Job job = jobDao.getJobByID(id); if(job == null) { LogService.getInstance().addLogEntry(LogService.Level.WARN, CLASS_NAME, "Failed to retrieve job with id " + id + ".", null); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to retrieve job."); return; } // Get transcode profile profile = transcodeService.getTranscodeProfile(id); if(profile == null) { LogService.getInstance().addLogEntry(LogService.Level.ERROR, CLASS_NAME, "Failed to retrieve transcode profile for job " + id + ".", null); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to retrieve transcode profile."); return; } // Get associated process transcodeProcess = adaptiveStreamingService.getProcessById(id); if(transcodeProcess == null) { LogService.getInstance().addLogEntry(LogService.Level.ERROR, CLASS_NAME, "Failed to find adaptive streaming process for job " + id + ".", null); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to retrieve transcode process."); return; } String mimeType; switch (profile.getFormat()) { case "hls": mimeType = "video/MP2T"; break; case "dash": mimeType = "video/mp4"; break; default: LogService.getInstance().addLogEntry(LogService.Level.WARN, CLASS_NAME, "Format for job " + id + " is not compatible with adaptive streaming.", null); response.sendError(HttpServletResponse.SC_NO_CONTENT, "Format is not supported for adaptive streaming."); return; } // Find Segment File segment = new File(SettingsService.getInstance().getCacheDirectory().getPath() + "/streams/" + id + "/" + file + "-" + type + "-" + extra); LogService.getInstance().addLogEntry(LogService.Level.DEBUG, CLASS_NAME, "Job ID=" + id + " Segment=" + file + " Type=" + type + " Extra=" + extra, null); if(profile.getFormat().equals("hls")) { // Update segment tracking int num = Integer.parseInt(file); int oldNum = transcodeProcess.getSegmentNum(); transcodeProcess.setSegmentNum(num); // If segment requested is not the next chronologically check if we need to start a new transcode process if(num != oldNum && num != (oldNum + 1) && !segment.exists()) { LogService.getInstance().addLogEntry(LogService.Level.DEBUG, CLASS_NAME, "Starting new transcode process.", null); adaptiveStreamingService.initialise(profile, num); } } File segmentList = new File(SettingsService.getInstance().getCacheDirectory().getPath() + "/streams/" + id + "/" + type + "-" + extra + ".txt"); int count = 0; // Wait for segment list to become available while(!segmentList.exists() && count < 5) { try { Thread.sleep(1000); } catch (InterruptedException ex) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error occured waiting for segment to become available."); } count++; } // Check if segment list is available if(!segmentList.exists()) { LogService.getInstance().addLogEntry(LogService.Level.WARN, CLASS_NAME, "Unable to get segment list for job " + id + ".", null); response.sendError(HttpServletResponse.SC_NO_CONTENT, "Unable to get segment list."); return; } List<String> segments = FileUtils.readFileToList(segmentList); count = 0; while(segments != null && !segments.contains(file + "-" + type + "-" + extra) && (count < 20)) { try { Thread.sleep(1000); } catch (InterruptedException ex) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error occured waiting for segment to become available."); } // Update segment list segments = FileUtils.readFileToList(segmentList); count++; } // Check if segment is definitely available if(count >= 20 || !segment.exists() || segments == null) { LogService.getInstance().addLogEntry(LogService.Level.WARN, CLASS_NAME, "Failed to return segment " + file + " for job " + id + ".", null); response.sendError(HttpServletResponse.SC_NO_CONTENT, "Requested segment is not available."); return; } if(profile.getMediaElement().getType().equals(MediaElementType.VIDEO)) { // Determine proper mimetype for audio if(type.equals("audio")) { switch(profile.getClient()) { case "chromecast": mimeType = TranscodeUtils.getMimeType(profile.getAudioTranscodes()[extra].getCodec(), MediaElementType.AUDIO); break; default: break; } } } process = new FileDownloadProcess(segment.toPath(), mimeType, request, response); process.start(); } catch (Exception ex) { // Called if client closes the connection early. LogService.getInstance().addLogEntry(LogService.Level.DEBUG, CLASS_NAME, "Client closed connection early (Job ID: " + id + " Segment: " + file + ")", ex); } finally { if(process != null && job != null) { jobDao.updateBytesTransferred(id, job.getBytesTransferred() + process.getBytesTransferred()); } } } @RequestMapping(value="/{id}", method=RequestMethod.GET) @ResponseBody public void getStream(@PathVariable("id") UUID id, @RequestParam(value = "atrack", required = false) Integer audioTrack, @RequestParam(value = "strack", required = false) Integer subtitleTrack, @RequestParam(value = "offset", required = false) Integer offset, HttpServletRequest request, HttpServletResponse response) { // Variables TranscodeProfile profile; Job job = null; SMSProcess process = null; /*********************** DEBUG: Get Request Headers *********************************/ String requestHeader = "\n***************\nRequest Header:\n***************\n"; Enumeration requestHeaderNames = request.getHeaderNames(); while (requestHeaderNames.hasMoreElements()) { String key = (String) requestHeaderNames.nextElement(); String value = request.getHeader(key); requestHeader += key + ": " + value + "\n"; } // Print Headers LogService.getInstance().addLogEntry(LogService.Level.INSANE, CLASS_NAME, requestHeader, null); /********************************************************************************/ try { // Retrieve Job job = jobDao.getJobByID(id); if(job == null) { LogService.getInstance().addLogEntry(LogService.Level.WARN, CLASS_NAME, "Failed to retrieve job with id " + id + ".", null); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to retrieve job."); return; } // Retrieve transcode profile profile = transcodeService.getTranscodeProfile(id); if(profile == null) { LogService.getInstance().addLogEntry(LogService.Level.WARN, CLASS_NAME, "Failed to retrieve transcode profile for job " + job.getID() + ".", null); response.sendError(HttpServletResponse.SC_NOT_FOUND, "Unable to retrieve transcode profile for job " + id + "."); return; } switch(profile.getType()) { case StreamType.LOCAL: case StreamType.REMOTE: if(profile.getFormat().equals("hls")) { adaptiveStreamingService.sendHLSPlaylist(id, null, null, request, response); } else if(profile.getFormat().equals("dash")) { adaptiveStreamingService.sendDashPlaylist(id, request, response); } break; case StreamType.DIRECT: if(profile.getMediaElement() == null) { LogService.getInstance().addLogEntry(LogService.Level.WARN, CLASS_NAME, "Failed to retrieve media element for job " + job.getID() + ".", null); response.sendError(HttpServletResponse.SC_NOT_FOUND, "Unable to find media element."); return; } process = new FileDownloadProcess(Paths.get(profile.getMediaElement().getPath()), profile.getMimeType(), request, response); process.start(); break; default: LogService.getInstance().addLogEntry(LogService.Level.WARN, CLASS_NAME, "Failed to determine stream type for job " + job.getID() + ".", null); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Cannot determine stream type."); } } catch (Exception ex) { // Called if client closes the connection early. if(process != null) { process.end(); } } finally { if(job != null && process != null) { jobDao.updateBytesTransferred(id, job.getBytesTransferred() + process.getBytesTransferred()); } } } }
src/main/java/com/scooter1556/sms/server/controller/StreamController.java
/* * Author: Scott Ware <[email protected]> * Copyright (c) 2015 Scott Ware * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.scooter1556.sms.server.controller; import com.scooter1556.sms.server.dao.JobDao; import com.scooter1556.sms.server.dao.MediaDao; import com.scooter1556.sms.server.domain.AudioTranscode.AudioQuality; import com.scooter1556.sms.server.domain.Job; import com.scooter1556.sms.server.domain.Job.JobType; import com.scooter1556.sms.server.domain.MediaElement; import com.scooter1556.sms.server.domain.MediaElement.MediaElementType; import com.scooter1556.sms.server.domain.TranscodeProfile; import com.scooter1556.sms.server.domain.TranscodeProfile.StreamType; import com.scooter1556.sms.server.domain.VideoTranscode.VideoQuality; import com.scooter1556.sms.server.io.AdaptiveStreamingProcess; import com.scooter1556.sms.server.io.FileDownloadProcess; import com.scooter1556.sms.server.io.SMSProcess; import com.scooter1556.sms.server.service.AdaptiveStreamingService; import com.scooter1556.sms.server.service.JobService; import com.scooter1556.sms.server.service.LogService; import com.scooter1556.sms.server.service.NetworkService; import com.scooter1556.sms.server.service.SessionService; import com.scooter1556.sms.server.service.SessionService.Session; import com.scooter1556.sms.server.service.SettingsService; import com.scooter1556.sms.server.service.TranscodeService; import com.scooter1556.sms.server.utilities.FileUtils; import com.scooter1556.sms.server.utilities.NetworkUtils; import com.scooter1556.sms.server.utilities.TranscodeUtils; import java.io.File; import java.io.IOException; import java.net.InetAddress; import java.net.InterfaceAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.net.UnknownHostException; import java.nio.file.Paths; import java.util.Enumeration; import java.util.List; import java.util.UUID; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; @Controller @RequestMapping(value="/stream") public class StreamController { private static final String CLASS_NAME = "StreamController"; @Autowired private MediaDao mediaDao; @Autowired private JobDao jobDao; @Autowired private JobService jobService; @Autowired private NetworkService networkService; @Autowired private TranscodeService transcodeService; @Autowired private AdaptiveStreamingService adaptiveStreamingService; @Autowired private SessionService sessionService; @CrossOrigin @RequestMapping(value="/initialise/{session}/{id}", method=RequestMethod.GET) @ResponseBody public ResponseEntity<TranscodeProfile> initialiseStream(@PathVariable("session") UUID sessionId, @PathVariable("id") Long id, @RequestParam(value = "client", required = false) String client, @RequestParam(value = "files", required = false) String files, @RequestParam(value = "codecs", required = true) String codecs, @RequestParam(value = "mchcodecs", required = false) String mchCodecs, @RequestParam(value = "format", required = false) String format, @RequestParam(value = "quality", required = true) Integer quality, @RequestParam(value = "samplerate", required = false) Integer maxSampleRate, @RequestParam(value = "bitrate", required = false) Integer maxBitRate, @RequestParam(value = "atrack", required = false) Integer audioTrack, @RequestParam(value = "strack", required = false) Integer subtitleTrack, @RequestParam(value = "direct", required = false) Boolean directPlay, @RequestParam(value = "update", required = false) Boolean update, HttpServletRequest request) { MediaElement mediaElement; Session session; Job job; Byte jobType; TranscodeProfile profile; Boolean transcodeRequired = true; // Check session is valid session = sessionService.getSessionById(sessionId); if(session == null) { LogService.getInstance().addLogEntry(LogService.Level.WARN, CLASS_NAME, "Session invalid with ID: " + sessionId, null); return new ResponseEntity<>(HttpStatus.BAD_GATEWAY); } // Check media element mediaElement = mediaDao.getMediaElementByID(id); if(mediaElement == null || codecs == null || quality == null) { LogService.getInstance().addLogEntry(LogService.Level.WARN, CLASS_NAME, "Invalid transcode request.", null); return new ResponseEntity<>(HttpStatus.NOT_FOUND); } // Check physical file is available if(!new File(mediaElement.getPath()).exists()) { LogService.getInstance().addLogEntry(LogService.Level.WARN, CLASS_NAME, "File not found for media element with ID " + id + ".", null); return new ResponseEntity<>(HttpStatus.NO_CONTENT); } // Validate codecs for(String codec : codecs.split(",")) { if(!TranscodeUtils.isSupported(TranscodeService.getSupportedCodecs(), codec)) { LogService.getInstance().addLogEntry(LogService.Level.WARN, CLASS_NAME, "Codec '" + codec + "' not recognised.", null); return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } } // Validate format if(format != null) { if(!TranscodeUtils.isSupported(TranscodeUtils.FORMATS, format)) { LogService.getInstance().addLogEntry(LogService.Level.WARN, CLASS_NAME, "Format '" + format + "' is not recognised.", null); return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } } // Determine job type & validate quality if(mediaElement.getType() == MediaElementType.AUDIO && AudioQuality.isValid(quality)) { jobType = JobType.AUDIO_STREAM; } else if(mediaElement.getType() == MediaElementType.VIDEO && VideoQuality.isValid(quality)) { jobType = JobType.VIDEO_STREAM; } else { LogService.getInstance().addLogEntry(LogService.Level.WARN, CLASS_NAME, "Invalid transcode request.", null); return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } // Ensure our metadata update flag is set if(update == null) { update = true; } // Create a new job job = jobService.createJob(jobType, session.getUsername(), mediaElement, update); if(job == null) { LogService.getInstance().addLogEntry(LogService.Level.ERROR, CLASS_NAME, "Failed to create job for trancode request.", null); return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); } // Determine if the device is on the local network boolean isLocal = false; try { InetAddress local = InetAddress.getByName(request.getLocalAddr()); InetAddress remote = InetAddress.getByName(request.getRemoteAddr()); NetworkInterface networkInterface = NetworkInterface.getByInetAddress(local); LogService.getInstance().addLogEntry(LogService.Level.INFO, CLASS_NAME, "Client connected with IP " + remote.toString(), null); // Check if the remote device is on the same subnet as the server for (InterfaceAddress address : networkInterface.getInterfaceAddresses()) { if(address.getAddress().equals(local)) { int mask = address.getNetworkPrefixLength(); isLocal = NetworkUtils.isLocalIP(local, remote, mask); } } // Check if request came from public IP if subnet check was false if(!isLocal) { String ip = networkService.getPublicIP(); if(ip != null) { isLocal = remote.toString().contains(ip); } } } catch (UnknownHostException | SocketException ex) { LogService.getInstance().addLogEntry(LogService.Level.WARN, CLASS_NAME, "Failed to check IP adress of client.", ex); } // Direct Play if(directPlay == null || !directPlay) { directPlay = isLocal; } // // Create transcode profile for job // profile = new TranscodeProfile(job.getID()); // Set stream type if(isLocal) { profile.setType(TranscodeProfile.StreamType.LOCAL); } else { profile.setType(TranscodeProfile.StreamType.REMOTE); } profile.setMediaElement(mediaElement); profile.setUrl(request.getRequestURL().toString().replaceFirst("/stream(.*)", "")); if(files != null) { profile.setFiles(files.split(",")); } profile.setCodecs(codecs.split(",")); if(client != null) { profile.setClient(client); } if(format != null) { profile.setFormat(format); } profile.setQuality(quality); if(maxSampleRate != null) { profile.setMaxSampleRate(maxSampleRate); } if(mchCodecs != null) { profile.setMchCodecs(mchCodecs.split(",")); } if(audioTrack != null) { if(TranscodeUtils.isAudioStreamAvailable(audioTrack, mediaElement)) { profile.setAudioTrack(audioTrack); } else { LogService.getInstance().addLogEntry(LogService.Level.WARN, CLASS_NAME, "Audio stream " + audioTrack + " is not available for media element " + mediaElement.getID() + ".", null); return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } } if(subtitleTrack != null) { if(TranscodeUtils.isSubtitleStreamAvailable(subtitleTrack, mediaElement)) { profile.setSubtitleTrack(subtitleTrack); } else { LogService.getInstance().addLogEntry(LogService.Level.WARN, CLASS_NAME, "Subtitle stream " + subtitleTrack + " is not available for media element " + mediaElement.getID() + ".", null); return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } } profile.setDirectPlayEnabled(directPlay); // Test if we can stream the file directly without transcoding if(profile.getFiles() != null) { // If the file type is supported and all codecs are supported without transcoding stream the file directly if(TranscodeUtils.isSupported(profile.getFiles(), mediaElement.getFormat())) { transcodeRequired = TranscodeService.isTranscodeRequired(profile); if(transcodeRequired == null) { LogService.getInstance().addLogEntry(LogService.Level.ERROR, CLASS_NAME, "Failed to determine trancode parameters for job " + job.getID() + ".", null); return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); } else if(!transcodeRequired) { profile.setType(StreamType.DIRECT); profile.setMimeType(TranscodeUtils.getMimeType(mediaElement.getFormat(), mediaElement.getType())); } } } // Populate max bitrate after determining if direct streaming is possible if(maxBitRate != null) { profile.setMaxBitRate(maxBitRate); } // If necessary process all streams ready for streaming and/or transcoding if(transcodeRequired) { if(mediaElement.getType() == MediaElementType.VIDEO) { // If a suitable format was not given we can't continue if(profile.getFormat() == null) { LogService.getInstance().addLogEntry(LogService.Level.WARN, CLASS_NAME, "No suitable format given for job " + job.getID() + ".", null); return new ResponseEntity<>(HttpStatus.NOT_ACCEPTABLE); } // Process subtitles if(!TranscodeService.processSubtitles(profile)) { LogService.getInstance().addLogEntry(LogService.Level.ERROR, CLASS_NAME, "Failed to process subtitle streams for job " + job.getID() + ".", null); return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); } // Process video if(!TranscodeService.processVideo(profile)) { LogService.getInstance().addLogEntry(LogService.Level.ERROR, CLASS_NAME, "Failed to process video stream for job " + job.getID() + ".", null); return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); } } // Process Audio if(!TranscodeService.processAudio(profile)) { LogService.getInstance().addLogEntry(LogService.Level.ERROR, CLASS_NAME, "Failed to process audio streams for job " + job.getID() + ".", null); return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); } // Set MIME Type if(profile.getFormat() != null) { profile.setMimeType(TranscodeUtils.getMimeType(profile.getFormat(), mediaElement.getType())); } } // If transcode is required start the transcode process if(profile.getType() > StreamType.DIRECT) { if(adaptiveStreamingService.initialise(profile, 0) == null) { LogService.getInstance().addLogEntry(LogService.Level.ERROR, CLASS_NAME, "Failed to intialise adaptive streaming process for job " + job.getID() + ".", null); return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); } } // Add profile to transcode service LogService.getInstance().addLogEntry(LogService.Level.INFO, CLASS_NAME, profile.toString(), null); transcodeService.addTranscodeProfile(profile); return new ResponseEntity<>(profile, HttpStatus.OK); } @ResponseBody @RequestMapping(value="/playlist/{id}/{type}/{extra}", method=RequestMethod.GET) public void getPlaylist(@PathVariable("id") UUID id, @PathVariable("type") String type, @PathVariable("extra") Integer extra, HttpServletRequest request, HttpServletResponse response) { Job job; TranscodeProfile profile; try { // Retrieve Job job = jobDao.getJobByID(id); if(job == null) { LogService.getInstance().addLogEntry(LogService.Level.WARN, CLASS_NAME, "Failed to retrieve job with id " + id + ".", null); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to retrieve job."); return; } // Get transcode profile profile = transcodeService.getTranscodeProfile(id); if(profile == null) { LogService.getInstance().addLogEntry(LogService.Level.ERROR, CLASS_NAME, "Failed to retrieve transcode profile for job " + id + ".", null); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to retrieve transcode profile."); return; } // Check type and transcode profile switch(type) { case "audio": if(profile.getAudioTranscodes() == null || profile.getAudioTranscodes().length <= extra) { LogService.getInstance().addLogEntry(LogService.Level.ERROR, CLASS_NAME, "Audio stream is out of range.", null); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Audio stream is out of range."); return; } break; case "video": if(profile.getVideoTranscodes() == null || extra >= profile.getVideoTranscodes().length) { LogService.getInstance().addLogEntry(LogService.Level.ERROR, CLASS_NAME, "Video stream requested is out of range.", null); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Video stream requested is out of range."); return; } break; case "subtitle": if(profile.getSubtitleTranscodes() == null || profile.getSubtitleTranscodes().length <= extra) { LogService.getInstance().addLogEntry(LogService.Level.ERROR, CLASS_NAME, "Subtitles stream is out of range.", null); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Subtitle stream is out of range."); return; } break; default: LogService.getInstance().addLogEntry(LogService.Level.WARN, CLASS_NAME, "Playlist type is not recognised.", null); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Playlist type is not recognised."); return; } // Return playlist switch (profile.getFormat()) { case "hls": adaptiveStreamingService.sendHLSPlaylist(id, type, extra, request, response); break; default: LogService.getInstance().addLogEntry(LogService.Level.WARN, CLASS_NAME, "Format for job " + id + " is not compatible with adaptive streaming.", null); response.sendError(HttpServletResponse.SC_NO_CONTENT, "Format is not supported for adaptive streaming."); } } catch (IOException ex) { // Called if client closes the connection early. } } @ResponseBody @RequestMapping(value="/segment/{id}/{type}/{extra}/{file}", method=RequestMethod.GET) public void getSegment(@PathVariable("id") UUID id, @PathVariable("type") String type, @PathVariable("extra") Integer extra, @PathVariable("file") String file, HttpServletRequest request, HttpServletResponse response) { Job job = null; TranscodeProfile profile; AdaptiveStreamingProcess transcodeProcess; SMSProcess process = null; File segment; try { // Retrieve Job job = jobDao.getJobByID(id); if(job == null) { LogService.getInstance().addLogEntry(LogService.Level.WARN, CLASS_NAME, "Failed to retrieve job with id " + id + ".", null); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to retrieve job."); return; } // Get transcode profile profile = transcodeService.getTranscodeProfile(id); if(profile == null) { LogService.getInstance().addLogEntry(LogService.Level.ERROR, CLASS_NAME, "Failed to retrieve transcode profile for job " + id + ".", null); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to retrieve transcode profile."); return; } // Get associated process transcodeProcess = adaptiveStreamingService.getProcessById(id); if(transcodeProcess == null) { LogService.getInstance().addLogEntry(LogService.Level.ERROR, CLASS_NAME, "Failed to find adaptive streaming process for job " + id + ".", null); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to retrieve transcode process."); return; } String mimeType; switch (profile.getFormat()) { case "hls": mimeType = "video/MP2T"; break; case "dash": mimeType = "video/mp4"; break; default: LogService.getInstance().addLogEntry(LogService.Level.WARN, CLASS_NAME, "Format for job " + id + " is not compatible with adaptive streaming.", null); response.sendError(HttpServletResponse.SC_NO_CONTENT, "Format is not supported for adaptive streaming."); return; } // Find Segment File segment = new File(SettingsService.getInstance().getCacheDirectory().getPath() + "/streams/" + id + "/" + file + "-" + type + "-" + extra); LogService.getInstance().addLogEntry(LogService.Level.DEBUG, CLASS_NAME, "Job ID=" + id + " Segment=" + file + " Type=" + type + " Extra=" + extra, null); if(profile.getFormat().equals("hls")) { // Update segment tracking int num = Integer.parseInt(file); int oldNum = transcodeProcess.getSegmentNum(); transcodeProcess.setSegmentNum(num); // If segment requested is not the next chronologically check if we need to start a new transcode process if(num != oldNum && num != (oldNum + 1) && !segment.exists()) { LogService.getInstance().addLogEntry(LogService.Level.DEBUG, CLASS_NAME, "Starting new transcode process.", null); adaptiveStreamingService.initialise(profile, num); } } File segmentList = new File(SettingsService.getInstance().getCacheDirectory().getPath() + "/streams/" + id + "/" + type + "-" + extra + ".txt"); int count = 0; // Wait for segment list to become available while(!segmentList.exists() && count < 5) { try { Thread.sleep(1000); } catch (InterruptedException ex) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error occured waiting for segment to become available."); } count++; } // Check if segment list is available if(!segmentList.exists()) { LogService.getInstance().addLogEntry(LogService.Level.WARN, CLASS_NAME, "Unable to get segment list for job " + id + ".", null); response.sendError(HttpServletResponse.SC_NO_CONTENT, "Unable to get segment list."); return; } List<String> segments = FileUtils.readFileToList(segmentList); count = 0; while(segments != null && !segments.contains(file + "-" + type + "-" + extra) && (count < 20)) { try { Thread.sleep(1000); } catch (InterruptedException ex) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error occured waiting for segment to become available."); } // Update segment list segments = FileUtils.readFileToList(segmentList); count++; } // Check if segment is definitely available if(count >= 20 || !segment.exists() || segments == null) { LogService.getInstance().addLogEntry(LogService.Level.WARN, CLASS_NAME, "Failed to return segment " + file + " for job " + id + ".", null); response.sendError(HttpServletResponse.SC_NO_CONTENT, "Requested segment is not available."); return; } if(profile.getMediaElement().getType().equals(MediaElementType.VIDEO)) { // Determine proper mimetype for audio if(type.equals("audio")) { switch(profile.getClient()) { case "chromecast": mimeType = TranscodeUtils.getMimeType(profile.getAudioTranscodes()[extra].getCodec(), MediaElementType.AUDIO); break; default: break; } } } process = new FileDownloadProcess(segment.toPath(), mimeType, request, response); process.start(); } catch (Exception ex) { // Called if client closes the connection early. LogService.getInstance().addLogEntry(LogService.Level.DEBUG, CLASS_NAME, "Client closed connection early (Job ID: " + id + " Segment: " + file + ")", ex); } finally { if(process != null && job != null) { jobDao.updateBytesTransferred(id, job.getBytesTransferred() + process.getBytesTransferred()); } } } @RequestMapping(value="/{id}", method=RequestMethod.GET) @ResponseBody public void getStream(@PathVariable("id") UUID id, @RequestParam(value = "atrack", required = false) Integer audioTrack, @RequestParam(value = "strack", required = false) Integer subtitleTrack, @RequestParam(value = "offset", required = false) Integer offset, HttpServletRequest request, HttpServletResponse response) { // Variables TranscodeProfile profile; Job job = null; SMSProcess process = null; /*********************** DEBUG: Get Request Headers *********************************/ String requestHeader = "\n***************\nRequest Header:\n***************\n"; Enumeration requestHeaderNames = request.getHeaderNames(); while (requestHeaderNames.hasMoreElements()) { String key = (String) requestHeaderNames.nextElement(); String value = request.getHeader(key); requestHeader += key + ": " + value + "\n"; } // Print Headers LogService.getInstance().addLogEntry(LogService.Level.INSANE, CLASS_NAME, requestHeader, null); /********************************************************************************/ try { // Retrieve Job job = jobDao.getJobByID(id); if(job == null) { LogService.getInstance().addLogEntry(LogService.Level.WARN, CLASS_NAME, "Failed to retrieve job with id " + id + ".", null); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to retrieve job."); return; } // Retrieve transcode profile profile = transcodeService.getTranscodeProfile(id); if(profile == null) { LogService.getInstance().addLogEntry(LogService.Level.WARN, CLASS_NAME, "Failed to retrieve transcode profile for job " + job.getID() + ".", null); response.sendError(HttpServletResponse.SC_NOT_FOUND, "Unable to retrieve transcode profile for job " + id + "."); return; } switch(profile.getType()) { case StreamType.LOCAL: case StreamType.REMOTE: if(profile.getFormat().equals("hls")) { adaptiveStreamingService.sendHLSPlaylist(id, null, null, request, response); } else if(profile.getFormat().equals("dash")) { adaptiveStreamingService.sendDashPlaylist(id, request, response); } break; case StreamType.DIRECT: if(profile.getMediaElement() == null) { LogService.getInstance().addLogEntry(LogService.Level.WARN, CLASS_NAME, "Failed to retrieve media element for job " + job.getID() + ".", null); response.sendError(HttpServletResponse.SC_NOT_FOUND, "Unable to find media element."); return; } process = new FileDownloadProcess(Paths.get(profile.getMediaElement().getPath()), profile.getMimeType(), request, response); process.start(); break; default: LogService.getInstance().addLogEntry(LogService.Level.WARN, CLASS_NAME, "Failed to determine stream type for job " + job.getID() + ".", null); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Cannot determine stream type."); } } catch (Exception ex) { // Called if client closes the connection early. if(process != null) { process.end(); } } finally { if(job != null && process != null) { jobDao.updateBytesTransferred(id, job.getBytesTransferred() + process.getBytesTransferred()); } } } }
Streaming: Fix setting of direct play flag Signed-off-by: Scott Ware <[email protected]>
src/main/java/com/scooter1556/sms/server/controller/StreamController.java
Streaming: Fix setting of direct play flag
Java
mit
a6d5b822e27479dd84c2f104af495afef79a59c9
0
McJty/DeepResonance
package mcjty.deepresonance.blocks.pedestal; import mcjty.deepresonance.blocks.ModBlocks; import mcjty.deepresonance.blocks.collector.EnergyCollectorSetup; import mcjty.deepresonance.blocks.collector.EnergyCollectorTileEntity; import mcjty.deepresonance.blocks.crystals.ResonatingCrystalTileEntity; import mcjty.deepresonance.config.ConfigMachines; import mcjty.lib.container.DefaultSidedInventory; import mcjty.lib.container.InventoryHelper; import mcjty.lib.container.InventoryLocator; import mcjty.lib.entity.GenericTileEntity; import mcjty.lib.varia.OrientationTools; import mcjty.lib.varia.SoundTools; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.EnumFacing; import net.minecraft.util.ITickable; import net.minecraft.util.math.BlockPos; import net.minecraft.world.WorldServer; import net.minecraftforge.common.util.FakePlayerFactory; import java.util.Optional; public class PedestalTileEntity extends GenericTileEntity implements DefaultSidedInventory, ITickable { private InventoryHelper inventoryHelper = new InventoryHelper(this, PedestalContainer.factory, 1); private int checkCounter = 0; // Cache for the inventory used to put the spent crystal material in. private InventoryLocator inventoryLocator = new InventoryLocator(); private BlockPos cachedLocator = null; @Override public InventoryHelper getInventoryHelper() { return inventoryHelper; } @Override protected boolean needsCustomInvWrapper() { return true; } @Override public void update() { if (!getWorld().isRemote){ checkStateServer(); } } protected void checkStateServer() { checkCounter--; if (checkCounter > 0) { return; } checkCounter = 20; BlockPos b = this.getCrystalPosition(); if (getWorld().isAirBlock(b)) { // Nothing in front. We can place a new crystal if we have one. placeCrystal(); } else if (getWorld().getBlockState(b).getBlock() == ModBlocks.resonatingCrystalBlock) { // Check if the crystal in front of us still has power. // If not we will remove it. checkCrystal(); } // else we can do nothing. } public BlockPos getCrystalPosition() { IBlockState state = getWorld().getBlockState(getPos()); EnumFacing orientation = OrientationTools.getOrientation(state); return pos.offset(orientation); } public Optional<ResonatingCrystalTileEntity> getCrystal() { BlockPos p = this.getCrystalPosition(); TileEntity t = getWorld().getTileEntity(p); if (t instanceof ResonatingCrystalTileEntity) { return Optional.of((ResonatingCrystalTileEntity)t); } return Optional.empty(); } public boolean crystalPresent() { return getWorld().getBlockState(this.getCrystalPosition()).getBlock() == ModBlocks.resonatingCrystalBlock; } private void placeCrystal() { BlockPos pos = getCrystalPosition(); ItemStack crystalStack = inventoryHelper.getStackInSlot(PedestalContainer.SLOT_CRYSTAL); if (!crystalStack.isEmpty()) { if (crystalStack.getItem() instanceof ItemBlock) { ItemBlock itemBlock = (ItemBlock) (crystalStack.getItem()); itemBlock.placeBlockAt(crystalStack, FakePlayerFactory.getMinecraft((WorldServer) getWorld()), getWorld(), pos, null, 0, 0, 0, itemBlock.getBlock().getStateFromMeta(0)); inventoryHelper.decrStackSize(PedestalContainer.SLOT_CRYSTAL, 1); SoundTools.playSound(getWorld(), ModBlocks.resonatingCrystalBlock.getSoundType().breakSound, getPos().getX(), getPos().getY(), getPos().getZ(), 1.0f, 1.0f); if (findCollector()) { TileEntity tileEntity = getWorld().getTileEntity(new BlockPos(cachedLocator)); if (tileEntity instanceof EnergyCollectorTileEntity) { EnergyCollectorTileEntity energyCollectorTileEntity = (EnergyCollectorTileEntity) tileEntity; energyCollectorTileEntity.addCrystal(pos.getX(), pos.getY(), pos.getZ()); } } } } } private static EnumFacing[] directions = new EnumFacing[] { EnumFacing.EAST, EnumFacing.WEST, EnumFacing.NORTH, EnumFacing.SOUTH, EnumFacing.UP, EnumFacing.DOWN }; private void checkCrystal() { BlockPos p = getCrystalPosition(); Optional<Boolean> powerLow = getCrystal().map(tile -> tile.getPower() <= EnergyCollectorTileEntity.CRYSTAL_MIN_POWER); if (powerLow.orElse(false)) { dropCrystal(); } } public void dropCrystal() { Optional<ResonatingCrystalTileEntity> crystal = getCrystal(); if (!crystal.isPresent()) { return; } ResonatingCrystalTileEntity resonatingCrystalTileEntity = crystal.get(); BlockPos p = resonatingCrystalTileEntity.getPos(); ItemStack spentCrystal = new ItemStack(ModBlocks.resonatingCrystalBlock, 1); NBTTagCompound tagCompound = new NBTTagCompound(); resonatingCrystalTileEntity.writeRestorableToNBT(tagCompound); spentCrystal.setTagCompound(tagCompound); inventoryLocator.ejectStack(getWorld(), getPos(), spentCrystal, pos, directions); getWorld().setBlockToAir(p); SoundTools.playSound(getWorld(), ModBlocks.resonatingCrystalBlock.getSoundType().breakSound, p.getX(), p.getY(), p.getZ(), 1.0f, 1.0f); } private boolean findCollector() { BlockPos crystalLocation = getCrystalPosition(); if (cachedLocator != null) { if (getWorld().getBlockState(cachedLocator).getBlock() == EnergyCollectorSetup.energyCollectorBlock) { return true; } cachedLocator = null; } float closestDistance = Float.MAX_VALUE; int yy = crystalLocation.getY(), xx = crystalLocation.getX(), zz = crystalLocation.getZ(); for (int y = yy - ConfigMachines.collector.maxVerticalCrystalDistance ; y <= yy + ConfigMachines.collector.maxVerticalCrystalDistance ; y++) { if (y >= 0 && y < getWorld().getHeight()) { int maxhordist = ConfigMachines.collector.maxHorizontalCrystalDistance; for (int x = xx - maxhordist; x <= xx + maxhordist; x++) { for (int z = zz - maxhordist; z <= zz + maxhordist; z++) { BlockPos pos = new BlockPos(x, y, z); if (getWorld().getBlockState(pos).getBlock() == EnergyCollectorSetup.energyCollectorBlock) { double sqdist = pos.distanceSq(crystalLocation); if (sqdist < closestDistance) { closestDistance = (float)sqdist; cachedLocator = pos; } } } } } } return cachedLocator != null; } @Override public void readFromNBT(NBTTagCompound tagCompound) { super.readFromNBT(tagCompound); } @Override public void readRestorableFromNBT(NBTTagCompound tagCompound) { super.readRestorableFromNBT(tagCompound); readBufferFromNBT(tagCompound, inventoryHelper); } @Override public NBTTagCompound writeToNBT(NBTTagCompound tagCompound) { super.writeToNBT(tagCompound); return tagCompound; } @Override public void writeRestorableToNBT(NBTTagCompound tagCompound) { super.writeRestorableToNBT(tagCompound); writeBufferToNBT(tagCompound, inventoryHelper); } @Override public int[] getSlotsForFace(EnumFacing side) { return new int[] { PedestalContainer.SLOT_CRYSTAL }; } @Override public boolean canExtractItem(int index, ItemStack stack, EnumFacing direction) { return false; } @Override public boolean canInsertItem(int index, ItemStack itemStackIn, EnumFacing direction) { return isItemValidForSlot(index, itemStackIn); } @Override public int getInventoryStackLimit() { return 1; } @Override public boolean isEmpty() { return false; } @Override public boolean isUsableByPlayer(EntityPlayer player) { return canPlayerAccess(player); } @Override public boolean isItemValidForSlot(int index, ItemStack stack) { return stack.getItem() == Item.getItemFromBlock(ModBlocks.resonatingCrystalBlock); } }
src/main/java/mcjty/deepresonance/blocks/pedestal/PedestalTileEntity.java
package mcjty.deepresonance.blocks.pedestal; import mcjty.deepresonance.blocks.ModBlocks; import mcjty.deepresonance.blocks.collector.EnergyCollectorSetup; import mcjty.deepresonance.blocks.collector.EnergyCollectorTileEntity; import mcjty.deepresonance.blocks.crystals.ResonatingCrystalTileEntity; import mcjty.deepresonance.config.ConfigMachines; import mcjty.lib.container.DefaultSidedInventory; import mcjty.lib.container.InventoryHelper; import mcjty.lib.container.InventoryLocator; import mcjty.lib.entity.GenericTileEntity; import mcjty.lib.varia.OrientationTools; import mcjty.lib.varia.SoundTools; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.EnumFacing; import net.minecraft.util.ITickable; import net.minecraft.util.math.BlockPos; import net.minecraft.world.WorldServer; import net.minecraftforge.common.util.FakePlayerFactory; import java.util.Optional; public class PedestalTileEntity extends GenericTileEntity implements DefaultSidedInventory, ITickable { private InventoryHelper inventoryHelper = new InventoryHelper(this, PedestalContainer.factory, 1); private int checkCounter = 0; // Cache for the inventory used to put the spent crystal material in. private InventoryLocator inventoryLocator = new InventoryLocator(); private BlockPos cachedLocator = null; @Override public InventoryHelper getInventoryHelper() { return inventoryHelper; } @Override protected boolean needsCustomInvWrapper() { return true; } @Override public void update() { if (!getWorld().isRemote){ checkStateServer(); } } protected void checkStateServer() { checkCounter--; if (checkCounter > 0) { return; } checkCounter = 20; BlockPos b = this.getCrystalPosition(); if (getWorld().isAirBlock(b)) { // Nothing in front. We can place a new crystal if we have one. placeCrystal(); } else if (getWorld().getBlockState(b).getBlock() == ModBlocks.resonatingCrystalBlock) { // Check if the crystal in front of us still has power. // If not we will remove it. checkCrystal(); } // else we can do nothing. } public BlockPos getCrystalPosition() { IBlockState state = getWorld().getBlockState(getPos()); EnumFacing orientation = OrientationTools.getOrientation(state); return pos.offset(orientation); } public Optional<ResonatingCrystalTileEntity> getCrystal() { BlockPos p = this.getCrystalPosition(); TileEntity t = getWorld().getTileEntity(p); if (t instanceof ResonatingCrystalTileEntity) { return Optional.of((ResonatingCrystalTileEntity)t); } return Optional.empty(); } public boolean crystalPresent() { return getWorld().getBlockState(this.getCrystalPosition()).getBlock() == ModBlocks.resonatingCrystalBlock; } private void placeCrystal() { BlockPos pos = getCrystalPosition(); ItemStack crystalStack = inventoryHelper.getStackInSlot(PedestalContainer.SLOT_CRYSTAL); if (!crystalStack.isEmpty()) { if (crystalStack.getItem() instanceof ItemBlock) { ItemBlock itemBlock = (ItemBlock) (crystalStack.getItem()); itemBlock.placeBlockAt(crystalStack, FakePlayerFactory.getMinecraft((WorldServer) getWorld()), getWorld(), pos, null, 0, 0, 0, itemBlock.getBlock().getStateFromMeta(0)); inventoryHelper.decrStackSize(PedestalContainer.SLOT_CRYSTAL, 1); SoundTools.playSound(getWorld(), ModBlocks.resonatingCrystalBlock.getSoundType().breakSound, getPos().getX(), getPos().getY(), getPos().getZ(), 1.0f, 1.0f); if (findCollector()) { TileEntity tileEntity = getWorld().getTileEntity(new BlockPos(cachedLocator)); if (tileEntity instanceof EnergyCollectorTileEntity) { EnergyCollectorTileEntity energyCollectorTileEntity = (EnergyCollectorTileEntity) tileEntity; energyCollectorTileEntity.addCrystal(pos.getX(), pos.getY(), pos.getZ()); } } } } } private static EnumFacing[] directions = new EnumFacing[] { EnumFacing.EAST, EnumFacing.WEST, EnumFacing.NORTH, EnumFacing.SOUTH, EnumFacing.UP, EnumFacing.DOWN }; private void checkCrystal() { BlockPos p = getCrystalPosition(); Optional<Boolean> powerLow = getCrystal().map(tile -> tile.getPower() <= EnergyCollectorTileEntity.CRYSTAL_MIN_POWER); if (powerLow.orElse(false)) { dropCrystal(); } } public void dropCrystal() { Optional<ResonatingCrystalTileEntity> crystal = getCrystal(); if (!crystal.isPresent()) { return; } ResonatingCrystalTileEntity resonatingCrystalTileEntity = crystal.get(); BlockPos p = resonatingCrystalTileEntity.getPos(); ItemStack spentCrystal = new ItemStack(ModBlocks.resonatingCrystalBlock, 1); NBTTagCompound tagCompound = new NBTTagCompound(); resonatingCrystalTileEntity.writeToNBT(tagCompound); spentCrystal.setTagCompound(tagCompound); inventoryLocator.ejectStack(getWorld(), getPos(), spentCrystal, pos, directions); getWorld().setBlockToAir(p); SoundTools.playSound(getWorld(), ModBlocks.resonatingCrystalBlock.getSoundType().breakSound, p.getX(), p.getY(), p.getZ(), 1.0f, 1.0f); } private boolean findCollector() { BlockPos crystalLocation = getCrystalPosition(); if (cachedLocator != null) { if (getWorld().getBlockState(cachedLocator).getBlock() == EnergyCollectorSetup.energyCollectorBlock) { return true; } cachedLocator = null; } float closestDistance = Float.MAX_VALUE; int yy = crystalLocation.getY(), xx = crystalLocation.getX(), zz = crystalLocation.getZ(); for (int y = yy - ConfigMachines.collector.maxVerticalCrystalDistance ; y <= yy + ConfigMachines.collector.maxVerticalCrystalDistance ; y++) { if (y >= 0 && y < getWorld().getHeight()) { int maxhordist = ConfigMachines.collector.maxHorizontalCrystalDistance; for (int x = xx - maxhordist; x <= xx + maxhordist; x++) { for (int z = zz - maxhordist; z <= zz + maxhordist; z++) { BlockPos pos = new BlockPos(x, y, z); if (getWorld().getBlockState(pos).getBlock() == EnergyCollectorSetup.energyCollectorBlock) { double sqdist = pos.distanceSq(crystalLocation); if (sqdist < closestDistance) { closestDistance = (float)sqdist; cachedLocator = pos; } } } } } } return cachedLocator != null; } @Override public void readFromNBT(NBTTagCompound tagCompound) { super.readFromNBT(tagCompound); } @Override public void readRestorableFromNBT(NBTTagCompound tagCompound) { super.readRestorableFromNBT(tagCompound); readBufferFromNBT(tagCompound, inventoryHelper); } @Override public NBTTagCompound writeToNBT(NBTTagCompound tagCompound) { super.writeToNBT(tagCompound); return tagCompound; } @Override public void writeRestorableToNBT(NBTTagCompound tagCompound) { super.writeRestorableToNBT(tagCompound); writeBufferToNBT(tagCompound, inventoryHelper); } @Override public int[] getSlotsForFace(EnumFacing side) { return new int[] { PedestalContainer.SLOT_CRYSTAL }; } @Override public boolean canExtractItem(int index, ItemStack stack, EnumFacing direction) { return false; } @Override public boolean canInsertItem(int index, ItemStack itemStackIn, EnumFacing direction) { return isItemValidForSlot(index, itemStackIn); } @Override public int getInventoryStackLimit() { return 1; } @Override public boolean isEmpty() { return false; } @Override public boolean isUsableByPlayer(EntityPlayer player) { return canPlayerAccess(player); } @Override public boolean isItemValidForSlot(int index, ItemStack stack) { return stack.getItem() == Item.getItemFromBlock(ModBlocks.resonatingCrystalBlock); } }
Fix #260
src/main/java/mcjty/deepresonance/blocks/pedestal/PedestalTileEntity.java
Fix #260
Java
mit
eedb18a2c40cf8feeb509ccf93f3833b0c2e9188
0
Guerra24/Voxel
/* * This file is part of Voxel * * Copyright (C) 2016 Lux Vacuos * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package net.luxvacuos.voxel.universal.tests; import static org.junit.Assert.*; import org.junit.After; import org.junit.Before; import org.junit.Test; public class ChunkTest { @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } @Test public void test() { //fail("Not yet implemented"); } }
universal/src/test/java/net/luxvacuos/voxel/universal/tests/ChunkTest.java
/* * This file is part of Voxel * * Copyright (C) 2016 Lux Vacuos * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package net.luxvacuos.voxel.universal.tests; import static org.junit.Assert.*; import org.junit.After; import org.junit.Before; import org.junit.Test; public class ChunkTest { @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } @Test public void test() { fail("Not yet implemented"); } }
Apparently Travis will fail a build because of this
universal/src/test/java/net/luxvacuos/voxel/universal/tests/ChunkTest.java
Apparently Travis will fail a build because of this
Java
epl-1.0
437089698812fc4c794d1f07ff59d9e9439d6fe6
0
debrief/limpet,debrief/limpet,debrief/limpet
package info.limpet.data2; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import info.limpet.ICommand; import info.limpet.IContext; import info.limpet.IOperation; import info.limpet.IStoreGroup; import info.limpet.IStoreItem; import info.limpet.impl.Document; import info.limpet.impl.LocationDocument; import info.limpet.impl.MockContext; import info.limpet.impl.NumberDocument; import info.limpet.impl.NumberDocumentBuilder; import info.limpet.impl.SampleData; import info.limpet.impl.StoreGroup; import info.limpet.operations.arithmetic.simple.AddLogQuantityOperation; import info.limpet.operations.arithmetic.simple.AddQuantityOperation; import info.limpet.operations.arithmetic.simple.SubtractLogQuantityOperation; import info.limpet.operations.arithmetic.simple.SubtractQuantityOperation; import info.limpet.operations.spatial.GeoSupport; import info.limpet.operations.spatial.IGeoCalculator; import info.limpet.operations.spatial.ProplossBetweenTwoTracksOperation; import info.limpet.operations.spatial.msa.BistaticAngleOperation; import info.limpet.persistence.csv.CsvParser; import java.awt.geom.Point2D; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.measure.unit.SI; import org.junit.Test; public class TestBistaticAngleCalculations { final private IContext context = new MockContext(); @Test public void testLoadTracks() throws IOException { File file = TestCsvParser.getDataFile("multistatics/tx1_stat.csv"); assertTrue(file.isFile()); CsvParser parser = new CsvParser(); List<IStoreItem> items = parser.parse(file.getAbsolutePath()); assertEquals("correct group", 1, items.size()); LocationDocument doc = (LocationDocument) items.get(0); assertEquals("singleton", 1, doc.size()); } @Test public void testAddLogData() throws IOException { IStoreGroup store = new StoreGroup("data"); // now get our tracks File file = TestCsvParser.getDataFile("multistatics/tx1_stat.csv"); assertTrue(file.isFile()); CsvParser parser = new CsvParser(); List<IStoreItem> tx1 = parser.parse(file.getAbsolutePath()); store.addAll(tx1); file = TestCsvParser.getDataFile("multistatics/rx1_stat.csv"); assertTrue(file.isFile()); List<IStoreItem> rx1 = parser.parse(file.getAbsolutePath()); store.addAll(rx1); file = TestCsvParser.getDataFile("multistatics/ssn_stat.csv"); assertTrue(file.isFile()); List<IStoreItem> ssn = parser.parse(file.getAbsolutePath()); store.addAll(ssn); IOperation pDiff = new ProplossBetweenTwoTracksOperation(); List<IStoreItem> selection = new ArrayList<IStoreItem>(); selection.add(tx1.get(0)); selection.add(ssn.get(0)); List<ICommand> actions = pDiff.actionsFor(selection, store, context); assertNotNull("found actions"); assertEquals("got actions", 1, actions.size()); assertEquals("store has original data", 3, store.size()); // run it actions.get(0).execute(); assertEquals("has new data", 4, store.size()); Document<?> txProp = actions.get(0).getOutputs().get(0); txProp.setName("txProp"); // now the other proploss file selection.clear(); selection.add(rx1.get(0)); selection.add(ssn.get(0)); actions = pDiff.actionsFor(selection, store, context); assertNotNull("found actions"); assertEquals("got actions", 1, actions.size()); assertEquals("store has original data", 4, store.size()); // run it actions.get(0).execute(); assertEquals("has new data", 5, store.size()); Document<?> rxProp = actions.get(0).getOutputs().get(0); rxProp.setName("rxProp"); // ok, now we can try to add them IOperation addL = new AddLogQuantityOperation(); IOperation add = new AddQuantityOperation(); selection.clear(); selection.add(txProp); selection.add(rxProp); // check the normal adder drops out actions = add.actionsFor(selection, store, context); assertEquals("no actions returned", 0, actions.size()); // now the log adder actions = addL.actionsFor(selection, store, context); assertEquals("actions returned", 1, actions.size()); // ok, run the first action actions.get(0).execute(); assertEquals("has new data", 6, store.size()); // check the outputs NumberDocument propSum = (NumberDocument) actions.get(0).getOutputs().get(0); propSum.setName("propSum"); // ok, check the values double valA = txProp.getDataset().getDouble(0); double valB = rxProp.getDataset().getDouble(0); double addRes = propSum.getDataset().getDouble(0); double testSum = doLogAdd(valA, valB); assertEquals("correct log sum", testSum, addRes, 0.0001); // ok, change the selection so we can do the reverse of the add selection.clear(); selection.add(propSum); selection.add(rxProp); // hmm, go for the subtract IOperation sub = new SubtractQuantityOperation(); IOperation subL = new SubtractLogQuantityOperation(); actions = sub.actionsFor(selection, store, context); assertEquals("none returned", 0, actions.size()); actions = subL.actionsFor(selection, store, context); assertEquals("actions returned", 2, actions.size()); // ok, run it actions.get(0).execute(); assertEquals("has new data", 7, store.size()); // check the results NumberDocument propDiff = (NumberDocument) actions.get(0).getOutputs().get(0); propDiff.setName("propDiff"); double subRes = propDiff.getDataset().getDouble(0); double testSubtract = doLogSubtract(addRes, valB); assertEquals("correct log sum", testSubtract, subRes, 0.0001); } private double doLogAdd(double valA, double valB) { double aN = Math.pow(10d, valA / 10d); double bN = Math.pow(10d, valB / 10d); double sum = aN + bN; double toLog = Math.log10(sum) * 10d; return toLog; } private double doLogSubtract(double valA, double valB) { double aN = Math.pow(10d, valA / 10d); double bN = Math.pow(10d, valB / 10d); double sum = aN - bN; double toLog = Math.log10(sum) * 10d; return toLog; } @Test public void testCreateActions() throws IOException { IStoreGroup store = new StoreGroup("data"); // now get our tracks File file = TestCsvParser.getDataFile("multistatics/tx1_stat.csv"); assertTrue(file.isFile()); CsvParser parser = new CsvParser(); List<IStoreItem> tx1 = parser.parse(file.getAbsolutePath()); store.addAll(tx1); file = TestCsvParser.getDataFile("multistatics/rx1_stat.csv"); assertTrue(file.isFile()); List<IStoreItem> rx1 = parser.parse(file.getAbsolutePath()); store.addAll(rx1); file = TestCsvParser.getDataFile("multistatics/ssn_stat.csv"); assertTrue(file.isFile()); List<IStoreItem> ssn = parser.parse(file.getAbsolutePath()); store.addAll(ssn); // check data loaded assertEquals("have all 3 tracks", 3, store.size()); // ok, generate the command BistaticAngleOperation generator = new BistaticAngleOperation(); List<IStoreItem> selection = new ArrayList<IStoreItem>(); // just one track selection.add(store.iterator().next()); List<ICommand> actions = generator.actionsFor(selection, store, context); assertEquals("correct actions", 0, actions.size()); // and two tracks selection.clear(); selection.add(tx1.get(0)); selection.add(ssn.get(0)); selection.add(rx1.get(0)); actions = generator.actionsFor(selection, store, context); assertEquals("correct actions", 2, actions.size()); // check the store contents assertEquals("correct datasets", 3, store.size()); // run the operation actions.get(0).execute(); assertEquals("new datasets generated", 6, store.size()); } @Test public void testCalculation() { NumberDocumentBuilder bi = new NumberDocumentBuilder("Bi angle", SampleData.DEGREE_ANGLE, null, SI.SECOND); NumberDocumentBuilder biA = new NumberDocumentBuilder("Bi Aspect angle", SampleData.DEGREE_ANGLE, null, SI.SECOND); NumberDocumentBuilder azA = new NumberDocumentBuilder("Azimuth angle", SampleData.DEGREE_ANGLE, null, SI.SECOND); double heading = 15; Point2D tx = new Point2D.Double(2, 2); Point2D tgt = new Point2D.Double(0, 0); Point2D rx = new Point2D.Double(2, -2); final double time = 1000d; final IGeoCalculator calc = GeoSupport.getCalculatorWGS84(); BistaticAngleOperation.calcAndStore(calc, tx, tgt, rx, heading, time, bi, biA, azA); // look at hte results assertEquals("correct Az angle", 30, azA.getValues().get(0), 1); assertEquals("correct bi angle", 90, bi.getValues().get(0), 1); assertEquals("correct bi A angle", 75, biA.getValues().get(0), 1); bi.clear(); biA.clear(); azA.clear(); // try another permutation heading = 45; tx = new Point2D.Double(4, 0); rx = new Point2D.Double(3, -3); BistaticAngleOperation.calcAndStore(calc, tx, tgt, rx, heading, time, bi, biA, azA); // look at the results assertEquals("correct Az angle", 45, azA.getValues().get(0), 1); assertEquals("correct bi angle", 45, bi.getValues().get(0), 1); assertEquals("correct bi A angle", 67, biA.getValues().get(0), 1); heading = 326; bi.clear(); biA.clear(); azA.clear(); BistaticAngleOperation.calcAndStore(calc, tx, tgt, rx, heading, time, bi, biA, azA); // look at the results assertEquals("correct az angle", 124, azA.getValues().get(0), 1); assertEquals("correct bi angle", 45, bi.getValues().get(0), 1); assertEquals("correct bi A angle", 147, biA.getValues().get(0), 1); tx.setLocation(1.4, 1.1); rx.setLocation(1.3, 1.3); tgt.setLocation(1, 1); heading = 0; bi.clear(); biA.clear(); BistaticAngleOperation.calcAndStore(calc, tx, tgt, rx, heading, time, bi, biA, azA); // look at the results assertEquals("correct bi angle", 30, bi.getValues().get(0), 1); assertEquals("correct bi A angle", 60, biA.getValues().get(0), 1); tx.setLocation(1.2, 1.05); rx.setLocation(1.1, 1.17); tgt.setLocation(1, 1); heading = 356; bi.clear(); biA.clear(); BistaticAngleOperation.calcAndStore(calc, tx, tgt, rx, heading, time, bi, biA, azA); // look at the results assertEquals("correct bi angle", 45, bi.getValues().get(0), 1); assertEquals("correct bi A angle", 57, biA.getValues().get(0), 1); } }
info.limpet.test/src/info/limpet/data2/TestBistaticAngleCalculations.java
package info.limpet.data2; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import info.limpet.ICommand; import info.limpet.IContext; import info.limpet.IOperation; import info.limpet.IStoreGroup; import info.limpet.IStoreItem; import info.limpet.impl.Document; import info.limpet.impl.LocationDocument; import info.limpet.impl.MockContext; import info.limpet.impl.NumberDocument; import info.limpet.impl.NumberDocumentBuilder; import info.limpet.impl.SampleData; import info.limpet.impl.StoreGroup; import info.limpet.operations.arithmetic.simple.AddLogQuantityOperation; import info.limpet.operations.arithmetic.simple.AddQuantityOperation; import info.limpet.operations.arithmetic.simple.SubtractLogQuantityOperation; import info.limpet.operations.arithmetic.simple.SubtractQuantityOperation; import info.limpet.operations.spatial.GeoSupport; import info.limpet.operations.spatial.IGeoCalculator; import info.limpet.operations.spatial.ProplossBetweenTwoTracksOperation; import info.limpet.operations.spatial.msa.BistaticAngleOperation; import info.limpet.persistence.csv.CsvParser; import java.awt.geom.Point2D; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.measure.unit.SI; import org.junit.Test; public class TestBistaticAngleCalculations { final private IContext context = new MockContext(); @Test public void testLoadTracks() throws IOException { File file = TestCsvParser.getDataFile("multistatics/tx1_stat.csv"); assertTrue(file.isFile()); CsvParser parser = new CsvParser(); List<IStoreItem> items = parser.parse(file.getAbsolutePath()); assertEquals("correct group", 1, items.size()); LocationDocument doc = (LocationDocument) items.get(0); assertEquals("singleton", 1, doc.size()); } @Test public void testAddLogData() throws IOException { IStoreGroup store = new StoreGroup("data"); // now get our tracks File file = TestCsvParser.getDataFile("multistatics/tx1_stat.csv"); assertTrue(file.isFile()); CsvParser parser = new CsvParser(); List<IStoreItem> tx1 = parser.parse(file.getAbsolutePath()); store.addAll(tx1); file = TestCsvParser.getDataFile("multistatics/rx1_stat.csv"); assertTrue(file.isFile()); List<IStoreItem> rx1 = parser.parse(file.getAbsolutePath()); store.addAll(rx1); file = TestCsvParser.getDataFile("multistatics/ssn_stat.csv"); assertTrue(file.isFile()); List<IStoreItem> ssn = parser.parse(file.getAbsolutePath()); store.addAll(ssn); IOperation pDiff = new ProplossBetweenTwoTracksOperation(); List<IStoreItem> selection = new ArrayList<IStoreItem>(); selection.add(tx1.get(0)); selection.add(ssn.get(0)); List<ICommand> actions = pDiff.actionsFor(selection, store, context); assertNotNull("found actions"); assertEquals("got actions", 1, actions.size()); assertEquals("store has original data", 3, store.size()); // run it actions.get(0).execute(); assertEquals("has new data", 4, store.size()); Document<?> txProp = actions.get(0).getOutputs().get(0); txProp.setName("txProp"); // now the other proploss file selection.clear(); selection.add(rx1.get(0)); selection.add(ssn.get(0)); actions = pDiff.actionsFor(selection, store, context); assertNotNull("found actions"); assertEquals("got actions", 1, actions.size()); assertEquals("store has original data", 4, store.size()); // run it actions.get(0).execute(); assertEquals("has new data", 5, store.size()); Document<?> rxProp = actions.get(0).getOutputs().get(0); rxProp.setName("rxProp"); // ok, now we can try to add them IOperation addL = new AddLogQuantityOperation(); IOperation add = new AddQuantityOperation(); selection.clear(); selection.add(txProp); selection.add(rxProp); // check the normal adder drops out actions = add.actionsFor(selection, store, context); assertEquals("no actions returned", 0, actions.size()); // now the log adder actions = addL.actionsFor(selection, store, context); assertEquals("actions returned", 1, actions.size()); // ok, run the first action actions.get(0).execute(); assertEquals("has new data", 6, store.size()); // check the outputs NumberDocument propSum = (NumberDocument) actions.get(0).getOutputs().get(0); propSum.setName("propSum"); // ok, check the values double valA = txProp.getDataset().getDouble(0); double valB = rxProp.getDataset().getDouble(0); double addRes = propSum.getDataset().getDouble(0); double testSum = doLogAdd(valA, valB); assertEquals("correct log sum", testSum, addRes, 0.0001); // ok, change the selection so we can do the reverse of the add selection.clear(); selection.add(propSum); selection.add(rxProp); // hmm, go for the subtract IOperation sub = new SubtractQuantityOperation(); IOperation subL = new SubtractLogQuantityOperation(); actions = sub.actionsFor(selection, store, context); assertEquals("none returned", 0, actions.size()); actions = subL.actionsFor(selection, store, context); assertEquals("actions returned", 2, actions.size()); // ok, run it actions.get(0).execute(); assertEquals("has new data", 7, store.size()); // check the results NumberDocument propDiff = (NumberDocument) actions.get(0).getOutputs().get(0); propDiff.setName("propDiff"); double subRes = propDiff.getDataset().getDouble(0); double testSubtract = doLogSubtract(addRes, valB); assertEquals("correct log sum", testSubtract, subRes, 0.0001); } private double doLogAdd(double valA, double valB) { double aN = Math.pow(10d, valA / 10d); double bN = Math.pow(10d, valB / 10d); double sum = aN + bN; double toLog = Math.log10(sum) * 10d; return toLog; } private double doLogSubtract(double valA, double valB) { double aN = Math.pow(10d, valA / 10d); double bN = Math.pow(10d, valB / 10d); double sum = aN - bN; double toLog = Math.log10(sum) * 10d; return toLog; } @Test public void testCreateActions() throws IOException { IStoreGroup store = new StoreGroup("data"); // now get our tracks File file = TestCsvParser.getDataFile("multistatics/tx1_stat.csv"); assertTrue(file.isFile()); CsvParser parser = new CsvParser(); List<IStoreItem> tx1 = parser.parse(file.getAbsolutePath()); store.addAll(tx1); file = TestCsvParser.getDataFile("multistatics/rx1_stat.csv"); assertTrue(file.isFile()); List<IStoreItem> rx1 = parser.parse(file.getAbsolutePath()); store.addAll(rx1); file = TestCsvParser.getDataFile("multistatics/ssn_stat.csv"); assertTrue(file.isFile()); List<IStoreItem> ssn = parser.parse(file.getAbsolutePath()); store.addAll(ssn); // check data loaded assertEquals("have all 3 tracks", 3, store.size()); // ok, generate the command BistaticAngleOperation generator = new BistaticAngleOperation(); List<IStoreItem> selection = new ArrayList<IStoreItem>(); // just one track selection.add(store.iterator().next()); List<ICommand> actions = generator.actionsFor(selection, store, context); assertEquals("correct actions", 0, actions.size()); // and two tracks selection.clear(); selection.add(tx1.get(0)); selection.add(ssn.get(0)); selection.add(rx1.get(0)); actions = generator.actionsFor(selection, store, context); assertEquals("correct actions", 1, actions.size()); // check the store contents assertEquals("correct datasets", 3, store.size()); } @Test public void testCalculation() { NumberDocumentBuilder bi = new NumberDocumentBuilder("Bi angle", SampleData.DEGREE_ANGLE, null, SI.SECOND); NumberDocumentBuilder biA = new NumberDocumentBuilder("Bi Aspect angle", SampleData.DEGREE_ANGLE, null, SI.SECOND); double heading = 15; Point2D tx = new Point2D.Double(2, 1); Point2D tgt = new Point2D.Double(1, 1); Point2D rx = new Point2D.Double(1.1, 0); final double time = 1000d; final IGeoCalculator calc = GeoSupport.getCalculatorWGS84(); BistaticAngleOperation.calcAndStore(calc, tx, tgt, rx, heading, time, bi, biA); // look at hte results assertEquals("correct bi angle", 85, bi.getValues().get(0), 1); assertEquals("correct bi A angle", 117, biA.getValues().get(0), 1); bi.clear(); biA.clear(); // try another permutation rx = new Point2D.Double(2, 1.5); BistaticAngleOperation.calcAndStore(calc, tx, tgt, rx, heading, time, bi, biA); // look at the results assertEquals("correct bi angle", 26, bi.getValues().get(0), 1); assertEquals("correct bi A angle", 61, biA.getValues().get(0), 1); heading = 326; bi.clear(); biA.clear(); BistaticAngleOperation.calcAndStore(calc, tx, tgt, rx, heading, time, bi, biA); // look at the results assertEquals("correct bi angle", 26, bi.getValues().get(0), 1); assertEquals("correct bi A angle", 110, biA.getValues().get(0), 1); tx.setLocation(1.4, 1.1); rx.setLocation(1.3, 1.3); tgt.setLocation(1, 1); heading = 0; bi.clear(); biA.clear(); BistaticAngleOperation.calcAndStore(calc, tx, tgt, rx, heading, time, bi, biA); // look at the results assertEquals("correct bi angle", 30, bi.getValues().get(0), 1); assertEquals("correct bi A angle", 60, biA.getValues().get(0), 1); tx.setLocation(1.2, 1.05); rx.setLocation(1.1, 1.17); tgt.setLocation(1, 1); heading = 356; bi.clear(); biA.clear(); BistaticAngleOperation.calcAndStore(calc, tx, tgt, rx, heading, time, bi, biA); // look at the results assertEquals("correct bi angle", 45, bi.getValues().get(0), 1); assertEquals("correct bi A angle", 57, biA.getValues().get(0), 1); } }
improve testing of calcs
info.limpet.test/src/info/limpet/data2/TestBistaticAngleCalculations.java
improve testing of calcs
Java
epl-1.0
f2e9391b3ee545a4158f4baee0bd8c70a7593b0f
0
RandallDW/Aruba_plugin,rgom/Pydev,rajul/Pydev,rgom/Pydev,rajul/Pydev,rajul/Pydev,RandallDW/Aruba_plugin,fabioz/Pydev,aptana/Pydev,rgom/Pydev,akurtakov/Pydev,RandallDW/Aruba_plugin,akurtakov/Pydev,rajul/Pydev,rgom/Pydev,rgom/Pydev,akurtakov/Pydev,rajul/Pydev,RandallDW/Aruba_plugin,fabioz/Pydev,akurtakov/Pydev,aptana/Pydev,fabioz/Pydev,fabioz/Pydev,RandallDW/Aruba_plugin,rgom/Pydev,rajul/Pydev,fabioz/Pydev,RandallDW/Aruba_plugin,aptana/Pydev,akurtakov/Pydev,fabioz/Pydev,akurtakov/Pydev
/* * Created on 07/09/2005 */ package com.python.pydev.analysis.additionalinfo; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.python.pydev.core.IInterpreterManager; import org.python.pydev.core.IModulesManager; import org.python.pydev.core.IPythonNature; import org.python.pydev.core.ModulesKey; import org.python.pydev.core.REF; import org.python.pydev.core.Tuple; import org.python.pydev.editor.codecompletion.revisited.PythonPathHelper; import org.python.pydev.editor.codecompletion.revisited.SystemModulesManager; import org.python.pydev.parser.PyParser; import org.python.pydev.parser.jython.SimpleNode; import org.python.pydev.plugin.PydevPlugin; import org.python.pydev.plugin.nature.PythonNature; import org.python.pydev.ui.NotConfiguredInterpreterException; import org.python.pydev.ui.interpreters.IInterpreterObserver; import org.python.pydev.ui.pythonpathconf.InterpreterInfo; import org.python.pydev.utils.JobProgressComunicator; public class InterpreterObserver implements IInterpreterObserver { private static final boolean DEBUG_INTERPRETER_OBSERVER = false; /** * @see org.python.pydev.ui.interpreters.IInterpreterObserver#notifyDefaultPythonpathRestored(org.python.pydev.ui.interpreters.AbstractInterpreterManager, org.eclipse.core.runtime.IProgressMonitor) */ public void notifyDefaultPythonpathRestored(IInterpreterManager manager, String defaultSelectedInterpreter, IProgressMonitor monitor){ if(DEBUG_INTERPRETER_OBSERVER){ System.out.println("notifyDefaultPythonpathRestored "+ defaultSelectedInterpreter); } try { try { AbstractAdditionalInterpreterInfo currInfo = AdditionalSystemInterpreterInfo.getAdditionalSystemInfo(manager); if(currInfo != null){ currInfo.clearAllInfo(); } InterpreterInfo defaultInterpreterInfo = (InterpreterInfo) manager.getInterpreterInfo(defaultSelectedInterpreter, monitor); SystemModulesManager m = defaultInterpreterInfo.modulesManager; AbstractAdditionalInterpreterInfo additionalSystemInfo = restoreInfoForModuleManager(monitor, m, "(system: " + manager.getManagerRelatedName() + ")", new AdditionalSystemInterpreterInfo(manager), null); if (additionalSystemInfo != null) { //ok, set it and save it AdditionalSystemInterpreterInfo.setAdditionalSystemInfo(manager, additionalSystemInfo); AbstractAdditionalInterpreterInfo.saveAdditionalSystemInfo(manager); } } catch (NotConfiguredInterpreterException e) { //ok, nothing configured, nothing to do... PydevPlugin.log(e); } } catch (Throwable e) { PydevPlugin.log(e); } } /** * received when the interpreter manager is restored * * this means that we have to restore the additional interpreter information we stored * * @see org.python.pydev.ui.interpreters.IInterpreterObserver#notifyInterpreterManagerRecreated(org.python.pydev.ui.interpreters.AbstractInterpreterManager) */ public void notifyInterpreterManagerRecreated(final IInterpreterManager iManager) { try { iManager.getDefaultInterpreter(); //may throw a 'not configured' exception if (!AdditionalSystemInterpreterInfo.loadAdditionalSystemInfo(iManager)) { //not successfully loaded Job j = new Job("Pydev... Restoring additional info") { @Override protected IStatus run(IProgressMonitor monitorArg) { try { final String defaultInterpreter = iManager.getDefaultInterpreter(); //it should be configured if we reach here. JobProgressComunicator jobProgressComunicator = new JobProgressComunicator(monitorArg, "Pydev... Restoring additional info", IProgressMonitor.UNKNOWN, this); notifyDefaultPythonpathRestored(iManager, defaultInterpreter, jobProgressComunicator); jobProgressComunicator.done(); } catch (Exception e) { PydevPlugin.log(e); } return Status.OK_STATUS; } }; j.setPriority(Job.BUILD); j.schedule(); } } catch (NotConfiguredInterpreterException e) { //ok, we've received the notification, so the interpreter was restored... but there is no info about it, //so, just ignore it. } } /** * Restores the info for a module manager * * @param monitor a monitor to keep track of the progress * @param m the module manager * @param nature the associated nature (may be null if there is no associated nature -- as is the case when * restoring system info). * * @return the info generated from the module manager */ private AbstractAdditionalInterpreterInfo restoreInfoForModuleManager(IProgressMonitor monitor, IModulesManager m, String additionalFeedback, AbstractAdditionalInterpreterInfo info, PythonNature nature) { //if we cannot get the version of the grammar, let's simply try to parse it with the latest version (because //it should be backward compatible). int grammarVersion = nature != null ? nature.getGrammarVersion() : IPythonNature.GRAMMAR_PYTHON_VERSION_2_5; long startsAt = System.currentTimeMillis(); ModulesKey[] allModules = m.getOnlyDirectModules(); int i = 0; for (ModulesKey key : allModules) { if(monitor.isCanceled()){ return null; } i++; if (key.file != null) { //otherwise it should be treated as a compiled module (no ast generation) if (key.file.exists()) { String fileAbsolutePath = REF.getFileAbsolutePath(key.file); if (PythonPathHelper.isValidSourceFile(fileAbsolutePath)) { StringBuffer buffer = new StringBuffer(); buffer.append("Creating "); buffer.append(additionalFeedback); buffer.append(" additional info (" ); buffer.append(i ); buffer.append(" of " ); buffer.append(allModules.length ); buffer.append(") for " ); buffer.append(key.file.getName()); monitor.setTaskName(buffer.toString()); monitor.worked(1); try { // the code below works with the default parser (that has much more info... and is much slower) PyParser.ParserInfo parserInfo = new PyParser.ParserInfo(REF.getDocFromFile(key.file), false, null, grammarVersion); Tuple<SimpleNode, Throwable> obj = PyParser.reparseDocument(parserInfo); SimpleNode node = obj.o1; //maybe later we can change by this, if it becomes faster and more consistent //SimpleNode node = FastParser.reparseDocument(REF.getFileContents(key.file)); if (node != null) { info.addAstInfo(node, key.name, nature, false); }else{ throw new RuntimeException("Unable to generate ast."); } } catch (Exception e) { PydevPlugin.log(IStatus.ERROR, "Problem parsing the file :" + key.file + ".", e); } } } else { PydevPlugin.log("The file :" + key.file + " does not exist, but is marked as existing in the pydev code completion."); } } } double delta = System.currentTimeMillis()-startsAt; delta = delta/1000; // in secs System.out.println("Time to restore additional info in secs: "+delta); System.out.println("Time to restore additional info in mins: "+delta/60.0); return info; } public void notifyProjectPythonpathRestored(final PythonNature nature, IProgressMonitor monitor, final String defaultSelectedInterpreter) { try { IModulesManager m = nature.getAstManager().getModulesManager(); IProject project = nature.getProject(); AbstractAdditionalDependencyInfo currInfo = AdditionalProjectInterpreterInfo.getAdditionalInfoForProject(project); if(currInfo != null){ currInfo.clearAllInfo(); } AdditionalProjectInterpreterInfo newProjectInfo = new AdditionalProjectInterpreterInfo(project); String feedback = "(project:" + project.getName() + ")"; synchronized(m){ AbstractAdditionalDependencyInfo info = (AbstractAdditionalDependencyInfo) restoreInfoForModuleManager( monitor, m, feedback, newProjectInfo, nature); if (info != null) { //ok, set it and save it AdditionalProjectInterpreterInfo.setAdditionalInfoForProject(project, info); AdditionalProjectInterpreterInfo.saveAdditionalInfoForProject(project); } } } catch (Exception e) { PydevPlugin.log(e); throw new RuntimeException(e); } } public void notifyNatureRecreated(final PythonNature nature, IProgressMonitor monitor) { if(!AdditionalProjectInterpreterInfo.loadAdditionalInfoForProject(nature.getProject())){ if(DEBUG_INTERPRETER_OBSERVER){ System.out.println("Unable to load the info correctly... restoring info from the pythonpath"); } notifyProjectPythonpathRestored(nature, monitor, null); } } }
com.python.pydev.analysis/src/com/python/pydev/analysis/additionalinfo/InterpreterObserver.java
/* * Created on 07/09/2005 */ package com.python.pydev.analysis.additionalinfo; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.python.pydev.core.IInterpreterManager; import org.python.pydev.core.IModulesManager; import org.python.pydev.core.ModulesKey; import org.python.pydev.core.REF; import org.python.pydev.core.Tuple; import org.python.pydev.editor.codecompletion.revisited.PythonPathHelper; import org.python.pydev.editor.codecompletion.revisited.SystemModulesManager; import org.python.pydev.parser.PyParser; import org.python.pydev.parser.jython.SimpleNode; import org.python.pydev.plugin.PydevPlugin; import org.python.pydev.plugin.nature.PythonNature; import org.python.pydev.ui.NotConfiguredInterpreterException; import org.python.pydev.ui.interpreters.IInterpreterObserver; import org.python.pydev.ui.pythonpathconf.InterpreterInfo; import org.python.pydev.utils.JobProgressComunicator; public class InterpreterObserver implements IInterpreterObserver { private static final boolean DEBUG_INTERPRETER_OBSERVER = false; /** * @see org.python.pydev.ui.interpreters.IInterpreterObserver#notifyDefaultPythonpathRestored(org.python.pydev.ui.interpreters.AbstractInterpreterManager, org.eclipse.core.runtime.IProgressMonitor) */ public void notifyDefaultPythonpathRestored(IInterpreterManager manager, String defaultSelectedInterpreter, IProgressMonitor monitor){ if(DEBUG_INTERPRETER_OBSERVER){ System.out.println("notifyDefaultPythonpathRestored "+ defaultSelectedInterpreter); } try { try { AbstractAdditionalInterpreterInfo currInfo = AdditionalSystemInterpreterInfo.getAdditionalSystemInfo(manager); if(currInfo != null){ currInfo.clearAllInfo(); } InterpreterInfo defaultInterpreterInfo = (InterpreterInfo) manager.getInterpreterInfo(defaultSelectedInterpreter, monitor); SystemModulesManager m = defaultInterpreterInfo.modulesManager; AbstractAdditionalInterpreterInfo additionalSystemInfo = restoreInfoForModuleManager(monitor, m, "(system: " + manager.getManagerRelatedName() + ")", new AdditionalSystemInterpreterInfo(manager), null); if (additionalSystemInfo != null) { //ok, set it and save it AdditionalSystemInterpreterInfo.setAdditionalSystemInfo(manager, additionalSystemInfo); AbstractAdditionalInterpreterInfo.saveAdditionalSystemInfo(manager); } } catch (NotConfiguredInterpreterException e) { //ok, nothing configured, nothing to do... PydevPlugin.log(e); } } catch (Throwable e) { PydevPlugin.log(e); } } /** * received when the interpreter manager is restored * * this means that we have to restore the additional interpreter information we stored * * @see org.python.pydev.ui.interpreters.IInterpreterObserver#notifyInterpreterManagerRecreated(org.python.pydev.ui.interpreters.AbstractInterpreterManager) */ public void notifyInterpreterManagerRecreated(final IInterpreterManager iManager) { try { iManager.getDefaultInterpreter(); //may throw a 'not configured' exception if (!AdditionalSystemInterpreterInfo.loadAdditionalSystemInfo(iManager)) { //not successfully loaded Job j = new Job("Pydev... Restoring additional info") { @Override protected IStatus run(IProgressMonitor monitorArg) { try { final String defaultInterpreter = iManager.getDefaultInterpreter(); //it should be configured if we reach here. JobProgressComunicator jobProgressComunicator = new JobProgressComunicator(monitorArg, "Pydev... Restoring additional info", IProgressMonitor.UNKNOWN, this); notifyDefaultPythonpathRestored(iManager, defaultInterpreter, jobProgressComunicator); jobProgressComunicator.done(); } catch (Exception e) { PydevPlugin.log(e); } return Status.OK_STATUS; } }; j.setPriority(Job.BUILD); j.schedule(); } } catch (NotConfiguredInterpreterException e) { //ok, we've received the notification, so the interpreter was restored... but there is no info about it, //so, just ignore it. } } /** * Restores the info for a module manager * * @param monitor a monitor to keep track of the progress * @param m the module manager * @param nature the associated nature (may be null if there is no associated nature -- as is the case when * restoring system info). * * @return the info generated from the module manager */ private AbstractAdditionalInterpreterInfo restoreInfoForModuleManager(IProgressMonitor monitor, IModulesManager m, String additionalFeedback, AbstractAdditionalInterpreterInfo info, PythonNature nature) { long startsAt = System.currentTimeMillis(); ModulesKey[] allModules = m.getOnlyDirectModules(); int i = 0; for (ModulesKey key : allModules) { if(monitor.isCanceled()){ return null; } i++; if (key.file != null) { //otherwise it should be treated as a compiled module (no ast generation) if (key.file.exists()) { String fileAbsolutePath = REF.getFileAbsolutePath(key.file); if (PythonPathHelper.isValidSourceFile(fileAbsolutePath)) { StringBuffer buffer = new StringBuffer(); buffer.append("Creating "); buffer.append(additionalFeedback); buffer.append(" additional info (" ); buffer.append(i ); buffer.append(" of " ); buffer.append(allModules.length ); buffer.append(") for " ); buffer.append(key.file.getName()); monitor.setTaskName(buffer.toString()); monitor.worked(1); try { // the code below works with the default parser (that has much more info... and is much slower) PyParser.ParserInfo parserInfo = new PyParser.ParserInfo(REF.getDocFromFile(key.file), false, null, nature.getGrammarVersion()); Tuple<SimpleNode, Throwable> obj = PyParser.reparseDocument(parserInfo); SimpleNode node = obj.o1; //maybe later we can change by this, if it becomes faster and more consistent //SimpleNode node = FastParser.reparseDocument(REF.getFileContents(key.file)); if (node != null) { info.addAstInfo(node, key.name, nature, false); }else{ throw new RuntimeException("Unable to generate ast."); } } catch (Exception e) { PydevPlugin.log(IStatus.ERROR, "Problem parsing the file :" + key.file + ".", e); } } } else { PydevPlugin.log("The file :" + key.file + " does not exist, but is marked as existing in the pydev code completion."); } } } double delta = System.currentTimeMillis()-startsAt; delta = delta/1000; // in secs System.out.println("Time to restore additional info in secs: "+delta); System.out.println("Time to restore additional info in mins: "+delta/60.0); return info; } public void notifyProjectPythonpathRestored(final PythonNature nature, IProgressMonitor monitor, final String defaultSelectedInterpreter) { try { IModulesManager m = nature.getAstManager().getModulesManager(); IProject project = nature.getProject(); AbstractAdditionalDependencyInfo currInfo = AdditionalProjectInterpreterInfo.getAdditionalInfoForProject(project); if(currInfo != null){ currInfo.clearAllInfo(); } AdditionalProjectInterpreterInfo newProjectInfo = new AdditionalProjectInterpreterInfo(project); String feedback = "(project:" + project.getName() + ")"; synchronized(m){ AbstractAdditionalDependencyInfo info = (AbstractAdditionalDependencyInfo) restoreInfoForModuleManager( monitor, m, feedback, newProjectInfo, nature); if (info != null) { //ok, set it and save it AdditionalProjectInterpreterInfo.setAdditionalInfoForProject(project, info); AdditionalProjectInterpreterInfo.saveAdditionalInfoForProject(project); } } } catch (Exception e) { PydevPlugin.log(e); throw new RuntimeException(e); } } public void notifyNatureRecreated(final PythonNature nature, IProgressMonitor monitor) { if(!AdditionalProjectInterpreterInfo.loadAdditionalInfoForProject(nature.getProject())){ if(DEBUG_INTERPRETER_OBSERVER){ System.out.println("Unable to load the info correctly... restoring info from the pythonpath"); } notifyProjectPythonpathRestored(nature, monitor, null); } } }
*** empty log message *** git-svn-id: cdbd3c3453b226d8644b39c93ea790e37ea3ca1b@713 42a48d6c-1186-114d-bcb1-a7d39102e91d
com.python.pydev.analysis/src/com/python/pydev/analysis/additionalinfo/InterpreterObserver.java
*** empty log message ***
Java
agpl-3.0
7ced6b5177c698e8386d26ca9daddb4518186d09
0
UniversityOfHawaiiORS/kc,iu-uits-es/kc,mukadder/kc,iu-uits-es/kc,geothomasp/kcmit,geothomasp/kcmit,ColostateResearchServices/kc,jwillia/kc-old1,jwillia/kc-old1,ColostateResearchServices/kc,geothomasp/kcmit,mukadder/kc,UniversityOfHawaiiORS/kc,geothomasp/kcmit,kuali/kc,geothomasp/kcmit,UniversityOfHawaiiORS/kc,kuali/kc,iu-uits-es/kc,mukadder/kc,jwillia/kc-old1,jwillia/kc-old1,ColostateResearchServices/kc,kuali/kc
/* * Copyright 2006-2008 The Kuali Foundation * * Licensed under the Educational Community License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl1.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kuali.kra.questionnaire; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.jmock.Expectations; import org.jmock.Mockery; import org.jmock.integration.junit4.JUnit4Mockery; import org.junit.Assert; import org.junit.Test; import org.kuali.kra.infrastructure.Constants; import org.kuali.kra.infrastructure.PermissionConstants; import org.kuali.rice.kns.service.BusinessObjectService; import org.kuali.rice.kns.service.ParameterService; public class QuestionnaireServiceTest { private Mockery context = new JUnit4Mockery(); @Test public void testCopyQuestionnaire() { final QuestionnaireServiceImpl questionnaireService = new QuestionnaireServiceImpl(); Questionnaire srcQuestionnaire = setupSourceQuestionnaire(); Questionnaire destQuestionnaire = new Questionnaire(); questionnaireService.copyQuestionnaire(srcQuestionnaire, destQuestionnaire); List<QuestionnaireQuestion> questionnaireQuestions = destQuestionnaire.getQuestionnaireQuestions(); List<QuestionnaireUsage> questionnaireUsages = destQuestionnaire.getQuestionnaireUsages(); assertTrue(questionnaireQuestions.size() == 2); Assert.assertNull(questionnaireQuestions.get(0).getQuestionnaireRefIdFk()); Assert.assertNull(questionnaireQuestions.get(1).getQuestionnaireRefIdFk()); Assert.assertNull(questionnaireQuestions.get(0).getQuestionnaireQuestionsId()); Assert.assertNull(questionnaireQuestions.get(1).getQuestionnaireQuestionsId()); assertEquals(questionnaireQuestions.get(0).getQuestionRefIdFk(), (Object)1000L); assertTrue(questionnaireUsages.size() == 2); assertEquals(questionnaireUsages.get(0).getQuestionnaireLabel(), "test 1"); assertEquals(questionnaireUsages.get(1).getQuestionnaireLabel(), "test 2"); Assert.assertNull(questionnaireUsages.get(0).getQuestionnaireRefIdFk()); Assert.assertNull(questionnaireUsages.get(1).getQuestionnaireRefIdFk()); Assert.assertNull(questionnaireUsages.get(0).getQuestionnaireUsageId()); Assert.assertNull(questionnaireUsages.get(1).getQuestionnaireUsageId()); } private Questionnaire setupSourceQuestionnaire() { Questionnaire questionnaire = new Questionnaire(); questionnaire.setQuestionnaireRefId(1L); QuestionnaireQuestion questionnaireQuestion = new QuestionnaireQuestion(); questionnaireQuestion.setQuestionnaireRefIdFk(1L); questionnaireQuestion.setQuestionRefIdFk(1L); questionnaireQuestion.setQuestionnaireQuestionsId(1L); questionnaireQuestion.setQuestionRefIdFk(1000L); questionnaire.getQuestionnaireQuestions().add(questionnaireQuestion); questionnaireQuestion = new QuestionnaireQuestion(); questionnaireQuestion.setQuestionnaireRefIdFk(1L); questionnaireQuestion.setQuestionRefIdFk(2L); questionnaireQuestion.setQuestionnaireQuestionsId(2L); questionnaireQuestion.setQuestionRefIdFk(1001L); questionnaire.getQuestionnaireQuestions().add(questionnaireQuestion); QuestionnaireUsage questionnaireUsage = new QuestionnaireUsage(); questionnaireUsage.setQuestionnaireRefIdFk(1L); questionnaireUsage.setQuestionnaireLabel("test 1"); questionnaireUsage.setQuestionnaireUsageId(1L); questionnaire.getQuestionnaireUsages().add(questionnaireUsage); questionnaireUsage = new QuestionnaireUsage(); questionnaireUsage.setQuestionnaireRefIdFk(1L); questionnaireUsage.setQuestionnaireLabel("test 2"); questionnaireUsage.setQuestionnaireUsageId(2L); questionnaire.getQuestionnaireUsages().add(questionnaireUsage); return questionnaire; } @Test public void testValidCodes() { final QuestionnaireAuthorizationService questionnaireAuthorizationService = context.mock(QuestionnaireAuthorizationService.class); final ParameterService parameterService = context.mock(ParameterService.class); final QuestionnaireServiceImpl questionnaireService = new QuestionnaireServiceImpl(); questionnaireService.setQuestionnaireAuthorizationService(questionnaireAuthorizationService); questionnaireService.setParameterService(parameterService); final List<String> permissions = new ArrayList<String>(); permissions.add(PermissionConstants.MODIFY_PROPOSAL); permissions.add(PermissionConstants.MODIFY_PROTOCOL); context.checking(new Expectations() {{ one(parameterService).getParameterValues(Constants.PARAMETER_MODULE_QUESTIONNAIRE, Constants.PARAMETER_COMPONENT_PERMISSION, "associateModuleQuestionnairePermission"); will(returnValue(permissions)); one(questionnaireAuthorizationService).hasPermission(PermissionConstants.MODIFY_PROPOSAL); will(returnValue(false)); one(questionnaireAuthorizationService).hasPermission(PermissionConstants.MODIFY_PROTOCOL); will(returnValue(true)); }}); List<String> modules = questionnaireService.getAssociateModules(); assertTrue(modules.size() == 1); assertEquals(modules.get(0), "7"); context.assertIsSatisfied(); } @Test public void testIsQuestionnaireNameExistTrue() { final BusinessObjectService businessObjectService = context.mock(BusinessObjectService.class); final QuestionnaireServiceImpl questionnaireService = new QuestionnaireServiceImpl(); questionnaireService.setBusinessObjectService(businessObjectService); final Questionnaire questionnaire = new Questionnaire(); questionnaire.setQuestionnaireId(1); questionnaire.setName("exist name"); final List<Questionnaire> questionnaires = new ArrayList<Questionnaire>(); questionnaires.add(questionnaire); final Map<String, Object> fieldValues = new HashMap<String, Object>(); fieldValues.put("name", "exist name"); context.checking(new Expectations() {{ one(businessObjectService).findMatching(Questionnaire.class, fieldValues); will(returnValue(questionnaires)); }}); assertTrue(questionnaireService.isQuestionnaireNameExist(null, "exist name")); context.assertIsSatisfied(); } @Test public void testIsQuestionnaireNameExistFalse() { final BusinessObjectService businessObjectService = context.mock(BusinessObjectService.class); final QuestionnaireServiceImpl questionnaireService = new QuestionnaireServiceImpl(); questionnaireService.setBusinessObjectService(businessObjectService); final Questionnaire questionnaire = new Questionnaire(); questionnaire.setQuestionnaireId(1); questionnaire.setName("exist name"); final List<Questionnaire> questionnaires = new ArrayList<Questionnaire>(); questionnaires.add(questionnaire); final Map<String, Object> fieldValues = new HashMap<String, Object>(); fieldValues.put("name", "exist name"); context.checking(new Expectations() {{ one(businessObjectService).findMatching(Questionnaire.class, fieldValues); will(returnValue(questionnaires)); }}); assertTrue(!questionnaireService.isQuestionnaireNameExist(1, "exist name")); context.assertIsSatisfied(); } @Test public void testIsQuestionnaireNameExistFalseNoMatch() { final BusinessObjectService businessObjectService = context.mock(BusinessObjectService.class); final QuestionnaireServiceImpl questionnaireService = new QuestionnaireServiceImpl(); questionnaireService.setBusinessObjectService(businessObjectService); final Map<String, Object> fieldValues = new HashMap<String, Object>(); fieldValues.put("name", "not exist name"); final List<Questionnaire> questionnaires = new ArrayList<Questionnaire>(); context.checking(new Expectations() {{ one(businessObjectService).findMatching(Questionnaire.class, fieldValues); will(returnValue(questionnaires)); }}); assertTrue(!questionnaireService.isQuestionnaireNameExist(1, "not exist name")); context.assertIsSatisfied(); } }
src/test/java/org/kuali/kra/questionnaire/QuestionnaireServiceTest.java
/* * Copyright 2006-2008 The Kuali Foundation * * Licensed under the Educational Community License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl1.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kuali.kra.questionnaire; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.jmock.Expectations; import org.jmock.Mockery; import org.jmock.integration.junit4.JUnit4Mockery; import org.junit.Assert; import org.junit.Test; import org.kuali.kra.infrastructure.Constants; import org.kuali.kra.infrastructure.PermissionConstants; import org.kuali.rice.kns.service.BusinessObjectService; import org.kuali.rice.kns.service.KualiConfigurationService; import org.kuali.rice.kns.service.ParameterService; public class QuestionnaireServiceTest { private Mockery context = new JUnit4Mockery(); @Test public void testCopyQuestionnaire() { final QuestionnaireServiceImpl questionnaireService = new QuestionnaireServiceImpl(); Questionnaire srcQuestionnaire = setupSourceQuestionnaire(); Questionnaire destQuestionnaire = new Questionnaire(); questionnaireService.copyQuestionnaire(srcQuestionnaire, destQuestionnaire); List<QuestionnaireQuestion> questionnaireQuestions = destQuestionnaire.getQuestionnaireQuestions(); List<QuestionnaireUsage> questionnaireUsages = destQuestionnaire.getQuestionnaireUsages(); assertTrue(questionnaireQuestions.size() == 2); Assert.assertNull(questionnaireQuestions.get(0).getQuestionnaireRefIdFk()); Assert.assertNull(questionnaireQuestions.get(1).getQuestionnaireRefIdFk()); Assert.assertNull(questionnaireQuestions.get(0).getQuestionnaireQuestionsId()); Assert.assertNull(questionnaireQuestions.get(1).getQuestionnaireQuestionsId()); assertEquals(questionnaireQuestions.get(0).getQuestionRefIdFk(), (Object)1000L); assertTrue(questionnaireUsages.size() == 2); assertEquals(questionnaireUsages.get(0).getQuestionnaireLabel(), "test 1"); assertEquals(questionnaireUsages.get(1).getQuestionnaireLabel(), "test 2"); Assert.assertNull(questionnaireUsages.get(0).getQuestionnaireRefIdFk()); Assert.assertNull(questionnaireUsages.get(1).getQuestionnaireRefIdFk()); Assert.assertNull(questionnaireUsages.get(0).getQuestionnaireUsageId()); Assert.assertNull(questionnaireUsages.get(1).getQuestionnaireUsageId()); } private Questionnaire setupSourceQuestionnaire() { Questionnaire questionnaire = new Questionnaire(); questionnaire.setQuestionnaireRefId(1L); QuestionnaireQuestion questionnaireQuestion = new QuestionnaireQuestion(); questionnaireQuestion.setQuestionnaireRefIdFk(1L); questionnaireQuestion.setQuestionRefIdFk(1L); questionnaireQuestion.setQuestionnaireQuestionsId(1L); questionnaireQuestion.setQuestionRefIdFk(1000L); questionnaire.getQuestionnaireQuestions().add(questionnaireQuestion); questionnaireQuestion = new QuestionnaireQuestion(); questionnaireQuestion.setQuestionnaireRefIdFk(1L); questionnaireQuestion.setQuestionRefIdFk(2L); questionnaireQuestion.setQuestionnaireQuestionsId(2L); questionnaireQuestion.setQuestionRefIdFk(1001L); questionnaire.getQuestionnaireQuestions().add(questionnaireQuestion); QuestionnaireUsage questionnaireUsage = new QuestionnaireUsage(); questionnaireUsage.setQuestionnaireRefIdFk(1L); questionnaireUsage.setQuestionnaireLabel("test 1"); questionnaireUsage.setQuestionnaireUsageId(1L); questionnaire.getQuestionnaireUsages().add(questionnaireUsage); questionnaireUsage = new QuestionnaireUsage(); questionnaireUsage.setQuestionnaireRefIdFk(1L); questionnaireUsage.setQuestionnaireLabel("test 2"); questionnaireUsage.setQuestionnaireUsageId(2L); questionnaire.getQuestionnaireUsages().add(questionnaireUsage); return questionnaire; } @Test public void testValidCodes() { final QuestionnaireAuthorizationService questionnaireAuthorizationService = context.mock(QuestionnaireAuthorizationService.class); final ParameterService parameterService = context.mock(ParameterService.class); final QuestionnaireServiceImpl questionnaireService = new QuestionnaireServiceImpl(); questionnaireService.setQuestionnaireAuthorizationService(questionnaireAuthorizationService); questionnaireService.setParameterService(parameterService); final List<String> permissions = new ArrayList<String>(); permissions.add(PermissionConstants.MODIFY_PROPOSAL); permissions.add(PermissionConstants.MODIFY_PROTOCOL); context.checking(new Expectations() {{ one(parameterService).getParameterValues(Constants.PARAMETER_MODULE_QUESTIONNAIRE, Constants.PARAMETER_COMPONENT_PERMISSION, "associateModuleQuestionnairePermission"); will(returnValue(permissions)); one(questionnaireAuthorizationService).hasPermission(PermissionConstants.MODIFY_PROPOSAL); will(returnValue(false)); one(questionnaireAuthorizationService).hasPermission(PermissionConstants.MODIFY_PROTOCOL); will(returnValue(true)); }}); List<String> modules = questionnaireService.getAssociateModules(); assertTrue(modules.size() == 1); assertEquals(modules.get(0), "7"); context.assertIsSatisfied(); } @Test public void testIsQuestionnaireNameExistTrue() { final BusinessObjectService businessObjectService = context.mock(BusinessObjectService.class); final QuestionnaireServiceImpl questionnaireService = new QuestionnaireServiceImpl(); questionnaireService.setBusinessObjectService(businessObjectService); final Questionnaire questionnaire = new Questionnaire(); questionnaire.setQuestionnaireId(1); questionnaire.setName("exist name"); final List<Questionnaire> questionnaires = new ArrayList<Questionnaire>(); questionnaires.add(questionnaire); final Map<String, Object> fieldValues = new HashMap<String, Object>(); fieldValues.put("name", "exist name"); context.checking(new Expectations() {{ one(businessObjectService).findMatching(Questionnaire.class, fieldValues); will(returnValue(questionnaires)); }}); assertTrue(questionnaireService.isQuestionnaireNameExist(null, "exist name")); context.assertIsSatisfied(); } @Test public void testIsQuestionnaireNameExistFalse() { final BusinessObjectService businessObjectService = context.mock(BusinessObjectService.class); final QuestionnaireServiceImpl questionnaireService = new QuestionnaireServiceImpl(); questionnaireService.setBusinessObjectService(businessObjectService); final Questionnaire questionnaire = new Questionnaire(); questionnaire.setQuestionnaireId(1); questionnaire.setName("exist name"); final List<Questionnaire> questionnaires = new ArrayList<Questionnaire>(); questionnaires.add(questionnaire); final Map<String, Object> fieldValues = new HashMap<String, Object>(); fieldValues.put("name", "exist name"); context.checking(new Expectations() {{ one(businessObjectService).findMatching(Questionnaire.class, fieldValues); will(returnValue(questionnaires)); }}); assertTrue(!questionnaireService.isQuestionnaireNameExist(1, "exist name")); context.assertIsSatisfied(); } @Test public void testIsQuestionnaireNameExistFalseNoMatch() { final BusinessObjectService businessObjectService = context.mock(BusinessObjectService.class); final QuestionnaireServiceImpl questionnaireService = new QuestionnaireServiceImpl(); questionnaireService.setBusinessObjectService(businessObjectService); final Map<String, Object> fieldValues = new HashMap<String, Object>(); fieldValues.put("name", "not exist name"); final List<Questionnaire> questionnaires = new ArrayList<Questionnaire>(); context.checking(new Expectations() {{ one(businessObjectService).findMatching(Questionnaire.class, fieldValues); will(returnValue(questionnaires)); }}); assertTrue(!questionnaireService.isQuestionnaireNameExist(1, "not exist name")); context.assertIsSatisfied(); } }
kcirb-372
src/test/java/org/kuali/kra/questionnaire/QuestionnaireServiceTest.java
kcirb-372
Java
agpl-3.0
9221cd6d34f7dd4bcd4d309855e96dc363b0977c
0
Shinewave-RD/SOPViewer
package com.shinewave.sopviewer; import android.app.AlertDialog; import android.content.DialogInterface; import android.os.Handler; import android.os.Message; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.animation.Animation; import android.view.animation.TranslateAnimation; import android.widget.RelativeLayout; import android.widget.SeekBar; import android.widget.TextView; import com.artifex.mupdfdemo.MuPDFCore; import com.artifex.mupdfdemo.MuPDFPageAdapter; import com.artifex.mupdfdemo.MuPDFReaderView; import com.artifex.mupdfdemo.OutlineActivityData; import java.util.ArrayList; import java.util.List; import java.util.Timer; import java.util.TimerTask; public class PDFPlayActivity extends AppCompatActivity { private MuPDFCore core; private MuPDFReaderView mDocView; private View mButtonsView; private SeekBar mPageSlider; private int mPageSliderRes; private TextView mPageNumberView; private boolean mButtonsVisible; private Handler handler; private int playItemCount = 0; private int loopCount = 0; private PlayList plist; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mButtonsView = getLayoutInflater().inflate(R.layout.buttons, null); //mPageSlider = (SeekBar) mButtonsView.findViewById(R.id.pageSlider); //mPageNumberView = (TextView) mButtonsView.findViewById(R.id.pageNumber); String playListName = getIntent().getStringExtra("PlayListName"); plist = DBManager.getPlayItem(playListName); if(plist != null && plist.playListItem.size() > 0) { mDocView = new MuPDFReaderView(this) { @Override protected void onMoveToChild(int i) { mPageNumberView.setText(String.format("%d / %d", i + 1, core.countPages())); mPageSlider.setMax((core.countPages() - 1) * mPageSliderRes); mPageSlider.setProgress(i * mPageSliderRes); super.onMoveToChild(i); } @Override protected void onTapMainDocArea() { if (!mButtonsVisible) { showButtons(); } else { hideButtons(); } } @Override protected void onDocMotion() { hideButtons(); } }; RelativeLayout layout = new RelativeLayout(this); layout.addView(mDocView); layout.addView(mButtonsView); setContentView(layout); setup(); } else { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Error!!"); builder.setMessage("Play list include no play item !!"); builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { } }); builder.create().show(); } } private void setup() { if(playItemCount >= plist.playListItem.size()) { loopCount++; playItemCount = 0; } if(loopCount >= plist.loop) return; final PlayListItem pItem = plist.playListItem.get(playItemCount); if(pItem != null) { mPageSlider = (SeekBar) mButtonsView.findViewById(R.id.pageSlider); mPageNumberView = (TextView) mButtonsView.findViewById(R.id.pageNumber); playItemCount++; core = null; core = openFile(pItem.getlocalFullFilePath()); if (core != null) { final List seqList = parseStringRange(pItem.strPages); handler = null; handler = new Handler() { Timer timer; int idx= 0; public void handleMessage(Message msg) { if (msg.what == mDocView.getCurrent()) { idx++; if (timer != null) { timer.cancel(); timer.purge(); timer = null; } timer = new Timer(); TimerTask timerTask = new TimerTask() { public void run() { handler.post(new Runnable() { public void run() { try { mDocView.setDisplayedViewIndex((int) seqList.get(idx)); } catch(Exception e) { setup(); } } }); } }; timer.schedule(timerTask, pItem.sec * 1000); } } }; int start = (int)seqList.get(0); mDocView.setAdapter(new MuPDFPageAdapter(this, null, core, handler)); mDocView.setCurrent(start); int smax = Math.max(core.countPages() - 1, 1); mPageSliderRes = ((10 + smax - 1) / smax) * 2; // Activate the seekbar mPageSlider.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { public void onStopTrackingTouch(SeekBar seekBar) { mDocView.setDisplayedViewIndex((seekBar.getProgress() + mPageSliderRes / 2) / mPageSliderRes); } public void onStartTrackingTouch(SeekBar seekBar) { } public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { updatePageNumView((progress + mPageSliderRes / 2) / mPageSliderRes); } }); mPageSlider.setMax((core.countPages() - 1) * mPageSliderRes); mPageSlider.setProgress(start); updatePageNumView(start); mDocView.refresh(false); } } } @Override public boolean onCreateOptionsMenu(Menu menu) { if (mButtonsVisible) { hideButtons(); } else { showButtons(); } return super.onPrepareOptionsMenu(menu); } @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); } private MuPDFCore openFile(String path) { try { core = new MuPDFCore(this, path); // New file: drop the old outline data OutlineActivityData.set(null); } catch (Exception e) { System.out.println(e); return null; } catch (java.lang.OutOfMemoryError e) { // out of memory is not an Exception, so we catch it separately. System.out.println(e); return null; } return core; } private void showButtons() { if (core == null) return; if (!mButtonsVisible) { mButtonsVisible = true; // Update page number text and slider int index = mDocView.getDisplayedViewIndex(); updatePageNumView(index); mPageSlider.setMax((core.countPages()-1)*mPageSliderRes); mPageSlider.setProgress(index * mPageSliderRes); Animation anim = new TranslateAnimation(0, 0, mPageSlider.getHeight(), 0); anim.setDuration(200); anim.setAnimationListener(new Animation.AnimationListener() { public void onAnimationStart(Animation animation) { mPageSlider.setVisibility(View.VISIBLE); } public void onAnimationRepeat(Animation animation) {} public void onAnimationEnd(Animation animation) { mPageNumberView.setVisibility(View.VISIBLE); } }); mPageSlider.startAnimation(anim); } } private void hideButtons() { if (mButtonsVisible) { mButtonsVisible = false; Animation anim = new TranslateAnimation(0, 0, 0, mPageSlider.getHeight()); anim.setDuration(200); anim.setAnimationListener(new Animation.AnimationListener() { public void onAnimationStart(Animation animation) { mPageNumberView.setVisibility(View.INVISIBLE); } public void onAnimationRepeat(Animation animation) { } public void onAnimationEnd(Animation animation) { mPageSlider.setVisibility(View.INVISIBLE); } }); mPageSlider.startAnimation(anim); } } private void updatePageNumView(int index) { if (core == null) return; mPageNumberView.setText(String.format("%d / %d", index + 1, core.countPages())); } private List parseStringRange(String str){ ArrayList list = new ArrayList<>(); if(core != null) { int length = core.countPages(); int start = 0; int end = length; if("".equals(str)) { for (int j = start; j < end; j++) { list.add(j); } } else { String[] tmpArray = str.split(","); for (String tmp : tmpArray) { try { if (tmp.contains("-")) { String[] tmpArray2 = tmp.split("-"); if (!"".equals(tmpArray2[0])) start = Integer.parseInt(tmpArray2[0]); if (!"".equals(tmpArray2[1])) end = Integer.parseInt(tmpArray2[1]); for (int j = start; j <= end; j++) { if (j > 0 && j <= length) { list.add(j - 1); } } } else { int number = Integer.parseInt(tmp); if (number > 0 && number <= length) { list.add(number - 1); } } } catch (Exception e) { } } } } return list; } }
app/src/main/java/com/shinewave/sopviewer/PDFPlayActivity.java
package com.shinewave.sopviewer; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.os.Handler; import android.os.Message; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.animation.Animation; import android.view.animation.TranslateAnimation; import android.view.inputmethod.InputMethodManager; import android.widget.RelativeLayout; import android.widget.SeekBar; import android.widget.TextView; import com.artifex.mupdfdemo.MuPDFCore; import com.artifex.mupdfdemo.MuPDFPageAdapter; import com.artifex.mupdfdemo.MuPDFReaderView; import com.artifex.mupdfdemo.MuPDFView; import com.artifex.mupdfdemo.OutlineActivityData; import java.util.Arrays; import java.util.Timer; import java.util.TimerTask; public class PDFPlayActivity extends AppCompatActivity { private MuPDFCore core; private String mFileName; private MuPDFReaderView mDocView; private View mButtonsView; private SeekBar mPageSlider; private int mPageSliderRes; private TextView mPageNumberView; private boolean mButtonsVisible; private Handler handler; private int playItemCount = 0; private PlayList plist; private int[] aa = {0,1,2,3,4,5,6,7,8,0,1,2,3,4,5,6,7,8}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mButtonsView = getLayoutInflater().inflate(R.layout.buttons, null); //mPageSlider = (SeekBar) mButtonsView.findViewById(R.id.pageSlider); //mPageNumberView = (TextView) mButtonsView.findViewById(R.id.pageNumber); String playListName = getIntent().getStringExtra("PlayListName"); plist = DBManager.getPlayItem(playListName); if(plist != null && plist.playListItem.size() > 0) { mDocView = new MuPDFReaderView(this) { @Override protected void onMoveToChild(int i) { mPageNumberView.setText(String.format("%d / %d", i + 1, core.countPages())); mPageSlider.setMax((core.countPages() - 1) * mPageSliderRes); mPageSlider.setProgress(i * mPageSliderRes); super.onMoveToChild(i); } @Override protected void onTapMainDocArea() { if (!mButtonsVisible) { showButtons(); } else { hideButtons(); } } @Override protected void onDocMotion() { hideButtons(); } }; RelativeLayout layout = new RelativeLayout(this); layout.addView(mDocView); layout.addView(mButtonsView); setContentView(layout); setup(); } else { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Error!!"); builder.setMessage("Play list include no play item !!"); builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { } }); builder.create().show(); } } private void setup() { if(playItemCount >= plist.playListItem.size()) return; final PlayListItem pItem = plist.playListItem.get(playItemCount); if(pItem != null) { mPageSlider = (SeekBar) mButtonsView.findViewById(R.id.pageSlider); mPageNumberView = (TextView) mButtonsView.findViewById(R.id.pageNumber); playItemCount++; core = null; core = openFile(pItem.getlocalFullFilePath()); if (core != null) { handler = null; handler = new Handler() { Timer timer; int a= 0; public void handleMessage(Message msg) { if (msg.what == mDocView.getCurrent()) { System.out.println("CCCCCCA=="+msg.what+","+ mDocView.getCurrent()+","+a+","+aa[a]); a++; if (timer != null) { timer.cancel(); timer.purge(); timer = null; } timer = new Timer(); TimerTask timerTask = new TimerTask() { public void run() { handler.post(new Runnable() { public void run() { mDocView.setDisplayedViewIndex(aa[a]); //int idx = mDocView.getDisplayedViewIndex(); //System.out.println("AAAAA=" + idx + "," + core.countPages() + "," + mDocView.getAdapter().getCount()); //if (0 <= idx && idx+1 >= core.countPages()-1) // setup(); } }); } }; timer.schedule(timerTask, pItem.sec * 1000); } } }; mDocView.setAdapter(new MuPDFPageAdapter(this, null, core, handler)); updatePageNumView(0); mPageSlider.setMax((core.countPages()-1)*mPageSliderRes); mPageSlider.setProgress(0); mDocView.refresh(false); } int smax = Math.max(core.countPages() - 1, 1); mPageSliderRes = ((10 + smax - 1) / smax) * 2; // Activate the seekbar mPageSlider.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { public void onStopTrackingTouch(SeekBar seekBar) { mDocView.setDisplayedViewIndex((seekBar.getProgress() + mPageSliderRes / 2) / mPageSliderRes); } public void onStartTrackingTouch(SeekBar seekBar) { } public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { updatePageNumView((progress + mPageSliderRes / 2) / mPageSliderRes); } }); } } @Override public boolean onCreateOptionsMenu(Menu menu) { if (mButtonsVisible) { hideButtons(); } else { showButtons(); } return super.onPrepareOptionsMenu(menu); } @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); } private MuPDFCore openFile(String path) { try { core = new MuPDFCore(this, path); // New file: drop the old outline data OutlineActivityData.set(null); } catch (Exception e) { System.out.println(e); return null; } catch (java.lang.OutOfMemoryError e) { // out of memory is not an Exception, so we catch it separately. System.out.println(e); return null; } return core; } private void showButtons() { if (core == null) return; if (!mButtonsVisible) { mButtonsVisible = true; // Update page number text and slider int index = mDocView.getDisplayedViewIndex(); updatePageNumView(index); mPageSlider.setMax((core.countPages()-1)*mPageSliderRes); mPageSlider.setProgress(index * mPageSliderRes); Animation anim = new TranslateAnimation(0, 0, mPageSlider.getHeight(), 0); anim.setDuration(200); anim.setAnimationListener(new Animation.AnimationListener() { public void onAnimationStart(Animation animation) { mPageSlider.setVisibility(View.VISIBLE); } public void onAnimationRepeat(Animation animation) {} public void onAnimationEnd(Animation animation) { mPageNumberView.setVisibility(View.VISIBLE); } }); mPageSlider.startAnimation(anim); } } private void hideButtons() { if (mButtonsVisible) { mButtonsVisible = false; Animation anim = new TranslateAnimation(0, 0, 0, mPageSlider.getHeight()); anim.setDuration(200); anim.setAnimationListener(new Animation.AnimationListener() { public void onAnimationStart(Animation animation) { mPageNumberView.setVisibility(View.INVISIBLE); } public void onAnimationRepeat(Animation animation) { } public void onAnimationEnd(Animation animation) { mPageSlider.setVisibility(View.INVISIBLE); } }); mPageSlider.startAnimation(anim); } } private void updatePageNumView(int index) { if (core == null) return; mPageNumberView.setText(String.format("%d / %d", index + 1, core.countPages())); } private int[] parseStringRange(String str){ str = "3,4,5,8,10-20,1,2"; String[] a = str.split(str); for(int i = 0; i < a.length; i++) { System.out.println(a[i]); } return null; } }
play loop update
app/src/main/java/com/shinewave/sopviewer/PDFPlayActivity.java
play loop update
Java
lgpl-2.1
d9c53968c5874512be745074d37ffb059c29bfe7
0
retoo/pystructure,retoo/pystructure,retoo/pystructure,retoo/pystructure
package ch.hsr.ifs.pystructure.typeinference.inferencer.dispatcher; import java.util.HashMap; import java.util.Map; import org.python.pydev.parser.jython.SimpleNode; import org.python.pydev.parser.jython.ast.Attribute; import org.python.pydev.parser.jython.ast.BinOp; import org.python.pydev.parser.jython.ast.BoolOp; import org.python.pydev.parser.jython.ast.Call; import org.python.pydev.parser.jython.ast.Compare; import org.python.pydev.parser.jython.ast.Dict; import org.python.pydev.parser.jython.ast.IfExp; import org.python.pydev.parser.jython.ast.Lambda; import org.python.pydev.parser.jython.ast.List; import org.python.pydev.parser.jython.ast.ListComp; import org.python.pydev.parser.jython.ast.Name; import org.python.pydev.parser.jython.ast.Num; import org.python.pydev.parser.jython.ast.Str; import org.python.pydev.parser.jython.ast.Subscript; import org.python.pydev.parser.jython.ast.Tuple; import org.python.pydev.parser.jython.ast.UnaryOp; import org.python.pydev.parser.jython.ast.num_typeType; import ch.hsr.ifs.pystructure.typeinference.evaluators.base.AbstractEvaluator; import ch.hsr.ifs.pystructure.typeinference.evaluators.references.AttributeReferencesEvaluator; import ch.hsr.ifs.pystructure.typeinference.evaluators.references.ClassReferencesEvaluator; import ch.hsr.ifs.pystructure.typeinference.evaluators.references.FunctionReferencesEvaluator; import ch.hsr.ifs.pystructure.typeinference.evaluators.references.MethodReferencesEvaluator; import ch.hsr.ifs.pystructure.typeinference.evaluators.references.PossibleAttributeReferencesEvaluator; import ch.hsr.ifs.pystructure.typeinference.evaluators.references.PossibleReferencesEvaluator; import ch.hsr.ifs.pystructure.typeinference.evaluators.references.VariableReferenceEvaluator; import ch.hsr.ifs.pystructure.typeinference.evaluators.types.ArgumentTypeEvaluator; import ch.hsr.ifs.pystructure.typeinference.evaluators.types.AssignTypeEvaluator; import ch.hsr.ifs.pystructure.typeinference.evaluators.types.AttributeTypeEvaluator; import ch.hsr.ifs.pystructure.typeinference.evaluators.types.BinOpTypeEvaluator; import ch.hsr.ifs.pystructure.typeinference.evaluators.types.CallTypeEvaluator; import ch.hsr.ifs.pystructure.typeinference.evaluators.types.ClassAttributeTypeEvaluator; import ch.hsr.ifs.pystructure.typeinference.evaluators.types.FixedAnswerEvaluator; import ch.hsr.ifs.pystructure.typeinference.evaluators.types.IfExpTypeEvaluator; import ch.hsr.ifs.pystructure.typeinference.evaluators.types.ImportTypeEvaluator; import ch.hsr.ifs.pystructure.typeinference.evaluators.types.ReturnTypeEvaluator; import ch.hsr.ifs.pystructure.typeinference.evaluators.types.TupleElementTypeEvaluator; import ch.hsr.ifs.pystructure.typeinference.goals.base.IGoal; import ch.hsr.ifs.pystructure.typeinference.goals.references.AttributeReferencesGoal; import ch.hsr.ifs.pystructure.typeinference.goals.references.ClassReferencesGoal; import ch.hsr.ifs.pystructure.typeinference.goals.references.FunctionReferencesGoal; import ch.hsr.ifs.pystructure.typeinference.goals.references.MethodReferencesGoal; import ch.hsr.ifs.pystructure.typeinference.goals.references.PossibleAttributeReferencesGoal; import ch.hsr.ifs.pystructure.typeinference.goals.references.PossibleReferencesGoal; import ch.hsr.ifs.pystructure.typeinference.goals.types.ClassAttributeTypeGoal; import ch.hsr.ifs.pystructure.typeinference.goals.types.DefinitionTypeGoal; import ch.hsr.ifs.pystructure.typeinference.goals.types.ExpressionTypeGoal; import ch.hsr.ifs.pystructure.typeinference.goals.types.ReturnTypeGoal; import ch.hsr.ifs.pystructure.typeinference.goals.types.TupleElementTypeGoal; import ch.hsr.ifs.pystructure.typeinference.model.definitions.Argument; import ch.hsr.ifs.pystructure.typeinference.model.definitions.AssignDefinition; import ch.hsr.ifs.pystructure.typeinference.model.definitions.Definition; import ch.hsr.ifs.pystructure.typeinference.model.definitions.ExceptDefinition; import ch.hsr.ifs.pystructure.typeinference.model.definitions.Function; import ch.hsr.ifs.pystructure.typeinference.model.definitions.ImportDefinition; import ch.hsr.ifs.pystructure.typeinference.model.definitions.LoopVariableDefinition; import ch.hsr.ifs.pystructure.typeinference.model.definitions.Module; import ch.hsr.ifs.pystructure.typeinference.model.definitions.NoDefintion; import ch.hsr.ifs.pystructure.typeinference.results.types.ClassType; import ch.hsr.ifs.pystructure.typeinference.results.types.FunctionType; import ch.hsr.ifs.pystructure.typeinference.results.types.MetaclassType; import ch.hsr.ifs.pystructure.typeinference.results.types.ModuleType; import ch.hsr.ifs.pystructure.typeinference.results.types.TupleType; /** * Evaluator factory which, given a goal, creates the appropriate evaluator. It * can be seen as a kind of dispatcher. */ public class PythonEvaluatorFactory { private final Map<Class<? extends IGoal>, Class<? extends AbstractEvaluator>> evaluators; public PythonEvaluatorFactory() { evaluators = new HashMap<Class<? extends IGoal>, Class<? extends AbstractEvaluator>>(); initEvaluatorMap(); } private void initEvaluatorMap() { evaluators.put(PossibleReferencesGoal.class, PossibleReferencesEvaluator.class); evaluators.put(PossibleAttributeReferencesGoal.class, PossibleAttributeReferencesEvaluator.class); evaluators.put(MethodReferencesGoal.class, MethodReferencesEvaluator.class); evaluators.put(FunctionReferencesGoal.class, FunctionReferencesEvaluator.class); evaluators.put(AttributeReferencesGoal.class, AttributeReferencesEvaluator.class); evaluators.put(ClassReferencesGoal.class, ClassReferencesEvaluator.class); evaluators.put(ReturnTypeGoal.class, ReturnTypeEvaluator.class); evaluators.put(TupleElementTypeGoal.class, TupleElementTypeEvaluator.class); evaluators.put(ClassAttributeTypeGoal.class, ClassAttributeTypeEvaluator.class); evaluators.put(PossibleReferencesGoal.class, PossibleReferencesEvaluator.class); evaluators.put(PossibleReferencesGoal.class, PossibleReferencesEvaluator.class); } public AbstractEvaluator createEvaluator(IGoal goal) { AbstractEvaluator evaluator = createEvaluatorFromMap(goal); if (evaluator != null) { return evaluator; } if (goal instanceof DefinitionTypeGoal) { DefinitionTypeGoal defGoal = (DefinitionTypeGoal) goal; return createDefinitionEvaluator(defGoal); } if (goal instanceof ExpressionTypeGoal) { ExpressionTypeGoal exprGoal = (ExpressionTypeGoal) goal; return createExpressionEvaluator(exprGoal); } throw new RuntimeException("Can't create Evaluator for " + goal); } private AbstractEvaluator createEvaluatorFromMap(IGoal goal) { Class<? extends IGoal> goalClass = goal.getClass(); Class<? extends AbstractEvaluator> evaluatorClass = evaluators.get(goalClass); if (evaluatorClass == null) { return null; } try { AbstractEvaluator evaluator = evaluatorClass.getConstructor(goalClass).newInstance(goal); return evaluator; } catch (Exception e) { if (e instanceof RuntimeException) { throw (RuntimeException) e; } else { throw new RuntimeException(e); } } } private AbstractEvaluator createDefinitionEvaluator(DefinitionTypeGoal goal) { Definition def = goal.getDefinition(); Module module = goal.getContext().getModule(); if (def instanceof AssignDefinition) { return new AssignTypeEvaluator(goal, (AssignDefinition) def); } if (def instanceof Argument) { return new ArgumentTypeEvaluator(goal, (Argument) def); } if (def instanceof ImportDefinition) { return new ImportTypeEvaluator(goal, (ImportDefinition) def); } if (def instanceof Function) { Function function = (Function) def; return new FixedAnswerEvaluator(goal, new FunctionType(module, function)); } if (def instanceof ch.hsr.ifs.pystructure.typeinference.model.definitions.Class) { ch.hsr.ifs.pystructure.typeinference.model.definitions.Class klass = (ch.hsr.ifs.pystructure.typeinference.model.definitions.Class) def; return new FixedAnswerEvaluator(goal, new MetaclassType(module, klass)); } if (def instanceof Module) { Module moduleDef = (Module) def; return new FixedAnswerEvaluator(goal, new ModuleType(moduleDef)); } if (def instanceof LoopVariableDefinition) { // TODO: Implement LoopVariableTypeEvaluator return new FixedAnswerEvaluator(goal, new ClassType("object")); } if (def instanceof ExceptDefinition) { // TODO: Implement ExceptTypeEvaluator return new FixedAnswerEvaluator(goal, new ClassType("object")); } if (def instanceof NoDefintion) { return new FixedAnswerEvaluator(goal, new ClassType("object")); } throw new RuntimeException("Can't create evaluator for definition " + def + ", goal " + goal); } private AbstractEvaluator createExpressionEvaluator(ExpressionTypeGoal goal) { SimpleNode expr = goal.getExpression(); if (expr instanceof Name) { Name name = (Name) expr; if (name.id.equals("None")) { /* FIXME: shoudln't we create a new class for NoneType? */ return new FixedAnswerEvaluator(goal, new ClassType("NoneType")); } if (name.id.equals("True") || name.id.equals("False")) { return new FixedAnswerEvaluator(goal, new ClassType("bool")); } return new VariableReferenceEvaluator(goal, name); } if (expr instanceof Call) { return new CallTypeEvaluator(goal, (Call) expr); } if (expr instanceof Attribute) { return new AttributeTypeEvaluator(goal, (Attribute) expr); } if (expr instanceof BinOp) { return new BinOpTypeEvaluator(goal, (BinOp) expr); } if (expr instanceof IfExp) { return new IfExpTypeEvaluator(goal, (IfExp) expr); } return createLiteralEvaluator(goal); } // TODO: Maybe move this into an ExpressionTypeEvaluator. private AbstractEvaluator createLiteralEvaluator(ExpressionTypeGoal goal) { SimpleNode expr = goal.getExpression(); if (expr instanceof Num) { Num num = (Num) expr; String type = null; switch (num.type) { case num_typeType.Long: type = "long"; break; case num_typeType.Float: type = "float"; break; case num_typeType.Comp: type = "complex"; break; case num_typeType.Int: case num_typeType.Oct: case num_typeType.Hex: default: type = "int"; break; } return new FixedAnswerEvaluator(goal, new ClassType(type)); } if (expr instanceof Str) { Str str = (Str) expr; if (str.unicode) { return new FixedAnswerEvaluator(goal, new ClassType("unicode")); } else { return new FixedAnswerEvaluator(goal, new ClassType("str")); } } if (expr instanceof List) { return new FixedAnswerEvaluator(goal, new ClassType("list")); } if (expr instanceof Tuple) { return new FixedAnswerEvaluator(goal, new TupleType((Tuple) expr)); } if (expr instanceof Dict) { return new FixedAnswerEvaluator(goal, new ClassType("dict")); } if (expr instanceof Subscript) { return new FixedAnswerEvaluator(goal, new ClassType("list-element")); } if (expr instanceof ListComp) { /* FIXME: this is a expression like: * [field for field in self.fields if field.isempty() * * we could use the generators.iter to find out what kind of * list we have to expect here, but for now we have no idea about lists anyway */ return new FixedAnswerEvaluator(goal, new ClassType("list")); } if (expr instanceof Compare) { return new FixedAnswerEvaluator(goal, new ClassType("bool")); } if (expr instanceof UnaryOp) { return new FixedAnswerEvaluator(goal, new ClassType("bool")); } if (expr instanceof BoolOp) { return new FixedAnswerEvaluator(goal, new ClassType("bool")); } if (expr instanceof Lambda) { // FIXME: Implement properly (like function) return new FixedAnswerEvaluator(goal, new ClassType("function")); } throw new RuntimeException("Can't create evaluator for literal expression " + expr + ", goal " + goal); } }
src/ch/hsr/ifs/pystructure/typeinference/inferencer/dispatcher/PythonEvaluatorFactory.java
/******************************************************************************* * Copyright (c) 2005, 2007 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * *******************************************************************************/ package ch.hsr.ifs.pystructure.typeinference.inferencer.dispatcher; import java.util.HashMap; import java.util.Map; import org.python.pydev.parser.jython.SimpleNode; import org.python.pydev.parser.jython.ast.Attribute; import org.python.pydev.parser.jython.ast.BinOp; import org.python.pydev.parser.jython.ast.BoolOp; import org.python.pydev.parser.jython.ast.Call; import org.python.pydev.parser.jython.ast.Compare; import org.python.pydev.parser.jython.ast.Dict; import org.python.pydev.parser.jython.ast.IfExp; import org.python.pydev.parser.jython.ast.Lambda; import org.python.pydev.parser.jython.ast.List; import org.python.pydev.parser.jython.ast.ListComp; import org.python.pydev.parser.jython.ast.Name; import org.python.pydev.parser.jython.ast.Num; import org.python.pydev.parser.jython.ast.Str; import org.python.pydev.parser.jython.ast.Subscript; import org.python.pydev.parser.jython.ast.Tuple; import org.python.pydev.parser.jython.ast.UnaryOp; import org.python.pydev.parser.jython.ast.num_typeType; import ch.hsr.ifs.pystructure.typeinference.evaluators.base.AbstractEvaluator; import ch.hsr.ifs.pystructure.typeinference.evaluators.references.AttributeReferencesEvaluator; import ch.hsr.ifs.pystructure.typeinference.evaluators.references.ClassReferencesEvaluator; import ch.hsr.ifs.pystructure.typeinference.evaluators.references.FunctionReferencesEvaluator; import ch.hsr.ifs.pystructure.typeinference.evaluators.references.MethodReferencesEvaluator; import ch.hsr.ifs.pystructure.typeinference.evaluators.references.PossibleAttributeReferencesEvaluator; import ch.hsr.ifs.pystructure.typeinference.evaluators.references.PossibleReferencesEvaluator; import ch.hsr.ifs.pystructure.typeinference.evaluators.references.VariableReferenceEvaluator; import ch.hsr.ifs.pystructure.typeinference.evaluators.types.ArgumentTypeEvaluator; import ch.hsr.ifs.pystructure.typeinference.evaluators.types.AssignTypeEvaluator; import ch.hsr.ifs.pystructure.typeinference.evaluators.types.AttributeTypeEvaluator; import ch.hsr.ifs.pystructure.typeinference.evaluators.types.BinOpTypeEvaluator; import ch.hsr.ifs.pystructure.typeinference.evaluators.types.CallTypeEvaluator; import ch.hsr.ifs.pystructure.typeinference.evaluators.types.ClassAttributeTypeEvaluator; import ch.hsr.ifs.pystructure.typeinference.evaluators.types.FixedAnswerEvaluator; import ch.hsr.ifs.pystructure.typeinference.evaluators.types.IfExpTypeEvaluator; import ch.hsr.ifs.pystructure.typeinference.evaluators.types.ImportTypeEvaluator; import ch.hsr.ifs.pystructure.typeinference.evaluators.types.ReturnTypeEvaluator; import ch.hsr.ifs.pystructure.typeinference.evaluators.types.TupleElementTypeEvaluator; import ch.hsr.ifs.pystructure.typeinference.goals.base.IGoal; import ch.hsr.ifs.pystructure.typeinference.goals.references.AttributeReferencesGoal; import ch.hsr.ifs.pystructure.typeinference.goals.references.ClassReferencesGoal; import ch.hsr.ifs.pystructure.typeinference.goals.references.FunctionReferencesGoal; import ch.hsr.ifs.pystructure.typeinference.goals.references.MethodReferencesGoal; import ch.hsr.ifs.pystructure.typeinference.goals.references.PossibleAttributeReferencesGoal; import ch.hsr.ifs.pystructure.typeinference.goals.references.PossibleReferencesGoal; import ch.hsr.ifs.pystructure.typeinference.goals.types.ClassAttributeTypeGoal; import ch.hsr.ifs.pystructure.typeinference.goals.types.DefinitionTypeGoal; import ch.hsr.ifs.pystructure.typeinference.goals.types.ExpressionTypeGoal; import ch.hsr.ifs.pystructure.typeinference.goals.types.ReturnTypeGoal; import ch.hsr.ifs.pystructure.typeinference.goals.types.TupleElementTypeGoal; import ch.hsr.ifs.pystructure.typeinference.model.definitions.Argument; import ch.hsr.ifs.pystructure.typeinference.model.definitions.AssignDefinition; import ch.hsr.ifs.pystructure.typeinference.model.definitions.Definition; import ch.hsr.ifs.pystructure.typeinference.model.definitions.ExceptDefinition; import ch.hsr.ifs.pystructure.typeinference.model.definitions.Function; import ch.hsr.ifs.pystructure.typeinference.model.definitions.ImportDefinition; import ch.hsr.ifs.pystructure.typeinference.model.definitions.LoopVariableDefinition; import ch.hsr.ifs.pystructure.typeinference.model.definitions.Module; import ch.hsr.ifs.pystructure.typeinference.model.definitions.NoDefintion; import ch.hsr.ifs.pystructure.typeinference.results.types.ClassType; import ch.hsr.ifs.pystructure.typeinference.results.types.FunctionType; import ch.hsr.ifs.pystructure.typeinference.results.types.MetaclassType; import ch.hsr.ifs.pystructure.typeinference.results.types.ModuleType; import ch.hsr.ifs.pystructure.typeinference.results.types.TupleType; /** * Evaluator factory which, given a goal, creates the appropriate evaluator. It * can be seen as a kind of dispatcher. */ public class PythonEvaluatorFactory { private final Map<Class<? extends IGoal>, Class<? extends AbstractEvaluator>> evaluators; public PythonEvaluatorFactory() { evaluators = new HashMap<Class<? extends IGoal>, Class<? extends AbstractEvaluator>>(); initEvaluatorMap(); } private void initEvaluatorMap() { evaluators.put(PossibleReferencesGoal.class, PossibleReferencesEvaluator.class); evaluators.put(PossibleAttributeReferencesGoal.class, PossibleAttributeReferencesEvaluator.class); evaluators.put(MethodReferencesGoal.class, MethodReferencesEvaluator.class); evaluators.put(FunctionReferencesGoal.class, FunctionReferencesEvaluator.class); evaluators.put(AttributeReferencesGoal.class, AttributeReferencesEvaluator.class); evaluators.put(ClassReferencesGoal.class, ClassReferencesEvaluator.class); evaluators.put(ReturnTypeGoal.class, ReturnTypeEvaluator.class); evaluators.put(TupleElementTypeGoal.class, TupleElementTypeEvaluator.class); evaluators.put(ClassAttributeTypeGoal.class, ClassAttributeTypeEvaluator.class); evaluators.put(PossibleReferencesGoal.class, PossibleReferencesEvaluator.class); evaluators.put(PossibleReferencesGoal.class, PossibleReferencesEvaluator.class); } public AbstractEvaluator createEvaluator(IGoal goal) { AbstractEvaluator evaluator = createEvaluatorFromMap(goal); if (evaluator != null) { return evaluator; } if (goal instanceof DefinitionTypeGoal) { DefinitionTypeGoal defGoal = (DefinitionTypeGoal) goal; return createDefinitionEvaluator(defGoal); } if (goal instanceof ExpressionTypeGoal) { ExpressionTypeGoal exprGoal = (ExpressionTypeGoal) goal; return createExpressionEvaluator(exprGoal); } throw new RuntimeException("Can't create Evaluator for " + goal); } private AbstractEvaluator createEvaluatorFromMap(IGoal goal) { Class<? extends IGoal> goalClass = goal.getClass(); Class<? extends AbstractEvaluator> evaluatorClass = evaluators.get(goalClass); if (evaluatorClass == null) { return null; } try { AbstractEvaluator evaluator = evaluatorClass.getConstructor(goalClass).newInstance(goal); return evaluator; } catch (Exception e) { if (e instanceof RuntimeException) { throw (RuntimeException) e; } else { throw new RuntimeException(e); } } } private AbstractEvaluator createDefinitionEvaluator(DefinitionTypeGoal goal) { Definition def = goal.getDefinition(); Module module = goal.getContext().getModule(); if (def instanceof AssignDefinition) { return new AssignTypeEvaluator(goal, (AssignDefinition) def); } if (def instanceof Argument) { return new ArgumentTypeEvaluator(goal, (Argument) def); } if (def instanceof ImportDefinition) { return new ImportTypeEvaluator(goal, (ImportDefinition) def); } if (def instanceof Function) { Function function = (Function) def; return new FixedAnswerEvaluator(goal, new FunctionType(module, function)); } if (def instanceof ch.hsr.ifs.pystructure.typeinference.model.definitions.Class) { ch.hsr.ifs.pystructure.typeinference.model.definitions.Class klass = (ch.hsr.ifs.pystructure.typeinference.model.definitions.Class) def; return new FixedAnswerEvaluator(goal, new MetaclassType(module, klass)); } if (def instanceof Module) { Module moduleDef = (Module) def; return new FixedAnswerEvaluator(goal, new ModuleType(moduleDef)); } if (def instanceof LoopVariableDefinition) { // TODO: Implement LoopVariableTypeEvaluator return new FixedAnswerEvaluator(goal, new ClassType("object")); } if (def instanceof ExceptDefinition) { // TODO: Implement ExceptTypeEvaluator return new FixedAnswerEvaluator(goal, new ClassType("object")); } if (def instanceof NoDefintion) { return new FixedAnswerEvaluator(goal, new ClassType("object")); } throw new RuntimeException("Can't create evaluator for definition " + def + ", goal " + goal); } private AbstractEvaluator createExpressionEvaluator(ExpressionTypeGoal goal) { SimpleNode expr = goal.getExpression(); if (expr instanceof Name) { Name name = (Name) expr; if (name.id.equals("None")) { /* FIXME: shoudln't we create a new class for NoneType? */ return new FixedAnswerEvaluator(goal, new ClassType("NoneType")); } if (name.id.equals("True") || name.id.equals("False")) { return new FixedAnswerEvaluator(goal, new ClassType("bool")); } return new VariableReferenceEvaluator(goal, name); } if (expr instanceof Call) { return new CallTypeEvaluator(goal, (Call) expr); } if (expr instanceof Attribute) { return new AttributeTypeEvaluator(goal, (Attribute) expr); } if (expr instanceof BinOp) { return new BinOpTypeEvaluator(goal, (BinOp) expr); } if (expr instanceof IfExp) { return new IfExpTypeEvaluator(goal, (IfExp) expr); } return createLiteralEvaluator(goal); } // TODO: Maybe move this into an ExpressionTypeEvaluator. private AbstractEvaluator createLiteralEvaluator(ExpressionTypeGoal goal) { SimpleNode expr = goal.getExpression(); if (expr instanceof Num) { Num num = (Num) expr; String type = null; switch (num.type) { case num_typeType.Long: type = "long"; break; case num_typeType.Float: type = "float"; break; case num_typeType.Comp: type = "complex"; break; case num_typeType.Int: case num_typeType.Oct: case num_typeType.Hex: default: type = "int"; break; } return new FixedAnswerEvaluator(goal, new ClassType(type)); } if (expr instanceof Str) { Str str = (Str) expr; if (str.unicode) { return new FixedAnswerEvaluator(goal, new ClassType("unicode")); } else { return new FixedAnswerEvaluator(goal, new ClassType("str")); } } if (expr instanceof List) { return new FixedAnswerEvaluator(goal, new ClassType("list")); } if (expr instanceof Tuple) { return new FixedAnswerEvaluator(goal, new TupleType((Tuple) expr)); } if (expr instanceof Dict) { return new FixedAnswerEvaluator(goal, new ClassType("dict")); } if (expr instanceof Subscript) { return new FixedAnswerEvaluator(goal, new ClassType("list-element")); } if (expr instanceof ListComp) { /* FIXME: this is a expression like: * [field for field in self.fields if field.isempty() * * we could use the generators.iter to find out what kind of * list we have to expect here, but for now we have no idea about lists anyway */ return new FixedAnswerEvaluator(goal, new ClassType("list")); } if (expr instanceof Compare) { return new FixedAnswerEvaluator(goal, new ClassType("bool")); } if (expr instanceof UnaryOp) { return new FixedAnswerEvaluator(goal, new ClassType("bool")); } if (expr instanceof BoolOp) { return new FixedAnswerEvaluator(goal, new ClassType("bool")); } if (expr instanceof Lambda) { // FIXME: Implement properly (like function) return new FixedAnswerEvaluator(goal, new ClassType("function")); } throw new RuntimeException("Can't create evaluator for literal expression " + expr + ", goal " + goal); } }
The PythonEvaluatorFactory was solely developed by us. Removed IBM copyright
src/ch/hsr/ifs/pystructure/typeinference/inferencer/dispatcher/PythonEvaluatorFactory.java
The PythonEvaluatorFactory was solely developed by us. Removed IBM copyright
Java
lgpl-2.1
0bdcbc6c0d34cac1eb28d42d26bc4aaf1cb750ff
0
zebrafishmine/intermine,justincc/intermine,tomck/intermine,justincc/intermine,justincc/intermine,justincc/intermine,kimrutherford/intermine,Arabidopsis-Information-Portal/intermine,JoeCarlson/intermine,joshkh/intermine,zebrafishmine/intermine,tomck/intermine,kimrutherford/intermine,Arabidopsis-Information-Portal/intermine,Arabidopsis-Information-Portal/intermine,tomck/intermine,zebrafishmine/intermine,zebrafishmine/intermine,joshkh/intermine,elsiklab/intermine,JoeCarlson/intermine,JoeCarlson/intermine,justincc/intermine,tomck/intermine,Arabidopsis-Information-Portal/intermine,tomck/intermine,joshkh/intermine,elsiklab/intermine,justincc/intermine,drhee/toxoMine,drhee/toxoMine,JoeCarlson/intermine,kimrutherford/intermine,joshkh/intermine,drhee/toxoMine,justincc/intermine,justincc/intermine,zebrafishmine/intermine,Arabidopsis-Information-Portal/intermine,elsiklab/intermine,drhee/toxoMine,drhee/toxoMine,joshkh/intermine,kimrutherford/intermine,tomck/intermine,kimrutherford/intermine,zebrafishmine/intermine,tomck/intermine,drhee/toxoMine,JoeCarlson/intermine,joshkh/intermine,elsiklab/intermine,JoeCarlson/intermine,kimrutherford/intermine,zebrafishmine/intermine,Arabidopsis-Information-Portal/intermine,elsiklab/intermine,JoeCarlson/intermine,joshkh/intermine,JoeCarlson/intermine,joshkh/intermine,elsiklab/intermine,tomck/intermine,Arabidopsis-Information-Portal/intermine,zebrafishmine/intermine,Arabidopsis-Information-Portal/intermine,kimrutherford/intermine,joshkh/intermine,elsiklab/intermine,tomck/intermine,drhee/toxoMine,elsiklab/intermine,Arabidopsis-Information-Portal/intermine,zebrafishmine/intermine,elsiklab/intermine,kimrutherford/intermine,drhee/toxoMine,justincc/intermine,drhee/toxoMine,JoeCarlson/intermine,kimrutherford/intermine
package org.flymine.dataconversion; /* * Copyright (C) 2002-2004 FlyMine * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. See the LICENSE file for more * information or http://www.gnu.org/copyleft/lesser.html. * */ import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.Set; import java.util.HashSet; import java.util.Map; import java.util.HashMap; import java.util.List; import java.util.ArrayList; import java.util.StringTokenizer; import java.io.File; import java.io.FileReader; import com.hp.hpl.jena.ontology.OntModel; import com.hp.hpl.jena.rdf.model.ModelFactory; import org.intermine.InterMineException; import org.intermine.util.XmlUtil; import org.intermine.xml.full.Attribute; import org.intermine.xml.full.Item; import org.intermine.xml.full.Reference; import org.intermine.xml.full.ReferenceList; import org.intermine.xml.full.ItemHelper; import org.intermine.objectstore.ObjectStoreException; import org.intermine.objectstore.ObjectStore; import org.intermine.objectstore.ObjectStoreFactory; import org.intermine.objectstore.ObjectStoreWriter; import org.intermine.objectstore.ObjectStoreWriterFactory; import org.intermine.dataconversion.ItemReader; import org.intermine.dataconversion.ObjectStoreItemReader; import org.intermine.dataconversion.ItemWriter; import org.intermine.dataconversion.ObjectStoreItemWriter; import org.intermine.dataconversion.ObjectStoreItemPathFollowingImpl; import org.intermine.dataconversion.DataTranslator; import org.intermine.dataconversion.ItemPrefetchDescriptor; import org.intermine.dataconversion.ItemPrefetchConstraintDynamic; import org.intermine.dataconversion.FieldNameAndValue; import org.apache.log4j.Logger; /** * Convert MAGE data in fulldata Item format conforming to a source OWL definition * to fulldata Item format conforming to InterMine OWL definition. * * @author Wenyan Ji * @author Richard Smith */ public class MageDataTranslator extends DataTranslator { protected static final Logger LOG = Logger.getLogger(MageDataTranslator.class); // flymine:ReporterLocation id -> flymine:Feature id protected Map rlToFeature = new HashMap(); // mage:Feature id -> flymine:MicroArraySlideDesign id protected Map featureToDesign = new HashMap(); // hold on to ReporterLocation items until end protected Set reporterLocs = new HashSet(); protected Map bioEntity2Gene = new HashMap(); //mage: Feature id -> flymine:MicroArrayExperimentResult id when processing BioAssayDatum protected Map maer2Feature = new HashMap(); protected Set maerSet = new HashSet(); //maerItem //flymine: BioEntity id -> mage:Feature id when processing Reporter protected Map bioEntity2Feature = new HashMap(); protected Map bioEntity2IdentifierMap = new HashMap(); protected Set bioEntitySet = new HashSet(); protected Map synonymMap = new HashMap(); //key:itemId value:synonymItem protected Map synonymAccessionMap = new HashMap();//key:accession value:synonymItem // reporterSet:Flymine reporter. reporter:material -> bioEntity may probably merged when //it has same identifier. need to reprocess reporterMaterial protected Set reporterSet = new HashSet(); protected Map bioEntityRefMap = new HashMap(); protected Map identifier2BioEntity = new HashMap(); protected Map treatment2BioSourceMap = new HashMap(); protected Set bioSource = new HashSet(); protected Map organismMap = new HashMap(); private Map dbs = new HashMap(); private Map dbRefs = new HashMap(); private Item expItem = new Item();//assume only one experiment item presented protected Map reporter2FeatureMap = new HashMap(); protected Map assay2Maer = new HashMap(); protected Map assay2LabeledExtract = new HashMap(); protected Map maer2Reporter = new HashMap(); protected Map maer2Assay = new HashMap(); protected Map maer2Tissue = new HashMap(); protected Map maer2Material = new HashMap(); protected Map maer2Gene = new HashMap(); protected Set cdnaSet = new HashSet(); protected Map geneMap = new HashMap(); //organisamDbId, geneItem protected Set assaySet = new HashSet(); protected Map sample2LabeledExtract = new HashMap(); protected Set labeledExractSet = new HashSet(); protected Map reporter2rl = new HashMap(); /** * @see DataTranslator#DataTranslator */ public MageDataTranslator(ItemReader srcItemReader, OntModel model, String ns) { super(srcItemReader, model, ns); } /** * @see DataTranslator#translate */ public void translate(ItemWriter tgtItemWriter) throws ObjectStoreException, InterMineException { super.translate(tgtItemWriter); Iterator i = processReporterLocs().iterator(); while (i.hasNext()) { tgtItemWriter.store(ItemHelper.convert((Item) i.next())); } i = processBioEntity().iterator(); while (i.hasNext()) { tgtItemWriter.store(ItemHelper.convert((Item) i.next())); } i = processGene().iterator(); while (i.hasNext()) { tgtItemWriter.store(ItemHelper.convert((Item) i.next())); } i = processReporterMaterial().iterator(); while (i.hasNext()) { tgtItemWriter.store(ItemHelper.convert((Item) i.next())); } i = processBioSourceTreatment().iterator(); while (i.hasNext()) { tgtItemWriter.store(ItemHelper.convert((Item) i.next())); } i = processOrganism().iterator(); while (i.hasNext()) { tgtItemWriter.store(ItemHelper.convert((Item) i.next())); } i = dbs.values().iterator(); while (i.hasNext()) { tgtItemWriter.store(ItemHelper.convert((Item) i.next())); } i = processMaer().iterator(); while (i.hasNext()) { tgtItemWriter.store(ItemHelper.convert((Item) i.next())); } i = processLabeledExtract2Assay().iterator(); while (i.hasNext()) { tgtItemWriter.store(ItemHelper.convert((Item) i.next())); } i = processAssay2Experiment().iterator(); while (i.hasNext()) { tgtItemWriter.store(ItemHelper.convert((Item) i.next())); } } /** * @see DataTranslator#translateItem */ protected Collection translateItem(Item srcItem) throws ObjectStoreException, InterMineException { Collection result = new HashSet(); String normalised = null; String srcNs = XmlUtil.getNamespaceFromURI(srcItem.getClassName()); String className = XmlUtil.getFragmentFromURI(srcItem.getClassName()); if (className.equals("BioAssayDatum")) { normalised = srcItem.getAttribute("normalised").getValue(); srcItem = removeNormalisedAttribute(srcItem); } Collection translated = super.translateItem(srcItem); Item gene = new Item(); Item organism = new Item(); if (translated != null) { for (Iterator i = translated.iterator(); i.hasNext();) { boolean storeTgtItem = true; Item tgtItem = (Item) i.next(); // mage: BibliographicReference flymine:Publication if (className.equals("BibliographicReference")) { Set authors = createAuthors(srcItem); List authorIds = new ArrayList(); Iterator j = authors.iterator(); while (j.hasNext()) { Item author = (Item) j.next(); authorIds.add(author.getIdentifier()); result.add(author); } ReferenceList authorsRef = new ReferenceList("authors", authorIds); tgtItem.addCollection(authorsRef); } else if (className.equals("Database")) { Attribute attr = srcItem.getAttribute("name"); if (attr != null) { getDb(attr.getValue()); } storeTgtItem = false; } else if (className.equals("FeatureReporterMap")) { setReporterLocationCoords(srcItem, tgtItem); storeTgtItem = false; } else if (className.equals("PhysicalArrayDesign")) { createFeatureMap(srcItem); translateMicroArraySlideDesign(srcItem, tgtItem); } else if (className.equals("Experiment")) { // collection bioassays includes MeasuredBioAssay, PhysicalBioAssay // and DerivedBioAssay, only keep DerivedBioAssay //keepDBA(srcItem, tgtItem, srcNs); expItem = translateMicroArrayExperiment(srcItem, tgtItem, srcNs); result.add(expItem); storeTgtItem = false; } else if (className.equals("DerivedBioAssay")) { translateMicroArrayAssay(srcItem, tgtItem); storeTgtItem = false; } else if (className.equals("BioAssayDatum")) { translateMicroArrayExperimentalResult(srcItem, tgtItem, normalised); storeTgtItem = false; } else if (className.equals("Reporter")) { setBioEntityMap(srcItem, tgtItem); storeTgtItem = false; } else if (className.equals("BioSequence")) { translateBioEntity(srcItem, tgtItem); storeTgtItem = false; } else if (className.equals("LabeledExtract")) { translateLabeledExtract(srcItem, tgtItem); storeTgtItem = false; } else if (className.equals("BioSource")) { translateSample(srcItem, tgtItem); storeTgtItem = false; } else if (className.equals("Treatment")) { translateTreatment(srcItem, tgtItem); } if (storeTgtItem) { result.add(tgtItem); } } } return result; } /** * @param srcItem = mage:BibliographicReference * @return author set */ protected Set createAuthors(Item srcItem) { Set result = new HashSet(); if (srcItem.hasAttribute("authors")) { Attribute authorsAttr = srcItem.getAttribute("authors"); if (authorsAttr != null) { String authorStr = authorsAttr.getValue(); StringTokenizer st = new StringTokenizer(authorStr, ";"); while (st.hasMoreTokens()) { String name = st.nextToken().trim(); Item author = createItem(tgtNs + "Author", ""); author.addAttribute(new Attribute("name", name)); result.add(author); } } } return result; } /** * @param srcItem = mage: FeatureReporterMap * @param tgtItem = flymine: ReporterLocation * @throws ObjectStoreException if problem occured during translating */ protected void setReporterLocationCoords(Item srcItem, Item tgtItem) throws ObjectStoreException { if (srcItem.hasCollection("featureInformationSources")) { ReferenceList featureInfos = srcItem.getCollection("featureInformationSources"); if (!isSingleElementCollection(featureInfos)) { LOG.error("FeatureReporterMap (" + srcItem.getIdentifier() + ") does not have single element collection" + featureInfos.getRefIds().toString()); // throw new IllegalArgumentException("FeatureReporterMap (" // + srcItem.getIdentifier() // + " has more than one featureInformationSource"); } //FeatureInformationSources->FeatureInformation->Feature->FeatureLocation // prefetch done Item featureInfo = ItemHelper.convert(srcItemReader .getItemById(getFirstId(featureInfos))); if (featureInfo.hasReference("feature")) { Item feature = ItemHelper.convert(srcItemReader .getItemById(featureInfo.getReference("feature").getRefId())); if (feature.hasReference("featureLocation")) { Item featureLoc = ItemHelper.convert(srcItemReader .getItemById(feature.getReference("featureLocation").getRefId())); if (featureLoc != null) { tgtItem.addAttribute(new Attribute("localX", featureLoc.getAttribute("column").getValue())); tgtItem.addAttribute(new Attribute("localY", featureLoc.getAttribute("row").getValue())); } } if (feature.hasReference("zone")) { Item zone = ItemHelper.convert(srcItemReader .getItemById(feature.getReference("zone").getRefId())); if (zone != null) { tgtItem.addAttribute(new Attribute("zoneX", zone.getAttribute("column").getValue())); tgtItem.addAttribute(new Attribute("zoneY", zone.getAttribute("row").getValue())); } } reporterLocs.add(tgtItem); rlToFeature.put(tgtItem.getIdentifier(), feature.getIdentifier()); } } else { LOG.error("FeatureReporterMap (" + srcItem.getIdentifier() + ") does not have featureInformationSource"); // throw new IllegalArgumentException("FeatureReporterMap (" // + srcItem.getIdentifier() // + " does not have featureInformationSource"); } if (srcItem.hasReference("reporter")) { reporter2rl.put(srcItem.getReference("reporter").getRefId(), srcItem.getIdentifier()); } } /** * @param srcItem = mage:PhysicalArrayDesign * @throws ObjectStoreException if problem occured during translating */ protected void createFeatureMap(Item srcItem) throws ObjectStoreException { if (srcItem.hasCollection("featureGroups")) { ReferenceList featureGroups = srcItem.getCollection("featureGroups"); if (featureGroups == null || !isSingleElementCollection(featureGroups)) { throw new IllegalArgumentException("PhysicalArrayDesign (" + srcItem.getIdentifier() + ") does not have exactly one featureGroup"); } // prefetch done Item featureGroup = ItemHelper.convert(srcItemReader .getItemById(getFirstId(featureGroups))); Iterator featureIter = featureGroup.getCollection("features").getRefIds().iterator(); while (featureIter.hasNext()) { featureToDesign.put((String) featureIter.next(), srcItem.getIdentifier()); } } } /** * @param srcItem = mage:Reporter * @param tgtItem = flymine:Reporter * set BioEntity2FeatureMap when translating Reporter * set BioEntity2IdentifierMap when translating Reporter * @throws ObjectStoreException if errors occured during translating */ protected void setBioEntityMap(Item srcItem, Item tgtItem) throws ObjectStoreException { StringBuffer sb = new StringBuffer(); boolean controlFlg = false; ReferenceList failTypes = new ReferenceList(); //prefetch done if (srcItem.hasCollection("failTypes")) { failTypes = srcItem.getCollection("failTypes"); if (failTypes != null) { for (Iterator l = srcItem.getCollection("failTypes").getRefIds().iterator(); l.hasNext();) { Item ontoItem = ItemHelper.convert(srcItemReader.getItemById( (String) l.next())); sb.append(ontoItem.getAttribute("value").getValue() + " "); } tgtItem.addAttribute(new Attribute("failType", sb.toString())); } } //prefetch done if (srcItem.hasReference("controlType")) { Reference controlType = srcItem.getReference("controlType"); if (controlType != null) { Item controlItem = ItemHelper.convert(srcItemReader.getItemById( (String) srcItem.getReference("controlType").getRefId())); if (controlItem.getAttribute("value").getValue().equals("control_buffer")) { controlFlg = true; } } } ReferenceList featureReporterMaps = srcItem.getCollection("featureReporterMaps"); ReferenceList immobilizedChar = srcItem.getCollection("immobilizedCharacteristics"); sb = new StringBuffer(); String identifier = null; if (immobilizedChar == null) { if (failTypes != null) { //throw new IllegalArgumentException( LOG.info("Reporter (" + srcItem.getIdentifier() + ") does not have immobilizedCharacteristics because it fails"); } else if (controlFlg) { LOG.info("Reporter (" + srcItem.getIdentifier() + ") does not have immobilizedCharacteristics because" + " it is a control_buffer"); } else { throw new IllegalArgumentException("Reporter (" + srcItem.getIdentifier() + ") does not have immobilizedCharacteristics"); } } else if (!isSingleElementCollection(immobilizedChar)) { throw new IllegalArgumentException("Reporter (" + srcItem.getIdentifier() + ") have more than one immobilizedCharacteristics"); } else { //create bioEntity2IdentifierMap //identifier = reporter: name for CDNAClone, Vector //identifier = reporter: controlType;name;descriptions for genomic_dna //prefetch done identifier = getFirstId(immobilizedChar); String identifierAttribute = null; Item bioSequence = ItemHelper.convert(srcItemReader.getItemById(identifier)); if (bioSequence.hasReference("type")) { Item oeItem = ItemHelper.convert(srcItemReader.getItemById( (String) bioSequence.getReference("type").getRefId())); if (oeItem.getAttribute("value").getValue().equals("genomic_DNA")) { sb = new StringBuffer(); if (srcItem.hasReference("controlType")) { Item controlItem = ItemHelper.convert(srcItemReader.getItemById((String) srcItem.getReference("controlType").getRefId())); if (controlItem.hasAttribute("value")) { sb.append(controlItem.getAttribute("value").getValue() + ";"); } } if (srcItem.hasAttribute("name")) { sb.append(srcItem.getAttribute("name").getValue() + ";"); } if (srcItem.hasCollection("descriptions")) { for (Iterator k = srcItem.getCollection( "descriptions").getRefIds().iterator(); k.hasNext();) { Item description = ItemHelper.convert(srcItemReader.getItemById( (String) k.next())); if (description.hasAttribute("text")) { sb.append(description.getAttribute("text").getValue() + ";"); } } } if (sb.length() > 1) { identifierAttribute = sb.substring(0, sb.length() - 1); bioEntity2IdentifierMap.put(identifier, identifierAttribute); } } else { sb = new StringBuffer(); if (srcItem.hasAttribute("name")) { sb.append(srcItem.getAttribute("name").getValue()); identifierAttribute = sb.toString(); bioEntity2IdentifierMap.put(identifier, identifierAttribute); } } } //create bioEntity2FeatureMap sb = new StringBuffer(); if (featureReporterMaps != null) { for (Iterator i = featureReporterMaps.getRefIds().iterator(); i.hasNext(); ) { //FeatureReporterMap //desc2 String s = (String) i.next(); Item frm = ItemHelper.convert(srcItemReader.getItemById(s)); if (frm.hasCollection("featureInformationSources")) { Iterator j = frm.getCollection("featureInformationSources"). getRefIds().iterator(); // prefetch done while (j.hasNext()) { Item fis = ItemHelper.convert(srcItemReader.getItemById( (String) j.next())); if (fis.hasReference("feature")) { sb.append(fis.getReference("feature").getRefId() + " "); } } } } if (sb.length() > 1) { String feature = sb.substring(0, sb.length() - 1); bioEntity2Feature.put(identifier, feature); reporter2FeatureMap.put(srcItem.getIdentifier(), feature); } LOG.debug("bioEntity2Feature" + bioEntity2Feature.toString()); tgtItem.addReference(new Reference("material", identifier)); } } reporterSet.add(tgtItem); } /** * @param srcItem = mage:PhysicalArrayDesign * @param tgtItem = flymine:MicroArraySlideDesign * @throws ObjectStoreException if problem occured during translating */ protected void translateMicroArraySlideDesign(Item srcItem, Item tgtItem) throws ObjectStoreException { // move descriptions reference list //prefetch done if (srcItem.hasCollection("descriptions")) { ReferenceList des = srcItem.getCollection("descriptions"); if (des != null) { for (Iterator i = des.getRefIds().iterator(); i.hasNext(); ) { Item anno = ItemHelper.convert(srcItemReader.getItemById((String) i.next())); if (anno != null) { promoteCollection(srcItem, "descriptions", "annotations", tgtItem, "descriptions"); } } } } // change substrateType reference to attribute //prefetch done if (srcItem.hasReference("surfaceType")) { Item surfaceType = ItemHelper.convert(srcItemReader .getItemById(srcItem.getReference("surfaceType").getRefId())); if (surfaceType.hasAttribute("value")) { tgtItem.addAttribute(new Attribute("surfaceType", surfaceType.getAttribute("value").getValue())); } } if (srcItem.hasAttribute("version")) { tgtItem.addAttribute(new Attribute("version", srcItem.getAttribute("version").getValue())); } if (srcItem.hasAttribute("name")) { tgtItem.addAttribute(new Attribute("name", srcItem.getAttribute("name").getValue())); } } /** * @param srcItem = mage:Experiment * @param tgtItem = flymine: MicroArrayExperiment * @param srcNs = mage: src namespace * @return experiment Item * also created a HashMap assay2LabeledExtract * @throws ObjectStoreException if problem occured during translating */ protected Item translateMicroArrayExperiment(Item srcItem, Item tgtItem, String srcNs) throws ObjectStoreException { String derived = null; String physical = null; // prefetch done if (srcItem.hasCollection("bioAssays")) { ReferenceList rl = srcItem.getCollection("bioAssays"); ReferenceList newRl = new ReferenceList(); newRl.setName("assays"); for (Iterator i = rl.getRefIds().iterator(); i.hasNext(); ) { Item baItem = ItemHelper.convert(srcItemReader.getItemById((String) i.next())); if (baItem.getClassName().equals(srcNs + "DerivedBioAssay")) { derived = baItem.getIdentifier(); newRl.addRefId(derived); } if (baItem.getClassName().equals(srcNs + "PhysicalBioAssay")) { physical = baItem.getIdentifier(); } } //tgtItem.addCollection(newRl); } //prefetch? List labeledExtract = new ArrayList(); if (physical != null && derived != null) { Item pbaItem = ItemHelper.convert(srcItemReader.getItemById(physical)); if (pbaItem.hasReference("bioAssayCreation")) { Item hybri = ItemHelper.convert(srcItemReader.getItemById( pbaItem.getReference("bioAssayCreation").getRefId())); if (hybri.hasCollection("sourceBioMaterialMeasurements")) { ReferenceList sbmm = hybri.getCollection("sourceBioMaterialMeasurements"); for (Iterator i = sbmm.getRefIds().iterator(); i.hasNext(); ) { Item bmm = ItemHelper.convert(srcItemReader.getItemById((String) i.next())); if (bmm.hasReference("bioMaterial")) { labeledExtract.add(bmm.getReference("bioMaterial").getRefId()); } } } } if (labeledExtract != null) { assay2LabeledExtract.put(derived, labeledExtract); } } if (srcItem.hasAttribute("name")) { tgtItem.addAttribute(new Attribute("name", srcItem.getAttribute("name").getValue())); } // prefetch done if (srcItem.hasCollection("descriptions")) { ReferenceList desRl = srcItem.getCollection("descriptions"); boolean desFlag = false; boolean pubFlag = false; for (Iterator i = desRl.getRefIds().iterator(); i.hasNext(); ) { Item desItem = ItemHelper.convert(srcItemReader.getItemById((String) i.next())); if (desItem.hasAttribute("text")) { if (desFlag) { LOG.error("Already set description for MicroArrayExperiment, " + " srcItem = " + srcItem.getIdentifier()); } else { tgtItem.addAttribute(new Attribute("description", desItem.getAttribute("text").getValue())); desFlag = true; } } if (desItem.hasCollection("bibliographicReferences")) { ReferenceList publication = desItem.getCollection( "bibliographicReferences"); if (publication != null) { if (!isSingleElementCollection(publication)) { throw new IllegalArgumentException("Experiment description collection (" + desItem.getIdentifier() + ") has more than one bibliographicReferences"); } else { if (pubFlag) { LOG.error("Already set publication for MicroArrayExperiment, " + " srcItem = " + srcItem.getIdentifier()); } else { tgtItem.addReference(new Reference("publication", getFirstId(publication))); pubFlag = true; } } } } } } if (expItem.getIdentifier() != "") { tgtItem.setIdentifier(expItem.getIdentifier()); } return tgtItem; } /** * @param srcItem = mage: DerivedBioAssay * @param tgtItem = flymine:MicroArrayAssay * @throws ObjectStoreException if problem occured during translating */ protected void translateMicroArrayAssay(Item srcItem, Item tgtItem) throws ObjectStoreException { if (srcItem.hasCollection("derivedBioAssayData")) { ReferenceList dbad = srcItem.getCollection("derivedBioAssayData"); List resultsRl = new ArrayList(); for (Iterator j = dbad.getRefIds().iterator(); j.hasNext(); ) { // prefetch done Item dbadItem = ItemHelper.convert(srcItemReader.getItemById((String) j.next())); if (dbadItem.hasReference("bioDataValues")) { Item bioDataTuples = ItemHelper.convert(srcItemReader.getItemById( dbadItem.getReference("bioDataValues").getRefId())); if (bioDataTuples.hasCollection("bioAssayTupleData")) { ReferenceList rl = bioDataTuples.getCollection("bioAssayTupleData"); for (Iterator i = rl.getRefIds().iterator(); i.hasNext(); ) { String ref = (String) i.next(); if (!resultsRl.contains(ref)) { resultsRl.add(ref); } } } } } //tgtItem.addCollection(new ReferenceList("results", resultsRl)); if (resultsRl != null) { assay2Maer.put(srcItem.getIdentifier(), resultsRl); assaySet.add(tgtItem); } } } /** * @param srcItem = mage:BioAssayDatum * @param tgtItem = flymine:MicroArrayExperimentalResult * @param normalised is defined in translateItem * @throws ObjectStoreException if problem occured during translating */ public void translateMicroArrayExperimentalResult(Item srcItem, Item tgtItem, String normalised) throws ObjectStoreException { tgtItem.addAttribute(new Attribute("normalised", normalised)); if (srcItem.hasAttribute("value")) { tgtItem.addAttribute(new Attribute("value", srcItem.getAttribute("value").getValue())); } tgtItem.addReference(new Reference("analysis", getAnalysisRef())); //create maer2Feature map, and maer set if (srcItem.hasReference("designElement")) { maer2Feature.put(tgtItem.getIdentifier(), srcItem.getReference("designElement").getRefId()); //maerSet.add(tgtItem.getIdentifier()); } //prefetch done if (srcItem.hasReference("quantitationType")) { Item qtItem = ItemHelper.convert(srcItemReader.getItemById( srcItem.getReference("quantitationType").getRefId())); if (qtItem.getClassName().endsWith("MeasuredSignal") || qtItem.getClassName().endsWith("Ratio")) { if (qtItem.hasAttribute("name")) { tgtItem.addAttribute(new Attribute("type", qtItem.getAttribute("name").getValue())); } else { LOG.error("srcItem ( " + qtItem.getIdentifier() + " ) does not have name attribute"); } if (qtItem.hasReference("scale")) { Item oeItem = ItemHelper.convert(srcItemReader.getItemById( qtItem.getReference("scale").getRefId())); tgtItem.addAttribute(new Attribute("scale", oeItem.getAttribute("value").getValue())); } else { LOG.error("srcItem (" + qtItem.getIdentifier() + "( does not have scale attribute "); } if (qtItem.hasAttribute("isBackground")) { tgtItem.addAttribute(new Attribute("isBackground", qtItem.getAttribute("isBackground").getValue())); } else { LOG.error("srcItem (" + qtItem.getIdentifier() + "( does not have scale reference "); } } else if (qtItem.getClassName().endsWith("Error")) { if (qtItem.hasAttribute("name")) { tgtItem.addAttribute(new Attribute("type", qtItem.getAttribute("name").getValue())); } else { LOG.error("srcItem ( " + qtItem.getIdentifier() + " ) does not have name attribute"); } if (qtItem.hasReference("targetQuantitationType")) { Item msItem = ItemHelper.convert(srcItemReader.getItemById( qtItem.getReference("targetQuantitationType").getRefId())); if (msItem.hasReference("scale")) { Item oeItem = ItemHelper.convert(srcItemReader.getItemById( msItem.getReference("scale").getRefId())); tgtItem.addAttribute(new Attribute("scale", oeItem.getAttribute("value").getValue())); } else { LOG.error("srcItem (" + msItem.getIdentifier() + "( does not have scale attribute "); } if (msItem.hasAttribute("isBackground")) { tgtItem.addAttribute(new Attribute("isBackground", msItem.getAttribute("isBackground").getValue())); } else { LOG.error("srcItem (" + msItem.getIdentifier() + "( does not have scale reference "); } } } } maerSet.add(tgtItem); } /** * @param srcItem = mage:BioSequence * @param tgtItem = flymine:BioEntity(genomic_DNA =>NuclearDNA cDNA_clone=>CDNAClone, * vector=>Vector) * extra will create for Gene(FBgn), Vector(FBmc) and Synonym(embl) * synonymMap(itemid, item), synonymAccessionMap(accession, item) and * synonymAccession (HashSet) created for flymine:Synonym, * geneList include Gene and Vector to reprocess to add mAER collection * bioEntityList include CDNAClone and NuclearDNA to add identifier attribute * and mAER collection * @throws ObjectStoreException if problem occured during translating */ protected void translateBioEntity(Item srcItem, Item tgtItem) throws ObjectStoreException { Item gene = new Item(); Item vector = new Item(); Item synonym = new Item(); String s = null; String identifier = null; //prefetch done if (srcItem.hasReference("type")) { Item item = ItemHelper.convert(srcItemReader.getItemById( srcItem.getReference("type").getRefId())); if (item.hasAttribute("value")) { s = item.getAttribute("value").getValue(); if (s.equals("genomic_DNA")) { tgtItem.setClassName(tgtNs + "NuclearDNA"); } else if (s.equals("cDNA_clone")) { tgtItem.setClassName(tgtNs + "CDNAClone"); } else if (s.equals("vector")) { tgtItem.setClassName(tgtNs + "Vector"); } else { tgtItem = null; } } } // prefetch done if (srcItem.hasCollection("sequenceDatabases")) { ReferenceList rl = srcItem.getCollection("sequenceDatabases"); identifier = null; List geneList = new ArrayList(); List emblList = new ArrayList(); for (Iterator i = rl.getRefIds().iterator(); i.hasNext(); ) { Item dbEntryItem = ItemHelper.convert(srcItemReader. getItemById((String) i.next())); if (dbEntryItem.hasReference("database")) { Item dbItem = ItemHelper.convert(srcItemReader.getItemById( (String) dbEntryItem.getReference("database").getRefId())); String synonymSourceId = dbItem.getIdentifier(); if (dbItem.hasAttribute("name")) { String dbName = dbItem.getAttribute("name").getValue(); String organismDbId = dbEntryItem.getAttribute("accession").getValue(); if (dbName.equals("flybase") && organismDbId.startsWith("FBgn")) { gene = createGene(tgtNs + "Gene", "", dbEntryItem.getIdentifier(), organismDbId, tgtItem.getIdentifier()); // } else if (dbName.equals("flybase") && organismDbId.startsWith("FBmc")) { // tgtItem.addAttribute(new Attribute("organismDbId", organismDbId)); } else if (dbName.equals("embl") && dbEntryItem.hasAttribute("accession")) { String accession = dbEntryItem.getAttribute("accession").getValue(); //make sure synonym only create once for same accession if (!synonymAccessionMap.keySet().contains(accession)) { emblList.add(dbEntryItem.getIdentifier()); synonym = createSynonym(dbEntryItem, getSourceRef("embl"), srcItem.getIdentifier()); synonymMap.put(dbEntryItem.getIdentifier(), synonym); synonymAccessionMap.put(accession, synonym); } } else { //getDatabaseRef(); } } } } if (emblList != null && !emblList.isEmpty()) { ReferenceList synonymEmblRl = new ReferenceList("synonyms", emblList); tgtItem.addCollection(synonymEmblRl); } } if (tgtItem != null) { bioEntitySet.add(tgtItem); } } /** * @param srcItem = databaseEntry item refed in BioSequence * @param sourceRef ref to sourceId = database id * @param subjectId = bioEntity identifier will probably be changed * when reprocessing bioEntitySet * @return synonym item */ protected Item createSynonym(Item srcItem, Reference sourceRef, String subjectId) { Item synonym = new Item(); synonym.setClassName(tgtNs + "Synonym"); synonym.setIdentifier(srcItem.getIdentifier()); synonym.setImplementations(""); synonym.addAttribute(new Attribute("type", "accession")); synonym.addReference(sourceRef); synonym.addAttribute(new Attribute("value", srcItem.getAttribute("accession").getValue())); synonym.addReference(new Reference("subject", subjectId)); return synonym; } /** * @param srcItem = mage:LabeledExtract * @param tgtItem = flymine:LabeledExtract * @throws ObjectStoreException if problem occured during translating * LabeledExtract -> {treatments} -> {sourceBioMaterialMeasurements} -> *(BioSample)extract -> {treatments} -> {sourceBioMaterialMeasurements} -> *(BioSample)not-extract -> {treatments} -> {sourceBioMaterialMeasurements} -> *(BioSource) */ public void translateLabeledExtract(Item srcItem, Item tgtItem) throws ObjectStoreException { //prefetch done if (srcItem.hasReference("materialType")) { Item type = ItemHelper.convert(srcItemReader.getItemById( (String) srcItem.getReference("materialType").getRefId())); tgtItem.addAttribute(new Attribute("materialType", type.getAttribute("value").getValue())); } if (srcItem.hasCollection("labels")) { ReferenceList labels = srcItem.getCollection("labels"); if (labels == null || !isSingleElementCollection(labels)) { throw new IllegalArgumentException("LabeledExtract (" + srcItem.getIdentifier() + " does not have exactly one label"); } // prefetch done Item label = ItemHelper.convert(srcItemReader .getItemById(getFirstId(labels))); tgtItem.addAttribute(new Attribute("label", label.getAttribute("name").getValue())); } // prefetch done List treatmentList = new ArrayList(); String sampleId = null; StringBuffer sb = new StringBuffer(); if (srcItem.hasCollection("treatments")) { ReferenceList treatments = srcItem.getCollection("treatments"); for (Iterator i = treatments.getRefIds().iterator(); i.hasNext(); ) { String refId = (String) i.next(); treatmentList.add(refId); Item treatmentItem = ItemHelper.convert(srcItemReader.getItemById(refId)); if (treatmentItem.hasCollection("sourceBioMaterialMeasurements")) { ReferenceList sourceRl = treatmentItem.getCollection( "sourceBioMaterialMeasurements"); for (Iterator j = sourceRl.getRefIds().iterator(); j.hasNext(); ) { //bioMaterialMeausrement Item bioMMItem = ItemHelper.convert(srcItemReader.getItemById( (String) j.next())); if (bioMMItem.hasReference("bioMaterial")) { Item bioSample = ItemHelper.convert(srcItemReader.getItemById( (String) bioMMItem.getReference("bioMaterial").getRefId())); if (bioSample.hasCollection("treatments")) { ReferenceList bioSampleTreatments = bioSample.getCollection( "treatments"); for (Iterator k = bioSampleTreatments.getRefIds().iterator(); k.hasNext();) { refId = (String) k.next(); if (!treatmentList.contains(refId)) { treatmentList.add(refId); } //create treatment2BioSourceMap Item treatItem = ItemHelper.convert(srcItemReader. getItemById(refId)); //sampleId should be same despite of different //intermediate value sampleId = createTreatment2BioSourceMap(treatItem, srcItem.getIdentifier()); sb.append(sampleId + " "); } } } } } } ReferenceList tgtTreatments = new ReferenceList("treatments", treatmentList); tgtItem.addCollection(tgtTreatments); StringTokenizer st = new StringTokenizer(sb.toString()); while (st.hasMoreTokens()) { String s = st.nextToken(); if (!s.equals(sampleId)) { throw new IllegalArgumentException ("LabeledExtract (" + srcItem.getIdentifier() + " does not have exactly one reference to sample"); } } tgtItem.addReference(new Reference("sample", sampleId)); sample2LabeledExtract.put(sampleId, tgtItem.getIdentifier()); } labeledExractSet.add(tgtItem); } /** * @param srcItem = mage:BioSource * @param tgtItem = flymine:Sample * extra flymine:Organism item is created and saved in organismMap * @throws ObjectStoreException if problem occured during translating */ protected void translateSample(Item srcItem, Item tgtItem) throws ObjectStoreException { List list = new ArrayList(); Item organism = new Item(); String s = null; if (srcItem.hasCollection("characteristics")) { ReferenceList characteristics = srcItem.getCollection("characteristics"); for (Iterator i = characteristics.getRefIds().iterator(); i.hasNext();) { String id = (String) i.next(); // prefetch done Item charItem = ItemHelper.convert(srcItemReader.getItemById(id)); if (charItem.hasAttribute("category")) { s = charItem.getAttribute("category").getValue(); if (s.equals("Organism")) { if (charItem.hasAttribute("value")) { String organismName = charItem.getAttribute("value").getValue(); organism = createOrganism(tgtNs + "Organism", "", organismName); tgtItem.addReference(new Reference("organism", organism.getIdentifier())); } } else { list.add(id); } } } ReferenceList tgtChar = new ReferenceList("characteristics", list); tgtItem.addCollection(tgtChar); } if (srcItem.hasReference("materialType")) { Item type = ItemHelper.convert(srcItemReader.getItemById( (String) srcItem.getReference("materialType").getRefId())); tgtItem.addAttribute(new Attribute("materialType", type.getAttribute("value").getValue())); } if (srcItem.hasAttribute("name")) { tgtItem.addAttribute(new Attribute("name", srcItem.getAttribute("name").getValue())); } bioSource.add(tgtItem); } /** * @param srcItem = mage:Treatment * @param tgtItem = flymine:Treatment * @throws ObjectStoreException if problem occured during translating */ public void translateTreatment(Item srcItem, Item tgtItem) throws ObjectStoreException { //prefetch done if (srcItem.hasReference("action")) { Item action = ItemHelper.convert(srcItemReader.getItemById( (String) srcItem.getReference("action").getRefId())); if (action.hasAttribute("value")) { tgtItem.addAttribute(new Attribute("action", action.getAttribute("value").getValue())); } } } /** * @param srcItem = mage:Treatment from BioSample<Extract> * @param sourceId = mage:LabeledExtract srcItem identifier * @return string of bioSourceId * @throws ObjectStoreException if problem occured during translating * method called when processing LabeledExtract */ protected String createTreatment2BioSourceMap(Item srcItem, String sourceId) throws ObjectStoreException { StringBuffer bioSourceId = new StringBuffer(); StringBuffer treatment = new StringBuffer(); String id = null; if (srcItem.hasCollection("sourceBioMaterialMeasurements")) { ReferenceList sourceRl1 = srcItem.getCollection("sourceBioMaterialMeasurements"); for (Iterator l = sourceRl1.getRefIds().iterator(); l.hasNext(); ) { // prefetch done (but limited) Item sbmmItem = ItemHelper.convert(srcItemReader.getItemById( (String) l.next())); if (sbmmItem.hasReference("bioMaterial")) { // bioSampleItem, type not-extract Item bioSampleItem = ItemHelper.convert(srcItemReader.getItemById( (String) sbmmItem.getReference("bioMaterial").getRefId())); if (bioSampleItem.hasCollection("treatments")) { ReferenceList bioSourceRl = bioSampleItem.getCollection("treatments"); for (Iterator m = bioSourceRl.getRefIds().iterator(); m.hasNext();) { String treatmentList = (String) m.next(); treatment.append(treatmentList + " "); Item bioSourceTreatmentItem = ItemHelper.convert(srcItemReader. getItemById(treatmentList)); if (bioSourceTreatmentItem.hasCollection( "sourceBioMaterialMeasurements")) { ReferenceList sbmmRl = bioSourceTreatmentItem.getCollection( "sourceBioMaterialMeasurements"); for (Iterator n = sbmmRl.getRefIds().iterator(); n.hasNext();) { Item bmm = ItemHelper.convert(srcItemReader.getItemById( (String) n.next())); if (bmm.hasReference("bioMaterial")) { id = (String) bmm.getReference("bioMaterial"). getRefId(); bioSourceId.append(id + " "); } } } } } } } } //BioSample(not-extract) -> {treatments} -> {sourceBioMaterialMeasurements} ->(BioSource) // StringTokenizer st = new StringTokenizer(bioSourceId.toString()); while (st.hasMoreTokens()) { String s = st.nextToken(); if (!s.equals(id)) { throw new IllegalArgumentException("LabeledExtract (" + sourceId + " does not have exactly one reference to sample"); } } treatment2BioSourceMap.put(id, treatment.toString()); return id; } /** * bioSourceItem = flymine:Sample item without treatment collection * treatment collection is from mage:BioSample<type: not-Extract> treatment collection * treatment2BioSourceMap is created when tranlating LabeledExtract * @return resultSet */ protected Set processBioSourceTreatment() { Set results = new HashSet(); Iterator i = bioSource.iterator(); while (i.hasNext()) { Item bioSourceItem = (Item) i.next(); String sampleId = (String) bioSourceItem.getIdentifier(); List treatList = new ArrayList(); String s = (String) treatment2BioSourceMap.get(sampleId); LOG.debug("treatmentList " + s + " for " + sampleId); if (s != null) { StringTokenizer st = new StringTokenizer(s); while (st.hasMoreTokens()) { treatList.add(st.nextToken()); } } ReferenceList treatments = new ReferenceList("treatments", treatList); bioSourceItem.addCollection(treatments); //add labeledExtract reference to Sample String le = null; if (sample2LabeledExtract.containsKey(sampleId)) { le = (String) sample2LabeledExtract.get(sampleId); if (le != null) { bioSourceItem.addReference(new Reference("labeledExtract", le)); } } results.add(bioSourceItem); } return results; } /** * get le2Assay hashmap from assay2LabeledExtract map * add assay reference to LabeledExtract * @return LabeledExtract */ protected Set processLabeledExtract2Assay() { Set results = new HashSet(); Map le2Assay = new HashMap(); for (Iterator i = assaySet.iterator(); i.hasNext(); ) { Item assayItem = (Item) i.next(); String id = (String) assayItem.getIdentifier(); if (assay2LabeledExtract.containsKey(id)) { List tissue = (ArrayList) assay2LabeledExtract.get(id); if (tissue != null) { for (Iterator j = tissue.iterator(); j.hasNext();) { le2Assay.put((String) j.next(), id); } } } } for (Iterator k = labeledExractSet.iterator(); k.hasNext();) { Item leItem = (Item) k.next(); String key = (String) leItem.getIdentifier(); if (le2Assay.containsKey(key)) { String assay = (String) le2Assay.get(key); if (assay != null) { leItem.addReference(new Reference("assay", assay)); results.add(leItem); } } } return results; } /** * set ReporterLocation.design reference, don't need to set * MicroArraySlideDesign.locations explicitly * @return results set */ protected Set processReporterLocs() { Set results = new HashSet(); if (reporterLocs != null && featureToDesign != null && rlToFeature != null) { for (Iterator i = reporterLocs.iterator(); i.hasNext();) { Item rl = (Item) i.next(); String designId = (String) featureToDesign.get(rlToFeature.get(rl.getIdentifier())); Reference designRef = new Reference(); if (designId != null) { designRef.setName("design"); designRef.setRefId(designId); rl.addReference(designRef); results.add(rl); } } } return results; } /** * BioAssayDatum mage:FeatureId -> flymine:MAEResultId (MicroArrayExperimentalResults) * Reporter flymine: BioEntityId -> mage:FeatureId * BioSequece BioEntityId -> BioEntity Item * -> extra Gene Item * @return add microExperimentalResults collection to BioEntity item * and add identifier attribute to BioEntity */ protected Set processBioEntity() { Set results = new HashSet(); Set entitySet = new HashSet(); String s = null; String itemId = null; String identifierAttribute = null; String bioEntityId = null; String anotherId = null; Set identifierSet = new HashSet(); for (Iterator i = bioEntitySet.iterator(); i.hasNext();) { Item bioEntity = (Item) i.next(); bioEntityId = bioEntity.getIdentifier(); //add attribute identifier for bioEntity identifierAttribute = (String) bioEntity2IdentifierMap.get(bioEntityId); if (identifier2BioEntity.containsKey(identifierAttribute)) { Item anotherEntity = (Item) identifier2BioEntity.get(identifierAttribute); anotherId = anotherEntity.getIdentifier(); List synonymList = new ArrayList(); if (anotherEntity.hasCollection("synonyms")) { ReferenceList synonymList1 = anotherEntity.getCollection("synonyms"); for (Iterator k = synonymList1.getRefIds().iterator(); k.hasNext();) { String refId = (String) k.next(); synonymList.add(refId); } } if (bioEntity.hasCollection("synonyms")) { ReferenceList synonymList2 = bioEntity.getCollection("synonyms"); String subject = anotherEntity.getIdentifier(); for (Iterator k = synonymList2.getRefIds().iterator(); k.hasNext();) { String refId = (String) k.next(); if (!synonymList.contains(refId)) { synonymList.add(refId); } //change subjectId for sysnonym when its bioentity is merged Item synonym = (Item) synonymMap.get(refId); String accession = synonym.getAttribute("value").getValue(); synonym.addReference(new Reference("subject", subject)); synonymAccessionMap.put(accession, synonym); } } if (synonymList != null) { anotherEntity.addCollection(new ReferenceList("synonyms", synonymList)); } identifier2BioEntity.put(identifierAttribute, anotherEntity); bioEntityRefMap.put(bioEntityId, anotherId); //modify bioEntity2Feature String mergedFeatures = (String) bioEntity2Feature.get(bioEntityId); String features = (String) bioEntity2Feature.get(anotherId); String newFeatures = null; if (mergedFeatures != null && features != null) { newFeatures = features.concat(" " + mergedFeatures); } else if (mergedFeatures != null && features == null) { newFeatures = mergedFeatures; } else if (mergedFeatures == null && features != null) { newFeatures = features; } if (newFeatures != null) { bioEntity2Feature.remove(bioEntityId); bioEntity2Feature.remove(anotherId); bioEntity2Feature.put(anotherId, newFeatures); } //modify bioEntity2Gene String mergedGene = (String) bioEntity2Gene.get(bioEntityId); String gene = (String) bioEntity2Gene.get(anotherId); String newGenes = null; if (gene != null && mergedGene != null) { newGenes = gene.concat(" " + mergedGene); } else if (gene == null && mergedGene != null) { newGenes = mergedGene; } else if (gene != null && mergedGene == null) { newGenes = gene; } if (newGenes != null) { bioEntity2Gene.remove(bioEntityId); bioEntity2Gene.remove(anotherId); bioEntity2Gene.put(anotherId, newGenes); } } else { bioEntity.addAttribute(new Attribute("identifier", identifierAttribute)); identifier2BioEntity.put(identifierAttribute, bioEntity); identifierSet.add(identifierAttribute); } } for (Iterator i = identifierSet.iterator(); i.hasNext();) { Item bioEntity = (Item) identifier2BioEntity.get((String) i.next()); results.add(bioEntity); if (bioEntity.getClassName().equals(tgtNs + "CDNAClone")) { cdnaSet.add(bioEntity.getIdentifier()); } } for (Iterator i = synonymAccessionMap.keySet().iterator(); i.hasNext();) { Item synonym = (Item) synonymAccessionMap.get((String) i.next()); results.add(synonym); } return results; } /** * BioAssayDatum mage:FeatureId -> flymine:MAEResultId (MicroArrayExperimentalResult) * Reporter flymine: BioEntityId -> mage:FeatureId * BioSequece BioEntityId -> BioEntity Item * -> extra Gene Item * @return add microExperimentalResult collection to Gene item */ protected Set processGene() { Set results = new HashSet(); for (Iterator i = geneMap.keySet().iterator(); i.hasNext();) { String organismDbId = (String) i.next(); Item gene = (Item) geneMap.get(organismDbId); results.add(gene); } return results; } /** * got reporterSet from setBioEntityMap() * refererence material may be changed after processBioEntity2MAEResult() * bioEntity is merged if it has the same identifierAttribute * @return resutls with right material refid */ protected Set processReporterMaterial() { Set results = new HashSet(); for (Iterator i = reporterSet.iterator(); i.hasNext();) { Item reporter = (Item) i.next(); String rl = (String) reporter2rl.get(reporter.getIdentifier()); reporter.addReference(new Reference("location", rl)); if (reporter.hasReference("material")) { String bioEntityId = (String) reporter.getReference("material").getRefId(); if (bioEntityRefMap.containsKey(bioEntityId)) { String newBioEntityId = (String) bioEntityRefMap.get(bioEntityId); reporter.addReference(new Reference("material", newBioEntityId)); } } results.add(reporter); } return results; } /** * got organismMap from createOrganism() * @return organism only once for the same item */ protected Set processOrganism() { Set results = new HashSet(); for (Iterator i = organismMap.keySet().iterator(); i.hasNext();) { String organismValue = (String) i.next(); Item organism = (Item) organismMap.get(organismValue); results.add(organism); } return results; } /** * maer add reference of reporter, material(CDNAClone only), assay(MicroArrayAssay) * add collection of genes and tissues(LabeledExtract) * @return maerItem collections */ protected Set processMaer() { Set results = new HashSet(); maer2Reporter = createMaer2ReporterMap(maer2Feature, reporter2FeatureMap, maerSet); maer2Assay = createMaer2AssayMap(assay2Maer); maer2Tissue = createMaer2TissueMap(maer2Assay, assay2LabeledExtract, maerSet); maer2Material = createMaer2MaterialMap(maer2Feature, bioEntity2Feature, maerSet, cdnaSet); maer2Gene = createMaer2GeneMap(maer2Feature, bioEntity2Feature, bioEntity2Gene, maerSet); for (Iterator i = maerSet.iterator(); i.hasNext(); ) { Item maerItem = (Item) i.next(); String id = maerItem.getIdentifier(); if (maer2Reporter.containsKey(id)) { String reporter = (String) maer2Reporter.get(id); if (reporter != null) { maerItem.addReference(new Reference("reporter", reporter)); } } if (maer2Assay.containsKey(id)) { String assay = (String) maer2Assay.get(id); if (assay != null) { maerItem.addReference(new Reference("assay", assay)); } } if (maer2Tissue.containsKey(id)) { List tissue = (List) maer2Tissue.get(id); if (tissue != null && !tissue.isEmpty()) { maerItem.addCollection(new ReferenceList("tissues", tissue)); } } if (maer2Material.containsKey(id)) { String material = (String) maer2Material.get(id); if (material != null) { maerItem.addReference(new Reference("material", material)); } } if (maer2Gene.containsKey(id)) { String genes = (String) maer2Gene.get(id); if (genes != null) { StringTokenizer st = new StringTokenizer(genes); List l = new ArrayList(); while (st.hasMoreTokens()) { String gene = st.nextToken(); l.add(gene); } maerItem.addCollection(new ReferenceList("genes", l)); } } results.add(maerItem); } return results; } /** * @param maer2Feature = HashMap * @param reporter2FeatureMap = HashMap * @param maerSet = HashSet * @return maer2Reporter */ protected Map createMaer2ReporterMap(Map maer2Feature, Map reporter2FeatureMap, Set maerSet) { Map feature2Reporter = new HashMap(); String features = null; String feature = null; String reporter = null; for (Iterator i = reporter2FeatureMap.keySet().iterator(); i.hasNext(); ) { reporter = (String) i.next(); features = null; feature = null; if (reporter2FeatureMap.containsKey(reporter)) { features = (String) reporter2FeatureMap.get(reporter); if (features != null) { StringTokenizer st = new StringTokenizer(features); while (st.hasMoreTokens()) { feature = (String) st.nextToken(); feature2Reporter.put(feature, reporter); } } } } for (Iterator i = maerSet.iterator(); i.hasNext(); ) { Item maerItem = (Item) i.next(); String maer = maerItem.getIdentifier(); feature = null; reporter = null; if (maer2Feature.containsKey(maer)) { feature = (String) maer2Feature.get(maer); if (feature != null && feature2Reporter.containsKey(feature)) { reporter = (String) feature2Reporter.get(feature); } if (reporter != null) { maer2Reporter.put(maer, reporter); } } } return maer2Reporter; } /** * @param assay2Maer = HashMap * @return maer2Assay */ protected Map createMaer2AssayMap(Map assay2Maer) { for (Iterator i = assay2Maer.keySet().iterator(); i.hasNext(); ) { String assay = (String) i.next(); if (assay2Maer.containsKey(assay)) { List maers = (ArrayList) assay2Maer.get(assay); if (maers != null) { for (Iterator j = maers.iterator(); j.hasNext(); ) { String maer = (String) j.next(); maer2Assay.put(maer, assay); } } } } return maer2Assay; } /** * @param maer2Assay = HashMap * @param assay2LabeledExtract = HashMap * @param maerSet = HashSet * @return maer2Tissue */ protected Map createMaer2TissueMap(Map maer2Assay, Map assay2LabeledExtract, Set maerSet) { for (Iterator i = maerSet.iterator(); i.hasNext(); ) { List le = new ArrayList(); String assay = null; Item maerItem = (Item) i.next(); String maer = maerItem.getIdentifier(); if (maer2Assay.containsKey(maer)) { assay = (String) maer2Assay.get(maer); } if (assay != null) { le = (ArrayList) assay2LabeledExtract.get(assay); } if (le != null) { maer2Tissue.put(maer, le); } } return maer2Tissue; } /** * @param maer2Feature = HashMap * @param bioEntity2Feature = HashMap * @param maerSet = HashSet * @param cdnaSet = HashSet * @return maer2Material */ protected Map createMaer2MaterialMap(Map maer2Feature, Map bioEntity2Feature, Set maerSet, Set cdnaSet) { Map feature2Cdna = new HashMap(); for (Iterator i = cdnaSet.iterator(); i.hasNext(); ) { String cdnaId = (String) i.next(); String feature = null; String features = null; if (bioEntity2Feature.containsKey(cdnaId)) { features = (String) bioEntity2Feature.get(cdnaId); } if (features != null) { StringTokenizer st = new StringTokenizer(features); while (st.hasMoreTokens()) { feature = st.nextToken(); feature2Cdna.put(feature, cdnaId); } } } for (Iterator j = maerSet.iterator(); j.hasNext();) { Item maerItem = (Item) j.next(); String maer = maerItem.getIdentifier(); String feature = null; String material = null; if (maer2Feature.containsKey(maer)) { feature = (String) maer2Feature.get(maer); if (feature != null && feature2Cdna.containsKey(feature)) { material = (String) feature2Cdna.get(feature); } if (material != null) { maer2Material.put(maer, material); } } } return maer2Material; } /** * @param maer2Feature = HashMap * @param bioEntity2Feature = HashMap * @param bioEntity2Gene = HashMap * @param maerSet = HashSet * @return maer2Gene */ protected Map createMaer2GeneMap(Map maer2Feature, Map bioEntity2Feature, Map bioEntity2Gene, Set maerSet) { Map feature2BioEntity = new HashMap(); String bioEntity = null; String genes = null; String feature = null; String features = null; for (Iterator i = bioEntity2Feature.keySet().iterator(); i.hasNext(); ) { String bioEntityId = (String) i.next(); feature = null; features = null; features = (String) bioEntity2Feature.get(bioEntityId); if (features != null) { StringTokenizer st = new StringTokenizer(features); while (st.hasMoreTokens()) { feature = st.nextToken(); feature2BioEntity.put(feature, bioEntityId); } } } for (Iterator j = maerSet.iterator(); j.hasNext(); ) { Item maerItem = (Item) j.next(); String maer = maerItem.getIdentifier(); feature = null; genes = null; bioEntity = null; if (maer2Feature.containsKey(maer)) { feature = (String) maer2Feature.get(maer); } if (feature != null && feature2BioEntity.containsKey(feature)) { bioEntity = (String) feature2BioEntity.get(feature); } if (bioEntity != null && bioEntity2Gene.containsKey(bioEntity)) { genes = (String) bioEntity2Gene.get(bioEntity); } if (genes != null) { maer2Gene.put(maer, genes); } } return maer2Gene; } /** * add experiment reference to MicroArrayAssay * @return assay set */ protected Set processAssay2Experiment() { Set results = new HashSet(); for (Iterator i = assaySet.iterator(); i.hasNext();) { Item assayItem = (Item) i.next(); assayItem.addReference(new Reference("experiment", expItem.getIdentifier())); results.add(assayItem); } return results; } /** * normalised attribute is added during MageConverter * converting BioAssayDatum * true for Derived BioAssayData * false for Measured BioAssayData * removed this attribute before translateItem */ private Item removeNormalisedAttribute(Item item) { Item newItem = new Item(); newItem.setClassName(item.getClassName()); newItem.setIdentifier(item.getIdentifier()); newItem.setImplementations(item.getImplementations()); Iterator i = item.getAttributes().iterator(); while (i.hasNext()) { Attribute attr = (Attribute) i.next(); if (!attr.getName().equals("normalised")) { newItem.addAttribute(attr); } } i = item.getReferences().iterator(); while (i.hasNext()) { newItem.addReference((Reference) i.next()); } i = item.getCollections().iterator(); while (i.hasNext()) { newItem.addCollection((ReferenceList) i.next()); } return newItem; } /** * @param className = tgtClassName * @param implementation = tgtClass implementation * @param identifier = gene item identifier from database item identifier * @param organismDbId = attribute for gene organismDbId * @return gene item */ private Item createGene(String className, String implementation, String identifier, String organismDbId, String bioEntityId) { Item gene = new Item(); if (!geneMap.containsKey(organismDbId)) { gene = createItem(className, implementation); gene.setIdentifier(identifier); gene.addAttribute(new Attribute("organismDbId", organismDbId)); geneMap.put(organismDbId, gene); bioEntity2Gene.put(bioEntityId, identifier); } else { gene = (Item) geneMap.get(organismDbId); } return gene; } /** * @param className = tgtClassName * @param implementation = tgtClass implementation * @param value = attribute for organism name * @return organism item */ private Item createOrganism(String className, String implementation, String value) { Item organism = new Item(); if (!organismMap.containsKey(value)) { organism = createItem(className, implementation); organism.addAttribute(new Attribute("name", value)); organismMap.put(value, organism); } else { organism = (Item) organismMap.get(value); } return organism; } /** * @param dbName = databaseName * @return databaseItem */ private Item getDb(String dbName) { Item db = (Item) dbs.get(dbName); if (db == null) { db = createItem(tgtNs + "Database", ""); Attribute title = new Attribute("title", dbName); db.addAttribute(title); dbs.put(dbName, db); } return db; } /** * @param dbName = databaseName * @return databaseReference */ private Reference getSourceRef(String dbName) { Reference sourceRef = (Reference) dbRefs.get(dbName); if (sourceRef == null) { sourceRef = new Reference("source", getDb(dbName).getIdentifier()); dbRefs.put(dbName, sourceRef); } return sourceRef; } /** * @return identifier for experimentItem assume only one experiment item presented */ private String getAnalysisRef() { if (expItem.getIdentifier() == "") { expItem = createItem(tgtNs + "MicroArrayExperiment", ""); } return expItem.getIdentifier(); } /** * main method * @param args command line arguments * @throws Exception if something goes wrong */ public static void main (String[] args) throws Exception { String srcOsName = args[0]; String tgtOswName = args[1]; String modelName = args[2]; String format = args[3]; String namespace = args[4]; Map paths = new HashMap(); HashSet descSet = new HashSet(); //setReporterLocationCoords ItemPrefetchDescriptor desc1 = new ItemPrefetchDescriptor( "(FeatureGroup <- Feature.featureGroup)"); desc1.addConstraint(new ItemPrefetchConstraintDynamic( ObjectStoreItemPathFollowingImpl.IDENTIFIER, "featureGroup")); desc1.addConstraint(new FieldNameAndValue(ObjectStoreItemPathFollowingImpl.CLASSNAME, "http://www.flymine.org/model/mage#Feature", false)); paths.put("http://www.flymine.org/model/mage#FeatureGroup", Collections.singleton(desc1)); // BioAssayDatum.quantitationType.scale desc1 = new ItemPrefetchDescriptor("BioAssayDatum.quantitationType"); desc1.addConstraint(new ItemPrefetchConstraintDynamic("quantitationType", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); ItemPrefetchDescriptor desc2 = new ItemPrefetchDescriptor( "(BioAssayDatum.quantitationType).scale"); desc2.addConstraint(new ItemPrefetchConstraintDynamic("scale", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); desc1.addPath(desc2); descSet.add(desc1); // BioAssayDatum.quantitationType.targetQuantitationType.scale ItemPrefetchDescriptor desc3 = new ItemPrefetchDescriptor( "(BioAssayDatum.quantitationType).targetQuantitationType"); desc3.addConstraint(new ItemPrefetchConstraintDynamic( "targetQuantitationType", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); ItemPrefetchDescriptor desc4 = new ItemPrefetchDescriptor( "(BioAssayDatum.quantitationType.targetQuantitationType).scale"); desc4.addConstraint(new ItemPrefetchConstraintDynamic("scale", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); desc3.addPath(desc4); desc1.addPath(desc3); descSet.add(desc1); //paths.put("http://www.flymine.org/model/mage#BioAssayDatum",Collections.singleton(desc1)); paths.put("http://www.flymine.org/model/mage#BioAssayDatum", descSet); // BioSequence... descSet = new HashSet(); // BioSequence.type desc1 = new ItemPrefetchDescriptor("BioSequence.type"); desc1.addConstraint(new ItemPrefetchConstraintDynamic("type", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); descSet.add(desc1); // BioSequence.sequenceDatabases.databaseEntry.database desc1 = new ItemPrefetchDescriptor("BioSequence.sequenceDatabases"); desc1.addConstraint(new ItemPrefetchConstraintDynamic("sequenceDatabases", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); desc2 = new ItemPrefetchDescriptor("(BioSequence.sequenceDatabases).databaseEntry"); desc2.addConstraint(new ItemPrefetchConstraintDynamic("databaseEntry", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); desc3 = new ItemPrefetchDescriptor( "((BioSequence.sequenceDatabases).databaseEntry).database"); desc3.addConstraint(new ItemPrefetchConstraintDynamic("database", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); desc2.addPath(desc3); desc1.addPath(desc2); descSet.add(desc1); paths.put("http://www.flymine.org/model/mage#BioSequence", descSet); // LabeledExtract... descSet = new HashSet(); // LabeledExtract.materialType desc1 = new ItemPrefetchDescriptor("LabeledExtract.materialType"); desc1.addConstraint(new ItemPrefetchConstraintDynamic("materialType", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); descSet.add(desc1); // LabeledExtract.labels desc1 = new ItemPrefetchDescriptor("LabeledExtract.labels"); desc1.addConstraint(new ItemPrefetchConstraintDynamic("labels", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); descSet.add(desc1); // code descends through treatments in a loop - prefetch can't handle // that so need to define cutoff (??) // LabeledExtract.treatments.sourceBioMaterialMeasurements.bioMaterial.treatments // .sourceBioMaterialMeasurements.bioMaterial.treatments desc1 = new ItemPrefetchDescriptor("LabeledExtract.treatments"); desc1.addConstraint(new ItemPrefetchConstraintDynamic("treatments", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); desc2 = new ItemPrefetchDescriptor( "(LabeledExtract.treatments).sourceBioMaterialMeasurements"); desc2.addConstraint(new ItemPrefetchConstraintDynamic("bioMaterialMeasurements", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); desc3 = new ItemPrefetchDescriptor( "((LabeledExtract.treatments).sourceBioMaterialMeasurements).bioMaterial"); desc3.addConstraint(new ItemPrefetchConstraintDynamic("bioMaterial", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); desc4 = new ItemPrefetchDescriptor( "(((LabeledExtract.treatments).sourceBioMaterialMeasurements).bioMaterial).treatments"); desc4.addConstraint(new ItemPrefetchConstraintDynamic("treatments", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); ItemPrefetchDescriptor desc5 = new ItemPrefetchDescriptor( "(...).sourceBioMaterialMeasurements"); desc5.addConstraint(new ItemPrefetchConstraintDynamic("sourceBioMaterialMeasurements", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); ItemPrefetchDescriptor desc6 = new ItemPrefetchDescriptor( "((...).sourceBioMaterialMeasurements).bioMaterial"); desc6.addConstraint(new ItemPrefetchConstraintDynamic("bioMaterial", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); ItemPrefetchDescriptor desc7 = new ItemPrefetchDescriptor( "(((...).sourceBioMaterialMeasurements).bioMaterial).treatments"); desc7.addConstraint(new ItemPrefetchConstraintDynamic("treatments", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); desc6.addPath(desc7); desc5.addPath(desc6); desc4.addPath(desc5); desc3.addPath(desc4); desc2.addPath(desc3); desc1.addPath(desc2); descSet.add(desc1); paths.put("http://www.flymine.org/model/mage#LabeledExtract", descSet); // BioSource... descSet = new HashSet(); // BioSource.materialType desc1 = new ItemPrefetchDescriptor("BioSource.materialType"); desc1.addConstraint(new ItemPrefetchConstraintDynamic("materialType", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); descSet.add(desc1); // BioSource.characteristics desc1 = new ItemPrefetchDescriptor("BioSource.characteristics"); desc1.addConstraint(new ItemPrefetchConstraintDynamic("characteristics", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); descSet.add(desc1); paths.put("http://www.flymine.org/model/mage#BioSource", descSet); // Treatment.action desc1 = new ItemPrefetchDescriptor("Treatment.action"); desc1.addConstraint(new ItemPrefetchConstraintDynamic( ObjectStoreItemPathFollowingImpl.IDENTIFIER, "action")); paths.put("http://www.flymine.org/model/mage#Treatment", Collections.singleton(desc1)); // new prefetch with collections // FeatureReporterMap->featureInformationSources->feature->featureLocation descSet = new HashSet(); desc1 = new ItemPrefetchDescriptor("FeatureReporterMap.featureInformaionSources"); desc1.addConstraint(new ItemPrefetchConstraintDynamic("featureInformationSources", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); desc2 = new ItemPrefetchDescriptor( "(FeatureReporterMap.featureInformaionSources).feature"); desc2.addConstraint(new ItemPrefetchConstraintDynamic("feature", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); desc3 = new ItemPrefetchDescriptor( "((FeatureReporterMap.featureInformaionSources).feature).featureLocation"); desc3.addConstraint(new ItemPrefetchConstraintDynamic("featureLocation", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); desc1.addPath(desc2); desc2.addPath(desc3); //descSet.add(desc1); required? // FeatureReporterMap->featureInformationSources->feature->zone desc4 = new ItemPrefetchDescriptor( "((FeatureReporterMap.featureInformaionSources).feature).zone"); desc4.addConstraint(new ItemPrefetchConstraintDynamic("zone", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); desc2.addPath(desc4); descSet.add(desc1); paths.put("http://www.flymine.org/model/mage#FeatureReporterMap", descSet); // PhysicalArrayDesign... descSet = new HashSet(); // PhysicalArrayDesign->featureGroups desc1 = new ItemPrefetchDescriptor("PhysicalArrayDesign.featureGroups"); desc1.addConstraint(new ItemPrefetchConstraintDynamic("featureGroups", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); descSet.add(desc1); // PhysicalArrayDesign->surfaceType desc1 = new ItemPrefetchDescriptor("PhysicalArrayDesign.surfaceType"); desc1.addConstraint(new ItemPrefetchConstraintDynamic("surfaceType", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); descSet.add(desc1); // PhysicalArrayDesign->descriptions desc1 = new ItemPrefetchDescriptor("PhysicalArrayDesign.descriptions"); desc1.addConstraint(new ItemPrefetchConstraintDynamic("descripions", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); descSet.add(desc1); paths.put("http://www.flymine.org/model/mage#PhysicalArrayDesign", descSet); // Reporter... descSet = new HashSet(); // Reporter <- FeatureReporterMap.reporter desc1 = new ItemPrefetchDescriptor("(Reporter <- FeatureReporterMap.reporter)"); desc1.addConstraint(new ItemPrefetchConstraintDynamic( ObjectStoreItemPathFollowingImpl.IDENTIFIER, "reporter")); desc1.addConstraint(new FieldNameAndValue(ObjectStoreItemPathFollowingImpl.CLASSNAME, "http://www.flymine.org/model/mage#FeatureReporterMap", false)); descSet.add(desc1); // Reporter->failTypes desc1 = new ItemPrefetchDescriptor("Reporter.failTypes"); desc1.addConstraint(new ItemPrefetchConstraintDynamic("failTypes", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); descSet.add(desc1); // Reporter->controlType desc1 = new ItemPrefetchDescriptor("Reporter.controlType"); desc1.addConstraint(new ItemPrefetchConstraintDynamic("controlType", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); descSet.add(desc1); // Reporter->immobilizedCharacteristics->type desc1 = new ItemPrefetchDescriptor("Reporter.immobilizedCharacteristics"); desc1.addConstraint(new ItemPrefetchConstraintDynamic("immobilizedCharacteristics", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); desc2 = new ItemPrefetchDescriptor( "(Reporter.immobilizedCharacteristics).type"); desc2.addConstraint(new ItemPrefetchConstraintDynamic("type", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); desc1.addPath(desc2); descSet.add(desc1); // Reporter->descriptions desc1 = new ItemPrefetchDescriptor("Reporter.descriptions"); desc1.addConstraint(new ItemPrefetchConstraintDynamic("descriptions", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); descSet.add(desc1); // Reporter->featureReporterMaps->featureInformationSources desc1 = new ItemPrefetchDescriptor("Reporter.featureReporterMaps"); desc1.addConstraint(new ItemPrefetchConstraintDynamic("featureReporterMaps", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); desc2 = new ItemPrefetchDescriptor( "(Reporter.featureReporterMaps).featureInformationSources"); desc2.addConstraint(new ItemPrefetchConstraintDynamic("featureInformationSources", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); desc1.addPath(desc2); descSet.add(desc1); paths.put("http://www.flymine.org/model/mage#Reporter", descSet); // Experiment... descSet = new HashSet(); // Experiment->bioAssays desc1 = new ItemPrefetchDescriptor("Experiment.bioAssays"); desc1.addConstraint(new ItemPrefetchConstraintDynamic("bioAssays", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); descSet.add(desc1); // Experiment->bioAssays.physicalBioAssay->Hybridization desc2 = new ItemPrefetchDescriptor( "(Experiment.bioAssays:physicalBioAssay).bioAssayCreation"); desc2.addConstraint(new ItemPrefetchConstraintDynamic("bioAssayCreation", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); desc1.addPath(desc2); // Experiment->bioAssays.physicalBioAssay->Hybridization.sourceBioMaterialMeasurements desc3 = new ItemPrefetchDescriptor( "(Experiment.bioAssays:physicalBioAssay.bioAssayCreation).sourceBioMaterialMeasurements"); desc3.addConstraint(new ItemPrefetchConstraintDynamic("sourceBioMaterialMeasurements", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); desc2.addPath(desc3); descSet.add(desc1); // Experiment.descriptions desc1 = new ItemPrefetchDescriptor("Experiment.descriptions"); desc1.addConstraint(new ItemPrefetchConstraintDynamic("descriptions", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); descSet.add(desc1); paths.put("http://www.flymine.org/model/mage#Experiment", descSet); // DerivedBioAssay.derivedBioAssayData.bioDataValues. desc1 = new ItemPrefetchDescriptor("DerivedBioAssay.derivedBioAssayData"); desc1.addConstraint(new ItemPrefetchConstraintDynamic("derivedBioAssayData", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); desc2 = new ItemPrefetchDescriptor( "(DerivedBioAssay.derivedBioAssayData).bioDataValues"); desc2.addConstraint(new ItemPrefetchConstraintDynamic("bioDataValues", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); desc1.addPath(desc2); descSet.add(desc1); paths.put("http://www.flymine.org/model/mage#DerivedBioAssay", Collections.singleton(desc1)); ObjectStore osSrc = ObjectStoreFactory.getObjectStore(srcOsName); ItemReader srcItemReader = new ObjectStoreItemReader(osSrc, paths); ObjectStoreWriter oswTgt = ObjectStoreWriterFactory.getObjectStoreWriter(tgtOswName); ItemWriter tgtItemWriter = new ObjectStoreItemWriter(oswTgt); OntModel model = ModelFactory.createOntologyModel(); model.read(new FileReader(new File(modelName)), null, format); DataTranslator dt = new MageDataTranslator(srcItemReader, model, namespace); model = null; dt.translate(tgtItemWriter); tgtItemWriter.close(); } }
flymine/model/mage/src/java/org/flymine/dataconversion/MageDataTranslator.java
package org.flymine.dataconversion; /* * Copyright (C) 2002-2004 FlyMine * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. See the LICENSE file for more * information or http://www.gnu.org/copyleft/lesser.html. * */ import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.Set; import java.util.HashSet; import java.util.Map; import java.util.HashMap; import java.util.List; import java.util.ArrayList; import java.util.StringTokenizer; import java.io.File; import java.io.FileReader; import com.hp.hpl.jena.ontology.OntModel; import com.hp.hpl.jena.rdf.model.ModelFactory; import org.intermine.InterMineException; import org.intermine.util.XmlUtil; import org.intermine.xml.full.Attribute; import org.intermine.xml.full.Item; import org.intermine.xml.full.Reference; import org.intermine.xml.full.ReferenceList; import org.intermine.xml.full.ItemHelper; import org.intermine.objectstore.ObjectStoreException; import org.intermine.objectstore.ObjectStore; import org.intermine.objectstore.ObjectStoreFactory; import org.intermine.objectstore.ObjectStoreWriter; import org.intermine.objectstore.ObjectStoreWriterFactory; import org.intermine.dataconversion.ItemReader; import org.intermine.dataconversion.ObjectStoreItemReader; import org.intermine.dataconversion.ItemWriter; import org.intermine.dataconversion.ObjectStoreItemWriter; import org.intermine.dataconversion.ObjectStoreItemPathFollowingImpl; import org.intermine.dataconversion.DataTranslator; import org.intermine.dataconversion.ItemPrefetchDescriptor; import org.intermine.dataconversion.ItemPrefetchConstraintDynamic; import org.intermine.dataconversion.FieldNameAndValue; import org.apache.log4j.Logger; /** * Convert MAGE data in fulldata Item format conforming to a source OWL definition * to fulldata Item format conforming to InterMine OWL definition. * * @author Wenyan Ji * @author Richard Smith */ public class MageDataTranslator extends DataTranslator { protected static final Logger LOG = Logger.getLogger(MageDataTranslator.class); // flymine:ReporterLocation id -> flymine:Feature id protected Map rlToFeature = new HashMap(); // mage:Feature id -> flymine:MicroArraySlideDesign id protected Map featureToDesign = new HashMap(); // hold on to ReporterLocation items until end protected Set reporterLocs = new HashSet(); protected Map bioEntity2Gene = new HashMap(); //mage: Feature id -> flymine:MicroArrayExperimentResult id when processing BioAssayDatum protected Map maer2Feature = new HashMap(); protected Set maerSet = new HashSet(); //maerItem //flymine: BioEntity id -> mage:Feature id when processing Reporter protected Map bioEntity2Feature = new HashMap(); protected Map bioEntity2IdentifierMap = new HashMap(); protected Set bioEntitySet = new HashSet(); protected Map synonymMap = new HashMap(); //key:itemId value:synonymItem protected Map synonymAccessionMap = new HashMap();//key:accession value:synonymItem // reporterSet:Flymine reporter. reporter:material -> bioEntity may probably merged when //it has same identifier. need to reprocess reporterMaterial protected Set reporterSet = new HashSet(); protected Map bioEntityRefMap = new HashMap(); protected Map identifier2BioEntity = new HashMap(); protected Map treatment2BioSourceMap = new HashMap(); protected Set bioSource = new HashSet(); protected Map organismMap = new HashMap(); private Map dbs = new HashMap(); private Map dbRefs = new HashMap(); private Item expItem = new Item();//assume only one experiment item presented protected Map reporter2FeatureMap = new HashMap(); protected Map assay2Maer = new HashMap(); protected Map assay2LabeledExtract = new HashMap(); protected Map maer2Reporter = new HashMap(); protected Map maer2Assay = new HashMap(); protected Map maer2Tissue = new HashMap(); protected Map maer2Material = new HashMap(); protected Map maer2Gene = new HashMap(); protected Set cdnaSet = new HashSet(); protected Map geneMap = new HashMap(); //organisamDbId, geneItem protected Set assaySet = new HashSet(); /** * @see DataTranslator#DataTranslator */ public MageDataTranslator(ItemReader srcItemReader, OntModel model, String ns) { super(srcItemReader, model, ns); } /** * @see DataTranslator#translate */ public void translate(ItemWriter tgtItemWriter) throws ObjectStoreException, InterMineException { super.translate(tgtItemWriter); Iterator i = processReporterLocs().iterator(); while (i.hasNext()) { tgtItemWriter.store(ItemHelper.convert((Item) i.next())); } i = processBioEntity().iterator(); while (i.hasNext()) { tgtItemWriter.store(ItemHelper.convert((Item) i.next())); } i = processGene().iterator(); while (i.hasNext()) { tgtItemWriter.store(ItemHelper.convert((Item) i.next())); } i = processReporterMaterial().iterator(); while (i.hasNext()) { tgtItemWriter.store(ItemHelper.convert((Item) i.next())); } i = processBioSourceTreatment().iterator(); while (i.hasNext()) { tgtItemWriter.store(ItemHelper.convert((Item) i.next())); } i = processAssayTissue().iterator(); while (i.hasNext()) { tgtItemWriter.store(ItemHelper.convert((Item) i.next())); } i = processOrganism().iterator(); while (i.hasNext()) { tgtItemWriter.store(ItemHelper.convert((Item) i.next())); } i = dbs.values().iterator(); while (i.hasNext()) { tgtItemWriter.store(ItemHelper.convert((Item) i.next())); } i = processMaer().iterator(); while (i.hasNext()) { tgtItemWriter.store(ItemHelper.convert((Item) i.next())); } } /** * @see DataTranslator#translateItem */ protected Collection translateItem(Item srcItem) throws ObjectStoreException, InterMineException { Collection result = new HashSet(); String normalised = null; String srcNs = XmlUtil.getNamespaceFromURI(srcItem.getClassName()); String className = XmlUtil.getFragmentFromURI(srcItem.getClassName()); if (className.equals("BioAssayDatum")) { normalised = srcItem.getAttribute("normalised").getValue(); srcItem = removeNormalisedAttribute(srcItem); } Collection translated = super.translateItem(srcItem); Item gene = new Item(); Item organism = new Item(); if (translated != null) { for (Iterator i = translated.iterator(); i.hasNext();) { boolean storeTgtItem = true; Item tgtItem = (Item) i.next(); // mage: BibliographicReference flymine:Publication if (className.equals("BibliographicReference")) { Set authors = createAuthors(srcItem); List authorIds = new ArrayList(); Iterator j = authors.iterator(); while (j.hasNext()) { Item author = (Item) j.next(); authorIds.add(author.getIdentifier()); result.add(author); } ReferenceList authorsRef = new ReferenceList("authors", authorIds); tgtItem.addCollection(authorsRef); } else if (className.equals("Database")) { Attribute attr = srcItem.getAttribute("name"); if (attr != null) { getDb(attr.getValue()); } storeTgtItem = false; } else if (className.equals("FeatureReporterMap")) { setReporterLocationCoords(srcItem, tgtItem); storeTgtItem = false; } else if (className.equals("PhysicalArrayDesign")) { createFeatureMap(srcItem); translateMicroArraySlideDesign(srcItem, tgtItem); } else if (className.equals("Experiment")) { // collection bioassays includes MeasuredBioAssay, PhysicalBioAssay // and DerivedBioAssay, only keep DerivedBioAssay //keepDBA(srcItem, tgtItem, srcNs); expItem = translateMicroArrayExperiment(srcItem, tgtItem, srcNs); result.add(expItem); storeTgtItem = false; } else if (className.equals("DerivedBioAssay")) { translateMicroArrayAssay(srcItem, tgtItem); storeTgtItem = false; } else if (className.equals("BioAssayDatum")) { translateMicroArrayExperimentalResult(srcItem, tgtItem, normalised); storeTgtItem = false; } else if (className.equals("Reporter")) { setBioEntityMap(srcItem, tgtItem); storeTgtItem = false; } else if (className.equals("BioSequence")) { translateBioEntity(srcItem, tgtItem); storeTgtItem = false; } else if (className.equals("LabeledExtract")) { translateLabeledExtract(srcItem, tgtItem); } else if (className.equals("BioSource")) { translateSample(srcItem, tgtItem); storeTgtItem = false; } else if (className.equals("Treatment")) { translateTreatment(srcItem, tgtItem); } if (storeTgtItem) { result.add(tgtItem); } } } return result; } /** * @param srcItem = mage:BibliographicReference * @return author set */ protected Set createAuthors(Item srcItem) { Set result = new HashSet(); if (srcItem.hasAttribute("authors")) { Attribute authorsAttr = srcItem.getAttribute("authors"); if (authorsAttr != null) { String authorStr = authorsAttr.getValue(); StringTokenizer st = new StringTokenizer(authorStr, ";"); while (st.hasMoreTokens()) { String name = st.nextToken().trim(); Item author = createItem(tgtNs + "Author", ""); author.addAttribute(new Attribute("name", name)); result.add(author); } } } return result; } /** * @param srcItem = mage: FeatureReporterMap * @param tgtItem = flymine: ReporterLocation * @throws ObjectStoreException if problem occured during translating */ protected void setReporterLocationCoords(Item srcItem, Item tgtItem) throws ObjectStoreException { if (srcItem.hasCollection("featureInformationSources")) { ReferenceList featureInfos = srcItem.getCollection("featureInformationSources"); if (!isSingleElementCollection(featureInfos)) { LOG.error("FeatureReporterMap (" + srcItem.getIdentifier() + ") does not have single element collection" + featureInfos.getRefIds().toString()); // throw new IllegalArgumentException("FeatureReporterMap (" // + srcItem.getIdentifier() // + " has more than one featureInformationSource"); } //FeatureInformationSources->FeatureInformation->Feature->FeatureLocation // prefetch done Item featureInfo = ItemHelper.convert(srcItemReader .getItemById(getFirstId(featureInfos))); if (featureInfo.hasReference("feature")) { Item feature = ItemHelper.convert(srcItemReader .getItemById(featureInfo.getReference("feature").getRefId())); if (feature.hasReference("featureLocation")) { Item featureLoc = ItemHelper.convert(srcItemReader .getItemById(feature.getReference("featureLocation").getRefId())); if (featureLoc != null) { tgtItem.addAttribute(new Attribute("localX", featureLoc.getAttribute("column").getValue())); tgtItem.addAttribute(new Attribute("localY", featureLoc.getAttribute("row").getValue())); } } if (feature.hasReference("zone")) { Item zone = ItemHelper.convert(srcItemReader .getItemById(feature.getReference("zone").getRefId())); if (zone != null) { tgtItem.addAttribute(new Attribute("zoneX", zone.getAttribute("column").getValue())); tgtItem.addAttribute(new Attribute("zoneY", zone.getAttribute("row").getValue())); } } reporterLocs.add(tgtItem); rlToFeature.put(tgtItem.getIdentifier(), feature.getIdentifier()); } } else { LOG.error("FeatureReporterMap (" + srcItem.getIdentifier() + ") does not have featureInformationSource"); // throw new IllegalArgumentException("FeatureReporterMap (" // + srcItem.getIdentifier() // + " does not have featureInformationSource"); } } /** * @param srcItem = mage:PhysicalArrayDesign * @throws ObjectStoreException if problem occured during translating */ protected void createFeatureMap(Item srcItem) throws ObjectStoreException { if (srcItem.hasCollection("featureGroups")) { ReferenceList featureGroups = srcItem.getCollection("featureGroups"); if (featureGroups == null || !isSingleElementCollection(featureGroups)) { throw new IllegalArgumentException("PhysicalArrayDesign (" + srcItem.getIdentifier() + ") does not have exactly one featureGroup"); } // prefetch done Item featureGroup = ItemHelper.convert(srcItemReader .getItemById(getFirstId(featureGroups))); Iterator featureIter = featureGroup.getCollection("features").getRefIds().iterator(); while (featureIter.hasNext()) { featureToDesign.put((String) featureIter.next(), srcItem.getIdentifier()); } } } /** * @param srcItem = mage:Reporter * @param tgtItem = flymine:Reporter * set BioEntity2FeatureMap when translating Reporter * set BioEntity2IdentifierMap when translating Reporter * @throws ObjectStoreException if errors occured during translating */ protected void setBioEntityMap(Item srcItem, Item tgtItem) throws ObjectStoreException { StringBuffer sb = new StringBuffer(); boolean controlFlg = false; ReferenceList failTypes = new ReferenceList(); //prefetch done if (srcItem.hasCollection("failTypes")) { failTypes = srcItem.getCollection("failTypes"); if (failTypes != null) { for (Iterator l = srcItem.getCollection("failTypes").getRefIds().iterator(); l.hasNext();) { Item ontoItem = ItemHelper.convert(srcItemReader.getItemById( (String) l.next())); sb.append(ontoItem.getAttribute("value").getValue() + " "); } tgtItem.addAttribute(new Attribute("failType", sb.toString())); } } //prefetch done if (srcItem.hasReference("controlType")) { Reference controlType = srcItem.getReference("controlType"); if (controlType != null) { Item controlItem = ItemHelper.convert(srcItemReader.getItemById( (String) srcItem.getReference("controlType").getRefId())); if (controlItem.getAttribute("value").getValue().equals("control_buffer")) { controlFlg = true; } } } ReferenceList featureReporterMaps = srcItem.getCollection("featureReporterMaps"); ReferenceList immobilizedChar = srcItem.getCollection("immobilizedCharacteristics"); sb = new StringBuffer(); String identifier = null; if (immobilizedChar == null) { if (failTypes != null) { //throw new IllegalArgumentException( LOG.info("Reporter (" + srcItem.getIdentifier() + ") does not have immobilizedCharacteristics because it fails"); } else if (controlFlg) { LOG.info("Reporter (" + srcItem.getIdentifier() + ") does not have immobilizedCharacteristics because" + " it is a control_buffer"); } else { throw new IllegalArgumentException("Reporter (" + srcItem.getIdentifier() + ") does not have immobilizedCharacteristics"); } } else if (!isSingleElementCollection(immobilizedChar)) { throw new IllegalArgumentException("Reporter (" + srcItem.getIdentifier() + ") have more than one immobilizedCharacteristics"); } else { //create bioEntity2IdentifierMap //identifier = reporter: name for CDNAClone, Vector //identifier = reporter: controlType;name;descriptions for genomic_dna //prefetch done identifier = getFirstId(immobilizedChar); String identifierAttribute = null; Item bioSequence = ItemHelper.convert(srcItemReader.getItemById(identifier)); if (bioSequence.hasReference("type")) { Item oeItem = ItemHelper.convert(srcItemReader.getItemById( (String) bioSequence.getReference("type").getRefId())); if (oeItem.getAttribute("value").getValue().equals("genomic_DNA")) { sb = new StringBuffer(); if (srcItem.hasReference("controlType")) { Item controlItem = ItemHelper.convert(srcItemReader.getItemById((String) srcItem.getReference("controlType").getRefId())); if (controlItem.hasAttribute("value")) { sb.append(controlItem.getAttribute("value").getValue() + ";"); } } if (srcItem.hasAttribute("name")) { sb.append(srcItem.getAttribute("name").getValue() + ";"); } if (srcItem.hasCollection("descriptions")) { for (Iterator k = srcItem.getCollection( "descriptions").getRefIds().iterator(); k.hasNext();) { Item description = ItemHelper.convert(srcItemReader.getItemById( (String) k.next())); if (description.hasAttribute("text")) { sb.append(description.getAttribute("text").getValue() + ";"); } } } if (sb.length() > 1) { identifierAttribute = sb.substring(0, sb.length() - 1); bioEntity2IdentifierMap.put(identifier, identifierAttribute); } } else { sb = new StringBuffer(); if (srcItem.hasAttribute("name")) { sb.append(srcItem.getAttribute("name").getValue()); identifierAttribute = sb.toString(); bioEntity2IdentifierMap.put(identifier, identifierAttribute); } } } //create bioEntity2FeatureMap sb = new StringBuffer(); if (featureReporterMaps != null) { for (Iterator i = featureReporterMaps.getRefIds().iterator(); i.hasNext(); ) { //FeatureReporterMap //desc2 String s = (String) i.next(); Item frm = ItemHelper.convert(srcItemReader.getItemById(s)); if (frm.hasCollection("featureInformationSources")) { Iterator j = frm.getCollection("featureInformationSources"). getRefIds().iterator(); // prefetch done while (j.hasNext()) { Item fis = ItemHelper.convert(srcItemReader.getItemById( (String) j.next())); if (fis.hasReference("feature")) { sb.append(fis.getReference("feature").getRefId() + " "); } } } } if (sb.length() > 1) { String feature = sb.substring(0, sb.length() - 1); bioEntity2Feature.put(identifier, feature); reporter2FeatureMap.put(srcItem.getIdentifier(), feature); } LOG.debug("bioEntity2Feature" + bioEntity2Feature.toString()); tgtItem.addReference(new Reference("material", identifier)); } } reporterSet.add(tgtItem); } /** * @param srcItem = mage:PhysicalArrayDesign * @param tgtItem = flymine:MicroArraySlideDesign * @throws ObjectStoreException if problem occured during translating */ protected void translateMicroArraySlideDesign(Item srcItem, Item tgtItem) throws ObjectStoreException { // move descriptions reference list //prefetch done if (srcItem.hasCollection("descriptions")) { ReferenceList des = srcItem.getCollection("descriptions"); if (des != null) { for (Iterator i = des.getRefIds().iterator(); i.hasNext(); ) { Item anno = ItemHelper.convert(srcItemReader.getItemById((String) i.next())); if (anno != null) { promoteCollection(srcItem, "descriptions", "annotations", tgtItem, "descriptions"); } } } } // change substrateType reference to attribute //prefetch done if (srcItem.hasReference("surfaceType")) { Item surfaceType = ItemHelper.convert(srcItemReader .getItemById(srcItem.getReference("surfaceType").getRefId())); if (surfaceType.hasAttribute("value")) { tgtItem.addAttribute(new Attribute("surfaceType", surfaceType.getAttribute("value").getValue())); } } if (srcItem.hasAttribute("version")) { tgtItem.addAttribute(new Attribute("version", srcItem.getAttribute("version").getValue())); } if (srcItem.hasAttribute("name")) { tgtItem.addAttribute(new Attribute("name", srcItem.getAttribute("name").getValue())); } } /** * @param srcItem = mage:Experiment * @param tgtItem = flymine: MicroArrayExperiment * @param srcNs = mage: src namespace * @return experiment Item * also created a HashMap assay2LabeledExtract * @throws ObjectStoreException if problem occured during translating */ protected Item translateMicroArrayExperiment(Item srcItem, Item tgtItem, String srcNs) throws ObjectStoreException { String derived = null; String physical = null; // prefetch done if (srcItem.hasCollection("bioAssays")) { ReferenceList rl = srcItem.getCollection("bioAssays"); ReferenceList newRl = new ReferenceList(); newRl.setName("assays"); for (Iterator i = rl.getRefIds().iterator(); i.hasNext(); ) { Item baItem = ItemHelper.convert(srcItemReader.getItemById((String) i.next())); if (baItem.getClassName().equals(srcNs + "DerivedBioAssay")) { derived = baItem.getIdentifier(); newRl.addRefId(derived); } if (baItem.getClassName().equals(srcNs + "PhysicalBioAssay")) { physical = baItem.getIdentifier(); } } tgtItem.addCollection(newRl); } //prefetch? List labeledExtract = new ArrayList(); if (physical != null && derived != null) { Item pbaItem = ItemHelper.convert(srcItemReader.getItemById(physical)); if (pbaItem.hasReference("bioAssayCreation")) { Item hybri = ItemHelper.convert(srcItemReader.getItemById( pbaItem.getReference("bioAssayCreation").getRefId())); if (hybri.hasCollection("sourceBioMaterialMeasurements")) { ReferenceList sbmm = hybri.getCollection("sourceBioMaterialMeasurements"); for (Iterator i = sbmm.getRefIds().iterator(); i.hasNext(); ) { Item bmm = ItemHelper.convert(srcItemReader.getItemById((String) i.next())); if (bmm.hasReference("bioMaterial")) { labeledExtract.add(bmm.getReference("bioMaterial").getRefId()); } } } } if (labeledExtract != null) { assay2LabeledExtract.put(derived, labeledExtract); } } if (srcItem.hasAttribute("name")) { tgtItem.addAttribute(new Attribute("name", srcItem.getAttribute("name").getValue())); } // prefetch done if (srcItem.hasCollection("descriptions")) { ReferenceList desRl = srcItem.getCollection("descriptions"); boolean desFlag = false; boolean pubFlag = false; for (Iterator i = desRl.getRefIds().iterator(); i.hasNext(); ) { Item desItem = ItemHelper.convert(srcItemReader.getItemById((String) i.next())); if (desItem.hasAttribute("text")) { if (desFlag) { LOG.error("Already set description for MicroArrayExperiment, " + " srcItem = " + srcItem.getIdentifier()); } else { tgtItem.addAttribute(new Attribute("description", desItem.getAttribute("text").getValue())); desFlag = true; } } if (desItem.hasCollection("bibliographicReferences")) { ReferenceList publication = desItem.getCollection( "bibliographicReferences"); if (publication != null) { if (!isSingleElementCollection(publication)) { throw new IllegalArgumentException("Experiment description collection (" + desItem.getIdentifier() + ") has more than one bibliographicReferences"); } else { if (pubFlag) { LOG.error("Already set publication for MicroArrayExperiment, " + " srcItem = " + srcItem.getIdentifier()); } else { tgtItem.addReference(new Reference("publication", getFirstId(publication))); pubFlag = true; } } } } } } if (expItem.getIdentifier() != "") { tgtItem.setIdentifier(expItem.getIdentifier()); } return tgtItem; } /** * @param srcItem = mage: DerivedBioAssay * @param tgtItem = flymine:MicroArrayAssay * @throws ObjectStoreException if problem occured during translating */ protected void translateMicroArrayAssay(Item srcItem, Item tgtItem) throws ObjectStoreException { if (srcItem.hasCollection("derivedBioAssayData")) { ReferenceList dbad = srcItem.getCollection("derivedBioAssayData"); List resultsRl = new ArrayList(); for (Iterator j = dbad.getRefIds().iterator(); j.hasNext(); ) { // prefetch done Item dbadItem = ItemHelper.convert(srcItemReader.getItemById((String) j.next())); if (dbadItem.hasReference("bioDataValues")) { Item bioDataTuples = ItemHelper.convert(srcItemReader.getItemById( dbadItem.getReference("bioDataValues").getRefId())); if (bioDataTuples.hasCollection("bioAssayTupleData")) { ReferenceList rl = bioDataTuples.getCollection("bioAssayTupleData"); for (Iterator i = rl.getRefIds().iterator(); i.hasNext(); ) { String ref = (String) i.next(); if (!resultsRl.contains(ref)) { resultsRl.add(ref); } } } } } //tgtItem.addCollection(new ReferenceList("results", resultsRl)); if (resultsRl != null) { assay2Maer.put(srcItem.getIdentifier(), resultsRl); assaySet.add(tgtItem); } } } /** * @param srcItem = mage:BioAssayDatum * @param tgtItem = flymine:MicroArrayExperimentalResult * @param normalised is defined in translateItem * @throws ObjectStoreException if problem occured during translating */ public void translateMicroArrayExperimentalResult(Item srcItem, Item tgtItem, String normalised) throws ObjectStoreException { tgtItem.addAttribute(new Attribute("normalised", normalised)); if (srcItem.hasAttribute("value")) { tgtItem.addAttribute(new Attribute("value", srcItem.getAttribute("value").getValue())); } tgtItem.addReference(new Reference("analysis", getAnalysisRef())); //create maer2Feature map, and maer set if (srcItem.hasReference("designElement")) { maer2Feature.put(tgtItem.getIdentifier(), srcItem.getReference("designElement").getRefId()); //maerSet.add(tgtItem.getIdentifier()); } //prefetch done if (srcItem.hasReference("quantitationType")) { Item qtItem = ItemHelper.convert(srcItemReader.getItemById( srcItem.getReference("quantitationType").getRefId())); if (qtItem.getClassName().endsWith("MeasuredSignal") || qtItem.getClassName().endsWith("Ratio")) { if (qtItem.hasAttribute("name")) { tgtItem.addAttribute(new Attribute("type", qtItem.getAttribute("name").getValue())); } else { LOG.error("srcItem ( " + qtItem.getIdentifier() + " ) does not have name attribute"); } if (qtItem.hasReference("scale")) { Item oeItem = ItemHelper.convert(srcItemReader.getItemById( qtItem.getReference("scale").getRefId())); tgtItem.addAttribute(new Attribute("scale", oeItem.getAttribute("value").getValue())); } else { LOG.error("srcItem (" + qtItem.getIdentifier() + "( does not have scale attribute "); } if (qtItem.hasAttribute("isBackground")) { tgtItem.addAttribute(new Attribute("isBackground", qtItem.getAttribute("isBackground").getValue())); } else { LOG.error("srcItem (" + qtItem.getIdentifier() + "( does not have scale reference "); } } else if (qtItem.getClassName().endsWith("Error")) { if (qtItem.hasAttribute("name")) { tgtItem.addAttribute(new Attribute("type", qtItem.getAttribute("name").getValue())); } else { LOG.error("srcItem ( " + qtItem.getIdentifier() + " ) does not have name attribute"); } if (qtItem.hasReference("targetQuantitationType")) { Item msItem = ItemHelper.convert(srcItemReader.getItemById( qtItem.getReference("targetQuantitationType").getRefId())); if (msItem.hasReference("scale")) { Item oeItem = ItemHelper.convert(srcItemReader.getItemById( msItem.getReference("scale").getRefId())); tgtItem.addAttribute(new Attribute("scale", oeItem.getAttribute("value").getValue())); } else { LOG.error("srcItem (" + msItem.getIdentifier() + "( does not have scale attribute "); } if (msItem.hasAttribute("isBackground")) { tgtItem.addAttribute(new Attribute("isBackground", msItem.getAttribute("isBackground").getValue())); } else { LOG.error("srcItem (" + msItem.getIdentifier() + "( does not have scale reference "); } } } } maerSet.add(tgtItem); } /** * @param srcItem = mage:BioSequence * @param tgtItem = flymine:BioEntity(genomic_DNA =>NuclearDNA cDNA_clone=>CDNAClone, * vector=>Vector) * extra will create for Gene(FBgn), Vector(FBmc) and Synonym(embl) * synonymMap(itemid, item), synonymAccessionMap(accession, item) and * synonymAccession (HashSet) created for flymine:Synonym, * geneList include Gene and Vector to reprocess to add mAER collection * bioEntityList include CDNAClone and NuclearDNA to add identifier attribute * and mAER collection * @throws ObjectStoreException if problem occured during translating */ protected void translateBioEntity(Item srcItem, Item tgtItem) throws ObjectStoreException { Item gene = new Item(); Item vector = new Item(); Item synonym = new Item(); String s = null; String identifier = null; //prefetch done if (srcItem.hasReference("type")) { Item item = ItemHelper.convert(srcItemReader.getItemById( srcItem.getReference("type").getRefId())); if (item.hasAttribute("value")) { s = item.getAttribute("value").getValue(); if (s.equals("genomic_DNA")) { tgtItem.setClassName(tgtNs + "NuclearDNA"); } else if (s.equals("cDNA_clone")) { tgtItem.setClassName(tgtNs + "CDNAClone"); } else if (s.equals("vector")) { tgtItem.setClassName(tgtNs + "Vector"); } else { tgtItem = null; } } } // prefetch done if (srcItem.hasCollection("sequenceDatabases")) { ReferenceList rl = srcItem.getCollection("sequenceDatabases"); identifier = null; List geneList = new ArrayList(); List emblList = new ArrayList(); for (Iterator i = rl.getRefIds().iterator(); i.hasNext(); ) { Item dbEntryItem = ItemHelper.convert(srcItemReader. getItemById((String) i.next())); if (dbEntryItem.hasReference("database")) { Item dbItem = ItemHelper.convert(srcItemReader.getItemById( (String) dbEntryItem.getReference("database").getRefId())); String synonymSourceId = dbItem.getIdentifier(); if (dbItem.hasAttribute("name")) { String dbName = dbItem.getAttribute("name").getValue(); String organismDbId = dbEntryItem.getAttribute("accession").getValue(); if (dbName.equals("flybase") && organismDbId.startsWith("FBgn")) { gene = createGene(tgtNs + "Gene", "", dbEntryItem.getIdentifier(), organismDbId, tgtItem.getIdentifier()); // } else if (dbName.equals("flybase") && organismDbId.startsWith("FBmc")) { // tgtItem.addAttribute(new Attribute("organismDbId", organismDbId)); } else if (dbName.equals("embl") && dbEntryItem.hasAttribute("accession")) { String accession = dbEntryItem.getAttribute("accession").getValue(); //make sure synonym only create once for same accession if (!synonymAccessionMap.keySet().contains(accession)) { emblList.add(dbEntryItem.getIdentifier()); synonym = createSynonym(dbEntryItem, getSourceRef("embl"), srcItem.getIdentifier()); synonymMap.put(dbEntryItem.getIdentifier(), synonym); synonymAccessionMap.put(accession, synonym); } } else { //getDatabaseRef(); } } } } if (emblList != null && !emblList.isEmpty()) { ReferenceList synonymEmblRl = new ReferenceList("synonyms", emblList); tgtItem.addCollection(synonymEmblRl); } } if (tgtItem != null) { bioEntitySet.add(tgtItem); } } /** * @param srcItem = databaseEntry item refed in BioSequence * @param sourceRef ref to sourceId = database id * @param subjectId = bioEntity identifier will probably be changed * when reprocessing bioEntitySet * @return synonym item */ protected Item createSynonym(Item srcItem, Reference sourceRef, String subjectId) { Item synonym = new Item(); synonym.setClassName(tgtNs + "Synonym"); synonym.setIdentifier(srcItem.getIdentifier()); synonym.setImplementations(""); synonym.addAttribute(new Attribute("type", "accession")); synonym.addReference(sourceRef); synonym.addAttribute(new Attribute("value", srcItem.getAttribute("accession").getValue())); synonym.addReference(new Reference("subject", subjectId)); return synonym; } /** * @param srcItem = mage:LabeledExtract * @param tgtItem = flymine:LabeledExtract * @throws ObjectStoreException if problem occured during translating * LabeledExtract -> {treatments} -> {sourceBioMaterialMeasurements} -> *(BioSample)extract -> {treatments} -> {sourceBioMaterialMeasurements} -> *(BioSample)not-extract -> {treatments} -> {sourceBioMaterialMeasurements} -> *(BioSource) */ public void translateLabeledExtract(Item srcItem, Item tgtItem) throws ObjectStoreException { //prefetch done if (srcItem.hasReference("materialType")) { Item type = ItemHelper.convert(srcItemReader.getItemById( (String) srcItem.getReference("materialType").getRefId())); tgtItem.addAttribute(new Attribute("materialType", type.getAttribute("value").getValue())); } if (srcItem.hasCollection("labels")) { ReferenceList labels = srcItem.getCollection("labels"); if (labels == null || !isSingleElementCollection(labels)) { throw new IllegalArgumentException("LabeledExtract (" + srcItem.getIdentifier() + " does not have exactly one label"); } // prefetch done Item label = ItemHelper.convert(srcItemReader .getItemById(getFirstId(labels))); tgtItem.addAttribute(new Attribute("label", label.getAttribute("name").getValue())); } // prefetch done List treatmentList = new ArrayList(); String sampleId = null; StringBuffer sb = new StringBuffer(); if (srcItem.hasCollection("treatments")) { ReferenceList treatments = srcItem.getCollection("treatments"); for (Iterator i = treatments.getRefIds().iterator(); i.hasNext(); ) { String refId = (String) i.next(); treatmentList.add(refId); Item treatmentItem = ItemHelper.convert(srcItemReader.getItemById(refId)); if (treatmentItem.hasCollection("sourceBioMaterialMeasurements")) { ReferenceList sourceRl = treatmentItem.getCollection( "sourceBioMaterialMeasurements"); for (Iterator j = sourceRl.getRefIds().iterator(); j.hasNext(); ) { //bioMaterialMeausrement Item bioMMItem = ItemHelper.convert(srcItemReader.getItemById( (String) j.next())); if (bioMMItem.hasReference("bioMaterial")) { Item bioSample = ItemHelper.convert(srcItemReader.getItemById( (String) bioMMItem.getReference("bioMaterial").getRefId())); if (bioSample.hasCollection("treatments")) { ReferenceList bioSampleTreatments = bioSample.getCollection( "treatments"); for (Iterator k = bioSampleTreatments.getRefIds().iterator(); k.hasNext();) { refId = (String) k.next(); if (!treatmentList.contains(refId)) { treatmentList.add(refId); } //create treatment2BioSourceMap Item treatItem = ItemHelper.convert(srcItemReader. getItemById(refId)); //sampleId should be same despite of different //intermediate value sampleId = createTreatment2BioSourceMap(treatItem, srcItem.getIdentifier()); sb.append(sampleId + " "); } } } } } } ReferenceList tgtTreatments = new ReferenceList("treatments", treatmentList); tgtItem.addCollection(tgtTreatments); StringTokenizer st = new StringTokenizer(sb.toString()); while (st.hasMoreTokens()) { String s = st.nextToken(); if (!s.equals(sampleId)) { throw new IllegalArgumentException ("LabeledExtract (" + srcItem.getIdentifier() + " does not have exactly one reference to sample"); } } tgtItem.addReference(new Reference("sample", sampleId)); } } /** * @param srcItem = mage:BioSource * @param tgtItem = flymine:Sample * extra flymine:Organism item is created and saved in organismMap * @throws ObjectStoreException if problem occured during translating */ protected void translateSample(Item srcItem, Item tgtItem) throws ObjectStoreException { List list = new ArrayList(); Item organism = new Item(); String s = null; if (srcItem.hasCollection("characteristics")) { ReferenceList characteristics = srcItem.getCollection("characteristics"); for (Iterator i = characteristics.getRefIds().iterator(); i.hasNext();) { String id = (String) i.next(); // prefetch done Item charItem = ItemHelper.convert(srcItemReader.getItemById(id)); if (charItem.hasAttribute("category")) { s = charItem.getAttribute("category").getValue(); if (s.equals("Organism")) { if (charItem.hasAttribute("value")) { String organismName = charItem.getAttribute("value").getValue(); organism = createOrganism(tgtNs + "Organism", "", organismName); tgtItem.addReference(new Reference("organism", organism.getIdentifier())); } } else { list.add(id); } } } ReferenceList tgtChar = new ReferenceList("characteristics", list); tgtItem.addCollection(tgtChar); } if (srcItem.hasReference("materialType")) { Item type = ItemHelper.convert(srcItemReader.getItemById( (String) srcItem.getReference("materialType").getRefId())); tgtItem.addAttribute(new Attribute("materialType", type.getAttribute("value").getValue())); } if (srcItem.hasAttribute("name")) { tgtItem.addAttribute(new Attribute("name", srcItem.getAttribute("name").getValue())); } bioSource.add(tgtItem); } /** * @param srcItem = mage:Treatment * @param tgtItem = flymine:Treatment * @throws ObjectStoreException if problem occured during translating */ public void translateTreatment(Item srcItem, Item tgtItem) throws ObjectStoreException { //prefetch done if (srcItem.hasReference("action")) { Item action = ItemHelper.convert(srcItemReader.getItemById( (String) srcItem.getReference("action").getRefId())); if (action.hasAttribute("value")) { tgtItem.addAttribute(new Attribute("action", action.getAttribute("value").getValue())); } } } /** * @param srcItem = mage:Treatment from BioSample<Extract> * @param sourceId = mage:LabeledExtract srcItem identifier * @return string of bioSourceId * @throws ObjectStoreException if problem occured during translating * method called when processing LabeledExtract */ protected String createTreatment2BioSourceMap(Item srcItem, String sourceId) throws ObjectStoreException { StringBuffer bioSourceId = new StringBuffer(); StringBuffer treatment = new StringBuffer(); String id = null; if (srcItem.hasCollection("sourceBioMaterialMeasurements")) { ReferenceList sourceRl1 = srcItem.getCollection("sourceBioMaterialMeasurements"); for (Iterator l = sourceRl1.getRefIds().iterator(); l.hasNext(); ) { // prefetch done (but limited) Item sbmmItem = ItemHelper.convert(srcItemReader.getItemById( (String) l.next())); if (sbmmItem.hasReference("bioMaterial")) { // bioSampleItem, type not-extract Item bioSampleItem = ItemHelper.convert(srcItemReader.getItemById( (String) sbmmItem.getReference("bioMaterial").getRefId())); if (bioSampleItem.hasCollection("treatments")) { ReferenceList bioSourceRl = bioSampleItem.getCollection("treatments"); for (Iterator m = bioSourceRl.getRefIds().iterator(); m.hasNext();) { String treatmentList = (String) m.next(); treatment.append(treatmentList + " "); Item bioSourceTreatmentItem = ItemHelper.convert(srcItemReader. getItemById(treatmentList)); if (bioSourceTreatmentItem.hasCollection( "sourceBioMaterialMeasurements")) { ReferenceList sbmmRl = bioSourceTreatmentItem.getCollection( "sourceBioMaterialMeasurements"); for (Iterator n = sbmmRl.getRefIds().iterator(); n.hasNext();) { Item bmm = ItemHelper.convert(srcItemReader.getItemById( (String) n.next())); if (bmm.hasReference("bioMaterial")) { id = (String) bmm.getReference("bioMaterial"). getRefId(); bioSourceId.append(id + " "); } } } } } } } } //BioSample(not-extract) -> {treatments} -> {sourceBioMaterialMeasurements} ->(BioSource) // StringTokenizer st = new StringTokenizer(bioSourceId.toString()); while (st.hasMoreTokens()) { String s = st.nextToken(); if (!s.equals(id)) { throw new IllegalArgumentException("LabeledExtract (" + sourceId + " does not have exactly one reference to sample"); } } treatment2BioSourceMap.put(id, treatment.toString()); return id; } /** * bioSourceItem = flymine:Sample item without treatment collection * treatment collection is from mage:BioSample<type: not-Extract> treatment collection * treatment2BioSourceMap is created when tranlating LabeledExtract * @return resultSet */ protected Set processBioSourceTreatment() { Set results = new HashSet(); Iterator i = bioSource.iterator(); while (i.hasNext()) { Item bioSourceItem = (Item) i.next(); List treatList = new ArrayList(); String s = (String) treatment2BioSourceMap.get((String) bioSourceItem.getIdentifier()); LOG.debug("treatmentList " + s + " for " + bioSourceItem.getIdentifier()); if (s != null) { StringTokenizer st = new StringTokenizer(s); while (st.hasMoreTokens()) { treatList.add(st.nextToken()); } } ReferenceList treatments = new ReferenceList("treatments", treatList); bioSourceItem.addCollection(treatments); results.add(bioSourceItem); } return results; } /** * add tissues collection to MicroArrayAssay * @return MicroArrayAssay */ protected Set processAssayTissue() { Set results = new HashSet(); for (Iterator i = assaySet.iterator(); i.hasNext(); ) { Item assayItem = (Item) i.next(); String id = (String) assayItem.getIdentifier(); if (assay2LabeledExtract.containsKey(id)) { List tissue = (ArrayList) assay2LabeledExtract.get(id); if (tissue != null) { assayItem.addCollection(new ReferenceList("tissues", tissue)); results.add(assayItem); } } } return results; } /** * set ReporterLocation.design reference, don't need to set * MicroArraySlideDesign.locations explicitly * @return results set */ protected Set processReporterLocs() { Set results = new HashSet(); if (reporterLocs != null && featureToDesign != null && rlToFeature != null) { for (Iterator i = reporterLocs.iterator(); i.hasNext();) { Item rl = (Item) i.next(); String designId = (String) featureToDesign.get(rlToFeature.get(rl.getIdentifier())); Reference designRef = new Reference(); if (designId != null) { designRef.setName("design"); designRef.setRefId(designId); rl.addReference(designRef); results.add(rl); } } } return results; } /** * BioAssayDatum mage:FeatureId -> flymine:MAEResultId (MicroArrayExperimentalResults) * Reporter flymine: BioEntityId -> mage:FeatureId * BioSequece BioEntityId -> BioEntity Item * -> extra Gene Item * @return add microExperimentalResults collection to BioEntity item * and add identifier attribute to BioEntity */ protected Set processBioEntity() { Set results = new HashSet(); Set entitySet = new HashSet(); String s = null; String itemId = null; String identifierAttribute = null; String bioEntityId = null; String anotherId = null; Set identifierSet = new HashSet(); for (Iterator i = bioEntitySet.iterator(); i.hasNext();) { Item bioEntity = (Item) i.next(); bioEntityId = bioEntity.getIdentifier(); //add attribute identifier for bioEntity identifierAttribute = (String) bioEntity2IdentifierMap.get(bioEntityId); if (identifier2BioEntity.containsKey(identifierAttribute)) { Item anotherEntity = (Item) identifier2BioEntity.get(identifierAttribute); anotherId = anotherEntity.getIdentifier(); List synonymList = new ArrayList(); if (anotherEntity.hasCollection("synonyms")) { ReferenceList synonymList1 = anotherEntity.getCollection("synonyms"); for (Iterator k = synonymList1.getRefIds().iterator(); k.hasNext();) { String refId = (String) k.next(); synonymList.add(refId); } } if (bioEntity.hasCollection("synonyms")) { ReferenceList synonymList2 = bioEntity.getCollection("synonyms"); String subject = anotherEntity.getIdentifier(); for (Iterator k = synonymList2.getRefIds().iterator(); k.hasNext();) { String refId = (String) k.next(); if (!synonymList.contains(refId)) { synonymList.add(refId); } //change subjectId for sysnonym when its bioentity is merged Item synonym = (Item) synonymMap.get(refId); String accession = synonym.getAttribute("value").getValue(); synonym.addReference(new Reference("subject", subject)); synonymAccessionMap.put(accession, synonym); } } if (synonymList != null) { anotherEntity.addCollection(new ReferenceList("synonyms", synonymList)); } identifier2BioEntity.put(identifierAttribute, anotherEntity); bioEntityRefMap.put(bioEntityId, anotherId); //modify bioEntity2Feature String mergedFeatures = (String) bioEntity2Feature.get(bioEntityId); String features = (String) bioEntity2Feature.get(anotherId); String newFeatures = null; if (mergedFeatures != null && features != null) { newFeatures = features.concat(" " + mergedFeatures); } else if (mergedFeatures != null && features == null) { newFeatures = mergedFeatures; } else if (mergedFeatures == null && features != null) { newFeatures = features; } if (newFeatures != null) { bioEntity2Feature.remove(bioEntityId); bioEntity2Feature.remove(anotherId); bioEntity2Feature.put(anotherId, newFeatures); } //modify bioEntity2Gene String mergedGene = (String) bioEntity2Gene.get(bioEntityId); String gene = (String) bioEntity2Gene.get(anotherId); String newGenes = null; if (gene != null && mergedGene != null) { newGenes = gene.concat(" " + mergedGene); } else if (gene == null && mergedGene != null) { newGenes = mergedGene; } else if (gene != null && mergedGene == null) { newGenes = gene; } if (newGenes != null) { bioEntity2Gene.remove(bioEntityId); bioEntity2Gene.remove(anotherId); bioEntity2Gene.put(anotherId, newGenes); } } else { bioEntity.addAttribute(new Attribute("identifier", identifierAttribute)); identifier2BioEntity.put(identifierAttribute, bioEntity); identifierSet.add(identifierAttribute); } } for (Iterator i = identifierSet.iterator(); i.hasNext();) { Item bioEntity = (Item) identifier2BioEntity.get((String) i.next()); results.add(bioEntity); if (bioEntity.getClassName().equals(tgtNs + "CDNAClone")) { cdnaSet.add(bioEntity.getIdentifier()); } } for (Iterator i = synonymAccessionMap.keySet().iterator(); i.hasNext();) { Item synonym = (Item) synonymAccessionMap.get((String) i.next()); results.add(synonym); } return results; } /** * BioAssayDatum mage:FeatureId -> flymine:MAEResultId (MicroArrayExperimentalResult) * Reporter flymine: BioEntityId -> mage:FeatureId * BioSequece BioEntityId -> BioEntity Item * -> extra Gene Item * @return add microExperimentalResult collection to Gene item */ protected Set processGene() { Set results = new HashSet(); for (Iterator i = geneMap.keySet().iterator(); i.hasNext();) { String organismDbId = (String) i.next(); Item gene = (Item) geneMap.get(organismDbId); results.add(gene); } return results; } /** * got reporterSet from setBioEntityMap() * refererence material may be changed after processBioEntity2MAEResult() * bioEntity is merged if it has the same identifierAttribute * @return resutls with right material refid */ protected Set processReporterMaterial() { Set results = new HashSet(); for (Iterator i = reporterSet.iterator(); i.hasNext();) { Item reporter = (Item) i.next(); if (reporter.hasReference("material")) { String bioEntityId = (String) reporter.getReference("material").getRefId(); if (bioEntityRefMap.containsKey(bioEntityId)) { String newBioEntityId = (String) bioEntityRefMap.get(bioEntityId); reporter.addReference(new Reference("material", newBioEntityId)); } } results.add(reporter); } return results; } /** * got organismMap from createOrganism() * @return organism only once for the same item */ protected Set processOrganism() { Set results = new HashSet(); for (Iterator i = organismMap.keySet().iterator(); i.hasNext();) { String organismValue = (String) i.next(); Item organism = (Item) organismMap.get(organismValue); results.add(organism); } return results; } /** * maer add reference of reporter, material(CDNAClone only), assay(MicroArrayAssay) * add collection of genes and tissues(LabeledExtract) * @return maerItem collections */ protected Set processMaer() { Set results = new HashSet(); maer2Reporter = createMaer2ReporterMap(maer2Feature, reporter2FeatureMap, maerSet); maer2Assay = createMaer2AssayMap(assay2Maer); maer2Tissue = createMaer2TissueMap(maer2Assay, assay2LabeledExtract, maerSet); maer2Material = createMaer2MaterialMap(maer2Feature, bioEntity2Feature, maerSet, cdnaSet); maer2Gene = createMaer2GeneMap(maer2Feature, bioEntity2Feature, bioEntity2Gene, maerSet); for (Iterator i = maerSet.iterator(); i.hasNext(); ) { Item maerItem = (Item) i.next(); String id = maerItem.getIdentifier(); if (maer2Reporter.containsKey(id)) { String reporter = (String) maer2Reporter.get(id); if (reporter != null) { maerItem.addReference(new Reference("reporter", reporter)); } } if (maer2Assay.containsKey(id)) { String assay = (String) maer2Assay.get(id); if (assay != null) { maerItem.addReference(new Reference("assay", assay)); } } if (maer2Tissue.containsKey(id)) { List tissue = (List) maer2Tissue.get(id); if (tissue != null && !tissue.isEmpty()) { maerItem.addCollection(new ReferenceList("tissues", tissue)); } } if (maer2Material.containsKey(id)) { String material = (String) maer2Material.get(id); if (material != null) { maerItem.addReference(new Reference("material", material)); } } if (maer2Gene.containsKey(id)) { String genes = (String) maer2Gene.get(id); if (genes != null) { StringTokenizer st = new StringTokenizer(genes); List l = new ArrayList(); while (st.hasMoreTokens()) { String gene = st.nextToken(); l.add(gene); } maerItem.addCollection(new ReferenceList("genes", l)); } } results.add(maerItem); } return results; } /** * @param maer2Feature = HashMap * @param reporter2FeatureMap = HashMap * @param maerSet = HashSet * @return maer2Reporter */ protected Map createMaer2ReporterMap(Map maer2Feature, Map reporter2FeatureMap, Set maerSet) { Map feature2Reporter = new HashMap(); String features = null; String feature = null; String reporter = null; for (Iterator i = reporter2FeatureMap.keySet().iterator(); i.hasNext(); ) { reporter = (String) i.next(); features = null; feature = null; if (reporter2FeatureMap.containsKey(reporter)) { features = (String) reporter2FeatureMap.get(reporter); if (features != null) { StringTokenizer st = new StringTokenizer(features); while (st.hasMoreTokens()) { feature = (String) st.nextToken(); feature2Reporter.put(feature, reporter); } } } } for (Iterator i = maerSet.iterator(); i.hasNext(); ) { Item maerItem = (Item) i.next(); String maer = maerItem.getIdentifier(); feature = null; reporter = null; if (maer2Feature.containsKey(maer)) { feature = (String) maer2Feature.get(maer); if (feature != null && feature2Reporter.containsKey(feature)) { reporter = (String) feature2Reporter.get(feature); } if (reporter != null) { maer2Reporter.put(maer, reporter); } } } return maer2Reporter; } /** * @param assay2Maer = HashMap * @return maer2Assay */ protected Map createMaer2AssayMap(Map assay2Maer) { for (Iterator i = assay2Maer.keySet().iterator(); i.hasNext(); ) { String assay = (String) i.next(); if (assay2Maer.containsKey(assay)) { List maers = (ArrayList) assay2Maer.get(assay); if (maers != null) { for (Iterator j = maers.iterator(); j.hasNext(); ) { String maer = (String) j.next(); maer2Assay.put(maer, assay); } } } } return maer2Assay; } /** * @param maer2Assay = HashMap * @param assay2LabeledExtract = HashMap * @param maerSet = HashSet * @return maer2Tissue */ protected Map createMaer2TissueMap(Map maer2Assay, Map assay2LabeledExtract, Set maerSet) { for (Iterator i = maerSet.iterator(); i.hasNext(); ) { List le = new ArrayList(); String assay = null; Item maerItem = (Item) i.next(); String maer = maerItem.getIdentifier(); if (maer2Assay.containsKey(maer)) { assay = (String) maer2Assay.get(maer); } if (assay != null) { le = (ArrayList) assay2LabeledExtract.get(assay); } if (le != null) { maer2Tissue.put(maer, le); } } return maer2Tissue; } /** * @param maer2Feature = HashMap * @param bioEntity2Feature = HashMap * @param maerSet = HashSet * @param cdnaSet = HashSet * @return maer2Material */ protected Map createMaer2MaterialMap(Map maer2Feature, Map bioEntity2Feature, Set maerSet, Set cdnaSet) { Map feature2Cdna = new HashMap(); for (Iterator i = cdnaSet.iterator(); i.hasNext(); ) { String cdnaId = (String) i.next(); String feature = null; String features = null; if (bioEntity2Feature.containsKey(cdnaId)) { features = (String) bioEntity2Feature.get(cdnaId); } if (features != null) { StringTokenizer st = new StringTokenizer(features); while (st.hasMoreTokens()) { feature = st.nextToken(); feature2Cdna.put(feature, cdnaId); } } } for (Iterator j = maerSet.iterator(); j.hasNext();) { Item maerItem = (Item) j.next(); String maer = maerItem.getIdentifier(); String feature = null; String material = null; if (maer2Feature.containsKey(maer)) { feature = (String) maer2Feature.get(maer); if (feature != null && feature2Cdna.containsKey(feature)) { material = (String) feature2Cdna.get(feature); } if (material != null) { maer2Material.put(maer, material); } } } return maer2Material; } /** * @param maer2Feature = HashMap * @param bioEntity2Feature = HashMap * @param bioEntity2Gene = HashMap * @param maerSet = HashSet * @return maer2Gene */ protected Map createMaer2GeneMap(Map maer2Feature, Map bioEntity2Feature, Map bioEntity2Gene, Set maerSet) { Map feature2BioEntity = new HashMap(); String bioEntity = null; String genes = null; String feature = null; String features = null; for (Iterator i = bioEntity2Feature.keySet().iterator(); i.hasNext(); ) { String bioEntityId = (String) i.next(); feature = null; features = null; features = (String) bioEntity2Feature.get(bioEntityId); if (features != null) { StringTokenizer st = new StringTokenizer(features); while (st.hasMoreTokens()) { feature = st.nextToken(); feature2BioEntity.put(feature, bioEntityId); } } } for (Iterator j = maerSet.iterator(); j.hasNext(); ) { Item maerItem = (Item) j.next(); String maer = maerItem.getIdentifier(); feature = null; genes = null; bioEntity = null; if (maer2Feature.containsKey(maer)) { feature = (String) maer2Feature.get(maer); } if (feature != null && feature2BioEntity.containsKey(feature)) { bioEntity = (String) feature2BioEntity.get(feature); } if (bioEntity != null && bioEntity2Gene.containsKey(bioEntity)) { genes = (String) bioEntity2Gene.get(bioEntity); } if (genes != null) { maer2Gene.put(maer, genes); } } return maer2Gene; } /** * normalised attribute is added during MageConverter * converting BioAssayDatum * true for Derived BioAssayData * false for Measured BioAssayData * removed this attribute before translateItem */ private Item removeNormalisedAttribute(Item item) { Item newItem = new Item(); newItem.setClassName(item.getClassName()); newItem.setIdentifier(item.getIdentifier()); newItem.setImplementations(item.getImplementations()); Iterator i = item.getAttributes().iterator(); while (i.hasNext()) { Attribute attr = (Attribute) i.next(); if (!attr.getName().equals("normalised")) { newItem.addAttribute(attr); } } i = item.getReferences().iterator(); while (i.hasNext()) { newItem.addReference((Reference) i.next()); } i = item.getCollections().iterator(); while (i.hasNext()) { newItem.addCollection((ReferenceList) i.next()); } return newItem; } /** * @param className = tgtClassName * @param implementation = tgtClass implementation * @param identifier = gene item identifier from database item identifier * @param organismDbId = attribute for gene organismDbId * @return gene item */ private Item createGene(String className, String implementation, String identifier, String organismDbId, String bioEntityId) { Item gene = new Item(); if (!geneMap.containsKey(organismDbId)) { gene = createItem(className, implementation); gene.setIdentifier(identifier); gene.addAttribute(new Attribute("organismDbId", organismDbId)); geneMap.put(organismDbId, gene); bioEntity2Gene.put(bioEntityId, identifier); } else { gene = (Item) geneMap.get(organismDbId); } return gene; } /** * @param className = tgtClassName * @param implementation = tgtClass implementation * @param value = attribute for organism name * @return organism item */ private Item createOrganism(String className, String implementation, String value) { Item organism = new Item(); if (!organismMap.containsKey(value)) { organism = createItem(className, implementation); organism.addAttribute(new Attribute("name", value)); organismMap.put(value, organism); } else { organism = (Item) organismMap.get(value); } return organism; } /** * @param dbName = databaseName * @return databaseItem */ private Item getDb(String dbName) { Item db = (Item) dbs.get(dbName); if (db == null) { db = createItem(tgtNs + "Database", ""); Attribute title = new Attribute("title", dbName); db.addAttribute(title); dbs.put(dbName, db); } return db; } /** * @param dbName = databaseName * @return databaseReference */ private Reference getSourceRef(String dbName) { Reference sourceRef = (Reference) dbRefs.get(dbName); if (sourceRef == null) { sourceRef = new Reference("source", getDb(dbName).getIdentifier()); dbRefs.put(dbName, sourceRef); } return sourceRef; } /** * @return identifier for experimentItem assume only one experiment item presented */ private String getAnalysisRef() { if (expItem.getIdentifier() == "") { expItem = createItem(tgtNs + "MicroArrayExperiment", ""); } return expItem.getIdentifier(); } /** * main method * @param args command line arguments * @throws Exception if something goes wrong */ public static void main (String[] args) throws Exception { String srcOsName = args[0]; String tgtOswName = args[1]; String modelName = args[2]; String format = args[3]; String namespace = args[4]; Map paths = new HashMap(); HashSet descSet = new HashSet(); //setReporterLocationCoords ItemPrefetchDescriptor desc1 = new ItemPrefetchDescriptor( "(FeatureGroup <- Feature.featureGroup)"); desc1.addConstraint(new ItemPrefetchConstraintDynamic( ObjectStoreItemPathFollowingImpl.IDENTIFIER, "featureGroup")); desc1.addConstraint(new FieldNameAndValue(ObjectStoreItemPathFollowingImpl.CLASSNAME, "http://www.flymine.org/model/mage#Feature", false)); paths.put("http://www.flymine.org/model/mage#FeatureGroup", Collections.singleton(desc1)); // BioAssayDatum.quantitationType.scale desc1 = new ItemPrefetchDescriptor("BioAssayDatum.quantitationType"); desc1.addConstraint(new ItemPrefetchConstraintDynamic("quantitationType", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); ItemPrefetchDescriptor desc2 = new ItemPrefetchDescriptor( "(BioAssayDatum.quantitationType).scale"); desc2.addConstraint(new ItemPrefetchConstraintDynamic("scale", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); desc1.addPath(desc2); descSet.add(desc1); // BioAssayDatum.quantitationType.targetQuantitationType.scale ItemPrefetchDescriptor desc3 = new ItemPrefetchDescriptor( "(BioAssayDatum.quantitationType).targetQuantitationType"); desc3.addConstraint(new ItemPrefetchConstraintDynamic( "targetQuantitationType", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); ItemPrefetchDescriptor desc4 = new ItemPrefetchDescriptor( "(BioAssayDatum.quantitationType.targetQuantitationType).scale"); desc4.addConstraint(new ItemPrefetchConstraintDynamic("scale", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); desc3.addPath(desc4); desc1.addPath(desc3); descSet.add(desc1); //paths.put("http://www.flymine.org/model/mage#BioAssayDatum",Collections.singleton(desc1)); paths.put("http://www.flymine.org/model/mage#BioAssayDatum", descSet); // BioSequence... descSet = new HashSet(); // BioSequence.type desc1 = new ItemPrefetchDescriptor("BioSequence.type"); desc1.addConstraint(new ItemPrefetchConstraintDynamic("type", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); descSet.add(desc1); // BioSequence.sequenceDatabases.databaseEntry.database desc1 = new ItemPrefetchDescriptor("BioSequence.sequenceDatabases"); desc1.addConstraint(new ItemPrefetchConstraintDynamic("sequenceDatabases", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); desc2 = new ItemPrefetchDescriptor("(BioSequence.sequenceDatabases).databaseEntry"); desc2.addConstraint(new ItemPrefetchConstraintDynamic("databaseEntry", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); desc3 = new ItemPrefetchDescriptor( "((BioSequence.sequenceDatabases).databaseEntry).database"); desc3.addConstraint(new ItemPrefetchConstraintDynamic("database", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); desc2.addPath(desc3); desc1.addPath(desc2); descSet.add(desc1); paths.put("http://www.flymine.org/model/mage#BioSequence", descSet); // LabeledExtract... descSet = new HashSet(); // LabeledExtract.materialType desc1 = new ItemPrefetchDescriptor("LabeledExtract.materialType"); desc1.addConstraint(new ItemPrefetchConstraintDynamic("materialType", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); descSet.add(desc1); // LabeledExtract.labels desc1 = new ItemPrefetchDescriptor("LabeledExtract.labels"); desc1.addConstraint(new ItemPrefetchConstraintDynamic("labels", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); descSet.add(desc1); // code descends through treatments in a loop - prefetch can't handle // that so need to define cutoff (??) // LabeledExtract.treatments.sourceBioMaterialMeasurements.bioMaterial.treatments // .sourceBioMaterialMeasurements.bioMaterial.treatments desc1 = new ItemPrefetchDescriptor("LabeledExtract.treatments"); desc1.addConstraint(new ItemPrefetchConstraintDynamic("treatments", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); desc2 = new ItemPrefetchDescriptor( "(LabeledExtract.treatments).sourceBioMaterialMeasurements"); desc2.addConstraint(new ItemPrefetchConstraintDynamic("bioMaterialMeasurements", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); desc3 = new ItemPrefetchDescriptor( "((LabeledExtract.treatments).sourceBioMaterialMeasurements).bioMaterial"); desc3.addConstraint(new ItemPrefetchConstraintDynamic("bioMaterial", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); desc4 = new ItemPrefetchDescriptor( "(((LabeledExtract.treatments).sourceBioMaterialMeasurements).bioMaterial).treatments"); desc4.addConstraint(new ItemPrefetchConstraintDynamic("treatments", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); ItemPrefetchDescriptor desc5 = new ItemPrefetchDescriptor( "(...).sourceBioMaterialMeasurements"); desc5.addConstraint(new ItemPrefetchConstraintDynamic("sourceBioMaterialMeasurements", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); ItemPrefetchDescriptor desc6 = new ItemPrefetchDescriptor( "((...).sourceBioMaterialMeasurements).bioMaterial"); desc6.addConstraint(new ItemPrefetchConstraintDynamic("bioMaterial", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); ItemPrefetchDescriptor desc7 = new ItemPrefetchDescriptor( "(((...).sourceBioMaterialMeasurements).bioMaterial).treatments"); desc7.addConstraint(new ItemPrefetchConstraintDynamic("treatments", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); desc6.addPath(desc7); desc5.addPath(desc6); desc4.addPath(desc5); desc3.addPath(desc4); desc2.addPath(desc3); desc1.addPath(desc2); descSet.add(desc1); paths.put("http://www.flymine.org/model/mage#LabeledExtract", descSet); // BioSource... descSet = new HashSet(); // BioSource.materialType desc1 = new ItemPrefetchDescriptor("BioSource.materialType"); desc1.addConstraint(new ItemPrefetchConstraintDynamic("materialType", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); descSet.add(desc1); // BioSource.characteristics desc1 = new ItemPrefetchDescriptor("BioSource.characteristics"); desc1.addConstraint(new ItemPrefetchConstraintDynamic("characteristics", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); descSet.add(desc1); paths.put("http://www.flymine.org/model/mage#BioSource", descSet); // Treatment.action desc1 = new ItemPrefetchDescriptor("Treatment.action"); desc1.addConstraint(new ItemPrefetchConstraintDynamic( ObjectStoreItemPathFollowingImpl.IDENTIFIER, "action")); paths.put("http://www.flymine.org/model/mage#Treatment", Collections.singleton(desc1)); // new prefetch with collections // FeatureReporterMap->featureInformationSources->feature->featureLocation descSet = new HashSet(); desc1 = new ItemPrefetchDescriptor("FeatureReporterMap.featureInformaionSources"); desc1.addConstraint(new ItemPrefetchConstraintDynamic("featureInformationSources", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); desc2 = new ItemPrefetchDescriptor( "(FeatureReporterMap.featureInformaionSources).feature"); desc2.addConstraint(new ItemPrefetchConstraintDynamic("feature", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); desc3 = new ItemPrefetchDescriptor( "((FeatureReporterMap.featureInformaionSources).feature).featureLocation"); desc3.addConstraint(new ItemPrefetchConstraintDynamic("featureLocation", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); desc1.addPath(desc2); desc2.addPath(desc3); //descSet.add(desc1); required? // FeatureReporterMap->featureInformationSources->feature->zone desc4 = new ItemPrefetchDescriptor( "((FeatureReporterMap.featureInformaionSources).feature).zone"); desc4.addConstraint(new ItemPrefetchConstraintDynamic("zone", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); desc2.addPath(desc4); descSet.add(desc1); paths.put("http://www.flymine.org/model/mage#FeatureReporterMap", descSet); // PhysicalArrayDesign... descSet = new HashSet(); // PhysicalArrayDesign->featureGroups desc1 = new ItemPrefetchDescriptor("PhysicalArrayDesign.featureGroups"); desc1.addConstraint(new ItemPrefetchConstraintDynamic("featureGroups", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); descSet.add(desc1); // PhysicalArrayDesign->surfaceType desc1 = new ItemPrefetchDescriptor("PhysicalArrayDesign.surfaceType"); desc1.addConstraint(new ItemPrefetchConstraintDynamic("surfaceType", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); descSet.add(desc1); // PhysicalArrayDesign->descriptions desc1 = new ItemPrefetchDescriptor("PhysicalArrayDesign.descriptions"); desc1.addConstraint(new ItemPrefetchConstraintDynamic("descripions", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); descSet.add(desc1); paths.put("http://www.flymine.org/model/mage#PhysicalArrayDesign", descSet); // Reporter... descSet = new HashSet(); // Reporter <- FeatureReporterMap.reporter desc1 = new ItemPrefetchDescriptor("(Reporter <- FeatureReporterMap.reporter)"); desc1.addConstraint(new ItemPrefetchConstraintDynamic( ObjectStoreItemPathFollowingImpl.IDENTIFIER, "reporter")); desc1.addConstraint(new FieldNameAndValue(ObjectStoreItemPathFollowingImpl.CLASSNAME, "http://www.flymine.org/model/mage#FeatureReporterMap", false)); descSet.add(desc1); // Reporter->failTypes desc1 = new ItemPrefetchDescriptor("Reporter.failTypes"); desc1.addConstraint(new ItemPrefetchConstraintDynamic("failTypes", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); descSet.add(desc1); // Reporter->controlType desc1 = new ItemPrefetchDescriptor("Reporter.controlType"); desc1.addConstraint(new ItemPrefetchConstraintDynamic("controlType", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); descSet.add(desc1); // Reporter->immobilizedCharacteristics->type desc1 = new ItemPrefetchDescriptor("Reporter.immobilizedCharacteristics"); desc1.addConstraint(new ItemPrefetchConstraintDynamic("immobilizedCharacteristics", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); desc2 = new ItemPrefetchDescriptor( "(Reporter.immobilizedCharacteristics).type"); desc2.addConstraint(new ItemPrefetchConstraintDynamic("type", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); desc1.addPath(desc2); descSet.add(desc1); // Reporter->descriptions desc1 = new ItemPrefetchDescriptor("Reporter.descriptions"); desc1.addConstraint(new ItemPrefetchConstraintDynamic("descriptions", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); descSet.add(desc1); // Reporter->featureReporterMaps->featureInformationSources desc1 = new ItemPrefetchDescriptor("Reporter.featureReporterMaps"); desc1.addConstraint(new ItemPrefetchConstraintDynamic("featureReporterMaps", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); desc2 = new ItemPrefetchDescriptor( "(Reporter.featureReporterMaps).featureInformationSources"); desc2.addConstraint(new ItemPrefetchConstraintDynamic("featureInformationSources", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); desc1.addPath(desc2); descSet.add(desc1); paths.put("http://www.flymine.org/model/mage#Reporter", descSet); // Experiment... descSet = new HashSet(); // Experiment->bioAssays desc1 = new ItemPrefetchDescriptor("Experiment.bioAssays"); desc1.addConstraint(new ItemPrefetchConstraintDynamic("bioAssays", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); descSet.add(desc1); // Experiment->bioAssays.physicalBioAssay->Hybridization desc2 = new ItemPrefetchDescriptor( "(Experiment.bioAssays:physicalBioAssay).bioAssayCreation"); desc2.addConstraint(new ItemPrefetchConstraintDynamic("bioAssayCreation", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); desc1.addPath(desc2); // Experiment->bioAssays.physicalBioAssay->Hybridization.sourceBioMaterialMeasurements desc3 = new ItemPrefetchDescriptor( "(Experiment.bioAssays:physicalBioAssay.bioAssayCreation).sourceBioMaterialMeasurements"); desc3.addConstraint(new ItemPrefetchConstraintDynamic("sourceBioMaterialMeasurements", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); desc2.addPath(desc3); descSet.add(desc1); // Experiment.descriptions desc1 = new ItemPrefetchDescriptor("Experiment.descriptions"); desc1.addConstraint(new ItemPrefetchConstraintDynamic("descriptions", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); descSet.add(desc1); paths.put("http://www.flymine.org/model/mage#Experiment", descSet); // DerivedBioAssay.derivedBioAssayData.bioDataValues. desc1 = new ItemPrefetchDescriptor("DerivedBioAssay.derivedBioAssayData"); desc1.addConstraint(new ItemPrefetchConstraintDynamic("derivedBioAssayData", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); desc2 = new ItemPrefetchDescriptor( "(DerivedBioAssay.derivedBioAssayData).bioDataValues"); desc2.addConstraint(new ItemPrefetchConstraintDynamic("bioDataValues", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); desc1.addPath(desc2); descSet.add(desc1); paths.put("http://www.flymine.org/model/mage#DerivedBioAssay", Collections.singleton(desc1)); ObjectStore osSrc = ObjectStoreFactory.getObjectStore(srcOsName); ItemReader srcItemReader = new ObjectStoreItemReader(osSrc, paths); ObjectStoreWriter oswTgt = ObjectStoreWriterFactory.getObjectStoreWriter(tgtOswName); ItemWriter tgtItemWriter = new ObjectStoreItemWriter(oswTgt); OntModel model = ModelFactory.createOntologyModel(); model.read(new FileReader(new File(modelName)), null, format); DataTranslator dt = new MageDataTranslator(srcItemReader, model, namespace); model = null; dt.translate(tgtItemWriter); tgtItemWriter.close(); } }
added 1-1 reference to both way
flymine/model/mage/src/java/org/flymine/dataconversion/MageDataTranslator.java
added 1-1 reference to both way
Java
lgpl-2.1
ef661fc4f7097e49eaf1885c6f1bfa27d6f1e094
0
aaronc/jfreechart,aaronc/jfreechart,aaronc/jfreechart
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2008, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ---------------------------- * XYBoxAndWhiskerRenderer.java * ---------------------------- * (C) Copyright 2003-2008, by David Browning and Contributors. * * Original Author: David Browning (for Australian Institute of Marine * Science); * Contributor(s): David Gilbert (for Object Refinery Limited); * * Changes * ------- * 05-Aug-2003 : Version 1, contributed by David Browning. Based on code in the * CandlestickRenderer class. Additional modifications by David * Gilbert to make the code work with 0.9.10 changes (DG); * 08-Aug-2003 : Updated some of the Javadoc * Allowed BoxAndwhiskerDataset Average value to be null - the * average value is an AIMS requirement * Allow the outlier and farout coefficients to be set - though * at the moment this only affects the calculation of farouts. * Added artifactPaint variable and setter/getter * 12-Aug-2003 Rewrote code to sort out and process outliers to take * advantage of changes in DefaultBoxAndWhiskerDataset * Added a limit of 10% for width of box should no width be * specified...maybe this should be setable??? * 20-Aug-2003 : Implemented Cloneable and PublicCloneable (DG); * 08-Sep-2003 : Changed ValueAxis API (DG); * 16-Sep-2003 : Changed ChartRenderingInfo --> PlotRenderingInfo (DG); * 25-Feb-2004 : Replaced CrosshairInfo with CrosshairState (DG); * 23-Apr-2004 : Added fillBox attribute, extended equals() method and fixed * serialization issue (DG); * 29-Apr-2004 : Fixed problem with drawing upper and lower shadows - bug id * 944011 (DG); * 15-Jul-2004 : Switched getX() with getXValue() and getY() with * getYValue() (DG); * 01-Oct-2004 : Renamed 'paint' --> 'boxPaint' to avoid conflict with * inherited attribute (DG); * 10-Jun-2005 : Updated equals() to handle GradientPaint (DG); * 06-Oct-2005 : Removed setPaint() call in drawItem(), it is causing a * loop (DG); * ------------- JFREECHART 1.0.x --------------------------------------------- * 02-Feb-2007 : Removed author tags from all over JFreeChart sources (DG); * 05-Feb-2007 : Added event notifications and fixed drawing for horizontal * plot orientation (DG); * 13-Jun-2007 : Replaced deprecated method call (DG); * 03-Jan-2008 : Check visibility of average marker before drawing it (DG); * 27-Mar-2008 : If boxPaint is null, revert to itemPaint (DG); * */ package org.jfree.chart.renderer.xy; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Shape; import java.awt.Stroke; import java.awt.geom.Ellipse2D; import java.awt.geom.Line2D; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.entity.EntityCollection; import org.jfree.chart.event.RendererChangeEvent; import org.jfree.chart.labels.BoxAndWhiskerXYToolTipGenerator; import org.jfree.chart.plot.CrosshairState; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.PlotRenderingInfo; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.renderer.Outlier; import org.jfree.chart.renderer.OutlierList; import org.jfree.chart.renderer.OutlierListCollection; import org.jfree.data.statistics.BoxAndWhiskerXYDataset; import org.jfree.data.xy.XYDataset; import org.jfree.io.SerialUtilities; import org.jfree.ui.RectangleEdge; import org.jfree.util.PaintUtilities; import org.jfree.util.PublicCloneable; /** * A renderer that draws box-and-whisker items on an {@link XYPlot}. This * renderer requires a {@link BoxAndWhiskerXYDataset}). * <P> * This renderer does not include any code to calculate the crosshair point. */ public class XYBoxAndWhiskerRenderer extends AbstractXYItemRenderer implements XYItemRenderer, Cloneable, PublicCloneable, Serializable { /** For serialization. */ private static final long serialVersionUID = -8020170108532232324L; /** The box width. */ private double boxWidth; /** The paint used to fill the box. */ private transient Paint boxPaint; /** A flag that controls whether or not the box is filled. */ private boolean fillBox; /** * The paint used to draw various artifacts such as outliers, farout * symbol, average ellipse and median line. */ private transient Paint artifactPaint = Color.black; /** * Creates a new renderer for box and whisker charts. */ public XYBoxAndWhiskerRenderer() { this(-1.0); } /** * Creates a new renderer for box and whisker charts. * <P> * Use -1 for the box width if you prefer the width to be calculated * automatically. * * @param boxWidth the box width. */ public XYBoxAndWhiskerRenderer(double boxWidth) { super(); this.boxWidth = boxWidth; this.boxPaint = Color.green; this.fillBox = true; setBaseToolTipGenerator(new BoxAndWhiskerXYToolTipGenerator()); } /** * Returns the width of each box. * * @return The box width. * * @see #setBoxWidth(double) */ public double getBoxWidth() { return this.boxWidth; } /** * Sets the box width and sends a {@link RendererChangeEvent} to all * registered listeners. * <P> * If you set the width to a negative value, the renderer will calculate * the box width automatically based on the space available on the chart. * * @param width the width. * * @see #getBoxWidth() */ public void setBoxWidth(double width) { if (width != this.boxWidth) { this.boxWidth = width; fireChangeEvent(); } } /** * Returns the paint used to fill boxes. * * @return The paint (possibly <code>null</code>). * * @see #setBoxPaint(Paint) */ public Paint getBoxPaint() { return this.boxPaint; } /** * Sets the paint used to fill boxes and sends a {@link RendererChangeEvent} * to all registered listeners. * * @param paint the paint (<code>null</code> permitted). * * @see #getBoxPaint() */ public void setBoxPaint(Paint paint) { this.boxPaint = paint; fireChangeEvent(); } /** * Returns the flag that controls whether or not the box is filled. * * @return A boolean. * * @see #setFillBox(boolean) */ public boolean getFillBox() { return this.fillBox; } /** * Sets the flag that controls whether or not the box is filled and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param flag the flag. * * @see #setFillBox(boolean) */ public void setFillBox(boolean flag) { this.fillBox = flag; fireChangeEvent(); } /** * Returns the paint used to paint the various artifacts such as outliers, * farout symbol, median line and the averages ellipse. * * @return The paint (never <code>null</code>). * * @see #setArtifactPaint(Paint) */ public Paint getArtifactPaint() { return this.artifactPaint; } /** * Sets the paint used to paint the various artifacts such as outliers, * farout symbol, median line and the averages ellipse, and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param paint the paint (<code>null</code> not permitted). * * @see #getArtifactPaint() */ public void setArtifactPaint(Paint paint) { if (paint == null) { throw new IllegalArgumentException("Null 'paint' argument."); } this.artifactPaint = paint; fireChangeEvent(); } /** * Returns the box paint or, if this is <code>null</code>, the item * paint. * * @param series the series index. * @param item the item index. * * @return The paint used to fill the box for the specified item (never * <code>null</code>). * * @since 1.0.10 */ protected Paint lookupBoxPaint(int series, int item) { Paint p = getBoxPaint(); if (p != null) { return p; } else { // TODO: could change this to itemFillPaint(). For backwards // compatibility, it might require a useFillPaint flag. return getItemPaint(series, item); } } /** * Draws the visual representation of a single data item. * * @param g2 the graphics device. * @param state the renderer state. * @param dataArea the area within which the plot is being drawn. * @param info collects info about the drawing. * @param plot the plot (can be used to obtain standard color * information etc). * @param domainAxis the domain axis. * @param rangeAxis the range axis. * @param dataset the dataset (must be an instance of * {@link BoxAndWhiskerXYDataset}). * @param series the series index (zero-based). * @param item the item index (zero-based). * @param crosshairState crosshair information for the plot * (<code>null</code> permitted). * @param pass the pass index. */ public void drawItem(Graphics2D g2, XYItemRendererState state, Rectangle2D dataArea, PlotRenderingInfo info, XYPlot plot, ValueAxis domainAxis, ValueAxis rangeAxis, XYDataset dataset, int series, int item, CrosshairState crosshairState, int pass) { PlotOrientation orientation = plot.getOrientation(); if (orientation == PlotOrientation.HORIZONTAL) { drawHorizontalItem(g2, dataArea, info, plot, domainAxis, rangeAxis, dataset, series, item, crosshairState, pass); } else if (orientation == PlotOrientation.VERTICAL) { drawVerticalItem(g2, dataArea, info, plot, domainAxis, rangeAxis, dataset, series, item, crosshairState, pass); } } /** * Draws the visual representation of a single data item. * * @param g2 the graphics device. * @param dataArea the area within which the plot is being drawn. * @param info collects info about the drawing. * @param plot the plot (can be used to obtain standard color * information etc). * @param domainAxis the domain axis. * @param rangeAxis the range axis. * @param dataset the dataset (must be an instance of * {@link BoxAndWhiskerXYDataset}). * @param series the series index (zero-based). * @param item the item index (zero-based). * @param crosshairState crosshair information for the plot * (<code>null</code> permitted). * @param pass the pass index. */ public void drawHorizontalItem(Graphics2D g2, Rectangle2D dataArea, PlotRenderingInfo info, XYPlot plot, ValueAxis domainAxis, ValueAxis rangeAxis, XYDataset dataset, int series, int item, CrosshairState crosshairState, int pass) { // setup for collecting optional entity info... EntityCollection entities = null; if (info != null) { entities = info.getOwner().getEntityCollection(); } BoxAndWhiskerXYDataset boxAndWhiskerData = (BoxAndWhiskerXYDataset) dataset; Number x = boxAndWhiskerData.getX(series, item); Number yMax = boxAndWhiskerData.getMaxRegularValue(series, item); Number yMin = boxAndWhiskerData.getMinRegularValue(series, item); Number yMedian = boxAndWhiskerData.getMedianValue(series, item); Number yAverage = boxAndWhiskerData.getMeanValue(series, item); Number yQ1Median = boxAndWhiskerData.getQ1Value(series, item); Number yQ3Median = boxAndWhiskerData.getQ3Value(series, item); double xx = domainAxis.valueToJava2D(x.doubleValue(), dataArea, plot.getDomainAxisEdge()); RectangleEdge location = plot.getRangeAxisEdge(); double yyMax = rangeAxis.valueToJava2D(yMax.doubleValue(), dataArea, location); double yyMin = rangeAxis.valueToJava2D(yMin.doubleValue(), dataArea, location); double yyMedian = rangeAxis.valueToJava2D(yMedian.doubleValue(), dataArea, location); double yyAverage = 0.0; if (yAverage != null) { yyAverage = rangeAxis.valueToJava2D(yAverage.doubleValue(), dataArea, location); } double yyQ1Median = rangeAxis.valueToJava2D(yQ1Median.doubleValue(), dataArea, location); double yyQ3Median = rangeAxis.valueToJava2D(yQ3Median.doubleValue(), dataArea, location); double exactBoxWidth = getBoxWidth(); double width = exactBoxWidth; double dataAreaX = dataArea.getHeight(); double maxBoxPercent = 0.1; double maxBoxWidth = dataAreaX * maxBoxPercent; if (exactBoxWidth <= 0.0) { int itemCount = boxAndWhiskerData.getItemCount(series); exactBoxWidth = dataAreaX / itemCount * 4.5 / 7; if (exactBoxWidth < 3) { width = 3; } else if (exactBoxWidth > maxBoxWidth) { width = maxBoxWidth; } else { width = exactBoxWidth; } } g2.setPaint(getItemPaint(series, item)); Stroke s = getItemStroke(series, item); g2.setStroke(s); // draw the upper shadow g2.draw(new Line2D.Double(yyMax, xx, yyQ3Median, xx)); g2.draw(new Line2D.Double(yyMax, xx - width / 2, yyMax, xx + width / 2)); // draw the lower shadow g2.draw(new Line2D.Double(yyMin, xx, yyQ1Median, xx)); g2.draw(new Line2D.Double(yyMin, xx - width / 2, yyMin, xx + width / 2)); // draw the body Shape box = null; if (yyQ1Median < yyQ3Median) { box = new Rectangle2D.Double(yyQ1Median, xx - width / 2, yyQ3Median - yyQ1Median, width); } else { box = new Rectangle2D.Double(yyQ3Median, xx - width / 2, yyQ1Median - yyQ3Median, width); } if (this.fillBox) { g2.setPaint(lookupBoxPaint(series, item)); g2.fill(box); } g2.setStroke(getItemOutlineStroke(series, item)); g2.setPaint(getItemOutlinePaint(series, item)); g2.draw(box); // draw median g2.setPaint(getArtifactPaint()); g2.draw(new Line2D.Double(yyMedian, xx - width / 2, yyMedian, xx + width / 2)); // draw average - SPECIAL AIMS REQUIREMENT if (yAverage != null) { double aRadius = width / 4; // here we check that the average marker will in fact be visible // before drawing it... if ((yyAverage > (dataArea.getMinX() - aRadius)) && (yyAverage < (dataArea.getMaxX() + aRadius))) { Ellipse2D.Double avgEllipse = new Ellipse2D.Double( yyAverage - aRadius, xx - aRadius, aRadius * 2, aRadius * 2); g2.fill(avgEllipse); g2.draw(avgEllipse); } } // FIXME: draw outliers // add an entity for the item... if (entities != null && box.intersects(dataArea)) { addEntity(entities, box, dataset, series, item, yyAverage, xx); } } /** * Draws the visual representation of a single data item. * * @param g2 the graphics device. * @param dataArea the area within which the plot is being drawn. * @param info collects info about the drawing. * @param plot the plot (can be used to obtain standard color * information etc). * @param domainAxis the domain axis. * @param rangeAxis the range axis. * @param dataset the dataset (must be an instance of * {@link BoxAndWhiskerXYDataset}). * @param series the series index (zero-based). * @param item the item index (zero-based). * @param crosshairState crosshair information for the plot * (<code>null</code> permitted). * @param pass the pass index. */ public void drawVerticalItem(Graphics2D g2, Rectangle2D dataArea, PlotRenderingInfo info, XYPlot plot, ValueAxis domainAxis, ValueAxis rangeAxis, XYDataset dataset, int series, int item, CrosshairState crosshairState, int pass) { // setup for collecting optional entity info... EntityCollection entities = null; if (info != null) { entities = info.getOwner().getEntityCollection(); } BoxAndWhiskerXYDataset boxAndWhiskerData = (BoxAndWhiskerXYDataset) dataset; Number x = boxAndWhiskerData.getX(series, item); Number yMax = boxAndWhiskerData.getMaxRegularValue(series, item); Number yMin = boxAndWhiskerData.getMinRegularValue(series, item); Number yMedian = boxAndWhiskerData.getMedianValue(series, item); Number yAverage = boxAndWhiskerData.getMeanValue(series, item); Number yQ1Median = boxAndWhiskerData.getQ1Value(series, item); Number yQ3Median = boxAndWhiskerData.getQ3Value(series, item); List yOutliers = boxAndWhiskerData.getOutliers(series, item); double xx = domainAxis.valueToJava2D(x.doubleValue(), dataArea, plot.getDomainAxisEdge()); RectangleEdge location = plot.getRangeAxisEdge(); double yyMax = rangeAxis.valueToJava2D(yMax.doubleValue(), dataArea, location); double yyMin = rangeAxis.valueToJava2D(yMin.doubleValue(), dataArea, location); double yyMedian = rangeAxis.valueToJava2D(yMedian.doubleValue(), dataArea, location); double yyAverage = 0.0; if (yAverage != null) { yyAverage = rangeAxis.valueToJava2D(yAverage.doubleValue(), dataArea, location); } double yyQ1Median = rangeAxis.valueToJava2D(yQ1Median.doubleValue(), dataArea, location); double yyQ3Median = rangeAxis.valueToJava2D(yQ3Median.doubleValue(), dataArea, location); double yyOutlier; double exactBoxWidth = getBoxWidth(); double width = exactBoxWidth; double dataAreaX = dataArea.getMaxX() - dataArea.getMinX(); double maxBoxPercent = 0.1; double maxBoxWidth = dataAreaX * maxBoxPercent; if (exactBoxWidth <= 0.0) { int itemCount = boxAndWhiskerData.getItemCount(series); exactBoxWidth = dataAreaX / itemCount * 4.5 / 7; if (exactBoxWidth < 3) { width = 3; } else if (exactBoxWidth > maxBoxWidth) { width = maxBoxWidth; } else { width = exactBoxWidth; } } g2.setPaint(getItemPaint(series, item)); Stroke s = getItemStroke(series, item); g2.setStroke(s); // draw the upper shadow g2.draw(new Line2D.Double(xx, yyMax, xx, yyQ3Median)); g2.draw(new Line2D.Double(xx - width / 2, yyMax, xx + width / 2, yyMax)); // draw the lower shadow g2.draw(new Line2D.Double(xx, yyMin, xx, yyQ1Median)); g2.draw(new Line2D.Double(xx - width / 2, yyMin, xx + width / 2, yyMin)); // draw the body Shape box = null; if (yyQ1Median > yyQ3Median) { box = new Rectangle2D.Double(xx - width / 2, yyQ3Median, width, yyQ1Median - yyQ3Median); } else { box = new Rectangle2D.Double(xx - width / 2, yyQ1Median, width, yyQ3Median - yyQ1Median); } if (this.fillBox) { g2.setPaint(lookupBoxPaint(series, item)); g2.fill(box); } g2.setStroke(getItemOutlineStroke(series, item)); g2.setPaint(getItemOutlinePaint(series, item)); g2.draw(box); // draw median g2.setPaint(getArtifactPaint()); g2.draw(new Line2D.Double(xx - width / 2, yyMedian, xx + width / 2, yyMedian)); double aRadius = 0; // average radius double oRadius = width / 3; // outlier radius // draw average - SPECIAL AIMS REQUIREMENT if (yAverage != null) { aRadius = width / 4; // here we check that the average marker will in fact be visible // before drawing it... if ((yyAverage > (dataArea.getMinY() - aRadius)) && (yyAverage < (dataArea.getMaxY() + aRadius))) { Ellipse2D.Double avgEllipse = new Ellipse2D.Double(xx - aRadius, yyAverage - aRadius, aRadius * 2, aRadius * 2); g2.fill(avgEllipse); g2.draw(avgEllipse); } } List outliers = new ArrayList(); OutlierListCollection outlierListCollection = new OutlierListCollection(); /* From outlier array sort out which are outliers and put these into * an arraylist. If there are any farouts, set the flag on the * OutlierListCollection */ for (int i = 0; i < yOutliers.size(); i++) { double outlier = ((Number) yOutliers.get(i)).doubleValue(); if (outlier > boxAndWhiskerData.getMaxOutlier(series, item).doubleValue()) { outlierListCollection.setHighFarOut(true); } else if (outlier < boxAndWhiskerData.getMinOutlier(series, item).doubleValue()) { outlierListCollection.setLowFarOut(true); } else if (outlier > boxAndWhiskerData.getMaxRegularValue(series, item).doubleValue()) { yyOutlier = rangeAxis.valueToJava2D(outlier, dataArea, location); outliers.add(new Outlier(xx, yyOutlier, oRadius)); } else if (outlier < boxAndWhiskerData.getMinRegularValue(series, item).doubleValue()) { yyOutlier = rangeAxis.valueToJava2D(outlier, dataArea, location); outliers.add(new Outlier(xx, yyOutlier, oRadius)); } Collections.sort(outliers); } // Process outliers. Each outlier is either added to the appropriate // outlier list or a new outlier list is made for (Iterator iterator = outliers.iterator(); iterator.hasNext();) { Outlier outlier = (Outlier) iterator.next(); outlierListCollection.add(outlier); } // draw yOutliers double maxAxisValue = rangeAxis.valueToJava2D(rangeAxis.getUpperBound(), dataArea, location) + aRadius; double minAxisValue = rangeAxis.valueToJava2D(rangeAxis.getLowerBound(), dataArea, location) - aRadius; // draw outliers for (Iterator iterator = outlierListCollection.iterator(); iterator.hasNext();) { OutlierList list = (OutlierList) iterator.next(); Outlier outlier = list.getAveragedOutlier(); Point2D point = outlier.getPoint(); if (list.isMultiple()) { drawMultipleEllipse(point, width, oRadius, g2); } else { drawEllipse(point, oRadius, g2); } } // draw farout if (outlierListCollection.isHighFarOut()) { drawHighFarOut(aRadius, g2, xx, maxAxisValue); } if (outlierListCollection.isLowFarOut()) { drawLowFarOut(aRadius, g2, xx, minAxisValue); } // add an entity for the item... if (entities != null && box.intersects(dataArea)) { addEntity(entities, box, dataset, series, item, xx, yyAverage); } } /** * Draws an ellipse to represent an outlier. * * @param point the location. * @param oRadius the radius. * @param g2 the graphics device. */ protected void drawEllipse(Point2D point, double oRadius, Graphics2D g2) { Ellipse2D.Double dot = new Ellipse2D.Double(point.getX() + oRadius / 2, point.getY(), oRadius, oRadius); g2.draw(dot); } /** * Draws two ellipses to represent overlapping outliers. * * @param point the location. * @param boxWidth the box width. * @param oRadius the radius. * @param g2 the graphics device. */ protected void drawMultipleEllipse(Point2D point, double boxWidth, double oRadius, Graphics2D g2) { Ellipse2D.Double dot1 = new Ellipse2D.Double(point.getX() - (boxWidth / 2) + oRadius, point.getY(), oRadius, oRadius); Ellipse2D.Double dot2 = new Ellipse2D.Double(point.getX() + (boxWidth / 2), point.getY(), oRadius, oRadius); g2.draw(dot1); g2.draw(dot2); } /** * Draws a triangle to indicate the presence of far out values. * * @param aRadius the radius. * @param g2 the graphics device. * @param xx the x value. * @param m the max y value. */ protected void drawHighFarOut(double aRadius, Graphics2D g2, double xx, double m) { double side = aRadius * 2; g2.draw(new Line2D.Double(xx - side, m + side, xx + side, m + side)); g2.draw(new Line2D.Double(xx - side, m + side, xx, m)); g2.draw(new Line2D.Double(xx + side, m + side, xx, m)); } /** * Draws a triangle to indicate the presence of far out values. * * @param aRadius the radius. * @param g2 the graphics device. * @param xx the x value. * @param m the min y value. */ protected void drawLowFarOut(double aRadius, Graphics2D g2, double xx, double m) { double side = aRadius * 2; g2.draw(new Line2D.Double(xx - side, m - side, xx + side, m - side)); g2.draw(new Line2D.Double(xx - side, m - side, xx, m)); g2.draw(new Line2D.Double(xx + side, m - side, xx, m)); } /** * Tests this renderer for equality with another object. * * @param obj the object (<code>null</code> permitted). * * @return <code>true</code> or <code>false</code>. */ public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof XYBoxAndWhiskerRenderer)) { return false; } if (!super.equals(obj)) { return false; } XYBoxAndWhiskerRenderer that = (XYBoxAndWhiskerRenderer) obj; if (this.boxWidth != that.getBoxWidth()) { return false; } if (!PaintUtilities.equal(this.boxPaint, that.boxPaint)) { return false; } if (!PaintUtilities.equal(this.artifactPaint, that.artifactPaint)) { return false; } if (this.fillBox != that.fillBox) { return false; } return true; } /** * Provides serialization support. * * @param stream the output stream. * * @throws IOException if there is an I/O error. */ private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); SerialUtilities.writePaint(this.boxPaint, stream); SerialUtilities.writePaint(this.artifactPaint, stream); } /** * Provides serialization support. * * @param stream the input stream. * * @throws IOException if there is an I/O error. * @throws ClassNotFoundException if there is a classpath problem. */ private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); this.boxPaint = SerialUtilities.readPaint(stream); this.artifactPaint = SerialUtilities.readPaint(stream); } /** * Returns a clone of the renderer. * * @return A clone. * * @throws CloneNotSupportedException if the renderer cannot be cloned. */ public Object clone() throws CloneNotSupportedException { return super.clone(); } }
source/org/jfree/chart/renderer/xy/XYBoxAndWhiskerRenderer.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2008, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ---------------------------- * XYBoxAndWhiskerRenderer.java * ---------------------------- * (C) Copyright 2003-2008, by David Browning and Contributors. * * Original Author: David Browning (for Australian Institute of Marine * Science); * Contributor(s): David Gilbert (for Object Refinery Limited); * * Changes * ------- * 05-Aug-2003 : Version 1, contributed by David Browning. Based on code in the * CandlestickRenderer class. Additional modifications by David * Gilbert to make the code work with 0.9.10 changes (DG); * 08-Aug-2003 : Updated some of the Javadoc * Allowed BoxAndwhiskerDataset Average value to be null - the * average value is an AIMS requirement * Allow the outlier and farout coefficients to be set - though * at the moment this only affects the calculation of farouts. * Added artifactPaint variable and setter/getter * 12-Aug-2003 Rewrote code to sort out and process outliers to take * advantage of changes in DefaultBoxAndWhiskerDataset * Added a limit of 10% for width of box should no width be * specified...maybe this should be setable??? * 20-Aug-2003 : Implemented Cloneable and PublicCloneable (DG); * 08-Sep-2003 : Changed ValueAxis API (DG); * 16-Sep-2003 : Changed ChartRenderingInfo --> PlotRenderingInfo (DG); * 25-Feb-2004 : Replaced CrosshairInfo with CrosshairState (DG); * 23-Apr-2004 : Added fillBox attribute, extended equals() method and fixed * serialization issue (DG); * 29-Apr-2004 : Fixed problem with drawing upper and lower shadows - bug id * 944011 (DG); * 15-Jul-2004 : Switched getX() with getXValue() and getY() with * getYValue() (DG); * 01-Oct-2004 : Renamed 'paint' --> 'boxPaint' to avoid conflict with * inherited attribute (DG); * 10-Jun-2005 : Updated equals() to handle GradientPaint (DG); * 06-Oct-2005 : Removed setPaint() call in drawItem(), it is causing a * loop (DG); * ------------- JFREECHART 1.0.x --------------------------------------------- * 02-Feb-2007 : Removed author tags from all over JFreeChart sources (DG); * 05-Feb-2007 : Added event notifications and fixed drawing for horizontal * plot orientation (DG); * 13-Jun-2007 : Replaced deprecated method call (DG); * 03-Jan-2008 : Check visibility of average marker before drawing it (DG); * 27-Mar-2008 : If boxPaint is null, revert to itemPaint (DG); * */ package org.jfree.chart.renderer.xy; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Shape; import java.awt.Stroke; import java.awt.geom.Ellipse2D; import java.awt.geom.Line2D; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.entity.EntityCollection; import org.jfree.chart.event.RendererChangeEvent; import org.jfree.chart.labels.BoxAndWhiskerXYToolTipGenerator; import org.jfree.chart.plot.CrosshairState; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.PlotRenderingInfo; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.renderer.Outlier; import org.jfree.chart.renderer.OutlierList; import org.jfree.chart.renderer.OutlierListCollection; import org.jfree.data.statistics.BoxAndWhiskerXYDataset; import org.jfree.data.xy.XYDataset; import org.jfree.io.SerialUtilities; import org.jfree.ui.RectangleEdge; import org.jfree.util.PaintUtilities; import org.jfree.util.PublicCloneable; /** * A renderer that draws box-and-whisker items on an {@link XYPlot}. This * renderer requires a {@link BoxAndWhiskerXYDataset}). * <P> * This renderer does not include any code to calculate the crosshair point. */ public class XYBoxAndWhiskerRenderer extends AbstractXYItemRenderer implements XYItemRenderer, Cloneable, PublicCloneable, Serializable { /** For serialization. */ private static final long serialVersionUID = -8020170108532232324L; /** The box width. */ private double boxWidth; /** The paint used to fill the box. */ private transient Paint boxPaint; /** A flag that controls whether or not the box is filled. */ private boolean fillBox; /** * The paint used to draw various artifacts such as outliers, farout * symbol, average ellipse and median line. */ private transient Paint artifactPaint = Color.black; /** * Creates a new renderer for box and whisker charts. */ public XYBoxAndWhiskerRenderer() { this(-1.0); } /** * Creates a new renderer for box and whisker charts. * <P> * Use -1 for the box width if you prefer the width to be calculated * automatically. * * @param boxWidth the box width. */ public XYBoxAndWhiskerRenderer(double boxWidth) { super(); this.boxWidth = boxWidth; this.boxPaint = Color.green; this.fillBox = true; setBaseToolTipGenerator(new BoxAndWhiskerXYToolTipGenerator()); } /** * Returns the width of each box. * * @return The box width. * * @see #setBoxWidth(double) */ public double getBoxWidth() { return this.boxWidth; } /** * Sets the box width and sends a {@link RendererChangeEvent} to all * registered listeners. * <P> * If you set the width to a negative value, the renderer will calculate * the box width automatically based on the space available on the chart. * * @param width the width. * * @see #getBoxWidth() */ public void setBoxWidth(double width) { if (width != this.boxWidth) { this.boxWidth = width; fireChangeEvent(); } } /** * Returns the paint used to fill boxes. * * @return The paint (possibly <code>null</code>). * * @see #setBoxPaint(Paint) */ public Paint getBoxPaint() { return this.boxPaint; } /** * Sets the paint used to fill boxes and sends a {@link RendererChangeEvent} * to all registered listeners. * * @param paint the paint (<code>null</code> permitted). * * @see #getBoxPaint() */ public void setBoxPaint(Paint paint) { this.boxPaint = paint; fireChangeEvent(); } /** * Returns the flag that controls whether or not the box is filled. * * @return A boolean. * * @see #setFillBox(boolean) */ public boolean getFillBox() { return this.fillBox; } /** * Sets the flag that controls whether or not the box is filled and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param flag the flag. * * @see #setFillBox(boolean) */ public void setFillBox(boolean flag) { this.fillBox = flag; fireChangeEvent(); } /** * Returns the paint used to paint the various artifacts such as outliers, * farout symbol, median line and the averages ellipse. * * @return The paint (never <code>null</code>). * * @see #setArtifactPaint(Paint) */ public Paint getArtifactPaint() { return this.artifactPaint; } /** * Sets the paint used to paint the various artifacts such as outliers, * farout symbol, median line and the averages ellipse, and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param paint the paint (<code>null</code> not permitted). * * @see #getArtifactPaint() */ public void setArtifactPaint(Paint paint) { if (paint == null) { throw new IllegalArgumentException("Null 'paint' argument."); } this.artifactPaint = paint; fireChangeEvent(); } /** * Returns the box paint or, if this is <code>null</code>, the item * paint. * * @param series the series index. * @param item the item index. * * @return The paint used to fill the box for the specified item (never * <code>null</code>). */ protected Paint lookupBoxPaint(int series, int item) { Paint p = getBoxPaint(); if (p != null) { return p; } else { // TODO: could change this to itemFillPaint(). For backwards // compatibility, it might require a useFillPaint flag. return getItemPaint(series, item); } } /** * Draws the visual representation of a single data item. * * @param g2 the graphics device. * @param state the renderer state. * @param dataArea the area within which the plot is being drawn. * @param info collects info about the drawing. * @param plot the plot (can be used to obtain standard color * information etc). * @param domainAxis the domain axis. * @param rangeAxis the range axis. * @param dataset the dataset (must be an instance of * {@link BoxAndWhiskerXYDataset}). * @param series the series index (zero-based). * @param item the item index (zero-based). * @param crosshairState crosshair information for the plot * (<code>null</code> permitted). * @param pass the pass index. */ public void drawItem(Graphics2D g2, XYItemRendererState state, Rectangle2D dataArea, PlotRenderingInfo info, XYPlot plot, ValueAxis domainAxis, ValueAxis rangeAxis, XYDataset dataset, int series, int item, CrosshairState crosshairState, int pass) { PlotOrientation orientation = plot.getOrientation(); if (orientation == PlotOrientation.HORIZONTAL) { drawHorizontalItem(g2, dataArea, info, plot, domainAxis, rangeAxis, dataset, series, item, crosshairState, pass); } else if (orientation == PlotOrientation.VERTICAL) { drawVerticalItem(g2, dataArea, info, plot, domainAxis, rangeAxis, dataset, series, item, crosshairState, pass); } } /** * Draws the visual representation of a single data item. * * @param g2 the graphics device. * @param dataArea the area within which the plot is being drawn. * @param info collects info about the drawing. * @param plot the plot (can be used to obtain standard color * information etc). * @param domainAxis the domain axis. * @param rangeAxis the range axis. * @param dataset the dataset (must be an instance of * {@link BoxAndWhiskerXYDataset}). * @param series the series index (zero-based). * @param item the item index (zero-based). * @param crosshairState crosshair information for the plot * (<code>null</code> permitted). * @param pass the pass index. */ public void drawHorizontalItem(Graphics2D g2, Rectangle2D dataArea, PlotRenderingInfo info, XYPlot plot, ValueAxis domainAxis, ValueAxis rangeAxis, XYDataset dataset, int series, int item, CrosshairState crosshairState, int pass) { // setup for collecting optional entity info... EntityCollection entities = null; if (info != null) { entities = info.getOwner().getEntityCollection(); } BoxAndWhiskerXYDataset boxAndWhiskerData = (BoxAndWhiskerXYDataset) dataset; Number x = boxAndWhiskerData.getX(series, item); Number yMax = boxAndWhiskerData.getMaxRegularValue(series, item); Number yMin = boxAndWhiskerData.getMinRegularValue(series, item); Number yMedian = boxAndWhiskerData.getMedianValue(series, item); Number yAverage = boxAndWhiskerData.getMeanValue(series, item); Number yQ1Median = boxAndWhiskerData.getQ1Value(series, item); Number yQ3Median = boxAndWhiskerData.getQ3Value(series, item); double xx = domainAxis.valueToJava2D(x.doubleValue(), dataArea, plot.getDomainAxisEdge()); RectangleEdge location = plot.getRangeAxisEdge(); double yyMax = rangeAxis.valueToJava2D(yMax.doubleValue(), dataArea, location); double yyMin = rangeAxis.valueToJava2D(yMin.doubleValue(), dataArea, location); double yyMedian = rangeAxis.valueToJava2D(yMedian.doubleValue(), dataArea, location); double yyAverage = 0.0; if (yAverage != null) { yyAverage = rangeAxis.valueToJava2D(yAverage.doubleValue(), dataArea, location); } double yyQ1Median = rangeAxis.valueToJava2D(yQ1Median.doubleValue(), dataArea, location); double yyQ3Median = rangeAxis.valueToJava2D(yQ3Median.doubleValue(), dataArea, location); double exactBoxWidth = getBoxWidth(); double width = exactBoxWidth; double dataAreaX = dataArea.getHeight(); double maxBoxPercent = 0.1; double maxBoxWidth = dataAreaX * maxBoxPercent; if (exactBoxWidth <= 0.0) { int itemCount = boxAndWhiskerData.getItemCount(series); exactBoxWidth = dataAreaX / itemCount * 4.5 / 7; if (exactBoxWidth < 3) { width = 3; } else if (exactBoxWidth > maxBoxWidth) { width = maxBoxWidth; } else { width = exactBoxWidth; } } g2.setPaint(getItemPaint(series, item)); Stroke s = getItemStroke(series, item); g2.setStroke(s); // draw the upper shadow g2.draw(new Line2D.Double(yyMax, xx, yyQ3Median, xx)); g2.draw(new Line2D.Double(yyMax, xx - width / 2, yyMax, xx + width / 2)); // draw the lower shadow g2.draw(new Line2D.Double(yyMin, xx, yyQ1Median, xx)); g2.draw(new Line2D.Double(yyMin, xx - width / 2, yyMin, xx + width / 2)); // draw the body Shape box = null; if (yyQ1Median < yyQ3Median) { box = new Rectangle2D.Double(yyQ1Median, xx - width / 2, yyQ3Median - yyQ1Median, width); } else { box = new Rectangle2D.Double(yyQ3Median, xx - width / 2, yyQ1Median - yyQ3Median, width); } if (this.fillBox) { g2.setPaint(lookupBoxPaint(series, item)); g2.fill(box); } g2.setStroke(getItemOutlineStroke(series, item)); g2.setPaint(getItemOutlinePaint(series, item)); g2.draw(box); // draw median g2.setPaint(getArtifactPaint()); g2.draw(new Line2D.Double(yyMedian, xx - width / 2, yyMedian, xx + width / 2)); // draw average - SPECIAL AIMS REQUIREMENT if (yAverage != null) { double aRadius = width / 4; // here we check that the average marker will in fact be visible // before drawing it... if ((yyAverage > (dataArea.getMinX() - aRadius)) && (yyAverage < (dataArea.getMaxX() + aRadius))) { Ellipse2D.Double avgEllipse = new Ellipse2D.Double( yyAverage - aRadius, xx - aRadius, aRadius * 2, aRadius * 2); g2.fill(avgEllipse); g2.draw(avgEllipse); } } // FIXME: draw outliers // add an entity for the item... if (entities != null && box.intersects(dataArea)) { addEntity(entities, box, dataset, series, item, yyAverage, xx); } } /** * Draws the visual representation of a single data item. * * @param g2 the graphics device. * @param dataArea the area within which the plot is being drawn. * @param info collects info about the drawing. * @param plot the plot (can be used to obtain standard color * information etc). * @param domainAxis the domain axis. * @param rangeAxis the range axis. * @param dataset the dataset (must be an instance of * {@link BoxAndWhiskerXYDataset}). * @param series the series index (zero-based). * @param item the item index (zero-based). * @param crosshairState crosshair information for the plot * (<code>null</code> permitted). * @param pass the pass index. */ public void drawVerticalItem(Graphics2D g2, Rectangle2D dataArea, PlotRenderingInfo info, XYPlot plot, ValueAxis domainAxis, ValueAxis rangeAxis, XYDataset dataset, int series, int item, CrosshairState crosshairState, int pass) { // setup for collecting optional entity info... EntityCollection entities = null; if (info != null) { entities = info.getOwner().getEntityCollection(); } BoxAndWhiskerXYDataset boxAndWhiskerData = (BoxAndWhiskerXYDataset) dataset; Number x = boxAndWhiskerData.getX(series, item); Number yMax = boxAndWhiskerData.getMaxRegularValue(series, item); Number yMin = boxAndWhiskerData.getMinRegularValue(series, item); Number yMedian = boxAndWhiskerData.getMedianValue(series, item); Number yAverage = boxAndWhiskerData.getMeanValue(series, item); Number yQ1Median = boxAndWhiskerData.getQ1Value(series, item); Number yQ3Median = boxAndWhiskerData.getQ3Value(series, item); List yOutliers = boxAndWhiskerData.getOutliers(series, item); double xx = domainAxis.valueToJava2D(x.doubleValue(), dataArea, plot.getDomainAxisEdge()); RectangleEdge location = plot.getRangeAxisEdge(); double yyMax = rangeAxis.valueToJava2D(yMax.doubleValue(), dataArea, location); double yyMin = rangeAxis.valueToJava2D(yMin.doubleValue(), dataArea, location); double yyMedian = rangeAxis.valueToJava2D(yMedian.doubleValue(), dataArea, location); double yyAverage = 0.0; if (yAverage != null) { yyAverage = rangeAxis.valueToJava2D(yAverage.doubleValue(), dataArea, location); } double yyQ1Median = rangeAxis.valueToJava2D(yQ1Median.doubleValue(), dataArea, location); double yyQ3Median = rangeAxis.valueToJava2D(yQ3Median.doubleValue(), dataArea, location); double yyOutlier; double exactBoxWidth = getBoxWidth(); double width = exactBoxWidth; double dataAreaX = dataArea.getMaxX() - dataArea.getMinX(); double maxBoxPercent = 0.1; double maxBoxWidth = dataAreaX * maxBoxPercent; if (exactBoxWidth <= 0.0) { int itemCount = boxAndWhiskerData.getItemCount(series); exactBoxWidth = dataAreaX / itemCount * 4.5 / 7; if (exactBoxWidth < 3) { width = 3; } else if (exactBoxWidth > maxBoxWidth) { width = maxBoxWidth; } else { width = exactBoxWidth; } } g2.setPaint(getItemPaint(series, item)); Stroke s = getItemStroke(series, item); g2.setStroke(s); // draw the upper shadow g2.draw(new Line2D.Double(xx, yyMax, xx, yyQ3Median)); g2.draw(new Line2D.Double(xx - width / 2, yyMax, xx + width / 2, yyMax)); // draw the lower shadow g2.draw(new Line2D.Double(xx, yyMin, xx, yyQ1Median)); g2.draw(new Line2D.Double(xx - width / 2, yyMin, xx + width / 2, yyMin)); // draw the body Shape box = null; if (yyQ1Median > yyQ3Median) { box = new Rectangle2D.Double(xx - width / 2, yyQ3Median, width, yyQ1Median - yyQ3Median); } else { box = new Rectangle2D.Double(xx - width / 2, yyQ1Median, width, yyQ3Median - yyQ1Median); } if (this.fillBox) { g2.setPaint(lookupBoxPaint(series, item)); g2.fill(box); } g2.setStroke(getItemOutlineStroke(series, item)); g2.setPaint(getItemOutlinePaint(series, item)); g2.draw(box); // draw median g2.setPaint(getArtifactPaint()); g2.draw(new Line2D.Double(xx - width / 2, yyMedian, xx + width / 2, yyMedian)); double aRadius = 0; // average radius double oRadius = width / 3; // outlier radius // draw average - SPECIAL AIMS REQUIREMENT if (yAverage != null) { aRadius = width / 4; // here we check that the average marker will in fact be visible // before drawing it... if ((yyAverage > (dataArea.getMinY() - aRadius)) && (yyAverage < (dataArea.getMaxY() + aRadius))) { Ellipse2D.Double avgEllipse = new Ellipse2D.Double(xx - aRadius, yyAverage - aRadius, aRadius * 2, aRadius * 2); g2.fill(avgEllipse); g2.draw(avgEllipse); } } List outliers = new ArrayList(); OutlierListCollection outlierListCollection = new OutlierListCollection(); /* From outlier array sort out which are outliers and put these into * an arraylist. If there are any farouts, set the flag on the * OutlierListCollection */ for (int i = 0; i < yOutliers.size(); i++) { double outlier = ((Number) yOutliers.get(i)).doubleValue(); if (outlier > boxAndWhiskerData.getMaxOutlier(series, item).doubleValue()) { outlierListCollection.setHighFarOut(true); } else if (outlier < boxAndWhiskerData.getMinOutlier(series, item).doubleValue()) { outlierListCollection.setLowFarOut(true); } else if (outlier > boxAndWhiskerData.getMaxRegularValue(series, item).doubleValue()) { yyOutlier = rangeAxis.valueToJava2D(outlier, dataArea, location); outliers.add(new Outlier(xx, yyOutlier, oRadius)); } else if (outlier < boxAndWhiskerData.getMinRegularValue(series, item).doubleValue()) { yyOutlier = rangeAxis.valueToJava2D(outlier, dataArea, location); outliers.add(new Outlier(xx, yyOutlier, oRadius)); } Collections.sort(outliers); } // Process outliers. Each outlier is either added to the appropriate // outlier list or a new outlier list is made for (Iterator iterator = outliers.iterator(); iterator.hasNext();) { Outlier outlier = (Outlier) iterator.next(); outlierListCollection.add(outlier); } // draw yOutliers double maxAxisValue = rangeAxis.valueToJava2D(rangeAxis.getUpperBound(), dataArea, location) + aRadius; double minAxisValue = rangeAxis.valueToJava2D(rangeAxis.getLowerBound(), dataArea, location) - aRadius; // draw outliers for (Iterator iterator = outlierListCollection.iterator(); iterator.hasNext();) { OutlierList list = (OutlierList) iterator.next(); Outlier outlier = list.getAveragedOutlier(); Point2D point = outlier.getPoint(); if (list.isMultiple()) { drawMultipleEllipse(point, width, oRadius, g2); } else { drawEllipse(point, oRadius, g2); } } // draw farout if (outlierListCollection.isHighFarOut()) { drawHighFarOut(aRadius, g2, xx, maxAxisValue); } if (outlierListCollection.isLowFarOut()) { drawLowFarOut(aRadius, g2, xx, minAxisValue); } // add an entity for the item... if (entities != null && box.intersects(dataArea)) { addEntity(entities, box, dataset, series, item, xx, yyAverage); } } /** * Draws an ellipse to represent an outlier. * * @param point the location. * @param oRadius the radius. * @param g2 the graphics device. */ protected void drawEllipse(Point2D point, double oRadius, Graphics2D g2) { Ellipse2D.Double dot = new Ellipse2D.Double(point.getX() + oRadius / 2, point.getY(), oRadius, oRadius); g2.draw(dot); } /** * Draws two ellipses to represent overlapping outliers. * * @param point the location. * @param boxWidth the box width. * @param oRadius the radius. * @param g2 the graphics device. */ protected void drawMultipleEllipse(Point2D point, double boxWidth, double oRadius, Graphics2D g2) { Ellipse2D.Double dot1 = new Ellipse2D.Double(point.getX() - (boxWidth / 2) + oRadius, point.getY(), oRadius, oRadius); Ellipse2D.Double dot2 = new Ellipse2D.Double(point.getX() + (boxWidth / 2), point.getY(), oRadius, oRadius); g2.draw(dot1); g2.draw(dot2); } /** * Draws a triangle to indicate the presence of far out values. * * @param aRadius the radius. * @param g2 the graphics device. * @param xx the x value. * @param m the max y value. */ protected void drawHighFarOut(double aRadius, Graphics2D g2, double xx, double m) { double side = aRadius * 2; g2.draw(new Line2D.Double(xx - side, m + side, xx + side, m + side)); g2.draw(new Line2D.Double(xx - side, m + side, xx, m)); g2.draw(new Line2D.Double(xx + side, m + side, xx, m)); } /** * Draws a triangle to indicate the presence of far out values. * * @param aRadius the radius. * @param g2 the graphics device. * @param xx the x value. * @param m the min y value. */ protected void drawLowFarOut(double aRadius, Graphics2D g2, double xx, double m) { double side = aRadius * 2; g2.draw(new Line2D.Double(xx - side, m - side, xx + side, m - side)); g2.draw(new Line2D.Double(xx - side, m - side, xx, m)); g2.draw(new Line2D.Double(xx + side, m - side, xx, m)); } /** * Tests this renderer for equality with another object. * * @param obj the object (<code>null</code> permitted). * * @return <code>true</code> or <code>false</code>. */ public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof XYBoxAndWhiskerRenderer)) { return false; } if (!super.equals(obj)) { return false; } XYBoxAndWhiskerRenderer that = (XYBoxAndWhiskerRenderer) obj; if (this.boxWidth != that.getBoxWidth()) { return false; } if (!PaintUtilities.equal(this.boxPaint, that.boxPaint)) { return false; } if (!PaintUtilities.equal(this.artifactPaint, that.artifactPaint)) { return false; } if (this.fillBox != that.fillBox) { return false; } return true; } /** * Provides serialization support. * * @param stream the output stream. * * @throws IOException if there is an I/O error. */ private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); SerialUtilities.writePaint(this.boxPaint, stream); SerialUtilities.writePaint(this.artifactPaint, stream); } /** * Provides serialization support. * * @param stream the input stream. * * @throws IOException if there is an I/O error. * @throws ClassNotFoundException if there is a classpath problem. */ private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); this.boxPaint = SerialUtilities.readPaint(stream); this.artifactPaint = SerialUtilities.readPaint(stream); } /** * Returns a clone of the renderer. * * @return A clone. * * @throws CloneNotSupportedException if the renderer cannot be cloned. */ public Object clone() throws CloneNotSupportedException { return super.clone(); } }
Added @since tag. git-svn-id: ca96c60061366ac92493e2142a352bb838ea8caa@818 4df5dd95-b682-48b0-b31b-748e37b65e73
source/org/jfree/chart/renderer/xy/XYBoxAndWhiskerRenderer.java
Added @since tag.
Java
unlicense
b0b5d335ed37f9240ade53d8fa24cf749d626861
0
Samourai-Wallet/samourai-wallet-android
package com.samourai.wallet.payload; import android.content.Context; import android.content.SharedPreferences; import android.os.Build; import android.os.Environment; import android.preference.PreferenceManager; import android.widget.Toast; //import android.util.Log; import com.samourai.wallet.R; import com.samourai.wallet.SamouraiWallet; import com.samourai.wallet.SendActivity; import com.samourai.wallet.access.AccessFactory; import com.samourai.wallet.api.APIFactory; import com.samourai.wallet.bip47.BIP47Meta; import com.samourai.wallet.bip47.BIP47Util; import com.samourai.wallet.crypto.AESUtil; import com.samourai.wallet.crypto.DecryptionException; import com.samourai.wallet.hd.HD_Account; import com.samourai.wallet.hd.HD_Wallet; import com.samourai.wallet.hd.HD_WalletFactory; import com.samourai.wallet.ricochet.RicochetMeta; import com.samourai.wallet.segwit.BIP49Util; import com.samourai.wallet.segwit.BIP84Util; import com.samourai.wallet.send.BlockedUTXO; import com.samourai.wallet.util.AddressFactory; import com.samourai.wallet.util.BatchSendUtil; import com.samourai.wallet.util.CharSequenceX; import com.samourai.wallet.util.PrefsUtil; import com.samourai.wallet.send.RBFUtil; import com.samourai.wallet.util.SIMUtil; import com.samourai.wallet.util.SendAddressUtil; import com.samourai.wallet.JSONRPC.TrustedNodeUtil; import com.samourai.wallet.util.TorUtil; import com.samourai.wallet.util.WebUtil; import org.apache.commons.codec.DecoderException; import org.bitcoinj.core.AddressFormatException; import org.bitcoinj.core.NetworkParameters; import org.bitcoinj.crypto.MnemonicException; import org.bitcoinj.params.MainNetParams; import org.bitcoinj.params.TestNet3Params; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.RandomAccessFile; import java.io.UnsupportedEncodingException; import java.io.Writer; import java.security.SecureRandom; public class PayloadUtil { private final static String dataDir = "wallet"; private final static String strFilename = "samourai.dat"; private final static String strTmpFilename = "samourai.tmp"; private final static String strBackupFilename = "samourai.sav"; private final static String strOptionalBackupDir = "/samourai"; private final static String strOptionalFilename = "samourai.txt"; private static Context context = null; private static PayloadUtil instance = null; private PayloadUtil() { ; } public static PayloadUtil getInstance(Context ctx) { context = ctx; if (instance == null) { instance = new PayloadUtil(); } return instance; } public File getBackupFile() { String directory = Environment.DIRECTORY_DOCUMENTS; File dir = null; if(context.getPackageName().contains("staging")) { dir = Environment.getExternalStoragePublicDirectory(directory + strOptionalBackupDir + "/staging"); } else { dir = Environment.getExternalStoragePublicDirectory(directory + strOptionalBackupDir); } File file = new File(dir, strOptionalFilename); return file; } public JSONObject putPayload(String data, boolean external) { JSONObject obj = new JSONObject(); try { obj.put("version", 1); obj.put("payload", data); obj.put("external", external); } catch(JSONException je) { return null; } return obj; } public boolean hasPayload(Context ctx) { File dir = ctx.getDir(dataDir, Context.MODE_PRIVATE); File file = new File(dir, strFilename); if(file.exists()) { return true; } return false; } public synchronized void wipe() throws IOException { BIP47Util.getInstance(context).reset(); BIP47Meta.getInstance().clear(); BIP49Util.getInstance(context).reset(); BIP84Util.getInstance(context).reset(); APIFactory.getInstance(context).reset(); try { int nbAccounts = HD_WalletFactory.getInstance(context).get().getAccounts().size(); for(int i = 0; i < nbAccounts; i++) { HD_WalletFactory.getInstance(context).get().getAccount(i).getReceive().setAddrIdx(0); HD_WalletFactory.getInstance(context).get().getAccount(i).getChange().setAddrIdx(0); AddressFactory.getInstance().setHighestTxReceiveIdx(i, 0); AddressFactory.getInstance().setHighestTxChangeIdx(i, 0); } HD_WalletFactory.getInstance(context).set(null); } catch(MnemonicException.MnemonicLengthException mle) { mle.printStackTrace(); } HD_WalletFactory.getInstance(context).clear(); File dir = context.getDir(dataDir, Context.MODE_PRIVATE); File datfile = new File(dir, strFilename); File tmpfile = new File(dir, strTmpFilename); if(tmpfile.exists()) { secureDelete(tmpfile); } if(datfile.exists()) { secureDelete(datfile); try { serialize(new JSONObject("{}"), new CharSequenceX("")); } catch(JSONException je) { je.printStackTrace(); } catch(Exception e) { e.printStackTrace(); } } } public JSONObject getPayload() { try { JSONObject wallet = new JSONObject(); wallet.put("testnet", SamouraiWallet.getInstance().isTestNet() ? true : false); if(HD_WalletFactory.getInstance(context).get().getSeedHex() != null) { wallet.put("seed", HD_WalletFactory.getInstance(context).get().getSeedHex()); wallet.put("passphrase", HD_WalletFactory.getInstance(context).get().getPassphrase()); // obj.put("mnemonic", getMnemonic()); } JSONArray accts = new JSONArray(); for(HD_Account acct : HD_WalletFactory.getInstance(context).get().getAccounts()) { accts.put(acct.toJSON(44)); } wallet.put("accounts", accts); // // export BIP47 payment code for debug payload // try { wallet.put("payment_code", BIP47Util.getInstance(context).getPaymentCode().toString()); } catch(AddressFormatException afe) { ; } // // export BIP49 account for debug payload // JSONArray bip49_account = new JSONArray(); bip49_account.put(BIP49Util.getInstance(context).getWallet().getAccount(0).toJSON(49)); wallet.put("bip49_accounts", bip49_account); // // export BIP84 account for debug payload // JSONArray bip84_account = new JSONArray(); bip84_account.put(BIP84Util.getInstance(context).getWallet().getAccount(0).toJSON(84)); wallet.put("bip84_accounts", bip84_account); // // can remove ??? // /* obj.put("receiveIdx", mAccounts.get(0).getReceive().getAddrIdx()); obj.put("changeIdx", mAccounts.get(0).getChange().getAddrIdx()); */ JSONObject meta = new JSONObject(); meta.put("version_name", context.getText(R.string.version_name)); meta.put("android_release", Build.VERSION.RELEASE == null ? "" : Build.VERSION.RELEASE); meta.put("device_manufacturer", Build.MANUFACTURER == null ? "" : Build.MANUFACTURER); meta.put("device_model", Build.MODEL == null ? "" : Build.MODEL); meta.put("device_product", Build.PRODUCT == null ? "" : Build.PRODUCT); meta.put("prev_balance", APIFactory.getInstance(context).getXpubBalance()); meta.put("sent_tos", SendAddressUtil.getInstance().toJSON()); meta.put("batch_send", BatchSendUtil.getInstance().toJSON()); meta.put("use_segwit", PrefsUtil.getInstance(context).getValue(PrefsUtil.USE_SEGWIT, true)); meta.put("use_like_typed_change", PrefsUtil.getInstance(context).getValue(PrefsUtil.USE_LIKE_TYPED_CHANGE, true)); meta.put("spend_type", PrefsUtil.getInstance(context).getValue(PrefsUtil.SPEND_TYPE, SendActivity.SPEND_BOLTZMANN)); meta.put("use_boltzmann", PrefsUtil.getInstance(context).getValue(PrefsUtil.USE_BOLTZMANN, true)); meta.put("rbf_opt_in", PrefsUtil.getInstance(context).getValue(PrefsUtil.RBF_OPT_IN, false)); meta.put("bip47", BIP47Meta.getInstance().toJSON()); meta.put("pin", AccessFactory.getInstance().getPIN()); meta.put("pin2", AccessFactory.getInstance().getPIN2()); meta.put("ricochet", RicochetMeta.getInstance(context).toJSON()); meta.put("trusted_node", TrustedNodeUtil.getInstance().toJSON()); meta.put("rbfs", RBFUtil.getInstance().toJSON()); meta.put("tor", TorUtil.getInstance(context).toJSON()); meta.put("blocked_utxos", BlockedUTXO.getInstance().toJSON()); meta.put("explorer", PrefsUtil.getInstance(context).getValue(PrefsUtil.BLOCK_EXPLORER, 0)); meta.put("trusted_no", PrefsUtil.getInstance(context).getValue(PrefsUtil.ALERT_MOBILE_NO, "")); meta.put("scramble_pin", PrefsUtil.getInstance(context).getValue(PrefsUtil.SCRAMBLE_PIN, false)); meta.put("haptic_pin", PrefsUtil.getInstance(context).getValue(PrefsUtil.HAPTIC_PIN, true)); meta.put("auto_backup", PrefsUtil.getInstance(context).getValue(PrefsUtil.AUTO_BACKUP, true)); meta.put("remote", PrefsUtil.getInstance(context).getValue(PrefsUtil.ACCEPT_REMOTE, false)); meta.put("use_trusted", PrefsUtil.getInstance(context).getValue(PrefsUtil.TRUSTED_LOCK, false)); meta.put("check_sim", PrefsUtil.getInstance(context).getValue(PrefsUtil.CHECK_SIM, false)); meta.put("fiat", PrefsUtil.getInstance(context).getValue(PrefsUtil.CURRENT_FIAT, "USD")); meta.put("fiat_sel", PrefsUtil.getInstance(context).getValue(PrefsUtil.CURRENT_FIAT_SEL, 0)); meta.put("fx", PrefsUtil.getInstance(context).getValue(PrefsUtil.CURRENT_EXCHANGE, "LocalBitcoins.com")); meta.put("fx_sel", PrefsUtil.getInstance(context).getValue(PrefsUtil.CURRENT_EXCHANGE_SEL, 0)); meta.put("use_trusted_node", PrefsUtil.getInstance(context).getValue(PrefsUtil.USE_TRUSTED_NODE, false)); meta.put("fee_provider_sel", PrefsUtil.getInstance(context).getValue(PrefsUtil.FEE_PROVIDER_SEL, 0)); meta.put("broadcast_tx", PrefsUtil.getInstance(context).getValue(PrefsUtil.BROADCAST_TX, true)); // meta.put("xpubreg44", PrefsUtil.getInstance(context).getValue(PrefsUtil.XPUB44REG, false)); meta.put("xpubreg49", PrefsUtil.getInstance(context).getValue(PrefsUtil.XPUB49REG, false)); meta.put("xpubreg84", PrefsUtil.getInstance(context).getValue(PrefsUtil.XPUB84REG, false)); meta.put("xpublock44", PrefsUtil.getInstance(context).getValue(PrefsUtil.XPUB44LOCK, false)); meta.put("xpublock49", PrefsUtil.getInstance(context).getValue(PrefsUtil.XPUB49LOCK, false)); meta.put("xpublock84", PrefsUtil.getInstance(context).getValue(PrefsUtil.XPUB84LOCK, false)); meta.put("paynym_claimed", PrefsUtil.getInstance(context).getValue(PrefsUtil.PAYNYM_CLAIMED, false)); meta.put("paynym_refused", PrefsUtil.getInstance(context).getValue(PrefsUtil.PAYNYM_REFUSED, false)); JSONObject obj = new JSONObject(); obj.put("wallet", wallet); obj.put("meta", meta); return obj; } catch(JSONException ex) { throw new RuntimeException(ex); } catch(IOException ioe) { throw new RuntimeException(ioe); } catch(MnemonicException.MnemonicLengthException mle) { throw new RuntimeException(mle); } } public synchronized void saveWalletToJSON(CharSequenceX password) throws MnemonicException.MnemonicLengthException, IOException, JSONException, DecryptionException, UnsupportedEncodingException { // Log.i("PayloadUtil", get().toJSON().toString()); // save payload serialize(getPayload(), password); // save optional external storage backup // encrypted using passphrase; cannot be used for restored wallets that do not use a passphrase if(SamouraiWallet.getInstance().hasPassphrase(context) && isExternalStorageWritable() && PrefsUtil.getInstance(context).getValue(PrefsUtil.AUTO_BACKUP, true) && HD_WalletFactory.getInstance(context).get() != null) { final String passphrase = HD_WalletFactory.getInstance(context).get().getPassphrase(); String encrypted = null; try { encrypted = AESUtil.encrypt(getPayload().toString(), new CharSequenceX(passphrase), AESUtil.DefaultPBKDF2Iterations); serialize(encrypted); } catch (Exception e) { // Toast.makeText(context, e.getMessage(), Toast.LENGTH_SHORT).show(); } finally { if (encrypted == null) { // Toast.makeText(context, R.string.encryption_error, Toast.LENGTH_SHORT).show(); return; } } } } public synchronized HD_Wallet restoreWalletfromJSON(JSONObject obj) throws DecoderException, MnemonicException.MnemonicLengthException { // Log.i("PayloadUtil", obj.toString()); HD_Wallet hdw = null; NetworkParameters params = SamouraiWallet.getInstance().getCurrentNetworkParams(); JSONObject wallet = null; JSONObject meta = null; try { if(obj.has("wallet")) { wallet = obj.getJSONObject("wallet"); } else { wallet = obj; } if(obj.has("meta")) { meta = obj.getJSONObject("meta"); } else { meta = obj; } } catch(JSONException je) { ; } try { SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(context).edit(); // Log.i("PayloadUtil", obj.toString()); if(wallet != null) { if(wallet.has("testnet")) { SamouraiWallet.getInstance().setCurrentNetworkParams(wallet.getBoolean("testnet") ? TestNet3Params.get() : MainNetParams.get()); PrefsUtil.getInstance(context).setValue(PrefsUtil.TESTNET, wallet.getBoolean("testnet")); } else { SamouraiWallet.getInstance().setCurrentNetworkParams(MainNetParams.get()); PrefsUtil.getInstance(context).removeValue(PrefsUtil.TESTNET); } hdw = new HD_Wallet(context, 44, wallet, params); hdw.getAccount(SamouraiWallet.SAMOURAI_ACCOUNT).getReceive().setAddrIdx(wallet.has("receiveIdx") ? wallet.getInt("receiveIdx") : 0); hdw.getAccount(SamouraiWallet.SAMOURAI_ACCOUNT).getChange().setAddrIdx(wallet.has("changeIdx") ? wallet.getInt("changeIdx") : 0); if(wallet.has("accounts")) { JSONArray accounts = wallet.getJSONArray("accounts"); // // temporarily set to 2 until use of public XPUB // for(int i = 0; i < 2; i++) { JSONObject account = accounts.getJSONObject(i); hdw.getAccount(i).getReceive().setAddrIdx(account.has("receiveIdx") ? account.getInt("receiveIdx") : 0); hdw.getAccount(i).getChange().setAddrIdx(account.has("changeIdx") ? account.getInt("changeIdx") : 0); AddressFactory.getInstance().account2xpub().put(i, hdw.getAccount(i).xpubstr()); AddressFactory.getInstance().xpub2account().put(hdw.getAccount(i).xpubstr(), i); } } } if(meta != null) { if(meta.has("prev_balance")) { APIFactory.getInstance(context).setXpubBalance(meta.getLong("prev_balance")); } if(meta.has("use_segwit")) { PrefsUtil.getInstance(context).setValue(PrefsUtil.USE_SEGWIT, meta.getBoolean("use_segwit")); editor.putBoolean("segwit", meta.getBoolean("use_segwit")); editor.commit(); } if(meta.has("use_like_typed_change")) { PrefsUtil.getInstance(context).setValue(PrefsUtil.USE_LIKE_TYPED_CHANGE, meta.getBoolean("use_like_typed_change")); editor.putBoolean("likeTypedChange", meta.getBoolean("use_like_typed_change")); editor.commit(); } if(meta.has("spend_type")) { PrefsUtil.getInstance(context).setValue(PrefsUtil.SPEND_TYPE, meta.getInt("spend_type")); editor.putBoolean("boltzmann", meta.getInt("spend_type") == SendActivity.SPEND_BOLTZMANN ? true : false); editor.commit(); } if(meta.has("use_bip126")) { PrefsUtil.getInstance(context).setValue(PrefsUtil.USE_BOLTZMANN, meta.getBoolean("use_bip126")); editor.putBoolean("boltzmann", meta.getBoolean("use_boltzmann")); editor.commit(); } if(meta.has("use_boltzmann")) { PrefsUtil.getInstance(context).setValue(PrefsUtil.USE_BOLTZMANN, meta.getBoolean("use_boltzmann")); editor.putBoolean("boltzmann", meta.getBoolean("use_boltzmann")); editor.commit(); } if(meta.has("rbf_opt_in")) { PrefsUtil.getInstance(context).setValue(PrefsUtil.RBF_OPT_IN, meta.getBoolean("rbf_opt_in")); editor.putBoolean("rbf", meta.getBoolean("rbf_opt_in") ? true : false); editor.commit(); } if(meta.has("sent_tos")) { SendAddressUtil.getInstance().fromJSON((JSONArray) meta.get("sent_tos")); } if(meta.has("batch_send")) { BatchSendUtil.getInstance().fromJSON((JSONArray) meta.get("batch_send")); } if(meta.has("bip47")) { try { BIP47Meta.getInstance().fromJSON((JSONObject) meta.get("bip47")); } catch(ClassCastException cce) { JSONArray _array = (JSONArray) meta.get("bip47"); JSONObject _obj = new JSONObject(); _obj.put("pcodes", _array); BIP47Meta.getInstance().fromJSON(_obj); } } if(meta.has("pin")) { AccessFactory.getInstance().setPIN((String) meta.get("pin")); } if(meta.has("pin2")) { AccessFactory.getInstance().setPIN2((String) meta.get("pin2")); } if(meta.has("ricochet")) { RicochetMeta.getInstance(context).fromJSON((JSONObject) meta.get("ricochet")); } if(meta.has("trusted_node")) { TrustedNodeUtil.getInstance().fromJSON((JSONObject) meta.get("trusted_node")); } if(meta.has("rbfs")) { RBFUtil.getInstance().fromJSON((JSONArray) meta.get("rbfs")); } if(meta.has("tor")) { TorUtil.getInstance(context).fromJSON((JSONObject) meta.get("tor")); } if(meta.has("blocked_utxos")) { BlockedUTXO.getInstance().fromJSON((JSONObject) meta.get("blocked_utxos")); } if(meta.has("explorer")) { PrefsUtil.getInstance(context).setValue(PrefsUtil.BLOCK_EXPLORER, meta.getInt("explorer")); } if(meta.has("trusted_no")) { PrefsUtil.getInstance(context).setValue(PrefsUtil.ALERT_MOBILE_NO, (String) meta.get("trusted_no")); editor.putString("alertSMSNo", meta.getString("trusted_no")); editor.commit(); } if(meta.has("scramble_pin")) { PrefsUtil.getInstance(context).setValue(PrefsUtil.SCRAMBLE_PIN, meta.getBoolean("scramble_pin")); editor.putBoolean("scramblePin", meta.getBoolean("scramble_pin")); editor.commit(); } if(meta.has("haptic_pin")) { PrefsUtil.getInstance(context).setValue(PrefsUtil.HAPTIC_PIN, meta.getBoolean("haptic_pin")); editor.putBoolean("haptic", meta.getBoolean("haptic_pin")); editor.commit(); } if(meta.has("auto_backup")) { PrefsUtil.getInstance(context).setValue(PrefsUtil.AUTO_BACKUP, meta.getBoolean("auto_backup")); editor.putBoolean("auto_backup", meta.getBoolean("auto_backup")); editor.commit(); } if(meta.has("remote")) { PrefsUtil.getInstance(context).setValue(PrefsUtil.ACCEPT_REMOTE, meta.getBoolean("remote")); editor.putBoolean("stealthRemote", meta.getBoolean("remote")); editor.commit(); } if(meta.has("use_trusted")) { PrefsUtil.getInstance(context).setValue(PrefsUtil.TRUSTED_LOCK, meta.getBoolean("use_trusted")); editor.putBoolean("trustedLock", meta.getBoolean("use_trusted")); editor.commit(); } if(meta.has("check_sim")) { PrefsUtil.getInstance(context).setValue(PrefsUtil.CHECK_SIM, meta.getBoolean("check_sim")); editor.putBoolean("sim_switch", meta.getBoolean("check_sim")); editor.commit(); if(meta.getBoolean("check_sim")) { SIMUtil.getInstance(context).setStoredSIM(); } } if (meta.has("fiat")) { PrefsUtil.getInstance(context).setValue(PrefsUtil.CURRENT_FIAT, (String)meta.get("fiat")); } if (meta.has("fiat_sel")) { PrefsUtil.getInstance(context).setValue(PrefsUtil.CURRENT_FIAT_SEL, meta.getInt("fiat_sel")); } if (meta.has("fx")) { PrefsUtil.getInstance(context).setValue(PrefsUtil.CURRENT_EXCHANGE, (String)meta.get("fx")); } if(meta.has("fx_sel")) { PrefsUtil.getInstance(context).setValue(PrefsUtil.CURRENT_EXCHANGE_SEL, meta.getInt("fx_sel")); } if(meta.has("use_trusted_node")) { PrefsUtil.getInstance(context).setValue(PrefsUtil.USE_TRUSTED_NODE, meta.getBoolean("use_trusted_node")); } if(meta.has("fee_provider_sel")) { // PrefsUtil.getInstance(context).setValue(PrefsUtil.FEE_PROVIDER_SEL, meta.getInt("fee_provider_sel") > 0 ? 0 : meta.getInt("fee_provider_sel")); PrefsUtil.getInstance(context).setValue(PrefsUtil.FEE_PROVIDER_SEL, 0); } if(meta.has("broadcast_tx")) { PrefsUtil.getInstance(context).setValue(PrefsUtil.BROADCAST_TX, meta.getBoolean("broadcast_tx")); } /* if(meta.has("xpubreg44")) { PrefsUtil.getInstance(context).setValue(PrefsUtil.XPUB44REG, meta.getBoolean("xpubreg44")); } */ if(meta.has("xpubreg49")) { PrefsUtil.getInstance(context).setValue(PrefsUtil.XPUB49REG, meta.getBoolean("xpubreg49")); } if(meta.has("xpubreg84")) { PrefsUtil.getInstance(context).setValue(PrefsUtil.XPUB84REG, meta.getBoolean("xpubreg84")); } if(meta.has("xpublock44")) { PrefsUtil.getInstance(context).setValue(PrefsUtil.XPUB44LOCK, meta.getBoolean("xpublock44")); } if(meta.has("xpublock49")) { PrefsUtil.getInstance(context).setValue(PrefsUtil.XPUB49LOCK, meta.getBoolean("xpublock49")); } if(meta.has("xpublock84")) { PrefsUtil.getInstance(context).setValue(PrefsUtil.XPUB84LOCK, meta.getBoolean("xpublock84")); } if(meta.has("paynym_claimed")) { PrefsUtil.getInstance(context).setValue(PrefsUtil.PAYNYM_CLAIMED, meta.getBoolean("paynym_claimed")); } if(meta.has("paynym_refused")) { PrefsUtil.getInstance(context).setValue(PrefsUtil.PAYNYM_REFUSED, meta.getBoolean("paynym_refused")); } /* if(obj.has("passphrase")) { Log.i("PayloadUtil", (String)obj.get("passphrase")); Toast.makeText(context, "'" + (String)obj.get("passphrase") + "'", Toast.LENGTH_SHORT).show(); } Toast.makeText(context, "'" + hdw.getPassphrase() + "'", Toast.LENGTH_SHORT).show(); */ } } catch(IOException ioe) { ioe.printStackTrace(); } catch(JSONException je) { je.printStackTrace(); } HD_WalletFactory.getInstance(context).getWallets().clear(); HD_WalletFactory.getInstance(context).getWallets().add(hdw); return hdw; } public synchronized HD_Wallet restoreWalletfromJSON(CharSequenceX password) throws DecoderException, MnemonicException.MnemonicLengthException { JSONObject obj = null; try { obj = deserialize(password, false); } catch(IOException ioe) { ioe.printStackTrace(); } catch(JSONException je0) { try { obj = deserialize(password, true); } catch(IOException ioe) { ioe.printStackTrace(); } catch(JSONException je1) { je1.printStackTrace(); } } return restoreWalletfromJSON(obj); } public synchronized boolean walletFileExists() { File dir = context.getDir(dataDir, Context.MODE_PRIVATE); File walletfile = new File(dir, strFilename); return walletfile.exists(); } private synchronized void serialize(JSONObject jsonobj, CharSequenceX password) throws IOException, JSONException, DecryptionException, UnsupportedEncodingException { File dir = context.getDir(dataDir, Context.MODE_PRIVATE); File newfile = new File(dir, strFilename); File tmpfile = new File(dir, strTmpFilename); File bakfile = new File(dir, strBackupFilename); newfile.setWritable(true, true); tmpfile.setWritable(true, true); bakfile.setWritable(true, true); // prepare tmp file. if(tmpfile.exists()) { tmpfile.delete(); // secureDelete(tmpfile); } String data = null; String jsonstr = jsonobj.toString(4); if(password != null) { data = AESUtil.encrypt(jsonstr, password, AESUtil.DefaultPBKDF2Iterations); } else { data = jsonstr; } JSONObject jsonObj = putPayload(data, false); if(jsonObj != null) { Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(tmpfile), "UTF-8")); try { out.write(jsonObj.toString()); } finally { out.close(); } copy(tmpfile, newfile); copy(tmpfile, bakfile); // secureDelete(tmpfile); } // // test payload // } private synchronized JSONObject deserialize(CharSequenceX password, boolean useBackup) throws IOException, JSONException { File dir = context.getDir(dataDir, Context.MODE_PRIVATE); File file = new File(dir, useBackup ? strBackupFilename : strFilename); // Log.i("PayloadUtil", "wallet file exists: " + file.exists()); StringBuilder sb = new StringBuilder(); BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF8")); String str = null; while((str = in.readLine()) != null) { sb.append(str); } in.close(); JSONObject jsonObj = null; try { jsonObj = new JSONObject(sb.toString()); } catch(JSONException je) { ; } String payload = null; if(jsonObj != null && jsonObj.has("payload")) { payload = jsonObj.getString("payload"); } // not a json stream, assume v0 if(payload == null) { payload = sb.toString(); } JSONObject node = null; if(password == null) { node = new JSONObject(payload); } else { String decrypted = null; try { decrypted = AESUtil.decrypt(payload, password, AESUtil.DefaultPBKDF2Iterations); } catch(Exception e) { return null; } if(decrypted == null) { return null; } node = new JSONObject(decrypted); } return node; } private synchronized void secureDelete(File file) throws IOException { if (file.exists()) { long length = file.length(); SecureRandom random = new SecureRandom(); RandomAccessFile raf = new RandomAccessFile(file, "rws"); for(int i = 0; i < 5; i++) { raf.seek(0); raf.getFilePointer(); byte[] data = new byte[64]; int pos = 0; while (pos < length) { random.nextBytes(data); raf.write(data); pos += data.length; } } raf.close(); file.delete(); } } public synchronized void copy(File src, File dst) throws IOException { InputStream in = new FileInputStream(src); try { OutputStream out = new FileOutputStream(dst); try { byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } } finally { out.close(); } } finally { in.close(); } } private boolean isExternalStorageWritable() { String state = Environment.getExternalStorageState(); if(Environment.MEDIA_MOUNTED.equals(state)) { return true; } return false; } private synchronized void serialize(String data) throws IOException { String directory = Environment.DIRECTORY_DOCUMENTS; File dir = null; if(context.getPackageName().contains("staging")) { dir = Environment.getExternalStoragePublicDirectory(directory + strOptionalBackupDir + "/staging"); } else { dir = Environment.getExternalStoragePublicDirectory(directory + strOptionalBackupDir); } if(!dir.exists()) { dir.mkdirs(); dir.setWritable(true, true); dir.setReadable(true, true); } File newfile = new File(dir, strOptionalFilename); newfile.setWritable(true, true); newfile.setReadable(true, true); JSONObject jsonObj = putPayload(data, false); if(jsonObj != null) { Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(newfile), "UTF-8")); try { out.write(jsonObj.toString()); } finally { out.close(); } } // // test payload // } public String getDecryptedBackupPayload(String data, CharSequenceX password) { String encrypted = null; try { JSONObject jsonObj = new JSONObject(data); if(jsonObj != null && jsonObj.has("payload")) { encrypted = jsonObj.getString("payload"); } else { encrypted = data; } } catch(JSONException je) { encrypted = data; } String decrypted = null; try { decrypted = AESUtil.decrypt(encrypted, password, AESUtil.DefaultPBKDF2Iterations); } catch (Exception e) { Toast.makeText(context, R.string.decryption_error, Toast.LENGTH_SHORT).show(); } finally { if (decrypted == null || decrypted.length() < 1) { Toast.makeText(context, R.string.decryption_error, Toast.LENGTH_SHORT).show(); // AppUtil.getInstance(context).restartApp(); } } return decrypted; } }
app/src/main/java/com/samourai/wallet/payload/PayloadUtil.java
package com.samourai.wallet.payload; import android.content.Context; import android.content.SharedPreferences; import android.os.Build; import android.os.Environment; import android.preference.PreferenceManager; import android.widget.Toast; //import android.util.Log; import com.samourai.wallet.R; import com.samourai.wallet.SamouraiWallet; import com.samourai.wallet.SendActivity; import com.samourai.wallet.access.AccessFactory; import com.samourai.wallet.api.APIFactory; import com.samourai.wallet.bip47.BIP47Meta; import com.samourai.wallet.bip47.BIP47Util; import com.samourai.wallet.crypto.AESUtil; import com.samourai.wallet.crypto.DecryptionException; import com.samourai.wallet.hd.HD_Account; import com.samourai.wallet.hd.HD_Wallet; import com.samourai.wallet.hd.HD_WalletFactory; import com.samourai.wallet.ricochet.RicochetMeta; import com.samourai.wallet.segwit.BIP49Util; import com.samourai.wallet.segwit.BIP84Util; import com.samourai.wallet.send.BlockedUTXO; import com.samourai.wallet.util.AddressFactory; import com.samourai.wallet.util.BatchSendUtil; import com.samourai.wallet.util.CharSequenceX; import com.samourai.wallet.util.PrefsUtil; import com.samourai.wallet.send.RBFUtil; import com.samourai.wallet.util.SIMUtil; import com.samourai.wallet.util.SendAddressUtil; import com.samourai.wallet.JSONRPC.TrustedNodeUtil; import com.samourai.wallet.util.TorUtil; import com.samourai.wallet.util.WebUtil; import org.apache.commons.codec.DecoderException; import org.bitcoinj.core.AddressFormatException; import org.bitcoinj.core.NetworkParameters; import org.bitcoinj.crypto.MnemonicException; import org.bitcoinj.params.MainNetParams; import org.bitcoinj.params.TestNet3Params; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.RandomAccessFile; import java.io.UnsupportedEncodingException; import java.io.Writer; import java.security.SecureRandom; public class PayloadUtil { private final static String dataDir = "wallet"; private final static String strFilename = "samourai.dat"; private final static String strTmpFilename = "samourai.tmp"; private final static String strBackupFilename = "samourai.sav"; private final static String strOptionalBackupDir = "/samourai"; private final static String strOptionalFilename = "samourai.txt"; private static Context context = null; private static PayloadUtil instance = null; private PayloadUtil() { ; } public static PayloadUtil getInstance(Context ctx) { context = ctx; if (instance == null) { instance = new PayloadUtil(); } return instance; } public File getBackupFile() { String directory = Environment.DIRECTORY_DOCUMENTS; File dir = null; if(context.getPackageName().contains("staging")) { dir = Environment.getExternalStoragePublicDirectory(directory + strOptionalBackupDir + "/staging"); } else { dir = Environment.getExternalStoragePublicDirectory(directory + strOptionalBackupDir); } File file = new File(dir, strOptionalFilename); return file; } public JSONObject putPayload(String data, boolean external) { JSONObject obj = new JSONObject(); try { obj.put("version", 1); obj.put("payload", data); obj.put("external", external); } catch(JSONException je) { return null; } return obj; } public boolean hasPayload(Context ctx) { File dir = ctx.getDir(dataDir, Context.MODE_PRIVATE); File file = new File(dir, strFilename); if(file.exists()) { return true; } return false; } public synchronized void wipe() throws IOException { BIP47Util.getInstance(context).reset(); BIP47Meta.getInstance().clear(); BIP49Util.getInstance(context).reset(); APIFactory.getInstance(context).reset(); try { int nbAccounts = HD_WalletFactory.getInstance(context).get().getAccounts().size(); for(int i = 0; i < nbAccounts; i++) { HD_WalletFactory.getInstance(context).get().getAccount(i).getReceive().setAddrIdx(0); HD_WalletFactory.getInstance(context).get().getAccount(i).getChange().setAddrIdx(0); AddressFactory.getInstance().setHighestTxReceiveIdx(i, 0); AddressFactory.getInstance().setHighestTxChangeIdx(i, 0); } HD_WalletFactory.getInstance(context).set(null); } catch(MnemonicException.MnemonicLengthException mle) { mle.printStackTrace(); } HD_WalletFactory.getInstance(context).clear(); File dir = context.getDir(dataDir, Context.MODE_PRIVATE); File datfile = new File(dir, strFilename); File tmpfile = new File(dir, strTmpFilename); if(tmpfile.exists()) { secureDelete(tmpfile); } if(datfile.exists()) { secureDelete(datfile); try { serialize(new JSONObject("{}"), new CharSequenceX("")); } catch(JSONException je) { je.printStackTrace(); } catch(Exception e) { e.printStackTrace(); } } } public JSONObject getPayload() { try { JSONObject wallet = new JSONObject(); wallet.put("testnet", SamouraiWallet.getInstance().isTestNet() ? true : false); if(HD_WalletFactory.getInstance(context).get().getSeedHex() != null) { wallet.put("seed", HD_WalletFactory.getInstance(context).get().getSeedHex()); wallet.put("passphrase", HD_WalletFactory.getInstance(context).get().getPassphrase()); // obj.put("mnemonic", getMnemonic()); } JSONArray accts = new JSONArray(); for(HD_Account acct : HD_WalletFactory.getInstance(context).get().getAccounts()) { accts.put(acct.toJSON(44)); } wallet.put("accounts", accts); // // export BIP47 payment code for debug payload // try { wallet.put("payment_code", BIP47Util.getInstance(context).getPaymentCode().toString()); } catch(AddressFormatException afe) { ; } // // export BIP49 account for debug payload // JSONArray bip49_account = new JSONArray(); bip49_account.put(BIP49Util.getInstance(context).getWallet().getAccount(0).toJSON(49)); wallet.put("bip49_accounts", bip49_account); // // export BIP84 account for debug payload // JSONArray bip84_account = new JSONArray(); bip84_account.put(BIP84Util.getInstance(context).getWallet().getAccount(0).toJSON(84)); wallet.put("bip84_accounts", bip84_account); // // can remove ??? // /* obj.put("receiveIdx", mAccounts.get(0).getReceive().getAddrIdx()); obj.put("changeIdx", mAccounts.get(0).getChange().getAddrIdx()); */ JSONObject meta = new JSONObject(); meta.put("version_name", context.getText(R.string.version_name)); meta.put("android_release", Build.VERSION.RELEASE == null ? "" : Build.VERSION.RELEASE); meta.put("device_manufacturer", Build.MANUFACTURER == null ? "" : Build.MANUFACTURER); meta.put("device_model", Build.MODEL == null ? "" : Build.MODEL); meta.put("device_product", Build.PRODUCT == null ? "" : Build.PRODUCT); meta.put("prev_balance", APIFactory.getInstance(context).getXpubBalance()); meta.put("sent_tos", SendAddressUtil.getInstance().toJSON()); meta.put("batch_send", BatchSendUtil.getInstance().toJSON()); meta.put("use_segwit", PrefsUtil.getInstance(context).getValue(PrefsUtil.USE_SEGWIT, true)); meta.put("use_like_typed_change", PrefsUtil.getInstance(context).getValue(PrefsUtil.USE_LIKE_TYPED_CHANGE, true)); meta.put("spend_type", PrefsUtil.getInstance(context).getValue(PrefsUtil.SPEND_TYPE, SendActivity.SPEND_BOLTZMANN)); meta.put("use_boltzmann", PrefsUtil.getInstance(context).getValue(PrefsUtil.USE_BOLTZMANN, true)); meta.put("rbf_opt_in", PrefsUtil.getInstance(context).getValue(PrefsUtil.RBF_OPT_IN, false)); meta.put("bip47", BIP47Meta.getInstance().toJSON()); meta.put("pin", AccessFactory.getInstance().getPIN()); meta.put("pin2", AccessFactory.getInstance().getPIN2()); meta.put("ricochet", RicochetMeta.getInstance(context).toJSON()); meta.put("trusted_node", TrustedNodeUtil.getInstance().toJSON()); meta.put("rbfs", RBFUtil.getInstance().toJSON()); meta.put("tor", TorUtil.getInstance(context).toJSON()); meta.put("blocked_utxos", BlockedUTXO.getInstance().toJSON()); meta.put("explorer", PrefsUtil.getInstance(context).getValue(PrefsUtil.BLOCK_EXPLORER, 0)); meta.put("trusted_no", PrefsUtil.getInstance(context).getValue(PrefsUtil.ALERT_MOBILE_NO, "")); meta.put("scramble_pin", PrefsUtil.getInstance(context).getValue(PrefsUtil.SCRAMBLE_PIN, false)); meta.put("haptic_pin", PrefsUtil.getInstance(context).getValue(PrefsUtil.HAPTIC_PIN, true)); meta.put("auto_backup", PrefsUtil.getInstance(context).getValue(PrefsUtil.AUTO_BACKUP, true)); meta.put("remote", PrefsUtil.getInstance(context).getValue(PrefsUtil.ACCEPT_REMOTE, false)); meta.put("use_trusted", PrefsUtil.getInstance(context).getValue(PrefsUtil.TRUSTED_LOCK, false)); meta.put("check_sim", PrefsUtil.getInstance(context).getValue(PrefsUtil.CHECK_SIM, false)); meta.put("fiat", PrefsUtil.getInstance(context).getValue(PrefsUtil.CURRENT_FIAT, "USD")); meta.put("fiat_sel", PrefsUtil.getInstance(context).getValue(PrefsUtil.CURRENT_FIAT_SEL, 0)); meta.put("fx", PrefsUtil.getInstance(context).getValue(PrefsUtil.CURRENT_EXCHANGE, "LocalBitcoins.com")); meta.put("fx_sel", PrefsUtil.getInstance(context).getValue(PrefsUtil.CURRENT_EXCHANGE_SEL, 0)); meta.put("use_trusted_node", PrefsUtil.getInstance(context).getValue(PrefsUtil.USE_TRUSTED_NODE, false)); meta.put("fee_provider_sel", PrefsUtil.getInstance(context).getValue(PrefsUtil.FEE_PROVIDER_SEL, 0)); meta.put("broadcast_tx", PrefsUtil.getInstance(context).getValue(PrefsUtil.BROADCAST_TX, true)); // meta.put("xpubreg44", PrefsUtil.getInstance(context).getValue(PrefsUtil.XPUB44REG, false)); meta.put("xpubreg49", PrefsUtil.getInstance(context).getValue(PrefsUtil.XPUB49REG, false)); meta.put("xpubreg84", PrefsUtil.getInstance(context).getValue(PrefsUtil.XPUB84REG, false)); meta.put("xpublock44", PrefsUtil.getInstance(context).getValue(PrefsUtil.XPUB44LOCK, false)); meta.put("xpublock49", PrefsUtil.getInstance(context).getValue(PrefsUtil.XPUB49LOCK, false)); meta.put("xpublock84", PrefsUtil.getInstance(context).getValue(PrefsUtil.XPUB84LOCK, false)); meta.put("paynym_claimed", PrefsUtil.getInstance(context).getValue(PrefsUtil.PAYNYM_CLAIMED, false)); meta.put("paynym_refused", PrefsUtil.getInstance(context).getValue(PrefsUtil.PAYNYM_REFUSED, false)); JSONObject obj = new JSONObject(); obj.put("wallet", wallet); obj.put("meta", meta); return obj; } catch(JSONException ex) { throw new RuntimeException(ex); } catch(IOException ioe) { throw new RuntimeException(ioe); } catch(MnemonicException.MnemonicLengthException mle) { throw new RuntimeException(mle); } } public synchronized void saveWalletToJSON(CharSequenceX password) throws MnemonicException.MnemonicLengthException, IOException, JSONException, DecryptionException, UnsupportedEncodingException { // Log.i("PayloadUtil", get().toJSON().toString()); // save payload serialize(getPayload(), password); // save optional external storage backup // encrypted using passphrase; cannot be used for restored wallets that do not use a passphrase if(SamouraiWallet.getInstance().hasPassphrase(context) && isExternalStorageWritable() && PrefsUtil.getInstance(context).getValue(PrefsUtil.AUTO_BACKUP, true) && HD_WalletFactory.getInstance(context).get() != null) { final String passphrase = HD_WalletFactory.getInstance(context).get().getPassphrase(); String encrypted = null; try { encrypted = AESUtil.encrypt(getPayload().toString(), new CharSequenceX(passphrase), AESUtil.DefaultPBKDF2Iterations); serialize(encrypted); } catch (Exception e) { // Toast.makeText(context, e.getMessage(), Toast.LENGTH_SHORT).show(); } finally { if (encrypted == null) { // Toast.makeText(context, R.string.encryption_error, Toast.LENGTH_SHORT).show(); return; } } } } public synchronized HD_Wallet restoreWalletfromJSON(JSONObject obj) throws DecoderException, MnemonicException.MnemonicLengthException { // Log.i("PayloadUtil", obj.toString()); HD_Wallet hdw = null; NetworkParameters params = SamouraiWallet.getInstance().getCurrentNetworkParams(); JSONObject wallet = null; JSONObject meta = null; try { if(obj.has("wallet")) { wallet = obj.getJSONObject("wallet"); } else { wallet = obj; } if(obj.has("meta")) { meta = obj.getJSONObject("meta"); } else { meta = obj; } } catch(JSONException je) { ; } try { SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(context).edit(); // Log.i("PayloadUtil", obj.toString()); if(wallet != null) { if(wallet.has("testnet")) { SamouraiWallet.getInstance().setCurrentNetworkParams(wallet.getBoolean("testnet") ? TestNet3Params.get() : MainNetParams.get()); PrefsUtil.getInstance(context).setValue(PrefsUtil.TESTNET, wallet.getBoolean("testnet")); } else { SamouraiWallet.getInstance().setCurrentNetworkParams(MainNetParams.get()); PrefsUtil.getInstance(context).removeValue(PrefsUtil.TESTNET); } hdw = new HD_Wallet(context, 44, wallet, params); hdw.getAccount(SamouraiWallet.SAMOURAI_ACCOUNT).getReceive().setAddrIdx(wallet.has("receiveIdx") ? wallet.getInt("receiveIdx") : 0); hdw.getAccount(SamouraiWallet.SAMOURAI_ACCOUNT).getChange().setAddrIdx(wallet.has("changeIdx") ? wallet.getInt("changeIdx") : 0); if(wallet.has("accounts")) { JSONArray accounts = wallet.getJSONArray("accounts"); // // temporarily set to 2 until use of public XPUB // for(int i = 0; i < 2; i++) { JSONObject account = accounts.getJSONObject(i); hdw.getAccount(i).getReceive().setAddrIdx(account.has("receiveIdx") ? account.getInt("receiveIdx") : 0); hdw.getAccount(i).getChange().setAddrIdx(account.has("changeIdx") ? account.getInt("changeIdx") : 0); AddressFactory.getInstance().account2xpub().put(i, hdw.getAccount(i).xpubstr()); AddressFactory.getInstance().xpub2account().put(hdw.getAccount(i).xpubstr(), i); } } } if(meta != null) { if(meta.has("prev_balance")) { APIFactory.getInstance(context).setXpubBalance(meta.getLong("prev_balance")); } if(meta.has("use_segwit")) { PrefsUtil.getInstance(context).setValue(PrefsUtil.USE_SEGWIT, meta.getBoolean("use_segwit")); editor.putBoolean("segwit", meta.getBoolean("use_segwit")); editor.commit(); } if(meta.has("use_like_typed_change")) { PrefsUtil.getInstance(context).setValue(PrefsUtil.USE_LIKE_TYPED_CHANGE, meta.getBoolean("use_like_typed_change")); editor.putBoolean("likeTypedChange", meta.getBoolean("use_like_typed_change")); editor.commit(); } if(meta.has("spend_type")) { PrefsUtil.getInstance(context).setValue(PrefsUtil.SPEND_TYPE, meta.getInt("spend_type")); editor.putBoolean("boltzmann", meta.getInt("spend_type") == SendActivity.SPEND_BOLTZMANN ? true : false); editor.commit(); } if(meta.has("use_bip126")) { PrefsUtil.getInstance(context).setValue(PrefsUtil.USE_BOLTZMANN, meta.getBoolean("use_bip126")); editor.putBoolean("boltzmann", meta.getBoolean("use_boltzmann")); editor.commit(); } if(meta.has("use_boltzmann")) { PrefsUtil.getInstance(context).setValue(PrefsUtil.USE_BOLTZMANN, meta.getBoolean("use_boltzmann")); editor.putBoolean("boltzmann", meta.getBoolean("use_boltzmann")); editor.commit(); } if(meta.has("rbf_opt_in")) { PrefsUtil.getInstance(context).setValue(PrefsUtil.RBF_OPT_IN, meta.getBoolean("rbf_opt_in")); editor.putBoolean("rbf", meta.getBoolean("rbf_opt_in") ? true : false); editor.commit(); } if(meta.has("sent_tos")) { SendAddressUtil.getInstance().fromJSON((JSONArray) meta.get("sent_tos")); } if(meta.has("batch_send")) { BatchSendUtil.getInstance().fromJSON((JSONArray) meta.get("batch_send")); } if(meta.has("bip47")) { try { BIP47Meta.getInstance().fromJSON((JSONObject) meta.get("bip47")); } catch(ClassCastException cce) { JSONArray _array = (JSONArray) meta.get("bip47"); JSONObject _obj = new JSONObject(); _obj.put("pcodes", _array); BIP47Meta.getInstance().fromJSON(_obj); } } if(meta.has("pin")) { AccessFactory.getInstance().setPIN((String) meta.get("pin")); } if(meta.has("pin2")) { AccessFactory.getInstance().setPIN2((String) meta.get("pin2")); } if(meta.has("ricochet")) { RicochetMeta.getInstance(context).fromJSON((JSONObject) meta.get("ricochet")); } if(meta.has("trusted_node")) { TrustedNodeUtil.getInstance().fromJSON((JSONObject) meta.get("trusted_node")); } if(meta.has("rbfs")) { RBFUtil.getInstance().fromJSON((JSONArray) meta.get("rbfs")); } if(meta.has("tor")) { TorUtil.getInstance(context).fromJSON((JSONObject) meta.get("tor")); } if(meta.has("blocked_utxos")) { BlockedUTXO.getInstance().fromJSON((JSONObject) meta.get("blocked_utxos")); } if(meta.has("explorer")) { PrefsUtil.getInstance(context).setValue(PrefsUtil.BLOCK_EXPLORER, meta.getInt("explorer")); } if(meta.has("trusted_no")) { PrefsUtil.getInstance(context).setValue(PrefsUtil.ALERT_MOBILE_NO, (String) meta.get("trusted_no")); editor.putString("alertSMSNo", meta.getString("trusted_no")); editor.commit(); } if(meta.has("scramble_pin")) { PrefsUtil.getInstance(context).setValue(PrefsUtil.SCRAMBLE_PIN, meta.getBoolean("scramble_pin")); editor.putBoolean("scramblePin", meta.getBoolean("scramble_pin")); editor.commit(); } if(meta.has("haptic_pin")) { PrefsUtil.getInstance(context).setValue(PrefsUtil.HAPTIC_PIN, meta.getBoolean("haptic_pin")); editor.putBoolean("haptic", meta.getBoolean("haptic_pin")); editor.commit(); } if(meta.has("auto_backup")) { PrefsUtil.getInstance(context).setValue(PrefsUtil.AUTO_BACKUP, meta.getBoolean("auto_backup")); editor.putBoolean("auto_backup", meta.getBoolean("auto_backup")); editor.commit(); } if(meta.has("remote")) { PrefsUtil.getInstance(context).setValue(PrefsUtil.ACCEPT_REMOTE, meta.getBoolean("remote")); editor.putBoolean("stealthRemote", meta.getBoolean("remote")); editor.commit(); } if(meta.has("use_trusted")) { PrefsUtil.getInstance(context).setValue(PrefsUtil.TRUSTED_LOCK, meta.getBoolean("use_trusted")); editor.putBoolean("trustedLock", meta.getBoolean("use_trusted")); editor.commit(); } if(meta.has("check_sim")) { PrefsUtil.getInstance(context).setValue(PrefsUtil.CHECK_SIM, meta.getBoolean("check_sim")); editor.putBoolean("sim_switch", meta.getBoolean("check_sim")); editor.commit(); if(meta.getBoolean("check_sim")) { SIMUtil.getInstance(context).setStoredSIM(); } } if (meta.has("fiat")) { PrefsUtil.getInstance(context).setValue(PrefsUtil.CURRENT_FIAT, (String)meta.get("fiat")); } if (meta.has("fiat_sel")) { PrefsUtil.getInstance(context).setValue(PrefsUtil.CURRENT_FIAT_SEL, meta.getInt("fiat_sel")); } if (meta.has("fx")) { PrefsUtil.getInstance(context).setValue(PrefsUtil.CURRENT_EXCHANGE, (String)meta.get("fx")); } if(meta.has("fx_sel")) { PrefsUtil.getInstance(context).setValue(PrefsUtil.CURRENT_EXCHANGE_SEL, meta.getInt("fx_sel")); } if(meta.has("use_trusted_node")) { PrefsUtil.getInstance(context).setValue(PrefsUtil.USE_TRUSTED_NODE, meta.getBoolean("use_trusted_node")); } if(meta.has("fee_provider_sel")) { // PrefsUtil.getInstance(context).setValue(PrefsUtil.FEE_PROVIDER_SEL, meta.getInt("fee_provider_sel") > 0 ? 0 : meta.getInt("fee_provider_sel")); PrefsUtil.getInstance(context).setValue(PrefsUtil.FEE_PROVIDER_SEL, 0); } if(meta.has("broadcast_tx")) { PrefsUtil.getInstance(context).setValue(PrefsUtil.BROADCAST_TX, meta.getBoolean("broadcast_tx")); } /* if(meta.has("xpubreg44")) { PrefsUtil.getInstance(context).setValue(PrefsUtil.XPUB44REG, meta.getBoolean("xpubreg44")); } */ if(meta.has("xpubreg49")) { PrefsUtil.getInstance(context).setValue(PrefsUtil.XPUB49REG, meta.getBoolean("xpubreg49")); } if(meta.has("xpubreg84")) { PrefsUtil.getInstance(context).setValue(PrefsUtil.XPUB84REG, meta.getBoolean("xpubreg84")); } if(meta.has("xpublock44")) { PrefsUtil.getInstance(context).setValue(PrefsUtil.XPUB44LOCK, meta.getBoolean("xpublock44")); } if(meta.has("xpublock49")) { PrefsUtil.getInstance(context).setValue(PrefsUtil.XPUB49LOCK, meta.getBoolean("xpublock49")); } if(meta.has("xpublock84")) { PrefsUtil.getInstance(context).setValue(PrefsUtil.XPUB84LOCK, meta.getBoolean("xpublock84")); } if(meta.has("paynym_claimed")) { PrefsUtil.getInstance(context).setValue(PrefsUtil.PAYNYM_CLAIMED, meta.getBoolean("paynym_claimed")); } if(meta.has("paynym_refused")) { PrefsUtil.getInstance(context).setValue(PrefsUtil.PAYNYM_REFUSED, meta.getBoolean("paynym_refused")); } /* if(obj.has("passphrase")) { Log.i("PayloadUtil", (String)obj.get("passphrase")); Toast.makeText(context, "'" + (String)obj.get("passphrase") + "'", Toast.LENGTH_SHORT).show(); } Toast.makeText(context, "'" + hdw.getPassphrase() + "'", Toast.LENGTH_SHORT).show(); */ } } catch(IOException ioe) { ioe.printStackTrace(); } catch(JSONException je) { je.printStackTrace(); } HD_WalletFactory.getInstance(context).getWallets().clear(); HD_WalletFactory.getInstance(context).getWallets().add(hdw); return hdw; } public synchronized HD_Wallet restoreWalletfromJSON(CharSequenceX password) throws DecoderException, MnemonicException.MnemonicLengthException { JSONObject obj = null; try { obj = deserialize(password, false); } catch(IOException ioe) { ioe.printStackTrace(); } catch(JSONException je0) { try { obj = deserialize(password, true); } catch(IOException ioe) { ioe.printStackTrace(); } catch(JSONException je1) { je1.printStackTrace(); } } return restoreWalletfromJSON(obj); } public synchronized boolean walletFileExists() { File dir = context.getDir(dataDir, Context.MODE_PRIVATE); File walletfile = new File(dir, strFilename); return walletfile.exists(); } private synchronized void serialize(JSONObject jsonobj, CharSequenceX password) throws IOException, JSONException, DecryptionException, UnsupportedEncodingException { File dir = context.getDir(dataDir, Context.MODE_PRIVATE); File newfile = new File(dir, strFilename); File tmpfile = new File(dir, strTmpFilename); File bakfile = new File(dir, strBackupFilename); newfile.setWritable(true, true); tmpfile.setWritable(true, true); bakfile.setWritable(true, true); // prepare tmp file. if(tmpfile.exists()) { tmpfile.delete(); // secureDelete(tmpfile); } String data = null; String jsonstr = jsonobj.toString(4); if(password != null) { data = AESUtil.encrypt(jsonstr, password, AESUtil.DefaultPBKDF2Iterations); } else { data = jsonstr; } JSONObject jsonObj = putPayload(data, false); if(jsonObj != null) { Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(tmpfile), "UTF-8")); try { out.write(jsonObj.toString()); } finally { out.close(); } copy(tmpfile, newfile); copy(tmpfile, bakfile); // secureDelete(tmpfile); } // // test payload // } private synchronized JSONObject deserialize(CharSequenceX password, boolean useBackup) throws IOException, JSONException { File dir = context.getDir(dataDir, Context.MODE_PRIVATE); File file = new File(dir, useBackup ? strBackupFilename : strFilename); // Log.i("PayloadUtil", "wallet file exists: " + file.exists()); StringBuilder sb = new StringBuilder(); BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF8")); String str = null; while((str = in.readLine()) != null) { sb.append(str); } in.close(); JSONObject jsonObj = null; try { jsonObj = new JSONObject(sb.toString()); } catch(JSONException je) { ; } String payload = null; if(jsonObj != null && jsonObj.has("payload")) { payload = jsonObj.getString("payload"); } // not a json stream, assume v0 if(payload == null) { payload = sb.toString(); } JSONObject node = null; if(password == null) { node = new JSONObject(payload); } else { String decrypted = null; try { decrypted = AESUtil.decrypt(payload, password, AESUtil.DefaultPBKDF2Iterations); } catch(Exception e) { return null; } if(decrypted == null) { return null; } node = new JSONObject(decrypted); } return node; } private synchronized void secureDelete(File file) throws IOException { if (file.exists()) { long length = file.length(); SecureRandom random = new SecureRandom(); RandomAccessFile raf = new RandomAccessFile(file, "rws"); for(int i = 0; i < 5; i++) { raf.seek(0); raf.getFilePointer(); byte[] data = new byte[64]; int pos = 0; while (pos < length) { random.nextBytes(data); raf.write(data); pos += data.length; } } raf.close(); file.delete(); } } public synchronized void copy(File src, File dst) throws IOException { InputStream in = new FileInputStream(src); try { OutputStream out = new FileOutputStream(dst); try { byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } } finally { out.close(); } } finally { in.close(); } } private boolean isExternalStorageWritable() { String state = Environment.getExternalStorageState(); if(Environment.MEDIA_MOUNTED.equals(state)) { return true; } return false; } private synchronized void serialize(String data) throws IOException { String directory = Environment.DIRECTORY_DOCUMENTS; File dir = null; if(context.getPackageName().contains("staging")) { dir = Environment.getExternalStoragePublicDirectory(directory + strOptionalBackupDir + "/staging"); } else { dir = Environment.getExternalStoragePublicDirectory(directory + strOptionalBackupDir); } if(!dir.exists()) { dir.mkdirs(); dir.setWritable(true, true); dir.setReadable(true, true); } File newfile = new File(dir, strOptionalFilename); newfile.setWritable(true, true); newfile.setReadable(true, true); JSONObject jsonObj = putPayload(data, false); if(jsonObj != null) { Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(newfile), "UTF-8")); try { out.write(jsonObj.toString()); } finally { out.close(); } } // // test payload // } public String getDecryptedBackupPayload(String data, CharSequenceX password) { String encrypted = null; try { JSONObject jsonObj = new JSONObject(data); if(jsonObj != null && jsonObj.has("payload")) { encrypted = jsonObj.getString("payload"); } else { encrypted = data; } } catch(JSONException je) { encrypted = data; } String decrypted = null; try { decrypted = AESUtil.decrypt(encrypted, password, AESUtil.DefaultPBKDF2Iterations); } catch (Exception e) { Toast.makeText(context, R.string.decryption_error, Toast.LENGTH_SHORT).show(); } finally { if (decrypted == null || decrypted.length() < 1) { Toast.makeText(context, R.string.decryption_error, Toast.LENGTH_SHORT).show(); // AppUtil.getInstance(context).restartApp(); } } return decrypted; } }
PayloadUtil: reset BIP84 account on wipe
app/src/main/java/com/samourai/wallet/payload/PayloadUtil.java
PayloadUtil: reset BIP84 account on wipe
Java
apache-2.0
d0882c65e2e4d59a6e3315d43a078840815f6c1f
0
aldaris/wicket,selckin/wicket,mosoft521/wicket,topicusonderwijs/wicket,apache/wicket,bitstorm/wicket,freiheit-com/wicket,AlienQueen/wicket,AlienQueen/wicket,dashorst/wicket,klopfdreh/wicket,topicusonderwijs/wicket,klopfdreh/wicket,zwsong/wicket,Servoy/wicket,AlienQueen/wicket,topicusonderwijs/wicket,klopfdreh/wicket,astrapi69/wicket,bitstorm/wicket,freiheit-com/wicket,Servoy/wicket,mosoft521/wicket,martin-g/wicket-osgi,mafulafunk/wicket,astrapi69/wicket,apache/wicket,astrapi69/wicket,selckin/wicket,selckin/wicket,astrapi69/wicket,zwsong/wicket,Servoy/wicket,freiheit-com/wicket,freiheit-com/wicket,klopfdreh/wicket,apache/wicket,aldaris/wicket,aldaris/wicket,zwsong/wicket,aldaris/wicket,topicusonderwijs/wicket,apache/wicket,AlienQueen/wicket,dashorst/wicket,martin-g/wicket-osgi,martin-g/wicket-osgi,freiheit-com/wicket,mafulafunk/wicket,mafulafunk/wicket,mosoft521/wicket,AlienQueen/wicket,aldaris/wicket,topicusonderwijs/wicket,selckin/wicket,klopfdreh/wicket,dashorst/wicket,mosoft521/wicket,bitstorm/wicket,selckin/wicket,mosoft521/wicket,bitstorm/wicket,zwsong/wicket,bitstorm/wicket,dashorst/wicket,dashorst/wicket,apache/wicket,Servoy/wicket,Servoy/wicket
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package wicket; import java.io.OutputStream; import java.io.Serializable; import java.util.List; import java.util.Locale; import wicket.markup.ComponentTag; import wicket.util.string.AppendingStringBuffer; import wicket.util.string.Strings; import wicket.util.time.Time; /** * Abstract base class for different implementations of response writing. A * subclass must implement write(String) to write a String to the response * destination (whether it be a browser, a file, a test harness or some other * place). A subclass may optionally implement close(), encodeURL(String), * redirect(String), isRedirect() or setContentType(String) as appropriate. * * @author Jonathan Locke */ public abstract class Response implements Serializable { /** Default encoding of output stream */ private String defaultEncoding; /** * Closes the response output stream */ public void close() { } /** * Called when the Response needs to reset itself. * Subclasses can empty there buffer or build up state. */ public void reset() { } /** * An implementation of this method is only required if a subclass wishes to * support sessions via URL rewriting. This default implementation simply * returns the URL String it is passed. * * @param url * The URL to encode * @return The encoded url */ public CharSequence encodeURL(final CharSequence url) { return url; } /** * THIS METHOD IS NOT PART OF THE WICKET PUBLIC API. DO NOT USE IT. * * Loops over all the response filters that were set (if any) with the give * response returns the response buffer itself if there where now filters or * the response buffer that was created/returned by the filter(s) * * @param responseBuffer * The response buffer to be filtered * @return Returns the filtered string buffer. */ public final AppendingStringBuffer filter(AppendingStringBuffer responseBuffer) { List responseFilters = Application.get().getRequestCycleSettings().getResponseFilters(); if (responseFilters == null) { return responseBuffer; } for (int i = 0; i < responseFilters.size(); i++) { IResponseFilter filter = (IResponseFilter)responseFilters.get(i); responseBuffer = filter.filter(responseBuffer); } return responseBuffer; } /** * Get the default encoding * * @return default encoding */ public String getCharacterEncoding() { if (this.defaultEncoding == null) { return Application.get().getRequestCycleSettings().getResponseRequestEncoding(); } else { return this.defaultEncoding; } } /** * @return The output stream for this response */ public abstract OutputStream getOutputStream(); /** * Returns true if a redirection has occurred. The default implementation * always returns false since redirect is not implemented by default. * * @return True if the redirect method has been called, making this response * a redirect. */ public boolean isRedirect() { return false; } /** * CLIENTS SHOULD NEVER CALL THIS METHOD FOR DAY TO DAY USE! * <p> * A subclass may override this method to implement redirection. Subclasses * which have no need to do redirection may choose not to override this * default implementation, which does nothing. For example, if a subclass * wishes to write output to a file or is part of a testing harness, there * may be no meaning to redirection. * </p> * * @param url * The URL to redirect to */ public void redirect(final String url) { } /** * Set the default encoding for the output. * Note: It is up to the derived class to make use of the information. * Class Respsonse simply stores the value, but does not apply * it anywhere automatically. * * @param encoding */ public void setCharacterEncoding(final String encoding) { this.defaultEncoding = encoding; } /** * Set the content length on the response, if appropriate in the subclass. * This default implementation does nothing. * * @param length * The length of the content */ public void setContentLength(final long length) { } /** * Set the content type on the response, if appropriate in the subclass. * This default implementation does nothing. * * @param mimeType * The mime type */ public void setContentType(final String mimeType) { } /** * Set the contents last modified time, if appropriate in the subclass. * This default implementation does nothing. * @param time * The time object */ public void setLastModifiedTime(Time time) { } /** * @param locale * Locale to use for this response */ public void setLocale(final Locale locale) { } /** * Writes the given tag to via the write(String) abstract method. * * @param tag * The tag to write */ public final void write(final ComponentTag tag) { write(tag.toString()); } /** * Writes the given string to the Response subclass output destination. * * @param string * The string to write */ public abstract void write(final CharSequence string); /** * Writes the given string to the Response subclass output destination and * appends a cr/nl depending on the OS * * @param string */ public final void println(final CharSequence string) { write(string); write(Strings.LINE_SEPARATOR); } }
wicket/src/main/java/wicket/Response.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package wicket; import java.io.OutputStream; import java.util.List; import java.util.Locale; import wicket.markup.ComponentTag; import wicket.util.string.AppendingStringBuffer; import wicket.util.string.Strings; import wicket.util.time.Time; /** * Abstract base class for different implementations of response writing. A * subclass must implement write(String) to write a String to the response * destination (whether it be a browser, a file, a test harness or some other * place). A subclass may optionally implement close(), encodeURL(String), * redirect(String), isRedirect() or setContentType(String) as appropriate. * * @author Jonathan Locke */ public abstract class Response { /** Default encoding of output stream */ private String defaultEncoding; /** * Closes the response output stream */ public void close() { } /** * Called when the Response needs to reset itself. * Subclasses can empty there buffer or build up state. */ public void reset() { } /** * An implementation of this method is only required if a subclass wishes to * support sessions via URL rewriting. This default implementation simply * returns the URL String it is passed. * * @param url * The URL to encode * @return The encoded url */ public CharSequence encodeURL(final CharSequence url) { return url; } /** * THIS METHOD IS NOT PART OF THE WICKET PUBLIC API. DO NOT USE IT. * * Loops over all the response filters that were set (if any) with the give * response returns the response buffer itself if there where now filters or * the response buffer that was created/returned by the filter(s) * * @param responseBuffer * The response buffer to be filtered * @return Returns the filtered string buffer. */ public final AppendingStringBuffer filter(AppendingStringBuffer responseBuffer) { List responseFilters = Application.get().getRequestCycleSettings().getResponseFilters(); if (responseFilters == null) { return responseBuffer; } for (int i = 0; i < responseFilters.size(); i++) { IResponseFilter filter = (IResponseFilter)responseFilters.get(i); responseBuffer = filter.filter(responseBuffer); } return responseBuffer; } /** * Get the default encoding * * @return default encoding */ public String getCharacterEncoding() { if (this.defaultEncoding == null) { return Application.get().getRequestCycleSettings().getResponseRequestEncoding(); } else { return this.defaultEncoding; } } /** * @return The output stream for this response */ public abstract OutputStream getOutputStream(); /** * Returns true if a redirection has occurred. The default implementation * always returns false since redirect is not implemented by default. * * @return True if the redirect method has been called, making this response * a redirect. */ public boolean isRedirect() { return false; } /** * CLIENTS SHOULD NEVER CALL THIS METHOD FOR DAY TO DAY USE! * <p> * A subclass may override this method to implement redirection. Subclasses * which have no need to do redirection may choose not to override this * default implementation, which does nothing. For example, if a subclass * wishes to write output to a file or is part of a testing harness, there * may be no meaning to redirection. * </p> * * @param url * The URL to redirect to */ public void redirect(final String url) { } /** * Set the default encoding for the output. * Note: It is up to the derived class to make use of the information. * Class Respsonse simply stores the value, but does not apply * it anywhere automatically. * * @param encoding */ public void setCharacterEncoding(final String encoding) { this.defaultEncoding = encoding; } /** * Set the content length on the response, if appropriate in the subclass. * This default implementation does nothing. * * @param length * The length of the content */ public void setContentLength(final long length) { } /** * Set the content type on the response, if appropriate in the subclass. * This default implementation does nothing. * * @param mimeType * The mime type */ public void setContentType(final String mimeType) { } /** * Set the contents last modified time, if appropriate in the subclass. * This default implementation does nothing. * @param time * The time object */ public void setLastModifiedTime(Time time) { } /** * @param locale * Locale to use for this response */ public void setLocale(final Locale locale) { } /** * Writes the given tag to via the write(String) abstract method. * * @param tag * The tag to write */ public final void write(final ComponentTag tag) { write(tag.toString()); } /** * Writes the given string to the Response subclass output destination. * * @param string * The string to write */ public abstract void write(final CharSequence string); /** * Writes the given string to the Response subclass output destination and * appends a cr/nl depending on the OS * * @param string */ public final void println(final CharSequence string) { write(string); write(Strings.LINE_SEPARATOR); } }
Response may temporarily end up in the session (actually String response) so to be sure, make serializable git-svn-id: 6d6ade8e88b1292e17cba3559b7335a947e495e0@478035 13f79535-47bb-0310-9956-ffa450edef68
wicket/src/main/java/wicket/Response.java
Response may temporarily end up in the session (actually String response) so to be sure, make serializable
Java
apache-2.0
de8bc0bb9a7e0a1040d9cff7b8f4c26b81d3ac5b
0
Kloudtek/kryptotek-oss
/* * Copyright (c) 2015 Kloudtek Ltd */ package com.kloudtek.kryptotek.keystore; import com.kloudtek.kryptotek.*; import com.kloudtek.kryptotek.key.*; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.security.InvalidKeyException; /** * Created by yannick on 22/11/2014. */ public abstract class AbstractKeyStore implements KeyStore { protected CryptoEngine cryptoEngine; protected AbstractKeyStore() { cryptoEngine = CryptoUtils.getEngine(); } protected AbstractKeyStore(CryptoEngine cryptoEngine) { this.cryptoEngine = cryptoEngine; } @Override public Key getKey(String keyLabel) throws KeyNotFoundException, KeyStoreAccessException, InvalidKeyException { return getKey(keyLabel, null); } @Override public <X extends Key> X getKey(Class<X> keyClass, String keyLabel) throws KeyNotFoundException, KeyStoreAccessException, InvalidKeyException { return getKey(keyClass, keyLabel, null); } @Override public Key getKey(String keyLabel, KeyStoreAccessToken keyStoreAccessToken) throws KeyNotFoundException, KeyStoreAccessException, InvalidKeyException { return getKey(Key.class, keyLabel, keyStoreAccessToken); } @Override public void importKey(String label, com.kloudtek.kryptotek.Key key) throws KeyStoreAccessException { importKey(label, key, null); } @Override public <X extends Key> void importKey(String label, EncodedKey encodedKey, Class<X> keyType, KeyStoreAccessToken keyStoreAccessToken) throws KeyStoreAccessException, InvalidKeyException { importKey(label, cryptoEngine.readKey(keyType, encodedKey), keyStoreAccessToken); } @NotNull @Override public RSAKeyPair generateRSAKeyPair(String keyLabel, int keySize) throws KeyStoreAccessException { final RSAKeyPair key = cryptoEngine.generateRSAKeyPair(keySize); importKey(keyLabel, key); return key; } @NotNull @Override public AESKey generateAESKey(String keyLabel, AESKeyLen keySize) throws KeyStoreAccessException { final AESKey key = cryptoEngine.generateAESKey(keySize); importKey(keyLabel, key); return key; } @NotNull @Override public AESKey generateAESKey(String keyLabel, AESKeyLen keySize, DHPrivateKey dhPrivateKey, DHPublicKey dhPublicKey) throws InvalidKeyException, KeyStoreAccessException { final AESKey key = cryptoEngine.generateAESKey(keySize, dhPrivateKey, dhPublicKey); importKey(keyLabel, key); return key; } @NotNull @Override public AESKey generatePBEAESKey(String keyLabel, char[] credential, int iterations, byte[] salt, AESKeyLen keyLen) throws KeyStoreAccessException { final AESKey key = cryptoEngine.generatePBEAESKey(DigestAlgorithm.SHA256, credential, iterations, salt, keyLen); importKey(keyLabel, key); return key; } @NotNull @Override public HMACKey generateHMACKey(String keyLabel, DigestAlgorithm digestAlgorithm) throws KeyStoreAccessException { final HMACKey key = cryptoEngine.generateHMACKey(digestAlgorithm); importKey(keyLabel, key); return key; } @NotNull @Override public HMACKey generateHMACKey(String keyLabel, DigestAlgorithm digestAlgorithm, DHPrivateKey dhPrivateKey, DHPublicKey dhPublicKey) throws InvalidKeyException, KeyStoreAccessException { final HMACKey key = cryptoEngine.generateHMACKey(digestAlgorithm, dhPrivateKey, dhPublicKey); importKey(keyLabel, key); return key; } @NotNull @Override public DHKeyPair generateDHKeyPair(String keyLabel, DHParameters parameterSpec) throws KeyStoreAccessException { final DHKeyPair keyPair = cryptoEngine.generateDHKeyPair(parameterSpec); importKey(keyLabel, keyPair); return keyPair; } @Override public HMACKey getHMACKey(@NotNull String keyLabel, @Nullable KeyStoreAccessToken keyStoreAccessToken) throws KeyNotFoundException, KeyStoreAccessException, InvalidKeyException { return getKey(HMACKey.class, keyLabel, keyStoreAccessToken); } @Override public HMACKey getHMACKey(String keyLabel) throws KeyNotFoundException, KeyStoreAccessException, InvalidKeyException { return getKey(HMACKey.class, keyLabel); } @Override public AESKey getAESKey(String keyLabel, KeyStoreAccessToken keyStoreAccessToken) throws KeyNotFoundException, KeyStoreAccessException, InvalidKeyException { return getKey(AESKey.class, keyLabel, keyStoreAccessToken); } @Override public AESKey getAESKey(String keyLabel) throws KeyNotFoundException, KeyStoreAccessException, InvalidKeyException { return getKey(AESKey.class, keyLabel); } @Override public RSAKeyPair getRSAKeyPair(String keyLabel, KeyStoreAccessToken keyStoreAccessToken) throws KeyNotFoundException, KeyStoreAccessException, InvalidKeyException { return getKey(RSAKeyPair.class, keyLabel, keyStoreAccessToken); } @Override public RSAKeyPair getRSAKeyPair(String keyLabel) throws KeyNotFoundException, KeyStoreAccessException, InvalidKeyException { return getKey(RSAKeyPair.class, keyLabel); } @Override public RSAPublicKey getRSAPublicKey(String keyLabel, KeyStoreAccessToken keyStoreAccessToken) throws KeyNotFoundException, KeyStoreAccessException, InvalidKeyException { return getKey(RSAPublicKey.class, keyLabel, keyStoreAccessToken); } @Override public RSAPublicKey getRSAPublicKey(String keyLabel) throws KeyNotFoundException, KeyStoreAccessException, InvalidKeyException { return getKey(RSAPublicKey.class, keyLabel); } @Override public DHKeyPair getDHKeyPair(String keyLabel, KeyStoreAccessToken keyStoreAccessToken) throws KeyNotFoundException, KeyStoreAccessException, InvalidKeyException { return getKey(DHKeyPair.class, keyLabel, keyStoreAccessToken); } @Override public DHKeyPair getDHKeyPair(String keyLabel) throws KeyNotFoundException, KeyStoreAccessException, InvalidKeyException { return getKey(DHKeyPair.class, keyLabel); } @Override public Certificate getCertificate(String keyLabel, KeyStoreAccessToken keyStoreAccessToken) throws KeyNotFoundException, KeyStoreAccessException, InvalidKeyException { return getKey(Certificate.class, keyLabel, keyStoreAccessToken); } @Override public Certificate getCertificate(String keyLabel) throws KeyNotFoundException, KeyStoreAccessException, InvalidKeyException { return getKey(Certificate.class, keyLabel); } }
core/src/main/java/com/kloudtek/kryptotek/keystore/AbstractKeyStore.java
/* * Copyright (c) 2015 Kloudtek Ltd */ package com.kloudtek.kryptotek.keystore; import com.kloudtek.kryptotek.*; import com.kloudtek.kryptotek.key.*; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.security.InvalidKeyException; /** * Created by yannick on 22/11/2014. */ public abstract class AbstractKeyStore implements KeyStore { protected CryptoEngine cryptoEngine; protected AbstractKeyStore() { cryptoEngine = CryptoUtils.getEngine(); } protected AbstractKeyStore(CryptoEngine cryptoEngine) { this.cryptoEngine = cryptoEngine; } @Override public Key getKey(String keyLabel) throws KeyNotFoundException, KeyStoreAccessException, InvalidKeyException { return getKey(keyLabel, null); } @Override public <X extends Key> X getKey(Class<X> keyClass, String keyLabel) throws KeyNotFoundException, KeyStoreAccessException, InvalidKeyException { return getKey(keyClass, keyLabel, null); } @Override public Key getKey(String keyLabel, KeyStoreAccessToken keyStoreAccessToken) throws KeyNotFoundException, KeyStoreAccessException, InvalidKeyException { return getKey(Key.class, keyLabel, keyStoreAccessToken); } @Override public void importKey(String label, com.kloudtek.kryptotek.Key key) throws KeyStoreAccessException { importKey(label, key, null); } @Override public <X extends Key> void importKey(String label, EncodedKey encodedKey, Class<X> keyType, KeyStoreAccessToken keyStoreAccessToken) throws KeyStoreAccessException, InvalidKeyException { importKey(label, cryptoEngine.readKey(keyType, encodedKey), keyStoreAccessToken); } @NotNull @Override public RSAKeyPair generateRSAKeyPair(String keyLabel, int keySize) throws KeyStoreAccessException { final RSAKeyPair key = cryptoEngine.generateRSAKeyPair(keySize); importKey(keyLabel, key); return key; } @NotNull @Override public AESKey generateAESKey(String keyLabel, AESKeyLen keySize) throws KeyStoreAccessException { final AESKey key = cryptoEngine.generateAESKey(keySize); importKey(keyLabel, key); return key; } @NotNull @Override public AESKey generateAESKey(String keyLabel, AESKeyLen keySize, DHPrivateKey dhPrivateKey, DHPublicKey dhPublicKey) throws InvalidKeyException, KeyStoreAccessException { final AESKey key = cryptoEngine.generateAESKey(keySize, dhPrivateKey, dhPublicKey); importKey(keyLabel, key); return key; } @NotNull @Override public AESKey generatePBEAESKey(String keyLabel, char[] credential, int iterations, byte[] salt, AESKeyLen keyLen) throws KeyStoreAccessException { final AESKey key = cryptoEngine.generatePBEAESKey(DigestAlgorithm.SHA256, credential, iterations, salt, keyLen); importKey(keyLabel, key); return key; } @NotNull @Override public HMACKey generateHMACKey(String keyLabel, DigestAlgorithm digestAlgorithm) throws KeyStoreAccessException { final HMACKey key = cryptoEngine.generateHMACKey(digestAlgorithm); importKey(keyLabel, key); return key; } @NotNull @Override public HMACKey generateHMACKey(String keyLabel, DigestAlgorithm digestAlgorithm, DHPrivateKey dhPrivateKey, DHPublicKey dhPublicKey) throws InvalidKeyException, KeyStoreAccessException { final HMACKey key = cryptoEngine.generateHMACKey(digestAlgorithm, dhPrivateKey, dhPublicKey); importKey(keyLabel, key); return key; } @NotNull @Override public DHKeyPair generateDHKeyPair(String keyLabel, DHParameters parameterSpec) throws KeyStoreAccessException { final DHKeyPair keyPair = cryptoEngine.generateDHKeyPair(parameterSpec); importKey(keyLabel, keyPair); return keyPair; } @Override public HMACKey getHMACKey(@NotNull String keyLabel, @Nullable KeyStoreAccessToken keyStoreAccessToken) throws KeyNotFoundException, KeyStoreAccessException, InvalidKeyException { return getKey(HMACKey.class, keyLabel, keyStoreAccessToken); } @Override public HMACKey getHMACKey(String keyLabel) throws KeyNotFoundException, KeyStoreAccessException, InvalidKeyException { return getKey(HMACKey.class, keyLabel); } @Override public AESKey getAESKey(String keyLabel, KeyStoreAccessToken keyStoreAccessToken) throws KeyNotFoundException, KeyStoreAccessException, InvalidKeyException { return getKey(AESKey.class, keyLabel, keyStoreAccessToken); } @Override public AESKey getAESKey(String keyLabel) throws KeyNotFoundException, KeyStoreAccessException, InvalidKeyException { return getKey(AESKey.class, keyLabel); } @Override public RSAKeyPair getRSAKeyPair(String keyLabel, KeyStoreAccessToken keyStoreAccessToken) throws KeyNotFoundException, KeyStoreAccessException, InvalidKeyException { return getKey(RSAKeyPair.class, keyLabel, keyStoreAccessToken); } @Override public RSAKeyPair getRSAKeyPair(String keyLabel) throws KeyNotFoundException, KeyStoreAccessException, InvalidKeyException { return getKey(RSAKeyPair.class, keyLabel); } @Override public RSAPublicKey getRSAPublicKey(String keyLabel, KeyStoreAccessToken keyStoreAccessToken) throws KeyNotFoundException, KeyStoreAccessException, InvalidKeyException { return getKey(RSAPublicKey.class, keyLabel, keyStoreAccessToken); } @Override public RSAPublicKey getRSAPublicKey(String keyLabel) throws KeyNotFoundException, KeyStoreAccessException, InvalidKeyException { return getKey(RSAPublicKey.class, keyLabel); } @Override public DHKeyPair getDHKeyPair(String keyLabel, KeyStoreAccessToken keyStoreAccessToken) throws KeyNotFoundException, KeyStoreAccessException, InvalidKeyException { return getKey(DHKeyPair.class, keyLabel, keyStoreAccessToken); } @Override public DHKeyPair getDHKeyPair(String keyLabel) throws KeyNotFoundException, KeyStoreAccessException, InvalidKeyException { return getKey(DHKeyPair.class, keyLabel); } @Override public Certificate getCertificate(String keyLabel, KeyStoreAccessToken keyStoreAccessToken) throws KeyNotFoundException, KeyStoreAccessException, InvalidKeyException { return getKey(Certificate.class, keyLabel, keyStoreAccessToken); } @Override public Certificate getCertificate(String keyLabel) throws KeyNotFoundException, KeyStoreAccessException, InvalidKeyException { return getKey(Certificate.class, keyLabel); } private static Class<? extends HMACKey> getHMACClass(@NotNull DigestAlgorithm digestAlgorithm) { switch (digestAlgorithm) { case SHA1: return HMACSHA1Key.class; case SHA256: return HMACSHA256Key.class; case SHA512: return HMACSHA512Key.class; default: throw new IllegalArgumentException("Unsupported HMAC digest type: "+digestAlgorithm); } } }
Fixed bug in keystore (get key must be transactional)
core/src/main/java/com/kloudtek/kryptotek/keystore/AbstractKeyStore.java
Fixed bug in keystore (get key must be transactional)
Java
apache-2.0
466286da0d2c92d8e0f9544ba908cf6dd9658606
0
retomerz/intellij-community,ibinti/intellij-community,FHannes/intellij-community,FHannes/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,salguarnieri/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,apixandru/intellij-community,hurricup/intellij-community,semonte/intellij-community,apixandru/intellij-community,ibinti/intellij-community,MER-GROUP/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,signed/intellij-community,salguarnieri/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,lucafavatella/intellij-community,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,vvv1559/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,signed/intellij-community,fitermay/intellij-community,allotria/intellij-community,retomerz/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,MER-GROUP/intellij-community,asedunov/intellij-community,kdwink/intellij-community,ibinti/intellij-community,signed/intellij-community,semonte/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,xfournet/intellij-community,apixandru/intellij-community,asedunov/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,da1z/intellij-community,da1z/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,lucafavatella/intellij-community,retomerz/intellij-community,michaelgallacher/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,semonte/intellij-community,signed/intellij-community,salguarnieri/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,kdwink/intellij-community,semonte/intellij-community,allotria/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,MER-GROUP/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,lucafavatella/intellij-community,semonte/intellij-community,youdonghai/intellij-community,lucafavatella/intellij-community,asedunov/intellij-community,FHannes/intellij-community,fitermay/intellij-community,allotria/intellij-community,da1z/intellij-community,asedunov/intellij-community,allotria/intellij-community,asedunov/intellij-community,da1z/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,kdwink/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,salguarnieri/intellij-community,salguarnieri/intellij-community,fitermay/intellij-community,xfournet/intellij-community,asedunov/intellij-community,FHannes/intellij-community,lucafavatella/intellij-community,mglukhikh/intellij-community,retomerz/intellij-community,apixandru/intellij-community,signed/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,salguarnieri/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,michaelgallacher/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,MER-GROUP/intellij-community,asedunov/intellij-community,MER-GROUP/intellij-community,xfournet/intellij-community,salguarnieri/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,retomerz/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,michaelgallacher/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,lucafavatella/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,signed/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,kdwink/intellij-community,youdonghai/intellij-community,kdwink/intellij-community,vvv1559/intellij-community,allotria/intellij-community,allotria/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,vvv1559/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,retomerz/intellij-community,ibinti/intellij-community,hurricup/intellij-community,hurricup/intellij-community,salguarnieri/intellij-community,MER-GROUP/intellij-community,salguarnieri/intellij-community,lucafavatella/intellij-community,idea4bsd/idea4bsd,semonte/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,MER-GROUP/intellij-community,kdwink/intellij-community,retomerz/intellij-community,hurricup/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,hurricup/intellij-community,kdwink/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,allotria/intellij-community,xfournet/intellij-community,salguarnieri/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,da1z/intellij-community,hurricup/intellij-community,mglukhikh/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,fitermay/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,salguarnieri/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,fitermay/intellij-community,semonte/intellij-community,retomerz/intellij-community,xfournet/intellij-community,lucafavatella/intellij-community,fitermay/intellij-community,retomerz/intellij-community,fitermay/intellij-community,semonte/intellij-community,retomerz/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,kdwink/intellij-community,retomerz/intellij-community,da1z/intellij-community,fitermay/intellij-community,MER-GROUP/intellij-community,michaelgallacher/intellij-community,hurricup/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,allotria/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,MER-GROUP/intellij-community,da1z/intellij-community,xfournet/intellij-community,xfournet/intellij-community,kdwink/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,fitermay/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,kdwink/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,da1z/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,suncycheng/intellij-community,da1z/intellij-community,xfournet/intellij-community,apixandru/intellij-community,allotria/intellij-community,asedunov/intellij-community,FHannes/intellij-community,semonte/intellij-community,kdwink/intellij-community,suncycheng/intellij-community,salguarnieri/intellij-community,MER-GROUP/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,signed/intellij-community,apixandru/intellij-community,signed/intellij-community,allotria/intellij-community,signed/intellij-community,retomerz/intellij-community,MER-GROUP/intellij-community,da1z/intellij-community,vvv1559/intellij-community,kdwink/intellij-community,MER-GROUP/intellij-community,suncycheng/intellij-community,hurricup/intellij-community,retomerz/intellij-community,FHannes/intellij-community,FHannes/intellij-community,lucafavatella/intellij-community,idea4bsd/idea4bsd,lucafavatella/intellij-community,allotria/intellij-community,asedunov/intellij-community
/* * Copyright 2000-2011 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.ui.components; import com.intellij.openapi.util.text.StringUtil; import com.intellij.ui.AnchorableComponent; import com.intellij.ui.ColorUtil; import com.intellij.util.SystemProperties; import com.intellij.util.ui.UIUtil; import org.intellij.lang.annotations.JdkConstants; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.text.BadLocationException; import javax.swing.text.EditorKit; import javax.swing.text.html.HTMLEditorKit; import javax.swing.text.html.StyleSheet; import java.awt.*; import java.awt.event.FocusAdapter; import java.awt.event.FocusEvent; import java.util.Collections; public class JBLabel extends JLabel implements AnchorableComponent { private UIUtil.ComponentStyle myComponentStyle = UIUtil.ComponentStyle.REGULAR; private UIUtil.FontColor myFontColor = UIUtil.FontColor.NORMAL; private JComponent myAnchor = null; private JEditorPane myEditorPane = null; private JLabel myIconLabel = null; private boolean myMultiline = false; public JBLabel() { super(); } public JBLabel(@NotNull UIUtil.ComponentStyle componentStyle) { super(); setComponentStyle(componentStyle); } public JBLabel(@Nullable Icon image) { super(image); } public JBLabel(@NotNull String text) { super(text); } public JBLabel(@NotNull String text, @NotNull UIUtil.ComponentStyle componentStyle) { super(text); setComponentStyle(componentStyle); } public JBLabel(@NotNull String text, @NotNull UIUtil.ComponentStyle componentStyle, @NotNull UIUtil.FontColor fontColor) { super(text); setComponentStyle(componentStyle); setFontColor(fontColor); } public JBLabel(@NotNull String text, @JdkConstants.HorizontalAlignment int horizontalAlignment) { super(text, horizontalAlignment); } public JBLabel(@Nullable Icon image, @JdkConstants.HorizontalAlignment int horizontalAlignment) { super(image, horizontalAlignment); } public JBLabel(@NotNull String text, @Nullable Icon icon, @JdkConstants.HorizontalAlignment int horizontalAlignment) { super(text, icon, horizontalAlignment); } public void setComponentStyle(@NotNull UIUtil.ComponentStyle componentStyle) { myComponentStyle = componentStyle; UIUtil.applyStyle(componentStyle, this); } public UIUtil.ComponentStyle getComponentStyle() { return myComponentStyle; } public UIUtil.FontColor getFontColor() { return myFontColor; } public void setFontColor(@NotNull UIUtil.FontColor fontColor) { myFontColor = fontColor; } @Override public Color getForeground() { if (!isEnabled()) { return UIUtil.getLabelDisabledForeground(); } if (myFontColor != null) { return UIUtil.getLabelFontColor(myFontColor); } return super.getForeground(); } @Override public void setForeground(Color fg) { myFontColor = null; super.setForeground(fg); if (myEditorPane != null) { updateStyle(myEditorPane); } } @Override public void setAnchor(@Nullable JComponent anchor) { myAnchor = anchor; } @Override public JComponent getAnchor() { return myAnchor; } @Override public Dimension getPreferredSize() { return myAnchor == null || myAnchor == this ? super.getPreferredSize() : myAnchor.getPreferredSize(); } @Override public Dimension getMinimumSize() { return myAnchor == null || myAnchor == this ? super.getMinimumSize() : myAnchor.getMinimumSize(); } @Override protected void paintComponent(Graphics g) { if (myEditorPane == null) { super.paintComponent(g); } } @Override public void setText(String text) { super.setText(text); if (myEditorPane != null) { myEditorPane.setText(getText()); updateStyle(myEditorPane); checkMultiline(); } } @Override public void setIcon(Icon icon) { super.setIcon(icon); if (myIconLabel != null) { myIconLabel.setIcon(icon); updateLayout(); } } private void checkMultiline() { myMultiline = StringUtil.removeHtmlTags(getText()).contains(SystemProperties.getLineSeparator()); } @Override public void setFont(Font font) { super.setFont(font); if (myEditorPane != null) { updateStyle(myEditorPane); } } @Override public void setIconTextGap(int iconTextGap) { super.setIconTextGap(iconTextGap); if (myEditorPane != null) { updateLayout(); } } protected void updateLayout() { setLayout(new BorderLayout(getIcon() == null ? 0 : getIconTextGap(), 0)); add(myIconLabel, BorderLayout.WEST); add(myEditorPane, BorderLayout.CENTER); } @Override public void updateUI() { super.updateUI(); if (myEditorPane != null) { //init inner components again (if any) to provide proper colors when LAF is being changed setCopyable(false); setCopyable(true); } } /** * * In 'copyable' mode JBLabel has the same appearance but user can select text with mouse and copy it to clipboard with standard shortcut. * @return 'this' (the same instance) */ // // By default JBLabel is NOT copyable // This method re public JBLabel setCopyable(boolean copyable) { if (copyable ^ myEditorPane != null) { if (myEditorPane == null) { final JLabel ellipsisLabel = new JBLabel("..."); myIconLabel = new JLabel(getIcon()); myEditorPane = new JEditorPane() { @Override public void paint(Graphics g) { Dimension size = getSize(); boolean paintEllipsis = getPreferredSize().width > size.width && !myMultiline; if (!paintEllipsis) { super.paint(g); } else { Dimension ellipsisSize = ellipsisLabel.getPreferredSize(); int endOffset = size.width - ellipsisSize.width; try { // do not paint half of the letter endOffset = modelToView(viewToModel(new Point(endOffset, 0)) - 1).x; } catch (BadLocationException ignore) { } Shape oldClip = g.getClip(); g.clipRect(0, 0, endOffset, size.height); super.paint(g); g.setClip(oldClip); g.translate(endOffset, 0); ellipsisLabel.setSize(ellipsisSize); ellipsisLabel.paint(g); g.translate(-endOffset, 0); } } }; myEditorPane.addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent e) { if (myEditorPane == null) return; int caretPosition = myEditorPane.getCaretPosition(); myEditorPane.setSelectionStart(caretPosition); myEditorPane.setSelectionEnd(caretPosition); } }); myEditorPane.setContentType("text/html"); myEditorPane.setEditable(false); myEditorPane.setBackground(UIUtil.TRANSPARENT_COLOR); myEditorPane.setOpaque(false); myEditorPane.setBorder(null); myEditorPane.setText(getText()); checkMultiline(); myEditorPane.setCaretPosition(0); UIUtil.putClientProperty(myEditorPane, UIUtil.NOT_IN_HIERARCHY_COMPONENTS, Collections.singleton(ellipsisLabel)); updateStyle(myEditorPane); updateLayout(); } else { removeAll(); myEditorPane = null; myIconLabel = null; } } return this; } private void updateStyle(@NotNull JEditorPane pane) { EditorKit kit = pane.getEditorKit(); if (kit instanceof HTMLEditorKit) { StyleSheet css = ((HTMLEditorKit)kit).getStyleSheet(); css.addRule("body, p {" + "color:#" + ColorUtil.toHex(getForeground()) + ";" + "font-family:" + getFont().getFamily() + ";" + "font-size:" + getFont().getSize() + "pt;" + "white-space:nowrap;}"); } } }
platform/platform-api/src/com/intellij/ui/components/JBLabel.java
/* * Copyright 2000-2011 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.ui.components; import com.intellij.openapi.util.text.StringUtil; import com.intellij.ui.AnchorableComponent; import com.intellij.ui.ColorUtil; import com.intellij.util.SystemProperties; import com.intellij.util.ui.UIUtil; import org.intellij.lang.annotations.JdkConstants; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.text.BadLocationException; import javax.swing.text.EditorKit; import javax.swing.text.html.HTMLEditorKit; import javax.swing.text.html.StyleSheet; import java.awt.*; import java.awt.event.FocusAdapter; import java.awt.event.FocusEvent; import java.util.Collections; public class JBLabel extends JLabel implements AnchorableComponent { private UIUtil.ComponentStyle myComponentStyle = UIUtil.ComponentStyle.REGULAR; private UIUtil.FontColor myFontColor = UIUtil.FontColor.NORMAL; private JComponent myAnchor = null; private JEditorPane myEditorPane = null; private JLabel myIconLabel = null; private boolean myMultiline = false; public JBLabel() { super(); } public JBLabel(@NotNull UIUtil.ComponentStyle componentStyle) { super(); setComponentStyle(componentStyle); } public JBLabel(@Nullable Icon image) { super(image); } public JBLabel(@NotNull String text) { super(text); } public JBLabel(@NotNull String text, @NotNull UIUtil.ComponentStyle componentStyle) { super(text); setComponentStyle(componentStyle); } public JBLabel(@NotNull String text, @NotNull UIUtil.ComponentStyle componentStyle, @NotNull UIUtil.FontColor fontColor) { super(text); setComponentStyle(componentStyle); setFontColor(fontColor); } public JBLabel(@NotNull String text, @JdkConstants.HorizontalAlignment int horizontalAlignment) { super(text, horizontalAlignment); } public JBLabel(@Nullable Icon image, @JdkConstants.HorizontalAlignment int horizontalAlignment) { super(image, horizontalAlignment); } public JBLabel(@NotNull String text, @Nullable Icon icon, @JdkConstants.HorizontalAlignment int horizontalAlignment) { super(text, icon, horizontalAlignment); } public void setComponentStyle(@NotNull UIUtil.ComponentStyle componentStyle) { myComponentStyle = componentStyle; UIUtil.applyStyle(componentStyle, this); } public UIUtil.ComponentStyle getComponentStyle() { return myComponentStyle; } public UIUtil.FontColor getFontColor() { return myFontColor; } public void setFontColor(@NotNull UIUtil.FontColor fontColor) { myFontColor = fontColor; } @Override public Color getForeground() { if (!isEnabled()) { return UIUtil.getLabelDisabledForeground(); } if (myFontColor != null) { return UIUtil.getLabelFontColor(myFontColor); } return super.getForeground(); } @Override public void setForeground(Color fg) { myFontColor = null; super.setForeground(fg); if (myEditorPane != null) { updateStyle(myEditorPane); } } @Override public void setAnchor(@Nullable JComponent anchor) { myAnchor = anchor; } @Override public JComponent getAnchor() { return myAnchor; } @Override public Dimension getPreferredSize() { return myAnchor == null || myAnchor == this ? super.getPreferredSize() : myAnchor.getPreferredSize(); } @Override public Dimension getMinimumSize() { return myAnchor == null || myAnchor == this ? super.getMinimumSize() : myAnchor.getMinimumSize(); } @Override protected void paintComponent(Graphics g) { if (myEditorPane == null) { super.paintComponent(g); } } @Override public void setText(String text) { super.setText(text); if (myEditorPane != null) { myEditorPane.setText(getText()); updateStyle(myEditorPane); checkMultiline(); } } @Override public void setIcon(Icon icon) { super.setIcon(icon); if (myIconLabel != null) { myIconLabel.setIcon(icon); } } private void checkMultiline() { myMultiline = StringUtil.removeHtmlTags(getText()).contains(SystemProperties.getLineSeparator()); } @Override public void setFont(Font font) { super.setFont(font); if (myEditorPane != null) { updateStyle(myEditorPane); } } @Override public void setIconTextGap(int iconTextGap) { super.setIconTextGap(iconTextGap); if (myEditorPane != null) { setLayout(new BorderLayout(iconTextGap, 0)); add(myIconLabel, BorderLayout.WEST); add(myEditorPane, BorderLayout.CENTER); } } @Override public void updateUI() { super.updateUI(); if (myEditorPane != null) { //init inner components again (if any) to provide proper colors when LAF is being changed setCopyable(false); setCopyable(true); } } /** * * In 'copyable' mode JBLabel has the same appearance but user can select text with mouse and copy it to clipboard with standard shortcut. * @return 'this' (the same instance) */ // // By default JBLabel is NOT copyable // This method re public JBLabel setCopyable(boolean copyable) { if (copyable ^ myEditorPane != null) { if (myEditorPane == null) { final JLabel ellipsisLabel = new JBLabel("..."); myIconLabel = new JLabel(getIcon()); myEditorPane = new JEditorPane() { @Override public void paint(Graphics g) { Dimension size = getSize(); boolean paintEllipsis = getPreferredSize().width > size.width && !myMultiline; if (!paintEllipsis) { super.paint(g); } else { Dimension ellipsisSize = ellipsisLabel.getPreferredSize(); int endOffset = size.width - ellipsisSize.width; try { // do not paint half of the letter endOffset = modelToView(viewToModel(new Point(endOffset, 0)) - 1).x; } catch (BadLocationException ignore) { } Shape oldClip = g.getClip(); g.clipRect(0, 0, endOffset, size.height); super.paint(g); g.setClip(oldClip); g.translate(endOffset, 0); ellipsisLabel.setSize(ellipsisSize); ellipsisLabel.paint(g); g.translate(-endOffset, 0); } } }; myEditorPane.addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent e) { if (myEditorPane == null) return; int caretPosition = myEditorPane.getCaretPosition(); myEditorPane.setSelectionStart(caretPosition); myEditorPane.setSelectionEnd(caretPosition); } }); myEditorPane.setContentType("text/html"); myEditorPane.setEditable(false); myEditorPane.setBackground(UIUtil.TRANSPARENT_COLOR); myEditorPane.setOpaque(false); myEditorPane.setBorder(null); myEditorPane.setText(getText()); checkMultiline(); myEditorPane.setCaretPosition(0); UIUtil.putClientProperty(myEditorPane, UIUtil.NOT_IN_HIERARCHY_COMPONENTS, Collections.singleton(ellipsisLabel)); updateStyle(myEditorPane); setLayout(new BorderLayout(getIconTextGap(), 0)); add(myIconLabel, BorderLayout.WEST); add(myEditorPane, BorderLayout.CENTER); } else { removeAll(); myEditorPane = null; myIconLabel = null; } } return this; } private void updateStyle(@NotNull JEditorPane pane) { EditorKit kit = pane.getEditorKit(); if (kit instanceof HTMLEditorKit) { StyleSheet css = ((HTMLEditorKit)kit).getStyleSheet(); css.addRule("body, p {" + "color:#" + ColorUtil.toHex(getForeground()) + ";" + "font-family:" + getFont().getFamily() + ";" + "font-size:" + getFont().getSize() + "pt;" + "white-space:nowrap;}"); } } }
Make JBLabel copyable: fix layout
platform/platform-api/src/com/intellij/ui/components/JBLabel.java
Make JBLabel copyable: fix layout
Java
apache-2.0
2d797bb24d3aee9a502be106b35bf3a38f1b2bf5
0
FHannes/intellij-community,alphafoobar/intellij-community,da1z/intellij-community,xfournet/intellij-community,Lekanich/intellij-community,apixandru/intellij-community,consulo/consulo,supersven/intellij-community,tmpgit/intellij-community,fnouama/intellij-community,MER-GROUP/intellij-community,akosyakov/intellij-community,fnouama/intellij-community,allotria/intellij-community,youdonghai/intellij-community,caot/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,izonder/intellij-community,MER-GROUP/intellij-community,asedunov/intellij-community,xfournet/intellij-community,MichaelNedzelsky/intellij-community,slisson/intellij-community,diorcety/intellij-community,MichaelNedzelsky/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,wreckJ/intellij-community,FHannes/intellij-community,slisson/intellij-community,samthor/intellij-community,MER-GROUP/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,adedayo/intellij-community,dslomov/intellij-community,hurricup/intellij-community,TangHao1987/intellij-community,orekyuu/intellij-community,mglukhikh/intellij-community,orekyuu/intellij-community,orekyuu/intellij-community,ThiagoGarciaAlves/intellij-community,pwoodworth/intellij-community,vladmm/intellij-community,muntasirsyed/intellij-community,pwoodworth/intellij-community,fengbaicanhe/intellij-community,wreckJ/intellij-community,izonder/intellij-community,mglukhikh/intellij-community,jagguli/intellij-community,MER-GROUP/intellij-community,vladmm/intellij-community,signed/intellij-community,FHannes/intellij-community,adedayo/intellij-community,michaelgallacher/intellij-community,vvv1559/intellij-community,fengbaicanhe/intellij-community,slisson/intellij-community,ahb0327/intellij-community,ernestp/consulo,idea4bsd/idea4bsd,izonder/intellij-community,kdwink/intellij-community,tmpgit/intellij-community,izonder/intellij-community,kool79/intellij-community,asedunov/intellij-community,diorcety/intellij-community,slisson/intellij-community,orekyuu/intellij-community,fengbaicanhe/intellij-community,dslomov/intellij-community,fitermay/intellij-community,samthor/intellij-community,petteyg/intellij-community,wreckJ/intellij-community,asedunov/intellij-community,SerCeMan/intellij-community,MichaelNedzelsky/intellij-community,signed/intellij-community,Lekanich/intellij-community,blademainer/intellij-community,fitermay/intellij-community,gnuhub/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,xfournet/intellij-community,robovm/robovm-studio,petteyg/intellij-community,fengbaicanhe/intellij-community,nicolargo/intellij-community,signed/intellij-community,asedunov/intellij-community,ivan-fedorov/intellij-community,ftomassetti/intellij-community,gnuhub/intellij-community,vladmm/intellij-community,Lekanich/intellij-community,vladmm/intellij-community,holmes/intellij-community,wreckJ/intellij-community,da1z/intellij-community,vladmm/intellij-community,caot/intellij-community,michaelgallacher/intellij-community,semonte/intellij-community,ivan-fedorov/intellij-community,gnuhub/intellij-community,robovm/robovm-studio,fengbaicanhe/intellij-community,ibinti/intellij-community,izonder/intellij-community,akosyakov/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,gnuhub/intellij-community,ivan-fedorov/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,ryano144/intellij-community,vladmm/intellij-community,pwoodworth/intellij-community,nicolargo/intellij-community,dslomov/intellij-community,dslomov/intellij-community,lucafavatella/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,ibinti/intellij-community,muntasirsyed/intellij-community,izonder/intellij-community,fnouama/intellij-community,ahb0327/intellij-community,akosyakov/intellij-community,muntasirsyed/intellij-community,pwoodworth/intellij-community,supersven/intellij-community,alphafoobar/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,retomerz/intellij-community,akosyakov/intellij-community,Lekanich/intellij-community,clumsy/intellij-community,joewalnes/idea-community,mglukhikh/intellij-community,adedayo/intellij-community,adedayo/intellij-community,ol-loginov/intellij-community,idea4bsd/idea4bsd,muntasirsyed/intellij-community,slisson/intellij-community,nicolargo/intellij-community,SerCeMan/intellij-community,dslomov/intellij-community,consulo/consulo,michaelgallacher/intellij-community,fitermay/intellij-community,fnouama/intellij-community,youdonghai/intellij-community,diorcety/intellij-community,alphafoobar/intellij-community,izonder/intellij-community,holmes/intellij-community,mglukhikh/intellij-community,ahb0327/intellij-community,ryano144/intellij-community,fitermay/intellij-community,ivan-fedorov/intellij-community,xfournet/intellij-community,amith01994/intellij-community,nicolargo/intellij-community,Distrotech/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,michaelgallacher/intellij-community,fnouama/intellij-community,muntasirsyed/intellij-community,izonder/intellij-community,supersven/intellij-community,lucafavatella/intellij-community,SerCeMan/intellij-community,fitermay/intellij-community,ernestp/consulo,Distrotech/intellij-community,idea4bsd/idea4bsd,lucafavatella/intellij-community,pwoodworth/intellij-community,nicolargo/intellij-community,suncycheng/intellij-community,kdwink/intellij-community,lucafavatella/intellij-community,FHannes/intellij-community,joewalnes/idea-community,suncycheng/intellij-community,retomerz/intellij-community,semonte/intellij-community,blademainer/intellij-community,TangHao1987/intellij-community,orekyuu/intellij-community,ivan-fedorov/intellij-community,allotria/intellij-community,suncycheng/intellij-community,Distrotech/intellij-community,vvv1559/intellij-community,semonte/intellij-community,adedayo/intellij-community,fengbaicanhe/intellij-community,amith01994/intellij-community,caot/intellij-community,amith01994/intellij-community,orekyuu/intellij-community,jagguli/intellij-community,hurricup/intellij-community,ibinti/intellij-community,ibinti/intellij-community,kdwink/intellij-community,jexp/idea2,lucafavatella/intellij-community,xfournet/intellij-community,joewalnes/idea-community,asedunov/intellij-community,lucafavatella/intellij-community,amith01994/intellij-community,SerCeMan/intellij-community,jexp/idea2,tmpgit/intellij-community,mglukhikh/intellij-community,robovm/robovm-studio,jagguli/intellij-community,amith01994/intellij-community,ivan-fedorov/intellij-community,salguarnieri/intellij-community,retomerz/intellij-community,apixandru/intellij-community,MER-GROUP/intellij-community,jagguli/intellij-community,alphafoobar/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,ernestp/consulo,da1z/intellij-community,dslomov/intellij-community,clumsy/intellij-community,vvv1559/intellij-community,pwoodworth/intellij-community,ivan-fedorov/intellij-community,ftomassetti/intellij-community,ftomassetti/intellij-community,fnouama/intellij-community,alphafoobar/intellij-community,ol-loginov/intellij-community,Distrotech/intellij-community,semonte/intellij-community,tmpgit/intellij-community,robovm/robovm-studio,ftomassetti/intellij-community,lucafavatella/intellij-community,jagguli/intellij-community,joewalnes/idea-community,Lekanich/intellij-community,ThiagoGarciaAlves/intellij-community,ahb0327/intellij-community,hurricup/intellij-community,diorcety/intellij-community,blademainer/intellij-community,joewalnes/idea-community,gnuhub/intellij-community,fengbaicanhe/intellij-community,alphafoobar/intellij-community,akosyakov/intellij-community,apixandru/intellij-community,ryano144/intellij-community,muntasirsyed/intellij-community,nicolargo/intellij-community,vladmm/intellij-community,consulo/consulo,asedunov/intellij-community,retomerz/intellij-community,blademainer/intellij-community,akosyakov/intellij-community,clumsy/intellij-community,diorcety/intellij-community,Lekanich/intellij-community,alphafoobar/intellij-community,salguarnieri/intellij-community,da1z/intellij-community,holmes/intellij-community,TangHao1987/intellij-community,supersven/intellij-community,orekyuu/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,nicolargo/intellij-community,youdonghai/intellij-community,da1z/intellij-community,blademainer/intellij-community,asedunov/intellij-community,joewalnes/idea-community,caot/intellij-community,kool79/intellij-community,holmes/intellij-community,petteyg/intellij-community,ol-loginov/intellij-community,petteyg/intellij-community,jexp/idea2,jagguli/intellij-community,semonte/intellij-community,clumsy/intellij-community,salguarnieri/intellij-community,Distrotech/intellij-community,Lekanich/intellij-community,petteyg/intellij-community,pwoodworth/intellij-community,alphafoobar/intellij-community,ThiagoGarciaAlves/intellij-community,hurricup/intellij-community,akosyakov/intellij-community,ol-loginov/intellij-community,alphafoobar/intellij-community,samthor/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,fengbaicanhe/intellij-community,wreckJ/intellij-community,robovm/robovm-studio,diorcety/intellij-community,ibinti/intellij-community,jagguli/intellij-community,xfournet/intellij-community,diorcety/intellij-community,signed/intellij-community,tmpgit/intellij-community,consulo/consulo,gnuhub/intellij-community,ahb0327/intellij-community,hurricup/intellij-community,fitermay/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,petteyg/intellij-community,suncycheng/intellij-community,blademainer/intellij-community,salguarnieri/intellij-community,semonte/intellij-community,semonte/intellij-community,kool79/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,fitermay/intellij-community,diorcety/intellij-community,adedayo/intellij-community,petteyg/intellij-community,idea4bsd/idea4bsd,MER-GROUP/intellij-community,robovm/robovm-studio,youdonghai/intellij-community,youdonghai/intellij-community,kdwink/intellij-community,kool79/intellij-community,caot/intellij-community,apixandru/intellij-community,tmpgit/intellij-community,Lekanich/intellij-community,signed/intellij-community,muntasirsyed/intellij-community,MER-GROUP/intellij-community,orekyuu/intellij-community,da1z/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,ThiagoGarciaAlves/intellij-community,ahb0327/intellij-community,michaelgallacher/intellij-community,amith01994/intellij-community,SerCeMan/intellij-community,orekyuu/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,petteyg/intellij-community,michaelgallacher/intellij-community,adedayo/intellij-community,amith01994/intellij-community,MER-GROUP/intellij-community,kdwink/intellij-community,apixandru/intellij-community,robovm/robovm-studio,asedunov/intellij-community,ftomassetti/intellij-community,fnouama/intellij-community,muntasirsyed/intellij-community,MER-GROUP/intellij-community,lucafavatella/intellij-community,ivan-fedorov/intellij-community,clumsy/intellij-community,ibinti/intellij-community,jagguli/intellij-community,SerCeMan/intellij-community,holmes/intellij-community,blademainer/intellij-community,MichaelNedzelsky/intellij-community,samthor/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,SerCeMan/intellij-community,SerCeMan/intellij-community,izonder/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,caot/intellij-community,asedunov/intellij-community,ftomassetti/intellij-community,allotria/intellij-community,samthor/intellij-community,apixandru/intellij-community,semonte/intellij-community,apixandru/intellij-community,ryano144/intellij-community,ftomassetti/intellij-community,signed/intellij-community,MichaelNedzelsky/intellij-community,muntasirsyed/intellij-community,allotria/intellij-community,tmpgit/intellij-community,ernestp/consulo,vvv1559/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,lucafavatella/intellij-community,samthor/intellij-community,tmpgit/intellij-community,signed/intellij-community,gnuhub/intellij-community,dslomov/intellij-community,jagguli/intellij-community,wreckJ/intellij-community,pwoodworth/intellij-community,ftomassetti/intellij-community,joewalnes/idea-community,fitermay/intellij-community,signed/intellij-community,wreckJ/intellij-community,ivan-fedorov/intellij-community,ahb0327/intellij-community,retomerz/intellij-community,slisson/intellij-community,da1z/intellij-community,kool79/intellij-community,kool79/intellij-community,wreckJ/intellij-community,vvv1559/intellij-community,kdwink/intellij-community,supersven/intellij-community,Distrotech/intellij-community,clumsy/intellij-community,slisson/intellij-community,hurricup/intellij-community,clumsy/intellij-community,retomerz/intellij-community,diorcety/intellij-community,holmes/intellij-community,jexp/idea2,robovm/robovm-studio,allotria/intellij-community,da1z/intellij-community,youdonghai/intellij-community,ftomassetti/intellij-community,samthor/intellij-community,kdwink/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,vladmm/intellij-community,dslomov/intellij-community,FHannes/intellij-community,allotria/intellij-community,jagguli/intellij-community,muntasirsyed/intellij-community,ibinti/intellij-community,ryano144/intellij-community,ahb0327/intellij-community,Lekanich/intellij-community,da1z/intellij-community,FHannes/intellij-community,allotria/intellij-community,blademainer/intellij-community,Lekanich/intellij-community,samthor/intellij-community,ryano144/intellij-community,vladmm/intellij-community,petteyg/intellij-community,retomerz/intellij-community,apixandru/intellij-community,TangHao1987/intellij-community,suncycheng/intellij-community,tmpgit/intellij-community,kool79/intellij-community,holmes/intellij-community,ryano144/intellij-community,alphafoobar/intellij-community,caot/intellij-community,ryano144/intellij-community,michaelgallacher/intellij-community,robovm/robovm-studio,idea4bsd/idea4bsd,jexp/idea2,clumsy/intellij-community,retomerz/intellij-community,signed/intellij-community,jexp/idea2,holmes/intellij-community,Distrotech/intellij-community,kool79/intellij-community,supersven/intellij-community,hurricup/intellij-community,samthor/intellij-community,muntasirsyed/intellij-community,SerCeMan/intellij-community,fnouama/intellij-community,ibinti/intellij-community,caot/intellij-community,orekyuu/intellij-community,kdwink/intellij-community,diorcety/intellij-community,akosyakov/intellij-community,ryano144/intellij-community,kdwink/intellij-community,ernestp/consulo,allotria/intellij-community,ol-loginov/intellij-community,tmpgit/intellij-community,robovm/robovm-studio,jexp/idea2,TangHao1987/intellij-community,amith01994/intellij-community,michaelgallacher/intellij-community,tmpgit/intellij-community,slisson/intellij-community,amith01994/intellij-community,adedayo/intellij-community,akosyakov/intellij-community,kdwink/intellij-community,kool79/intellij-community,pwoodworth/intellij-community,samthor/intellij-community,supersven/intellij-community,fnouama/intellij-community,ahb0327/intellij-community,mglukhikh/intellij-community,salguarnieri/intellij-community,hurricup/intellij-community,MichaelNedzelsky/intellij-community,ftomassetti/intellij-community,lucafavatella/intellij-community,FHannes/intellij-community,ol-loginov/intellij-community,consulo/consulo,fitermay/intellij-community,jagguli/intellij-community,salguarnieri/intellij-community,suncycheng/intellij-community,SerCeMan/intellij-community,ThiagoGarciaAlves/intellij-community,consulo/consulo,pwoodworth/intellij-community,supersven/intellij-community,tmpgit/intellij-community,vladmm/intellij-community,wreckJ/intellij-community,suncycheng/intellij-community,supersven/intellij-community,youdonghai/intellij-community,holmes/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,nicolargo/intellij-community,petteyg/intellij-community,caot/intellij-community,salguarnieri/intellij-community,supersven/intellij-community,ol-loginov/intellij-community,MichaelNedzelsky/intellij-community,alphafoobar/intellij-community,clumsy/intellij-community,ivan-fedorov/intellij-community,signed/intellij-community,amith01994/intellij-community,ftomassetti/intellij-community,ahb0327/intellij-community,semonte/intellij-community,vladmm/intellij-community,dslomov/intellij-community,xfournet/intellij-community,hurricup/intellij-community,FHannes/intellij-community,michaelgallacher/intellij-community,slisson/intellij-community,MichaelNedzelsky/intellij-community,fengbaicanhe/intellij-community,ryano144/intellij-community,idea4bsd/idea4bsd,ahb0327/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,Distrotech/intellij-community,joewalnes/idea-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,adedayo/intellij-community,wreckJ/intellij-community,youdonghai/intellij-community,ryano144/intellij-community,suncycheng/intellij-community,joewalnes/idea-community,signed/intellij-community,Distrotech/intellij-community,salguarnieri/intellij-community,blademainer/intellij-community,Distrotech/intellij-community,akosyakov/intellij-community,amith01994/intellij-community,dslomov/intellij-community,slisson/intellij-community,suncycheng/intellij-community,TangHao1987/intellij-community,TangHao1987/intellij-community,mglukhikh/intellij-community,blademainer/intellij-community,pwoodworth/intellij-community,akosyakov/intellij-community,slisson/intellij-community,vladmm/intellij-community,alphafoobar/intellij-community,gnuhub/intellij-community,MER-GROUP/intellij-community,samthor/intellij-community,TangHao1987/intellij-community,apixandru/intellij-community,diorcety/intellij-community,jagguli/intellij-community,ivan-fedorov/intellij-community,vvv1559/intellij-community,holmes/intellij-community,da1z/intellij-community,nicolargo/intellij-community,ol-loginov/intellij-community,ThiagoGarciaAlves/intellij-community,SerCeMan/intellij-community,MichaelNedzelsky/intellij-community,vvv1559/intellij-community,adedayo/intellij-community,nicolargo/intellij-community,petteyg/intellij-community,MER-GROUP/intellij-community,apixandru/intellij-community,xfournet/intellij-community,ernestp/consulo,fengbaicanhe/intellij-community,fengbaicanhe/intellij-community,izonder/intellij-community,akosyakov/intellij-community,TangHao1987/intellij-community,apixandru/intellij-community,ftomassetti/intellij-community,clumsy/intellij-community,fnouama/intellij-community,ibinti/intellij-community,ibinti/intellij-community,supersven/intellij-community,xfournet/intellij-community,jexp/idea2,FHannes/intellij-community,MichaelNedzelsky/intellij-community,dslomov/intellij-community,Lekanich/intellij-community,ryano144/intellij-community,hurricup/intellij-community,allotria/intellij-community,ivan-fedorov/intellij-community,gnuhub/intellij-community,vvv1559/intellij-community,michaelgallacher/intellij-community,wreckJ/intellij-community,dslomov/intellij-community,samthor/intellij-community,hurricup/intellij-community,kool79/intellij-community,izonder/intellij-community,ahb0327/intellij-community,salguarnieri/intellij-community,kdwink/intellij-community,Lekanich/intellij-community,fengbaicanhe/intellij-community,kdwink/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,retomerz/intellij-community,adedayo/intellij-community,kool79/intellij-community,allotria/intellij-community,fnouama/intellij-community,blademainer/intellij-community,SerCeMan/intellij-community,apixandru/intellij-community,retomerz/intellij-community,orekyuu/intellij-community,lucafavatella/intellij-community,muntasirsyed/intellij-community,ThiagoGarciaAlves/intellij-community,petteyg/intellij-community,TangHao1987/intellij-community,ol-loginov/intellij-community,ol-loginov/intellij-community,TangHao1987/intellij-community,TangHao1987/intellij-community,Distrotech/intellij-community,pwoodworth/intellij-community,da1z/intellij-community,allotria/intellij-community,fitermay/intellij-community,mglukhikh/intellij-community,gnuhub/intellij-community,ol-loginov/intellij-community,clumsy/intellij-community,salguarnieri/intellij-community,ol-loginov/intellij-community,FHannes/intellij-community,holmes/intellij-community,MichaelNedzelsky/intellij-community,michaelgallacher/intellij-community,holmes/intellij-community,salguarnieri/intellij-community,robovm/robovm-studio,fnouama/intellij-community,asedunov/intellij-community,retomerz/intellij-community,kool79/intellij-community,robovm/robovm-studio,salguarnieri/intellij-community,xfournet/intellij-community,Distrotech/intellij-community,blademainer/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,gnuhub/intellij-community,orekyuu/intellij-community,caot/intellij-community,diorcety/intellij-community,retomerz/intellij-community,apixandru/intellij-community,clumsy/intellij-community,gnuhub/intellij-community,semonte/intellij-community,nicolargo/intellij-community,lucafavatella/intellij-community,supersven/intellij-community,MichaelNedzelsky/intellij-community,amith01994/intellij-community,vvv1559/intellij-community,wreckJ/intellij-community,lucafavatella/intellij-community,semonte/intellij-community,izonder/intellij-community,MER-GROUP/intellij-community,caot/intellij-community,fitermay/intellij-community,allotria/intellij-community,adedayo/intellij-community,youdonghai/intellij-community,slisson/intellij-community,caot/intellij-community
package com.intellij.testFramework; import com.intellij.codeHighlighting.HighlightDisplayLevel; import com.intellij.codeInsight.daemon.HighlightDisplayKey; import com.intellij.codeInspection.LocalInspectionTool; import com.intellij.codeInspection.ex.InspectionProfileImpl; import com.intellij.codeInspection.ex.InspectionTool; import com.intellij.codeInspection.ex.LocalInspectionToolWrapper; import com.intellij.ide.impl.ProjectUtil; import com.intellij.ide.startup.impl.StartupManagerImpl; import com.intellij.idea.IdeaLogger; import com.intellij.idea.IdeaTestApplication; import com.intellij.openapi.actionSystem.DataConstants; import com.intellij.openapi.actionSystem.DataProvider; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.command.undo.UndoManager; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.EditorFactory; import com.intellij.openapi.fileTypes.FileTypeManager; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.project.ModuleListener; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectManager; import com.intellij.openapi.project.ex.ProjectManagerEx; import com.intellij.openapi.projectRoots.ProjectJdk; import com.intellij.openapi.projectRoots.impl.JavaSdkImpl; import com.intellij.openapi.roots.*; import com.intellij.openapi.startup.StartupManager; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.Computable; import com.intellij.openapi.util.EmptyRunnable; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.ex.dummy.DummyFileSystem; import com.intellij.openapi.vfs.impl.VirtualFilePointerManagerImpl; import com.intellij.openapi.vfs.pointers.VirtualFilePointerManager; import com.intellij.profile.codeInspection.InspectionProfileManager; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiManager; import com.intellij.psi.codeStyle.CodeStyleSettings; import com.intellij.psi.codeStyle.CodeStyleSettingsManager; import com.intellij.psi.impl.PsiManagerImpl; import com.intellij.util.IncorrectOperationException; import com.intellij.util.LocalTimeCounter; import junit.framework.TestCase; import org.jetbrains.annotations.NonNls; import javax.swing.*; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; /** * A testcase that provides IDEA application and project. Note both are reused for each test run in the session so * be careful to return all the modification made to application and project components (such as settings) after * test is finished so other test aren't affected. The project is initialized with single module that have single * content&amp;source entry. For your convinience the project may be equipped with some mock JDK so your tests may * refer to external classes. In order to enable this feature you have to have a folder named "mockJDK" under * idea installation home that is used for test running. Place src.zip under that folder. We'd suggest this is real mock * so it contains classes that is really needed in order to speed up tests startup. */ @NonNls public class LightIdeaTestCase extends TestCase implements DataProvider { protected static final String PROFILE = "Configurable"; private static IdeaTestApplication ourApplication; private static Project ourProject; private static Module ourModule; private static ProjectJdk ourJDK; private static PsiManager ourPsiManager; private static boolean ourAssertionsInTestDetected; private static VirtualFile ourSourceRoot; private static TestCase ourTestCase = null; public static Thread ourTestThread; private Map<String, LocalInspectionTool> myAvailableTools = new HashMap<String, LocalInspectionTool>(); /** * @return Project to be used in tests for example for project components retrieval. */ public static Project getProject() { return ourProject; } /** * @return Module to be used in tests for example for module components retrieval. */ public static Module getModule() { return ourModule; } /** * Shortcut to PsiManager.getInstance(getProject()) */ public static PsiManager getPsiManager() { if (ourPsiManager == null) { ourPsiManager = PsiManager.getInstance(ourProject); } return ourPsiManager; } static void initApplication(final DataProvider dataProvider) throws Exception { ourApplication = IdeaTestApplication.getInstance(); ourApplication.setDataProvider(dataProvider); } private void cleanupApplicationCaches() { ((VirtualFilePointerManagerImpl)VirtualFilePointerManager.getInstance()).cleanupForNextTest(); if (ourProject != null) { UndoManager.getInstance(ourProject).dropHistory(); } resetAllFields(); /* if (ourPsiManager != null) { ((PsiManagerImpl)ourPsiManager).cleanupForNextTest(); } */ } protected void resetAllFields() { resetClassFields(getClass()); } private void resetClassFields(final Class<?> aClass) { if (aClass == null) return; final Field[] fields = aClass.getDeclaredFields(); for (Field field : fields) { final int modifiers = field.getModifiers(); if ((modifiers & Modifier.FINAL) == 0 && (modifiers & Modifier.STATIC) == 0 && !field.getType().isPrimitive()) { field.setAccessible(true); try { field.set(this, null); } catch (IllegalAccessException e) { e.printStackTrace(); } } } if (aClass == LightIdeaTestCase.class) return; resetClassFields(aClass.getSuperclass()); } private static void initProject(final ProjectJdk projectJDK) throws Exception { ApplicationManager.getApplication().runWriteAction(new Runnable() { @SuppressWarnings({"AssignmentToStaticFieldFromInstanceMethod"}) public void run() { if (ourProject != null) { ProjectUtil.closeProject(ourProject); } ourProject = ProjectManagerEx.getInstanceEx().newProject("LightIdeaTestCaseProject", false, false); ourPsiManager = null; ourModule = createMainModule(); ourSourceRoot = DummyFileSystem.getInstance().createRoot("src"); final ModuleRootManager rootManager = ModuleRootManager.getInstance(ourModule); final ModifiableRootModel rootModel = rootManager.getModifiableModel(); if (projectJDK != null) { ourJDK = projectJDK; rootModel.setJdk(projectJDK); } final ContentEntry contentEntry = rootModel.addContentEntry(ourSourceRoot); contentEntry.addSourceFolder(ourSourceRoot, false); rootModel.commit(); ProjectRootManager.getInstance(ourProject).addModuleRootListener(new ModuleRootListener() { public void beforeRootsChange(ModuleRootEvent event) { if (!event.isCausedByFileTypesChange()) { fail("Root modification in LightIdeaTestCase is not allowed."); } } public void rootsChanged(ModuleRootEvent event) { } }); ModuleManager.getInstance(ourProject).addModuleListener(new ModuleListener() { public void moduleAdded(Project project, Module module) { fail("Adding modules is not permitted in LightIdeaTestCase."); } public void beforeModuleRemoved(Project project, Module module) { } public void moduleRemoved(Project project, Module module) { } public void modulesRenamed(Project project, List<Module> modules) { } }); //((PsiManagerImpl) PsiManager.getInstance(ourProject)).runPreStartupActivity(); ((StartupManagerImpl)StartupManager.getInstance(getProject())).runStartupActivities(); } }); } protected static Module createMainModule() { return ApplicationManager.getApplication().runWriteAction(new Computable<Module>() { public Module compute() { return ModuleManager.getInstance(ourProject).newModule(""); } }); } /** * @return The only source root */ protected static VirtualFile getSourceRoot() { return ourSourceRoot; } protected void setUp() throws Exception { super.setUp(); doSetup(getProjectJDK(), configureLocalInspectionTools(), this, this.myAvailableTools); } static void doSetup(final ProjectJdk projectJDK, final LocalInspectionTool[] localInspectionTools, final DataProvider dataProvider, final Map<String, LocalInspectionTool> availableToolsMap) throws Exception { assertNull("Previous test " + ourTestCase + " haven't called tearDown(). Probably overriden without super call.", ourTestCase); IdeaLogger.ourErrorsOccurred = null; initApplication(dataProvider); if (ourProject == null || isJDKChanged(projectJDK)) { initProject(projectJDK); } for (LocalInspectionTool tool : localInspectionTools) { _enableInspectionTool(tool, availableToolsMap); } final InspectionProfileImpl profile = new InspectionProfileImpl("Configurable") { public LocalInspectionTool[] getHighlightingLocalInspectionTools() { final Collection<LocalInspectionTool> tools = availableToolsMap.values(); return tools.toArray(new LocalInspectionTool[tools.size()]); } public boolean isToolEnabled(HighlightDisplayKey key) { if (key == null) return false; return availableToolsMap.containsKey(key.toString()) || isNonInspectionHighlighting(key); } public HighlightDisplayLevel getErrorLevel(HighlightDisplayKey key) { final LocalInspectionTool localInspectionTool = availableToolsMap.get(key.toString()); return localInspectionTool != null ? localInspectionTool.getDefaultLevel() : HighlightDisplayLevel.WARNING; } public InspectionTool getInspectionTool(String shortName) { if (availableToolsMap.containsKey(shortName)) { return new LocalInspectionToolWrapper(availableToolsMap.get(shortName)); } return null; } }; final InspectionProfileManager inspectionProfileManager = InspectionProfileManager.getInstance(); inspectionProfileManager.addProfile(profile); inspectionProfileManager.setRootProfile(profile.getName()); assertFalse(getPsiManager().isDisposed()); CodeStyleSettingsManager.getInstance(getProject()).setTemporarySettings(new CodeStyleSettings()); } protected void enableInspectionTool(LocalInspectionTool tool){ _enableInspectionTool(tool, myAvailableTools); } private static void _enableInspectionTool(final LocalInspectionTool tool, final Map<String, LocalInspectionTool> availableToolsMap) { final String shortName = tool.getShortName(); final HighlightDisplayKey key = HighlightDisplayKey.find(shortName); if (key == null){ HighlightDisplayKey.register(shortName, tool.getDisplayName(), tool.getID()); } availableToolsMap.put(shortName, tool); } protected LocalInspectionTool[] configureLocalInspectionTools() { return new LocalInspectionTool[0]; } protected void tearDown() throws Exception { super.tearDown(); doTearDown(); } static void doTearDown() throws Exception { InspectionProfileManager.getInstance().deleteProfile(PROFILE); CodeStyleSettingsManager.getInstance(getProject()).setTemporarySettings(null); assertNotNull("Application components damaged", ProjectManager.getInstance()); ApplicationManager.getApplication().runWriteAction(new Runnable() { public void run() { try { final VirtualFile[] children = ourSourceRoot.getChildren(); for (VirtualFile aChildren : children) { aChildren.delete(this); } } catch (IOException e) { //noinspection CallToPrintStackTrace e.printStackTrace(); } } }); // final Project[] openProjects = ProjectManagerEx.getInstanceEx().getOpenProjects(); // assertTrue(Arrays.asList(openProjects).contains(ourProject)); assertFalse(PsiManager.getInstance(getProject()).isDisposed()); if (!ourAssertionsInTestDetected) { if (IdeaLogger.ourErrorsOccurred != null) { throw IdeaLogger.ourErrorsOccurred; } //assertTrue("Logger errors occurred. ", IdeaLogger.ourErrorsOccurred == null); } ourApplication.setDataProvider(null); ourTestCase = null; ((PsiManagerImpl)ourPsiManager).cleanupForNextTest(); final Editor[] allEditors = EditorFactory.getInstance().getAllEditors(); if (allEditors.length > 0) { for (Editor allEditor : allEditors) { EditorFactory.getInstance().releaseEditor(allEditor); } fail("Unreleased editors: " + allEditors.length); } } public final void runBare() throws Throwable { final Throwable[] throwables = new Throwable[1]; SwingUtilities.invokeAndWait(new Runnable() { public void run() { try { ourTestThread = Thread.currentThread(); startRunAndTear(); } catch (Throwable throwable) { throwables[0] = throwable; } finally { ourTestThread = null; try { cleanupApplicationCaches(); } catch (Exception e) { e.printStackTrace(); } } } }); if (throwables[0] != null) { throw throwables[0]; } // just to make sure all deffered Runnable's to finish SwingUtilities.invokeAndWait(EmptyRunnable.getInstance()); if (IdeaLogger.ourErrorsOccurred != null) { throw IdeaLogger.ourErrorsOccurred; } } private void startRunAndTear() throws Throwable { setUp(); try { ourAssertionsInTestDetected = true; runTest(); ourAssertionsInTestDetected = false; } finally { try{ tearDown(); } catch(Throwable th){ //noinspection CallToPrintStackTrace th.printStackTrace(); } } } public Object getData(String dataId) { if (dataId.equals(DataConstants.PROJECT)) { return ourProject; } else { return null; } } private static boolean isJDKChanged(final ProjectJdk newJDK) { return ourJDK == null || !Comparing.equal(ourJDK.getVersionString(), newJDK.getVersionString()); } protected ProjectJdk getProjectJDK() { return JavaSdkImpl.getMockJdk("java 1.4"); } /** * Creates dummy source file. One is not placed under source root so some PSI functions like resolve to external classes * may not work. Though it works significantly faster and yet can be used if you need to create some PSI structures for * test purposes * * @param fileName - name of the file to create. Extension is used to choose what PSI should be created like java, jsp, aj, xml etc. * @param text - file text. * @return dummy psi file. * @throws IncorrectOperationException */ protected static PsiFile createFile(String fileName, String text) throws IncorrectOperationException { return getPsiManager().getElementFactory().createFileFromText(fileName, text); } protected static PsiFile createPseudoPhysicalFile(String fileName, String text) throws IncorrectOperationException { return getPsiManager().getElementFactory().createFileFromText(fileName, FileTypeManager.getInstance().getFileTypeByFileName(fileName), text, LocalTimeCounter.currentTime(), true); } /** * Convinient conversion of testSomeTest -> someTest | SomeTest where testSomeTest is the name of current test. * * @param lowercaseFirstLetter - whether first letter after test should be lowercased. */ protected String getTestName(boolean lowercaseFirstLetter) { String name = getName(); assertTrue("Test name should start with 'test'", name.startsWith("test")); name = name.substring("test".length()); if (lowercaseFirstLetter) { name = Character.toLowerCase(name.charAt(0)) + name.substring(1); } return name; } protected static void commitDocument(final Document document) { PsiDocumentManager.getInstance(getProject()).commitDocument(document); } protected Document getDocument(final PsiFile file) { return PsiDocumentManager.getInstance(getProject()).getDocument(file); } }
ExtendedApi/src/com/intellij/testFramework/LightIdeaTestCase.java
package com.intellij.testFramework; import com.intellij.codeHighlighting.HighlightDisplayLevel; import com.intellij.codeInsight.daemon.HighlightDisplayKey; import com.intellij.codeInspection.LocalInspectionTool; import com.intellij.codeInspection.ex.InspectionProfileImpl; import com.intellij.codeInspection.ex.InspectionTool; import com.intellij.codeInspection.ex.LocalInspectionToolWrapper; import com.intellij.ide.impl.ProjectUtil; import com.intellij.ide.startup.impl.StartupManagerImpl; import com.intellij.idea.IdeaLogger; import com.intellij.idea.IdeaTestApplication; import com.intellij.openapi.actionSystem.DataConstants; import com.intellij.openapi.actionSystem.DataProvider; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.command.undo.UndoManager; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.EditorFactory; import com.intellij.openapi.fileTypes.FileTypeManager; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.project.ModuleListener; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectManager; import com.intellij.openapi.project.ex.ProjectManagerEx; import com.intellij.openapi.projectRoots.ProjectJdk; import com.intellij.openapi.projectRoots.impl.JavaSdkImpl; import com.intellij.openapi.roots.*; import com.intellij.openapi.startup.StartupManager; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.Computable; import com.intellij.openapi.util.EmptyRunnable; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.ex.dummy.DummyFileSystem; import com.intellij.openapi.vfs.impl.VirtualFilePointerManagerImpl; import com.intellij.openapi.vfs.pointers.VirtualFilePointerManager; import com.intellij.profile.codeInspection.InspectionProfileManager; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiManager; import com.intellij.psi.codeStyle.CodeStyleSettings; import com.intellij.psi.codeStyle.CodeStyleSettingsManager; import com.intellij.psi.impl.PsiManagerImpl; import com.intellij.util.IncorrectOperationException; import com.intellij.util.LocalTimeCounter; import junit.framework.TestCase; import org.jetbrains.annotations.NonNls; import javax.swing.*; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; /** * A testcase that provides IDEA application and project. Note both are reused for each test run in the session so * be careful to return all the modification made to application and project components (such as settings) after * test is finished so other test aren't affected. The project is initialized with single module that have single * content&amp;source entry. For your convinience the project may be equipped with some mock JDK so your tests may * refer to external classes. In order to enable this feature you have to have a folder named "mockJDK" under * idea installation home that is used for test running. Place src.zip under that folder. We'd suggest this is real mock * so it contains classes that is really needed in order to speed up tests startup. */ @NonNls public class LightIdeaTestCase extends TestCase implements DataProvider { protected static final String PROFILE = "Configurable"; private static IdeaTestApplication ourApplication; private static Project ourProject; private static Module ourModule; private static ProjectJdk ourJDK; private static PsiManager ourPsiManager; private static boolean ourAssertionsInTestDetected; private static VirtualFile ourSourceRoot; private static TestCase ourTestCase = null; public static Thread ourTestThread; private Map<String, LocalInspectionTool> myAvailableTools = new HashMap<String, LocalInspectionTool>(); /** * @return Project to be used in tests for example for project components retrieval. */ public static Project getProject() { return ourProject; } /** * @return Module to be used in tests for example for module components retrieval. */ public static Module getModule() { return ourModule; } /** * Shortcut to PsiManager.getInstance(getProject()) */ public static PsiManager getPsiManager() { if (ourPsiManager == null) { ourPsiManager = PsiManager.getInstance(ourProject); } return ourPsiManager; } static void initApplication(final DataProvider dataProvider) throws Exception { ourApplication = IdeaTestApplication.getInstance(); ourApplication.setDataProvider(dataProvider); } private void cleanupApplicationCaches() { ((VirtualFilePointerManagerImpl)VirtualFilePointerManager.getInstance()).cleanupForNextTest(); if (ourProject != null) { UndoManager.getInstance(ourProject).dropHistory(); } resetAllFields(); /* if (ourPsiManager != null) { ((PsiManagerImpl)ourPsiManager).cleanupForNextTest(); } */ } protected void resetAllFields() { resetClassFields(getClass()); } private void resetClassFields(final Class<?> aClass) { if (aClass == null) return; final Field[] fields = aClass.getDeclaredFields(); for (Field field : fields) { final int modifiers = field.getModifiers(); if ((modifiers & Modifier.FINAL) == 0 && (modifiers & Modifier.STATIC) == 0 && !field.getType().isPrimitive()) { field.setAccessible(true); try { field.set(this, null); } catch (IllegalAccessException e) { e.printStackTrace(); } } } if (aClass == LightIdeaTestCase.class) return; resetClassFields(aClass.getSuperclass()); } private static void initProject(final ProjectJdk projectJDK) throws Exception { ApplicationManager.getApplication().runWriteAction(new Runnable() { @SuppressWarnings({"AssignmentToStaticFieldFromInstanceMethod"}) public void run() { if (ourProject != null) { ProjectUtil.closeProject(ourProject); } ourProject = ProjectManagerEx.getInstanceEx().newProject("LightIdeaTestCaseProject", false, false); ourPsiManager = null; ourModule = createMainModule(); ourSourceRoot = DummyFileSystem.getInstance().createRoot("src"); final ModuleRootManager rootManager = ModuleRootManager.getInstance(ourModule); final ModifiableRootModel rootModel = rootManager.getModifiableModel(); if (projectJDK != null) { ourJDK = projectJDK; rootModel.setJdk(projectJDK); } final ContentEntry contentEntry = rootModel.addContentEntry(ourSourceRoot); contentEntry.addSourceFolder(ourSourceRoot, false); rootModel.commit(); ProjectRootManager.getInstance(ourProject).addModuleRootListener(new ModuleRootListener() { public void beforeRootsChange(ModuleRootEvent event) { if (!event.isCausedByFileTypesChange()) { fail("Root modification in LightIdeaTestCase is not allowed."); } } public void rootsChanged(ModuleRootEvent event) { } }); ModuleManager.getInstance(ourProject).addModuleListener(new ModuleListener() { public void moduleAdded(Project project, Module module) { fail("Adding modules is not permitted in LightIdeaTestCase."); } public void beforeModuleRemoved(Project project, Module module) { } public void moduleRemoved(Project project, Module module) { } public void modulesRenamed(Project project, List<Module> modules) { } }); //((PsiManagerImpl) PsiManager.getInstance(ourProject)).runPreStartupActivity(); ((StartupManagerImpl)StartupManager.getInstance(getProject())).runStartupActivities(); } }); } protected static Module createMainModule() { return ApplicationManager.getApplication().runWriteAction(new Computable<Module>() { public Module compute() { return ModuleManager.getInstance(ourProject).newModule(""); } }); } /** * @return The only source root */ protected static VirtualFile getSourceRoot() { return ourSourceRoot; } protected void setUp() throws Exception { super.setUp(); doSetup(getProjectJDK(), configureLocalInspectionTools(), this, this.myAvailableTools); } static void doSetup(final ProjectJdk projectJDK, final LocalInspectionTool[] localInspectionTools, final DataProvider dataProvider, final Map<String, LocalInspectionTool> availableToolsMap) throws Exception { assertNull("Previous test " + ourTestCase + " haven't called tearDown(). Probably overriden without super call.", ourTestCase); IdeaLogger.ourErrorsOccurred = null; initApplication(dataProvider); if (ourProject == null || isJDKChanged(projectJDK)) { initProject(projectJDK); } for (LocalInspectionTool tool : localInspectionTools) { _enableInspectionTool(tool, availableToolsMap); } final InspectionProfileImpl profile = new InspectionProfileImpl("Configurable") { public LocalInspectionTool[] getHighlightingLocalInspectionTools() { final Collection<LocalInspectionTool> tools = availableToolsMap.values(); return tools.toArray(new LocalInspectionTool[tools.size()]); } public boolean isToolEnabled(HighlightDisplayKey key) { if (key == null) return false; return availableToolsMap.containsKey(key.toString()) || isNonInspectionHighlighting(key); } public HighlightDisplayLevel getErrorLevel(HighlightDisplayKey key) { final LocalInspectionTool localInspectionTool = availableToolsMap.get(key.toString()); return localInspectionTool != null ? localInspectionTool.getDefaultLevel() : HighlightDisplayLevel.WARNING; } public InspectionTool getInspectionTool(String shortName) { if (availableToolsMap.containsKey(shortName)) { return new LocalInspectionToolWrapper(availableToolsMap.get(shortName)); } return null; } }; final InspectionProfileManager inspectionProfileManager = InspectionProfileManager.getInstance(); inspectionProfileManager.addProfile(profile); inspectionProfileManager.setRootProfile(profile.getName()); assertFalse(getPsiManager().isDisposed()); CodeStyleSettingsManager.getInstance(getProject()).setTemporarySettings(new CodeStyleSettings()); } protected void enableInspectionTool(LocalInspectionTool tool){ _enableInspectionTool(tool, myAvailableTools); } private static void _enableInspectionTool(final LocalInspectionTool tool, final Map<String, LocalInspectionTool> availableToolsMap) { final String shortName = tool.getShortName(); final HighlightDisplayKey key = HighlightDisplayKey.find(shortName); if (key == null){ HighlightDisplayKey.register(shortName, tool.getDisplayName(), tool.getID()); } availableToolsMap.put(shortName, tool); } protected LocalInspectionTool[] configureLocalInspectionTools() { return new LocalInspectionTool[0]; } protected void tearDown() throws Exception { super.tearDown(); doTearDown(); } static void doTearDown() throws Exception { InspectionProfileManager.getInstance().deleteProfile(PROFILE); CodeStyleSettingsManager.getInstance(getProject()).setTemporarySettings(null); assertNotNull("Application components damaged", ProjectManager.getInstance()); ApplicationManager.getApplication().runWriteAction(new Runnable() { public void run() { try { final VirtualFile[] children = ourSourceRoot.getChildren(); for (VirtualFile aChildren : children) { aChildren.delete(this); } } catch (IOException e) { //noinspection CallToPrintStackTrace e.printStackTrace(); } } }); // final Project[] openProjects = ProjectManagerEx.getInstanceEx().getOpenProjects(); // assertTrue(Arrays.asList(openProjects).contains(ourProject)); assertFalse(PsiManager.getInstance(getProject()).isDisposed()); if (!ourAssertionsInTestDetected) { if (IdeaLogger.ourErrorsOccurred != null) { throw IdeaLogger.ourErrorsOccurred; } //assertTrue("Logger errors occurred. ", IdeaLogger.ourErrorsOccurred == null); } ourApplication.setDataProvider(null); ourTestCase = null; ((PsiManagerImpl)ourPsiManager).cleanupForNextTest(); final Editor[] allEditors = EditorFactory.getInstance().getAllEditors(); if (allEditors.length > 0) { for (Editor allEditor : allEditors) { EditorFactory.getInstance().releaseEditor(allEditor); } fail("Unreleased editors: " + allEditors.length); } } public final void runBare() throws Throwable { final Throwable[] throwables = new Throwable[1]; SwingUtilities.invokeAndWait(new Runnable() { public void run() { try { ourTestThread = Thread.currentThread(); startRunAndTear(); } catch (Throwable throwable) { throwables[0] = throwable; } finally { ourTestThread = null; cleanupApplicationCaches(); } } }); if (throwables[0] != null) { throw throwables[0]; } // just to make sure all deffered Runnable's to finish SwingUtilities.invokeAndWait(EmptyRunnable.getInstance()); if (IdeaLogger.ourErrorsOccurred != null) { throw IdeaLogger.ourErrorsOccurred; } } private void startRunAndTear() throws Throwable { setUp(); try { ourAssertionsInTestDetected = true; runTest(); ourAssertionsInTestDetected = false; } finally { try{ tearDown(); } catch(Throwable th){ //noinspection CallToPrintStackTrace th.printStackTrace(); } } } public Object getData(String dataId) { if (dataId.equals(DataConstants.PROJECT)) { return ourProject; } else { return null; } } private static boolean isJDKChanged(final ProjectJdk newJDK) { return ourJDK == null || !Comparing.equal(ourJDK.getVersionString(), newJDK.getVersionString()); } protected ProjectJdk getProjectJDK() { return JavaSdkImpl.getMockJdk("java 1.4"); } /** * Creates dummy source file. One is not placed under source root so some PSI functions like resolve to external classes * may not work. Though it works significantly faster and yet can be used if you need to create some PSI structures for * test purposes * * @param fileName - name of the file to create. Extension is used to choose what PSI should be created like java, jsp, aj, xml etc. * @param text - file text. * @return dummy psi file. * @throws IncorrectOperationException */ protected static PsiFile createFile(String fileName, String text) throws IncorrectOperationException { return getPsiManager().getElementFactory().createFileFromText(fileName, text); } protected static PsiFile createPseudoPhysicalFile(String fileName, String text) throws IncorrectOperationException { return getPsiManager().getElementFactory().createFileFromText(fileName, FileTypeManager.getInstance().getFileTypeByFileName(fileName), text, LocalTimeCounter.currentTime(), true); } /** * Convinient conversion of testSomeTest -> someTest | SomeTest where testSomeTest is the name of current test. * * @param lowercaseFirstLetter - whether first letter after test should be lowercased. */ protected String getTestName(boolean lowercaseFirstLetter) { String name = getName(); assertTrue("Test name should start with 'test'", name.startsWith("test")); name = name.substring("test".length()); if (lowercaseFirstLetter) { name = Character.toLowerCase(name.charAt(0)) + name.substring(1); } return name; } protected static void commitDocument(final Document document) { PsiDocumentManager.getInstance(getProject()).commitDocument(document); } protected Document getDocument(final PsiFile file) { return PsiDocumentManager.getInstance(getProject()).getDocument(file); } }
surround call to cleanupApplicationCaches() with try catch in order to not miss exceptions during setup
ExtendedApi/src/com/intellij/testFramework/LightIdeaTestCase.java
surround call to cleanupApplicationCaches() with try catch in order to not miss exceptions during setup
Java
apache-2.0
5b41a4af9ca843ac4506c4a94e8a1b3f5f90961c
0
netarchivesuite/heritrix3-wrapper,nclarkekb/heritrix3-wrapper
package org.netarchivesuite.heritrix3wrapper; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.RandomAccessFile; import java.io.UnsupportedEncodingException; import java.nio.channels.FileChannel; import java.security.KeyManagementException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.UnrecoverableKeyException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.LinkedList; import java.util.List; import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import javax.xml.bind.JAXBException; import javax.xml.stream.XMLStreamException; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.NoHttpResponseException; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.conn.ssl.X509HostnameVerifier; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.message.BasicNameValuePair; import org.netarchivesuite.heritrix3wrapper.jaxb.Engine; import org.netarchivesuite.heritrix3wrapper.jaxb.Job; import org.netarchivesuite.heritrix3wrapper.jaxb.Script; import org.netarchivesuite.heritrix3wrapper.xmlutils.XmlValidator; public class Heritrix3Wrapper { protected HttpClient httpClient; protected String baseUrl; protected XmlValidator xmlValidator = new XmlValidator(); private static final String GC_ACTION= "action=gc"; private static final String RESCAN_ACTION = "action=rescan"; private static final String BUILD_ACTION = "action=build"; private static final String LAUNCH_ACTION = "action=launch"; private static final String TEARDOWN_ACTION = "action=teardown"; private static final String PAUSE_ACTION = "action=pause"; private static final String UNPAUSE_ACTION = "action=unpause"; private static final String TERMINATE_ACTION = "action=terminate"; private static final String CHECKPOINT_ACTION = "action=checkpoint"; public static enum CrawlControllerState { NASCENT, RUNNING, EMPTY, PAUSED, PAUSING, STOPPING, FINISHED, PREPARING } protected Heritrix3Wrapper() { } public static Heritrix3Wrapper getInstance(String hostname, int port, File keystoreFile, String keyStorePassword, String userName, String password) { Heritrix3Wrapper h3 = new Heritrix3Wrapper(); InputStream instream = null; KeyManager[] keyManagers = null; try { if (keystoreFile != null) { KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); instream = new FileInputStream(keystoreFile); ks.load(instream, keyStorePassword.toCharArray()); KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); kmf.init(ks, keyStorePassword.toCharArray()); keyManagers = kmf.getKeyManagers(); } X509TrustManager tm = new X509TrustManager() { public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException { } public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException { } public X509Certificate[] getAcceptedIssuers() { return null; } }; SSLContext sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(keyManagers, new TrustManager[] {tm}, null); X509HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER; //SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(ctx); //socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier); //Scheme sch = new Scheme("https", socketFactory, port); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(hostname, port), new UsernamePasswordCredentials(userName, password)); HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); //httpClientBuilder.setSSLSocketFactory(sslSocketFactory).setHostnameVerifier(hostnameVerifier); httpClientBuilder.setSslcontext(sslcontext); httpClientBuilder.setHostnameVerifier(hostnameVerifier); h3.httpClient = httpClientBuilder.setDefaultCredentialsProvider(credsProvider).build(); //h3.httpClient.getConnectionManager().getSchemeRegistry().register(sch); h3.baseUrl = "https://" + hostname + ":" + Integer.toString(port) + "/engine/"; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (CertificateException e) { e.printStackTrace(); } catch (UnrecoverableKeyException e) { e.printStackTrace(); } finally { if (instream != null) { try { instream.close(); } catch (IOException e) { } } } return h3; } /** * Send JVM shutdown to Heritrix 3. Also requres marked 'checkbox' for each active job. * @return * @throws UnsupportedEncodingException */ public EngineResult exitJavaProcess(List<String> ignoreJobs){ HttpPost postRequest = new HttpPost(baseUrl); List<NameValuePair> nvp = new LinkedList<NameValuePair>(); nvp.add(new BasicNameValuePair("action", "Exit Java Process")); nvp.add(new BasicNameValuePair("im_sure", "on")); // ignore__${jobname}=on if (ignoreJobs != null && ignoreJobs.size() > 0) { for (int i=0; i<ignoreJobs.size(); ++i) { nvp.add(new BasicNameValuePair("ignore__" + ignoreJobs.get(i), "on")); } } StringEntity postEntity = null; try { postEntity = new UrlEncodedFormEntity(nvp); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } postEntity.setContentType("application/x-www-form-urlencoded"); postRequest.addHeader("Accept", "application/xml"); postRequest.setEntity(postEntity); return engineResult(postRequest); } public EngineResult postEngineRequest(String url, String action) { HttpPost postRequest = new HttpPost(url); StringEntity postEntity = null; try { postEntity = new StringEntity(action); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } postEntity.setContentType("application/x-www-form-urlencoded"); postRequest.addHeader("Accept", "application/xml"); postRequest.setEntity(postEntity); return engineResult(postRequest); } /** * Returns engine state and a list of registered jobs. * @return engine state and a list of registered jobs * @throws UnsupportedEncodingException */ public EngineResult rescanJobDirectory() { return postEngineRequest(baseUrl, RESCAN_ACTION); } /** * Invoke GarbageCollector in JVM running Heritrix 3. * @return * @throws UnsupportedEncodingException */ public EngineResult gc() { return postEngineRequest(baseUrl, GC_ACTION); } /** * * @param tries * @param interval * @return * @throws UnsupportedEncodingException */ public EngineResult waitForEngineReady(int tries, int interval) { EngineResult engineResult = null; if (tries <= 0) { tries = 1; } if (interval <= 99) { interval = 1000; } boolean bLoop = true; while (bLoop && tries > 0) { engineResult = rescanJobDirectory(); // debug System.out.println(engineResult.status + " - " + ResultStatus.OK); if (engineResult.status == ResultStatus.OK) { bLoop = false; } --tries; if (bLoop && tries > 0) { try { Thread.sleep(interval); } catch (InterruptedException e) { } } } return engineResult; } /** * Creates a new job with the default cxml file which must be modified before launch. * @param jobname * @return * @throws UnsupportedEncodingException */ public EngineResult createNewJob(String jobname) { HttpPost postRequest = new HttpPost(baseUrl); List<NameValuePair> nvp = new LinkedList<NameValuePair>(); nvp.add(new BasicNameValuePair("action", "create")); nvp.add(new BasicNameValuePair("createpath", jobname)); StringEntity postEntity = null; try { postEntity = new UrlEncodedFormEntity(nvp); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } postEntity.setContentType("application/x-www-form-urlencoded"); postRequest.addHeader("Accept", "application/xml"); postRequest.setEntity(postEntity); return engineResult(postRequest); } /** * * @param path * @return * @throws UnsupportedEncodingException */ public EngineResult addJobDirectory(String path) { HttpPost postRequest = new HttpPost(baseUrl); List<NameValuePair> nvp = new LinkedList<NameValuePair>(); nvp.add(new BasicNameValuePair("action", "add")); nvp.add(new BasicNameValuePair("addpath", path)); StringEntity postEntity= null; try { postEntity = new UrlEncodedFormEntity(nvp); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } postEntity.setContentType("application/x-www-form-urlencoded"); postRequest.addHeader("Accept", "application/xml"); postRequest.setEntity(postEntity); return engineResult(postRequest); } public EngineResult engineResult(HttpRequestBase request) { EngineResult engineResult = new EngineResult(); try { HttpResponse response = httpClient.execute(request); if (response != null) { engineResult.responseCode = response.getStatusLine().getStatusCode(); HttpEntity responseEntity = response.getEntity(); long contentLength = responseEntity.getContentLength(); if (contentLength < 0) { contentLength = 0; } ByteArrayOutputStream bOut = new ByteArrayOutputStream((int) contentLength); InputStream in = responseEntity.getContent(); int read; byte[] tmpBuf = new byte[8192]; while ((read = in.read(tmpBuf)) != -1) { bOut.write(tmpBuf, 0, read); } in.close(); bOut.close(); engineResult.response = bOut.toByteArray(); switch (engineResult.responseCode) { case 200: engineResult.parse(xmlValidator); in = new ByteArrayInputStream(engineResult.response); engineResult.engine = Engine.unmarshall(in); in.close(); engineResult.status = ResultStatus.OK; break; case 404: engineResult.status = ResultStatus.NOT_FOUND; break; case 500: engineResult.status = ResultStatus.INTERNAL_ERROR; break; default: engineResult.status = ResultStatus.NO_RESPONSE; break; } } else { engineResult.status = ResultStatus.NO_RESPONSE; } } catch (NoHttpResponseException e) { engineResult.status = ResultStatus.OFFLINE; engineResult.t = e; } catch (ClientProtocolException e) { engineResult.status = ResultStatus.RESPONSE_EXCEPTION; engineResult.t = e; } catch (IOException e) { engineResult.status = ResultStatus.RESPONSE_EXCEPTION; engineResult.t = e; } catch (JAXBException e) { engineResult.status = ResultStatus.XML_EXCEPTION; engineResult.t = e; } catch (XMLStreamException e) { engineResult.status = ResultStatus.JAXB_EXCEPTION; engineResult.t = e; } return engineResult; } public JobResult jobResult(HttpRequestBase request) { JobResult jobResult = new JobResult(); try { HttpResponse response = httpClient.execute(request); if (response != null) { jobResult.responseCode = response.getStatusLine().getStatusCode(); HttpEntity responseEntity = response.getEntity(); long contentLength = responseEntity.getContentLength(); if (contentLength < 0) { contentLength = 0; } ByteArrayOutputStream bOut = new ByteArrayOutputStream((int) contentLength); InputStream in = responseEntity.getContent(); int read; byte[] tmpBuf = new byte[8192]; while ((read = in.read(tmpBuf)) != -1) { bOut.write(tmpBuf, 0, read); } in.close(); bOut.close(); jobResult.response = bOut.toByteArray(); switch (jobResult.responseCode) { case 200: jobResult.parse(xmlValidator); in = new ByteArrayInputStream(jobResult.response); jobResult.job = Job.unmarshall(in); in.close(); jobResult.status = ResultStatus.OK; break; case 404: jobResult.status = ResultStatus.NOT_FOUND; break; case 500: jobResult.status = ResultStatus.INTERNAL_ERROR; break; default: jobResult.status = ResultStatus.NO_RESPONSE; break; } } else { jobResult.status = ResultStatus.NO_RESPONSE; } } catch (NoHttpResponseException e) { jobResult.status = ResultStatus.OFFLINE; jobResult.t = e; } catch (ClientProtocolException e) { jobResult.status = ResultStatus.RESPONSE_EXCEPTION; jobResult.t = e; } catch (IOException e) { jobResult.status = ResultStatus.RESPONSE_EXCEPTION; jobResult.t = e; } catch (JAXBException e) { jobResult.status = ResultStatus.XML_EXCEPTION; jobResult.t = e; } catch (XMLStreamException e) { jobResult.status = ResultStatus.JAXB_EXCEPTION; jobResult.t = e; } return jobResult; } /** * Returns job object given a jobname. * @param jobname * @return */ public JobResult job(String jobname) { HttpGet getRequest = new HttpGet(baseUrl + "job/" + jobname); getRequest.addHeader("Accept", "application/xml"); return jobResult(getRequest); } public JobResult waitForJobState(String jobname, CrawlControllerState state, int tries, int interval) throws UnsupportedEncodingException { JobResult jobResult = null; if (tries <= 0) { tries = 1; } if (interval <= 99) { interval = 1000; } boolean bLoop = true; while (bLoop && tries > 0) { jobResult = job(jobname); // debug System.out.println(jobResult.status + " - " + ResultStatus.OK); if (jobResult.status == ResultStatus.OK) { // debug System.out.println(jobResult.job.crawlControllerState + " - " + state.name()); if (state.name().equals(jobResult.job.crawlControllerState)) { bLoop = false; } } --tries; if (bLoop && tries > 0) { try { Thread.sleep(interval); } catch (InterruptedException e) { } } } return jobResult; } /** * * @param srcJobname * @param dstJobName * @param bAsProfile * @return * @throws UnsupportedEncodingException */ public JobResult copyJob(String srcJobname, String dstJobName, boolean bAsProfile) { HttpPost postRequest = new HttpPost(baseUrl + "job/" + srcJobname); List<NameValuePair> nvp = new LinkedList<NameValuePair>(); nvp.add(new BasicNameValuePair("copyTo", dstJobName)); if (bAsProfile) { nvp.add(new BasicNameValuePair("asProfile", "on")); } StringEntity postEntity = null; try { postEntity = new UrlEncodedFormEntity(nvp); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } postEntity.setContentType("application/x-www-form-urlencoded"); postRequest.addHeader("Accept", "application/xml"); postRequest.setEntity(postEntity); return jobResult(postRequest); } /** * Build an existing job. * @param jobname * @return * @throws UnsupportedEncodingException */ public JobResult buildJobConfiguration(String jobname){ HttpPost postRequest = new HttpPost(baseUrl + "job/" + jobname); StringEntity postEntity = null; try { postEntity = new StringEntity(BUILD_ACTION); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } postEntity.setContentType("application/x-www-form-urlencoded"); postRequest.addHeader("Accept", "application/xml"); postRequest.setEntity(postEntity); return jobResult(postRequest); } /** * Teardown job and return it's state to unbuild. Note the job object will not include all the information present before calling this method. * @param jobname * @return */ public JobResult teardownJob(String jobname) { HttpPost postRequest = new HttpPost(baseUrl + "job/" + jobname); StringEntity postEntity = null; try { postEntity = new StringEntity(TEARDOWN_ACTION); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } postEntity.setContentType("application/x-www-form-urlencoded"); postRequest.addHeader("Accept", "application/xml"); postRequest.setEntity(postEntity); return jobResult(postRequest); } /** * Launch a built job in pause state. * @param jobname * @return * @throws UnsupportedEncodingException */ public JobResult launchJob(String jobname) { HttpPost postRequest = new HttpPost(baseUrl + "job/" + jobname); StringEntity postEntity = null; try { postEntity = new StringEntity(LAUNCH_ACTION); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } postEntity.setContentType("application/x-www-form-urlencoded"); postRequest.addHeader("Accept", "application/xml"); postRequest.setEntity(postEntity); return jobResult(postRequest); } /** * Pause running job. * @param jobname * @return */ public JobResult pauseJob(String jobname) { HttpPost postRequest = new HttpPost(baseUrl + "job/" + jobname); StringEntity postEntity = null; try { postEntity = new StringEntity(PAUSE_ACTION); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } postEntity.setContentType("application/x-www-form-urlencoded"); postRequest.addHeader("Accept", "application/xml"); postRequest.setEntity(postEntity); return jobResult(postRequest); } /** * Un-pause job. * @param jobname * @return * @throws UnsupportedEncodingException */ public JobResult unpauseJob(String jobname){ HttpPost postRequest = new HttpPost(baseUrl + "job/" + jobname); StringEntity postEntity = null; try { postEntity = new StringEntity(UNPAUSE_ACTION); } catch (UnsupportedEncodingException e) { // This should never happen e.printStackTrace(); } postEntity.setContentType("application/x-www-form-urlencoded"); postRequest.addHeader("Accept", "application/xml"); postRequest.setEntity(postEntity); return jobResult(postRequest); } /** * Checkpoint job. * @param jobname * @return * @throws UnsupportedEncodingException */ public JobResult checkpointJob(String jobname) { HttpPost postRequest = new HttpPost(baseUrl + "job/" + jobname); StringEntity postEntity = null; try { postEntity = new StringEntity(CHECKPOINT_ACTION); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } postEntity.setContentType("application/x-www-form-urlencoded"); postRequest.addHeader("Accept", "application/xml"); postRequest.setEntity(postEntity); return jobResult(postRequest); } /** * Terminate running job. * @param jobname * @return * @throws UnsupportedEncodingException */ public JobResult terminateJob(String jobname) { HttpPost postRequest = new HttpPost(baseUrl + "job/" + jobname); StringEntity postEntity = null; try { postEntity = new StringEntity(TERMINATE_ACTION); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } postEntity.setContentType("application/x-www-form-urlencoded"); postRequest.addHeader("Accept", "application/xml"); postRequest.setEntity(postEntity); return jobResult(postRequest); } public JobResult test(String url) throws ClientProtocolException, IOException, JAXBException, XMLStreamException { HttpGet getRequest = new HttpGet(url); getRequest.addHeader("Accept", "application/xml"); return jobResult(getRequest); } /* * [beanshell,js,groovy,AppleScriptEngine] */ public ScriptResult ExecuteShellScriptInJob(String jobname, String engine, String script) { HttpPost postRequest = new HttpPost(baseUrl + "job/" + jobname + "/script"); List<NameValuePair> nvp = new LinkedList<NameValuePair>(); nvp.add(new BasicNameValuePair("engine", engine)); nvp.add(new BasicNameValuePair("script", script)); StringEntity postEntity = null; try { postEntity = new UrlEncodedFormEntity(nvp); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } postEntity.setContentType("application/x-www-form-urlencoded"); postRequest.addHeader("Accept", "application/xml"); postRequest.setEntity(postEntity); return scriptResult(postRequest); } public ScriptResult scriptResult(HttpRequestBase request) { ScriptResult scriptResult = new ScriptResult(); try { HttpResponse response = httpClient.execute(request); if (response != null) { scriptResult.responseCode = response.getStatusLine().getStatusCode(); HttpEntity responseEntity = response.getEntity(); long contentLength = responseEntity.getContentLength(); if (contentLength < 0) { contentLength = 0; } ByteArrayOutputStream bOut = new ByteArrayOutputStream((int) contentLength); InputStream in = responseEntity.getContent(); int read; byte[] tmpBuf = new byte[8192]; while ((read = in.read(tmpBuf)) != -1) { bOut.write(tmpBuf, 0, read); } in.close(); bOut.close(); scriptResult.response = bOut.toByteArray(); switch (scriptResult.responseCode) { case 200: scriptResult.parse(xmlValidator); in = new ByteArrayInputStream(scriptResult.response); scriptResult.script = Script.unmarshall(in); in.close(); scriptResult.status = ResultStatus.OK; break; case 404: scriptResult.status = ResultStatus.NOT_FOUND; break; case 500: scriptResult.status = ResultStatus.INTERNAL_ERROR; break; default: scriptResult.status = ResultStatus.NO_RESPONSE; break; } } else { scriptResult.status = ResultStatus.NO_RESPONSE; } } catch (NoHttpResponseException e) { scriptResult.status = ResultStatus.OFFLINE; scriptResult.t = e; } catch (ClientProtocolException e) { scriptResult.status = ResultStatus.RESPONSE_EXCEPTION; scriptResult.t = e; } catch (IOException e) { scriptResult.status = ResultStatus.RESPONSE_EXCEPTION; scriptResult.t = e; } catch (JAXBException e) { scriptResult.status = ResultStatus.XML_EXCEPTION; scriptResult.t = e; } catch (XMLStreamException e) { scriptResult.status = ResultStatus.JAXB_EXCEPTION; scriptResult.t = e; } return scriptResult; } public static void copyFile(File srcFile, File dstDir) throws IOException { RandomAccessFile srcRaf = new RandomAccessFile(srcFile, "r"); FileChannel srcChannel = srcRaf.getChannel(); File dstFile = new File(dstDir, srcFile.getName()); RandomAccessFile dstRaf = new RandomAccessFile(dstFile, "rw"); dstRaf.seek(0); dstRaf.setLength(0); FileChannel dstChannel = dstRaf.getChannel(); long position = 0; long count = srcRaf.length(); long transferred; while (count > 0) { transferred = srcChannel.transferTo(position, count, dstChannel); position += transferred; count -= transferred; } dstRaf.close(); srcRaf.close(); dstFile.setLastModified(srcFile.lastModified()); } public static void copyFileAs(File srcFile, File dstDir, String dstFName) throws IOException { RandomAccessFile srcRaf = new RandomAccessFile(srcFile, "r"); FileChannel srcChannel = srcRaf.getChannel(); File dstFile = new File(dstDir, dstFName); RandomAccessFile dstRaf = new RandomAccessFile(dstFile, "rw"); dstRaf.seek(0); dstRaf.setLength(0); FileChannel dstChannel = dstRaf.getChannel(); long position = 0; long count = srcRaf.length(); long transferred; while (count > 0) { transferred = srcChannel.transferTo(position, count, dstChannel); position += transferred; count -= transferred; } dstRaf.close(); srcRaf.close(); dstFile.setLastModified(srcFile.lastModified()); } }
src/main/java/org/netarchivesuite/heritrix3wrapper/Heritrix3Wrapper.java
package org.netarchivesuite.heritrix3wrapper; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.RandomAccessFile; import java.io.UnsupportedEncodingException; import java.nio.channels.FileChannel; import java.security.KeyManagementException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.UnrecoverableKeyException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.LinkedList; import java.util.List; import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import javax.xml.bind.JAXBException; import javax.xml.stream.XMLStreamException; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.NoHttpResponseException; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.conn.ssl.X509HostnameVerifier; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.message.BasicNameValuePair; import org.netarchivesuite.heritrix3wrapper.jaxb.Engine; import org.netarchivesuite.heritrix3wrapper.jaxb.Job; import org.netarchivesuite.heritrix3wrapper.jaxb.Script; import org.netarchivesuite.heritrix3wrapper.xmlutils.XmlValidator; public class Heritrix3Wrapper { protected HttpClient httpClient; protected String baseUrl; protected XmlValidator xmlValidator = new XmlValidator(); private static final String GC_ACTION= "action=gc"; private static final String RESCAN_ACTION = "action=rescan"; private static final String BUILD_ACTION = "action=build"; private static final String LAUNCH_ACTION = "action=launch"; private static final String TEARDOWN_ACTION = "action=teardown"; private static final String PAUSE_ACTION = "action=pause"; private static final String UNPAUSE_ACTION = "action=unpause"; private static final String TERMINATE_ACTION = "action=terminate"; private static final String CHECKPOINT_ACTION = "action=checkpoint"; public static enum CrawlControllerState { NASCENT, RUNNING, EMPTY, PAUSED, PAUSING, STOPPING, FINISHED, PREPARING } protected Heritrix3Wrapper() { } public static Heritrix3Wrapper getInstance(String hostname, int port, File keystoreFile, String keyStorePassword, String userName, String password) { Heritrix3Wrapper h3 = new Heritrix3Wrapper(); InputStream instream = null; KeyManager[] keyManagers = null; try { if (keystoreFile != null) { KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); instream = new FileInputStream(keystoreFile); ks.load(instream, keyStorePassword.toCharArray()); KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); kmf.init(ks, keyStorePassword.toCharArray()); keyManagers = kmf.getKeyManagers(); } X509TrustManager tm = new X509TrustManager() { public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException { } public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException { } public X509Certificate[] getAcceptedIssuers() { return null; } }; SSLContext ctx = SSLContext.getInstance("TLS"); ctx.init(keyManagers, new TrustManager[] {tm}, null); X509HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER; SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(ctx); //socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier); //Scheme sch = new Scheme("https", socketFactory, port); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(hostname, port), new UsernamePasswordCredentials(userName, password)); HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); httpClientBuilder.setSSLSocketFactory(sslSocketFactory).setHostnameVerifier(hostnameVerifier); h3.httpClient = httpClientBuilder.setDefaultCredentialsProvider(credsProvider).build(); //h3.httpClient.getConnectionManager().getSchemeRegistry().register(sch); h3.baseUrl = "https://" + hostname + ":" + Integer.toString(port) + "/engine/"; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (CertificateException e) { e.printStackTrace(); } catch (UnrecoverableKeyException e) { e.printStackTrace(); } finally { if (instream != null) { try { instream.close(); } catch (IOException e) { } } } return h3; } /** * Send JVM shutdown to Heritrix 3. Also requres marked 'checkbox' for each active job. * @return * @throws UnsupportedEncodingException */ public EngineResult exitJavaProcess(List<String> ignoreJobs){ HttpPost postRequest = new HttpPost(baseUrl); List<NameValuePair> nvp = new LinkedList<NameValuePair>(); nvp.add(new BasicNameValuePair("action", "Exit Java Process")); nvp.add(new BasicNameValuePair("im_sure", "on")); // ignore__${jobname}=on if (ignoreJobs != null && ignoreJobs.size() > 0) { for (int i=0; i<ignoreJobs.size(); ++i) { nvp.add(new BasicNameValuePair("ignore__" + ignoreJobs.get(i), "on")); } } StringEntity postEntity = null; try { postEntity = new UrlEncodedFormEntity(nvp); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } postEntity.setContentType("application/x-www-form-urlencoded"); postRequest.addHeader("Accept", "application/xml"); postRequest.setEntity(postEntity); return engineResult(postRequest); } public EngineResult postEngineRequest(String url, String action) { HttpPost postRequest = new HttpPost(url); StringEntity postEntity = null; try { postEntity = new StringEntity(action); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } postEntity.setContentType("application/x-www-form-urlencoded"); postRequest.addHeader("Accept", "application/xml"); postRequest.setEntity(postEntity); return engineResult(postRequest); } /** * Returns engine state and a list of registered jobs. * @return engine state and a list of registered jobs * @throws UnsupportedEncodingException */ public EngineResult rescanJobDirectory() { return postEngineRequest(baseUrl, RESCAN_ACTION); } /** * Invoke GarbageCollector in JVM running Heritrix 3. * @return * @throws UnsupportedEncodingException */ public EngineResult gc() { return postEngineRequest(baseUrl, GC_ACTION); } /** * * @param tries * @param interval * @return * @throws UnsupportedEncodingException */ public EngineResult waitForEngineReady(int tries, int interval) { EngineResult engineResult = null; if (tries <= 0) { tries = 1; } if (interval <= 99) { interval = 1000; } boolean bLoop = true; while (bLoop && tries > 0) { engineResult = rescanJobDirectory(); // debug System.out.println(engineResult.status + " - " + ResultStatus.OK); if (engineResult.status == ResultStatus.OK) { bLoop = false; } --tries; if (bLoop && tries > 0) { try { Thread.sleep(interval); } catch (InterruptedException e) { } } } return engineResult; } /** * Creates a new job with the default cxml file which must be modified before launch. * @param jobname * @return * @throws UnsupportedEncodingException */ public EngineResult createNewJob(String jobname) { HttpPost postRequest = new HttpPost(baseUrl); List<NameValuePair> nvp = new LinkedList<NameValuePair>(); nvp.add(new BasicNameValuePair("action", "create")); nvp.add(new BasicNameValuePair("createpath", jobname)); StringEntity postEntity = null; try { postEntity = new UrlEncodedFormEntity(nvp); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } postEntity.setContentType("application/x-www-form-urlencoded"); postRequest.addHeader("Accept", "application/xml"); postRequest.setEntity(postEntity); return engineResult(postRequest); } /** * * @param path * @return * @throws UnsupportedEncodingException */ public EngineResult addJobDirectory(String path) { HttpPost postRequest = new HttpPost(baseUrl); List<NameValuePair> nvp = new LinkedList<NameValuePair>(); nvp.add(new BasicNameValuePair("action", "add")); nvp.add(new BasicNameValuePair("addpath", path)); StringEntity postEntity= null; try { postEntity = new UrlEncodedFormEntity(nvp); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } postEntity.setContentType("application/x-www-form-urlencoded"); postRequest.addHeader("Accept", "application/xml"); postRequest.setEntity(postEntity); return engineResult(postRequest); } public EngineResult engineResult(HttpRequestBase request) { EngineResult engineResult = new EngineResult(); try { HttpResponse response = httpClient.execute(request); if (response != null) { engineResult.responseCode = response.getStatusLine().getStatusCode(); HttpEntity responseEntity = response.getEntity(); long contentLength = responseEntity.getContentLength(); if (contentLength < 0) { contentLength = 0; } ByteArrayOutputStream bOut = new ByteArrayOutputStream((int) contentLength); InputStream in = responseEntity.getContent(); int read; byte[] tmpBuf = new byte[8192]; while ((read = in.read(tmpBuf)) != -1) { bOut.write(tmpBuf, 0, read); } in.close(); bOut.close(); engineResult.response = bOut.toByteArray(); switch (engineResult.responseCode) { case 200: engineResult.parse(xmlValidator); in = new ByteArrayInputStream(engineResult.response); engineResult.engine = Engine.unmarshall(in); in.close(); engineResult.status = ResultStatus.OK; break; case 404: engineResult.status = ResultStatus.NOT_FOUND; break; case 500: engineResult.status = ResultStatus.INTERNAL_ERROR; break; default: engineResult.status = ResultStatus.NO_RESPONSE; break; } } else { engineResult.status = ResultStatus.NO_RESPONSE; } } catch (NoHttpResponseException e) { engineResult.status = ResultStatus.OFFLINE; engineResult.t = e; } catch (ClientProtocolException e) { engineResult.status = ResultStatus.RESPONSE_EXCEPTION; engineResult.t = e; } catch (IOException e) { engineResult.status = ResultStatus.RESPONSE_EXCEPTION; engineResult.t = e; } catch (JAXBException e) { engineResult.status = ResultStatus.XML_EXCEPTION; engineResult.t = e; } catch (XMLStreamException e) { engineResult.status = ResultStatus.JAXB_EXCEPTION; engineResult.t = e; } return engineResult; } public JobResult jobResult(HttpRequestBase request) { JobResult jobResult = new JobResult(); try { HttpResponse response = httpClient.execute(request); if (response != null) { jobResult.responseCode = response.getStatusLine().getStatusCode(); HttpEntity responseEntity = response.getEntity(); long contentLength = responseEntity.getContentLength(); if (contentLength < 0) { contentLength = 0; } ByteArrayOutputStream bOut = new ByteArrayOutputStream((int) contentLength); InputStream in = responseEntity.getContent(); int read; byte[] tmpBuf = new byte[8192]; while ((read = in.read(tmpBuf)) != -1) { bOut.write(tmpBuf, 0, read); } in.close(); bOut.close(); jobResult.response = bOut.toByteArray(); switch (jobResult.responseCode) { case 200: jobResult.parse(xmlValidator); in = new ByteArrayInputStream(jobResult.response); jobResult.job = Job.unmarshall(in); in.close(); jobResult.status = ResultStatus.OK; break; case 404: jobResult.status = ResultStatus.NOT_FOUND; break; case 500: jobResult.status = ResultStatus.INTERNAL_ERROR; break; default: jobResult.status = ResultStatus.NO_RESPONSE; break; } } else { jobResult.status = ResultStatus.NO_RESPONSE; } } catch (NoHttpResponseException e) { jobResult.status = ResultStatus.OFFLINE; jobResult.t = e; } catch (ClientProtocolException e) { jobResult.status = ResultStatus.RESPONSE_EXCEPTION; jobResult.t = e; } catch (IOException e) { jobResult.status = ResultStatus.RESPONSE_EXCEPTION; jobResult.t = e; } catch (JAXBException e) { jobResult.status = ResultStatus.XML_EXCEPTION; jobResult.t = e; } catch (XMLStreamException e) { jobResult.status = ResultStatus.JAXB_EXCEPTION; jobResult.t = e; } return jobResult; } /** * Returns job object given a jobname. * @param jobname * @return */ public JobResult job(String jobname) { HttpGet getRequest = new HttpGet(baseUrl + "job/" + jobname); getRequest.addHeader("Accept", "application/xml"); return jobResult(getRequest); } public JobResult waitForJobState(String jobname, CrawlControllerState state, int tries, int interval) throws UnsupportedEncodingException { JobResult jobResult = null; if (tries <= 0) { tries = 1; } if (interval <= 99) { interval = 1000; } boolean bLoop = true; while (bLoop && tries > 0) { jobResult = job(jobname); // debug System.out.println(jobResult.status + " - " + ResultStatus.OK); if (jobResult.status == ResultStatus.OK) { // debug System.out.println(jobResult.job.crawlControllerState + " - " + state.name()); if (state.name().equals(jobResult.job.crawlControllerState)) { bLoop = false; } } --tries; if (bLoop && tries > 0) { try { Thread.sleep(interval); } catch (InterruptedException e) { } } } return jobResult; } /** * * @param srcJobname * @param dstJobName * @param bAsProfile * @return * @throws UnsupportedEncodingException */ public JobResult copyJob(String srcJobname, String dstJobName, boolean bAsProfile) { HttpPost postRequest = new HttpPost(baseUrl + "job/" + srcJobname); List<NameValuePair> nvp = new LinkedList<NameValuePair>(); nvp.add(new BasicNameValuePair("copyTo", dstJobName)); if (bAsProfile) { nvp.add(new BasicNameValuePair("asProfile", "on")); } StringEntity postEntity = null; try { postEntity = new UrlEncodedFormEntity(nvp); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } postEntity.setContentType("application/x-www-form-urlencoded"); postRequest.addHeader("Accept", "application/xml"); postRequest.setEntity(postEntity); return jobResult(postRequest); } /** * Build an existing job. * @param jobname * @return * @throws UnsupportedEncodingException */ public JobResult buildJobConfiguration(String jobname){ HttpPost postRequest = new HttpPost(baseUrl + "job/" + jobname); StringEntity postEntity = null; try { postEntity = new StringEntity(BUILD_ACTION); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } postEntity.setContentType("application/x-www-form-urlencoded"); postRequest.addHeader("Accept", "application/xml"); postRequest.setEntity(postEntity); return jobResult(postRequest); } /** * Teardown job and return it's state to unbuild. Note the job object will not include all the information present before calling this method. * @param jobname * @return */ public JobResult teardownJob(String jobname) { HttpPost postRequest = new HttpPost(baseUrl + "job/" + jobname); StringEntity postEntity = null; try { postEntity = new StringEntity(TEARDOWN_ACTION); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } postEntity.setContentType("application/x-www-form-urlencoded"); postRequest.addHeader("Accept", "application/xml"); postRequest.setEntity(postEntity); return jobResult(postRequest); } /** * Launch a built job in pause state. * @param jobname * @return * @throws UnsupportedEncodingException */ public JobResult launchJob(String jobname) { HttpPost postRequest = new HttpPost(baseUrl + "job/" + jobname); StringEntity postEntity = null; try { postEntity = new StringEntity(LAUNCH_ACTION); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } postEntity.setContentType("application/x-www-form-urlencoded"); postRequest.addHeader("Accept", "application/xml"); postRequest.setEntity(postEntity); return jobResult(postRequest); } /** * Pause running job. * @param jobname * @return */ public JobResult pauseJob(String jobname) { HttpPost postRequest = new HttpPost(baseUrl + "job/" + jobname); StringEntity postEntity = null; try { postEntity = new StringEntity(PAUSE_ACTION); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } postEntity.setContentType("application/x-www-form-urlencoded"); postRequest.addHeader("Accept", "application/xml"); postRequest.setEntity(postEntity); return jobResult(postRequest); } /** * Un-pause job. * @param jobname * @return * @throws UnsupportedEncodingException */ public JobResult unpauseJob(String jobname){ HttpPost postRequest = new HttpPost(baseUrl + "job/" + jobname); StringEntity postEntity = null; try { postEntity = new StringEntity(UNPAUSE_ACTION); } catch (UnsupportedEncodingException e) { // This should never happen e.printStackTrace(); } postEntity.setContentType("application/x-www-form-urlencoded"); postRequest.addHeader("Accept", "application/xml"); postRequest.setEntity(postEntity); return jobResult(postRequest); } /** * Checkpoint job. * @param jobname * @return * @throws UnsupportedEncodingException */ public JobResult checkpointJob(String jobname) { HttpPost postRequest = new HttpPost(baseUrl + "job/" + jobname); StringEntity postEntity = null; try { postEntity = new StringEntity(CHECKPOINT_ACTION); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } postEntity.setContentType("application/x-www-form-urlencoded"); postRequest.addHeader("Accept", "application/xml"); postRequest.setEntity(postEntity); return jobResult(postRequest); } /** * Terminate running job. * @param jobname * @return * @throws UnsupportedEncodingException */ public JobResult terminateJob(String jobname) { HttpPost postRequest = new HttpPost(baseUrl + "job/" + jobname); StringEntity postEntity = null; try { postEntity = new StringEntity(TERMINATE_ACTION); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } postEntity.setContentType("application/x-www-form-urlencoded"); postRequest.addHeader("Accept", "application/xml"); postRequest.setEntity(postEntity); return jobResult(postRequest); } public JobResult test(String url) throws ClientProtocolException, IOException, JAXBException, XMLStreamException { HttpGet getRequest = new HttpGet(url); getRequest.addHeader("Accept", "application/xml"); return jobResult(getRequest); } /* * [beanshell,js,groovy,AppleScriptEngine] */ public ScriptResult ExecuteShellScriptInJob(String jobname, String engine, String script) { HttpPost postRequest = new HttpPost(baseUrl + "job/" + jobname + "/script"); List<NameValuePair> nvp = new LinkedList<NameValuePair>(); nvp.add(new BasicNameValuePair("engine", engine)); nvp.add(new BasicNameValuePair("script", script)); StringEntity postEntity = null; try { postEntity = new UrlEncodedFormEntity(nvp); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } postEntity.setContentType("application/x-www-form-urlencoded"); postRequest.addHeader("Accept", "application/xml"); postRequest.setEntity(postEntity); return scriptResult(postRequest); } public ScriptResult scriptResult(HttpRequestBase request) { ScriptResult scriptResult = new ScriptResult(); try { HttpResponse response = httpClient.execute(request); if (response != null) { scriptResult.responseCode = response.getStatusLine().getStatusCode(); HttpEntity responseEntity = response.getEntity(); long contentLength = responseEntity.getContentLength(); if (contentLength < 0) { contentLength = 0; } ByteArrayOutputStream bOut = new ByteArrayOutputStream((int) contentLength); InputStream in = responseEntity.getContent(); int read; byte[] tmpBuf = new byte[8192]; while ((read = in.read(tmpBuf)) != -1) { bOut.write(tmpBuf, 0, read); } in.close(); bOut.close(); scriptResult.response = bOut.toByteArray(); switch (scriptResult.responseCode) { case 200: scriptResult.parse(xmlValidator); in = new ByteArrayInputStream(scriptResult.response); scriptResult.script = Script.unmarshall(in); in.close(); scriptResult.status = ResultStatus.OK; break; case 404: scriptResult.status = ResultStatus.NOT_FOUND; break; case 500: scriptResult.status = ResultStatus.INTERNAL_ERROR; break; default: scriptResult.status = ResultStatus.NO_RESPONSE; break; } } else { scriptResult.status = ResultStatus.NO_RESPONSE; } } catch (NoHttpResponseException e) { scriptResult.status = ResultStatus.OFFLINE; scriptResult.t = e; } catch (ClientProtocolException e) { scriptResult.status = ResultStatus.RESPONSE_EXCEPTION; scriptResult.t = e; } catch (IOException e) { scriptResult.status = ResultStatus.RESPONSE_EXCEPTION; scriptResult.t = e; } catch (JAXBException e) { scriptResult.status = ResultStatus.XML_EXCEPTION; scriptResult.t = e; } catch (XMLStreamException e) { scriptResult.status = ResultStatus.JAXB_EXCEPTION; scriptResult.t = e; } return scriptResult; } public static void copyFile(File srcFile, File dstDir) throws IOException { RandomAccessFile srcRaf = new RandomAccessFile(srcFile, "r"); FileChannel srcChannel = srcRaf.getChannel(); File dstFile = new File(dstDir, srcFile.getName()); RandomAccessFile dstRaf = new RandomAccessFile(dstFile, "rw"); dstRaf.seek(0); dstRaf.setLength(0); FileChannel dstChannel = dstRaf.getChannel(); long position = 0; long count = srcRaf.length(); long transferred; while (count > 0) { transferred = srcChannel.transferTo(position, count, dstChannel); position += transferred; count -= transferred; } dstRaf.close(); srcRaf.close(); dstFile.setLastModified(srcFile.lastModified()); } public static void copyFileAs(File srcFile, File dstDir, String dstFName) throws IOException { RandomAccessFile srcRaf = new RandomAccessFile(srcFile, "r"); FileChannel srcChannel = srcRaf.getChannel(); File dstFile = new File(dstDir, dstFName); RandomAccessFile dstRaf = new RandomAccessFile(dstFile, "rw"); dstRaf.seek(0); dstRaf.setLength(0); FileChannel dstChannel = dstRaf.getChannel(); long position = 0; long count = srcRaf.length(); long transferred; while (count > 0) { transferred = srcChannel.transferTo(position, count, dstChannel); position += transferred; count -= transferred; } dstRaf.close(); srcRaf.close(); dstFile.setLastModified(srcFile.lastModified()); } }
Seems I finally figured out how to get the latest httpclient to work with hostnameverfiers and trustmanagers.
src/main/java/org/netarchivesuite/heritrix3wrapper/Heritrix3Wrapper.java
Seems I finally figured out how to get the latest httpclient to work with hostnameverfiers and trustmanagers.
Java
apache-2.0
24fb3d3d5c81c6b1271745fdfe14175e0eac054e
0
mulesoft/mule-module-cors
/* * Copyright 2014 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mule.modules.cors; import org.mule.DefaultMuleEvent; import org.mule.NonBlockingVoidMuleEvent; import org.mule.OptimizedRequestContext; import org.mule.VoidMuleEvent; import org.mule.api.MessagingException; import org.mule.api.MuleEvent; import org.mule.api.MuleException; import org.mule.api.MuleMessage; import org.mule.api.config.MuleProperties; import org.mule.api.store.ObjectStoreException; import org.mule.api.transport.PropertyScope; import org.mule.api.transport.ReplyToHandler; import org.mule.processor.AbstractRequestResponseMessageProcessor; import org.apache.commons.lang.StringUtils; public class ValidateMessageProcessor extends AbstractRequestResponseMessageProcessor { private static final String STOP_PROCESSING_FLAG = MuleProperties.PROPERTY_PREFIX + "__stopProcessing"; private boolean publicResource; private boolean acceptsCredentials; private CorsConfig config; @Override protected MuleEvent processRequest(MuleEvent event) throws MuleException { if (publicResource && acceptsCredentials) { throw new IllegalArgumentException("Resource may not be public and accept credentials at the same time"); } //read the origin String origin = event.getMessage().getInboundProperty(Constants.ORIGIN); //if origin is not present, then not a CORS request if (StringUtils.isEmpty(origin)) { if (logger.isDebugEnabled()) { logger.debug("Request is not a CORS request."); } return event; } //read headers including those of the preflight String method = event.getMessage().getInboundProperty(Constants.HTTP_METHOD); //decide if we want to invoke the flow. if (shouldInvokeFlow(origin, method, publicResource)) { return event; } //setting the response to null. event.getMessage().setPayload(null); //Set flag to stop further processing. I need this workaround because there are some headers //that might be set on the response and returning null or VoidMuleEvent won't allow it. event.getMessage().setInvocationProperty(STOP_PROCESSING_FLAG, true); return event; } @Override protected MuleEvent processNext(MuleEvent event) throws MuleException { if(event != null && !VoidMuleEvent.getInstance().equals(event) && Boolean.TRUE.equals(event.getMessage().getInvocationProperty(STOP_PROCESSING_FLAG))) { event.getMessage().removeProperty(STOP_PROCESSING_FLAG, PropertyScope.INVOCATION); return event; } return super.processNext(event); } protected MuleEvent processResponse(final String origin, final String method, final String requestMethod, final String requestHeaders, MuleEvent event) throws MuleException { MuleMessage message = event.getMessage(); if(StringUtils.isEmpty(origin)) { return event; } boolean isPreflight = StringUtils.equals(Constants.PREFLIGHT_METHOD, method); //if the resource is public then we don't check if (publicResource) { message.setOutboundProperty(Constants.ACCESS_CONTROL_ALLOW_ORIGIN, "*"); //and if it is a preflight call if (isPreflight) { message.setOutboundProperty(Constants.ACCESS_CONTROL_ALLOW_METHODS, requestMethod); message.setOutboundProperty(Constants.ACCESS_CONTROL_ALLOW_HEADERS, requestHeaders); } //no further processing return event; } Origin configuredOrigin = findOrigin(origin); //no matching origin has been found. if (configuredOrigin == null) { return event; } String checkMethod = isPreflight ? requestMethod : method; //if the method is not present, then we don't allow. if (configuredOrigin.getMethods() == null || !configuredOrigin.getMethods().contains(checkMethod)) { return event; } //add the allow origin message.setOutboundProperty(Constants.ACCESS_CONTROL_ALLOW_ORIGIN, origin); //if the resource accepts credentials if (acceptsCredentials) { message.setOutboundProperty(Constants.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"); } //if this is not a preflight, then we don't want to add the other headers if (!isPreflight) { return event; } //serialize the list of allowed methods if (configuredOrigin.getMethods() != null) { message.setOutboundProperty(Constants.ACCESS_CONTROL_ALLOW_METHODS, StringUtils.join(configuredOrigin.getMethods(), ", ")); } //serialize the list of allowed headers if (configuredOrigin.getHeaders() != null) { message.setOutboundProperty(Constants.ACCESS_CONTROL_ALLOW_HEADERS, StringUtils.join(configuredOrigin.getHeaders(), ", ")); } //serialize the list of allowed headers if (configuredOrigin.getExposeHeaders() != null) { message.setOutboundProperty(Constants.ACCESS_CONTROL_EXPOSE_HEADERS, StringUtils.join(configuredOrigin.getExposeHeaders(), ", ")); } //set the configured max age for this origin if (configuredOrigin.getAccessControlMaxAge() != null) { message.setOutboundProperty(Constants.ACCESS_CONTROL_MAX_AGE, configuredOrigin.getAccessControlMaxAge()); } return event; } @Override protected MuleEvent processBlocking(MuleEvent event) throws MuleException { MessagingException exception = null; final String origin = event.getMessage().getInboundProperty(Constants.ORIGIN); final String method = event.getMessage().getInboundProperty(Constants.HTTP_METHOD); final String requestMethod = event.getMessage().getInboundProperty(Constants.REQUEST_METHOD); final String requestHeaders = event.getMessage().getInboundProperty(Constants.REQUEST_HEADERS); try { return processResponse(origin, method, requestMethod, requestHeaders, processNext(processRequest(event))); } catch (MessagingException e) { exception = e; throw e; } finally { processFinally(event, exception); } } protected MuleEvent processNonBlocking(MuleEvent event) throws MuleException { final String origin = event.getMessage().getInboundProperty(Constants.ORIGIN); final String method = event.getMessage().getInboundProperty(Constants.HTTP_METHOD); final String requestMethod = event.getMessage().getInboundProperty(Constants.REQUEST_METHOD); final String requestHeaders = event.getMessage().getInboundProperty(Constants.REQUEST_HEADERS); final ReplyToHandler corsReplyToHandler = new CorsReplyToHandler(event.getReplyToHandler(), origin, method, requestMethod, requestHeaders); event = new DefaultMuleEvent(event, corsReplyToHandler); // Update RequestContext ThreadLocal for backwards compatibility OptimizedRequestContext.unsafeSetEvent(event); try { MuleEvent result = processNext(processRequest(event)); if (!(result instanceof NonBlockingVoidMuleEvent)) { return processResponse(origin, method, requestMethod, requestHeaders, result); } else { return result; } } catch (MessagingException exception) { processFinally(event, exception); throw exception; } } class CorsReplyToHandler implements ReplyToHandler { private final String origin; private final String method; private final String requestMethod; private final String requestHeaders; private final ReplyToHandler originalReplyToHandler; public CorsReplyToHandler(final ReplyToHandler originalReplyToHandler, final String origin, final String method, final String requestMethod, final String requestHeaders) { this.originalReplyToHandler = originalReplyToHandler; this.origin = origin; this.method = method; this.requestMethod = requestMethod; this.requestHeaders = requestHeaders; } @Override public void processReplyTo(MuleEvent event, MuleMessage muleMessage, Object replyTo) throws MuleException { MuleEvent response = processResponse(origin, method, requestMethod, requestHeaders, new DefaultMuleEvent(event, originalReplyToHandler)); // Update RequestContext ThreadLocal for backwards compatibility OptimizedRequestContext.unsafeSetEvent(response); if (!NonBlockingVoidMuleEvent.getInstance().equals(response)) { originalReplyToHandler.processReplyTo(response, null, null); } processFinally(event, null); } @Override public void processExceptionReplyTo(MessagingException exception, Object replyTo) { originalReplyToHandler.processExceptionReplyTo(exception, replyTo); processFinally(exception.getEvent(), exception); } } private boolean shouldInvokeFlow(String origin, String method, boolean publicResource) throws ObjectStoreException { //if it is the preflight request, then logic wont be invoked. if (StringUtils.equals(Constants.PREFLIGHT_METHOD, method)) { if (logger.isDebugEnabled()) logger.debug("OPTIONS header, will not continue processing."); return false; } //if it is a public resource and not preflight, then let's do it :) if (publicResource) { return true; } Origin configuredOrigin = findOrigin(origin); if (configuredOrigin == null) { if (logger.isDebugEnabled()) { logger.debug("Could not find configuration for origin: " + origin); } return false; } //verify the allowed methods. if (configuredOrigin.getMethods() != null) { return configuredOrigin.getMethods().contains(method); } else { logger.warn("Configured origin has no methods. Not allowing the execution of the flow"); return false; } } private Origin findOrigin(String origin) throws ObjectStoreException{ //if origin is not present then don't add headers if (!config.getOriginsStore().contains(origin)) { if (!config.getOriginsStore().contains(Constants.DEFAULT_ORIGIN_NAME)) { return null; } else { return config.getOriginsStore().retrieve(Constants.DEFAULT_ORIGIN_NAME); } } return config.getOriginsStore().retrieve(origin); } public void setPublicResource(boolean publicResource) { this.publicResource = publicResource; } public void setAcceptsCredentials(boolean acceptsCredentials) { this.acceptsCredentials = acceptsCredentials; } public void setConfig(CorsConfig config) { this.config = config; } }
src/main/java/org/mule/modules/cors/ValidateMessageProcessor.java
/* * Copyright 2014 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mule.modules.cors; import org.mule.DefaultMuleEvent; import org.mule.NonBlockingVoidMuleEvent; import org.mule.OptimizedRequestContext; import org.mule.api.MessagingException; import org.mule.api.MuleEvent; import org.mule.api.MuleException; import org.mule.api.MuleMessage; import org.mule.api.store.ObjectStoreException; import org.mule.api.transport.ReplyToHandler; import org.mule.processor.AbstractRequestResponseMessageProcessor; import org.apache.commons.lang.StringUtils; public class ValidateMessageProcessor extends AbstractRequestResponseMessageProcessor { private boolean publicResource; private boolean acceptsCredentials; private CorsConfig config; @Override protected MuleEvent processRequest(MuleEvent event) throws MuleException { if (publicResource && acceptsCredentials) { throw new IllegalArgumentException("Resource may not be public and accept credentials at the same time"); } //read the origin String origin = event.getMessage().getInboundProperty(Constants.ORIGIN); //if origin is not present, then not a CORS request if (StringUtils.isEmpty(origin)) { if (logger.isDebugEnabled()) { logger.debug("Request is not a CORS request."); } return event; } //read headers including those of the preflight String method = event.getMessage().getInboundProperty(Constants.HTTP_METHOD); //decide if we want to invoke the flow. if (shouldInvokeFlow(origin, method, publicResource)) { return event; } //setting the response to null. event.getMessage().setPayload(null); //Set next message processor to null to stop further processing setListener(null); return event; } protected MuleEvent processResponse(final String origin, final String method, final String requestMethod, final String requestHeaders, MuleEvent event) throws MuleException { MuleMessage message = event.getMessage(); if(StringUtils.isEmpty(origin)) { return event; } boolean isPreflight = StringUtils.equals(Constants.PREFLIGHT_METHOD, method); //if the resource is public then we don't check if (publicResource) { message.setOutboundProperty(Constants.ACCESS_CONTROL_ALLOW_ORIGIN, "*"); //and if it is a preflight call if (isPreflight) { message.setOutboundProperty(Constants.ACCESS_CONTROL_ALLOW_METHODS, requestMethod); message.setOutboundProperty(Constants.ACCESS_CONTROL_ALLOW_HEADERS, requestHeaders); } //no further processing return event; } Origin configuredOrigin = findOrigin(origin); //no matching origin has been found. if (configuredOrigin == null) { return event; } String checkMethod = isPreflight ? requestMethod : method; //if the method is not present, then we don't allow. if (configuredOrigin.getMethods() == null || !configuredOrigin.getMethods().contains(checkMethod)) { return event; } //add the allow origin message.setOutboundProperty(Constants.ACCESS_CONTROL_ALLOW_ORIGIN, origin); //if the resource accepts credentials if (acceptsCredentials) { message.setOutboundProperty(Constants.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"); } //if this is not a preflight, then we don't want to add the other headers if (!isPreflight) { return event; } //serialize the list of allowed methods if (configuredOrigin.getMethods() != null) { message.setOutboundProperty(Constants.ACCESS_CONTROL_ALLOW_METHODS, StringUtils.join(configuredOrigin.getMethods(), ", ")); } //serialize the list of allowed headers if (configuredOrigin.getHeaders() != null) { message.setOutboundProperty(Constants.ACCESS_CONTROL_ALLOW_HEADERS, StringUtils.join(configuredOrigin.getHeaders(), ", ")); } //serialize the list of allowed headers if (configuredOrigin.getExposeHeaders() != null) { message.setOutboundProperty(Constants.ACCESS_CONTROL_EXPOSE_HEADERS, StringUtils.join(configuredOrigin.getExposeHeaders(), ", ")); } //set the configured max age for this origin if (configuredOrigin.getAccessControlMaxAge() != null) { message.setOutboundProperty(Constants.ACCESS_CONTROL_MAX_AGE, configuredOrigin.getAccessControlMaxAge()); } return event; } @Override protected MuleEvent processBlocking(MuleEvent event) throws MuleException { MessagingException exception = null; final String origin = event.getMessage().getInboundProperty(Constants.ORIGIN); final String method = event.getMessage().getInboundProperty(Constants.HTTP_METHOD); final String requestMethod = event.getMessage().getInboundProperty(Constants.REQUEST_METHOD); final String requestHeaders = event.getMessage().getInboundProperty(Constants.REQUEST_HEADERS); try { return processResponse(origin, method, requestMethod, requestHeaders, processNext(processRequest(event))); } catch (MessagingException e) { exception = e; throw e; } finally { processFinally(event, exception); } } protected MuleEvent processNonBlocking(MuleEvent event) throws MuleException { final String origin = event.getMessage().getInboundProperty(Constants.ORIGIN); final String method = event.getMessage().getInboundProperty(Constants.HTTP_METHOD); final String requestMethod = event.getMessage().getInboundProperty(Constants.REQUEST_METHOD); final String requestHeaders = event.getMessage().getInboundProperty(Constants.REQUEST_HEADERS); final ReplyToHandler corsReplyToHandler = new CorsReplyToHandler(event.getReplyToHandler(), origin, method, requestMethod, requestHeaders); event = new DefaultMuleEvent(event, corsReplyToHandler); // Update RequestContext ThreadLocal for backwards compatibility OptimizedRequestContext.unsafeSetEvent(event); try { MuleEvent result = processNext(processRequest(event)); if (!(result instanceof NonBlockingVoidMuleEvent)) { return processResponse(origin, method, requestMethod, requestHeaders, result); } else { return result; } } catch (MessagingException exception) { processFinally(event, exception); throw exception; } } class CorsReplyToHandler implements ReplyToHandler { private final String origin; private final String method; private final String requestMethod; private final String requestHeaders; private final ReplyToHandler originalReplyToHandler; public CorsReplyToHandler(final ReplyToHandler originalReplyToHandler, final String origin, final String method, final String requestMethod, final String requestHeaders) { this.originalReplyToHandler = originalReplyToHandler; this.origin = origin; this.method = method; this.requestMethod = requestMethod; this.requestHeaders = requestHeaders; } @Override public void processReplyTo(MuleEvent event, MuleMessage muleMessage, Object replyTo) throws MuleException { MuleEvent response = processResponse(origin, method, requestMethod, requestHeaders, new DefaultMuleEvent(event, originalReplyToHandler)); // Update RequestContext ThreadLocal for backwards compatibility OptimizedRequestContext.unsafeSetEvent(response); if (!NonBlockingVoidMuleEvent.getInstance().equals(response)) { originalReplyToHandler.processReplyTo(response, null, null); } processFinally(event, null); } @Override public void processExceptionReplyTo(MessagingException exception, Object replyTo) { originalReplyToHandler.processExceptionReplyTo(exception, replyTo); processFinally(exception.getEvent(), exception); } } private boolean shouldInvokeFlow(String origin, String method, boolean publicResource) throws ObjectStoreException { //if it is the preflight request, then logic wont be invoked. if (StringUtils.equals(Constants.PREFLIGHT_METHOD, method)) { if (logger.isDebugEnabled()) logger.debug("OPTIONS header, will not continue processing."); return false; } //if it is a public resource and not preflight, then let's do it :) if (publicResource) { return true; } Origin configuredOrigin = findOrigin(origin); if (configuredOrigin == null) { if (logger.isDebugEnabled()) { logger.debug("Could not find configuration for origin: " + origin); } return false; } //verify the allowed methods. if (configuredOrigin.getMethods() != null) { return configuredOrigin.getMethods().contains(method); } else { logger.warn("Configured origin has no methods. Not allowing the execution of the flow"); return false; } } private Origin findOrigin(String origin) throws ObjectStoreException{ //if origin is not present then don't add headers if (!config.getOriginsStore().contains(origin)) { if (!config.getOriginsStore().contains(Constants.DEFAULT_ORIGIN_NAME)) { return null; } else { return config.getOriginsStore().retrieve(Constants.DEFAULT_ORIGIN_NAME); } } return config.getOriginsStore().retrieve(origin); } public void setPublicResource(boolean publicResource) { this.publicResource = publicResource; } public void setAcceptsCredentials(boolean acceptsCredentials) { this.acceptsCredentials = acceptsCredentials; } public void setConfig(CorsConfig config) { this.config = config; } }
- Add proper logic to stop further processing of the event but still enable the process response method to add headers to the response.
src/main/java/org/mule/modules/cors/ValidateMessageProcessor.java
- Add proper logic to stop further processing of the event but still enable the process response method to add headers to the response.
Java
apache-2.0
ea519a81cda86a150946a4bfa0666f928aedd643
0
ipeirotis/mturk-tracker-gae,ipeirotis/mturk-tracker-gae,ipeirotis/mturk-tracker-gae
package com.tracker.servlet.task; import static com.tracker.ofy.OfyService.ofy; import java.io.IOException; import java.text.DateFormat; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.logging.Logger; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.api.client.googleapis.extensions.appengine.auth.oauth2.AppIdentityCredential; import com.google.api.client.http.HttpTransport; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.jackson2.JacksonFactory; import com.google.api.services.bigquery.Bigquery; import com.google.api.services.bigquery.BigqueryScopes; import com.google.appengine.api.utils.SystemProperty; import com.tracker.bigquery.BigQueryService; import com.tracker.bigquery.QueryResult; import com.tracker.entity.ArrivalCompletions; import com.tracker.util.SafeDateFormat; @SuppressWarnings("serial") public class ComputeActiveRequesters extends HttpServlet { @SuppressWarnings("unused") private static final Logger logger = Logger.getLogger(ComputeActiveRequesters.class.getName()); private static final String APPLICATION_ID = SystemProperty.applicationId.get(); private static final String BUCKET = "entities"; private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport(); private static final JsonFactory JSON_FACTORY = new JacksonFactory(); private static final DateFormat dateFormat = SafeDateFormat.forPattern("yyyy-MM-dd HH:mm"); public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { Calendar dateFrom = Calendar.getInstance(); dateFrom.setTime(new Date()); dateFrom.set(Calendar.HOUR_OF_DAY, 0); dateFrom.set(Calendar.MINUTE, 0); dateFrom.set(Calendar.SECOND, 0); dateFrom.set(Calendar.MILLISECOND, 0); dateFrom.add(Calendar.DAY_OF_MONTH, -1); Calendar dateTo = Calendar.getInstance(); dateTo.setTime(dateFrom.getTime()); dateTo.add(Calendar.DAY_OF_MONTH, 1); AppIdentityCredential appIdentityCredential = new AppIdentityCredential(Collections.singleton(BigqueryScopes.BIGQUERY)); Bigquery bigquery = new Bigquery.Builder(HTTP_TRANSPORT, JSON_FACTORY, appIdentityCredential) .setApplicationName(APPLICATION_ID) .build(); BigQueryService bigQueryService = new BigQueryService(bigquery, APPLICATION_ID, BUCKET); List<ArrivalCompletions> list = ofy().load().type(ArrivalCompletions.class) .filter("from >=", dateFrom.getTime()).filter("from <", dateTo.getTime()).list(); for(ArrivalCompletions ac :list) { String query = String.format("SELECT COUNT(*) FROM (SELECT requesterId FROM [entities.HITgroup] " + "WHERE firstSeen<'%s' AND lastSeen>'%s' GROUP BY requesterId)", dateFormat.format(ac.getFrom()), dateFormat.format(ac.getTo())); QueryResult queryResult = bigQueryService.executeQuery(query); long count = 0; for(List<Object> row : queryResult.getData()){ count += Long.parseLong((String)row.get(0)); } if(count > 0) { ac.setActiveRequesters(count); ofy().save().entity(ac); } } } }
src/main/java/com/tracker/servlet/task/ComputeActiveRequesters.java
package com.tracker.servlet.task; import static com.tracker.ofy.OfyService.ofy; import java.io.IOException; import java.text.DateFormat; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.logging.Logger; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.api.client.googleapis.extensions.appengine.auth.oauth2.AppIdentityCredential; import com.google.api.client.http.HttpTransport; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.jackson2.JacksonFactory; import com.google.api.services.bigquery.Bigquery; import com.google.api.services.bigquery.BigqueryScopes; import com.google.appengine.api.utils.SystemProperty; import com.tracker.bigquery.BigQueryService; import com.tracker.bigquery.QueryResult; import com.tracker.entity.ArrivalCompletions; import com.tracker.util.SafeDateFormat; @SuppressWarnings("serial") public class ComputeActiveRequesters extends HttpServlet { @SuppressWarnings("unused") private static final Logger logger = Logger.getLogger(ComputeActiveRequesters.class.getName()); private static final String APPLICATION_ID = SystemProperty.applicationId.get(); private static final String BUCKET = "entities"; private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport(); private static final JsonFactory JSON_FACTORY = new JacksonFactory(); private static final DateFormat dateFormat = SafeDateFormat.forPattern("yyyy-MM-dd HH:mm"); public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { Calendar dateFrom = Calendar.getInstance(); dateFrom.setTime(new Date()); dateFrom.set(Calendar.HOUR_OF_DAY, 0); dateFrom.set(Calendar.MINUTE, 0); dateFrom.set(Calendar.SECOND, 0); dateFrom.set(Calendar.MILLISECOND, 0); dateFrom.add(Calendar.DAY_OF_MONTH, -1); Calendar dateTo = Calendar.getInstance(); dateTo.setTime(dateFrom.getTime()); dateTo.add(Calendar.DAY_OF_MONTH, 1); AppIdentityCredential appIdentityCredential = new AppIdentityCredential(Collections.singleton(BigqueryScopes.BIGQUERY)); Bigquery bigquery = new Bigquery.Builder(HTTP_TRANSPORT, JSON_FACTORY, appIdentityCredential) .setApplicationName(APPLICATION_ID) .build(); BigQueryService bigQueryService = new BigQueryService(bigquery, APPLICATION_ID, BUCKET); List<ArrivalCompletions> list = ofy().load().type(ArrivalCompletions.class) .filter("from >=", dateFrom.getTime()).filter("from <", dateTo.getTime()).list(); for(ArrivalCompletions ac :list) { String query = String.format("SELECT requesterId, COUNT(*) AS cnt " + "FROM [entities.HITgroup] WHERE firstSeen<'%s' AND lastSeen>'%s' GROUP BY requesterId", dateFormat.format(ac.getFrom()), dateFormat.format(ac.getTo())); QueryResult queryResult = bigQueryService.executeQuery(query); long count = 0; for(List<Object> row : queryResult.getData()){ count += Long.parseLong((String)row.get(1)); } if(count > 0) { ac.setActiveRequesters(count); ofy().save().entity(ac); } } } }
updated the query in active requesters computation
src/main/java/com/tracker/servlet/task/ComputeActiveRequesters.java
updated the query in active requesters computation
Java
apache-2.0
9831392b62aa0cc45a8f9d5a236075a819b13f56
0
michaelgallacher/intellij-community,FHannes/intellij-community,xfournet/intellij-community,xfournet/intellij-community,ibinti/intellij-community,apixandru/intellij-community,asedunov/intellij-community,signed/intellij-community,hurricup/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,signed/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,signed/intellij-community,youdonghai/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,ibinti/intellij-community,hurricup/intellij-community,da1z/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,youdonghai/intellij-community,fitermay/intellij-community,da1z/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,michaelgallacher/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,ibinti/intellij-community,da1z/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,mglukhikh/intellij-community,fitermay/intellij-community,hurricup/intellij-community,ibinti/intellij-community,FHannes/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,signed/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,semonte/intellij-community,asedunov/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,michaelgallacher/intellij-community,michaelgallacher/intellij-community,asedunov/intellij-community,semonte/intellij-community,FHannes/intellij-community,hurricup/intellij-community,allotria/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,michaelgallacher/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,ibinti/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,asedunov/intellij-community,hurricup/intellij-community,allotria/intellij-community,hurricup/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,xfournet/intellij-community,ibinti/intellij-community,fitermay/intellij-community,da1z/intellij-community,michaelgallacher/intellij-community,hurricup/intellij-community,signed/intellij-community,allotria/intellij-community,ibinti/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,hurricup/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,FHannes/intellij-community,FHannes/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,da1z/intellij-community,signed/intellij-community,youdonghai/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,michaelgallacher/intellij-community,xfournet/intellij-community,fitermay/intellij-community,asedunov/intellij-community,semonte/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,apixandru/intellij-community,signed/intellij-community,da1z/intellij-community,suncycheng/intellij-community,fitermay/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,apixandru/intellij-community,da1z/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,FHannes/intellij-community,ibinti/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,allotria/intellij-community,da1z/intellij-community,signed/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,hurricup/intellij-community,semonte/intellij-community,vvv1559/intellij-community,semonte/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,michaelgallacher/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,semonte/intellij-community,youdonghai/intellij-community,fitermay/intellij-community,signed/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,apixandru/intellij-community,apixandru/intellij-community,allotria/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,asedunov/intellij-community,fitermay/intellij-community,allotria/intellij-community,vvv1559/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,allotria/intellij-community,xfournet/intellij-community,semonte/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,da1z/intellij-community,fitermay/intellij-community
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.openapi.project; import com.intellij.ide.caches.FileContent; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.vfs.InvalidVirtualFileAccessException; import com.intellij.openapi.vfs.VFileProperty; import com.intellij.openapi.vfs.VfsUtilCore; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.SystemProperties; import com.intellij.util.concurrency.AppExecutorUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Collection; import java.util.Deque; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; /** * @author peter */ public class FileContentQueue { private static final Logger LOG = Logger.getInstance("#com.intellij.ide.startup.FileContentQueue"); private static final long MAX_SIZE_OF_BYTES_IN_QUEUE = 1024 * 1024; private static final long PROCESSED_FILE_BYTES_THRESHOLD = 1024 * 1024 * 3; private static final long LARGE_SIZE_REQUEST_THRESHOLD = PROCESSED_FILE_BYTES_THRESHOLD - 1024 * 300; // 300k for other threads private static final int ourTasksNumber = SystemProperties.getBooleanProperty("idea.allow.parallel.file.reading", true) ? CacheUpdateRunner.indexingThreadCount() : 1; private static final ExecutorService ourExecutor = AppExecutorUtil.createBoundedApplicationPoolExecutor(ourTasksNumber); // Unbounded (!) private final LinkedBlockingDeque<FileContent> myLoadedContents = new LinkedBlockingDeque<FileContent>(); private final AtomicInteger myContentsToLoad = new AtomicInteger(); private final AtomicLong myLoadedBytesInQueue = new AtomicLong(); private final Object myProceedWithLoadingLock = new Object(); private volatile long myBytesBeingProcessed; private volatile boolean myLargeSizeRequested; private final Object myProceedWithProcessingLock = new Object(); private final BlockingQueue<VirtualFile> myFilesQueue; private final ProgressIndicator myProgressIndicator; private static final Deque<FileContentQueue> ourContentLoadingQueues = new LinkedBlockingDeque<>(); public FileContentQueue(@NotNull Collection<VirtualFile> files, @NotNull final ProgressIndicator indicator) { int numberOfFiles = files.size(); myContentsToLoad.set(numberOfFiles); // ABQ is more memory efficient for significant number of files (e.g. 500K) myFilesQueue = numberOfFiles > 0 ? new ArrayBlockingQueue<VirtualFile>(numberOfFiles, false, files) : null; myProgressIndicator = indicator; } public void startLoading() { if (myContentsToLoad.get() == 0) return; for (int i = 0; i < ourTasksNumber; ++i) { ourContentLoadingQueues.addLast(this); Runnable task = () -> { FileContentQueue contentQueue = ourContentLoadingQueues.pollFirst(); while (contentQueue != null) { if (contentQueue.loadNextContent()) { ourContentLoadingQueues.addLast(contentQueue); } contentQueue = ourContentLoadingQueues.pollFirst(); } }; ourExecutor.submit(task); } } private boolean loadNextContent() { VirtualFile file = myFilesQueue.poll(); if (file == null || myProgressIndicator.isCanceled()) return false; try { myProgressIndicator.checkCanceled(); myLoadedContents.offer(loadContent(file, myProgressIndicator)); } catch (ProcessCanceledException e) { return false; } catch (InterruptedException e) { LOG.error(e); } finally { myContentsToLoad.addAndGet(-1); } return true; } private FileContent loadContent(@NotNull VirtualFile file, @NotNull ProgressIndicator indicator) throws InterruptedException { FileContent content = new FileContent(file); if (!isValidFile(file) || !doLoadContent(content, indicator)) { content.setEmptyContent(); } return content; } private static boolean isValidFile(@NotNull VirtualFile file) { return file.isValid() && !file.isDirectory() && !file.is(VFileProperty.SPECIAL) && !VfsUtilCore.isBrokenLink(file); } @SuppressWarnings("InstanceofCatchParameter") private boolean doLoadContent(@NotNull FileContent content, @NotNull final ProgressIndicator indicator) throws InterruptedException { final long contentLength = content.getLength(); boolean counterUpdated = false; try { while (myLoadedBytesInQueue.get() > MAX_SIZE_OF_BYTES_IN_QUEUE) { indicator.checkCanceled(); synchronized (myProceedWithLoadingLock) { myProceedWithLoadingLock.wait(300); } } myLoadedBytesInQueue.addAndGet(contentLength); counterUpdated = true; content.getBytes(); // Reads the content bytes and caches them. return true; } catch (Throwable e) { if (counterUpdated) { myLoadedBytesInQueue.addAndGet(-contentLength); // revert size counter } if (e instanceof ProcessCanceledException) { throw (ProcessCanceledException)e; } else if (e instanceof InterruptedException) { throw (InterruptedException)e; } else if (e instanceof IOException || e instanceof InvalidVirtualFileAccessException) { if (e instanceof FileNotFoundException) { LOG.debug(e); // it is possible to not observe file system change until refresh finish, we handle missed file properly anyway } else { LOG.info(e); } } else if (ApplicationManager.getApplication().isUnitTestMode()) { //noinspection CallToPrintStackTrace e.printStackTrace(); } else { LOG.error(e); } return false; } } @Nullable public FileContent take(@NotNull ProgressIndicator indicator) throws ProcessCanceledException { final FileContent content = doTake(indicator); if (content == null) { return null; } final long length = content.getLength(); while (true) { try { indicator.checkCanceled(); } catch (ProcessCanceledException e) { pushBack(content); throw e; } synchronized (myProceedWithProcessingLock) { final boolean requestingLargeSize = length > LARGE_SIZE_REQUEST_THRESHOLD; if (requestingLargeSize) { myLargeSizeRequested = true; } try { if (myLargeSizeRequested && !requestingLargeSize || myBytesBeingProcessed + length > Math.max(PROCESSED_FILE_BYTES_THRESHOLD, length)) { myProceedWithProcessingLock.wait(300); } else { myBytesBeingProcessed += length; if (requestingLargeSize) { myLargeSizeRequested = false; } return content; } } catch (InterruptedException ignore) { } } } } @Nullable private FileContent doTake(ProgressIndicator indicator) { FileContent result = null; while (result == null) { try { int remainingContentsToLoad = myContentsToLoad.get(); result = myLoadedContents.poll(50, TimeUnit.MILLISECONDS); if (result == null) { if (remainingContentsToLoad == 0) { return null; } indicator.checkCanceled(); } } catch (InterruptedException ex) { throw new RuntimeException(ex); } } long loadedBytesInQueueNow = myLoadedBytesInQueue.addAndGet(-result.getLength()); if (loadedBytesInQueueNow < MAX_SIZE_OF_BYTES_IN_QUEUE) { synchronized (myProceedWithLoadingLock) { // we actually ask only content loading thread to proceed, so there should not be much difference with plain notify myProceedWithLoadingLock.notifyAll(); } } return result; } public void release(@NotNull FileContent content) { synchronized (myProceedWithProcessingLock) { myBytesBeingProcessed -= content.getLength(); myProceedWithProcessingLock.notifyAll(); // ask all sleeping threads to proceed, there can be more than one of them } } public void pushBack(@NotNull FileContent content) { myLoadedBytesInQueue.addAndGet(content.getLength()); myLoadedContents.addFirst(content); } }
platform/platform-impl/src/com/intellij/openapi/project/FileContentQueue.java
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.openapi.project; import com.intellij.ide.caches.FileContent; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.vfs.InvalidVirtualFileAccessException; import com.intellij.openapi.vfs.VFileProperty; import com.intellij.openapi.vfs.VfsUtilCore; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.SystemProperties; import com.intellij.util.concurrency.AppExecutorUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Collection; import java.util.Deque; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicInteger; /** * @author peter */ public class FileContentQueue { private static final Logger LOG = Logger.getInstance("#com.intellij.ide.startup.FileContentQueue"); private static final long MAX_SIZE_OF_BYTES_IN_QUEUE = 1024 * 1024; private static final long PROCESSED_FILE_BYTES_THRESHOLD = 1024 * 1024 * 3; private static final long LARGE_SIZE_REQUEST_THRESHOLD = PROCESSED_FILE_BYTES_THRESHOLD - 1024 * 300; // 300k for other threads private static final int ourTasksNumber = SystemProperties.getBooleanProperty("idea.allow.parallel.file.reading", true) ? CacheUpdateRunner.indexingThreadCount() : 1; private static final ExecutorService ourExecutor = AppExecutorUtil.createBoundedApplicationPoolExecutor(ourTasksNumber); // Unbounded (!) private final LinkedBlockingDeque<FileContent> myLoadedContents = new LinkedBlockingDeque<FileContent>(); private final AtomicInteger myContentsToLoad = new AtomicInteger(); private volatile long myLoadedBytesInQueue; private final Object myProceedWithLoadingLock = new Object(); private volatile long myBytesBeingProcessed; private volatile boolean myLargeSizeRequested; private final Object myProceedWithProcessingLock = new Object(); private final BlockingQueue<VirtualFile> myFilesQueue; private final ProgressIndicator myProgressIndicator; private static final Deque<FileContentQueue> ourContentLoadingQueues = new LinkedBlockingDeque<>(); public FileContentQueue(@NotNull Collection<VirtualFile> files, @NotNull final ProgressIndicator indicator) { int numberOfFiles = files.size(); myContentsToLoad.set(numberOfFiles); // ABQ is more memory efficient for significant number of files (e.g. 500K) myFilesQueue = numberOfFiles > 0 ? new ArrayBlockingQueue<VirtualFile>(numberOfFiles, false, files) : null; myProgressIndicator = indicator; } public void startLoading() { if (myContentsToLoad.get() == 0) return; for (int i = 0; i < ourTasksNumber; ++i) { ourContentLoadingQueues.addLast(this); Runnable task = () -> { FileContentQueue contentQueue = ourContentLoadingQueues.pollFirst(); while (contentQueue != null) { if (contentQueue.loadNextContent()) { ourContentLoadingQueues.addLast(contentQueue); } contentQueue = ourContentLoadingQueues.pollFirst(); } }; ourExecutor.submit(task); } } private boolean loadNextContent() { VirtualFile file = myFilesQueue.poll(); if (file == null || myProgressIndicator.isCanceled()) return false; try { myProgressIndicator.checkCanceled(); myLoadedContents.offer(loadContent(file, myProgressIndicator)); } catch (ProcessCanceledException e) { return false; } catch (InterruptedException e) { LOG.error(e); } finally { myContentsToLoad.addAndGet(-1); } return true; } private FileContent loadContent(@NotNull VirtualFile file, @NotNull ProgressIndicator indicator) throws InterruptedException { FileContent content = new FileContent(file); if (!isValidFile(file) || !doLoadContent(content, indicator)) { content.setEmptyContent(); } return content; } private static boolean isValidFile(@NotNull VirtualFile file) { return file.isValid() && !file.isDirectory() && !file.is(VFileProperty.SPECIAL) && !VfsUtilCore.isBrokenLink(file); } @SuppressWarnings("InstanceofCatchParameter") private boolean doLoadContent(@NotNull FileContent content, @NotNull final ProgressIndicator indicator) throws InterruptedException { final long contentLength = content.getLength(); boolean counterUpdated = false; try { synchronized (myProceedWithLoadingLock) { while (myLoadedBytesInQueue > MAX_SIZE_OF_BYTES_IN_QUEUE) { indicator.checkCanceled(); myProceedWithLoadingLock.wait(300); } myLoadedBytesInQueue += contentLength; counterUpdated = true; } content.getBytes(); // Reads the content bytes and caches them. return true; } catch (Throwable e) { if (counterUpdated) { synchronized (myProceedWithLoadingLock) { myLoadedBytesInQueue -= contentLength; // revert size counter } } if (e instanceof ProcessCanceledException) { throw (ProcessCanceledException)e; } else if (e instanceof InterruptedException) { throw (InterruptedException)e; } else if (e instanceof IOException || e instanceof InvalidVirtualFileAccessException) { if (e instanceof FileNotFoundException) { LOG.debug(e); // it is possible to not observe file system change until refresh finish, we handle missed file properly anyway } else { LOG.info(e); } } else if (ApplicationManager.getApplication().isUnitTestMode()) { //noinspection CallToPrintStackTrace e.printStackTrace(); } else { LOG.error(e); } return false; } } @Nullable public FileContent take(@NotNull ProgressIndicator indicator) throws ProcessCanceledException { final FileContent content = doTake(indicator); if (content == null) { return null; } final long length = content.getLength(); while (true) { try { indicator.checkCanceled(); } catch (ProcessCanceledException e) { pushBack(content); throw e; } synchronized (myProceedWithProcessingLock) { final boolean requestingLargeSize = length > LARGE_SIZE_REQUEST_THRESHOLD; if (requestingLargeSize) { myLargeSizeRequested = true; } try { if (myLargeSizeRequested && !requestingLargeSize || myBytesBeingProcessed + length > Math.max(PROCESSED_FILE_BYTES_THRESHOLD, length)) { myProceedWithProcessingLock.wait(300); } else { myBytesBeingProcessed += length; if (requestingLargeSize) { myLargeSizeRequested = false; } return content; } } catch (InterruptedException ignore) { } } } } @Nullable private FileContent doTake(ProgressIndicator indicator) { FileContent result = null; while (result == null) { try { int remainingContentsToLoad = myContentsToLoad.get(); result = myLoadedContents.poll(50, TimeUnit.MILLISECONDS); if (result == null) { if (remainingContentsToLoad == 0) { return null; } indicator.checkCanceled(); } } catch (InterruptedException ex) { throw new RuntimeException(ex); } } synchronized (myProceedWithLoadingLock) { myLoadedBytesInQueue -= result.getLength(); if (myLoadedBytesInQueue < MAX_SIZE_OF_BYTES_IN_QUEUE) { myProceedWithLoadingLock .notifyAll(); // we actually ask only content loading thread to proceed, so there should not be much difference with plain notify } } return result; } public void release(@NotNull FileContent content) { synchronized (myProceedWithProcessingLock) { myBytesBeingProcessed -= content.getLength(); myProceedWithProcessingLock.notifyAll(); // ask all sleeping threads to proceed, there can be more than one of them } } public void pushBack(@NotNull FileContent content) { synchronized (myProceedWithLoadingLock) { myLoadedBytesInQueue += content.getLength(); } myLoadedContents.addFirst(content); } }
[cleanup] use myProceedWithLoadingLock only for waiting when content queue is full and for signalling to proceed with content loading
platform/platform-impl/src/com/intellij/openapi/project/FileContentQueue.java
[cleanup] use myProceedWithLoadingLock only for waiting when content queue is full and for signalling to proceed with content loading
Java
apache-2.0
92aba9f8d280d2f13ea9459e89591919a045a961
0
MovingBlocks/DestinationSol,MovingBlocks/DestinationSol
/* * Copyright 2018 MovingBlocks * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.destinationsol.assets.audio; import com.badlogic.gdx.audio.Music; import org.destinationsol.GameOptions; import org.destinationsol.assets.Assets; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Class responsible for playing all music throughout the game. * <p> * This class does not rely on external updates; once a music set is set to be played, it will play, even looping, * until another is chosen. By default, music does not play concurrently. */ public class OggMusicManager { public static final String MENU_MUSIC_SET = "menu"; public static final String GAME_MUSIC_SET = "game"; private final Map<String, List<Music>> musicMap; private final Music menuMusic; private final List<Music> gameMusic; private Music currentlyPlaying = null; public OggMusicManager() { musicMap = new HashMap<>(); menuMusic = Assets.getMusic("engine:dreadnaught").getMusic(); menuMusic.setLooping(true); registerMusic(MENU_MUSIC_SET, "engine:dreadnaught"); gameMusic = new ArrayList<>(); gameMusic.add(Assets.getMusic("engine:cimmerianDawn").getMusic()); gameMusic.add(Assets.getMusic("engine:intoTheDark").getMusic()); gameMusic.add(Assets.getMusic("engine:spaceTheatre").getMusic()); registerMusic(GAME_MUSIC_SET, "engine:cimmerianDawn"); registerMusic(GAME_MUSIC_SET, "engine:intoTheDark"); registerMusic(GAME_MUSIC_SET, "engine:spaceTheatre"); } public void registerMusic(String musicSet, String music) { registerMusic(musicSet, Assets.getMusic(music).getMusic()); } public void registerMusic(String musicSet, Music music) { if (!musicMap.containsKey(musicSet)) { musicMap.put(musicSet, new ArrayList<>()); } musicMap.get(musicSet).add(music); } public void playMusic(final String musicSet, final GameOptions options) { stopMusic(); int index = 0; if (currentlyPlaying != null && musicMap.get(musicSet).contains(currentlyPlaying)) { // skip the track index = musicMap.get(musicSet).indexOf(currentlyPlaying); if (++index + 1 > musicMap.get(musicSet).size()) { // next track, plus one because indexing is from 0 index = 0; } } final Music music = musicMap.get(musicSet).get(index); music.setOnCompletionListener(a -> playMusic(musicSet, options)); playMusicTrack(music, options); } /** * Start playing the music menu from the beginning of the track. The menu music loops continuously. */ public void playMenuMusic(GameOptions options) { playMusic(MENU_MUSIC_SET, options); } public void playGameMusic(final GameOptions options) { playMusic(GAME_MUSIC_SET, options); } public void playMusicTrack(Music music, GameOptions options) { currentlyPlaying = music; currentlyPlaying.setVolume(options.musicVolumeMultiplier); currentlyPlaying.play(); } /** * Stop playing all music. */ public void stopMusic() { if (currentlyPlaying != null) { currentlyPlaying.stop(); } } public void resetVolume(GameOptions options) { currentlyPlaying.setVolume(options.musicVolumeMultiplier); } }
engine/src/main/java/org/destinationsol/assets/audio/OggMusicManager.java
/* * Copyright 2018 MovingBlocks * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.destinationsol.assets.audio; import com.badlogic.gdx.audio.Music; import org.destinationsol.GameOptions; import org.destinationsol.assets.Assets; import java.util.ArrayList; import java.util.List; /** * Class responsible for playing all music throughout the game. * * This class does not rely on external updates; once a music set is set to be played, it will play, even looping, * until another is chosen. */ public class OggMusicManager { private final Music menuMusic; private final List<Music> gameMusic; private Music currentlyPlaying = null; public OggMusicManager() { menuMusic = Assets.getMusic("engine:dreadnaught").getMusic(); menuMusic.setLooping(true); gameMusic = new ArrayList<>(); gameMusic.add(Assets.getMusic("engine:cimmerianDawn").getMusic()); gameMusic.add(Assets.getMusic("engine:intoTheDark").getMusic()); gameMusic.add(Assets.getMusic("engine:spaceTheatre").getMusic()); } /** * Start playing the music menu from the beginning of the track. The menu music loops continuously. */ public void playMenuMusic(GameOptions options) { if (currentlyPlaying != null) { if (currentlyPlaying != menuMusic || !currentlyPlaying.isPlaying()) { stopMusic(); playMusic(menuMusic, options); } } else { stopMusic(); playMusic(menuMusic, options); } } public void playGameMusic(final GameOptions options) { stopMusic(); if (currentlyPlaying != null && gameMusic.contains(currentlyPlaying)) { int index = gameMusic.indexOf(currentlyPlaying) + 1; if (gameMusic.size() - 1 >= index) { playMusic(gameMusic.get(index), options); currentlyPlaying.setOnCompletionListener(music -> playGameMusic(options)); } else { playMusic(gameMusic.get(0), options); } } else { playMusic(gameMusic.get(0), options); } } public void playMusic(Music music, GameOptions options) { currentlyPlaying = music; currentlyPlaying.setVolume(options.musicVolumeMultiplier); currentlyPlaying.play(); } /** * Stop playing all music. */ public void stopMusic() { if (currentlyPlaying != null) { currentlyPlaying.stop(); } } public void resetVolume(GameOptions options) { currentlyPlaying.setVolume(options.musicVolumeMultiplier); } }
refactored musicmanager
engine/src/main/java/org/destinationsol/assets/audio/OggMusicManager.java
refactored musicmanager
Java
apache-2.0
07e2a5fcfe2ce7deab4fc959626525203c797314
0
allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.psi.impl; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.util.Pair; import com.intellij.psi.*; import com.intellij.psi.impl.source.HierarchicalMethodSignatureImpl; import com.intellij.psi.impl.source.PsiClassImpl; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.searches.DeepestSuperMethodsSearch; import com.intellij.psi.search.searches.SuperMethodsSearch; import com.intellij.psi.util.*; import com.intellij.util.ArrayUtil; import com.intellij.util.NotNullFunction; import com.intellij.util.Processor; import com.intellij.util.SmartList; import com.intellij.util.containers.ConcurrentFactoryMap; import com.intellij.util.containers.hash.EqualityPolicy; import com.intellij.util.containers.hash.LinkedHashMap; import gnu.trove.THashMap; import gnu.trove.THashSet; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; import java.util.concurrent.ConcurrentMap; public class PsiSuperMethodImplUtil { private static final Logger LOG = Logger.getInstance("#com.intellij.psi.impl.PsiSuperMethodImplUtil"); private static final PsiCacheKey<Map<MethodSignature, HierarchicalMethodSignature>, PsiClass> SIGNATURES_FOR_CLASS_KEY = PsiCacheKey .create("SIGNATURES_FOR_CLASS_KEY", (NotNullFunction<PsiClass, Map<MethodSignature, HierarchicalMethodSignature>>)dom -> buildMethodHierarchy(dom, null, PsiSubstitutor.EMPTY, true, new THashSet<PsiClass>(), false, dom.getResolveScope())); private static final PsiCacheKey<Map<Pair<String, GlobalSearchScope>, Map<MethodSignature, HierarchicalMethodSignature>>, PsiClass> SIGNATURES_BY_NAME_KEY = PsiCacheKey .create("SIGNATURES_BY_NAME_KEY", psiClass -> ConcurrentFactoryMap.createMap( pair -> buildMethodHierarchy(psiClass, pair.first, PsiSubstitutor.EMPTY, true, new THashSet<>(), false, pair.second))); private PsiSuperMethodImplUtil() { } @NotNull public static PsiMethod[] findSuperMethods(@NotNull PsiMethod method) { return findSuperMethods(method, null); } @NotNull public static PsiMethod[] findSuperMethods(@NotNull PsiMethod method, boolean checkAccess) { if (!canHaveSuperMethod(method, checkAccess, false)) return PsiMethod.EMPTY_ARRAY; return findSuperMethodsInternal(method, null); } @NotNull public static PsiMethod[] findSuperMethods(@NotNull PsiMethod method, PsiClass parentClass) { if (!canHaveSuperMethod(method, true, false)) return PsiMethod.EMPTY_ARRAY; return findSuperMethodsInternal(method, parentClass); } @NotNull private static PsiMethod[] findSuperMethodsInternal(@NotNull PsiMethod method, PsiClass parentClass) { List<MethodSignatureBackedByPsiMethod> outputMethods = findSuperMethodSignatures(method, parentClass, false); return MethodSignatureUtil.convertMethodSignaturesToMethods(outputMethods); } @NotNull public static List<MethodSignatureBackedByPsiMethod> findSuperMethodSignaturesIncludingStatic(@NotNull PsiMethod method, boolean checkAccess) { if (!canHaveSuperMethod(method, checkAccess, true)) return Collections.emptyList(); return findSuperMethodSignatures(method, null, true); } @NotNull private static List<MethodSignatureBackedByPsiMethod> findSuperMethodSignatures(@NotNull PsiMethod method, PsiClass parentClass, boolean allowStaticMethod) { return new ArrayList<>(SuperMethodsSearch.search(method, parentClass, true, allowStaticMethod).findAll()); } private static boolean canHaveSuperMethod(@NotNull PsiMethod method, boolean checkAccess, boolean allowStaticMethod) { if (method.isConstructor()) return false; if (!allowStaticMethod && method.hasModifierProperty(PsiModifier.STATIC)) return false; if (checkAccess && method.hasModifierProperty(PsiModifier.PRIVATE)) return false; PsiClass parentClass = method.getContainingClass(); return parentClass != null && !CommonClassNames.JAVA_LANG_OBJECT.equals(parentClass.getQualifiedName()); } @Nullable public static PsiMethod findDeepestSuperMethod(@NotNull PsiMethod method) { if (!canHaveSuperMethod(method, true, false)) return null; return DeepestSuperMethodsSearch.search(method).findFirst(); } @NotNull public static PsiMethod[] findDeepestSuperMethods(@NotNull PsiMethod method) { if (!canHaveSuperMethod(method, true, false)) return PsiMethod.EMPTY_ARRAY; Collection<PsiMethod> collection = DeepestSuperMethodsSearch.search(method).findAll(); return collection.toArray(PsiMethod.EMPTY_ARRAY); } @NotNull private static Map<MethodSignature, HierarchicalMethodSignature> buildMethodHierarchy(@NotNull PsiClass aClass, @Nullable String nameHint, @NotNull PsiSubstitutor substitutor, final boolean includePrivates, @NotNull final Set<? super PsiClass> visited, boolean isInRawContext, GlobalSearchScope resolveScope) { ProgressManager.checkCanceled(); Map<MethodSignature, HierarchicalMethodSignature> result = new LinkedHashMap<>( new EqualityPolicy<MethodSignature>() { @Override public int getHashCode(MethodSignature object) { return object.hashCode(); } @Override public boolean isEqual(MethodSignature o1, MethodSignature o2) { if (o1.equals(o2)) { final PsiMethod method1 = ((MethodSignatureBackedByPsiMethod)o1).getMethod(); final PsiType returnType1 = method1.getReturnType(); final PsiMethod method2 = ((MethodSignatureBackedByPsiMethod)o2).getMethod(); final PsiType returnType2 = method2.getReturnType(); if (method1.hasModifierProperty(PsiModifier.STATIC) || method2.hasModifierProperty(PsiModifier.STATIC)) { return true; } if (MethodSignatureUtil.isReturnTypeSubstitutable(o1, o2, returnType1, returnType2)) { return true; } final PsiClass containingClass1 = method1.getContainingClass(); final PsiClass containingClass2 = method2.getContainingClass(); if (containingClass1 != null && containingClass2 != null) { return containingClass1.isAnnotationType() || containingClass2.isAnnotationType(); } } return false; } }); final Map<MethodSignature, List<PsiMethod>> sameParameterErasureMethods = new THashMap<>(MethodSignatureUtil.METHOD_PARAMETERS_ERASURE_EQUALITY); Map<MethodSignature, HierarchicalMethodSignatureImpl> map = new LinkedHashMap<>(new EqualityPolicy<MethodSignature>() { @Override public int getHashCode(MethodSignature signature) { return MethodSignatureUtil.METHOD_PARAMETERS_ERASURE_EQUALITY.computeHashCode(signature); } @Override public boolean isEqual(MethodSignature o1, MethodSignature o2) { if (!MethodSignatureUtil.METHOD_PARAMETERS_ERASURE_EQUALITY.equals(o1, o2)) return false; List<PsiMethod> list = sameParameterErasureMethods.get(o1); boolean toCheckReturnType = list != null && list.size() > 1; if (!toCheckReturnType) return true; PsiType returnType1 = ((MethodSignatureBackedByPsiMethod)o1).getMethod().getReturnType(); PsiType returnType2 = ((MethodSignatureBackedByPsiMethod)o2).getMethod().getReturnType(); if (returnType1 == null && returnType2 == null) return true; if (returnType1 == null || returnType2 == null) return false; PsiType erasure1 = TypeConversionUtil.erasure(o1.getSubstitutor().substitute(returnType1)); PsiType erasure2 = TypeConversionUtil.erasure(o2.getSubstitutor().substitute(returnType2)); return erasure1.equals(erasure2); } }); PsiMethod[] methods = nameHint == null ? aClass.getMethods() : aClass.findMethodsByName(nameHint, false); if ((nameHint == null || "values".equals(nameHint)) && aClass instanceof PsiClassImpl) { final PsiMethod valuesMethod = ((PsiClassImpl)aClass).getValuesMethod(); if (valuesMethod != null) { methods = ArrayUtil.append(methods, valuesMethod); } } for (PsiMethod method : methods) { if (!method.isValid()) { throw new PsiInvalidElementAccessException(method, "class.valid=" + aClass.isValid() + "; name=" + method.getName()); } if (!includePrivates && method.hasModifierProperty(PsiModifier.PRIVATE)) continue; final MethodSignatureBackedByPsiMethod signature = MethodSignatureBackedByPsiMethod.create(method, PsiSubstitutor.EMPTY, isInRawContext); HierarchicalMethodSignatureImpl newH = new HierarchicalMethodSignatureImpl(MethodSignatureBackedByPsiMethod.create(method, substitutor, isInRawContext)); List<PsiMethod> list = sameParameterErasureMethods.get(signature); if (list == null) { list = new SmartList<>(); sameParameterErasureMethods.put(signature, list); } list.add(method); LOG.assertTrue(newH.getMethod().isValid()); result.put(signature, newH); map.put(signature, newH); } final List<PsiClassType.ClassResolveResult> superTypes = PsiClassImplUtil.getScopeCorrectedSuperTypes(aClass, resolveScope); for (PsiClassType.ClassResolveResult superTypeResolveResult : superTypes) { PsiClass superClass = superTypeResolveResult.getElement(); if (superClass == null) continue; if (!visited.add(superClass)) continue; // cyclic inheritance final PsiSubstitutor superSubstitutor = superTypeResolveResult.getSubstitutor(); PsiSubstitutor finalSubstitutor = PsiSuperMethodUtil.obtainFinalSubstitutor(superClass, superSubstitutor, substitutor, isInRawContext); final boolean isInRawContextSuper = (isInRawContext || PsiUtil.isRawSubstitutor(superClass, superSubstitutor)) && superClass.getTypeParameters().length != 0; Map<MethodSignature, HierarchicalMethodSignature> superResult = buildMethodHierarchy(superClass, nameHint, finalSubstitutor, false, visited, isInRawContextSuper, resolveScope); visited.remove(superClass); List<Pair<MethodSignature, HierarchicalMethodSignature>> flattened = new ArrayList<>(); for (Map.Entry<MethodSignature, HierarchicalMethodSignature> entry : superResult.entrySet()) { HierarchicalMethodSignature hms = entry.getValue(); MethodSignature signature = MethodSignatureBackedByPsiMethod.create(hms.getMethod(), hms.getSubstitutor(), hms.isRaw()); PsiClass containingClass = hms.getMethod().getContainingClass(); List<HierarchicalMethodSignature> supers = new ArrayList<>(hms.getSuperSignatures()); for (HierarchicalMethodSignature aSuper : supers) { PsiClass superContainingClass = aSuper.getMethod().getContainingClass(); if (containingClass != null && superContainingClass != null && !containingClass.isInheritor(superContainingClass, true)) { // methods must be inherited from unrelated classes, so flatten hierarchy here // class C implements SAM1, SAM2 { void methodimpl() {} } //hms.getSuperSignatures().remove(aSuper); flattened.add(Pair.create(signature, aSuper)); } } putInMap(aClass, result, map, hms, signature); } for (Pair<MethodSignature, HierarchicalMethodSignature> pair : flattened) { putInMap(aClass, result, map, pair.second, pair.first); } } for (Map.Entry<MethodSignature, HierarchicalMethodSignatureImpl> entry : map.entrySet()) { HierarchicalMethodSignatureImpl hierarchicalMethodSignature = entry.getValue(); MethodSignature methodSignature = entry.getKey(); if (result.get(methodSignature) == null) { LOG.assertTrue(hierarchicalMethodSignature.getMethod().isValid()); result.put(methodSignature, hierarchicalMethodSignature); } } return result; } private static void putInMap(@NotNull PsiClass aClass, @NotNull Map<MethodSignature, HierarchicalMethodSignature> result, @NotNull Map<MethodSignature, HierarchicalMethodSignatureImpl> map, @NotNull HierarchicalMethodSignature hierarchicalMethodSignature, @NotNull MethodSignature signature) { HierarchicalMethodSignatureImpl existing = map.get(signature); if (existing == null) { HierarchicalMethodSignatureImpl copy = copy(hierarchicalMethodSignature); LOG.assertTrue(copy.getMethod().isValid()); map.put(signature, copy); } else if (isReturnTypeIsMoreSpecificThan(hierarchicalMethodSignature, existing) && isSuperMethod(aClass, hierarchicalMethodSignature, existing)) { HierarchicalMethodSignatureImpl newSuper = copy(hierarchicalMethodSignature); mergeSupers(newSuper, existing); LOG.assertTrue(newSuper.getMethod().isValid()); map.put(signature, newSuper); } else if (isSuperMethod(aClass, existing, hierarchicalMethodSignature)) { mergeSupers(existing, hierarchicalMethodSignature); } // just drop an invalid method declaration there - to highlight accordingly else if (!result.containsKey(signature)) { LOG.assertTrue(hierarchicalMethodSignature.getMethod().isValid()); result.put(signature, hierarchicalMethodSignature); } } private static boolean isReturnTypeIsMoreSpecificThan(@NotNull HierarchicalMethodSignature thisSig, @NotNull HierarchicalMethodSignature thatSig) { PsiType thisRet = thisSig.getSubstitutor().substitute(thisSig.getMethod().getReturnType()); PsiType thatRet = thatSig.getSubstitutor().substitute(thatSig.getMethod().getReturnType()); PsiSubstitutor unifyingSubstitutor = MethodSignatureUtil.isSubsignature(thatSig, thisSig) ? MethodSignatureUtil.getSuperMethodSignatureSubstitutor(thisSig, thatSig) : null; if (unifyingSubstitutor != null) { thisRet = unifyingSubstitutor.substitute(thisRet); thatRet = unifyingSubstitutor.substitute(thatRet); } return thatRet != null && thisRet != null && !thatRet.equals(thisRet) && TypeConversionUtil.isAssignable(thatRet, thisRet, false); } private static void mergeSupers(@NotNull HierarchicalMethodSignatureImpl existing, @NotNull HierarchicalMethodSignature superSignature) { for (HierarchicalMethodSignature existingSuper : existing.getSuperSignatures()) { if (existingSuper.getMethod() == superSignature.getMethod()) { for (HierarchicalMethodSignature signature : superSignature.getSuperSignatures()) { mergeSupers((HierarchicalMethodSignatureImpl)existingSuper, signature); } return; } } if (existing.getMethod() == superSignature.getMethod()) { List<HierarchicalMethodSignature> existingSupers = existing.getSuperSignatures(); for (HierarchicalMethodSignature supers : superSignature.getSuperSignatures()) { if (!existingSupers.contains(supers)) existing.addSuperSignature(copy(supers)); } } else { HierarchicalMethodSignatureImpl copy = copy(superSignature); existing.addSuperSignature(copy); } } private static boolean isSuperMethod(@NotNull PsiClass aClass, @NotNull MethodSignatureBackedByPsiMethod hierarchicalMethodSignature, @NotNull MethodSignatureBackedByPsiMethod superSignatureHierarchical) { PsiMethod superMethod = superSignatureHierarchical.getMethod(); PsiClass superClass = superMethod.getContainingClass(); PsiMethod method = hierarchicalMethodSignature.getMethod(); PsiClass containingClass = method.getContainingClass(); if (!superMethod.isConstructor() && !aClass.equals(superClass) && MethodSignatureUtil.isSubsignature(superSignatureHierarchical, hierarchicalMethodSignature) && superClass != null) { if (superClass.isInterface() || CommonClassNames.JAVA_LANG_OBJECT.equals(superClass.getQualifiedName())) { if (superMethod.hasModifierProperty(PsiModifier.STATIC) || superMethod.hasModifierProperty(PsiModifier.DEFAULT) && method.hasModifierProperty(PsiModifier.STATIC) && !InheritanceUtil.isInheritorOrSelf(containingClass, superClass, true)) { return false; } if (superMethod.hasModifierProperty(PsiModifier.DEFAULT) || method.hasModifierProperty(PsiModifier.DEFAULT)) { return superMethod.equals(method) || !InheritanceUtil.isInheritorOrSelf(superClass, containingClass, true); } return true; } if (containingClass != null) { if (containingClass.isInterface()) { return false; } if (!aClass.isInterface() && !InheritanceUtil.isInheritorOrSelf(superClass, containingClass, true)) { return true; } } } return false; } @NotNull private static HierarchicalMethodSignatureImpl copy(@NotNull HierarchicalMethodSignature hi) { HierarchicalMethodSignatureImpl hierarchicalMethodSignature = new HierarchicalMethodSignatureImpl(hi); for (HierarchicalMethodSignature his : hi.getSuperSignatures()) { hierarchicalMethodSignature.addSuperSignature(copy(his)); } return hierarchicalMethodSignature; } @NotNull public static Collection<HierarchicalMethodSignature> getVisibleSignatures(@NotNull PsiClass aClass) { Map<MethodSignature, HierarchicalMethodSignature> map = getSignaturesMap(aClass); return map.values(); } @NotNull public static HierarchicalMethodSignature getHierarchicalMethodSignature(@NotNull PsiMethod method) { return getHierarchicalMethodSignature(method, method.getResolveScope()); } @NotNull public static HierarchicalMethodSignature getHierarchicalMethodSignature(@NotNull PsiMethod method, @NotNull GlobalSearchScope resolveScope) { Map<GlobalSearchScope, HierarchicalMethodSignature> signatures = CachedValuesManager.getCachedValue(method, () -> { ConcurrentMap<GlobalSearchScope, HierarchicalMethodSignature> map = ConcurrentFactoryMap.createMap(scope -> { PsiClass aClass = method.getContainingClass(); MethodSignature signature = method.getSignature(PsiSubstitutor.EMPTY); HierarchicalMethodSignature result = null; if (aClass != null) { result = SIGNATURES_BY_NAME_KEY.getValue(aClass).get(Pair.create(method.getName(), scope)).get(signature); } if (result == null) { result = new HierarchicalMethodSignatureImpl((MethodSignatureBackedByPsiMethod)signature); } return result; }); return CachedValueProvider.Result.create(map, PsiModificationTracker.JAVA_STRUCTURE_MODIFICATION_COUNT); }); return signatures.get(resolveScope); } @NotNull private static Map<MethodSignature, HierarchicalMethodSignature> getSignaturesMap(@NotNull PsiClass aClass) { return SIGNATURES_FOR_CLASS_KEY.getValue(aClass); } // uses hierarchy signature tree if available, traverses class structure by itself otherwise public static boolean processDirectSuperMethodsSmart(@NotNull PsiMethod method, @NotNull Processor<? super PsiMethod> superMethodProcessor) { //boolean old = PsiSuperMethodUtil.isSuperMethod(method, superMethod); PsiClass aClass = method.getContainingClass(); if (aClass == null) return false; if (!canHaveSuperMethod(method, true, false)) return false; Map<MethodSignature, HierarchicalMethodSignature> cachedMap = SIGNATURES_BY_NAME_KEY.getValue(aClass).get(Pair.create(method.getName(), method.getResolveScope())); HierarchicalMethodSignature signature = cachedMap.get(method.getSignature(PsiSubstitutor.EMPTY)); if (signature != null) { List<HierarchicalMethodSignature> superSignatures = signature.getSuperSignatures(); for (HierarchicalMethodSignature superSignature : superSignatures) { if (!superMethodProcessor.process(superSignature.getMethod())) return false; } } return true; } }
java/java-psi-impl/src/com/intellij/psi/impl/PsiSuperMethodImplUtil.java
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.psi.impl; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.util.Pair; import com.intellij.psi.*; import com.intellij.psi.impl.source.HierarchicalMethodSignatureImpl; import com.intellij.psi.impl.source.PsiClassImpl; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.searches.DeepestSuperMethodsSearch; import com.intellij.psi.search.searches.SuperMethodsSearch; import com.intellij.psi.util.*; import com.intellij.util.ArrayUtil; import com.intellij.util.NotNullFunction; import com.intellij.util.Processor; import com.intellij.util.SmartList; import com.intellij.util.containers.ConcurrentFactoryMap; import com.intellij.util.containers.hash.EqualityPolicy; import com.intellij.util.containers.hash.LinkedHashMap; import gnu.trove.THashMap; import gnu.trove.THashSet; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; import java.util.concurrent.ConcurrentMap; public class PsiSuperMethodImplUtil { private static final Logger LOG = Logger.getInstance("#com.intellij.psi.impl.PsiSuperMethodImplUtil"); private static final PsiCacheKey<Map<MethodSignature, HierarchicalMethodSignature>, PsiClass> SIGNATURES_FOR_CLASS_KEY = PsiCacheKey .create("SIGNATURES_FOR_CLASS_KEY", (NotNullFunction<PsiClass, Map<MethodSignature, HierarchicalMethodSignature>>)dom -> buildMethodHierarchy(dom, null, PsiSubstitutor.EMPTY, true, new THashSet<PsiClass>(), false, dom.getResolveScope())); private static final PsiCacheKey<Map<Pair<String, GlobalSearchScope>, Map<MethodSignature, HierarchicalMethodSignature>>, PsiClass> SIGNATURES_BY_NAME_KEY = PsiCacheKey .create("SIGNATURES_BY_NAME_KEY", psiClass -> ConcurrentFactoryMap.createMap( pair -> buildMethodHierarchy(psiClass, pair.first, PsiSubstitutor.EMPTY, true, new THashSet<>(), false, pair.second))); private PsiSuperMethodImplUtil() { } @NotNull public static PsiMethod[] findSuperMethods(@NotNull PsiMethod method) { return findSuperMethods(method, null); } @NotNull public static PsiMethod[] findSuperMethods(@NotNull PsiMethod method, boolean checkAccess) { if (!canHaveSuperMethod(method, checkAccess, false)) return PsiMethod.EMPTY_ARRAY; return findSuperMethodsInternal(method, null); } @NotNull public static PsiMethod[] findSuperMethods(@NotNull PsiMethod method, PsiClass parentClass) { if (!canHaveSuperMethod(method, true, false)) return PsiMethod.EMPTY_ARRAY; return findSuperMethodsInternal(method, parentClass); } @NotNull private static PsiMethod[] findSuperMethodsInternal(@NotNull PsiMethod method, PsiClass parentClass) { List<MethodSignatureBackedByPsiMethod> outputMethods = findSuperMethodSignatures(method, parentClass, false); return MethodSignatureUtil.convertMethodSignaturesToMethods(outputMethods); } @NotNull public static List<MethodSignatureBackedByPsiMethod> findSuperMethodSignaturesIncludingStatic(@NotNull PsiMethod method, boolean checkAccess) { if (!canHaveSuperMethod(method, checkAccess, true)) return Collections.emptyList(); return findSuperMethodSignatures(method, null, true); } @NotNull private static List<MethodSignatureBackedByPsiMethod> findSuperMethodSignatures(@NotNull PsiMethod method, PsiClass parentClass, boolean allowStaticMethod) { return new ArrayList<>(SuperMethodsSearch.search(method, parentClass, true, allowStaticMethod).findAll()); } private static boolean canHaveSuperMethod(@NotNull PsiMethod method, boolean checkAccess, boolean allowStaticMethod) { if (method.isConstructor()) return false; if (!allowStaticMethod && method.hasModifierProperty(PsiModifier.STATIC)) return false; if (checkAccess && method.hasModifierProperty(PsiModifier.PRIVATE)) return false; PsiClass parentClass = method.getContainingClass(); return parentClass != null && !CommonClassNames.JAVA_LANG_OBJECT.equals(parentClass.getQualifiedName()); } @Nullable public static PsiMethod findDeepestSuperMethod(@NotNull PsiMethod method) { if (!canHaveSuperMethod(method, true, false)) return null; return DeepestSuperMethodsSearch.search(method).findFirst(); } @NotNull public static PsiMethod[] findDeepestSuperMethods(@NotNull PsiMethod method) { if (!canHaveSuperMethod(method, true, false)) return PsiMethod.EMPTY_ARRAY; Collection<PsiMethod> collection = DeepestSuperMethodsSearch.search(method).findAll(); return collection.toArray(PsiMethod.EMPTY_ARRAY); } @NotNull private static Map<MethodSignature, HierarchicalMethodSignature> buildMethodHierarchy(@NotNull PsiClass aClass, @Nullable String nameHint, @NotNull PsiSubstitutor substitutor, final boolean includePrivates, @NotNull final Set<? super PsiClass> visited, boolean isInRawContext, GlobalSearchScope resolveScope) { ProgressManager.checkCanceled(); Map<MethodSignature, HierarchicalMethodSignature> result = new LinkedHashMap<>( new EqualityPolicy<MethodSignature>() { @Override public int getHashCode(MethodSignature object) { return object.hashCode(); } @Override public boolean isEqual(MethodSignature o1, MethodSignature o2) { if (o1.equals(o2)) { final PsiMethod method1 = ((MethodSignatureBackedByPsiMethod)o1).getMethod(); final PsiType returnType1 = method1.getReturnType(); final PsiMethod method2 = ((MethodSignatureBackedByPsiMethod)o2).getMethod(); final PsiType returnType2 = method2.getReturnType(); if (method1.hasModifierProperty(PsiModifier.STATIC) || method2.hasModifierProperty(PsiModifier.STATIC)) { return true; } if (MethodSignatureUtil.isReturnTypeSubstitutable(o1, o2, returnType1, returnType2)) { return true; } final PsiClass containingClass1 = method1.getContainingClass(); final PsiClass containingClass2 = method2.getContainingClass(); if (containingClass1 != null && containingClass2 != null) { return containingClass1.isAnnotationType() || containingClass2.isAnnotationType(); } } return false; } }); final Map<MethodSignature, List<PsiMethod>> sameParameterErasureMethods = new THashMap<>(MethodSignatureUtil.METHOD_PARAMETERS_ERASURE_EQUALITY); Map<MethodSignature, HierarchicalMethodSignatureImpl> map = new LinkedHashMap<>(new EqualityPolicy<MethodSignature>() { @Override public int getHashCode(MethodSignature signature) { return MethodSignatureUtil.METHOD_PARAMETERS_ERASURE_EQUALITY.computeHashCode(signature); } @Override public boolean isEqual(MethodSignature o1, MethodSignature o2) { if (!MethodSignatureUtil.METHOD_PARAMETERS_ERASURE_EQUALITY.equals(o1, o2)) return false; List<PsiMethod> list = sameParameterErasureMethods.get(o1); boolean toCheckReturnType = list != null && list.size() > 1; if (!toCheckReturnType) return true; PsiType returnType1 = ((MethodSignatureBackedByPsiMethod)o1).getMethod().getReturnType(); PsiType returnType2 = ((MethodSignatureBackedByPsiMethod)o2).getMethod().getReturnType(); if (returnType1 == null && returnType2 == null) return true; if (returnType1 == null || returnType2 == null) return false; PsiType erasure1 = TypeConversionUtil.erasure(o1.getSubstitutor().substitute(returnType1)); PsiType erasure2 = TypeConversionUtil.erasure(o2.getSubstitutor().substitute(returnType2)); return erasure1.equals(erasure2); } }); PsiMethod[] methods = aClass.getMethods(); if ((nameHint == null || "values".equals(nameHint)) && aClass instanceof PsiClassImpl) { final PsiMethod valuesMethod = ((PsiClassImpl)aClass).getValuesMethod(); if (valuesMethod != null) { methods = ArrayUtil.append(methods, valuesMethod); } } for (PsiMethod method : methods) { if (!method.isValid()) { throw new PsiInvalidElementAccessException(method, "class.valid=" + aClass.isValid() + "; name=" + method.getName()); } if (nameHint != null && !nameHint.equals(method.getName())) continue; if (!includePrivates && method.hasModifierProperty(PsiModifier.PRIVATE)) continue; final MethodSignatureBackedByPsiMethod signature = MethodSignatureBackedByPsiMethod.create(method, PsiSubstitutor.EMPTY, isInRawContext); HierarchicalMethodSignatureImpl newH = new HierarchicalMethodSignatureImpl(MethodSignatureBackedByPsiMethod.create(method, substitutor, isInRawContext)); List<PsiMethod> list = sameParameterErasureMethods.get(signature); if (list == null) { list = new SmartList<>(); sameParameterErasureMethods.put(signature, list); } list.add(method); LOG.assertTrue(newH.getMethod().isValid()); result.put(signature, newH); map.put(signature, newH); } final List<PsiClassType.ClassResolveResult> superTypes = PsiClassImplUtil.getScopeCorrectedSuperTypes(aClass, resolveScope); for (PsiClassType.ClassResolveResult superTypeResolveResult : superTypes) { PsiClass superClass = superTypeResolveResult.getElement(); if (superClass == null) continue; if (!visited.add(superClass)) continue; // cyclic inheritance final PsiSubstitutor superSubstitutor = superTypeResolveResult.getSubstitutor(); PsiSubstitutor finalSubstitutor = PsiSuperMethodUtil.obtainFinalSubstitutor(superClass, superSubstitutor, substitutor, isInRawContext); final boolean isInRawContextSuper = (isInRawContext || PsiUtil.isRawSubstitutor(superClass, superSubstitutor)) && superClass.getTypeParameters().length != 0; Map<MethodSignature, HierarchicalMethodSignature> superResult = buildMethodHierarchy(superClass, nameHint, finalSubstitutor, false, visited, isInRawContextSuper, resolveScope); visited.remove(superClass); List<Pair<MethodSignature, HierarchicalMethodSignature>> flattened = new ArrayList<>(); for (Map.Entry<MethodSignature, HierarchicalMethodSignature> entry : superResult.entrySet()) { HierarchicalMethodSignature hms = entry.getValue(); MethodSignature signature = MethodSignatureBackedByPsiMethod.create(hms.getMethod(), hms.getSubstitutor(), hms.isRaw()); PsiClass containingClass = hms.getMethod().getContainingClass(); List<HierarchicalMethodSignature> supers = new ArrayList<>(hms.getSuperSignatures()); for (HierarchicalMethodSignature aSuper : supers) { PsiClass superContainingClass = aSuper.getMethod().getContainingClass(); if (containingClass != null && superContainingClass != null && !containingClass.isInheritor(superContainingClass, true)) { // methods must be inherited from unrelated classes, so flatten hierarchy here // class C implements SAM1, SAM2 { void methodimpl() {} } //hms.getSuperSignatures().remove(aSuper); flattened.add(Pair.create(signature, aSuper)); } } putInMap(aClass, result, map, hms, signature); } for (Pair<MethodSignature, HierarchicalMethodSignature> pair : flattened) { putInMap(aClass, result, map, pair.second, pair.first); } } for (Map.Entry<MethodSignature, HierarchicalMethodSignatureImpl> entry : map.entrySet()) { HierarchicalMethodSignatureImpl hierarchicalMethodSignature = entry.getValue(); MethodSignature methodSignature = entry.getKey(); if (result.get(methodSignature) == null) { LOG.assertTrue(hierarchicalMethodSignature.getMethod().isValid()); result.put(methodSignature, hierarchicalMethodSignature); } } return result; } private static void putInMap(@NotNull PsiClass aClass, @NotNull Map<MethodSignature, HierarchicalMethodSignature> result, @NotNull Map<MethodSignature, HierarchicalMethodSignatureImpl> map, @NotNull HierarchicalMethodSignature hierarchicalMethodSignature, @NotNull MethodSignature signature) { HierarchicalMethodSignatureImpl existing = map.get(signature); if (existing == null) { HierarchicalMethodSignatureImpl copy = copy(hierarchicalMethodSignature); LOG.assertTrue(copy.getMethod().isValid()); map.put(signature, copy); } else if (isReturnTypeIsMoreSpecificThan(hierarchicalMethodSignature, existing) && isSuperMethod(aClass, hierarchicalMethodSignature, existing)) { HierarchicalMethodSignatureImpl newSuper = copy(hierarchicalMethodSignature); mergeSupers(newSuper, existing); LOG.assertTrue(newSuper.getMethod().isValid()); map.put(signature, newSuper); } else if (isSuperMethod(aClass, existing, hierarchicalMethodSignature)) { mergeSupers(existing, hierarchicalMethodSignature); } // just drop an invalid method declaration there - to highlight accordingly else if (!result.containsKey(signature)) { LOG.assertTrue(hierarchicalMethodSignature.getMethod().isValid()); result.put(signature, hierarchicalMethodSignature); } } private static boolean isReturnTypeIsMoreSpecificThan(@NotNull HierarchicalMethodSignature thisSig, @NotNull HierarchicalMethodSignature thatSig) { PsiType thisRet = thisSig.getSubstitutor().substitute(thisSig.getMethod().getReturnType()); PsiType thatRet = thatSig.getSubstitutor().substitute(thatSig.getMethod().getReturnType()); PsiSubstitutor unifyingSubstitutor = MethodSignatureUtil.isSubsignature(thatSig, thisSig) ? MethodSignatureUtil.getSuperMethodSignatureSubstitutor(thisSig, thatSig) : null; if (unifyingSubstitutor != null) { thisRet = unifyingSubstitutor.substitute(thisRet); thatRet = unifyingSubstitutor.substitute(thatRet); } return thatRet != null && thisRet != null && !thatRet.equals(thisRet) && TypeConversionUtil.isAssignable(thatRet, thisRet, false); } private static void mergeSupers(@NotNull HierarchicalMethodSignatureImpl existing, @NotNull HierarchicalMethodSignature superSignature) { for (HierarchicalMethodSignature existingSuper : existing.getSuperSignatures()) { if (existingSuper.getMethod() == superSignature.getMethod()) { for (HierarchicalMethodSignature signature : superSignature.getSuperSignatures()) { mergeSupers((HierarchicalMethodSignatureImpl)existingSuper, signature); } return; } } if (existing.getMethod() == superSignature.getMethod()) { List<HierarchicalMethodSignature> existingSupers = existing.getSuperSignatures(); for (HierarchicalMethodSignature supers : superSignature.getSuperSignatures()) { if (!existingSupers.contains(supers)) existing.addSuperSignature(copy(supers)); } } else { HierarchicalMethodSignatureImpl copy = copy(superSignature); existing.addSuperSignature(copy); } } private static boolean isSuperMethod(@NotNull PsiClass aClass, @NotNull MethodSignatureBackedByPsiMethod hierarchicalMethodSignature, @NotNull MethodSignatureBackedByPsiMethod superSignatureHierarchical) { PsiMethod superMethod = superSignatureHierarchical.getMethod(); PsiClass superClass = superMethod.getContainingClass(); PsiMethod method = hierarchicalMethodSignature.getMethod(); PsiClass containingClass = method.getContainingClass(); if (!superMethod.isConstructor() && !aClass.equals(superClass) && MethodSignatureUtil.isSubsignature(superSignatureHierarchical, hierarchicalMethodSignature) && superClass != null) { if (superClass.isInterface() || CommonClassNames.JAVA_LANG_OBJECT.equals(superClass.getQualifiedName())) { if (superMethod.hasModifierProperty(PsiModifier.STATIC) || superMethod.hasModifierProperty(PsiModifier.DEFAULT) && method.hasModifierProperty(PsiModifier.STATIC) && !InheritanceUtil.isInheritorOrSelf(containingClass, superClass, true)) { return false; } if (superMethod.hasModifierProperty(PsiModifier.DEFAULT) || method.hasModifierProperty(PsiModifier.DEFAULT)) { return superMethod.equals(method) || !InheritanceUtil.isInheritorOrSelf(superClass, containingClass, true); } return true; } if (containingClass != null) { if (containingClass.isInterface()) { return false; } if (!aClass.isInterface() && !InheritanceUtil.isInheritorOrSelf(superClass, containingClass, true)) { return true; } } } return false; } @NotNull private static HierarchicalMethodSignatureImpl copy(@NotNull HierarchicalMethodSignature hi) { HierarchicalMethodSignatureImpl hierarchicalMethodSignature = new HierarchicalMethodSignatureImpl(hi); for (HierarchicalMethodSignature his : hi.getSuperSignatures()) { hierarchicalMethodSignature.addSuperSignature(copy(his)); } return hierarchicalMethodSignature; } @NotNull public static Collection<HierarchicalMethodSignature> getVisibleSignatures(@NotNull PsiClass aClass) { Map<MethodSignature, HierarchicalMethodSignature> map = getSignaturesMap(aClass); return map.values(); } @NotNull public static HierarchicalMethodSignature getHierarchicalMethodSignature(@NotNull PsiMethod method) { return getHierarchicalMethodSignature(method, method.getResolveScope()); } @NotNull public static HierarchicalMethodSignature getHierarchicalMethodSignature(@NotNull PsiMethod method, @NotNull GlobalSearchScope resolveScope) { Map<GlobalSearchScope, HierarchicalMethodSignature> signatures = CachedValuesManager.getCachedValue(method, () -> { ConcurrentMap<GlobalSearchScope, HierarchicalMethodSignature> map = ConcurrentFactoryMap.createMap(scope -> { PsiClass aClass = method.getContainingClass(); MethodSignature signature = method.getSignature(PsiSubstitutor.EMPTY); HierarchicalMethodSignature result = null; if (aClass != null) { result = SIGNATURES_BY_NAME_KEY.getValue(aClass).get(Pair.create(method.getName(), scope)).get(signature); } if (result == null) { result = new HierarchicalMethodSignatureImpl((MethodSignatureBackedByPsiMethod)signature); } return result; }); return CachedValueProvider.Result.create(map, PsiModificationTracker.JAVA_STRUCTURE_MODIFICATION_COUNT); }); return signatures.get(resolveScope); } @NotNull private static Map<MethodSignature, HierarchicalMethodSignature> getSignaturesMap(@NotNull PsiClass aClass) { return SIGNATURES_FOR_CLASS_KEY.getValue(aClass); } // uses hierarchy signature tree if available, traverses class structure by itself otherwise public static boolean processDirectSuperMethodsSmart(@NotNull PsiMethod method, @NotNull Processor<? super PsiMethod> superMethodProcessor) { //boolean old = PsiSuperMethodUtil.isSuperMethod(method, superMethod); PsiClass aClass = method.getContainingClass(); if (aClass == null) return false; if (!canHaveSuperMethod(method, true, false)) return false; Map<MethodSignature, HierarchicalMethodSignature> cachedMap = SIGNATURES_BY_NAME_KEY.getValue(aClass).get(Pair.create(method.getName(), method.getResolveScope())); HierarchicalMethodSignature signature = cachedMap.get(method.getSignature(PsiSubstitutor.EMPTY)); if (signature != null) { List<HierarchicalMethodSignature> superSignatures = signature.getSuperSignatures(); for (HierarchicalMethodSignature superSignature : superSignatures) { if (!superMethodProcessor.process(superSignature.getMethod())) return false; } } return true; } }
don't iterate over differently-named methods when building method hierarchy (IDEA-222019) GitOrigin-RevId: c222318f742827528ab1013940d146b1fe6e1aa0
java/java-psi-impl/src/com/intellij/psi/impl/PsiSuperMethodImplUtil.java
don't iterate over differently-named methods when building method hierarchy (IDEA-222019)
Java
apache-2.0
11e46699a61e1b571ba0a89ef6cf0263afee0037
0
liningone/zstack,winger007/zstack,winger007/zstack,zstackio/zstack,camilesing/zstack,WangXijue/zstack,zsyzsyhao/zstack,zstackio/zstack,HeathHose/zstack,MatheMatrix/zstack,zxwing/zstack-1,Alvin-Lau/zstack,zstackorg/zstack,AlanJager/zstack,hhjuliet/zstack,HeathHose/zstack,MaJin1996/zstack,zxwing/zstack-1,MaJin1996/zstack,zstackorg/zstack,WangXijue/zstack,MatheMatrix/zstack,MatheMatrix/zstack,hhjuliet/zstack,AlanJager/zstack,AlanJager/zstack,zsyzsyhao/zstack,WangXijue/zstack,mingjian2049/zstack,zstackio/zstack,mingjian2049/zstack,camilesing/zstack,AlanJinTS/zstack,AlanJinTS/zstack,mingjian2049/zstack,Alvin-Lau/zstack,zxwing/zstack-1,liningone/zstack,Alvin-Lau/zstack,liningone/zstack,HeathHose/zstack,AlanJinTS/zstack,camilesing/zstack
package org.zstack.core.scheduler; import org.springframework.beans.factory.annotation.Autowired; import org.zstack.core.cloudbus.CloudBus; import org.zstack.core.db.DatabaseFacade; import org.zstack.core.errorcode.ErrorFacade; import org.zstack.header.apimediator.ApiMessageInterceptionException; import org.zstack.header.apimediator.ApiMessageInterceptor; import org.zstack.header.apimediator.StopRoutingException; import org.zstack.header.core.scheduler.APICreateSchedulerMessage; import org.zstack.header.core.scheduler.SchedulerVO; import org.zstack.header.errorcode.SysErrors; import org.zstack.header.message.APIMessage; /** * Created by Mei Lei on 7/5/16. */ public class SchedulerApiInterceptor implements ApiMessageInterceptor { @Autowired private CloudBus bus; @Autowired private DatabaseFacade dbf; @Autowired private ErrorFacade errf; private void setServiceId(APIMessage msg) { if (msg instanceof SchedulerMessage) { SchedulerMessage schedmsg = (SchedulerMessage) msg; bus.makeTargetServiceIdByResourceUuid(msg, SchedulerConstant.SERVICE_ID, schedmsg.getSchedulerUuid()); } } // meilei: to do strict check for api @Override public APIMessage intercept(APIMessage msg) throws ApiMessageInterceptionException { setServiceId(msg); if (msg instanceof APIDeleteSchedulerMsg) { validate((APIDeleteSchedulerMsg) msg); } else if (msg instanceof APIUpdateSchedulerMsg) { validate((APIUpdateSchedulerMsg) msg); } else if (msg instanceof APICreateSchedulerMessage ) { validate((APICreateSchedulerMessage) msg); } return msg; } private void validate(APIDeleteSchedulerMsg msg) { if (!dbf.isExist(msg.getUuid(), SchedulerVO.class)) { APIDeleteSchedulerEvent evt = new APIDeleteSchedulerEvent(msg.getId()); bus.publish(evt); throw new StopRoutingException(); } } private void validate(APIUpdateSchedulerMsg msg) { if (!dbf.isExist(msg.getUuid(), SchedulerVO.class)) { APIDeleteSchedulerEvent evt = new APIDeleteSchedulerEvent(msg.getId()); bus.publish(evt); throw new StopRoutingException(); } } private void validate(APICreateSchedulerMessage msg) { if (msg.getStartDate() != null && msg.getStartDate() < 0) { throw new ApiMessageInterceptionException(errf.instantiateErrorCode(SysErrors.INVALID_ARGUMENT_ERROR, String.format("startDate must be positive integer or 0") )); } else if (msg.getStartDate() > 2147454847 ){ // mysql timestamp range is '1970-01-01 00:00:01' UTC to '2038-01-19 03:14:07' UTC. // we accept 0 as startDate means start from current time throw new ApiMessageInterceptionException(errf.instantiateErrorCode(SysErrors.INVALID_ARGUMENT_ERROR, String.format("startDate out of range") )); } if (msg.getRepeatCount() != null && msg.getRepeatCount() <= 0) { throw new ApiMessageInterceptionException(errf.instantiateErrorCode(SysErrors.INVALID_ARGUMENT_ERROR, String.format("repeatCount must be positive integer") )); } if (msg.getType().equals("simple")) { if (msg.getInterval() == null) { if (msg.getRepeatCount() != null && msg.getRepeatCount() != 1) { throw new ApiMessageInterceptionException(errf.instantiateErrorCode(SysErrors.INVALID_ARGUMENT_ERROR, String.format("interval must be set when use simple scheduler when repeat more than once") )); } } else if (msg.getInterval() != null && msg.getInterval() <= 0) { throw new ApiMessageInterceptionException(errf.instantiateErrorCode(SysErrors.INVALID_ARGUMENT_ERROR, String.format("interval must be positive integer") )); } if (msg.getStartDate() == null) { throw new ApiMessageInterceptionException(errf.instantiateErrorCode(SysErrors.INVALID_ARGUMENT_ERROR, String.format("startDate must be set when use simple scheduler") )); } } if (msg.getType().equals("cron")) { if (msg.getCron() == null || ( msg.getCron() !=null && msg.getCron().isEmpty())) { throw new ApiMessageInterceptionException(errf.instantiateErrorCode(SysErrors.INVALID_ARGUMENT_ERROR, String.format("cron must be set when use cron scheduler") )); } if ( (! msg.getCron().contains("?")) || msg.getCron().split(" ").length != 6) { throw new ApiMessageInterceptionException(errf.instantiateErrorCode(SysErrors.INVALID_ARGUMENT_ERROR, String.format("cron task must follow format like this : \"0 0/3 17-23 * * ?\" ") )); } } } }
core/src/main/java/org/zstack/core/scheduler/SchedulerApiInterceptor.java
package org.zstack.core.scheduler; import org.springframework.beans.factory.annotation.Autowired; import org.zstack.core.cloudbus.CloudBus; import org.zstack.core.db.DatabaseFacade; import org.zstack.core.errorcode.ErrorFacade; import org.zstack.header.apimediator.ApiMessageInterceptionException; import org.zstack.header.apimediator.ApiMessageInterceptor; import org.zstack.header.apimediator.StopRoutingException; import org.zstack.header.core.scheduler.APICreateSchedulerMessage; import org.zstack.header.core.scheduler.SchedulerVO; import org.zstack.header.errorcode.SysErrors; import org.zstack.header.message.APIMessage; /** * Created by Mei Lei on 7/5/16. */ public class SchedulerApiInterceptor implements ApiMessageInterceptor { @Autowired private CloudBus bus; @Autowired private DatabaseFacade dbf; @Autowired private ErrorFacade errf; private void setServiceId(APIMessage msg) { if (msg instanceof SchedulerMessage) { SchedulerMessage schedmsg = (SchedulerMessage) msg; bus.makeTargetServiceIdByResourceUuid(msg, SchedulerConstant.SERVICE_ID, schedmsg.getSchedulerUuid()); } } // meilei: to do strict check for api @Override public APIMessage intercept(APIMessage msg) throws ApiMessageInterceptionException { setServiceId(msg); if (msg instanceof APIDeleteSchedulerMsg) { validate((APIDeleteSchedulerMsg) msg); } else if (msg instanceof APIUpdateSchedulerMsg) { validate((APIUpdateSchedulerMsg) msg); } else if (msg instanceof APICreateSchedulerMessage ) { validate((APICreateSchedulerMessage) msg); } return msg; } private void validate(APIDeleteSchedulerMsg msg) { if (!dbf.isExist(msg.getUuid(), SchedulerVO.class)) { APIDeleteSchedulerEvent evt = new APIDeleteSchedulerEvent(msg.getId()); bus.publish(evt); throw new StopRoutingException(); } } private void validate(APIUpdateSchedulerMsg msg) { if (!dbf.isExist(msg.getUuid(), SchedulerVO.class)) { APIDeleteSchedulerEvent evt = new APIDeleteSchedulerEvent(msg.getId()); bus.publish(evt); throw new StopRoutingException(); } } private void validate(APICreateSchedulerMessage msg) { if (msg.getStartDate() != null && msg.getStartDate() < 0) { throw new ApiMessageInterceptionException(errf.instantiateErrorCode(SysErrors.INVALID_ARGUMENT_ERROR, String.format("startDate must be positive integer or 0") )); } else if (msg.getStartDate() > 2147454847 ){ // mysql timestamp range is '1970-01-01 00:00:01' UTC to '2038-01-19 03:14:07' UTC. // we accept 0 as startDate means start from current time throw new ApiMessageInterceptionException(errf.instantiateErrorCode(SysErrors.INVALID_ARGUMENT_ERROR, String.format("startDate out of range") )); } if (msg.getRepeatCount() != null && msg.getRepeatCount() <= 0) { throw new ApiMessageInterceptionException(errf.instantiateErrorCode(SysErrors.INVALID_ARGUMENT_ERROR, String.format("repeatCount must be positive integer") )); } if (msg.getType().equals("simple")) { if (msg.getInterval() == null && msg.getRepeatCount() != 1) { throw new ApiMessageInterceptionException(errf.instantiateErrorCode(SysErrors.INVALID_ARGUMENT_ERROR, String.format("interval must be set when use simple scheduler when repeat more than once") )); } if (msg.getInterval() != null && msg.getInterval() <= 0) { throw new ApiMessageInterceptionException(errf.instantiateErrorCode(SysErrors.INVALID_ARGUMENT_ERROR, String.format("interval must be positive integer") )); } if (msg.getStartDate() == null) { throw new ApiMessageInterceptionException(errf.instantiateErrorCode(SysErrors.INVALID_ARGUMENT_ERROR, String.format("startDate must be set when use simple scheduler") )); } } if (msg.getType().equals("cron")) { if (msg.getCron() == null || msg.getCron().isEmpty()) { throw new ApiMessageInterceptionException(errf.instantiateErrorCode(SysErrors.INVALID_ARGUMENT_ERROR, String.format("cron must be set when use cron scheduler") )); } if ( ! msg.getCron().contains("?") || msg.getCron().split(" ").length != 6) { throw new ApiMessageInterceptionException(errf.instantiateErrorCode(SysErrors.INVALID_ARGUMENT_ERROR, String.format("cron task must follow format like this : \"0 0/3 17-23 * * ?\" ") )); } } } }
more strict check for use simple scheduler for https://github.com/zxwing/premium/issues/777 Signed-off-by: Mei Lei <[email protected]>
core/src/main/java/org/zstack/core/scheduler/SchedulerApiInterceptor.java
more strict check for use simple scheduler
Java
apache-2.0
805a13506068da57ddab0edb30f38016ae1f2a98
0
introp-software/sakai,willkara/sakai,ouit0408/sakai,OpenCollabZA/sakai,buckett/sakai-gitflow,kwedoff1/sakai,Fudan-University/sakai,liubo404/sakai,colczr/sakai,udayg/sakai,surya-janani/sakai,ktakacs/sakai,bkirschn/sakai,udayg/sakai,whumph/sakai,joserabal/sakai,ktakacs/sakai,clhedrick/sakai,clhedrick/sakai,clhedrick/sakai,buckett/sakai-gitflow,joserabal/sakai,kingmook/sakai,kwedoff1/sakai,bkirschn/sakai,surya-janani/sakai,ouit0408/sakai,udayg/sakai,noondaysun/sakai,udayg/sakai,colczr/sakai,lorenamgUMU/sakai,kwedoff1/sakai,ktakacs/sakai,buckett/sakai-gitflow,OpenCollabZA/sakai,conder/sakai,hackbuteer59/sakai,Fudan-University/sakai,introp-software/sakai,OpenCollabZA/sakai,bkirschn/sakai,duke-compsci290-spring2016/sakai,rodriguezdevera/sakai,willkara/sakai,conder/sakai,ouit0408/sakai,frasese/sakai,whumph/sakai,Fudan-University/sakai,colczr/sakai,bkirschn/sakai,liubo404/sakai,pushyamig/sakai,hackbuteer59/sakai,wfuedu/sakai,willkara/sakai,colczr/sakai,kwedoff1/sakai,liubo404/sakai,clhedrick/sakai,whumph/sakai,wfuedu/sakai,duke-compsci290-spring2016/sakai,zqian/sakai,liubo404/sakai,zqian/sakai,conder/sakai,joserabal/sakai,willkara/sakai,OpenCollabZA/sakai,lorenamgUMU/sakai,joserabal/sakai,buckett/sakai-gitflow,clhedrick/sakai,introp-software/sakai,liubo404/sakai,zqian/sakai,surya-janani/sakai,noondaysun/sakai,ouit0408/sakai,noondaysun/sakai,pushyamig/sakai,introp-software/sakai,hackbuteer59/sakai,ouit0408/sakai,bkirschn/sakai,frasese/sakai,bzhouduke123/sakai,wfuedu/sakai,frasese/sakai,bzhouduke123/sakai,OpenCollabZA/sakai,puramshetty/sakai,wfuedu/sakai,bkirschn/sakai,wfuedu/sakai,Fudan-University/sakai,pushyamig/sakai,ktakacs/sakai,bzhouduke123/sakai,Fudan-University/sakai,hackbuteer59/sakai,frasese/sakai,wfuedu/sakai,kingmook/sakai,Fudan-University/sakai,puramshetty/sakai,udayg/sakai,conder/sakai,lorenamgUMU/sakai,duke-compsci290-spring2016/sakai,hackbuteer59/sakai,wfuedu/sakai,ktakacs/sakai,kingmook/sakai,zqian/sakai,surya-janani/sakai,joserabal/sakai,willkara/sakai,whumph/sakai,kwedoff1/sakai,clhedrick/sakai,pushyamig/sakai,whumph/sakai,colczr/sakai,bkirschn/sakai,zqian/sakai,introp-software/sakai,duke-compsci290-spring2016/sakai,tl-its-umich-edu/sakai,joserabal/sakai,surya-janani/sakai,introp-software/sakai,bzhouduke123/sakai,puramshetty/sakai,hackbuteer59/sakai,puramshetty/sakai,udayg/sakai,ouit0408/sakai,tl-its-umich-edu/sakai,ouit0408/sakai,buckett/sakai-gitflow,liubo404/sakai,duke-compsci290-spring2016/sakai,hackbuteer59/sakai,duke-compsci290-spring2016/sakai,Fudan-University/sakai,pushyamig/sakai,bzhouduke123/sakai,buckett/sakai-gitflow,noondaysun/sakai,ktakacs/sakai,wfuedu/sakai,kingmook/sakai,colczr/sakai,duke-compsci290-spring2016/sakai,OpenCollabZA/sakai,tl-its-umich-edu/sakai,tl-its-umich-edu/sakai,puramshetty/sakai,OpenCollabZA/sakai,conder/sakai,clhedrick/sakai,lorenamgUMU/sakai,colczr/sakai,rodriguezdevera/sakai,frasese/sakai,whumph/sakai,kwedoff1/sakai,frasese/sakai,hackbuteer59/sakai,surya-janani/sakai,zqian/sakai,noondaysun/sakai,pushyamig/sakai,rodriguezdevera/sakai,frasese/sakai,conder/sakai,willkara/sakai,kwedoff1/sakai,pushyamig/sakai,willkara/sakai,kwedoff1/sakai,frasese/sakai,bkirschn/sakai,rodriguezdevera/sakai,duke-compsci290-spring2016/sakai,whumph/sakai,joserabal/sakai,whumph/sakai,kingmook/sakai,liubo404/sakai,pushyamig/sakai,noondaysun/sakai,buckett/sakai-gitflow,udayg/sakai,rodriguezdevera/sakai,clhedrick/sakai,lorenamgUMU/sakai,rodriguezdevera/sakai,tl-its-umich-edu/sakai,ktakacs/sakai,lorenamgUMU/sakai,tl-its-umich-edu/sakai,joserabal/sakai,bzhouduke123/sakai,zqian/sakai,surya-janani/sakai,bzhouduke123/sakai,noondaysun/sakai,tl-its-umich-edu/sakai,willkara/sakai,ktakacs/sakai,puramshetty/sakai,Fudan-University/sakai,noondaysun/sakai,puramshetty/sakai,colczr/sakai,puramshetty/sakai,rodriguezdevera/sakai,bzhouduke123/sakai,buckett/sakai-gitflow,tl-its-umich-edu/sakai,kingmook/sakai,introp-software/sakai,ouit0408/sakai,liubo404/sakai,udayg/sakai,conder/sakai,introp-software/sakai,kingmook/sakai,surya-janani/sakai,OpenCollabZA/sakai,lorenamgUMU/sakai,rodriguezdevera/sakai,kingmook/sakai,lorenamgUMU/sakai,conder/sakai,zqian/sakai
import java.sql.*; import java.io.*; import java.lang.*; import java.util.*; /** * This class fix the sum of assessmentGrading and amke sure that GB scores is the same as * assessmentGrading. * * @author Daisy Flemming<[email protected]> */ public class FixGradingScore { public static void main(String args[]){ if (args[0].equals("fixGradingScore")){ if (args.length > 1) process(args[1], true); // true => persist else System.out.println("Usage: fixGradingScore <publishedAssessmentId>"); } if (args[0].equals("printFixGradingScore")){ if (args.length > 1) process(args[1], false); // false => just print else System.out.println("Usage: printFixGradingScore <publishedAssessmentId>"); } } public static void process(String pubAssessmentIdString, boolean persist){ Long pubAssessmentId = new Long(pubAssessmentIdString); // 1a. get list of assessmentGradingId who has submitted the assesment ArrayList assessmentGradingList = getAssessmentGradingList(pubAssessmentId); // 2. fix assessmentGrading score System.out.println(); System.out.println("--- fix assessmentGrading score ---"); updateAllAssessmentGrading(assessmentGradingList, persist); // 3. fix GB score System.out.println(); System.out.println("--- fix GB score where assessmentGrading.forGrade=1 ---"); int scoringType = getScoringType(pubAssessmentId); HashMap assessmentGradingMap = getAssessmentGradingMap(pubAssessmentId, scoringType); updateGradebookScore(pubAssessmentId, assessmentGradingMap, persist); } /* return a list of assessmentGradingId for a published assessment */ public static ArrayList getAssessmentGradingList(Long assessmentId){ ArrayList list = new ArrayList(); Properties prop = getProperties(); String driver = prop.getProperty("driver"); String url = prop.getProperty("url"); Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; String query = "select a.ASSESSMENTGRADINGID "+ " from SAM_ASSESSMENTGRADING_T a "+ " where a.PUBLISHEDASSESSMENTID="+assessmentId.toString(); try{ // Connect to the database Class.forName(driver).newInstance(); conn = DriverManager.getConnection(url); stmt = conn.prepareStatement(query); rs = stmt.executeQuery(); long currentAssessmentGradingId=0; long currentPublishedItemId=0; while (rs.next()){ long assesmentGradingId = rs.getLong("ASSESSMENTGRADINGID"); list.add(new Long(assesmentGradingId)); } } catch (Exception e) { e.printStackTrace(); } finally{ try { if (rs !=null){rs.close();} if (stmt !=null){stmt.close();} if (conn !=null){conn.close();} } catch (Exception e1){ e1.printStackTrace(); } } return list; } public static void updateAllAssessmentGrading(ArrayList list, boolean persist){ for (int i=0; i<list.size();i++){ updateAssessmentGrading((Long)list.get(i), persist); } } public static void updateAssessmentGrading(Long assessmentGradingId, boolean persist){ Properties prop = getProperties(); String driver = prop.getProperty("driver"); String url = prop.getProperty("url"); Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; float sum = 0; float finalScore = 0; try{ // Connect to the database to get all the answer Class.forName(driver).newInstance(); conn = DriverManager.getConnection(url); String query="update SAM_ASSESSMENTGRADING_T set "+ " TOTALAUTOSCORE=(select SUM(AUTOSCORE) from SAM_ITEMGRADING_T where ASSESSMENTGRADINGID="+ assessmentGradingId.toString()+"), "+ " FINALSCORE=TOTALOVERRIDESCORE + "+ "(select SUM(AUTOSCORE) from SAM_ITEMGRADING_T where ASSESSMENTGRADINGID="+ assessmentGradingId.toString()+") "+ " where ASSESSMENTGRADINGID="+assessmentGradingId.toString(); System.out.println(query); if (persist){ stmt = conn.prepareStatement(query); stmt.executeUpdate(); } } catch (Exception e) { e.printStackTrace(); } finally{ try { if (rs !=null){rs.close();} if (stmt !=null){stmt.close();} if (conn !=null){conn.close();} } catch (Exception e1){ e1.printStackTrace(); } } } public static void updateGradebookScore(Long assessmentId, HashMap map, boolean persist){ Properties prop = getProperties(); String driver = prop.getProperty("driver"); String url = prop.getProperty("url"); Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try{ // Connect to the database Class.forName(driver).newInstance(); conn = DriverManager.getConnection(url); Set keys = map.keySet(); Iterator iter = keys.iterator(); while (iter.hasNext()){ String studentId = (String) iter.next(); Long assessmentGradingId = (Long) map.get(studentId); String finalScore ="(select FINALSCORE from SAM_ASSESSMENTGRADING_T where ASSESSMENTGRADINGID="+ assessmentGradingId.toString()+") "; String title ="(select TITLE from SAM_PUBLISHEDASSESSMENT_T where ID="+assessmentId.toString()+")"; String gradableObjectId ="(select ID from GB_GRADABLE_OBJECT_T where NAME="+title+")"; String query = "update GB_GRADE_RECORD_T set "+ "POINTS_EARNED="+finalScore+" where "+ "STUDENT_ID='"+studentId+"' and "+ "GRADABLE_OBJECT_ID="+gradableObjectId; System.out.println(query); if (persist){ stmt = conn.prepareStatement(query); stmt.executeUpdate(); } } } catch (Exception e) { e.printStackTrace(); } finally{ try { if (rs !=null){rs.close();} if (stmt !=null){stmt.close();} if (conn !=null){conn.close();} } catch (Exception e1){ e1.printStackTrace(); } } } /* 1. get only the assessmentGrading where forgrade=1 and * 2. the last or the highest based on publishedAssessment settings */ public static HashMap getAssessmentGradingMap(Long assessmentId, int scoringType){ HashMap map = new HashMap(); Properties prop = getProperties(); String driver = prop.getProperty("driver"); String url = prop.getProperty("url"); Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; String query ="select ASSESSMENTGRADINGID, AGENTID from SAM_ASSESSMENTGRADING_T where "+ " PUBLISHEDASSESSMENTID="+assessmentId.longValue()+ " and FORGRADE=1 order by AGENTID ASC, SUBMITTEDDATE DESC" ; if (scoringType == 1){ // highest query ="select ASSESSMENTGRADINGID, AGENTID from SAM_ASSESSMENTGRADING_T where "+ " PUBLISHEDASSESSMENTID="+assessmentId.longValue()+ " and FORGRADE=1 order by AGENTID ASC, FINALSCORE DESC" ; } try{ // Connect to the database Class.forName(driver).newInstance(); conn = DriverManager.getConnection(url); stmt = conn.prepareStatement(query); rs = stmt.executeQuery(); while (rs.next()) { long id = rs.getLong("ASSESSMENTGRADINGID"); String agentId = rs.getString("AGENTID"); if (map.get(agentId)==null) map.put(agentId, new Long(id)); } } catch (Exception e) { e.printStackTrace(); } finally{ try { if (rs !=null){rs.close();} if (stmt !=null){stmt.close();} if (conn !=null){conn.close();} } catch (Exception e1){ e1.printStackTrace(); } } return map; } public static int getScoringType(Long assessmentId){ int scoringType = 1; // 1=> highest; 2=> last ArrayList list = new ArrayList(); Properties prop = getProperties(); String driver = prop.getProperty("driver"); String url = prop.getProperty("url"); Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; String query = "select SCORINGTYPE "+ " from SAM_PUBLISHEDEVALUATION_T "+ " where ASSESSMENTID="+assessmentId.toString(); try{ // Connect to the database Class.forName(driver).newInstance(); conn = DriverManager.getConnection(url); stmt = conn.prepareStatement(query); rs = stmt.executeQuery(); long currentAssessmentGradingId=0; long currentPublishedItemId=0; if (rs.next()){ scoringType = rs.getInt("SCORINGTYPE"); } } catch (Exception e) { e.printStackTrace(); } finally{ try { if (rs !=null){rs.close();} if (stmt !=null){stmt.close();} if (conn !=null){conn.close();} } catch (Exception e1){ e1.printStackTrace(); } } return scoringType; } public static Properties getProperties(){ Connection conn = null; Properties prop = new Properties(); try { FileInputStream in = new FileInputStream("database.properties"); prop.load(in); } catch (Exception e) { e.printStackTrace(); } return prop; } }
samigo/tool/src/sql/SAK-VIVIE/FixGradingScore.java
import java.sql.*; import java.io.*; import java.lang.*; import java.util.*; /** * This class removes any duplicate MC/Survey submitted answer so that only the last one stay in * the database. It will also recalculate the final score for an assessment and fix up * data in the gradebook, So that final score in bothe assessment and gradebook is * consistent. Note that the item score will not be modified and we can't fix the MCMR question type. * * @author Daisy Flemming<[email protected]> */ public class FixGradingScore { public static void main(String args[]){ if (args[0].equals("fixGradingScore")){ if (args.length > 1) process(args[1], true); // true => persist else System.out.println("Usage: fixGradingScore <publishedAssessmentId>"); } if (args[0].equals("printFixGradingScore")){ if (args.length > 1) process(args[1], false); // false => just print else System.out.println("Usage: printFixGradingScore <publishedAssessmentId>"); } } public static void process(String pubAssessmentIdString, boolean persist){ Long pubAssessmentId = new Long(pubAssessmentIdString); // 1a. get list of assessmentGradingId who has submitted the assesment // b. get the list of itemGrading taht need to be deleted ArrayList assessmentGradingList = getAssessmentGradingList(pubAssessmentId); // 2. fix assessmentGrading score System.out.println(); System.out.println("--- fix assessmentGrading score ---"); updateAllAssessmentGrading(assessmentGradingList, persist); // 3. fix GB score System.out.println(); System.out.println("--- fix GB score where assessmentGrading.forGrade=1 ---"); int scoringType = getScoringType(pubAssessmentId); HashMap assessmentGradingMap = getAssessmentGradingMap(pubAssessmentId, scoringType); updateGradebookScore(pubAssessmentId, assessmentGradingMap, persist); } /* return a list of assessmentGradingId for a published assessment */ public static ArrayList getAssessmentGradingList(Long assessmentId){ ArrayList list = new ArrayList(); Properties prop = getProperties(); String driver = prop.getProperty("driver"); String url = prop.getProperty("url"); Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; String query = "select a.ASSESSMENTGRADINGID "+ " from SAM_ASSESSMENTGRADING_T a "+ " where a.PUBLISHEDASSESSMENTID="+assessmentId.toString(); try{ // Connect to the database Class.forName(driver).newInstance(); conn = DriverManager.getConnection(url); stmt = conn.prepareStatement(query); rs = stmt.executeQuery(); long currentAssessmentGradingId=0; long currentPublishedItemId=0; while (rs.next()){ long assesmentGradingId = rs.getLong("ASSESSMENTGRADINGID"); list.add(new Long(assesmentGradingId)); } } catch (Exception e) { e.printStackTrace(); } finally{ try { if (rs !=null){rs.close();} if (stmt !=null){stmt.close();} if (conn !=null){conn.close();} } catch (Exception e1){ e1.printStackTrace(); } } return list; } public static void updateAllAssessmentGrading(ArrayList list, boolean persist){ for (int i=0; i<list.size();i++){ updateAssessmentGrading((Long)list.get(i), persist); } } public static void updateAssessmentGrading(Long assessmentGradingId, boolean persist){ Properties prop = getProperties(); String driver = prop.getProperty("driver"); String url = prop.getProperty("url"); Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; float sum = 0; float finalScore = 0; try{ // Connect to the database to get all the answer Class.forName(driver).newInstance(); conn = DriverManager.getConnection(url); String query="update SAM_ASSESSMENTGRADING_T set "+ " TOTALAUTOSCORE=(select SUM(AUTOSCORE) from SAM_ITEMGRADING_T where ASSESSMENTGRADINGID="+ assessmentGradingId.toString()+"), "+ " FINALSCORE=TOTALOVERRIDESCORE + "+ "(select SUM(AUTOSCORE) from SAM_ITEMGRADING_T where ASSESSMENTGRADINGID="+ assessmentGradingId.toString()+") "+ " where ASSESSMENTGRADINGID="+assessmentGradingId.toString(); System.out.println(query); if (persist){ stmt = conn.prepareStatement(query); stmt.executeUpdate(); } } catch (Exception e) { e.printStackTrace(); } finally{ try { if (rs !=null){rs.close();} if (stmt !=null){stmt.close();} if (conn !=null){conn.close();} } catch (Exception e1){ e1.printStackTrace(); } } } public static void updateGradebookScore(Long assessmentId, HashMap map, boolean persist){ Properties prop = getProperties(); String driver = prop.getProperty("driver"); String url = prop.getProperty("url"); Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try{ // Connect to the database Class.forName(driver).newInstance(); conn = DriverManager.getConnection(url); Set keys = map.keySet(); Iterator iter = keys.iterator(); while (iter.hasNext()){ String studentId = (String) iter.next(); Long assessmentGradingId = (Long) map.get(studentId); String finalScore ="(select FINALSCORE from SAM_ASSESSMENTGRADING_T where ASSESSMENTGRADINGID="+ assessmentGradingId.toString()+") "; String title ="(select TITLE from SAM_PUBLISHEDASSESSMENT_T where ID="+assessmentId.toString()+")"; String gradableObjectId ="(select ID from GB_GRADABLE_OBJECT_T where NAME="+title+")"; String query = "update GB_GRADE_RECORD_T set "+ "POINTS_EARNED="+finalScore+" where "+ "STUDENT_ID='"+studentId+"' and "+ "GRADABLE_OBJECT_ID="+gradableObjectId; System.out.println(query); if (persist){ stmt = conn.prepareStatement(query); stmt.executeUpdate(); } } } catch (Exception e) { e.printStackTrace(); } finally{ try { if (rs !=null){rs.close();} if (stmt !=null){stmt.close();} if (conn !=null){conn.close();} } catch (Exception e1){ e1.printStackTrace(); } } } /* 1. get only the assessmentGrading where forgrade=1 and * 2. the last or the highest based on publishedAssessment settings */ public static HashMap getAssessmentGradingMap(Long assessmentId, int scoringType){ HashMap map = new HashMap(); Properties prop = getProperties(); String driver = prop.getProperty("driver"); String url = prop.getProperty("url"); Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; String query ="select ASSESSMENTGRADINGID, AGENTID from SAM_ASSESSMENTGRADING_T where "+ " PUBLISHEDASSESSMENTID="+assessmentId.longValue()+ " and FORGRADE=1 order by AGENTID ASC, SUBMITTEDDATE DESC" ; if (scoringType == 1){ // highest query ="select ASSESSMENTGRADINGID, AGENTID from SAM_ASSESSMENTGRADING_T where "+ " PUBLISHEDASSESSMENTID="+assessmentId.longValue()+ " and FORGRADE=1 order by AGENTID ASC, FINALSCORE DESC" ; } try{ // Connect to the database Class.forName(driver).newInstance(); conn = DriverManager.getConnection(url); stmt = conn.prepareStatement(query); rs = stmt.executeQuery(); while (rs.next()) { long id = rs.getLong("ASSESSMENTGRADINGID"); String agentId = rs.getString("AGENTID"); if (map.get(agentId)==null) map.put(agentId, new Long(id)); } } catch (Exception e) { e.printStackTrace(); } finally{ try { if (rs !=null){rs.close();} if (stmt !=null){stmt.close();} if (conn !=null){conn.close();} } catch (Exception e1){ e1.printStackTrace(); } } return map; } public static int getScoringType(Long assessmentId){ int scoringType = 1; // 1=> highest; 2=> last ArrayList list = new ArrayList(); Properties prop = getProperties(); String driver = prop.getProperty("driver"); String url = prop.getProperty("url"); Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; String query = "select SCORINGTYPE "+ " from SAM_PUBLISHEDEVALUATION_T "+ " where ASSESSMENTID="+assessmentId.toString(); try{ // Connect to the database Class.forName(driver).newInstance(); conn = DriverManager.getConnection(url); stmt = conn.prepareStatement(query); rs = stmt.executeQuery(); long currentAssessmentGradingId=0; long currentPublishedItemId=0; if (rs.next()){ scoringType = rs.getInt("SCORINGTYPE"); } } catch (Exception e) { e.printStackTrace(); } finally{ try { if (rs !=null){rs.close();} if (stmt !=null){stmt.close();} if (conn !=null){conn.close();} } catch (Exception e1){ e1.printStackTrace(); } } return scoringType; } public static Properties getProperties(){ Connection conn = null; Properties prop = new Properties(); try { FileInputStream in = new FileInputStream("database.properties"); prop.load(in); } catch (Exception e) { e.printStackTrace(); } return prop; } }
fix comment git-svn-id: 574bb14f304dbe16c01253ed6697ea749724087f@8961 66ffb92e-73f9-0310-93c1-f5514f145a0a
samigo/tool/src/sql/SAK-VIVIE/FixGradingScore.java
fix comment
Java
apache-2.0
5d8105c835aedeca5791a9ece27057e5b9d2049f
0
facebook/presto,mvp/presto,shixuan-fan/presto,shixuan-fan/presto,prestodb/presto,prestodb/presto,twitter-forks/presto,arhimondr/presto,ptkool/presto,twitter-forks/presto,arhimondr/presto,prestodb/presto,EvilMcJerkface/presto,prestodb/presto,shixuan-fan/presto,zzhao0/presto,zzhao0/presto,facebook/presto,ptkool/presto,ptkool/presto,twitter-forks/presto,zzhao0/presto,mvp/presto,ptkool/presto,mvp/presto,zzhao0/presto,arhimondr/presto,EvilMcJerkface/presto,twitter-forks/presto,twitter-forks/presto,arhimondr/presto,facebook/presto,facebook/presto,prestodb/presto,EvilMcJerkface/presto,shixuan-fan/presto,EvilMcJerkface/presto,EvilMcJerkface/presto,arhimondr/presto,mvp/presto,zzhao0/presto,ptkool/presto,shixuan-fan/presto,facebook/presto,prestodb/presto,mvp/presto
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.orc.reader; import com.facebook.presto.memory.context.LocalMemoryContext; import com.facebook.presto.orc.StreamDescriptor; import com.facebook.presto.orc.TupleDomainFilter; import com.facebook.presto.orc.metadata.ColumnEncoding; import com.facebook.presto.orc.metadata.OrcType; import com.facebook.presto.orc.stream.BooleanInputStream; import com.facebook.presto.orc.stream.ByteArrayInputStream; import com.facebook.presto.orc.stream.InputStreamSource; import com.facebook.presto.orc.stream.InputStreamSources; import com.facebook.presto.orc.stream.LongInputStream; import com.facebook.presto.spi.PrestoException; import com.facebook.presto.spi.block.Block; import com.facebook.presto.spi.block.BlockLease; import com.facebook.presto.spi.block.ClosingBlockLease; import com.facebook.presto.spi.block.RunLengthEncodedBlock; import com.facebook.presto.spi.block.VariableWidthBlock; import com.facebook.presto.spi.type.Type; import io.airlift.slice.Slice; import io.airlift.slice.Slices; import io.airlift.units.DataSize; import org.openjdk.jol.info.ClassLayout; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.Optional; import static com.facebook.presto.array.Arrays.ensureCapacity; import static com.facebook.presto.orc.metadata.Stream.StreamKind.DATA; import static com.facebook.presto.orc.metadata.Stream.StreamKind.LENGTH; import static com.facebook.presto.orc.metadata.Stream.StreamKind.PRESENT; import static com.facebook.presto.orc.reader.SliceSelectiveStreamReader.computeTruncatedLength; import static com.facebook.presto.orc.stream.MissingInputStreamSource.missingStreamSource; import static com.facebook.presto.spi.StandardErrorCode.GENERIC_INTERNAL_ERROR; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; import static io.airlift.slice.SizeOf.sizeOf; import static io.airlift.units.DataSize.Unit.GIGABYTE; import static java.lang.Math.toIntExact; import static java.lang.String.format; import static java.util.Objects.requireNonNull; public class SliceDirectSelectiveStreamReader implements SelectiveStreamReader { private static final int INSTANCE_SIZE = ClassLayout.parseClass(SliceDirectSelectiveStreamReader.class).instanceSize(); private static final int ONE_GIGABYTE = toIntExact(new DataSize(1, GIGABYTE).toBytes()); private final TupleDomainFilter filter; private final boolean nonDeterministicFilter; private final boolean nullsAllowed; private final StreamDescriptor streamDescriptor; private final boolean outputRequired; private final Type outputType; private final boolean isCharType; private final int maxCodePointCount; private int readOffset; private InputStreamSource<BooleanInputStream> presentStreamSource = missingStreamSource(BooleanInputStream.class); private BooleanInputStream presentStream; private InputStreamSource<ByteArrayInputStream> dataStreamSource = missingStreamSource(ByteArrayInputStream.class); private ByteArrayInputStream dataStream; private InputStreamSource<LongInputStream> lengthStreamSource = missingStreamSource(LongInputStream.class); private LongInputStream lengthStream; private boolean rowGroupOpen; private LocalMemoryContext systemMemoryContext; private boolean[] nulls; private int[] outputPositions; private int outputPositionCount; private boolean outputPositionsReadOnly; private boolean allNulls; // true if all requested positions are null private boolean[] isNullVector; // isNull flags for all positions up to the last positions requested in read() private int[] lengthVector; // lengths for all positions up to the last positions requested in read() private int lengthIndex; // index into lengthVector array private int[] offsets; // offsets of requested positions only; specifies position boundaries for the data array private byte[] data; // data for requested positions only private Slice dataAsSlice; // data array wrapped in Slice private boolean valuesInUse; public SliceDirectSelectiveStreamReader(StreamDescriptor streamDescriptor, Optional<TupleDomainFilter> filter, Optional<Type> outputType, LocalMemoryContext newLocalMemoryContext) { this.streamDescriptor = requireNonNull(streamDescriptor, "streamDescriptor is null"); this.filter = requireNonNull(filter, "filter is null").orElse(null); this.systemMemoryContext = newLocalMemoryContext; this.nonDeterministicFilter = this.filter != null && !this.filter.isDeterministic(); this.nullsAllowed = this.filter == null || nonDeterministicFilter || this.filter.testNull(); this.outputType = requireNonNull(outputType, "outputType is null").orElse(null); this.outputRequired = outputType.isPresent(); this.isCharType = streamDescriptor.getOrcType().getOrcTypeKind() == OrcType.OrcTypeKind.CHAR; this.maxCodePointCount = streamDescriptor.getOrcType().getLength().orElse(-1); checkArgument(filter.isPresent() || outputRequired, "filter must be present if outputRequired is false"); } @Override public int read(int offset, int[] positions, int positionCount) throws IOException { if (!rowGroupOpen) { openRowGroup(); } checkState(!valuesInUse, "BlockLease hasn't been closed yet"); if (filter != null) { outputPositions = ensureCapacity(outputPositions, positionCount); } else { outputPositions = positions; outputPositionsReadOnly = true; } systemMemoryContext.setBytes(getRetainedSizeInBytes()); if (readOffset < offset) { skip(offset - readOffset); } prepareForNextRead(positionCount, positions); int streamPosition; if (lengthStream == null) { streamPosition = readAllNulls(positions, positionCount); } else if (filter == null) { streamPosition = readNoFilter(positions, positionCount); } else { streamPosition = readWithFilter(positions, positionCount); } readOffset = offset + streamPosition; return outputPositionCount; } private int readNoFilter(int[] positions, int positionCount) throws IOException { int streamPosition = 0; allNulls = false; for (int i = 0; i < positionCount; i++) { int position = positions[i]; if (position > streamPosition) { skipData(streamPosition, position - streamPosition); streamPosition = position; } int offset = offsets[i]; if (presentStream != null && isNullVector[position]) { if (offsets != null) { offsets[i + 1] = offset; } nulls[i] = true; } else { int length = lengthVector[lengthIndex]; int truncatedLength = 0; if (length > 0) { dataStream.next(data, offset, offset + length); truncatedLength = computeTruncatedLength(dataAsSlice, offset, length, maxCodePointCount, isCharType); } offsets[i + 1] = offset + truncatedLength; lengthIndex++; if (presentStream != null) { nulls[i] = false; } } streamPosition++; } outputPositionCount = positionCount; return streamPosition; } private int readWithFilter(int[] positions, int positionCount) throws IOException { allNulls = false; int streamPosition = 0; int dataToSkip = 0; for (int i = 0; i < positionCount; i++) { int position = positions[i]; if (position > streamPosition) { skipData(streamPosition, position - streamPosition); streamPosition = position; } int offset = outputRequired ? offsets[outputPositionCount] : 0; if (presentStream != null && isNullVector[position]) { if ((nonDeterministicFilter && filter.testNull()) || nullsAllowed) { if (outputRequired) { offsets[outputPositionCount + 1] = offset; nulls[outputPositionCount] = true; } outputPositions[outputPositionCount] = position; outputPositionCount++; } } else { int length = lengthVector[lengthIndex]; int dataOffset = outputRequired ? offset : 0; if (filter.testLength(length)) { if (dataStream != null) { dataStream.skip(dataToSkip); dataToSkip = 0; dataStream.next(data, dataOffset, dataOffset + length); if (filter.testBytes(data, dataOffset, length)) { if (outputRequired) { int truncatedLength = computeTruncatedLength(dataAsSlice, dataOffset, length, maxCodePointCount, isCharType); offsets[outputPositionCount + 1] = offset + truncatedLength; if (nullsAllowed && isNullVector != null) { nulls[outputPositionCount] = false; } } outputPositions[outputPositionCount] = position; outputPositionCount++; } } else { assert length == 0; if (outputRequired) { offsets[outputPositionCount + 1] = offset; if (nullsAllowed && isNullVector != null) { nulls[outputPositionCount] = false; } } outputPositions[outputPositionCount] = position; outputPositionCount++; } } else { dataToSkip += length; } lengthIndex++; } streamPosition++; if (filter != null) { outputPositionCount -= filter.getPrecedingPositionsToFail(); int succeedingPositionsToFail = filter.getSucceedingPositionsToFail(); if (succeedingPositionsToFail > 0) { int positionsToSkip = 0; for (int j = 0; j < succeedingPositionsToFail; j++) { i++; int nextPosition = positions[i]; positionsToSkip += 1 + nextPosition - streamPosition; streamPosition = nextPosition + 1; } skipData(streamPosition, positionsToSkip); } } } if (dataToSkip > 0) { dataStream.skip(dataToSkip); } return streamPosition; } private int readAllNulls(int[] positions, int positionCount) { if (nonDeterministicFilter) { outputPositionCount = 0; for (int i = 0; i < positionCount; i++) { if (filter.testNull()) { outputPositionCount++; } else { outputPositionCount -= filter.getPrecedingPositionsToFail(); i += filter.getSucceedingPositionsToFail(); } } } else if (nullsAllowed) { outputPositionCount = positionCount; if (filter != null) { outputPositions = positions; outputPositionsReadOnly = true; } } else { outputPositionCount = 0; } allNulls = true; return positions[positionCount - 1] + 1; } private void skip(int items) throws IOException { // in case of an empty varbinary both the presentStream and dataStream are null and only lengthStream is present. if (dataStream == null && presentStream != null) { presentStream.skip(items); } else if (presentStream != null) { int lengthToSkip = presentStream.countBitsSet(items); dataStream.skip(lengthStream.sum(lengthToSkip)); } else { long sum = lengthStream.sum(items); if (dataStream != null) { dataStream.skip(sum); } } } private void skipData(int start, int items) throws IOException { int dataToSkip = 0; for (int i = 0; i < items; i++) { if (presentStream == null || !isNullVector[start + i]) { dataToSkip += lengthVector[lengthIndex]; lengthIndex++; } } // in case of an empty varbinary both the presentStream and dataStream are null and only lengthStream is present. if (dataStream != null) { dataStream.skip(dataToSkip); } } @Override public int[] getReadPositions() { return outputPositions; } @Override public Block getBlock(int[] positions, int positionCount) { checkArgument(outputPositionCount > 0, "outputPositionCount must be greater than zero"); checkState(outputRequired, "This stream reader doesn't produce output"); checkState(positionCount <= outputPositionCount, "Not enough values"); checkState(!valuesInUse, "BlockLease hasn't been closed yet"); if (allNulls) { return new RunLengthEncodedBlock(outputType.createBlockBuilder(null, 1).appendNull().build(), outputPositionCount); } boolean includeNulls = nullsAllowed && presentStream != null; if (positionCount != outputPositionCount) { compactValues(positions, positionCount, includeNulls); } Block block = new VariableWidthBlock(positionCount, dataAsSlice, offsets, Optional.ofNullable(includeNulls ? nulls : null)); dataAsSlice = null; data = null; offsets = null; nulls = null; return block; } private void compactValues(int[] positions, int positionCount, boolean includeNulls) { if (outputPositionsReadOnly) { outputPositions = Arrays.copyOf(outputPositions, outputPositionCount); outputPositionsReadOnly = false; } int positionIndex = 0; int nextPosition = positions[positionIndex]; for (int i = 0; i < outputPositionCount; i++) { if (outputPositions[i] < nextPosition) { continue; } assert outputPositions[i] == nextPosition; int length = offsets[i + 1] - offsets[i]; if (length > 0) { System.arraycopy(data, offsets[i], data, offsets[positionIndex], length); } offsets[positionIndex + 1] = offsets[positionIndex] + length; outputPositions[positionIndex] = nextPosition; if (includeNulls) { nulls[positionIndex] = nulls[i]; } positionIndex++; if (positionIndex >= positionCount) { break; } nextPosition = positions[positionIndex]; } outputPositionCount = positionCount; } @Override public BlockLease getBlockView(int[] positions, int positionCount) { checkArgument(outputPositionCount > 0, "outputPositionCount must be greater than zero"); checkState(outputRequired, "This stream reader doesn't produce output"); checkState(positionCount <= outputPositionCount, "Not enough values"); checkState(!valuesInUse, "BlockLease hasn't been closed yet"); if (allNulls) { return newLease(new RunLengthEncodedBlock(outputType.createBlockBuilder(null, 1).appendNull().build(), outputPositionCount)); } boolean includeNulls = nullsAllowed && presentStream != null; if (positionCount != outputPositionCount) { compactValues(positions, positionCount, includeNulls); } return newLease(new VariableWidthBlock(positionCount, dataAsSlice, offsets, Optional.ofNullable(includeNulls ? nulls : null))); } private BlockLease newLease(Block block) { valuesInUse = true; return ClosingBlockLease.newLease(block, () -> valuesInUse = false); } @Override public void throwAnyError(int[] positions, int positionCount) { } @Override public void close() { systemMemoryContext.close(); } private void openRowGroup() throws IOException { presentStream = presentStreamSource.openStream(); lengthStream = lengthStreamSource.openStream(); dataStream = dataStreamSource.openStream(); rowGroupOpen = true; } @Override public void startStripe(InputStreamSources dictionaryStreamSources, List<ColumnEncoding> encoding) { presentStreamSource = missingStreamSource(BooleanInputStream.class); lengthStreamSource = missingStreamSource(LongInputStream.class); dataStreamSource = missingStreamSource(ByteArrayInputStream.class); readOffset = 0; presentStream = null; lengthStream = null; dataStream = null; rowGroupOpen = false; } @Override public void startRowGroup(InputStreamSources dataStreamSources) { presentStreamSource = dataStreamSources.getInputStreamSource(streamDescriptor, PRESENT, BooleanInputStream.class); lengthStreamSource = dataStreamSources.getInputStreamSource(streamDescriptor, LENGTH, LongInputStream.class); dataStreamSource = dataStreamSources.getInputStreamSource(streamDescriptor, DATA, ByteArrayInputStream.class); readOffset = 0; presentStream = null; lengthStream = null; dataStream = null; rowGroupOpen = false; } @Override public long getRetainedSizeInBytes() { return INSTANCE_SIZE + sizeOf(offsets) + sizeOf(outputPositions) + sizeOf(data) + sizeOf(nulls) + sizeOf(lengthVector) + sizeOf(isNullVector); } private void prepareForNextRead(int positionCount, int[] positions) throws IOException { lengthIndex = 0; outputPositionCount = 0; int totalLength = 0; int maxLength = 0; int totalPositions = positions[positionCount - 1] + 1; int nullCount = 0; if (presentStream != null) { isNullVector = ensureCapacity(isNullVector, totalPositions); nullCount = presentStream.getUnsetBits(totalPositions, isNullVector); } if (lengthStream != null) { int nonNullCount = totalPositions - nullCount; lengthVector = ensureCapacity(lengthVector, nonNullCount); lengthStream.nextIntVector(nonNullCount, lengthVector, 0); //TODO calculate totalLength for only requested positions for (int i = 0; i < nonNullCount; i++) { totalLength += lengthVector[i]; maxLength = Math.max(maxLength, lengthVector[i]); } if (totalLength > ONE_GIGABYTE) { throw new PrestoException( GENERIC_INTERNAL_ERROR, format("Values in column \"%s\" are too large to process for Presto. %s column values are larger than 1GB [%s]", streamDescriptor.getFieldName(), positionCount, streamDescriptor.getOrcDataSourceId())); } } if (outputRequired) { if (presentStream != null && nullsAllowed) { nulls = ensureCapacity(nulls, positionCount); } data = ensureCapacity(data, totalLength); offsets = ensureCapacity(offsets, totalPositions + 1); } else { data = ensureCapacity(data, maxLength); } dataAsSlice = Slices.wrappedBuffer(data); } }
presto-orc/src/main/java/com/facebook/presto/orc/reader/SliceDirectSelectiveStreamReader.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.orc.reader; import com.facebook.presto.memory.context.LocalMemoryContext; import com.facebook.presto.orc.StreamDescriptor; import com.facebook.presto.orc.TupleDomainFilter; import com.facebook.presto.orc.metadata.ColumnEncoding; import com.facebook.presto.orc.metadata.OrcType; import com.facebook.presto.orc.stream.BooleanInputStream; import com.facebook.presto.orc.stream.ByteArrayInputStream; import com.facebook.presto.orc.stream.InputStreamSource; import com.facebook.presto.orc.stream.InputStreamSources; import com.facebook.presto.orc.stream.LongInputStream; import com.facebook.presto.spi.PrestoException; import com.facebook.presto.spi.block.Block; import com.facebook.presto.spi.block.BlockLease; import com.facebook.presto.spi.block.ClosingBlockLease; import com.facebook.presto.spi.block.RunLengthEncodedBlock; import com.facebook.presto.spi.block.VariableWidthBlock; import com.facebook.presto.spi.type.Type; import io.airlift.slice.Slice; import io.airlift.slice.Slices; import io.airlift.units.DataSize; import org.openjdk.jol.info.ClassLayout; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.Optional; import static com.facebook.presto.array.Arrays.ensureCapacity; import static com.facebook.presto.orc.metadata.Stream.StreamKind.DATA; import static com.facebook.presto.orc.metadata.Stream.StreamKind.LENGTH; import static com.facebook.presto.orc.metadata.Stream.StreamKind.PRESENT; import static com.facebook.presto.orc.reader.SliceSelectiveStreamReader.computeTruncatedLength; import static com.facebook.presto.orc.stream.MissingInputStreamSource.missingStreamSource; import static com.facebook.presto.spi.StandardErrorCode.GENERIC_INTERNAL_ERROR; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; import static io.airlift.slice.SizeOf.sizeOf; import static io.airlift.units.DataSize.Unit.GIGABYTE; import static java.lang.Math.toIntExact; import static java.lang.String.format; import static java.util.Objects.requireNonNull; public class SliceDirectSelectiveStreamReader implements SelectiveStreamReader { private static final int INSTANCE_SIZE = ClassLayout.parseClass(SliceDirectSelectiveStreamReader.class).instanceSize(); private static final int ONE_GIGABYTE = toIntExact(new DataSize(1, GIGABYTE).toBytes()); private final TupleDomainFilter filter; private final boolean nonDeterministicFilter; private final boolean nullsAllowed; private final StreamDescriptor streamDescriptor; private final boolean outputRequired; private final Type outputType; private final boolean isCharType; private final int maxCodePointCount; private int readOffset; private InputStreamSource<BooleanInputStream> presentStreamSource = missingStreamSource(BooleanInputStream.class); private BooleanInputStream presentStream; private InputStreamSource<ByteArrayInputStream> dataStreamSource = missingStreamSource(ByteArrayInputStream.class); private ByteArrayInputStream dataStream; private InputStreamSource<LongInputStream> lengthStreamSource = missingStreamSource(LongInputStream.class); private LongInputStream lengthStream; private boolean rowGroupOpen; private LocalMemoryContext systemMemoryContext; private boolean[] nulls; private int[] outputPositions; private int outputPositionCount; private boolean outputPositionsReadOnly; private boolean allNulls; // true if all requested positions are null private boolean[] isNullVector; // isNull flags for all positions up to the last positions requested in read() private int[] lengthVector; // lengths for all positions up to the last positions requested in read() private int lengthIndex; // index into lengthVector array private int[] offsets; // offsets of requested positions only; specifies position boundaries for the data array private byte[] data; // data for requested positions only private Slice dataAsSlice; // data array wrapped in Slice private boolean valuesInUse; public SliceDirectSelectiveStreamReader(StreamDescriptor streamDescriptor, Optional<TupleDomainFilter> filter, Optional<Type> outputType, LocalMemoryContext newLocalMemoryContext) { this.streamDescriptor = requireNonNull(streamDescriptor, "streamDescriptor is null"); this.filter = requireNonNull(filter, "filter is null").orElse(null); this.systemMemoryContext = newLocalMemoryContext; this.nonDeterministicFilter = this.filter != null && !this.filter.isDeterministic(); this.nullsAllowed = this.filter == null || nonDeterministicFilter || this.filter.testNull(); this.outputType = requireNonNull(outputType, "outputType is null").orElse(null); this.outputRequired = outputType.isPresent(); this.isCharType = streamDescriptor.getOrcType().getOrcTypeKind() == OrcType.OrcTypeKind.CHAR; this.maxCodePointCount = streamDescriptor.getOrcType().getLength().orElse(-1); checkArgument(filter.isPresent() || outputRequired, "filter must be present if outputRequired is false"); } @Override public int read(int offset, int[] positions, int positionCount) throws IOException { if (!rowGroupOpen) { openRowGroup(); } checkState(!valuesInUse, "BlockLease hasn't been closed yet"); if (filter != null) { outputPositions = ensureCapacity(outputPositions, positionCount); } else { outputPositions = positions; outputPositionsReadOnly = true; } systemMemoryContext.setBytes(getRetainedSizeInBytes()); if (readOffset < offset) { skip(offset - readOffset); } prepareForNextRead(positionCount, positions); int streamPosition; if (lengthStream == null) { streamPosition = readAllNulls(positions, positionCount); } else if (filter == null) { streamPosition = readNoFilter(positions, positionCount); } else { streamPosition = readWithFilter(positions, positionCount); } readOffset = offset + streamPosition; return outputPositionCount; } private int readNoFilter(int[] positions, int positionCount) throws IOException { int streamPosition = 0; allNulls = false; for (int i = 0; i < positionCount; i++) { int position = positions[i]; if (position > streamPosition) { skipData(streamPosition, position - streamPosition); streamPosition = position; } int offset = offsets[i]; if (presentStream != null && isNullVector[position]) { if (offsets != null) { offsets[i + 1] = offset; } nulls[i] = true; } else { int length = lengthVector[lengthIndex]; int truncatedLength = 0; if (length > 0) { dataStream.next(data, offset, offset + length); truncatedLength = computeTruncatedLength(dataAsSlice, offset, length, maxCodePointCount, isCharType); } offsets[i + 1] = offset + truncatedLength; lengthIndex++; if (presentStream != null) { nulls[i] = false; } } streamPosition++; } outputPositionCount = positionCount; return streamPosition; } private int readWithFilter(int[] positions, int positionCount) throws IOException { allNulls = false; int streamPosition = 0; int dataToSkip = 0; for (int i = 0; i < positionCount; i++) { int position = positions[i]; if (position > streamPosition) { skipData(streamPosition, position - streamPosition); streamPosition = position; } int offset = outputRequired ? offsets[outputPositionCount] : 0; if (isNullVector != null && isNullVector[position]) { if ((nonDeterministicFilter && filter.testNull()) || nullsAllowed) { if (outputRequired) { offsets[outputPositionCount + 1] = offset; nulls[outputPositionCount] = true; } outputPositions[outputPositionCount] = position; outputPositionCount++; } } else { int length = lengthVector[lengthIndex]; int dataOffset = outputRequired ? offset : 0; if (filter.testLength(length)) { if (dataStream != null) { dataStream.skip(dataToSkip); dataToSkip = 0; dataStream.next(data, dataOffset, dataOffset + length); if (filter.testBytes(data, dataOffset, length)) { if (outputRequired) { int truncatedLength = computeTruncatedLength(dataAsSlice, dataOffset, length, maxCodePointCount, isCharType); offsets[outputPositionCount + 1] = offset + truncatedLength; if (nullsAllowed && isNullVector != null) { nulls[outputPositionCount] = false; } } outputPositions[outputPositionCount] = position; outputPositionCount++; } } else { assert length == 0; if (outputRequired) { offsets[outputPositionCount + 1] = offset; if (nullsAllowed && isNullVector != null) { nulls[outputPositionCount] = false; } } outputPositions[outputPositionCount] = position; outputPositionCount++; } } else { dataToSkip += length; } lengthIndex++; } streamPosition++; if (filter != null) { outputPositionCount -= filter.getPrecedingPositionsToFail(); int succeedingPositionsToFail = filter.getSucceedingPositionsToFail(); if (succeedingPositionsToFail > 0) { int positionsToSkip = 0; for (int j = 0; j < succeedingPositionsToFail; j++) { i++; int nextPosition = positions[i]; positionsToSkip += 1 + nextPosition - streamPosition; streamPosition = nextPosition + 1; } skipData(streamPosition, positionsToSkip); } } } if (dataToSkip > 0) { dataStream.skip(dataToSkip); } return streamPosition; } private int readAllNulls(int[] positions, int positionCount) { if (nonDeterministicFilter) { outputPositionCount = 0; for (int i = 0; i < positionCount; i++) { if (filter.testNull()) { outputPositionCount++; } else { outputPositionCount -= filter.getPrecedingPositionsToFail(); i += filter.getSucceedingPositionsToFail(); } } } else if (nullsAllowed) { outputPositionCount = positionCount; if (filter != null) { outputPositions = positions; outputPositionsReadOnly = true; } } else { outputPositionCount = 0; } allNulls = true; return positions[positionCount - 1] + 1; } private void skip(int items) throws IOException { // in case of an empty varbinary both the presentStream and dataStream are null and only lengthStream is present. if (dataStream == null && presentStream != null) { presentStream.skip(items); } else if (presentStream != null) { int lengthToSkip = presentStream.countBitsSet(items); dataStream.skip(lengthStream.sum(lengthToSkip)); } else { long sum = lengthStream.sum(items); if (dataStream != null) { dataStream.skip(sum); } } } private void skipData(int start, int items) throws IOException { int dataToSkip = 0; for (int i = 0; i < items; i++) { if (presentStream == null || !isNullVector[start + i]) { dataToSkip += lengthVector[lengthIndex]; lengthIndex++; } } // in case of an empty varbinary both the presentStream and dataStream are null and only lengthStream is present. if (dataStream != null) { dataStream.skip(dataToSkip); } } @Override public int[] getReadPositions() { return outputPositions; } @Override public Block getBlock(int[] positions, int positionCount) { checkArgument(outputPositionCount > 0, "outputPositionCount must be greater than zero"); checkState(outputRequired, "This stream reader doesn't produce output"); checkState(positionCount <= outputPositionCount, "Not enough values"); checkState(!valuesInUse, "BlockLease hasn't been closed yet"); if (allNulls) { return new RunLengthEncodedBlock(outputType.createBlockBuilder(null, 1).appendNull().build(), outputPositionCount); } boolean includeNulls = nullsAllowed && presentStream != null; if (positionCount != outputPositionCount) { compactValues(positions, positionCount, includeNulls); } Block block = new VariableWidthBlock(positionCount, dataAsSlice, offsets, Optional.ofNullable(includeNulls ? nulls : null)); dataAsSlice = null; data = null; offsets = null; nulls = null; return block; } private void compactValues(int[] positions, int positionCount, boolean includeNulls) { if (outputPositionsReadOnly) { outputPositions = Arrays.copyOf(outputPositions, outputPositionCount); outputPositionsReadOnly = false; } int positionIndex = 0; int nextPosition = positions[positionIndex]; for (int i = 0; i < outputPositionCount; i++) { if (outputPositions[i] < nextPosition) { continue; } assert outputPositions[i] == nextPosition; int length = offsets[i + 1] - offsets[i]; if (length > 0) { System.arraycopy(data, offsets[i], data, offsets[positionIndex], length); } offsets[positionIndex + 1] = offsets[positionIndex] + length; outputPositions[positionIndex] = nextPosition; if (includeNulls) { nulls[positionIndex] = nulls[i]; } positionIndex++; if (positionIndex >= positionCount) { break; } nextPosition = positions[positionIndex]; } outputPositionCount = positionCount; } @Override public BlockLease getBlockView(int[] positions, int positionCount) { checkArgument(outputPositionCount > 0, "outputPositionCount must be greater than zero"); checkState(outputRequired, "This stream reader doesn't produce output"); checkState(positionCount <= outputPositionCount, "Not enough values"); checkState(!valuesInUse, "BlockLease hasn't been closed yet"); if (allNulls) { return newLease(new RunLengthEncodedBlock(outputType.createBlockBuilder(null, 1).appendNull().build(), outputPositionCount)); } boolean includeNulls = nullsAllowed && presentStream != null; if (positionCount != outputPositionCount) { compactValues(positions, positionCount, includeNulls); } return newLease(new VariableWidthBlock(positionCount, dataAsSlice, offsets, Optional.ofNullable(includeNulls ? nulls : null))); } private BlockLease newLease(Block block) { valuesInUse = true; return ClosingBlockLease.newLease(block, () -> valuesInUse = false); } @Override public void throwAnyError(int[] positions, int positionCount) { } @Override public void close() { systemMemoryContext.close(); } private void openRowGroup() throws IOException { presentStream = presentStreamSource.openStream(); lengthStream = lengthStreamSource.openStream(); dataStream = dataStreamSource.openStream(); rowGroupOpen = true; } @Override public void startStripe(InputStreamSources dictionaryStreamSources, List<ColumnEncoding> encoding) { presentStreamSource = missingStreamSource(BooleanInputStream.class); lengthStreamSource = missingStreamSource(LongInputStream.class); dataStreamSource = missingStreamSource(ByteArrayInputStream.class); readOffset = 0; presentStream = null; lengthStream = null; dataStream = null; rowGroupOpen = false; } @Override public void startRowGroup(InputStreamSources dataStreamSources) { presentStreamSource = dataStreamSources.getInputStreamSource(streamDescriptor, PRESENT, BooleanInputStream.class); lengthStreamSource = dataStreamSources.getInputStreamSource(streamDescriptor, LENGTH, LongInputStream.class); dataStreamSource = dataStreamSources.getInputStreamSource(streamDescriptor, DATA, ByteArrayInputStream.class); readOffset = 0; presentStream = null; lengthStream = null; dataStream = null; rowGroupOpen = false; } @Override public long getRetainedSizeInBytes() { return INSTANCE_SIZE + sizeOf(offsets) + sizeOf(outputPositions) + sizeOf(data) + sizeOf(nulls) + sizeOf(lengthVector) + sizeOf(isNullVector); } private void prepareForNextRead(int positionCount, int[] positions) throws IOException { lengthIndex = 0; outputPositionCount = 0; int totalLength = 0; int maxLength = 0; int totalPositions = positions[positionCount - 1] + 1; int nullCount = 0; if (presentStream != null) { isNullVector = ensureCapacity(isNullVector, totalPositions); nullCount = presentStream.getUnsetBits(totalPositions, isNullVector); } if (lengthStream != null) { int nonNullCount = totalPositions - nullCount; lengthVector = ensureCapacity(lengthVector, nonNullCount); lengthStream.nextIntVector(nonNullCount, lengthVector, 0); //TODO calculate totalLength for only requested positions for (int i = 0; i < nonNullCount; i++) { totalLength += lengthVector[i]; maxLength = Math.max(maxLength, lengthVector[i]); } if (totalLength > ONE_GIGABYTE) { throw new PrestoException( GENERIC_INTERNAL_ERROR, format("Values in column \"%s\" are too large to process for Presto. %s column values are larger than 1GB [%s]", streamDescriptor.getFieldName(), positionCount, streamDescriptor.getOrcDataSourceId())); } } if (outputRequired) { if (presentStream != null && nullsAllowed) { nulls = ensureCapacity(nulls, positionCount); } data = ensureCapacity(data, totalLength); offsets = ensureCapacity(offsets, totalPositions + 1); } else { data = ensureCapacity(data, maxLength); } dataAsSlice = Slices.wrappedBuffer(data); } }
Fix slice reader check for presentStream
presto-orc/src/main/java/com/facebook/presto/orc/reader/SliceDirectSelectiveStreamReader.java
Fix slice reader check for presentStream
Java
apache-2.0
db79dac1792207149722902d7fb3026c72825fd9
0
allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jetbrains.jsonSchema; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.AtomicClearableLazyValue; import com.intellij.openapi.util.io.FileUtilRt; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.vfs.VfsUtilCore; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.ArrayUtil; import com.intellij.util.PairProcessor; import com.intellij.util.PatternUtil; import com.intellij.util.SmartList; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.xmlb.annotations.Tag; import com.intellij.util.xmlb.annotations.Transient; import com.jetbrains.jsonSchema.ide.JsonSchemaService; import com.jetbrains.jsonSchema.impl.JsonSchemaObject; import com.jetbrains.jsonSchema.impl.JsonSchemaVersion; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.File; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Objects; import java.util.regex.Pattern; /** * @author Irina.Chernushina on 4/19/2017. */ @Tag("SchemaInfo") public class UserDefinedJsonSchemaConfiguration { private final static Comparator<Item> ITEM_COMPARATOR = (o1, o2) -> { if (o1.isPattern() != o2.isPattern()) return o1.isPattern() ? -1 : 1; if (o1.isDirectory() != o2.isDirectory()) return o1.isDirectory() ? -1 : 1; return o1.path.compareToIgnoreCase(o2.path); }; public String name; public String relativePathToSchema; public JsonSchemaVersion schemaVersion = JsonSchemaVersion.SCHEMA_4; public boolean applicationDefined; public List<Item> patterns = new SmartList<>(); @Transient private final AtomicClearableLazyValue<List<PairProcessor<Project, VirtualFile>>> myCalculatedPatterns = new AtomicClearableLazyValue<List<PairProcessor<Project, VirtualFile>>>() { @NotNull @Override protected List<PairProcessor<Project, VirtualFile>> compute() { return recalculatePatterns(); } }; public UserDefinedJsonSchemaConfiguration() { } public UserDefinedJsonSchemaConfiguration(@NotNull String name, JsonSchemaVersion schemaVersion, @NotNull String relativePathToSchema, boolean applicationDefined, @Nullable List<Item> patterns) { this.name = name; this.relativePathToSchema = relativePathToSchema; this.schemaVersion = schemaVersion; this.applicationDefined = applicationDefined; setPatterns(patterns); } public String getName() { return name; } public void setName(@NotNull String name) { this.name = name; } public String getRelativePathToSchema() { return relativePathToSchema; } public JsonSchemaVersion getSchemaVersion() { return schemaVersion; } public void setSchemaVersion(JsonSchemaVersion schemaVersion) { this.schemaVersion = schemaVersion; } public void setRelativePathToSchema(String relativePathToSchema) { this.relativePathToSchema = relativePathToSchema; } public boolean isApplicationDefined() { return applicationDefined; } public void setApplicationDefined(boolean applicationDefined) { this.applicationDefined = applicationDefined; } public List<Item> getPatterns() { return patterns; } public void setPatterns(@Nullable List<Item> patterns) { this.patterns.clear(); if (patterns != null) this.patterns.addAll(patterns); Collections.sort(this.patterns, ITEM_COMPARATOR); myCalculatedPatterns.drop(); } public void refreshPatterns() { myCalculatedPatterns.drop(); } @NotNull public List<PairProcessor<Project, VirtualFile>> getCalculatedPatterns() { return myCalculatedPatterns.getValue(); } private List<PairProcessor<Project, VirtualFile>> recalculatePatterns() { final List<PairProcessor<Project, VirtualFile>> result = new SmartList<>(); for (final Item patternText : patterns) { switch (patternText.mappingKind) { case File: result.add((project, vfile) -> vfile.equals(getRelativeFile(project, patternText)) || vfile.getUrl().equals(patternText.getPath())); break; case Pattern: String pathText = patternText.getPath().replace(File.separatorChar, '/').replace('\\', '/'); final Pattern pattern = pathText.isEmpty() ? PatternUtil.NOTHING : pathText.indexOf('/') >= 0 ? PatternUtil.compileSafe(".*/" + PatternUtil.convertToRegex(pathText), PatternUtil.NOTHING) : PatternUtil.fromMask(pathText); result.add((project, file) -> JsonSchemaObject.matchPattern(pattern, pathText.indexOf('/') >= 0 ? file.getPath() : file.getName())); break; case Directory: result.add((project, vfile) -> { final VirtualFile relativeFile = getRelativeFile(project, patternText); if (relativeFile == null || !VfsUtilCore.isAncestor(relativeFile, vfile, true)) return false; JsonSchemaService service = JsonSchemaService.Impl.get(project); return service.isApplicableToFile(vfile); }); break; } } return result; } @Nullable private static VirtualFile getRelativeFile(@NotNull final Project project, @NotNull final Item pattern) { if (project.getBasePath() == null) { return null; } final String path = FileUtilRt.toSystemIndependentName(StringUtil.notNullize(pattern.path)); final List<String> parts = pathToPartsList(path); if (parts.isEmpty()) { return project.getBaseDir(); } else { return VfsUtil.findRelativeFile(project.getBaseDir(), ArrayUtil.toStringArray(parts)); } } @NotNull private static List<String> pathToPartsList(@NotNull String path) { return ContainerUtil.filter(StringUtil.split(path, "/"), s -> !".".equals(s)); } @NotNull private static String[] pathToParts(@NotNull String path) { return ArrayUtil.toStringArray(pathToPartsList(path)); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; UserDefinedJsonSchemaConfiguration info = (UserDefinedJsonSchemaConfiguration)o; if (applicationDefined != info.applicationDefined) return false; if (schemaVersion != info.schemaVersion) return false; if (!Objects.equals(name, info.name)) return false; if (!Objects.equals(relativePathToSchema, info.relativePathToSchema)) return false; return Objects.equals(patterns, info.patterns); } @Override public int hashCode() { int result = name != null ? name.hashCode() : 0; result = 31 * result + (relativePathToSchema != null ? relativePathToSchema.hashCode() : 0); result = 31 * result + (applicationDefined ? 1 : 0); result = 31 * result + (patterns != null ? patterns.hashCode() : 0); result = 31 * result + schemaVersion.hashCode(); return result; } public static class Item { public String path; public JsonMappingKind mappingKind = JsonMappingKind.File; public Item() { } public Item(String path, JsonMappingKind mappingKind) { this.path = neutralizePath(path); this.mappingKind = mappingKind; } public Item(String path, boolean isPattern, boolean isDirectory) { this.path = neutralizePath(path); this.mappingKind = isPattern ? JsonMappingKind.Pattern : isDirectory ? JsonMappingKind.Directory : JsonMappingKind.File; } @NotNull private static String normalizePath(String path) { if (preserveSlashes(path)) return path; return StringUtil.trimEnd(FileUtilRt.toSystemDependentName(path), File.separatorChar); } private static boolean preserveSlashes(String path) { // http/https URLs to schemas // mock URLs of fragments editor return StringUtil.startsWith(path, "http:") || StringUtil.startsWith(path, "https:") || StringUtil.startsWith(path, "mock:"); } @NotNull private static String neutralizePath(String path) { if (preserveSlashes(path)) return path; return StringUtil.trimEnd(FileUtilRt.toSystemIndependentName(path), '/'); } public String getPath() { return normalizePath(path); } public void setPath(String path) { this.path = neutralizePath(path); } public String getError() { switch (mappingKind) { case File: return !StringUtil.isEmpty(path) ? null : "Empty file path doesn't match anything"; case Pattern: return !StringUtil.isEmpty(path) ? null : "Empty pattern matches nothing"; case Directory: return null; } return "Unknown mapping kind"; } public boolean isPattern() { return mappingKind == JsonMappingKind.Pattern; } public void setPattern(boolean pattern) { mappingKind = pattern ? JsonMappingKind.Pattern : JsonMappingKind.File; } public boolean isDirectory() { return mappingKind == JsonMappingKind.Directory; } public void setDirectory(boolean directory) { mappingKind = directory ? JsonMappingKind.Directory : JsonMappingKind.File; } public String getPresentation() { if (mappingKind == JsonMappingKind.Directory && StringUtil.isEmpty(path)) { return mappingKind.getPrefix() + "[Project Directory]"; } return mappingKind.getPrefix() + getPath(); } public String[] getPathParts() { return pathToParts(path); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Item item = (Item)o; if (mappingKind != item.mappingKind) return false; return Objects.equals(path, item.path); } @Override public int hashCode() { int result = Objects.hashCode(path); result = 31 * result + Objects.hashCode(mappingKind); return result; } } }
json/src/com/jetbrains/jsonSchema/UserDefinedJsonSchemaConfiguration.java
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jetbrains.jsonSchema; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.AtomicClearableLazyValue; import com.intellij.openapi.util.io.FileUtilRt; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.vfs.VfsUtilCore; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.ArrayUtil; import com.intellij.util.PairProcessor; import com.intellij.util.PatternUtil; import com.intellij.util.SmartList; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.xmlb.annotations.Tag; import com.intellij.util.xmlb.annotations.Transient; import com.jetbrains.jsonSchema.ide.JsonSchemaService; import com.jetbrains.jsonSchema.impl.JsonSchemaObject; import com.jetbrains.jsonSchema.impl.JsonSchemaVersion; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.File; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Objects; import java.util.regex.Pattern; /** * @author Irina.Chernushina on 4/19/2017. */ @Tag("SchemaInfo") public class UserDefinedJsonSchemaConfiguration { private final static Comparator<Item> ITEM_COMPARATOR = (o1, o2) -> { if (o1.isPattern() != o2.isPattern()) return o1.isPattern() ? -1 : 1; if (o1.isDirectory() != o2.isDirectory()) return o1.isDirectory() ? -1 : 1; return o1.path.compareToIgnoreCase(o2.path); }; public String name; public String relativePathToSchema; public JsonSchemaVersion schemaVersion = JsonSchemaVersion.SCHEMA_4; public boolean applicationDefined; public List<Item> patterns = new SmartList<>(); @Transient private final AtomicClearableLazyValue<List<PairProcessor<Project, VirtualFile>>> myCalculatedPatterns = new AtomicClearableLazyValue<List<PairProcessor<Project, VirtualFile>>>() { @NotNull @Override protected List<PairProcessor<Project, VirtualFile>> compute() { return recalculatePatterns(); } }; public UserDefinedJsonSchemaConfiguration() { } public UserDefinedJsonSchemaConfiguration(@NotNull String name, JsonSchemaVersion schemaVersion, @NotNull String relativePathToSchema, boolean applicationDefined, @Nullable List<Item> patterns) { this.name = name; this.relativePathToSchema = relativePathToSchema; this.schemaVersion = schemaVersion; this.applicationDefined = applicationDefined; setPatterns(patterns); } public String getName() { return name; } public void setName(@NotNull String name) { this.name = name; } public String getRelativePathToSchema() { return relativePathToSchema; } public JsonSchemaVersion getSchemaVersion() { return schemaVersion; } public void setSchemaVersion(JsonSchemaVersion schemaVersion) { this.schemaVersion = schemaVersion; } public void setRelativePathToSchema(String relativePathToSchema) { this.relativePathToSchema = relativePathToSchema; } public boolean isApplicationDefined() { return applicationDefined; } public void setApplicationDefined(boolean applicationDefined) { this.applicationDefined = applicationDefined; } public List<Item> getPatterns() { return patterns; } public void setPatterns(@Nullable List<Item> patterns) { this.patterns.clear(); if (patterns != null) this.patterns.addAll(patterns); Collections.sort(this.patterns, ITEM_COMPARATOR); myCalculatedPatterns.drop(); } public void refreshPatterns() { myCalculatedPatterns.drop(); } @NotNull public List<PairProcessor<Project, VirtualFile>> getCalculatedPatterns() { return myCalculatedPatterns.getValue(); } private List<PairProcessor<Project, VirtualFile>> recalculatePatterns() { final List<PairProcessor<Project, VirtualFile>> result = new SmartList<>(); for (final Item patternText : patterns) { switch (patternText.mappingKind) { case File: result.add((project, vfile) -> vfile.equals(getRelativeFile(project, patternText)) || vfile.getUrl().equals(patternText.getPath())); break; case Pattern: String pathText = patternText.getPath().replace(File.separatorChar, '/').replace('\\', '/'); final Pattern pattern = pathText.isEmpty() ? PatternUtil.NOTHING : pathText.indexOf('/') >= 0 ? PatternUtil.compileSafe(".*/" + PatternUtil.convertToRegex(pathText), PatternUtil.NOTHING) : PatternUtil.fromMask(pathText); result.add((project, file) -> JsonSchemaObject.matchPattern(pattern, pathText.indexOf('/') >= 0 ? file.getPath() : file.getName())); break; case Directory: result.add((project, vfile) -> { final VirtualFile relativeFile = getRelativeFile(project, patternText); if (relativeFile == null || !VfsUtilCore.isAncestor(relativeFile, vfile, true)) return false; JsonSchemaService service = JsonSchemaService.Impl.get(project); return service.isApplicableToFile(vfile) && !service.isSchemaFile(vfile); }); break; } } return result; } @Nullable private static VirtualFile getRelativeFile(@NotNull final Project project, @NotNull final Item pattern) { if (project.getBasePath() == null) { return null; } final String path = FileUtilRt.toSystemIndependentName(StringUtil.notNullize(pattern.path)); final List<String> parts = pathToPartsList(path); if (parts.isEmpty()) { return project.getBaseDir(); } else { return VfsUtil.findRelativeFile(project.getBaseDir(), ArrayUtil.toStringArray(parts)); } } @NotNull private static List<String> pathToPartsList(@NotNull String path) { return ContainerUtil.filter(StringUtil.split(path, "/"), s -> !".".equals(s)); } @NotNull private static String[] pathToParts(@NotNull String path) { return ArrayUtil.toStringArray(pathToPartsList(path)); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; UserDefinedJsonSchemaConfiguration info = (UserDefinedJsonSchemaConfiguration)o; if (applicationDefined != info.applicationDefined) return false; if (schemaVersion != info.schemaVersion) return false; if (!Objects.equals(name, info.name)) return false; if (!Objects.equals(relativePathToSchema, info.relativePathToSchema)) return false; return Objects.equals(patterns, info.patterns); } @Override public int hashCode() { int result = name != null ? name.hashCode() : 0; result = 31 * result + (relativePathToSchema != null ? relativePathToSchema.hashCode() : 0); result = 31 * result + (applicationDefined ? 1 : 0); result = 31 * result + (patterns != null ? patterns.hashCode() : 0); result = 31 * result + schemaVersion.hashCode(); return result; } public static class Item { public String path; public JsonMappingKind mappingKind = JsonMappingKind.File; public Item() { } public Item(String path, JsonMappingKind mappingKind) { this.path = neutralizePath(path); this.mappingKind = mappingKind; } public Item(String path, boolean isPattern, boolean isDirectory) { this.path = neutralizePath(path); this.mappingKind = isPattern ? JsonMappingKind.Pattern : isDirectory ? JsonMappingKind.Directory : JsonMappingKind.File; } @NotNull private static String normalizePath(String path) { if (preserveSlashes(path)) return path; return StringUtil.trimEnd(FileUtilRt.toSystemDependentName(path), File.separatorChar); } private static boolean preserveSlashes(String path) { // http/https URLs to schemas // mock URLs of fragments editor return StringUtil.startsWith(path, "http:") || StringUtil.startsWith(path, "https:") || StringUtil.startsWith(path, "mock:"); } @NotNull private static String neutralizePath(String path) { if (preserveSlashes(path)) return path; return StringUtil.trimEnd(FileUtilRt.toSystemIndependentName(path), '/'); } public String getPath() { return normalizePath(path); } public void setPath(String path) { this.path = neutralizePath(path); } public String getError() { switch (mappingKind) { case File: return !StringUtil.isEmpty(path) ? null : "Empty file path doesn't match anything"; case Pattern: return !StringUtil.isEmpty(path) ? null : "Empty pattern matches nothing"; case Directory: return null; } return "Unknown mapping kind"; } public boolean isPattern() { return mappingKind == JsonMappingKind.Pattern; } public void setPattern(boolean pattern) { mappingKind = pattern ? JsonMappingKind.Pattern : JsonMappingKind.File; } public boolean isDirectory() { return mappingKind == JsonMappingKind.Directory; } public void setDirectory(boolean directory) { mappingKind = directory ? JsonMappingKind.Directory : JsonMappingKind.File; } public String getPresentation() { if (mappingKind == JsonMappingKind.Directory && StringUtil.isEmpty(path)) { return mappingKind.getPrefix() + "[Project Directory]"; } return mappingKind.getPrefix() + getPath(); } public String[] getPathParts() { return pathToParts(path); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Item item = (Item)o; if (mappingKind != item.mappingKind) return false; return Objects.equals(path, item.path); } @Override public int hashCode() { int result = Objects.hashCode(path); result = 31 * result + Objects.hashCode(mappingKind); return result; } } }
EA-128232 - NA: JsonSchemaUserDefinedProviderFactory$MyProvider.isAvailable after the preceding fix, there's no need to check for schema-schema here anymore
json/src/com/jetbrains/jsonSchema/UserDefinedJsonSchemaConfiguration.java
EA-128232 - NA: JsonSchemaUserDefinedProviderFactory$MyProvider.isAvailable
Java
apache-2.0
b2140097d6fe2e49071e97fae996596df5bd0a65
0
smartnews/presto,hgschmie/presto,erichwang/presto,11xor6/presto,dain/presto,hgschmie/presto,losipiuk/presto,11xor6/presto,Praveen2112/presto,dain/presto,electrum/presto,martint/presto,dain/presto,electrum/presto,treasure-data/presto,martint/presto,electrum/presto,ebyhr/presto,erichwang/presto,treasure-data/presto,11xor6/presto,Praveen2112/presto,martint/presto,hgschmie/presto,ebyhr/presto,smartnews/presto,hgschmie/presto,treasure-data/presto,smartnews/presto,smartnews/presto,smartnews/presto,Praveen2112/presto,losipiuk/presto,ebyhr/presto,dain/presto,ebyhr/presto,electrum/presto,11xor6/presto,martint/presto,dain/presto,11xor6/presto,losipiuk/presto,Praveen2112/presto,treasure-data/presto,hgschmie/presto,erichwang/presto,erichwang/presto,martint/presto,erichwang/presto,losipiuk/presto,ebyhr/presto,losipiuk/presto,electrum/presto,treasure-data/presto,Praveen2112/presto,treasure-data/presto
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.prestosql.plugin.kudu; import com.google.common.collect.ImmutableList; import io.airlift.log.Logger; import io.prestosql.plugin.kudu.properties.ColumnDesign; import io.prestosql.plugin.kudu.properties.HashPartitionDefinition; import io.prestosql.plugin.kudu.properties.KuduTableProperties; import io.prestosql.plugin.kudu.properties.PartitionDesign; import io.prestosql.plugin.kudu.properties.RangePartition; import io.prestosql.plugin.kudu.properties.RangePartitionDefinition; import io.prestosql.plugin.kudu.schema.SchemaEmulation; import io.prestosql.spi.PrestoException; import io.prestosql.spi.connector.ColumnHandle; import io.prestosql.spi.connector.ColumnMetadata; import io.prestosql.spi.connector.ConnectorTableMetadata; import io.prestosql.spi.connector.SchemaNotFoundException; import io.prestosql.spi.connector.SchemaTableName; import io.prestosql.spi.connector.TableNotFoundException; import io.prestosql.spi.predicate.DiscreteValues; import io.prestosql.spi.predicate.Domain; import io.prestosql.spi.predicate.EquatableValueSet; import io.prestosql.spi.predicate.Marker; import io.prestosql.spi.predicate.Range; import io.prestosql.spi.predicate.Ranges; import io.prestosql.spi.predicate.SortedRangeSet; import io.prestosql.spi.predicate.TupleDomain; import io.prestosql.spi.predicate.ValueSet; import io.prestosql.spi.type.DecimalType; import org.apache.kudu.ColumnSchema; import org.apache.kudu.ColumnTypeAttributes; import org.apache.kudu.Schema; import org.apache.kudu.Type; import org.apache.kudu.client.AlterTableOptions; import org.apache.kudu.client.CreateTableOptions; import org.apache.kudu.client.KuduClient; import org.apache.kudu.client.KuduException; import org.apache.kudu.client.KuduPredicate; import org.apache.kudu.client.KuduScanToken; import org.apache.kudu.client.KuduScanner; import org.apache.kudu.client.KuduSession; import org.apache.kudu.client.KuduTable; import org.apache.kudu.client.PartialRow; import java.io.IOException; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.stream.IntStream; import static com.google.common.base.Verify.verify; import static com.google.common.collect.ImmutableList.toImmutableList; import static io.prestosql.spi.StandardErrorCode.GENERIC_INTERNAL_ERROR; import static io.prestosql.spi.StandardErrorCode.QUERY_REJECTED; import static io.prestosql.spi.predicate.Marker.Bound.ABOVE; import static io.prestosql.spi.predicate.Marker.Bound.BELOW; import static java.util.stream.Collectors.toList; import static org.apache.kudu.client.KuduPredicate.ComparisonOp.GREATER; import static org.apache.kudu.client.KuduPredicate.ComparisonOp.GREATER_EQUAL; import static org.apache.kudu.client.KuduPredicate.ComparisonOp.LESS; import static org.apache.kudu.client.KuduPredicate.ComparisonOp.LESS_EQUAL; public class KuduClientSession { private static final Logger log = Logger.get(KuduClientSession.class); public static final String DEFAULT_SCHEMA = "default"; private final KuduClient client; private final SchemaEmulation schemaEmulation; public KuduClientSession(KuduClient client, SchemaEmulation schemaEmulation) { this.client = client; this.schemaEmulation = schemaEmulation; } public List<String> listSchemaNames() { return schemaEmulation.listSchemaNames(client); } private List<String> internalListTables(String prefix) { try { if (prefix.isEmpty()) { return client.getTablesList().getTablesList(); } return client.getTablesList(prefix).getTablesList(); } catch (KuduException e) { throw new PrestoException(GENERIC_INTERNAL_ERROR, e); } } public List<SchemaTableName> listTables(Optional<String> optSchemaName) { if (optSchemaName.isPresent()) { return listTablesSingleSchema(optSchemaName.get()); } List<SchemaTableName> all = new ArrayList<>(); for (String schemaName : listSchemaNames()) { List<SchemaTableName> single = listTablesSingleSchema(schemaName); all.addAll(single); } return all; } private List<SchemaTableName> listTablesSingleSchema(String schemaName) { final String prefix = schemaEmulation.getPrefixForTablesOfSchema(schemaName); List<String> tables = internalListTables(prefix); if (schemaName.equals(DEFAULT_SCHEMA)) { tables = schemaEmulation.filterTablesForDefaultSchema(tables); } return tables.stream() .map(schemaEmulation::fromRawName) .filter(Objects::nonNull) .collect(toImmutableList()); } public Schema getTableSchema(KuduTableHandle tableHandle) { KuduTable table = tableHandle.getTable(this); return table.getSchema(); } public Map<String, Object> getTableProperties(KuduTableHandle tableHandle) { KuduTable table = tableHandle.getTable(this); return KuduTableProperties.toMap(table); } public List<KuduSplit> buildKuduSplits(KuduTableHandle tableHandle) { KuduTable table = tableHandle.getTable(this); final int primaryKeyColumnCount = table.getSchema().getPrimaryKeyColumnCount(); KuduScanToken.KuduScanTokenBuilder builder = client.newScanTokenBuilder(table); TupleDomain<ColumnHandle> constraint = tableHandle.getConstraint(); if (constraint.isNone()) { return ImmutableList.of(); } addConstraintPredicates(table, builder, constraint); Optional<List<ColumnHandle>> desiredColumns = tableHandle.getDesiredColumns(); List<Integer> columnIndexes; if (tableHandle.isDeleteHandle()) { if (desiredColumns.isPresent()) { columnIndexes = IntStream .range(0, primaryKeyColumnCount) .boxed().collect(toList()); for (ColumnHandle column : desiredColumns.get()) { KuduColumnHandle k = (KuduColumnHandle) column; int index = k.getOrdinalPosition(); if (index >= primaryKeyColumnCount) { columnIndexes.add(index); } } columnIndexes = ImmutableList.copyOf(columnIndexes); } else { columnIndexes = IntStream .range(0, table.getSchema().getColumnCount()) .boxed().collect(toImmutableList()); } } else { if (desiredColumns.isPresent()) { columnIndexes = desiredColumns.get().stream() .map(handle -> ((KuduColumnHandle) handle).getOrdinalPosition()) .collect(toImmutableList()); } else { ImmutableList.Builder<Integer> columnIndexesBuilder = ImmutableList.builder(); Schema schema = table.getSchema(); for (int ordinal = 0; ordinal < schema.getColumnCount(); ordinal++) { ColumnSchema column = schema.getColumnByIndex(ordinal); // Skip hidden "row_uuid" column if (!column.isKey() || !column.getName().equals(KuduColumnHandle.ROW_ID)) { columnIndexesBuilder.add(ordinal); } } columnIndexes = columnIndexesBuilder.build(); } } builder.setProjectedColumnIndexes(columnIndexes); List<KuduScanToken> tokens = builder.build(); return tokens.stream() .map(token -> toKuduSplit(tableHandle, token, primaryKeyColumnCount)) .collect(toImmutableList()); } public KuduScanner createScanner(KuduSplit kuduSplit) { try { return KuduScanToken.deserializeIntoScanner(kuduSplit.getSerializedScanToken(), client); } catch (IOException e) { throw new RuntimeException(e); } } public KuduTable openTable(SchemaTableName schemaTableName) { String rawName = schemaEmulation.toRawName(schemaTableName); try { return client.openTable(rawName); } catch (KuduException e) { log.debug("Error on doOpenTable: " + e, e); if (!listSchemaNames().contains(schemaTableName.getSchemaName())) { throw new SchemaNotFoundException(schemaTableName.getSchemaName()); } throw new TableNotFoundException(schemaTableName); } } public KuduSession newSession() { return client.newSession(); } public void createSchema(String schemaName) { schemaEmulation.createSchema(client, schemaName); } public void dropSchema(String schemaName) { schemaEmulation.dropSchema(client, schemaName); } public void dropTable(SchemaTableName schemaTableName) { try { String rawName = schemaEmulation.toRawName(schemaTableName); client.deleteTable(rawName); } catch (KuduException e) { throw new PrestoException(GENERIC_INTERNAL_ERROR, e); } } public void renameTable(SchemaTableName schemaTableName, SchemaTableName newSchemaTableName) { try { String rawName = schemaEmulation.toRawName(schemaTableName); String newRawName = schemaEmulation.toRawName(newSchemaTableName); AlterTableOptions alterOptions = new AlterTableOptions(); alterOptions.renameTable(newRawName); client.alterTable(rawName, alterOptions); } catch (KuduException e) { throw new PrestoException(GENERIC_INTERNAL_ERROR, e); } } public KuduTable createTable(ConnectorTableMetadata tableMetadata, boolean ignoreExisting) { try { String rawName = schemaEmulation.toRawName(tableMetadata.getTable()); if (ignoreExisting) { if (client.tableExists(rawName)) { return null; } } if (!schemaEmulation.existsSchema(client, tableMetadata.getTable().getSchemaName())) { throw new SchemaNotFoundException(tableMetadata.getTable().getSchemaName()); } List<ColumnMetadata> columns = tableMetadata.getColumns(); Map<String, Object> properties = tableMetadata.getProperties(); Schema schema = buildSchema(columns, properties); CreateTableOptions options = buildCreateTableOptions(schema, properties); return client.createTable(rawName, schema, options); } catch (KuduException e) { throw new PrestoException(GENERIC_INTERNAL_ERROR, e); } } public void addColumn(SchemaTableName schemaTableName, ColumnMetadata column) { try { String rawName = schemaEmulation.toRawName(schemaTableName); AlterTableOptions alterOptions = new AlterTableOptions(); Type type = TypeHelper.toKuduClientType(column.getType()); alterOptions.addNullableColumn(column.getName(), type); client.alterTable(rawName, alterOptions); } catch (KuduException e) { throw new PrestoException(GENERIC_INTERNAL_ERROR, e); } } public void dropColumn(SchemaTableName schemaTableName, String name) { try { String rawName = schemaEmulation.toRawName(schemaTableName); AlterTableOptions alterOptions = new AlterTableOptions(); alterOptions.dropColumn(name); client.alterTable(rawName, alterOptions); } catch (KuduException e) { throw new PrestoException(GENERIC_INTERNAL_ERROR, e); } } public void renameColumn(SchemaTableName schemaTableName, String oldName, String newName) { try { String rawName = schemaEmulation.toRawName(schemaTableName); AlterTableOptions alterOptions = new AlterTableOptions(); alterOptions.renameColumn(oldName, newName); client.alterTable(rawName, alterOptions); } catch (KuduException e) { throw new PrestoException(GENERIC_INTERNAL_ERROR, e); } } public void addRangePartition(SchemaTableName schemaTableName, RangePartition rangePartition) { changeRangePartition(schemaTableName, rangePartition, RangePartitionChange.ADD); } public void dropRangePartition(SchemaTableName schemaTableName, RangePartition rangePartition) { changeRangePartition(schemaTableName, rangePartition, RangePartitionChange.DROP); } private void changeRangePartition(SchemaTableName schemaTableName, RangePartition rangePartition, RangePartitionChange change) { try { String rawName = schemaEmulation.toRawName(schemaTableName); KuduTable table = client.openTable(rawName); Schema schema = table.getSchema(); PartitionDesign design = KuduTableProperties.getPartitionDesign(table); RangePartitionDefinition definition = design.getRange(); if (definition == null) { throw new PrestoException(QUERY_REJECTED, "Table " + schemaTableName + " has no range partition"); } PartialRow lowerBound = KuduTableProperties.toRangeBoundToPartialRow(schema, definition, rangePartition.getLower()); PartialRow upperBound = KuduTableProperties.toRangeBoundToPartialRow(schema, definition, rangePartition.getUpper()); AlterTableOptions alterOptions = new AlterTableOptions(); switch (change) { case ADD: alterOptions.addRangePartition(lowerBound, upperBound); break; case DROP: alterOptions.dropRangePartition(lowerBound, upperBound); break; } client.alterTable(rawName, alterOptions); } catch (KuduException e) { throw new PrestoException(GENERIC_INTERNAL_ERROR, e); } } private Schema buildSchema(List<ColumnMetadata> columns, Map<String, Object> tableProperties) { List<ColumnSchema> kuduColumns = columns.stream() .map(this::toColumnSchema) .collect(ImmutableList.toImmutableList()); return new Schema(kuduColumns); } private ColumnSchema toColumnSchema(ColumnMetadata columnMetadata) { String name = columnMetadata.getName(); ColumnDesign design = KuduTableProperties.getColumnDesign(columnMetadata.getProperties()); Type ktype = TypeHelper.toKuduClientType(columnMetadata.getType()); ColumnSchema.ColumnSchemaBuilder builder = new ColumnSchema.ColumnSchemaBuilder(name, ktype); builder.key(design.isPrimaryKey()).nullable(design.isNullable()); setEncoding(name, builder, design); setCompression(name, builder, design); setTypeAttributes(columnMetadata, builder); return builder.build(); } private void setTypeAttributes(ColumnMetadata columnMetadata, ColumnSchema.ColumnSchemaBuilder builder) { if (columnMetadata.getType() instanceof DecimalType) { DecimalType type = (DecimalType) columnMetadata.getType(); ColumnTypeAttributes attributes = new ColumnTypeAttributes.ColumnTypeAttributesBuilder() .precision(type.getPrecision()) .scale(type.getScale()).build(); builder.typeAttributes(attributes); } } private void setCompression(String name, ColumnSchema.ColumnSchemaBuilder builder, ColumnDesign design) { if (design.getCompression() != null) { try { ColumnSchema.CompressionAlgorithm algorithm = KuduTableProperties.lookupCompression(design.getCompression()); builder.compressionAlgorithm(algorithm); } catch (IllegalArgumentException e) { throw new PrestoException(GENERIC_INTERNAL_ERROR, "Unknown compression algorithm " + design.getCompression() + " for column " + name); } } } private void setEncoding(String name, ColumnSchema.ColumnSchemaBuilder builder, ColumnDesign design) { if (design.getEncoding() != null) { try { ColumnSchema.Encoding encoding = KuduTableProperties.lookupEncoding(design.getEncoding()); builder.encoding(encoding); } catch (IllegalArgumentException e) { throw new PrestoException(GENERIC_INTERNAL_ERROR, "Unknown encoding " + design.getEncoding() + " for column " + name); } } } private CreateTableOptions buildCreateTableOptions(Schema schema, Map<String, Object> properties) { CreateTableOptions options = new CreateTableOptions(); RangePartitionDefinition rangePartitionDefinition = null; PartitionDesign partitionDesign = KuduTableProperties.getPartitionDesign(properties); if (partitionDesign.getHash() != null) { for (HashPartitionDefinition partition : partitionDesign.getHash()) { options.addHashPartitions(partition.getColumns(), partition.getBuckets()); } } if (partitionDesign.getRange() != null) { rangePartitionDefinition = partitionDesign.getRange(); options.setRangePartitionColumns(rangePartitionDefinition.getColumns()); } List<RangePartition> rangePartitions = KuduTableProperties.getRangePartitions(properties); if (rangePartitionDefinition != null && !rangePartitions.isEmpty()) { for (RangePartition rangePartition : rangePartitions) { PartialRow lower = KuduTableProperties.toRangeBoundToPartialRow(schema, rangePartitionDefinition, rangePartition.getLower()); PartialRow upper = KuduTableProperties.toRangeBoundToPartialRow(schema, rangePartitionDefinition, rangePartition.getUpper()); options.addRangePartition(lower, upper); } } Optional<Integer> numReplicas = KuduTableProperties.getNumReplicas(properties); numReplicas.ifPresent(options::setNumReplicas); return options; } /** * translates TupleDomain to KuduPredicates. */ private void addConstraintPredicates(KuduTable table, KuduScanToken.KuduScanTokenBuilder builder, TupleDomain<ColumnHandle> constraintSummary) { verify(!constraintSummary.isNone(), "constraintSummary is none"); if (constraintSummary.isAll()) { return; } Schema schema = table.getSchema(); for (TupleDomain.ColumnDomain<ColumnHandle> columnDomain : constraintSummary.getColumnDomains().get()) { int position = ((KuduColumnHandle) columnDomain.getColumn()).getOrdinalPosition(); ColumnSchema columnSchema = schema.getColumnByIndex(position); Domain domain = columnDomain.getDomain(); verify(!domain.isNone(), "Domain is none"); if (domain.isAll()) { // no restriction } else if (domain.isOnlyNull()) { builder.addPredicate(KuduPredicate.newIsNullPredicate(columnSchema)); } else if (domain.getValues().isAll() && domain.isNullAllowed()) { builder.addPredicate(KuduPredicate.newIsNotNullPredicate(columnSchema)); } else if (domain.isSingleValue()) { KuduPredicate predicate = createEqualsPredicate(columnSchema, domain.getSingleValue()); builder.addPredicate(predicate); } else { ValueSet valueSet = domain.getValues(); if (valueSet instanceof EquatableValueSet) { DiscreteValues discreteValues = valueSet.getDiscreteValues(); KuduPredicate predicate = createInListPredicate(columnSchema, discreteValues); builder.addPredicate(predicate); } else if (valueSet instanceof SortedRangeSet) { Ranges ranges = ((SortedRangeSet) valueSet).getRanges(); List<Range> rangeList = ranges.getOrderedRanges(); if (rangeList.stream().allMatch(Range::isSingleValue)) { io.prestosql.spi.type.Type type = TypeHelper.fromKuduColumn(columnSchema); List<Object> javaValues = rangeList.stream() .map(range -> TypeHelper.getJavaValue(type, range.getSingleValue())) .collect(toImmutableList()); KuduPredicate predicate = KuduPredicate.newInListPredicate(columnSchema, javaValues); builder.addPredicate(predicate); } else { Range span = ranges.getSpan(); Marker low = span.getLow(); if (!low.isLowerUnbounded()) { KuduPredicate.ComparisonOp op = (low.getBound() == ABOVE) ? GREATER : GREATER_EQUAL; KuduPredicate predicate = createComparisonPredicate(columnSchema, op, low.getValue()); builder.addPredicate(predicate); } Marker high = span.getHigh(); if (!high.isUpperUnbounded()) { KuduPredicate.ComparisonOp op = (high.getBound() == BELOW) ? LESS : LESS_EQUAL; KuduPredicate predicate = createComparisonPredicate(columnSchema, op, high.getValue()); builder.addPredicate(predicate); } } } else { throw new IllegalStateException("Unexpected domain: " + domain); } } } } private KuduPredicate createInListPredicate(ColumnSchema columnSchema, DiscreteValues discreteValues) { io.prestosql.spi.type.Type type = TypeHelper.fromKuduColumn(columnSchema); List<Object> javaValues = discreteValues.getValues().stream().map(value -> TypeHelper.getJavaValue(type, value)).collect(toImmutableList()); return KuduPredicate.newInListPredicate(columnSchema, javaValues); } private KuduPredicate createEqualsPredicate(ColumnSchema columnSchema, Object value) { return createComparisonPredicate(columnSchema, KuduPredicate.ComparisonOp.EQUAL, value); } private KuduPredicate createComparisonPredicate(ColumnSchema columnSchema, KuduPredicate.ComparisonOp op, Object value) { io.prestosql.spi.type.Type type = TypeHelper.fromKuduColumn(columnSchema); Object javaValue = TypeHelper.getJavaValue(type, value); if (javaValue instanceof Long) { return KuduPredicate.newComparisonPredicate(columnSchema, op, (Long) javaValue); } if (javaValue instanceof BigDecimal) { return KuduPredicate.newComparisonPredicate(columnSchema, op, (BigDecimal) javaValue); } if (javaValue instanceof Integer) { return KuduPredicate.newComparisonPredicate(columnSchema, op, (Integer) javaValue); } if (javaValue instanceof Short) { return KuduPredicate.newComparisonPredicate(columnSchema, op, (Short) javaValue); } if (javaValue instanceof Byte) { return KuduPredicate.newComparisonPredicate(columnSchema, op, (Byte) javaValue); } if (javaValue instanceof String) { return KuduPredicate.newComparisonPredicate(columnSchema, op, (String) javaValue); } if (javaValue instanceof Double) { return KuduPredicate.newComparisonPredicate(columnSchema, op, (Double) javaValue); } if (javaValue instanceof Float) { return KuduPredicate.newComparisonPredicate(columnSchema, op, (Float) javaValue); } if (javaValue instanceof Boolean) { return KuduPredicate.newComparisonPredicate(columnSchema, op, (Boolean) javaValue); } if (javaValue instanceof byte[]) { return KuduPredicate.newComparisonPredicate(columnSchema, op, (byte[]) javaValue); } if (javaValue == null) { throw new IllegalStateException("Unexpected null java value for column " + columnSchema.getName()); } throw new IllegalStateException("Unexpected java value for column " + columnSchema.getName() + ": " + javaValue + "(" + javaValue.getClass() + ")"); } private KuduSplit toKuduSplit(KuduTableHandle tableHandle, KuduScanToken token, int primaryKeyColumnCount) { try { byte[] serializedScanToken = token.serialize(); return new KuduSplit(tableHandle, primaryKeyColumnCount, serializedScanToken); } catch (IOException e) { throw new PrestoException(GENERIC_INTERNAL_ERROR, e); } } }
presto-kudu/src/main/java/io/prestosql/plugin/kudu/KuduClientSession.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.prestosql.plugin.kudu; import com.google.common.collect.ImmutableList; import io.airlift.log.Logger; import io.prestosql.plugin.kudu.properties.ColumnDesign; import io.prestosql.plugin.kudu.properties.HashPartitionDefinition; import io.prestosql.plugin.kudu.properties.KuduTableProperties; import io.prestosql.plugin.kudu.properties.PartitionDesign; import io.prestosql.plugin.kudu.properties.RangePartition; import io.prestosql.plugin.kudu.properties.RangePartitionDefinition; import io.prestosql.plugin.kudu.schema.SchemaEmulation; import io.prestosql.spi.PrestoException; import io.prestosql.spi.connector.ColumnHandle; import io.prestosql.spi.connector.ColumnMetadata; import io.prestosql.spi.connector.ConnectorTableMetadata; import io.prestosql.spi.connector.SchemaNotFoundException; import io.prestosql.spi.connector.SchemaTableName; import io.prestosql.spi.connector.TableNotFoundException; import io.prestosql.spi.predicate.DiscreteValues; import io.prestosql.spi.predicate.Domain; import io.prestosql.spi.predicate.EquatableValueSet; import io.prestosql.spi.predicate.Marker; import io.prestosql.spi.predicate.Range; import io.prestosql.spi.predicate.Ranges; import io.prestosql.spi.predicate.SortedRangeSet; import io.prestosql.spi.predicate.TupleDomain; import io.prestosql.spi.predicate.ValueSet; import io.prestosql.spi.type.DecimalType; import org.apache.kudu.ColumnSchema; import org.apache.kudu.ColumnTypeAttributes; import org.apache.kudu.Schema; import org.apache.kudu.Type; import org.apache.kudu.client.AlterTableOptions; import org.apache.kudu.client.CreateTableOptions; import org.apache.kudu.client.KuduClient; import org.apache.kudu.client.KuduException; import org.apache.kudu.client.KuduPredicate; import org.apache.kudu.client.KuduScanToken; import org.apache.kudu.client.KuduScanner; import org.apache.kudu.client.KuduSession; import org.apache.kudu.client.KuduTable; import org.apache.kudu.client.PartialRow; import java.io.IOException; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.stream.IntStream; import static com.google.common.base.Verify.verify; import static com.google.common.collect.ImmutableList.toImmutableList; import static io.prestosql.spi.StandardErrorCode.GENERIC_INTERNAL_ERROR; import static io.prestosql.spi.StandardErrorCode.QUERY_REJECTED; import static io.prestosql.spi.predicate.Marker.Bound.ABOVE; import static io.prestosql.spi.predicate.Marker.Bound.BELOW; import static java.util.stream.Collectors.toList; import static org.apache.kudu.client.KuduPredicate.ComparisonOp.GREATER; import static org.apache.kudu.client.KuduPredicate.ComparisonOp.GREATER_EQUAL; import static org.apache.kudu.client.KuduPredicate.ComparisonOp.LESS; import static org.apache.kudu.client.KuduPredicate.ComparisonOp.LESS_EQUAL; public class KuduClientSession { private static final Logger log = Logger.get(KuduClientSession.class); public static final String DEFAULT_SCHEMA = "default"; private final KuduClient client; private final SchemaEmulation schemaEmulation; public KuduClientSession(KuduClient client, SchemaEmulation schemaEmulation) { this.client = client; this.schemaEmulation = schemaEmulation; } public List<String> listSchemaNames() { return schemaEmulation.listSchemaNames(client); } private List<String> internalListTables(String prefix) { try { if (prefix.isEmpty()) { return client.getTablesList().getTablesList(); } return client.getTablesList(prefix).getTablesList(); } catch (KuduException e) { throw new PrestoException(GENERIC_INTERNAL_ERROR, e); } } public List<SchemaTableName> listTables(Optional<String> optSchemaName) { if (optSchemaName.isPresent()) { return listTablesSingleSchema(optSchemaName.get()); } List<SchemaTableName> all = new ArrayList<>(); for (String schemaName : listSchemaNames()) { List<SchemaTableName> single = listTablesSingleSchema(schemaName); all.addAll(single); } return all; } private List<SchemaTableName> listTablesSingleSchema(String schemaName) { final String prefix = schemaEmulation.getPrefixForTablesOfSchema(schemaName); List<String> tables = internalListTables(prefix); if (schemaName.equals(DEFAULT_SCHEMA)) { tables = schemaEmulation.filterTablesForDefaultSchema(tables); } return tables.stream() .map(schemaEmulation::fromRawName) .filter(Objects::nonNull) .collect(toImmutableList()); } public Schema getTableSchema(KuduTableHandle tableHandle) { KuduTable table = tableHandle.getTable(this); return table.getSchema(); } public Map<String, Object> getTableProperties(KuduTableHandle tableHandle) { KuduTable table = tableHandle.getTable(this); return KuduTableProperties.toMap(table); } public List<KuduSplit> buildKuduSplits(KuduTableHandle tableHandle) { KuduTable table = tableHandle.getTable(this); final int primaryKeyColumnCount = table.getSchema().getPrimaryKeyColumnCount(); KuduScanToken.KuduScanTokenBuilder builder = client.newScanTokenBuilder(table); TupleDomain<ColumnHandle> constraint = tableHandle.getConstraint(); if (!addConstraintPredicates(table, builder, constraint)) { return ImmutableList.of(); } Optional<List<ColumnHandle>> desiredColumns = tableHandle.getDesiredColumns(); List<Integer> columnIndexes; if (tableHandle.isDeleteHandle()) { if (desiredColumns.isPresent()) { columnIndexes = IntStream .range(0, primaryKeyColumnCount) .boxed().collect(toList()); for (ColumnHandle column : desiredColumns.get()) { KuduColumnHandle k = (KuduColumnHandle) column; int index = k.getOrdinalPosition(); if (index >= primaryKeyColumnCount) { columnIndexes.add(index); } } columnIndexes = ImmutableList.copyOf(columnIndexes); } else { columnIndexes = IntStream .range(0, table.getSchema().getColumnCount()) .boxed().collect(toImmutableList()); } } else { if (desiredColumns.isPresent()) { columnIndexes = desiredColumns.get().stream() .map(handle -> ((KuduColumnHandle) handle).getOrdinalPosition()) .collect(toImmutableList()); } else { ImmutableList.Builder<Integer> columnIndexesBuilder = ImmutableList.builder(); Schema schema = table.getSchema(); for (int ordinal = 0; ordinal < schema.getColumnCount(); ordinal++) { ColumnSchema column = schema.getColumnByIndex(ordinal); // Skip hidden "row_uuid" column if (!column.isKey() || !column.getName().equals(KuduColumnHandle.ROW_ID)) { columnIndexesBuilder.add(ordinal); } } columnIndexes = columnIndexesBuilder.build(); } } builder.setProjectedColumnIndexes(columnIndexes); List<KuduScanToken> tokens = builder.build(); return tokens.stream() .map(token -> toKuduSplit(tableHandle, token, primaryKeyColumnCount)) .collect(toImmutableList()); } public KuduScanner createScanner(KuduSplit kuduSplit) { try { return KuduScanToken.deserializeIntoScanner(kuduSplit.getSerializedScanToken(), client); } catch (IOException e) { throw new RuntimeException(e); } } public KuduTable openTable(SchemaTableName schemaTableName) { String rawName = schemaEmulation.toRawName(schemaTableName); try { return client.openTable(rawName); } catch (KuduException e) { log.debug("Error on doOpenTable: " + e, e); if (!listSchemaNames().contains(schemaTableName.getSchemaName())) { throw new SchemaNotFoundException(schemaTableName.getSchemaName()); } throw new TableNotFoundException(schemaTableName); } } public KuduSession newSession() { return client.newSession(); } public void createSchema(String schemaName) { schemaEmulation.createSchema(client, schemaName); } public void dropSchema(String schemaName) { schemaEmulation.dropSchema(client, schemaName); } public void dropTable(SchemaTableName schemaTableName) { try { String rawName = schemaEmulation.toRawName(schemaTableName); client.deleteTable(rawName); } catch (KuduException e) { throw new PrestoException(GENERIC_INTERNAL_ERROR, e); } } public void renameTable(SchemaTableName schemaTableName, SchemaTableName newSchemaTableName) { try { String rawName = schemaEmulation.toRawName(schemaTableName); String newRawName = schemaEmulation.toRawName(newSchemaTableName); AlterTableOptions alterOptions = new AlterTableOptions(); alterOptions.renameTable(newRawName); client.alterTable(rawName, alterOptions); } catch (KuduException e) { throw new PrestoException(GENERIC_INTERNAL_ERROR, e); } } public KuduTable createTable(ConnectorTableMetadata tableMetadata, boolean ignoreExisting) { try { String rawName = schemaEmulation.toRawName(tableMetadata.getTable()); if (ignoreExisting) { if (client.tableExists(rawName)) { return null; } } if (!schemaEmulation.existsSchema(client, tableMetadata.getTable().getSchemaName())) { throw new SchemaNotFoundException(tableMetadata.getTable().getSchemaName()); } List<ColumnMetadata> columns = tableMetadata.getColumns(); Map<String, Object> properties = tableMetadata.getProperties(); Schema schema = buildSchema(columns, properties); CreateTableOptions options = buildCreateTableOptions(schema, properties); return client.createTable(rawName, schema, options); } catch (KuduException e) { throw new PrestoException(GENERIC_INTERNAL_ERROR, e); } } public void addColumn(SchemaTableName schemaTableName, ColumnMetadata column) { try { String rawName = schemaEmulation.toRawName(schemaTableName); AlterTableOptions alterOptions = new AlterTableOptions(); Type type = TypeHelper.toKuduClientType(column.getType()); alterOptions.addNullableColumn(column.getName(), type); client.alterTable(rawName, alterOptions); } catch (KuduException e) { throw new PrestoException(GENERIC_INTERNAL_ERROR, e); } } public void dropColumn(SchemaTableName schemaTableName, String name) { try { String rawName = schemaEmulation.toRawName(schemaTableName); AlterTableOptions alterOptions = new AlterTableOptions(); alterOptions.dropColumn(name); client.alterTable(rawName, alterOptions); } catch (KuduException e) { throw new PrestoException(GENERIC_INTERNAL_ERROR, e); } } public void renameColumn(SchemaTableName schemaTableName, String oldName, String newName) { try { String rawName = schemaEmulation.toRawName(schemaTableName); AlterTableOptions alterOptions = new AlterTableOptions(); alterOptions.renameColumn(oldName, newName); client.alterTable(rawName, alterOptions); } catch (KuduException e) { throw new PrestoException(GENERIC_INTERNAL_ERROR, e); } } public void addRangePartition(SchemaTableName schemaTableName, RangePartition rangePartition) { changeRangePartition(schemaTableName, rangePartition, RangePartitionChange.ADD); } public void dropRangePartition(SchemaTableName schemaTableName, RangePartition rangePartition) { changeRangePartition(schemaTableName, rangePartition, RangePartitionChange.DROP); } private void changeRangePartition(SchemaTableName schemaTableName, RangePartition rangePartition, RangePartitionChange change) { try { String rawName = schemaEmulation.toRawName(schemaTableName); KuduTable table = client.openTable(rawName); Schema schema = table.getSchema(); PartitionDesign design = KuduTableProperties.getPartitionDesign(table); RangePartitionDefinition definition = design.getRange(); if (definition == null) { throw new PrestoException(QUERY_REJECTED, "Table " + schemaTableName + " has no range partition"); } PartialRow lowerBound = KuduTableProperties.toRangeBoundToPartialRow(schema, definition, rangePartition.getLower()); PartialRow upperBound = KuduTableProperties.toRangeBoundToPartialRow(schema, definition, rangePartition.getUpper()); AlterTableOptions alterOptions = new AlterTableOptions(); switch (change) { case ADD: alterOptions.addRangePartition(lowerBound, upperBound); break; case DROP: alterOptions.dropRangePartition(lowerBound, upperBound); break; } client.alterTable(rawName, alterOptions); } catch (KuduException e) { throw new PrestoException(GENERIC_INTERNAL_ERROR, e); } } private Schema buildSchema(List<ColumnMetadata> columns, Map<String, Object> tableProperties) { List<ColumnSchema> kuduColumns = columns.stream() .map(this::toColumnSchema) .collect(ImmutableList.toImmutableList()); return new Schema(kuduColumns); } private ColumnSchema toColumnSchema(ColumnMetadata columnMetadata) { String name = columnMetadata.getName(); ColumnDesign design = KuduTableProperties.getColumnDesign(columnMetadata.getProperties()); Type ktype = TypeHelper.toKuduClientType(columnMetadata.getType()); ColumnSchema.ColumnSchemaBuilder builder = new ColumnSchema.ColumnSchemaBuilder(name, ktype); builder.key(design.isPrimaryKey()).nullable(design.isNullable()); setEncoding(name, builder, design); setCompression(name, builder, design); setTypeAttributes(columnMetadata, builder); return builder.build(); } private void setTypeAttributes(ColumnMetadata columnMetadata, ColumnSchema.ColumnSchemaBuilder builder) { if (columnMetadata.getType() instanceof DecimalType) { DecimalType type = (DecimalType) columnMetadata.getType(); ColumnTypeAttributes attributes = new ColumnTypeAttributes.ColumnTypeAttributesBuilder() .precision(type.getPrecision()) .scale(type.getScale()).build(); builder.typeAttributes(attributes); } } private void setCompression(String name, ColumnSchema.ColumnSchemaBuilder builder, ColumnDesign design) { if (design.getCompression() != null) { try { ColumnSchema.CompressionAlgorithm algorithm = KuduTableProperties.lookupCompression(design.getCompression()); builder.compressionAlgorithm(algorithm); } catch (IllegalArgumentException e) { throw new PrestoException(GENERIC_INTERNAL_ERROR, "Unknown compression algorithm " + design.getCompression() + " for column " + name); } } } private void setEncoding(String name, ColumnSchema.ColumnSchemaBuilder builder, ColumnDesign design) { if (design.getEncoding() != null) { try { ColumnSchema.Encoding encoding = KuduTableProperties.lookupEncoding(design.getEncoding()); builder.encoding(encoding); } catch (IllegalArgumentException e) { throw new PrestoException(GENERIC_INTERNAL_ERROR, "Unknown encoding " + design.getEncoding() + " for column " + name); } } } private CreateTableOptions buildCreateTableOptions(Schema schema, Map<String, Object> properties) { CreateTableOptions options = new CreateTableOptions(); RangePartitionDefinition rangePartitionDefinition = null; PartitionDesign partitionDesign = KuduTableProperties.getPartitionDesign(properties); if (partitionDesign.getHash() != null) { for (HashPartitionDefinition partition : partitionDesign.getHash()) { options.addHashPartitions(partition.getColumns(), partition.getBuckets()); } } if (partitionDesign.getRange() != null) { rangePartitionDefinition = partitionDesign.getRange(); options.setRangePartitionColumns(rangePartitionDefinition.getColumns()); } List<RangePartition> rangePartitions = KuduTableProperties.getRangePartitions(properties); if (rangePartitionDefinition != null && !rangePartitions.isEmpty()) { for (RangePartition rangePartition : rangePartitions) { PartialRow lower = KuduTableProperties.toRangeBoundToPartialRow(schema, rangePartitionDefinition, rangePartition.getLower()); PartialRow upper = KuduTableProperties.toRangeBoundToPartialRow(schema, rangePartitionDefinition, rangePartition.getUpper()); options.addRangePartition(lower, upper); } } Optional<Integer> numReplicas = KuduTableProperties.getNumReplicas(properties); numReplicas.ifPresent(options::setNumReplicas); return options; } /** * translates TupleDomain to KuduPredicates. * * @return false if TupleDomain or one of its domains is none */ private boolean addConstraintPredicates(KuduTable table, KuduScanToken.KuduScanTokenBuilder builder, TupleDomain<ColumnHandle> constraintSummary) { if (constraintSummary.isNone()) { return false; } if (!constraintSummary.isAll()) { Schema schema = table.getSchema(); for (TupleDomain.ColumnDomain<ColumnHandle> columnDomain : constraintSummary.getColumnDomains().get()) { int position = ((KuduColumnHandle) columnDomain.getColumn()).getOrdinalPosition(); ColumnSchema columnSchema = schema.getColumnByIndex(position); Domain domain = columnDomain.getDomain(); verify(!domain.isNone(), "Domain is none"); if (domain.isAll()) { // no restriction } else if (domain.isOnlyNull()) { builder.addPredicate(KuduPredicate.newIsNullPredicate(columnSchema)); } else if (domain.getValues().isAll() && domain.isNullAllowed()) { builder.addPredicate(KuduPredicate.newIsNotNullPredicate(columnSchema)); } else if (domain.isSingleValue()) { KuduPredicate predicate = createEqualsPredicate(columnSchema, domain.getSingleValue()); builder.addPredicate(predicate); } else { ValueSet valueSet = domain.getValues(); if (valueSet instanceof EquatableValueSet) { DiscreteValues discreteValues = valueSet.getDiscreteValues(); KuduPredicate predicate = createInListPredicate(columnSchema, discreteValues); builder.addPredicate(predicate); } else if (valueSet instanceof SortedRangeSet) { Ranges ranges = ((SortedRangeSet) valueSet).getRanges(); List<Range> rangeList = ranges.getOrderedRanges(); if (rangeList.stream().allMatch(Range::isSingleValue)) { io.prestosql.spi.type.Type type = TypeHelper.fromKuduColumn(columnSchema); List<Object> javaValues = rangeList.stream() .map(range -> TypeHelper.getJavaValue(type, range.getSingleValue())) .collect(toImmutableList()); KuduPredicate predicate = KuduPredicate.newInListPredicate(columnSchema, javaValues); builder.addPredicate(predicate); } else { Range span = ranges.getSpan(); Marker low = span.getLow(); if (!low.isLowerUnbounded()) { KuduPredicate.ComparisonOp op = (low.getBound() == ABOVE) ? GREATER : GREATER_EQUAL; KuduPredicate predicate = createComparisonPredicate(columnSchema, op, low.getValue()); builder.addPredicate(predicate); } Marker high = span.getHigh(); if (!high.isUpperUnbounded()) { KuduPredicate.ComparisonOp op = (high.getBound() == BELOW) ? LESS : LESS_EQUAL; KuduPredicate predicate = createComparisonPredicate(columnSchema, op, high.getValue()); builder.addPredicate(predicate); } } } else { throw new IllegalStateException("Unexpected domain: " + domain); } } } } return true; } private KuduPredicate createInListPredicate(ColumnSchema columnSchema, DiscreteValues discreteValues) { io.prestosql.spi.type.Type type = TypeHelper.fromKuduColumn(columnSchema); List<Object> javaValues = discreteValues.getValues().stream().map(value -> TypeHelper.getJavaValue(type, value)).collect(toImmutableList()); return KuduPredicate.newInListPredicate(columnSchema, javaValues); } private KuduPredicate createEqualsPredicate(ColumnSchema columnSchema, Object value) { return createComparisonPredicate(columnSchema, KuduPredicate.ComparisonOp.EQUAL, value); } private KuduPredicate createComparisonPredicate(ColumnSchema columnSchema, KuduPredicate.ComparisonOp op, Object value) { io.prestosql.spi.type.Type type = TypeHelper.fromKuduColumn(columnSchema); Object javaValue = TypeHelper.getJavaValue(type, value); if (javaValue instanceof Long) { return KuduPredicate.newComparisonPredicate(columnSchema, op, (Long) javaValue); } if (javaValue instanceof BigDecimal) { return KuduPredicate.newComparisonPredicate(columnSchema, op, (BigDecimal) javaValue); } if (javaValue instanceof Integer) { return KuduPredicate.newComparisonPredicate(columnSchema, op, (Integer) javaValue); } if (javaValue instanceof Short) { return KuduPredicate.newComparisonPredicate(columnSchema, op, (Short) javaValue); } if (javaValue instanceof Byte) { return KuduPredicate.newComparisonPredicate(columnSchema, op, (Byte) javaValue); } if (javaValue instanceof String) { return KuduPredicate.newComparisonPredicate(columnSchema, op, (String) javaValue); } if (javaValue instanceof Double) { return KuduPredicate.newComparisonPredicate(columnSchema, op, (Double) javaValue); } if (javaValue instanceof Float) { return KuduPredicate.newComparisonPredicate(columnSchema, op, (Float) javaValue); } if (javaValue instanceof Boolean) { return KuduPredicate.newComparisonPredicate(columnSchema, op, (Boolean) javaValue); } if (javaValue instanceof byte[]) { return KuduPredicate.newComparisonPredicate(columnSchema, op, (byte[]) javaValue); } if (javaValue == null) { throw new IllegalStateException("Unexpected null java value for column " + columnSchema.getName()); } throw new IllegalStateException("Unexpected java value for column " + columnSchema.getName() + ": " + javaValue + "(" + javaValue.getClass() + ")"); } private KuduSplit toKuduSplit(KuduTableHandle tableHandle, KuduScanToken token, int primaryKeyColumnCount) { try { byte[] serializedScanToken = token.serialize(); return new KuduSplit(tableHandle, primaryKeyColumnCount, serializedScanToken); } catch (IOException e) { throw new PrestoException(GENERIC_INTERNAL_ERROR, e); } } }
Remove return value from addConstraintPredicates method Handle none `TupleDomain` on the calling side.
presto-kudu/src/main/java/io/prestosql/plugin/kudu/KuduClientSession.java
Remove return value from addConstraintPredicates method
Java
apache-2.0
94bc0863f33ee93b903da07495d32446da2f40c4
0
pupnewfster/Lavasurvival,pupnewfster/Lavasurvival
package me.eddiep.minecraft.ls.game; import com.crossge.necessities.Commands.CmdHide; import com.crossge.necessities.RankManager.Rank; import me.eddiep.handles.ClassicPhysicsEvent; import me.eddiep.minecraft.ls.Lavasurvival; import me.eddiep.minecraft.ls.game.impl.Flood; import me.eddiep.minecraft.ls.game.impl.Rise; import me.eddiep.minecraft.ls.game.shop.ShopFactory; import me.eddiep.minecraft.ls.ranks.UserInfo; import me.eddiep.minecraft.ls.ranks.UserManager; import me.eddiep.minecraft.ls.system.BukkitUtils; import me.eddiep.minecraft.ls.system.FileUtils; import me.eddiep.minecraft.ls.system.PhysicsListener; import me.eddiep.minecraft.ls.system.PlayerListener; import mkremins.fanciful.FancyMessage; import org.bukkit.*; import org.bukkit.block.Block; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.material.MaterialData; import org.bukkit.scheduler.BukkitRunnable; import org.bukkit.scoreboard.Scoreboard; import java.io.File; import java.io.IOException; import java.util.*; public abstract class Gamemode { public static final Material[] DEFAULT_BLOCKS = new Material[] { Material.TORCH, Material.COBBLESTONE, Material.DIRT, Material.GRASS, Material.WOOD, Material.SAND }; public static final Class[] GAMES = new Class[] { Rise.class, Flood.class }; public static final int VOTE_COUNT; static { if (LavaMap.getPossibleMaps().length == 0) VOTE_COUNT = 0; else VOTE_COUNT = LavaMap.getPossibleMaps().length <= 3 ? LavaMap.getPossibleMaps().length - 1 : 3; } public static final Random RANDOM = new Random(); public static double DAMAGE = 3, DAMAGE_FREQUENCY = 0.5; public static boolean LAVA = true, voting = false; private LavaMap[] nextMaps = new LavaMap[VOTE_COUNT]; private int[] votes = new int[VOTE_COUNT]; private int voteCount; private static LavaMap lastMap, currentMap; private static ArrayList<UUID> alive, dead; private static Scoreboard scoreboard; private static PlayerListener listener; private static PhysicsListener physicsListener; private static Gamemode currentGame = null; protected boolean poured; private BukkitRunnable tickTask; private Gamemode nextGame; private LavaMap map; public static PlayerListener getPlayerListener() { return listener; } public static LavaMap getCurrentMap() { return currentMap; } public static World getCurrentWorld() { return currentMap.getWorld(); } public static Gamemode getCurrentGame() { return currentGame; } public static Scoreboard getScoreboard() { return scoreboard; } public static void cleanup() { if (listener != null) listener.cleanup(); if (physicsListener != null) physicsListener.cleanup(); } public void prepare() { if (scoreboard == null) scoreboard = Bukkit.getScoreboardManager().getMainScoreboard(); if (listener == null) { listener = new PlayerListener(); Lavasurvival.INSTANCE.getServer().getPluginManager().registerEvents(listener, Lavasurvival.INSTANCE); } if (physicsListener == null) { physicsListener = new PhysicsListener(); } physicsListener.prepare(); Lavasurvival.INSTANCE.getServer().getPluginManager().registerEvents(physicsListener, Lavasurvival.INSTANCE); if (map == null) { String[] files = LavaMap.getPossibleMaps(); lastMap = currentMap; do { String next = files[RANDOM.nextInt(files.length)]; try { currentMap = LavaMap.load(next); break; } catch (IOException e) { e.printStackTrace(); } } while (true); } else currentMap = map; currentMap.prepare(); } private long lastMoneyCheck = System.currentTimeMillis(); public void start() { Lavasurvival.log("New game on " + getCurrentWorld().getName()); isEnding = false; hasEnded = false; if (currentMap.getFloodOptions().isLavaEnabled() && currentMap.getFloodOptions().isWaterEnabled()) { LAVA = RANDOM.nextInt(100) < 75; //Have water/lava check be in here instead of as arguement } else { LAVA = currentMap.getFloodOptions().isLavaEnabled() || !currentMap.getFloodOptions().isWaterEnabled() && RANDOM.nextInt(100) < 75; } alive = new ArrayList<>(); dead = new ArrayList<>(); for (Player p : Bukkit.getOnlinePlayers()) playerJoin(p); currentGame = this; if (lastMap != null) { Lavasurvival.log("Unloading " + lastMap.getWorld().getName() + ".."); boolean success = Bukkit.unloadWorld(lastMap.getWorld(), false); if (!success) Lavasurvival.log("Failed to unload last map! A manual unload may be required.."); else { new Thread(new Runnable() { @Override public void run() { restoreBackup(lastMap.getWorld()); } }).start(); } } Lavasurvival.INSTANCE.MONEY_VIEWER.run(); tickTask = new BukkitRunnable() { @Override public void run() { if (System.currentTimeMillis() - lastMoneyCheck >= 20000) { Lavasurvival.INSTANCE.MONEY_VIEWER.run(); lastMoneyCheck = System.currentTimeMillis(); } tick(); } }; tickTask.runTaskTimer(Lavasurvival.INSTANCE, 0, 20); } private void restoreBackup(World world) { Lavasurvival.log("Restoring backup of " + world.getName()); try { FileUtils.copyDirectory(new File(Lavasurvival.INSTANCE.getDataFolder(), world.getName()), world.getWorldFolder()); new File(Lavasurvival.INSTANCE.getDataFolder(), world.getName()).delete(); } catch (IOException e) { e.printStackTrace(); } } private long timeTickCount; private void tick() { double multiplier = currentMap.getTimeOptions().getMultiplier(); if (currentMap.getTimeOptions().isEnabled()) { if (multiplier != 1.0) { timeTickCount++; long tick = (long) (timeTickCount * multiplier); getCurrentWorld().setTime(currentMap.getTimeOptions().getStartTimeTick() + timeTickCount); } } else { currentMap.getWorld().setTime(currentMap.getTimeOptions().getStartTimeTick()); } onTick(); } protected abstract void onTick(); protected abstract double calculateReward(Player player, int blockCount); protected int countAirBlocksAround(Player player, int limit) { return airBlocksAround(player.getLocation(), player.getLocation(), limit, new ArrayList<Block>()); } protected int airBlocksAround(Location original, Location location, int limit, List<Block> alreadyChecked) { if (original.toVector().distanceSquared(location.toVector()) >= limit) return 1; int total = 0; for (int x = -1; x <= 1; x++) { for (int y = -1; y <= 1; y++) { for (int z = -1; z <= 1; z++) { Block check = location.clone().add(x, y, z).getBlock(); if (alreadyChecked.contains(check)) continue; if (!check.getType().isSolid() && !check.isLiquid()) { alreadyChecked.add(check); total += airBlocksAround(original, check.getLocation(), limit, alreadyChecked) + 1; } } } } return total; } protected boolean isEnding, hasEnded; public void endRoundIn(long seconds) { if (isEnding) return; isEnding = true; Bukkit.getScheduler().scheduleSyncDelayedTask(Lavasurvival.INSTANCE, new Runnable() { @Override public void run() { endRound(); } }, seconds * 20L); } public boolean hasEnded() { return hasEnded; } public void endRound() { if (hasEnded) return; end(); final UserManager um = Lavasurvival.INSTANCE.getUserManager(); CmdHide hide = Lavasurvival.INSTANCE.getHide(); int amount = alive.size(); if (amount == 0) { globalMessage("No one survived.."); } else if (amount <= 45) { globalMessage("Congratulations to the survivors!"); String survivors = ""; for (UUID id : alive) { if (id == null || Bukkit.getPlayer(id) == null || hide.isHidden(Bukkit.getPlayer(id)) || isInSpawn(Bukkit.getPlayer(id))) continue; if (survivors.equals("")) survivors += Bukkit.getPlayer(id).getName(); else survivors += ", " + Bukkit.getPlayer(id).getName(); } globalMessage(survivors); } else { globalMessage("Congratulations to all " + amount + " survivors!"); } final HashMap<Player, Integer> winners = new HashMap<>(); for (UUID id : alive) { Player player = Bukkit.getPlayer(id); if (id == null || player == null || hide.isHidden(player) || isInSpawn(Bukkit.getPlayer(id))) continue; int blockCount = countAirBlocksAround(player, 20); double reward = calculateReward(player, blockCount); winners.put(player, blockCount); Lavasurvival.INSTANCE.getEconomy().depositPlayer(player, reward); player.getPlayer().sendMessage(ChatColor.GREEN + "+ " + ChatColor.GOLD + "You won " + ChatColor.BOLD + reward + ChatColor.RESET + "" + ChatColor.GOLD + " GGs!"); } calculateGlicko(winners, um); Lavasurvival.INSTANCE.MONEY_VIEWER.run(); lastMoneyCheck = System.currentTimeMillis(); new Thread(new Runnable() { @Override public void run() { startVoting(); } }).start(); new Thread(new Runnable() { @Override public void run() { System.out.println("Updating ratings.."); int count = 0; long start = System.currentTimeMillis(); for (Player p : Bukkit.getOnlinePlayers()) { UserInfo info = um.getUser(p.getUniqueId()); if (info.getRanking().shouldUpdate()) { info.getRanking().update(); count++; } } System.out.println("Updated " + count + " in " + (System.currentTimeMillis() - start) + "ms !"); } }).start(); } private void calculateGlicko(HashMap<Player, Integer> winners, UserManager um) { for (Player player : winners.keySet()) { int reward = winners.get(player); UserInfo info = um.getUser(player.getUniqueId()); for (Player other : winners.keySet()) { if (player.equals(other)) continue; UserInfo otherInfo = um.getUser(other.getUniqueId()); int otherReward = winners.get(other); double result; if (reward > otherReward) result = 1; //They won else if (reward < otherReward) result = 0; //They lost else result = 0.5; //They tied info.getRanking().addResult(otherInfo, result); } for (UUID id : dead) { Player p = Bukkit.getPlayer(id); if (p == null) continue; UserInfo otherInfo = um.getUser(id); info.getRanking().addResult(otherInfo, 1.0); otherInfo.getRanking().addResult(info, 0.0); } } } public List<LavaMap> getMapsInVote() { return Collections.unmodifiableList(Arrays.asList(nextMaps)); } public boolean hasVoted(Player player) { return voted.contains(player); } public void voteFor(int index) { votes[index]++; voteCount++; } private ArrayList<OfflinePlayer> voted = new ArrayList<>(); public void voteFor(int number, Player player) { if (number >= nextMaps.length) { player.sendMessage(ChatColor.DARK_RED + "Invalid number! Please choose a number between (1 - " + nextMaps.length + ")."); return; } voted.add(player); votes[number]++; voteCount++; player.sendMessage(ChatColor.GREEN + "+ " + ChatColor.RESET + "" + ChatColor.BOLD + "You voted for " + nextMaps[number].getName() + "!"); } public boolean isVoting() { return voting; } public void startVoting() { if (voting) return; String[] files = LavaMap.getPossibleMaps(); if (files.length > 1) { FancyMessage message = new FancyMessage(""); for (int i = 0; i < nextMaps.length; i++) { votes[i] = 0; //reset votes boolean found; String next; do { found = false; next = files[RANDOM.nextInt(files.length)]; File possibleNext = new File(next); if (currentMap.getFile().equals(possibleNext)) { found = true; continue; } for (LavaMap nextMap : nextMaps) { if (nextMap != null && nextMap.getFile().equals(possibleNext)) { found = true; break; } } } while (found); try { nextMaps[i] = LavaMap.load(next); } catch (IOException e) { e.printStackTrace(); } message.then((i + 1) + ". " + nextMaps[i].getName()) .style(ChatColor.UNDERLINE) .command("/lvote " + (i + 1)) .tooltip("Vote for " + nextMaps[i].getName()) .then(" "); } voted.clear(); globalMessage(ChatColor.GREEN + "It's time to vote for the next map!"); voting = true; globalMessage(ChatColor.BOLD + "No talking will be allowed during the vote."); globalMessageNoPrefix(ChatColor.BOLD + "" + ChatColor.UNDERLINE + "Click the map you want to vote for:"); globalMessageNoPrefix(" "); globalRawMessage(message); globalMessageNoPrefix(" "); long start = System.currentTimeMillis(); while (true) { long cur = System.currentTimeMillis(); if (voteCount >= Bukkit.getServer().getOnlinePlayers().size() || cur - start >= 50000) break; try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } voting = false; voteCount = 0; LavaMap next = null; int highest = 0; for (int i = 0; i < nextMaps.length; i++) { globalMessage(ChatColor.BOLD + nextMaps[i].getName() + ChatColor.RESET + " - " + votes[i] + " votes"); if (next == null) { next = nextMaps[i]; highest = votes[i]; } else if (votes[i] > highest) { highest = votes[i]; next = nextMaps[i]; } } if(next != null) globalMessage(ChatColor.BOLD + next.getName() + ChatColor.RESET + " won the vote!"); if (nextGame == null) nextGame = pickRandomGame(next); nextGame.map = next; } else { try { if (nextGame == null) nextGame = pickRandomGame(null); nextGame.map = LavaMap.load(files[0]); } catch (IOException e) { e.printStackTrace(); } } Bukkit.getScheduler().scheduleSyncDelayedTask(Lavasurvival.INSTANCE, new Runnable() { @Override public void run() { lastMap = getCurrentMap(); tryNextGame(); } }, 20); } public void forceEnd() { end(); } private void end() { tickTask.cancel(); Bukkit.getScheduler().cancelTasks(Lavasurvival.INSTANCE); ClassicPhysicsEvent.getHandlerList().unregister(physicsListener); physicsListener = null; globalMessage(ChatColor.GREEN + "The round has ended!"); isEnding = false; hasEnded = true; } protected Gamemode pickRandomGame(LavaMap map) { if (map == null) { Class<?> nextGameClass = GAMES[RANDOM.nextInt(GAMES.length)]; try { return (Gamemode) nextGameClass.newInstance(); } catch (Exception e) { e.printStackTrace(); } } else { Class<? extends Gamemode>[] games = map.getEnabledGames(); Class<? extends Gamemode> nextGameClass = games[RANDOM.nextInt(games.length)]; try { return nextGameClass.newInstance(); } catch (InstantiationException | IllegalAccessException e) { e.printStackTrace(); } } return null; } protected void tryNextGame() { if (nextGame != null) { globalMessage("Preparing next game.."); nextGame.prepare(); Bukkit.getScheduler().scheduleSyncDelayedTask(Lavasurvival.INSTANCE, new Runnable() { @Override public void run() { nextGame.start(); } }, 40); //2 seconds } } protected double getDefaultReward(OfflinePlayer player, int blockCount) { Player onlinePlayer = player.getPlayer(); if (onlinePlayer == null) return 0.0; double base = 100.0; Rank rank = Lavasurvival.INSTANCE.getNecessitiesUserManager().getUser(player.getUniqueId()).getRank(); double bonusAdd = 5.0 + (1 + Lavasurvival.INSTANCE.getRankManager().getOrder().indexOf(rank)); //int blockCount = countAirBlocksAround(onlinePlayer, 20); System.out.println(onlinePlayer.getName() + " had " + blockCount + " blocks around them!"); return base + (bonusAdd * blockCount); } protected void setNextGame(Gamemode game) { this.nextGame = game; } protected void setNextMap(LavaMap map) { if (this.nextGame != null) this.nextGame.map = map; } public void playerJoin(Player player) { setAlive(player); player.teleport(new Location(getCurrentWorld(), getCurrentMap().getMapSpawn().getX(), getCurrentMap().getMapSpawn().getY(), getCurrentMap().getMapSpawn().getZ())); player.setGameMode(GameMode.SURVIVAL); player.setHealth(player.getMaxHealth()); globalMessageNoPrefix(ChatColor.GREEN + "+ " + player.getDisplayName() + ChatColor.RESET + " has joined the game!"); Inventory inv = player.getInventory(); for (Material DEFAULT_BLOCK : DEFAULT_BLOCKS) { ItemStack toGive = new ItemStack(DEFAULT_BLOCK, 1); if (BukkitUtils.hasItem(player.getInventory(), toGive)) continue; ItemMeta im = toGive.getItemMeta(); im.setLore(Arrays.asList("Melt time: " + PhysicsListener.getMeltTimeAsString(new MaterialData(toGive.getType())))); toGive.setItemMeta(im); player.getInventory().addItem(toGive); } if (!player.getInventory().containsAtLeast(Lavasurvival.INSTANCE.getRules(), 1)) player.getInventory().addItem(Lavasurvival.INSTANCE.getRules()); ShopFactory.validateInventory(inv); UserManager um = Lavasurvival.INSTANCE.getUserManager(); UserInfo u = um.getUser(player.getUniqueId()); if (u != null) u.giveBoughtBlocks(); } public void setAlive(Player player) { if (player == null) return; UUID uuid = player.getUniqueId(); if (dead.contains(uuid)) dead.remove(uuid); if (!alive.contains(uuid)) alive.add(uuid); Lavasurvival.INSTANCE.getNecessitiesUserManager().getUser(uuid).setStatus("alive"); player.setGameMode(GameMode.SURVIVAL); Lavasurvival.log(player.getName() + " has joined the alive team."); } public void setDead(Player player) { if (player == null) return; UUID uuid = player.getUniqueId(); if (alive.contains(uuid)) alive.remove(uuid); if (!dead.contains(uuid)) dead.add(uuid); Lavasurvival.INSTANCE.getNecessitiesUserManager().getUser(uuid).setStatus("dead"); player.setGameMode(GameMode.SPECTATOR); Lavasurvival.log(player.getName() + " has joined the dead team."); } public boolean isAlive(Player player) { return player != null && (alive.contains(player.getUniqueId())); } public boolean isDead(Player player) { return player != null && dead.contains(player.getUniqueId()); } public boolean isInGame(Player player) { return player != null && (alive.contains(player.getUniqueId()) || dead.contains(player.getUniqueId())); } public void globalMessage(String message) { for (Player p : getCurrentWorld().getPlayers()) p.sendMessage(ChatColor.RED + "[Lavasurvival] " + ChatColor.RESET + message); } public void globalMessageNoPrefix(String message) { for (Player p : getCurrentWorld().getPlayers()) p.sendMessage(message); } public void globalRawMessage(FancyMessage rawMessage) { for (Player p : getCurrentWorld().getPlayers()) rawMessage.send(p); } protected Material getMat() { return LAVA ? Material.STATIONARY_LAVA : Material.STATIONARY_WATER; } public boolean isInSpawn(Player player) { return player != null && (getCurrentMap().isInSafeZone(player.getLocation()) || getCurrentMap().isInSafeZone(player.getEyeLocation())); } }
Lavasurvival/src/main/java/me/eddiep/minecraft/ls/game/Gamemode.java
package me.eddiep.minecraft.ls.game; import com.crossge.necessities.Commands.CmdHide; import com.crossge.necessities.RankManager.Rank; import me.eddiep.handles.ClassicPhysicsEvent; import me.eddiep.minecraft.ls.Lavasurvival; import me.eddiep.minecraft.ls.game.impl.Flood; import me.eddiep.minecraft.ls.game.impl.Rise; import me.eddiep.minecraft.ls.game.shop.ShopFactory; import me.eddiep.minecraft.ls.ranks.UserInfo; import me.eddiep.minecraft.ls.ranks.UserManager; import me.eddiep.minecraft.ls.system.BukkitUtils; import me.eddiep.minecraft.ls.system.FileUtils; import me.eddiep.minecraft.ls.system.PhysicsListener; import me.eddiep.minecraft.ls.system.PlayerListener; import mkremins.fanciful.FancyMessage; import org.bukkit.*; import org.bukkit.block.Block; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.material.MaterialData; import org.bukkit.scheduler.BukkitRunnable; import org.bukkit.scoreboard.Scoreboard; import java.io.File; import java.io.IOException; import java.util.*; public abstract class Gamemode { public static final Material[] DEFAULT_BLOCKS = new Material[] { Material.TORCH, Material.COBBLESTONE, Material.DIRT, Material.GRASS, Material.WOOD, Material.SAND }; public static final Class[] GAMES = new Class[] { Rise.class, Flood.class }; public static final int VOTE_COUNT; static { if (LavaMap.getPossibleMaps().length == 0) VOTE_COUNT = 0; else VOTE_COUNT = LavaMap.getPossibleMaps().length <= 3 ? LavaMap.getPossibleMaps().length - 1 : 3; } public static final Random RANDOM = new Random(); public static double DAMAGE = 3, DAMAGE_FREQUENCY = 0.5; public static boolean LAVA = true, voting = false; private LavaMap[] nextMaps = new LavaMap[VOTE_COUNT]; private int[] votes = new int[VOTE_COUNT]; private int voteCount; private static LavaMap lastMap, currentMap; private static ArrayList<UUID> alive, dead; private static Scoreboard scoreboard; private static PlayerListener listener; private static PhysicsListener physicsListener; private static Gamemode currentGame = null; protected boolean poured; private BukkitRunnable tickTask; private Gamemode nextGame; private LavaMap map; public static PlayerListener getPlayerListener() { return listener; } public static LavaMap getCurrentMap() { return currentMap; } public static World getCurrentWorld() { return currentMap.getWorld(); } public static Gamemode getCurrentGame() { return currentGame; } public static Scoreboard getScoreboard() { return scoreboard; } public static void cleanup() { if (listener != null) listener.cleanup(); if (physicsListener != null) physicsListener.cleanup(); } public void prepare() { if (scoreboard == null) scoreboard = Bukkit.getScoreboardManager().getMainScoreboard(); if (listener == null) { listener = new PlayerListener(); Lavasurvival.INSTANCE.getServer().getPluginManager().registerEvents(listener, Lavasurvival.INSTANCE); } if (physicsListener == null) { physicsListener = new PhysicsListener(); } physicsListener.prepare(); Lavasurvival.INSTANCE.getServer().getPluginManager().registerEvents(physicsListener, Lavasurvival.INSTANCE); if (map == null) { String[] files = LavaMap.getPossibleMaps(); lastMap = currentMap; do { String next = files[RANDOM.nextInt(files.length)]; try { currentMap = LavaMap.load(next); break; } catch (IOException e) { e.printStackTrace(); } } while (true); } else currentMap = map; currentMap.prepare(); } private long lastMoneyCheck = System.currentTimeMillis(); public void start() { Lavasurvival.log("New game on " + getCurrentWorld().getName()); isEnding = false; hasEnded = false; if (currentMap.getFloodOptions().isLavaEnabled() && currentMap.getFloodOptions().isWaterEnabled()) { LAVA = RANDOM.nextInt(100) < 75; //Have water/lava check be in here instead of as arguement } else { LAVA = currentMap.getFloodOptions().isLavaEnabled() || !currentMap.getFloodOptions().isWaterEnabled() && RANDOM.nextInt(100) < 75; } alive = new ArrayList<>(); dead = new ArrayList<>(); for (Player p : Bukkit.getOnlinePlayers()) playerJoin(p); currentGame = this; if (lastMap != null) { Lavasurvival.log("Unloading " + lastMap.getWorld().getName() + ".."); boolean success = Bukkit.unloadWorld(lastMap.getWorld(), false); if (!success) Lavasurvival.log("Failed to unload last map! A manual unload may be required.."); else { new Thread(new Runnable() { @Override public void run() { restoreBackup(lastMap.getWorld()); } }).start(); } } Lavasurvival.INSTANCE.MONEY_VIEWER.run(); tickTask = new BukkitRunnable() { @Override public void run() { if (System.currentTimeMillis() - lastMoneyCheck >= 20000) { Lavasurvival.INSTANCE.MONEY_VIEWER.run(); lastMoneyCheck = System.currentTimeMillis(); } tick(); } }; tickTask.runTaskTimer(Lavasurvival.INSTANCE, 0, 20); } private void restoreBackup(World world) { Lavasurvival.log("Restoring backup of " + world.getName()); try { FileUtils.copyDirectory(new File(Lavasurvival.INSTANCE.getDataFolder(), world.getName()), world.getWorldFolder()); new File(Lavasurvival.INSTANCE.getDataFolder(), world.getName()).delete(); } catch (IOException e) { e.printStackTrace(); } } private long timeTickCount; private void tick() { double multiplier = currentMap.getTimeOptions().getMultiplier(); if (currentMap.getTimeOptions().isEnabled()) { if (multiplier != 1.0) { timeTickCount++; long tick = (long) (timeTickCount * multiplier); getCurrentWorld().setTime(currentMap.getTimeOptions().getStartTimeTick() + timeTickCount); } } else { currentMap.getWorld().setTime(currentMap.getTimeOptions().getStartTimeTick()); } onTick(); } protected abstract void onTick(); protected abstract double calculateReward(Player player, int blockCount); protected int countAirBlocksAround(Player player, int limit) { return airBlocksAround(player.getLocation(), player.getLocation(), limit, new ArrayList<Block>()); } protected int airBlocksAround(Location original, Location location, int limit, List<Block> alreadyChecked) { if (original.toVector().distanceSquared(location.toVector()) >= limit) return 1; int total = 0; for (int x = -1; x <= 1; x++) { for (int y = -1; y <= 1; y++) { for (int z = -1; z <= 1; z++) { Block check = location.clone().add(x, y, z).getBlock(); if (alreadyChecked.contains(check)) continue; if (!check.getType().isSolid() && !check.isLiquid()) { alreadyChecked.add(check); total += airBlocksAround(original, check.getLocation(), limit, alreadyChecked) + 1; } } } } return total; } protected boolean isEnding, hasEnded; public void endRoundIn(long seconds) { if (isEnding) return; isEnding = true; Bukkit.getScheduler().scheduleSyncDelayedTask(Lavasurvival.INSTANCE, new Runnable() { @Override public void run() { endRound(); } }, seconds * 20L); } public boolean hasEnded() { return hasEnded; } public void endRound() { if (hasEnded) return; end(); final UserManager um = Lavasurvival.INSTANCE.getUserManager(); CmdHide hide = Lavasurvival.INSTANCE.getHide(); int amount = alive.size(); if (amount == 0) { globalMessage("No one survived.."); } else if (amount <= 45) { globalMessage("Congratulations to the survivors!"); String survivors = ""; for (UUID id : alive) { if (id == null || Bukkit.getPlayer(id) == null || hide.isHidden(Bukkit.getPlayer(id)) || isInSpawn(Bukkit.getPlayer(id))) continue; if (survivors.equals("")) survivors += Bukkit.getPlayer(id).getName(); else survivors += ", " + Bukkit.getPlayer(id).getName(); } globalMessage(survivors); } else { globalMessage("Congratulations to all " + amount + " survivors!"); } final HashMap<Player, Integer> winners = new HashMap<>(); for (UUID id : alive) { Player player = Bukkit.getPlayer(id); if (id == null || player == null || hide.isHidden(player) || isInSpawn(Bukkit.getPlayer(id))) continue; int blockCount = countAirBlocksAround(player, 20); double reward = calculateReward(player, blockCount); winners.put(player, blockCount); Lavasurvival.INSTANCE.getEconomy().depositPlayer(player, reward); player.getPlayer().sendMessage(ChatColor.GREEN + "+ " + ChatColor.GOLD + "You won " + ChatColor.BOLD + reward + ChatColor.RESET + "" + ChatColor.GOLD + " GGs!"); } calculateGlicko(winners, um); Lavasurvival.INSTANCE.MONEY_VIEWER.run(); lastMoneyCheck = System.currentTimeMillis(); new Thread(new Runnable() { @Override public void run() { startVoting(); } }).start(); new Thread(new Runnable() { @Override public void run() { System.out.println("Updating ratings.."); int count = 0; long start = System.currentTimeMillis(); for (Player p : winners.keySet()) { UserInfo info = um.getUser(p.getUniqueId()); if (info.getRanking().shouldUpdate()) { info.getRanking().update(); count++; } } System.out.println("Updated " + count + " in " + (System.currentTimeMillis() - start) + "ms !"); } }).start(); } private void calculateGlicko(HashMap<Player, Integer> winners, UserManager um) { for (Player player : winners.keySet()) { int reward = winners.get(player); UserInfo info = um.getUser(player.getUniqueId()); for (Player other : winners.keySet()) { if (player.equals(other)) continue; UserInfo otherInfo = um.getUser(other.getUniqueId()); int otherReward = winners.get(other); double result; if (reward > otherReward) result = 1; //They won else if (reward < otherReward) result = 0; //They lost else result = 0.5; //They tied info.getRanking().addResult(otherInfo, result); } for (UUID id : dead) { Player p = Bukkit.getPlayer(id); if (p == null) continue; UserInfo otherInfo = um.getUser(id); info.getRanking().addResult(otherInfo, 1.0); otherInfo.getRanking().addResult(info, 0.0); } } } public List<LavaMap> getMapsInVote() { return Collections.unmodifiableList(Arrays.asList(nextMaps)); } public boolean hasVoted(Player player) { return voted.contains(player); } public void voteFor(int index) { votes[index]++; voteCount++; } private ArrayList<OfflinePlayer> voted = new ArrayList<>(); public void voteFor(int number, Player player) { if (number >= nextMaps.length) { player.sendMessage(ChatColor.DARK_RED + "Invalid number! Please choose a number between (1 - " + nextMaps.length + ")."); return; } voted.add(player); votes[number]++; voteCount++; player.sendMessage(ChatColor.GREEN + "+ " + ChatColor.RESET + "" + ChatColor.BOLD + "You voted for " + nextMaps[number].getName() + "!"); } public boolean isVoting() { return voting; } public void startVoting() { if (voting) return; String[] files = LavaMap.getPossibleMaps(); if (files.length > 1) { FancyMessage message = new FancyMessage(""); for (int i = 0; i < nextMaps.length; i++) { votes[i] = 0; //reset votes boolean found; String next; do { found = false; next = files[RANDOM.nextInt(files.length)]; File possibleNext = new File(next); if (currentMap.getFile().equals(possibleNext)) { found = true; continue; } for (LavaMap nextMap : nextMaps) { if (nextMap != null && nextMap.getFile().equals(possibleNext)) { found = true; break; } } } while (found); try { nextMaps[i] = LavaMap.load(next); } catch (IOException e) { e.printStackTrace(); } message.then((i + 1) + ". " + nextMaps[i].getName()) .style(ChatColor.UNDERLINE) .command("/lvote " + (i + 1)) .tooltip("Vote for " + nextMaps[i].getName()) .then(" "); } voted.clear(); globalMessage(ChatColor.GREEN + "It's time to vote for the next map!"); voting = true; globalMessage(ChatColor.BOLD + "No talking will be allowed during the vote."); globalMessageNoPrefix(ChatColor.BOLD + "" + ChatColor.UNDERLINE + "Click the map you want to vote for:"); globalMessageNoPrefix(" "); globalRawMessage(message); globalMessageNoPrefix(" "); long start = System.currentTimeMillis(); while (true) { long cur = System.currentTimeMillis(); if (voteCount >= Bukkit.getServer().getOnlinePlayers().size() || cur - start >= 50000) break; try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } voting = false; voteCount = 0; LavaMap next = null; int highest = 0; for (int i = 0; i < nextMaps.length; i++) { globalMessage(ChatColor.BOLD + nextMaps[i].getName() + ChatColor.RESET + " - " + votes[i] + " votes"); if (next == null) { next = nextMaps[i]; highest = votes[i]; } else if (votes[i] > highest) { highest = votes[i]; next = nextMaps[i]; } } if(next != null) globalMessage(ChatColor.BOLD + next.getName() + ChatColor.RESET + " won the vote!"); if (nextGame == null) nextGame = pickRandomGame(next); nextGame.map = next; } else { try { if (nextGame == null) nextGame = pickRandomGame(null); nextGame.map = LavaMap.load(files[0]); } catch (IOException e) { e.printStackTrace(); } } Bukkit.getScheduler().scheduleSyncDelayedTask(Lavasurvival.INSTANCE, new Runnable() { @Override public void run() { lastMap = getCurrentMap(); tryNextGame(); } }, 20); } public void forceEnd() { end(); } private void end() { tickTask.cancel(); Bukkit.getScheduler().cancelTasks(Lavasurvival.INSTANCE); ClassicPhysicsEvent.getHandlerList().unregister(physicsListener); physicsListener = null; globalMessage(ChatColor.GREEN + "The round has ended!"); isEnding = false; hasEnded = true; } protected Gamemode pickRandomGame(LavaMap map) { if (map == null) { Class<?> nextGameClass = GAMES[RANDOM.nextInt(GAMES.length)]; try { return (Gamemode) nextGameClass.newInstance(); } catch (Exception e) { e.printStackTrace(); } } else { Class<? extends Gamemode>[] games = map.getEnabledGames(); Class<? extends Gamemode> nextGameClass = games[RANDOM.nextInt(games.length)]; try { return nextGameClass.newInstance(); } catch (InstantiationException | IllegalAccessException e) { e.printStackTrace(); } } return null; } protected void tryNextGame() { if (nextGame != null) { globalMessage("Preparing next game.."); nextGame.prepare(); Bukkit.getScheduler().scheduleSyncDelayedTask(Lavasurvival.INSTANCE, new Runnable() { @Override public void run() { nextGame.start(); } }, 40); //2 seconds } } protected double getDefaultReward(OfflinePlayer player, int blockCount) { Player onlinePlayer = player.getPlayer(); if (onlinePlayer == null) return 0.0; double base = 100.0; Rank rank = Lavasurvival.INSTANCE.getNecessitiesUserManager().getUser(player.getUniqueId()).getRank(); double bonusAdd = 5.0 + (1 + Lavasurvival.INSTANCE.getRankManager().getOrder().indexOf(rank)); //int blockCount = countAirBlocksAround(onlinePlayer, 20); System.out.println(onlinePlayer.getName() + " had " + blockCount + " blocks around them!"); return base + (bonusAdd * blockCount); } protected void setNextGame(Gamemode game) { this.nextGame = game; } protected void setNextMap(LavaMap map) { if (this.nextGame != null) this.nextGame.map = map; } public void playerJoin(Player player) { setAlive(player); player.teleport(new Location(getCurrentWorld(), getCurrentMap().getMapSpawn().getX(), getCurrentMap().getMapSpawn().getY(), getCurrentMap().getMapSpawn().getZ())); player.setGameMode(GameMode.SURVIVAL); player.setHealth(player.getMaxHealth()); globalMessageNoPrefix(ChatColor.GREEN + "+ " + player.getDisplayName() + ChatColor.RESET + " has joined the game!"); Inventory inv = player.getInventory(); for (Material DEFAULT_BLOCK : DEFAULT_BLOCKS) { ItemStack toGive = new ItemStack(DEFAULT_BLOCK, 1); if (BukkitUtils.hasItem(player.getInventory(), toGive)) continue; ItemMeta im = toGive.getItemMeta(); im.setLore(Arrays.asList("Melt time: " + PhysicsListener.getMeltTimeAsString(new MaterialData(toGive.getType())))); toGive.setItemMeta(im); player.getInventory().addItem(toGive); } if (!player.getInventory().containsAtLeast(Lavasurvival.INSTANCE.getRules(), 1)) player.getInventory().addItem(Lavasurvival.INSTANCE.getRules()); ShopFactory.validateInventory(inv); UserManager um = Lavasurvival.INSTANCE.getUserManager(); UserInfo u = um.getUser(player.getUniqueId()); if (u != null) u.giveBoughtBlocks(); } public void setAlive(Player player) { if (player == null) return; UUID uuid = player.getUniqueId(); if (dead.contains(uuid)) dead.remove(uuid); if (!alive.contains(uuid)) alive.add(uuid); Lavasurvival.INSTANCE.getNecessitiesUserManager().getUser(uuid).setStatus("alive"); player.setGameMode(GameMode.SURVIVAL); Lavasurvival.log(player.getName() + " has joined the alive team."); } public void setDead(Player player) { if (player == null) return; UUID uuid = player.getUniqueId(); if (alive.contains(uuid)) alive.remove(uuid); if (!dead.contains(uuid)) dead.add(uuid); Lavasurvival.INSTANCE.getNecessitiesUserManager().getUser(uuid).setStatus("dead"); player.setGameMode(GameMode.SPECTATOR); Lavasurvival.log(player.getName() + " has joined the dead team."); } public boolean isAlive(Player player) { return player != null && (alive.contains(player.getUniqueId())); } public boolean isDead(Player player) { return player != null && dead.contains(player.getUniqueId()); } public boolean isInGame(Player player) { return player != null && (alive.contains(player.getUniqueId()) || dead.contains(player.getUniqueId())); } public void globalMessage(String message) { for (Player p : getCurrentWorld().getPlayers()) p.sendMessage(ChatColor.RED + "[Lavasurvival] " + ChatColor.RESET + message); } public void globalMessageNoPrefix(String message) { for (Player p : getCurrentWorld().getPlayers()) p.sendMessage(message); } public void globalRawMessage(FancyMessage rawMessage) { for (Player p : getCurrentWorld().getPlayers()) rawMessage.send(p); } protected Material getMat() { return LAVA ? Material.STATIONARY_LAVA : Material.STATIONARY_WATER; } public boolean isInSpawn(Player player) { return player != null && (getCurrentMap().isInSafeZone(player.getLocation()) || getCurrentMap().isInSafeZone(player.getEyeLocation())); } }
Fixed bug in Glicko
Lavasurvival/src/main/java/me/eddiep/minecraft/ls/game/Gamemode.java
Fixed bug in Glicko
Java
apache-2.0
1aed2258007bd855b56b409fa8a0fa1ca48606ac
0
StepicOrg/stepic-android,StepicOrg/stepik-android,StepicOrg/stepik-android,StepicOrg/stepic-android,StepicOrg/stepik-android,StepicOrg/stepic-android
package org.stepic.droid.preferences; import android.content.Context; import android.content.SharedPreferences; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.stepic.droid.analytic.Analytic; import org.stepic.droid.core.DefaultFilter; import org.stepic.droid.di.AppSingleton; import org.stepic.droid.model.EmailAddress; import org.stepic.droid.model.Profile; import org.stepic.droid.model.StepikFilter; import org.stepic.droid.model.comments.DiscussionOrder; import org.stepic.droid.notifications.model.NotificationType; import org.stepic.droid.ui.util.TimeIntervalUtil; import org.stepic.droid.util.AppConstants; import org.stepic.droid.util.DateTimeHelper; import org.stepic.droid.util.RWLocks; import org.stepic.droid.web.AuthenticationStepikResponse; import java.util.EnumSet; import java.util.List; import javax.inject.Inject; @AppSingleton public class SharedPreferenceHelper { private static final String NOTIFICATION_SOUND_DISABLED = "notification_sound"; private static final String NEED_DROP_116 = "need_drop_116"; private static final String DISCOUNTING_POLICY_DIALOG = "discounting_pol_dialog"; private static final String KEEP_SCREEN_ON_STEPS = "keep_screen_on_steps"; private static final String IS_ADAPTIVE_MODE_ENABLED = "is_adaptive_mode_enabled"; private static final String IS_FIRST_ADAPTIVE_COURSE = "is_first_adaptive_course"; private static final String IS_ADAPTIVE_EXP_TOOLTIP_WAS_SHOWN = "is_adaptive_exp_tooltip_was_shown"; private static final String ROTATE_PREF = "rotate_pref"; private static final String NOTIFICATION_LEARN_DISABLED = "notification_disabled_by_user"; private static final String NOTIFICATION_COMMENT_DISABLED = "notification_comment_disabled"; private static final String NOTIFICATION_TEACH_DISABLED = "notification_teach_disabled"; private static final String NOTIFICATION_REVIEW_DISABLED = "notification_review_disabled"; private static final String NOTIFICATION_OTHER_DISABLED = "notification_other_disabled"; private static final String NOTIFICATION_VIBRATION_DISABLED = "not_vibrat_disabled"; private final static String ONE_DAY_NOTIFICATION = "one_day_notification"; private final static String SEVEN_DAY_NOTIFICATION = "seven_day_notification"; private static final String FILTER_RUSSIAN_LANGUAGE = "russian_lang"; private static final String FILTER_ENGLISH_LANGUAGE = "english_lang"; private static final String NOTIFICATIONS_COUNT = "notifications_count"; private static final String IS_EVER_LOGGED = "is_ever_logged"; private static final String IS_LANG_WIDGET_WAS_SHOWN_AFTER_LOGIN = "is_lang_widget_was_shown_after_login"; private static final String NEED_SHOW_LANG_WIDGET = "need_show_lang_widget"; private final String ACCESS_TOKEN_TIMESTAMP = "access_token_timestamp"; private final String AUTH_RESPONSE_JSON = "auth_response_json"; private final String PROFILE_JSON = "profile_json"; private final String EMAIL_LIST = "email_list"; private final String WIFI_KEY = "wifi_key"; private final String IS_SOCIAL = "is_social_key"; private final String VIDEO_QUALITY_KEY = "video_quality_key"; private final String VIDEO_QUALITY_KEY_FOR_PLAYING = "video_quality_key_for_playing"; private final String TEMP_POSITION_KEY = "temp_position_key"; private final String VIDEO_RATE_PREF_KEY = "video_rate_pref_key"; private final String VIDEO_EXTERNAL_PREF_KEY = "video_external_pref_key"; private final String GCM_TOKEN_ACTUAL = "gcm_token_actual_with_badges"; // '_with_badges' suffix was added to force update of gcm token to enable silent push with badge count, see #188 private final String SD_CHOSEN = "sd_chosen"; private final String FIRST_TIME_LAUNCH = "first_time_launch"; private final String SCHEDULED_LINK_CACHED = "scheduled_cached"; private final String DISCUSSION_ORDER = "discussion_order"; private final String CALENDAR_WIDGET = "calenda_widget"; private final String VIDEO_QUALITY_EXPLANATION = "video_quality_explanation"; private final String NEED_DROP_114 = "need_drop_114"; private final String REMIND_CLICK = "remind_click"; private final String ANY_STEP_SOLVED = "any_step_solved"; private final String NUMBER_OF_STEPS_SOLVED = "number_of_steps_solved"; private final String NEW_USER_ALARM_TIMESTAMP = "new_user_alarm_timestamp"; private final String REGISTRATION_ALARM_TIMESTAMP = "registration_alarm_timestamp"; private final String NUMBER_OF_SHOWN_STREAK_DIALOG = "number_of_shown_streak_dialog"; private final String STREAK_DIALOG_SHOWN_TIMESTAMP = "streak_dialog_shown_timestamp"; private final String STREAK_NUMBER_OF_IGNORED = "streak_number_of_ignored"; private final String TIME_NOTIFICATION_CODE = "time_notification_code"; private final String STREAK_NOTIFICATION = "streak_notification"; private final String USER_START_KEY = "user_start_app"; private final String RATE_LAST_TIMESTAMP = "rate_last_timestamp"; private final String RATE_TIMES_SHOWN = "rate_times_shown"; private final String RATE_WAS_HANDLED = "rate_was_handled"; private AuthenticationStepikResponse cachedAuthStepikResponse = null; private final Context context; private final Analytic analytic; private final DefaultFilter defaultFilter; public enum NotificationDay { DAY_ONE(ONE_DAY_NOTIFICATION), DAY_SEVEN(SEVEN_DAY_NOTIFICATION); private String internalNotificationKey; NotificationDay(String notificationKey) { this.internalNotificationKey = notificationKey; } public String getInternalNotificationKey() { return internalNotificationKey; } } @Inject public SharedPreferenceHelper(Analytic analytic, DefaultFilter defaultFilter, Context context) { this.analytic = analytic; this.defaultFilter = defaultFilter; this.context = context; } /** * call when user click Google Play or Support at rate Dialog */ public void afterRateWasHandled() { put(PreferenceType.DEVICE_SPECIFIC, RATE_WAS_HANDLED, true); } public boolean wasRateHandled() { return getBoolean(PreferenceType.DEVICE_SPECIFIC, RATE_WAS_HANDLED); } public void rateShown(long timeMillis) { put(PreferenceType.DEVICE_SPECIFIC, RATE_LAST_TIMESTAMP, timeMillis); long times = getLong(PreferenceType.DEVICE_SPECIFIC, RATE_TIMES_SHOWN, 0); put(PreferenceType.DEVICE_SPECIFIC, RATE_TIMES_SHOWN, times + 1); } /** * @return last timestamp, when it was shown, -1 when it has never been shown */ public long whenRateWasShown() { return getLong(PreferenceType.DEVICE_SPECIFIC, RATE_LAST_TIMESTAMP, -1); } public long howManyRateWasShownBefore() { return getLong(PreferenceType.DEVICE_SPECIFIC, RATE_TIMES_SHOWN, 0); } public void incrementNumberOfNotifications() { int numberOfIgnored = getInt(PreferenceType.LOGIN, STREAK_NUMBER_OF_IGNORED, 0); numberOfIgnored++; put(PreferenceType.LOGIN, STREAK_NUMBER_OF_IGNORED, numberOfIgnored); } public void resetNumberOfStreakNotifications() { put(PreferenceType.LOGIN, STREAK_NUMBER_OF_IGNORED, 0); } public int getNumberOfStreakNotifications() { return getInt(PreferenceType.LOGIN, STREAK_NUMBER_OF_IGNORED, 0); } public boolean anyStepIsSolved() { return getBoolean(PreferenceType.LOGIN, ANY_STEP_SOLVED, false); } public void trackWhenUserSolved() { put(PreferenceType.LOGIN, ANY_STEP_SOLVED, true); } public void incrementUserSolved() { long userSolved = getLong(PreferenceType.LOGIN, NUMBER_OF_STEPS_SOLVED, 0); put(PreferenceType.LOGIN, NUMBER_OF_STEPS_SOLVED, userSolved + 1); } public long numberOfSolved() { return getLong(PreferenceType.LOGIN, NUMBER_OF_STEPS_SOLVED, 0); } public void saveNewUserRemindTimestamp(long scheduleMillis) { put(PreferenceType.DEVICE_SPECIFIC, NEW_USER_ALARM_TIMESTAMP, scheduleMillis); } public long getNewUserRemindTimestamp() { return getLong(PreferenceType.DEVICE_SPECIFIC, NEW_USER_ALARM_TIMESTAMP); } public void saveRegistrationRemindTimestamp(long scheduleMillis) { put(PreferenceType.DEVICE_SPECIFIC, REGISTRATION_ALARM_TIMESTAMP, scheduleMillis); } public long getRegistrationRemindTimestamp() { return getLong(PreferenceType.DEVICE_SPECIFIC, REGISTRATION_ALARM_TIMESTAMP); } /** * Lang widget should be kept the whole session after first time catalog was opened after new login */ public boolean isNeedShowLangWidget() { boolean isLangWidgetWasShown = getBoolean(PreferenceType.LOGIN, IS_LANG_WIDGET_WAS_SHOWN_AFTER_LOGIN, false); if (!isLangWidgetWasShown) { put(PreferenceType.LOGIN, IS_LANG_WIDGET_WAS_SHOWN_AFTER_LOGIN, true); put(PreferenceType.LOGIN, NEED_SHOW_LANG_WIDGET, true); } return getBoolean(PreferenceType.LOGIN, NEED_SHOW_LANG_WIDGET, true); } public void onSessionAfterLogin() { put(PreferenceType.LOGIN, IS_LANG_WIDGET_WAS_SHOWN_AFTER_LOGIN, false); } public void onNewSession() { put(PreferenceType.LOGIN, NEED_SHOW_LANG_WIDGET, false); } public void clickEnrollNotification(long timestamp) { put(PreferenceType.DEVICE_SPECIFIC, REMIND_CLICK, timestamp); } @Nullable public Long getLastClickEnrollNotification() { long lastClickNotificationRemind = getLong(PreferenceType.DEVICE_SPECIFIC, REMIND_CLICK); if (lastClickNotificationRemind <= 0) { return null; } else { return lastClickNotificationRemind; } } public int getTimeNotificationCode() { return getInt(PreferenceType.LOGIN, TIME_NOTIFICATION_CODE, TimeIntervalUtil.INSTANCE.getDefaultTimeCode()); } public void setTimeNotificationCode(int value) { put(PreferenceType.LOGIN, TIME_NOTIFICATION_CODE, value); } public boolean isStreakNotificationEnabled() { int simpleCode = getInt(PreferenceType.LOGIN, STREAK_NOTIFICATION, -1); return simpleCode > 0; } /** * Null by default */ @Nullable public Boolean isStreakNotificationEnabledNullable() { int codeInt = getInt(PreferenceType.LOGIN, STREAK_NOTIFICATION, -1); if (codeInt > 0) { return true; } else if (codeInt == 0) { return false; } else { return null; } } public void setStreakNotificationEnabled(boolean value) { put(PreferenceType.LOGIN, STREAK_NOTIFICATION, value ? 1 : 0); analytic.setStreaksNotificationsEnabled(value); resetNumberOfStreakNotifications(); } public boolean canShowStreakDialog() { int streakDialogShownNumber = getInt(PreferenceType.LOGIN, NUMBER_OF_SHOWN_STREAK_DIALOG, 0); if (streakDialogShownNumber > AppConstants.MAX_NUMBER_OF_SHOWING_STREAK_DIALOG) { return false; } else { long millis = getLong(PreferenceType.LOGIN, STREAK_DIALOG_SHOWN_TIMESTAMP, -1L); if (millis < 0) { onShowStreakDialog(streakDialogShownNumber); // first time return true; } else { long calculatedMillis = millis + AppConstants.NUMBER_OF_DAYS_BETWEEN_STREAK_SHOWING * AppConstants.MILLIS_IN_24HOURS; if (DateTimeHelper.INSTANCE.isBeforeNowUtc(calculatedMillis)) { //we can show onShowStreakDialog(streakDialogShownNumber); return true; } else { return false; } } } } private void onShowStreakDialog(int streakDialogShownNumber) { analytic.reportEvent(Analytic.Streak.CAN_SHOW_DIALOG, streakDialogShownNumber + ""); put(PreferenceType.LOGIN, STREAK_DIALOG_SHOWN_TIMESTAMP, DateTimeHelper.INSTANCE.nowUtc()); put(PreferenceType.LOGIN, NUMBER_OF_SHOWN_STREAK_DIALOG, streakDialogShownNumber + 1); } public boolean isNotificationWasShown(NotificationDay day) { return getBoolean(PreferenceType.DEVICE_SPECIFIC, day.getInternalNotificationKey(), false); } public void setNotificationShown(NotificationDay day) { put(PreferenceType.DEVICE_SPECIFIC, day.getInternalNotificationKey(), true); } public int incrementNumberOfLaunches() { int numberOfLaunches = getInt(PreferenceType.DEVICE_SPECIFIC, USER_START_KEY); int newValue = numberOfLaunches + 1; put(PreferenceType.DEVICE_SPECIFIC, USER_START_KEY, newValue); return newValue; } public int getNumberOfLaunches() { return getInt(PreferenceType.DEVICE_SPECIFIC, USER_START_KEY); } public boolean isSDChosen() { //default is not. false -> sd is not chosen return getBoolean(PreferenceType.DEVICE_SPECIFIC, SD_CHOSEN); } public void setSDChosen(boolean isSdChosen) { put(PreferenceType.DEVICE_SPECIFIC, SD_CHOSEN, isSdChosen); } public boolean isNotificationVibrationDisabled() { //default is enabled return getBoolean(PreferenceType.DEVICE_SPECIFIC, NOTIFICATION_VIBRATION_DISABLED); } public void setNotificationVibrationDisabled(boolean isNotificationVibrationDisabled) { put(PreferenceType.DEVICE_SPECIFIC, NOTIFICATION_VIBRATION_DISABLED, isNotificationVibrationDisabled); } public boolean isNotificationDisabled(NotificationType type) { String resultKey = keyByNotificationType(type); if (resultKey == null) return true; return getBoolean(PreferenceType.DEVICE_SPECIFIC, resultKey); } @Nullable private String keyByNotificationType(NotificationType type) { switch (type) { case learn: return NOTIFICATION_LEARN_DISABLED; case teach: return NOTIFICATION_TEACH_DISABLED; case comments: return NOTIFICATION_COMMENT_DISABLED; case other: return NOTIFICATION_OTHER_DISABLED; case review: return NOTIFICATION_REVIEW_DISABLED; } return null; } public void setRotateAlways(boolean needRotate) { put(PreferenceType.DEVICE_SPECIFIC, ROTATE_PREF, needRotate); } public boolean needRotate() { return getBoolean(PreferenceType.DEVICE_SPECIFIC, ROTATE_PREF, true); } public void setNotificationDisabled(NotificationType type, boolean isNotificationDisabled) { String key = keyByNotificationType(type); if (key != null) { analytic.reportEventWithIdName(Analytic.Notification.PERSISTENT_KEY_NULL, "0", type.name()); put(PreferenceType.DEVICE_SPECIFIC, key, isNotificationDisabled); } } public boolean isNotificationSoundDisabled() { return getBoolean(PreferenceType.DEVICE_SPECIFIC, NOTIFICATION_SOUND_DISABLED); } public void setNotificationSoundDisabled(boolean isDisabled) { put(PreferenceType.DEVICE_SPECIFIC, NOTIFICATION_SOUND_DISABLED, isDisabled); } public boolean isOnboardingNotPassedYet() { // before onboarding App was tracked first time launch // for avoiding to show onboarding for old users this property is reused return getBoolean(PreferenceType.DEVICE_SPECIFIC, FIRST_TIME_LAUNCH, true); } public boolean isScheduleAdded() { return getBoolean(PreferenceType.DEVICE_SPECIFIC, SCHEDULED_LINK_CACHED, false); } public void afterScheduleAdded() { put(PreferenceType.DEVICE_SPECIFIC, SCHEDULED_LINK_CACHED, true); } public void afterOnboardingPassed() { put(PreferenceType.DEVICE_SPECIFIC, FIRST_TIME_LAUNCH, false); } public boolean isFirstAdaptiveCourse() { return getBoolean(PreferenceType.DEVICE_SPECIFIC, IS_FIRST_ADAPTIVE_COURSE, true); } public void afterAdaptiveOnboardingPassed() { put(PreferenceType.DEVICE_SPECIFIC, IS_FIRST_ADAPTIVE_COURSE, false); } public boolean isAdaptiveExpTooltipWasShown() { return getBoolean(PreferenceType.DEVICE_SPECIFIC, IS_ADAPTIVE_EXP_TOOLTIP_WAS_SHOWN, false); } public void afterAdaptiveExpTooltipWasShown() { put(PreferenceType.DEVICE_SPECIFIC, IS_ADAPTIVE_EXP_TOOLTIP_WAS_SHOWN, true); } public void setHasEverLogged() { put(PreferenceType.DEVICE_SPECIFIC, IS_EVER_LOGGED, true); } public boolean isEverLogged() { return getBoolean(PreferenceType.DEVICE_SPECIFIC, IS_EVER_LOGGED, false); } public boolean isNeedToShowVideoQualityExplanation() { return getBoolean(PreferenceType.DEVICE_SPECIFIC, VIDEO_QUALITY_EXPLANATION, true); } public boolean isKeepScreenOnSteps() { return getBoolean(PreferenceType.DEVICE_SPECIFIC, KEEP_SCREEN_ON_STEPS, true); } public void setKeepScreenOnSteps(boolean isChecked) { put(PreferenceType.DEVICE_SPECIFIC, KEEP_SCREEN_ON_STEPS, isChecked); } public boolean isAdaptiveModeEnabled() { return getBoolean(PreferenceType.DEVICE_SPECIFIC, IS_ADAPTIVE_MODE_ENABLED, true); } public void setAdaptiveModeEnabled(boolean isEnabled) { put(PreferenceType.DEVICE_SPECIFIC, IS_ADAPTIVE_MODE_ENABLED, isEnabled); } public void setNeedToShowVideoQualityExplanation(boolean needToShowCalendarWidget) { put(PreferenceType.DEVICE_SPECIFIC, VIDEO_QUALITY_EXPLANATION, needToShowCalendarWidget); } public boolean isNeedToShowCalendarWidget() { return getBoolean(PreferenceType.DEVICE_SPECIFIC, CALENDAR_WIDGET, true); } public boolean isShowDiscountingPolicyWarning() { return getBoolean(PreferenceType.DEVICE_SPECIFIC, DISCOUNTING_POLICY_DIALOG, true); } public void setNeedToShowCalendarWidget(boolean needToShowCalendarWidget) { put(PreferenceType.DEVICE_SPECIFIC, CALENDAR_WIDGET, needToShowCalendarWidget); } public void setShowDiscountingPolicyWarning(boolean needToShowCalendarWidget) { put(PreferenceType.DEVICE_SPECIFIC, DISCOUNTING_POLICY_DIALOG, needToShowCalendarWidget); } public boolean isNeedDropCoursesIn114() { return getBoolean(PreferenceType.DEVICE_SPECIFIC, NEED_DROP_114, true) || getBoolean(PreferenceType.DEVICE_SPECIFIC, NEED_DROP_116, true); } public void afterNeedDropCoursesIn114() { put(PreferenceType.DEVICE_SPECIFIC, NEED_DROP_114, false); put(PreferenceType.DEVICE_SPECIFIC, NEED_DROP_116, false); } private String mapToPreferenceName(StepikFilter filter) { switch (filter) { case RUSSIAN: return FILTER_RUSSIAN_LANGUAGE; case ENGLISH: return FILTER_ENGLISH_LANGUAGE; default: throw new IllegalArgumentException("Unknown StepikFilter type: " + filter); } } @NotNull public EnumSet<StepikFilter> getFilterForFeatured() { EnumSet<StepikFilter> filters = EnumSet.noneOf(StepikFilter.class); for (StepikFilter filter : StepikFilter.values()) { appendValueForFilter(filters, filter, defaultFilter.getDefaultFilter(filter)); } if (filters.size() > 1) { //only one of languages are allowed put(PreferenceType.FEATURED_FILTER, mapToPreferenceName(StepikFilter.ENGLISH), false); return EnumSet.of(StepikFilter.RUSSIAN); } return filters; } private void appendValueForFilter(EnumSet<StepikFilter> filter, StepikFilter value, boolean defaultValue) { if (getBoolean(PreferenceType.FEATURED_FILTER, mapToPreferenceName(value), defaultValue)) { filter.add(value); } } public void saveFilterForFeatured(EnumSet<StepikFilter> filters) { for (StepikFilter filterValue : StepikFilter.values()) { String key = mapToPreferenceName(filterValue); put(PreferenceType.FEATURED_FILTER, key, filters.contains(filterValue)); } } private enum PreferenceType { LOGIN("login preference"), WIFI("wifi_preference"), VIDEO_QUALITY("video_quality_preference"), TEMP("temporary"), VIDEO_SETTINGS("video_settings"), DEVICE_SPECIFIC("device_specific"), FEATURED_FILTER("featured_filter_prefs"); private String description; PreferenceType(String description) { this.description = description; } public String getStoreName() { return description; } } public DiscussionOrder getDiscussionOrder() { int orderId = getInt(PreferenceType.LOGIN, DISCUSSION_ORDER); DiscussionOrder order = DiscussionOrder.Companion.getById(orderId); analytic.reportEvent(Analytic.Comments.ORDER_TREND, order.toString()); return order; } public void setDiscussionOrder(DiscussionOrder disscussionOrder) { put(PreferenceType.LOGIN, DISCUSSION_ORDER, disscussionOrder.getId()); } public void setIsGcmTokenOk(boolean isGcmTokenOk) { put(PreferenceType.LOGIN, GCM_TOKEN_ACTUAL, isGcmTokenOk); } public boolean isGcmTokenOk() { return getBoolean(PreferenceType.LOGIN, GCM_TOKEN_ACTUAL); } public void setNotificationsCount(int count) { put(PreferenceType.LOGIN, NOTIFICATIONS_COUNT, count); } public int getNotificationsCount() { return getInt(PreferenceType.LOGIN, NOTIFICATIONS_COUNT, 0); } public void storeVideoPlaybackRate(@NotNull VideoPlaybackRate videoPlaybackRate) { int videoIndex = videoPlaybackRate.getIndex(); put(PreferenceType.VIDEO_SETTINGS, VIDEO_RATE_PREF_KEY, videoIndex); } @NotNull public VideoPlaybackRate getVideoPlaybackRate() { int index = getInt(PreferenceType.VIDEO_SETTINGS, VIDEO_RATE_PREF_KEY); for (VideoPlaybackRate item : VideoPlaybackRate.values()) { if (index == item.getIndex()) return item; } return VideoPlaybackRate.x1_0;//default } public boolean isOpenInExternal() { return getBoolean(PreferenceType.VIDEO_SETTINGS, VIDEO_EXTERNAL_PREF_KEY); } public void setOpenInExternal(boolean isOpenInExternal) { put(PreferenceType.VIDEO_SETTINGS, VIDEO_EXTERNAL_PREF_KEY, isOpenInExternal); } public void storeProfile(Profile profile) { //todo save picture of user profile //todo validate profile from the server with cached profile and make restore to cache. make //todo query when nav drawer is occurred? if (profile != null) { analytic.setUserId(profile.getId() + ""); } Gson gson = new Gson(); String json = gson.toJson(profile); put(PreferenceType.LOGIN, PROFILE_JSON, json); } @Nullable public Profile getProfile() { String json = getString(PreferenceType.LOGIN, PROFILE_JSON); if (json == null) { return null; } Gson gson = new GsonBuilder().create(); Profile result = gson.fromJson(json, Profile.class); return result; } public void storeEmailAddresses(List<EmailAddress> emailAddresses) { if (emailAddresses == null) return; Gson gson = new Gson(); String json = gson.toJson(emailAddresses); put(PreferenceType.LOGIN, EMAIL_LIST, json); } @Nullable public List<EmailAddress> getStoredEmails() { String json = getString(PreferenceType.LOGIN, EMAIL_LIST); if (json == null) { return null; } Gson gson = new GsonBuilder().create(); List<EmailAddress> result = null; try { result = gson.fromJson(json, new TypeToken<List<EmailAddress>>() { }.getType()); } catch (Exception e) { return null; } return result; } public void saveVideoQualityForPlaying(String videoQuality) { put(PreferenceType.VIDEO_QUALITY, VIDEO_QUALITY_KEY_FOR_PLAYING, videoQuality); } public void storeVideoQuality(String videoQuality) { put(PreferenceType.VIDEO_QUALITY, VIDEO_QUALITY_KEY, videoQuality); } public void storeTempPosition(int position) { put(PreferenceType.TEMP, TEMP_POSITION_KEY, position); } public int getTempPosition() { return getInt(PreferenceType.TEMP, TEMP_POSITION_KEY); } @NotNull public String getVideoQuality() { String str = getString(PreferenceType.VIDEO_QUALITY, VIDEO_QUALITY_KEY); if (str == null) { return AppConstants.DEFAULT_QUALITY; } else if (str.equals("1080")) { //it is hack for removing 1080 quality from dialogs return AppConstants.MAX_QUALITY; } else { return str; } } public String getVideoQualityForPlaying() { String str = getString(PreferenceType.VIDEO_QUALITY, VIDEO_QUALITY_KEY_FOR_PLAYING); if (str == null) { //by default high return AppConstants.MAX_QUALITY; } else { return str; } } public void storeAuthInfo(AuthenticationStepikResponse response) { Gson gson = new Gson(); String json = gson.toJson(response); put(PreferenceType.LOGIN, AUTH_RESPONSE_JSON, json); cachedAuthStepikResponse = response; long millisNow = DateTimeHelper.INSTANCE.nowUtc(); // we should use +0 UTC for avoid problems with TimeZones put(PreferenceType.LOGIN, ACCESS_TOKEN_TIMESTAMP, millisNow); put(PreferenceType.DEVICE_SPECIFIC, IS_EVER_LOGGED, true); } public void storeLastTokenType(boolean isSocial) { put(PreferenceType.LOGIN, IS_SOCIAL, isSocial); } public boolean isLastTokenSocial() { return getBoolean(PreferenceType.LOGIN, IS_SOCIAL); } public void deleteAuthInfo() { RWLocks.AuthLock.writeLock().lock(); try { Profile profile = getProfile(); String userId = "anon_prev"; if (profile != null) { userId += profile.getId(); } analytic.setUserId(userId); cachedAuthStepikResponse = null; clear(PreferenceType.LOGIN); clear(PreferenceType.FEATURED_FILTER); } finally { RWLocks.AuthLock.writeLock().unlock(); } } @Nullable public AuthenticationStepikResponse getAuthResponseFromStore() { if (cachedAuthStepikResponse != null) { return cachedAuthStepikResponse; } String json = getString(PreferenceType.LOGIN, AUTH_RESPONSE_JSON); if (json == null) { return null; } Gson gson = new GsonBuilder().create(); cachedAuthStepikResponse = gson.fromJson(json, AuthenticationStepikResponse.class); return cachedAuthStepikResponse; } public long getAccessTokenTimestamp() { long timestamp = getLong(PreferenceType.LOGIN, ACCESS_TOKEN_TIMESTAMP); return timestamp; } public boolean isMobileInternetAlsoAllowed() { return getBoolean(PreferenceType.WIFI, WIFI_KEY); } public void setMobileInternetAndWifiAllowed(boolean isOnlyWifi) { put(PreferenceType.WIFI, WIFI_KEY, isOnlyWifi); } private void put(PreferenceType type, String key, String value) { SharedPreferences.Editor editor = context.getSharedPreferences(type.getStoreName(), Context.MODE_PRIVATE).edit(); editor.putString(key, value).apply(); } private void put(PreferenceType type, String key, int value) { SharedPreferences.Editor editor = context.getSharedPreferences(type.getStoreName(), Context.MODE_PRIVATE).edit(); editor.putInt(key, value).apply(); } private void put(PreferenceType type, String key, long value) { SharedPreferences.Editor editor = context.getSharedPreferences(type.getStoreName(), Context.MODE_PRIVATE).edit(); editor.putLong(key, value).apply(); } private void put(PreferenceType type, String key, Boolean value) { SharedPreferences.Editor editor = context.getSharedPreferences(type.getStoreName(), Context.MODE_PRIVATE).edit(); editor.putBoolean(key, value).apply(); } private void clear(PreferenceType type) { SharedPreferences.Editor editor = context.getSharedPreferences(type.getStoreName(), Context.MODE_PRIVATE).edit(); editor.clear().apply(); } private int getInt(PreferenceType preferenceType, String key, int defaultValue) { return context.getSharedPreferences(preferenceType.getStoreName(), Context.MODE_PRIVATE) .getInt(key, defaultValue); } private int getInt(PreferenceType preferenceType, String key) { return context.getSharedPreferences(preferenceType.getStoreName(), Context.MODE_PRIVATE) .getInt(key, -1); } private long getLong(PreferenceType preferenceType, String key, long defaultValue) { return context.getSharedPreferences(preferenceType.getStoreName(), Context.MODE_PRIVATE) .getLong(key, defaultValue); } private long getLong(PreferenceType preferenceType, String key) { return context.getSharedPreferences(preferenceType.getStoreName(), Context.MODE_PRIVATE) .getLong(key, -1); } private String getString(PreferenceType preferenceType, String key) { return context.getSharedPreferences(preferenceType.getStoreName(), Context.MODE_PRIVATE) .getString(key, null); } private boolean getBoolean(PreferenceType preferenceType, String key) { return getBoolean(preferenceType, key, false); } private boolean getBoolean(PreferenceType preferenceType, String key, boolean defaultValue) { return context.getSharedPreferences(preferenceType.getStoreName(), Context.MODE_PRIVATE) .getBoolean(key, defaultValue); } }
app/src/main/java/org/stepic/droid/preferences/SharedPreferenceHelper.java
package org.stepic.droid.preferences; import android.content.Context; import android.content.SharedPreferences; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.stepic.droid.analytic.Analytic; import org.stepic.droid.core.DefaultFilter; import org.stepic.droid.di.AppSingleton; import org.stepic.droid.model.EmailAddress; import org.stepic.droid.model.Profile; import org.stepic.droid.model.StepikFilter; import org.stepic.droid.model.comments.DiscussionOrder; import org.stepic.droid.notifications.model.NotificationType; import org.stepic.droid.ui.util.TimeIntervalUtil; import org.stepic.droid.util.AppConstants; import org.stepic.droid.util.DateTimeHelper; import org.stepic.droid.util.RWLocks; import org.stepic.droid.web.AuthenticationStepikResponse; import java.util.EnumSet; import java.util.List; import javax.inject.Inject; @AppSingleton public class SharedPreferenceHelper { private static final String NOTIFICATION_SOUND_DISABLED = "notification_sound"; private static final String NEED_DROP_116 = "need_drop_116"; private static final String DISCOUNTING_POLICY_DIALOG = "discounting_pol_dialog"; private static final String KEEP_SCREEN_ON_STEPS = "keep_screen_on_steps"; private static final String IS_ADAPTIVE_MODE_ENABLED = "is_adaptive_mode_enabled"; private static final String IS_FIRST_ADAPTIVE_COURSE = "is_first_adaptive_course"; private static final String IS_ADAPTIVE_EXP_TOOLTIP_WAS_SHOWN = "is_adaptive_exp_tooltip_was_shown"; private static final String ROTATE_PREF = "rotate_pref"; private static final String NOTIFICATION_LEARN_DISABLED = "notification_disabled_by_user"; private static final String NOTIFICATION_COMMENT_DISABLED = "notification_comment_disabled"; private static final String NOTIFICATION_TEACH_DISABLED = "notification_teach_disabled"; private static final String NOTIFICATION_REVIEW_DISABLED = "notification_review_disabled"; private static final String NOTIFICATION_OTHER_DISABLED = "notification_other_disabled"; private static final String NOTIFICATION_VIBRATION_DISABLED = "not_vibrat_disabled"; private final static String ONE_DAY_NOTIFICATION = "one_day_notification"; private final static String SEVEN_DAY_NOTIFICATION = "seven_day_notification"; private static final String FILTER_RUSSIAN_LANGUAGE = "russian_lang"; private static final String FILTER_ENGLISH_LANGUAGE = "english_lang"; private static final String NOTIFICATIONS_COUNT = "notifications_count"; private static final String IS_EVER_LOGGED = "is_ever_logged"; private static final String IS_LANG_WIDGET_WAS_SHOWN_AFTER_LOGIN = "is_lang_widget_was_shown_after_login"; private static final String NEED_SHOW_LANG_WIDGET = "need_show_lang_widget"; private final String ACCESS_TOKEN_TIMESTAMP = "access_token_timestamp"; private final String AUTH_RESPONSE_JSON = "auth_response_json"; private final String PROFILE_JSON = "profile_json"; private final String EMAIL_LIST = "email_list"; private final String WIFI_KEY = "wifi_key"; private final String IS_SOCIAL = "is_social_key"; private final String VIDEO_QUALITY_KEY = "video_quality_key"; private final String VIDEO_QUALITY_KEY_FOR_PLAYING = "video_quality_key_for_playing"; private final String TEMP_POSITION_KEY = "temp_position_key"; private final String VIDEO_RATE_PREF_KEY = "video_rate_pref_key"; private final String VIDEO_EXTERNAL_PREF_KEY = "video_external_pref_key"; private final String GCM_TOKEN_ACTUAL = "gcm_token_actual_with_badges"; // '_with_badges' suffix was added to force update of gcm token to enable silent push with badge count, see #188 private final String SD_CHOSEN = "sd_chosen"; private final String FIRST_TIME_LAUNCH = "first_time_launch"; private final String SCHEDULED_LINK_CACHED = "scheduled_cached"; private final String DISCUSSION_ORDER = "discussion_order"; private final String CALENDAR_WIDGET = "calenda_widget"; private final String VIDEO_QUALITY_EXPLANATION = "video_quality_explanation"; private final String NEED_DROP_114 = "need_drop_114"; private final String REMIND_CLICK = "remind_click"; private final String ANY_STEP_SOLVED = "any_step_solved"; private final String NUMBER_OF_STEPS_SOLVED = "number_of_steps_solved"; private final String NEW_USER_ALARM_TIMESTAMP = "new_user_alarm_timestamp"; private final String REGISTRATION_ALARM_TIMESTAMP = "registration_alarm_timestamp"; private final String NUMBER_OF_SHOWN_STREAK_DIALOG = "number_of_shown_streak_dialog"; private final String STREAK_DIALOG_SHOWN_TIMESTAMP = "streak_dialog_shown_timestamp"; private final String STREAK_NUMBER_OF_IGNORED = "streak_number_of_ignored"; private final String TIME_NOTIFICATION_CODE = "time_notification_code"; private final String STREAK_NOTIFICATION = "streak_notification"; private final String USER_START_KEY = "user_start_app"; private final String RATE_LAST_TIMESTAMP = "rate_last_timestamp"; private final String RATE_TIMES_SHOWN = "rate_times_shown"; private final String RATE_WAS_HANDLED = "rate_was_handled"; private AuthenticationStepikResponse cachedAuthStepikResponse = null; private final Context context; private final Analytic analytic; private final DefaultFilter defaultFilter; public enum NotificationDay { DAY_ONE(ONE_DAY_NOTIFICATION), DAY_SEVEN(SEVEN_DAY_NOTIFICATION); private String internalNotificationKey; NotificationDay(String notificationKey) { this.internalNotificationKey = notificationKey; } public String getInternalNotificationKey() { return internalNotificationKey; } } @Inject public SharedPreferenceHelper(Analytic analytic, DefaultFilter defaultFilter, Context context) { this.analytic = analytic; this.defaultFilter = defaultFilter; this.context = context; } /** * call when user click Google Play or Support at rate Dialog */ public void afterRateWasHandled() { put(PreferenceType.DEVICE_SPECIFIC, RATE_WAS_HANDLED, true); } public boolean wasRateHandled() { return getBoolean(PreferenceType.DEVICE_SPECIFIC, RATE_WAS_HANDLED); } public void rateShown(long timeMillis) { put(PreferenceType.DEVICE_SPECIFIC, RATE_LAST_TIMESTAMP, timeMillis); long times = getLong(PreferenceType.DEVICE_SPECIFIC, RATE_TIMES_SHOWN, 0); put(PreferenceType.DEVICE_SPECIFIC, RATE_TIMES_SHOWN, times + 1); } /** * @return last timestamp, when it was shown, -1 when it has never been shown */ public long whenRateWasShown() { return getLong(PreferenceType.DEVICE_SPECIFIC, RATE_LAST_TIMESTAMP, -1); } public long howManyRateWasShownBefore() { return getLong(PreferenceType.DEVICE_SPECIFIC, RATE_TIMES_SHOWN, 0); } public void incrementNumberOfNotifications() { int numberOfIgnored = getInt(PreferenceType.LOGIN, STREAK_NUMBER_OF_IGNORED, 0); numberOfIgnored++; put(PreferenceType.LOGIN, STREAK_NUMBER_OF_IGNORED, numberOfIgnored); } public void resetNumberOfStreakNotifications() { put(PreferenceType.LOGIN, STREAK_NUMBER_OF_IGNORED, 0); } public int getNumberOfStreakNotifications() { return getInt(PreferenceType.LOGIN, STREAK_NUMBER_OF_IGNORED, 0); } public boolean anyStepIsSolved() { return getBoolean(PreferenceType.LOGIN, ANY_STEP_SOLVED, false); } public void trackWhenUserSolved() { put(PreferenceType.LOGIN, ANY_STEP_SOLVED, true); } public void incrementUserSolved() { long userSolved = getLong(PreferenceType.LOGIN, NUMBER_OF_STEPS_SOLVED, 0); put(PreferenceType.LOGIN, NUMBER_OF_STEPS_SOLVED, userSolved + 1); } public long numberOfSolved() { return getLong(PreferenceType.LOGIN, NUMBER_OF_STEPS_SOLVED, 0); } public void saveNewUserRemindTimestamp(long scheduleMillis) { put(PreferenceType.DEVICE_SPECIFIC, NEW_USER_ALARM_TIMESTAMP, scheduleMillis); } public long getNewUserRemindTimestamp() { return getLong(PreferenceType.DEVICE_SPECIFIC, NEW_USER_ALARM_TIMESTAMP); } public void saveRegistrationRemindTimestamp(long scheduleMillis) { put(PreferenceType.DEVICE_SPECIFIC, REGISTRATION_ALARM_TIMESTAMP, scheduleMillis); } public long getRegistrationRemindTimestamp() { return getLong(PreferenceType.DEVICE_SPECIFIC, REGISTRATION_ALARM_TIMESTAMP); } /** * Lang widget should be kept the whole session after first time catalog was opened after new login */ public boolean isNeedShowLangWidget() { boolean isLangWidgetWasShown = getBoolean(PreferenceType.LOGIN, IS_LANG_WIDGET_WAS_SHOWN_AFTER_LOGIN, false); if (!isLangWidgetWasShown) { put(PreferenceType.LOGIN, IS_LANG_WIDGET_WAS_SHOWN_AFTER_LOGIN, true); put(PreferenceType.LOGIN, NEED_SHOW_LANG_WIDGET, true); } return getBoolean(PreferenceType.LOGIN, NEED_SHOW_LANG_WIDGET, true); } public void onSessionAfterLogin() { put(PreferenceType.LOGIN, IS_LANG_WIDGET_WAS_SHOWN_AFTER_LOGIN, false); } public void onNewSession() { put(PreferenceType.LOGIN, NEED_SHOW_LANG_WIDGET, false); } public void clickEnrollNotification(long timestamp) { put(PreferenceType.DEVICE_SPECIFIC, REMIND_CLICK, timestamp); } @Nullable public Long getLastClickEnrollNotification() { long lastClickNotificationRemind = getLong(PreferenceType.DEVICE_SPECIFIC, REMIND_CLICK); if (lastClickNotificationRemind <= 0) { return null; } else { return lastClickNotificationRemind; } } public int getTimeNotificationCode() { return getInt(PreferenceType.LOGIN, TIME_NOTIFICATION_CODE, TimeIntervalUtil.INSTANCE.getDefaultTimeCode()); } public void setTimeNotificationCode(int value) { put(PreferenceType.LOGIN, TIME_NOTIFICATION_CODE, value); } public boolean isStreakNotificationEnabled() { int simpleCode = getInt(PreferenceType.LOGIN, STREAK_NOTIFICATION, -1); return simpleCode > 0; } /** * Null by default */ @Nullable public Boolean isStreakNotificationEnabledNullable() { int codeInt = getInt(PreferenceType.LOGIN, STREAK_NOTIFICATION, -1); if (codeInt > 0) { return true; } else if (codeInt == 0) { return false; } else { return null; } } public void setStreakNotificationEnabled(boolean value) { put(PreferenceType.LOGIN, STREAK_NOTIFICATION, value ? 1 : 0); resetNumberOfStreakNotifications(); } public boolean canShowStreakDialog() { int streakDialogShownNumber = getInt(PreferenceType.LOGIN, NUMBER_OF_SHOWN_STREAK_DIALOG, 0); if (streakDialogShownNumber > AppConstants.MAX_NUMBER_OF_SHOWING_STREAK_DIALOG) { return false; } else { long millis = getLong(PreferenceType.LOGIN, STREAK_DIALOG_SHOWN_TIMESTAMP, -1L); if (millis < 0) { onShowStreakDialog(streakDialogShownNumber); // first time return true; } else { long calculatedMillis = millis + AppConstants.NUMBER_OF_DAYS_BETWEEN_STREAK_SHOWING * AppConstants.MILLIS_IN_24HOURS; if (DateTimeHelper.INSTANCE.isBeforeNowUtc(calculatedMillis)) { //we can show onShowStreakDialog(streakDialogShownNumber); return true; } else { return false; } } } } private void onShowStreakDialog(int streakDialogShownNumber) { analytic.reportEvent(Analytic.Streak.CAN_SHOW_DIALOG, streakDialogShownNumber + ""); put(PreferenceType.LOGIN, STREAK_DIALOG_SHOWN_TIMESTAMP, DateTimeHelper.INSTANCE.nowUtc()); put(PreferenceType.LOGIN, NUMBER_OF_SHOWN_STREAK_DIALOG, streakDialogShownNumber + 1); } public boolean isNotificationWasShown(NotificationDay day) { return getBoolean(PreferenceType.DEVICE_SPECIFIC, day.getInternalNotificationKey(), false); } public void setNotificationShown(NotificationDay day) { put(PreferenceType.DEVICE_SPECIFIC, day.getInternalNotificationKey(), true); } public int incrementNumberOfLaunches() { int numberOfLaunches = getInt(PreferenceType.DEVICE_SPECIFIC, USER_START_KEY); int newValue = numberOfLaunches + 1; put(PreferenceType.DEVICE_SPECIFIC, USER_START_KEY, newValue); return newValue; } public int getNumberOfLaunches() { return getInt(PreferenceType.DEVICE_SPECIFIC, USER_START_KEY); } public boolean isSDChosen() { //default is not. false -> sd is not chosen return getBoolean(PreferenceType.DEVICE_SPECIFIC, SD_CHOSEN); } public void setSDChosen(boolean isSdChosen) { put(PreferenceType.DEVICE_SPECIFIC, SD_CHOSEN, isSdChosen); } public boolean isNotificationVibrationDisabled() { //default is enabled return getBoolean(PreferenceType.DEVICE_SPECIFIC, NOTIFICATION_VIBRATION_DISABLED); } public void setNotificationVibrationDisabled(boolean isNotificationVibrationDisabled) { put(PreferenceType.DEVICE_SPECIFIC, NOTIFICATION_VIBRATION_DISABLED, isNotificationVibrationDisabled); } public boolean isNotificationDisabled(NotificationType type) { String resultKey = keyByNotificationType(type); if (resultKey == null) return true; return getBoolean(PreferenceType.DEVICE_SPECIFIC, resultKey); } @Nullable private String keyByNotificationType(NotificationType type) { switch (type) { case learn: return NOTIFICATION_LEARN_DISABLED; case teach: return NOTIFICATION_TEACH_DISABLED; case comments: return NOTIFICATION_COMMENT_DISABLED; case other: return NOTIFICATION_OTHER_DISABLED; case review: return NOTIFICATION_REVIEW_DISABLED; } return null; } public void setRotateAlways(boolean needRotate) { put(PreferenceType.DEVICE_SPECIFIC, ROTATE_PREF, needRotate); } public boolean needRotate() { return getBoolean(PreferenceType.DEVICE_SPECIFIC, ROTATE_PREF, true); } public void setNotificationDisabled(NotificationType type, boolean isNotificationDisabled) { String key = keyByNotificationType(type); if (key != null) { analytic.reportEventWithIdName(Analytic.Notification.PERSISTENT_KEY_NULL, "0", type.name()); put(PreferenceType.DEVICE_SPECIFIC, key, isNotificationDisabled); } } public boolean isNotificationSoundDisabled() { return getBoolean(PreferenceType.DEVICE_SPECIFIC, NOTIFICATION_SOUND_DISABLED); } public void setNotificationSoundDisabled(boolean isDisabled) { put(PreferenceType.DEVICE_SPECIFIC, NOTIFICATION_SOUND_DISABLED, isDisabled); } public boolean isOnboardingNotPassedYet() { // before onboarding App was tracked first time launch // for avoiding to show onboarding for old users this property is reused return getBoolean(PreferenceType.DEVICE_SPECIFIC, FIRST_TIME_LAUNCH, true); } public boolean isScheduleAdded() { return getBoolean(PreferenceType.DEVICE_SPECIFIC, SCHEDULED_LINK_CACHED, false); } public void afterScheduleAdded() { put(PreferenceType.DEVICE_SPECIFIC, SCHEDULED_LINK_CACHED, true); } public void afterOnboardingPassed() { put(PreferenceType.DEVICE_SPECIFIC, FIRST_TIME_LAUNCH, false); } public boolean isFirstAdaptiveCourse() { return getBoolean(PreferenceType.DEVICE_SPECIFIC, IS_FIRST_ADAPTIVE_COURSE, true); } public void afterAdaptiveOnboardingPassed() { put(PreferenceType.DEVICE_SPECIFIC, IS_FIRST_ADAPTIVE_COURSE, false); } public boolean isAdaptiveExpTooltipWasShown() { return getBoolean(PreferenceType.DEVICE_SPECIFIC, IS_ADAPTIVE_EXP_TOOLTIP_WAS_SHOWN, false); } public void afterAdaptiveExpTooltipWasShown() { put(PreferenceType.DEVICE_SPECIFIC, IS_ADAPTIVE_EXP_TOOLTIP_WAS_SHOWN, true); } public void setHasEverLogged() { put(PreferenceType.DEVICE_SPECIFIC, IS_EVER_LOGGED, true); } public boolean isEverLogged() { return getBoolean(PreferenceType.DEVICE_SPECIFIC, IS_EVER_LOGGED, false); } public boolean isNeedToShowVideoQualityExplanation() { return getBoolean(PreferenceType.DEVICE_SPECIFIC, VIDEO_QUALITY_EXPLANATION, true); } public boolean isKeepScreenOnSteps() { return getBoolean(PreferenceType.DEVICE_SPECIFIC, KEEP_SCREEN_ON_STEPS, true); } public void setKeepScreenOnSteps(boolean isChecked) { put(PreferenceType.DEVICE_SPECIFIC, KEEP_SCREEN_ON_STEPS, isChecked); } public boolean isAdaptiveModeEnabled() { return getBoolean(PreferenceType.DEVICE_SPECIFIC, IS_ADAPTIVE_MODE_ENABLED, true); } public void setAdaptiveModeEnabled(boolean isEnabled) { put(PreferenceType.DEVICE_SPECIFIC, IS_ADAPTIVE_MODE_ENABLED, isEnabled); } public void setNeedToShowVideoQualityExplanation(boolean needToShowCalendarWidget) { put(PreferenceType.DEVICE_SPECIFIC, VIDEO_QUALITY_EXPLANATION, needToShowCalendarWidget); } public boolean isNeedToShowCalendarWidget() { return getBoolean(PreferenceType.DEVICE_SPECIFIC, CALENDAR_WIDGET, true); } public boolean isShowDiscountingPolicyWarning() { return getBoolean(PreferenceType.DEVICE_SPECIFIC, DISCOUNTING_POLICY_DIALOG, true); } public void setNeedToShowCalendarWidget(boolean needToShowCalendarWidget) { put(PreferenceType.DEVICE_SPECIFIC, CALENDAR_WIDGET, needToShowCalendarWidget); } public void setShowDiscountingPolicyWarning(boolean needToShowCalendarWidget) { put(PreferenceType.DEVICE_SPECIFIC, DISCOUNTING_POLICY_DIALOG, needToShowCalendarWidget); } public boolean isNeedDropCoursesIn114() { return getBoolean(PreferenceType.DEVICE_SPECIFIC, NEED_DROP_114, true) || getBoolean(PreferenceType.DEVICE_SPECIFIC, NEED_DROP_116, true); } public void afterNeedDropCoursesIn114() { put(PreferenceType.DEVICE_SPECIFIC, NEED_DROP_114, false); put(PreferenceType.DEVICE_SPECIFIC, NEED_DROP_116, false); } private String mapToPreferenceName(StepikFilter filter) { switch (filter) { case RUSSIAN: return FILTER_RUSSIAN_LANGUAGE; case ENGLISH: return FILTER_ENGLISH_LANGUAGE; default: throw new IllegalArgumentException("Unknown StepikFilter type: " + filter); } } @NotNull public EnumSet<StepikFilter> getFilterForFeatured() { EnumSet<StepikFilter> filters = EnumSet.noneOf(StepikFilter.class); for (StepikFilter filter : StepikFilter.values()) { appendValueForFilter(filters, filter, defaultFilter.getDefaultFilter(filter)); } if (filters.size() > 1) { //only one of languages are allowed put(PreferenceType.FEATURED_FILTER, mapToPreferenceName(StepikFilter.ENGLISH), false); return EnumSet.of(StepikFilter.RUSSIAN); } return filters; } private void appendValueForFilter(EnumSet<StepikFilter> filter, StepikFilter value, boolean defaultValue) { if (getBoolean(PreferenceType.FEATURED_FILTER, mapToPreferenceName(value), defaultValue)) { filter.add(value); } } public void saveFilterForFeatured(EnumSet<StepikFilter> filters) { for (StepikFilter filterValue : StepikFilter.values()) { String key = mapToPreferenceName(filterValue); put(PreferenceType.FEATURED_FILTER, key, filters.contains(filterValue)); } } private enum PreferenceType { LOGIN("login preference"), WIFI("wifi_preference"), VIDEO_QUALITY("video_quality_preference"), TEMP("temporary"), VIDEO_SETTINGS("video_settings"), DEVICE_SPECIFIC("device_specific"), FEATURED_FILTER("featured_filter_prefs"); private String description; PreferenceType(String description) { this.description = description; } public String getStoreName() { return description; } } public DiscussionOrder getDiscussionOrder() { int orderId = getInt(PreferenceType.LOGIN, DISCUSSION_ORDER); DiscussionOrder order = DiscussionOrder.Companion.getById(orderId); analytic.reportEvent(Analytic.Comments.ORDER_TREND, order.toString()); return order; } public void setDiscussionOrder(DiscussionOrder disscussionOrder) { put(PreferenceType.LOGIN, DISCUSSION_ORDER, disscussionOrder.getId()); } public void setIsGcmTokenOk(boolean isGcmTokenOk) { put(PreferenceType.LOGIN, GCM_TOKEN_ACTUAL, isGcmTokenOk); } public boolean isGcmTokenOk() { return getBoolean(PreferenceType.LOGIN, GCM_TOKEN_ACTUAL); } public void setNotificationsCount(int count) { put(PreferenceType.LOGIN, NOTIFICATIONS_COUNT, count); } public int getNotificationsCount() { return getInt(PreferenceType.LOGIN, NOTIFICATIONS_COUNT, 0); } public void storeVideoPlaybackRate(@NotNull VideoPlaybackRate videoPlaybackRate) { int videoIndex = videoPlaybackRate.getIndex(); put(PreferenceType.VIDEO_SETTINGS, VIDEO_RATE_PREF_KEY, videoIndex); } @NotNull public VideoPlaybackRate getVideoPlaybackRate() { int index = getInt(PreferenceType.VIDEO_SETTINGS, VIDEO_RATE_PREF_KEY); for (VideoPlaybackRate item : VideoPlaybackRate.values()) { if (index == item.getIndex()) return item; } return VideoPlaybackRate.x1_0;//default } public boolean isOpenInExternal() { return getBoolean(PreferenceType.VIDEO_SETTINGS, VIDEO_EXTERNAL_PREF_KEY); } public void setOpenInExternal(boolean isOpenInExternal) { put(PreferenceType.VIDEO_SETTINGS, VIDEO_EXTERNAL_PREF_KEY, isOpenInExternal); } public void storeProfile(Profile profile) { //todo save picture of user profile //todo validate profile from the server with cached profile and make restore to cache. make //todo query when nav drawer is occurred? if (profile != null) { analytic.setUserId(profile.getId() + ""); } Gson gson = new Gson(); String json = gson.toJson(profile); put(PreferenceType.LOGIN, PROFILE_JSON, json); } @Nullable public Profile getProfile() { String json = getString(PreferenceType.LOGIN, PROFILE_JSON); if (json == null) { return null; } Gson gson = new GsonBuilder().create(); Profile result = gson.fromJson(json, Profile.class); return result; } public void storeEmailAddresses(List<EmailAddress> emailAddresses) { if (emailAddresses == null) return; Gson gson = new Gson(); String json = gson.toJson(emailAddresses); put(PreferenceType.LOGIN, EMAIL_LIST, json); } @Nullable public List<EmailAddress> getStoredEmails() { String json = getString(PreferenceType.LOGIN, EMAIL_LIST); if (json == null) { return null; } Gson gson = new GsonBuilder().create(); List<EmailAddress> result = null; try { result = gson.fromJson(json, new TypeToken<List<EmailAddress>>() { }.getType()); } catch (Exception e) { return null; } return result; } public void saveVideoQualityForPlaying(String videoQuality) { put(PreferenceType.VIDEO_QUALITY, VIDEO_QUALITY_KEY_FOR_PLAYING, videoQuality); } public void storeVideoQuality(String videoQuality) { put(PreferenceType.VIDEO_QUALITY, VIDEO_QUALITY_KEY, videoQuality); } public void storeTempPosition(int position) { put(PreferenceType.TEMP, TEMP_POSITION_KEY, position); } public int getTempPosition() { return getInt(PreferenceType.TEMP, TEMP_POSITION_KEY); } @NotNull public String getVideoQuality() { String str = getString(PreferenceType.VIDEO_QUALITY, VIDEO_QUALITY_KEY); if (str == null) { return AppConstants.DEFAULT_QUALITY; } else if (str.equals("1080")) { //it is hack for removing 1080 quality from dialogs return AppConstants.MAX_QUALITY; } else { return str; } } public String getVideoQualityForPlaying() { String str = getString(PreferenceType.VIDEO_QUALITY, VIDEO_QUALITY_KEY_FOR_PLAYING); if (str == null) { //by default high return AppConstants.MAX_QUALITY; } else { return str; } } public void storeAuthInfo(AuthenticationStepikResponse response) { Gson gson = new Gson(); String json = gson.toJson(response); put(PreferenceType.LOGIN, AUTH_RESPONSE_JSON, json); cachedAuthStepikResponse = response; long millisNow = DateTimeHelper.INSTANCE.nowUtc(); // we should use +0 UTC for avoid problems with TimeZones put(PreferenceType.LOGIN, ACCESS_TOKEN_TIMESTAMP, millisNow); put(PreferenceType.DEVICE_SPECIFIC, IS_EVER_LOGGED, true); } public void storeLastTokenType(boolean isSocial) { put(PreferenceType.LOGIN, IS_SOCIAL, isSocial); } public boolean isLastTokenSocial() { return getBoolean(PreferenceType.LOGIN, IS_SOCIAL); } public void deleteAuthInfo() { RWLocks.AuthLock.writeLock().lock(); try { Profile profile = getProfile(); String userId = "anon_prev"; if (profile != null) { userId += profile.getId(); } analytic.setUserId(userId); cachedAuthStepikResponse = null; clear(PreferenceType.LOGIN); clear(PreferenceType.FEATURED_FILTER); } finally { RWLocks.AuthLock.writeLock().unlock(); } } @Nullable public AuthenticationStepikResponse getAuthResponseFromStore() { if (cachedAuthStepikResponse != null) { return cachedAuthStepikResponse; } String json = getString(PreferenceType.LOGIN, AUTH_RESPONSE_JSON); if (json == null) { return null; } Gson gson = new GsonBuilder().create(); cachedAuthStepikResponse = gson.fromJson(json, AuthenticationStepikResponse.class); return cachedAuthStepikResponse; } public long getAccessTokenTimestamp() { long timestamp = getLong(PreferenceType.LOGIN, ACCESS_TOKEN_TIMESTAMP); return timestamp; } public boolean isMobileInternetAlsoAllowed() { return getBoolean(PreferenceType.WIFI, WIFI_KEY); } public void setMobileInternetAndWifiAllowed(boolean isOnlyWifi) { put(PreferenceType.WIFI, WIFI_KEY, isOnlyWifi); } private void put(PreferenceType type, String key, String value) { SharedPreferences.Editor editor = context.getSharedPreferences(type.getStoreName(), Context.MODE_PRIVATE).edit(); editor.putString(key, value).apply(); } private void put(PreferenceType type, String key, int value) { SharedPreferences.Editor editor = context.getSharedPreferences(type.getStoreName(), Context.MODE_PRIVATE).edit(); editor.putInt(key, value).apply(); } private void put(PreferenceType type, String key, long value) { SharedPreferences.Editor editor = context.getSharedPreferences(type.getStoreName(), Context.MODE_PRIVATE).edit(); editor.putLong(key, value).apply(); } private void put(PreferenceType type, String key, Boolean value) { SharedPreferences.Editor editor = context.getSharedPreferences(type.getStoreName(), Context.MODE_PRIVATE).edit(); editor.putBoolean(key, value).apply(); } private void clear(PreferenceType type) { SharedPreferences.Editor editor = context.getSharedPreferences(type.getStoreName(), Context.MODE_PRIVATE).edit(); editor.clear().apply(); } private int getInt(PreferenceType preferenceType, String key, int defaultValue) { return context.getSharedPreferences(preferenceType.getStoreName(), Context.MODE_PRIVATE) .getInt(key, defaultValue); } private int getInt(PreferenceType preferenceType, String key) { return context.getSharedPreferences(preferenceType.getStoreName(), Context.MODE_PRIVATE) .getInt(key, -1); } private long getLong(PreferenceType preferenceType, String key, long defaultValue) { return context.getSharedPreferences(preferenceType.getStoreName(), Context.MODE_PRIVATE) .getLong(key, defaultValue); } private long getLong(PreferenceType preferenceType, String key) { return context.getSharedPreferences(preferenceType.getStoreName(), Context.MODE_PRIVATE) .getLong(key, -1); } private String getString(PreferenceType preferenceType, String key) { return context.getSharedPreferences(preferenceType.getStoreName(), Context.MODE_PRIVATE) .getString(key, null); } private boolean getBoolean(PreferenceType preferenceType, String key) { return getBoolean(preferenceType, key, false); } private boolean getBoolean(PreferenceType preferenceType, String key, boolean defaultValue) { return context.getSharedPreferences(preferenceType.getStoreName(), Context.MODE_PRIVATE) .getBoolean(key, defaultValue); } }
track streak notifications enabled property
app/src/main/java/org/stepic/droid/preferences/SharedPreferenceHelper.java
track streak notifications enabled property