answer
stringlengths
17
10.2M
package company.com.gitdemo; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Toast; import android.widget.Button; public class GitActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_git); Button button = (Button) findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(GitActivity.this, "Hey", Toast.LENGTH_SHORT).show(); } }); } // New comment // Fuck ur skins @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_git, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
package io.spine.server.delivery; import com.google.errorprone.annotations.Immutable; import io.spine.base.EventMessage; /** * A marker interface for the signals controlling the execution of catch-up processes. */ @Immutable public interface CatchUpSignal extends EventMessage { /** * Obtains the identifier of the {@link CatchUp} to which this signal relates. */ CatchUpId getId(); }
package io.spine.server.storage; import com.google.common.base.MoreObjects; import com.google.errorprone.annotations.Immutable; import io.spine.annotation.Internal; import io.spine.server.entity.storage.ColumnName; /** * An abstract base for different column types. */ @Immutable @Internal @SuppressWarnings("AbstractClassWithoutAbstractMethods") // Prevent instantiation in favor of concrete column types. public abstract class AbstractColumn implements Column { private final ColumnName name; private final Class<?> type; protected AbstractColumn(ColumnName name, Class<?> type) { this.name = name; this.type = type; } @Override public ColumnName name() { return name; } @Override public Class<?> type() { return type; } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("name", name) .add("type", type) .toString(); } }
package com.uber.okbuck.core.util; import java.io.File; import java.util.Map; import java.util.stream.Stream; import com.android.build.gradle.AppPlugin; import com.android.build.gradle.LibraryPlugin; import com.uber.okbuck.OkBuckGradlePlugin; import com.uber.okbuck.core.dependency.DependencyCache; import com.uber.okbuck.core.model.base.ProjectType; import com.uber.okbuck.core.model.base.Scope; import com.uber.okbuck.core.model.base.Target; import com.uber.okbuck.core.model.base.TargetCache; import org.gradle.api.Project; import org.gradle.api.artifacts.component.ModuleComponentIdentifier; import org.gradle.api.plugins.GroovyPlugin; import org.gradle.api.plugins.JavaPlugin; import org.gradle.api.plugins.PluginContainer; import org.gradle.api.plugins.scala.ScalaPlugin; import org.jetbrains.annotations.Nullable; import org.jetbrains.kotlin.gradle.plugin.KotlinPluginWrapper; public final class ProjectUtil { private ProjectUtil() {} public static ProjectType getType(Project project) { PluginContainer plugins = project.getPlugins(); if (plugins.hasPlugin(AppPlugin.class)) { return ProjectType.ANDROID_APP; } else if (plugins.hasPlugin(LibraryPlugin.class)) { return ProjectType.ANDROID_LIB; } else if (plugins.hasPlugin(GroovyPlugin.class)) { return ProjectType.GROOVY_LIB; } else if (plugins.hasPlugin(KotlinPluginWrapper.class)) { return ProjectType.KOTLIN_LIB; } else if (plugins.hasPlugin(ScalaPlugin.class)) { return ProjectType.SCALA_LIB; } else if (plugins.hasPlugin(JavaPlugin.class)) { return ProjectType.JAVA_LIB; } else { return ProjectType.UNKNOWN; } } public static DependencyCache getDependencyCache(Project project) { return getPlugin(project).depCache; } public static Map<String, Target> getTargets(Project project) { return getTargetCache(project).getTargets(project); } @Nullable public static Target getTargetForOutput(Project targetProject, File output) { return getTargetCache(targetProject).getTargetForOutput(targetProject, output); } public static Map<Project, Map<String, Scope>> getScopes(Project project) { return getPlugin(project).scopes; } static OkBuckGradlePlugin getPlugin(Project project) { return project.getRootProject().getPlugins().getPlugin(OkBuckGradlePlugin.class); } private static TargetCache getTargetCache(Project project) { return getPlugin(project).targetCache; } @Nullable static String findVersionInClasspath(Project project, String group, String module) { return project.getBuildscript() .getConfigurations() .getByName("classpath") .getIncoming() .getArtifacts() .getArtifacts() .stream() .flatMap(artifactResult -> artifactResult.getId().getComponentIdentifier() instanceof ModuleComponentIdentifier ? Stream.of((ModuleComponentIdentifier) artifactResult.getId().getComponentIdentifier()) : Stream.empty()) .filter(identifier -> (group.equals(identifier.getGroup()) && module.equals(identifier.getModule()))) .findFirst() .map(ModuleComponentIdentifier::getVersion) .orElse(null); } }
package org.jscsi.testing; import static org.testng.Assert.assertTrue; import java.io.File; import java.io.IOException; import java.nio.ByteBuffer; import java.util.Random; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import javax.xml.parsers.ParserConfigurationException; import org.jscsi.exception.ConfigurationException; import org.jscsi.exception.TaskExecutionException; import org.jscsi.initiator.Configuration; import org.jscsi.initiator.Initiator; import org.jscsi.initiator.LinkFactory; import org.jscsi.initiator.connection.Session; import org.jscsi.target.TargetServer; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.xml.sax.SAXException; /** * This test suite independently test the initiatior against a dynamically * generated target. * * Throughout the project a lot of tests have been set in aspects. * * @author Andreas Rain * */ public class BlackBoxTest { /** Name of the device name on the iSCSI Target. */ private static final String TARGET_DRIVE_NAME = "testing-xen2-disk1"; /** The size (in bytes) of the buffer to use for reads and writes. */ private static final int BUFFER_SIZE = 46 * 1024; /** The logical block address of the start block to begin an operation. */ private static final int LOGICAL_BLOCK_ADDRESS = 20; /** The initiator object. */ private static Initiator initiator; /** The session object **/ private static Session session; /** The linkfactory object **/ private static LinkFactory factory; /** Initiator configuration */ private static Configuration configuration; /** Buffer, which is used for storing a read operation. */ private static ByteBuffer readBuffer; /** Buffer, which is used for storing a write operation. */ private static ByteBuffer writeBuffer; /** The random number generator to fill the buffer to send. */ private static Random randomGenerator; /** An instance of the target will be dynamically created */ private static TargetServer target; /** The targets configuration file */ private static File targetConfigurationFile; /** * The relative path (to the project) of the main directory of all * configuration files. */ private static final File CONFIG_DIR = new File(new StringBuilder("src").append(File.separator).append( "test").append(File.separator).append("resources").append(File.separator).toString()); /** * A helping class to start the target in a threadpool so the tests can run * next to it. * */ public static class CallableStart { static ExecutorService threadPool; /** * This method starts a targetserver in a threadpool. * * @throws SAXException * @throws ParserConfigurationException * @throws IOException * @throws ConfigurationException */ public static void start() throws Exception { if (isWindows()) { targetConfigurationFile = new File(CONFIG_DIR, "jscsi-target-windows.xml"); } else { targetConfigurationFile = new File(CONFIG_DIR, "jscsi-target-linux.xml"); } org.jscsi.target.Configuration targetConfiguration = org.jscsi.target.Configuration.create(new File(CONFIG_DIR, "jscsi-target.xsd"), targetConfigurationFile); target = new TargetServer(targetConfiguration); // Getting an Executor threadPool = Executors.newSingleThreadExecutor(); // Starting the target threadPool.submit(target); } /** * After the tests are finished shutdown the threadpool. */ public static void stop() { threadPool.shutdown(); } } @BeforeClass public static final void initialize() throws Exception { CallableStart.start(); configuration = Configuration.create(new File(CONFIG_DIR, "jscsi.xsd"), new File(CONFIG_DIR, "jscsi.xml")); initiator = new Initiator(configuration); readBuffer = ByteBuffer.allocate(BUFFER_SIZE); writeBuffer = ByteBuffer.allocate(BUFFER_SIZE); randomGenerator = new Random(System.currentTimeMillis()); randomGenerator.nextBytes(writeBuffer.array()); factory = new LinkFactory(initiator); session = factory.getSession(configuration, TARGET_DRIVE_NAME, configuration .getTargetAddress(TARGET_DRIVE_NAME)); } @AfterClass public static final void close() throws Exception { // initiator.closeSession(TARGET_DRIVE_NAME); session.logout(); session.close(); CallableStart.stop(); } /** * This test checks if a written bytebuffer still is the same when being * read from the target. * * @throws Exception */ @Test public final void testReadWriteEquality() throws Exception { Future<Void> returnVal1 = session.write(writeBuffer, LOGICAL_BLOCK_ADDRESS, writeBuffer.remaining()); returnVal1.get(); assertTrue(!writeBuffer.equals(readBuffer)); Future<Void> returnVal2 = session.read(readBuffer, LOGICAL_BLOCK_ADDRESS, readBuffer.remaining()); returnVal2.get(); assertTrue(writeBuffer.equals(readBuffer)); writeBuffer.flip(); readBuffer.flip(); assertTrue(writeBuffer.equals(readBuffer)); } /** * This test writes multiple buffers into the target and reads them * afterwards. * * @throws TaskExecutionException * @throws ExecutionException * @throws InterruptedException */ @Test public final void testMultipleReadWrite() throws TaskExecutionException, InterruptedException, ExecutionException { /** * Creating multiple buffers. */ ByteBuffer[] readBuffers = new ByteBuffer[10]; ByteBuffer[] writeBuffers = new ByteBuffer[10]; for (int i = 0; i < writeBuffers.length; i++) { readBuffers[i] = ByteBuffer.allocate(BUFFER_SIZE); writeBuffers[i] = ByteBuffer.allocate(BUFFER_SIZE); randomGenerator = new Random(System.currentTimeMillis()); randomGenerator.nextBytes(writeBuffers[i].array()); } for (int i = 0; i < writeBuffers.length; i++) { Future<Void> returnVal1; returnVal1 = session.write(writeBuffers[i], LOGICAL_BLOCK_ADDRESS, writeBuffers[i].remaining()); returnVal1.get(); assertTrue(!writeBuffers[i].equals(readBuffers[i])); } for (int i = 0; i < writeBuffers.length; i++) { Future<Void> returnVal1; returnVal1 = session.read(readBuffers[i], LOGICAL_BLOCK_ADDRESS, readBuffers[i].remaining()); returnVal1.get(); } for (int i = 0; i < writeBuffers.length; i++) { assertTrue(writeBuffers[i].equals(readBuffers[writeBuffers.length - i - 1])); // Need to write them into a separate buffer since flip doesn't seem // to work in a Array of ByteBuffers.. ByteBuffer write = ByteBuffer.allocate(BUFFER_SIZE); ByteBuffer read = ByteBuffer.allocate(BUFFER_SIZE); write.put(writeBuffers[i]); read.put(readBuffers[writeBuffers.length - i - 1]); write.flip(); read.flip(); assertTrue(write.equals(read)); } } private static boolean isWindows() { String os = System.getProperty("os.name").toLowerCase(); // windows return (os.indexOf("win") >= 0); } }
package arrayList; import java.util.ArrayList; import java.util.Iterator; /** * Class explaining the usage of ArrayList * * ArrayList supports dynamic arrays that can grow as needed. * Entries in Array list will be stored sequentially in the memory * Not good if list needs to be manipulated many times * Access each entry directly without iterating through the entire list * * @author prithviMandula */ public class ArrayList_Example { public static void main(String[] args) { ArrayList<String> data = new ArrayList<String>(); data.add("Adding"); data.add("Elements"); data.add("to"); data.add("ArrayList"); // Using an Iterator System.out.println("Printing Array List using Iterator"); Iterator<String> itr = data.iterator(); while(itr.hasNext()) { System.out.println(itr.next()); } // Using advanced for loop System.out.println("Printing Array List using For loop"); for(String word : data) { System.out.println(word); } // Using Java 8 Lambda Expression System.out.println("Printing Array List using Java 8 Lambda Expressions"); data.forEach((word)-> { System.out.println(word); }); } }
package com.parc.ccn.security.crypto; import java.io.IOException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.SignatureException; import java.sql.Timestamp; import com.parc.ccn.data.ContentName; import com.parc.ccn.data.ContentObject; import com.parc.ccn.data.security.KeyLocator; import com.parc.ccn.data.security.PublisherPublicKeyDigest; import com.parc.ccn.data.security.SignedInfo.ContentType; import com.parc.ccn.library.CCNSegmenter; /** * An aggregated signer takes a set of blocks and computes signatures * over them such that each block can be verified individually. * An example aggregated signer computes a Merkle hash tree over * the component blocks and then constructs signatures for each. * * This could be a base abstract class or an interface; the former * would have a set of constructors or static factory methods that * made an object returning blocks. Instead, we try an interface * that has a set of bulk put methods which construct blocks, put * them to the network, and return an individual ContentObject. * * * @author smetters * */ public interface CCNAggregatedSigner { // public CCNAggregatedSigner(); // example constructor /** * Sign pre-segmented content. * @param contentBlocks array of blocks of data, not all may be used * @param blockCount how many blocks of the array to use - number of leaves in the tree * @param baseBlockIndex first block to use * @param lastBlockLength how many bytes of last block to use */ public long putBlocks( CCNSegmenter segmenter, ContentName name, long baseNameIndex, byte [][] contentBlocks, int blockCount, int baseBlockIndex, int lastBlockLength, ContentType type, Timestamp timestamp, Integer freshnessSeconds, Long finalSegmentIndex, KeyLocator locator, PublisherPublicKeyDigest publisher) throws InvalidKeyException, SignatureException, NoSuchAlgorithmException, IOException; /** * Sign and segment content from a source array. * @param segmenter * @param name * @param baseNameIndex * @param content * @param offset * @param length * @param blockWidth * @param type * @param timestamp * @param freshnessSeconds * @param finalSegmentIndex * @param locator * @param publisher * @return * @throws InvalidKeyException * @throws SignatureException * @throws NoSuchAlgorithmException * @throws IOException */ public long putBlocks( CCNSegmenter segmenter, ContentName name, long baseNameIndex, byte [] content, int offset, int length, int blockWidth, ContentType type, Timestamp timestamp, Integer freshnessSeconds, Long finalSegmentIndex, KeyLocator locator, PublisherPublicKeyDigest publisher) throws InvalidKeyException, SignatureException, NoSuchAlgorithmException, IOException; /** * * Sign a set of unrelated content objects in one aggregated signature pass. * Objects must have already been constructed and initialized. They must * all indicate the same signer. * DKS TODO -- should we re-set the signer? Opens up the option to muck with * the insides of COs more than idea. * TODO -- should the segmenter and these classes move into same package * with CO in order to have access to internal methods? * @param segmenter * @param contentObjects * @param publisher used to select the private key to sign with. * @return * @throws InvalidKeyException * @throws SignatureException * @throws NoSuchAlgorithmException * @throws IOException */ public void putBlocks( CCNSegmenter segmenter, ContentObject [] contentObjects, PublisherPublicKeyDigest publisher) throws InvalidKeyException, SignatureException, NoSuchAlgorithmException, IOException; }
package de.factoryfx.soap; import javax.xml.bind.*; import javax.xml.namespace.QName; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.soap.*; import java.util.logging.Level; import java.util.logging.Logger; public class SOAPMessageUtil { private final JAXBContext jaxbContext; private final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); static final Logger trashMessagesLogger = Logger.getLogger("javax.xml.soap"); static { trashMessagesLogger.setLevel(Level.OFF); //avoid useless not fixable warning } public SOAPMessageUtil(JAXBContext jaxbContext) { this.jaxbContext = jaxbContext; } public Object parseRequest(SOAPMessage soapMessage){ try { Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); return unmarshaller.unmarshal(soapMessage.getSOAPBody().getFirstChild()); } catch (JAXBException | SOAPException e) { throw new RuntimeException(e); } } public SOAPMessage wrapRequest(Object request, MessageFactory messageFactory){ try { // SOAPFactory soapFactory = SOAPFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL); SOAPMessage requestMessage = messageFactory.createMessage(); Marshaller marshaller = jaxbContext.createMarshaller(); DocumentBuilder db = dbf.newDocumentBuilder(); org.w3c.dom.Document document = db.newDocument(); marshaller.marshal(request, document); org.w3c.dom.Node importedNode = requestMessage.getSOAPBody().getOwnerDocument().importNode(document.getChildNodes().item(0), true); requestMessage.getSOAPBody().appendChild(importedNode); requestMessage.saveChanges(); return requestMessage; } catch (SOAPException | ParserConfigurationException | JAXBException e) { throw new RuntimeException(e); } } public SOAPMessage wrapResponse(Object response, MessageFactory messageFactory){ try { SOAPMessage responseMessage = messageFactory.createMessage(); Marshaller marshaller = jaxbContext.createMarshaller(); DocumentBuilder db = dbf.newDocumentBuilder(); org.w3c.dom.Document document = db.newDocument(); marshaller.marshal(response, document); org.w3c.dom.Node importedNode = responseMessage.getSOAPBody().getOwnerDocument().importNode(document.getChildNodes().item(0), true); // if (fault.isPresent()) { // SOAPFault soapFault = response.getSOAPBody().addFault(); // soapFault.setFaultCode(faultCode.orElse(new QName(SOAPConstants.URI_NS_SOAP_ENVELOPE, "Server"))); // soapFault.setFaultString(faultString.orElse("Unspecified error")); // soapFault.addDetail(); // DetailEntry detailEntry = soapFault.getDetail().addDetailEntry(new QName(importedNode.getNamespaceURI(), importedNode.getLocalName(), importedNode.getPrefix())); // detailEntry.appendChild(importedNode); // ((SoapSupportResource) This).logSoapFault(response.getSOAPBody(), logger); // } else { // response.getSOAPBody().appendChild(importedNode); responseMessage.getSOAPBody().appendChild(importedNode); return responseMessage; } catch (SOAPException | ParserConfigurationException | JAXBException e) { throw new RuntimeException(e); } } public SOAPMessage wrapFault(JAXBElement fault, String faultString, MessageFactory messageFactory, boolean soap12){ try { SOAPMessage responseMessage = messageFactory.createMessage(); Marshaller marshaller = jaxbContext.createMarshaller(); DocumentBuilder db = dbf.newDocumentBuilder(); org.w3c.dom.Document document = db.newDocument(); marshaller.marshal(fault, document); org.w3c.dom.Node importedNode = responseMessage.getSOAPBody().getOwnerDocument().importNode(document.getChildNodes().item(0), true); SOAPFault soapFault = responseMessage.getSOAPBody().addFault(); if (soap12) { soapFault.setFaultCode(SOAPConstants.SOAP_SENDER_FAULT); } else { soapFault.setFaultCode(fault.getName()); } soapFault.setFaultString(faultString!=null?faultString:"Unspecified error"); soapFault.addDetail(); DetailEntry detailEntry = soapFault.getDetail().addDetailEntry(new QName(importedNode.getNamespaceURI(), importedNode.getLocalName(), importedNode.getPrefix())); detailEntry.appendChild(importedNode); responseMessage.getSOAPBody().appendChild(importedNode); return responseMessage; } catch (SOAPException | ParserConfigurationException | JAXBException e) { throw new RuntimeException(e); } } }
package expertsystem; import java.util.List; public class AIEngine { private RulesBase BR; public AIEngine(RulesBase _BR){ BR= _BR; } private boolean VERIF(List<Word> WList, FactsBase FB) { boolean ver = true; for(Word W : WList) { while(ver == true) //ver = DEMO(b, BF); ver = (true || false); } return ver; } public FactsBase forwardChaining(FactsBase BF) { boolean inf= true; int nbInf= 0; while(inf){ inf= false; RulesBase BRcpy= new RulesBase(BR); for ( Rule rule : BRcpy){ // boolean dec= true; // Iterator<Word> iter= rule.getAntecedants().iterator(); // while ( iter.hasNext() && dec ){ // TODO OBLIGATOIRE, corriger contains() pour comparaison System.out.println("Parcours des antécédents"); for (Word wAnt : rule.getAntecedants()){ // Word wAnt= iter.next(); Word tmp= BF.contains(wAnt); if ( tmp == null || ! (tmp.getVal()).equals(wAnt.getVal()) ) // /*BF c valeur de f dans BF*/VF(f)!=/*VA(wAnt,r)*/ dec= false; } if (dec){ // , for (Word wCons : rule.getConsequences() ){ BF.add(wCons); } inf= true; ++nbInf; //TODO this.Mémoriser(r,nbInf) /* Pour l'explication TODO ???*/ BR.tryRemove(rule); } } } System.out.println("Nb inférence chainage avant : "+ nbInf); // TODO retour et conclusion pour utilisateur (en passant par bridge-constructor) return BF; } public boolean DEMO(Affirmation A, FactsBase FB) { RulesBase RB = new RulesBase(BR); boolean dem = false; if(FB.contains(A) != null) dem = true; for(Rule R : RB.rules) { } if(dem == false ) { // Poser la question b ? // dem = reponse(b) VRAI, FAUX, ou inconnu } if(dem == true) FB.add(A); // return dem ? return dem; } }
package org.bonej.plugins; import java.util.Arrays; import java.util.concurrent.atomic.AtomicInteger; import org.bonej.util.ImageCheck; import org.bonej.util.Multithreader; import org.bonej.util.ResultInserter; import ij.IJ; import ij.ImagePlus; import ij.ImageStack; import ij.macro.Interpreter; import ij.measure.Calibration; import ij.plugin.PlugIn; public class Connectivity implements PlugIn { private final static int[] EULER_LUT = fillEulerLUT(); /** working image width */ private int width = 0; /** working image height */ private int height = 0; /** working image depth */ private int depth = 0; @Override public void run(final String arg) { final ImagePlus imp = IJ.getImage(); if (!ImageCheck.isBinary(imp)) { IJ.error("Connectivity requires a binary image."); return; } final double sumEuler = getSumEuler(imp); final double deltaChi = getDeltaChi(imp, sumEuler); final double connectivity = getConnectivity(deltaChi); final double connDensity = getConnDensity(imp, connectivity); if (connectivity < 0 && !Interpreter.isBatchMode()) { IJ.showMessage("Caution", "Connectivity is negative.\n\n" + "This usually happens if there are multiple\n" + "particles or enclosed cavities.\n\n" + "Try running Purify prior to Connectivity."); } final ResultInserter ri = ResultInserter.getInstance(); ri.setResultInRow(imp, "Euler ch.", sumEuler); ri.setResultInRow(imp, "Δ(χ)", deltaChi); ri.setResultInRow(imp, "Connectivity", connectivity); ri.setResultInRow(imp, "Conn.D (" + imp.getCalibration().getUnit() + "^-3)", connDensity); ri.updateTable(); UsageReporter.reportEvent(this).send(); return; } /** * Calculate connectivity density * * @param imp Binary ImagePlus * @param connectivity Result of getConnectivity() * @return connectivity density. */ public double getConnDensity(final ImagePlus imp, final double connectivity) { setDimensions(imp); final Calibration cal = imp.getCalibration(); final double vW = cal.pixelWidth; final double vH = cal.pixelHeight; final double vD = cal.pixelDepth; final double stackVolume = width * height * depth * vW * vH * vD; final double connDensity = connectivity / stackVolume; return connDensity; } /** * Return the connectivity of the image, which is 1 - deltaChi. * * @param deltaChi result of getDeltaChi() * @return double connectivity */ public double getConnectivity(final double deltaChi) { final double connectivity = 1 - deltaChi; return connectivity; } /** * Get the contribution of the stack's foreground particles to the Euler * characteristic of the universe the stack was cut from. * * @param imp * Binary ImagePlus * @param sumEuler * (result of getSumEuler() ) * @return delta Chi */ public double getDeltaChi(final ImagePlus imp, final double sumEuler) { setDimensions(imp); final double deltaChi = sumEuler - correctForEdges(imp.getStack()); return deltaChi; } /** * Calculate the Euler characteristic of the foreground in a binary stack * * @param imp * Binary ImagePlus * @return Euler characteristic of the foreground particles */ public double getSumEuler(final ImagePlus imp) { setDimensions(imp); final ImageStack stack = imp.getImageStack(); final int[] sumEulerInt = new int[depth + 1]; final AtomicInteger ai = new AtomicInteger(0); final Thread[] threads = Multithreader.newThreads(); for (int thread = 0; thread < threads.length; thread++) { threads[thread] = new Thread(new Runnable() { @Override public void run() { byte o1 = 0, o2 = 0, o3 = 0, o4 = 0, o5 = 0, o6 = 0, o7 = 0, o8 = 0; for (int z = ai.getAndIncrement(); z <= depth; z = ai.getAndIncrement()) { for (int y = 0; y <= height; y++) { for (int x = 0; x <= width; x++) { final int y1 = y - 1; final int z1 = z - 1; o1 = o3; o2 = o4; o3 = getPixel(stack, x, y1, z1); o4 = getPixel(stack, x, y, z1); o5 = o7; o6 = o8; o7 = getPixel(stack, x, y1, z); o8 = getPixel(stack, x, y, z); if ( o1 != 0 || o2 != 0 || o3 != 0 || o4 != 0 || o5 != 0 || o6 != 0 || o7 != 0 || o8 != 0 ) sumEulerInt[z] += getDeltaEuler(o1, o2, o3, o4, o5, o6, o7, o8); } } } } }); } Multithreader.startAndJoin(threads); double sumEuler = Arrays.stream(sumEulerInt).sum(); sumEuler /= 8; return sumEuler; } private void setDimensions(final ImagePlus imp) { this.width = imp.getWidth(); this.height = imp.getHeight(); this.depth = imp.getStackSize(); return; } /** * Get pixel in 3D image stack (0 border conditions) * * @param stack * 3D image * @param x * x- coordinate * @param y * y- coordinate * @param z * z- coordinate (in image stacks the indexes start at 1) * @return corresponding pixel (0 if out of image) */ private byte getPixel(final ImageStack stack, final int x, final int y, final int z) { if (x >= 0 && x < this.width && y >= 0 && y < this.height && z >= 0 && z < this.depth) return ((byte[]) stack.getPixels(z + 1))[y * this.width + x]; return 0; } /* end getPixel */ /** * Get delta euler value for an octant (~= vertex) from look up table * * Use this method only when there is at least one foreground voxel in * octant. * * In binary images, foreground is -1, background = 0. o1 = 08 are the octant values. * @return delta Euler for the octant or false if the point is Euler invariant or not */ private int getDeltaEuler(final byte o1, final byte o2, final byte o3, final byte o4, final byte o5, final byte o6, final byte o7, final byte o8) { char n = 1; if (o8 == -1) { if (o1 == -1) n |= 128; if (o2 == -1) n |= 64; if (o3 == -1) n |= 32; if (o4 == -1) n |= 16; if (o5 == -1) n |= 8; if (o6 == -1) n |= 4; if (o7 == -1) n |= 2; } else if (o7 == -1) { if (o2 == -1) n |= 128; if (o4 == -1) n |= 64; if (o1 == -1) n |= 32; if (o3 == -1) n |= 16; if (o6 == -1) n |= 8; if (o5 == -1) n |= 2; } else if (o6 == -1) { if (o3 == -1) n |= 128; if (o1 == -1) n |= 64; if (o4 == -1) n |= 32; if (o2 == -1) n |= 16; if (o5 == -1) n |= 4; } else if (o5 == -1) { if (o4 == -1) n |= 128; if (o3 == -1) n |= 64; if (o2 == -1) n |= 32; if (o1 == -1) n |= 16; } else if (o4 == -1) { if (o1 == -1) n |= 8; if (o3 == -1) n |= 4; if (o2 == -1) n |= 2; } else if (o3 == -1) { if (o2 == -1) n |= 8; if (o1 == -1) n |= 4; } else if (o2 == -1) { if (o1 == -1) n |= 2; } else return 1; return EULER_LUT[n]; }/* end getDeltaEuler */ /** * Check all vertices of stack and count if foreground (-1) this is &#967; * <sub>0</sub> from Odgaard and Gundersen (1993) and <i>f</i> in my working * * @param stack * @return number of voxel vertices intersecting with stack vertices */ private long getStackVertices(final ImageStack stack) { long nStackVertices = 0; final int xInc = Math.max(1, width - 1); final int yInc = Math.max(1, height - 1); final int zInc = Math.max(1, depth - 1); for (int z = 0; z < depth; z += zInc) { for (int y = 0; y < height; y += yInc) { for (int x = 0; x < width; x += xInc) { if (getPixel(stack, x, y, z) == -1) nStackVertices++; } } } return nStackVertices; }/* end getStackVertices */ /** * Count the number of foreground voxels on edges of stack, this is part of * &#967;<sub>1</sub> (<i>e</i> in my working) * * @param stack * @return number of voxel edges intersecting with stack edges */ private long getStackEdges(final ImageStack stack) { long nStackEdges = 0; final int w1 = width - 1; final int h1 = height - 1; final int d1 = depth -1; final int xInc = Math.max(1, w1); final int yInc = Math.max(1, h1); final int zInc = Math.max(1, d1); // left to right stack edges for (int z = 0; z < depth; z += zInc) { for (int y = 0; y < height; y += yInc) { for (int x = 1; x < w1; x++) { if (getPixel(stack, x, y, z) == -1) nStackEdges++; } } } // back to front stack edges for (int z = 0; z < depth; z += zInc) { for (int x = 0; x < width; x += xInc) { for (int y = 1; y < h1; y++) { if (getPixel(stack, x, y, z) == -1) nStackEdges++; } } } // top to bottom stack edges for (int y = 0; y < height; y += yInc) { for (int x = 0; x < width; x += xInc) { for (int z = 1; z < d1; z++) { if (getPixel(stack, x, y, z) == -1) nStackEdges++; } } } return nStackEdges; }/* end getStackEdges */ /** * Count the number of foreground voxel faces intersecting with stack faces * This is part of &#967;<sub>2</sub> and is <i>c</i> in my working * * @param stack * @return number of voxel faces intersecting with stack faces */ private long getStackFaces(final ImageStack stack) { final int w1 = width - 1; final int h1 = height - 1; final int d1 = depth -1; final int xInc = Math.max(1, w1); final int yInc = Math.max(1, h1); final int zInc = Math.max(1, d1); long nStackFaces = 0; // top and bottom faces for (int z = 0; z < depth; z += zInc) { for (int y = 1; y < h1; y++) { for (int x = 1; x < w1; x++) { if (getPixel(stack, x, y, z) == -1) nStackFaces++; } } } // back and front faces for (int y = 0; y < height; y += yInc) { for (int z = 1; z < d1; z++) { for (int x = 1; x < w1; x++) { if (getPixel(stack, x, y, z) == -1) nStackFaces++; } } } // left and right faces for (int x = 0; x < width; x += xInc) { for (int y = 1; y < h1; y++) { for (int z = 1; z < d1; z++) { if (getPixel(stack, x, y, z) == -1) nStackFaces++; } } } return nStackFaces; }/* end getStackFaces */ /** * Count the number of voxel vertices intersecting stack faces. This * contributes to &#967;<sub>2</sub> (<i>a</i> in my working) * * @param stack * @return Number of voxel vertices intersecting stack faces */ private long getFaceVertices(final ImageStack stack) { final int xInc = Math.max(1, width - 1); final int yInc = Math.max(1, height - 1); final int zInc = Math.max(1, depth - 1); long nFaceVertices = 0; // top and bottom faces (all 4 edges) for (int z = 0; z < depth; z += zInc) { for (int y = 0; y <= height; y++) { for (int x = 0; x <= width; x++) { // if the voxel or any of its neighbours are foreground, the // vertex is counted if (getPixel(stack, x, y, z) == -1) nFaceVertices++; else if (getPixel(stack, x, y - 1, z) == -1) nFaceVertices++; else if (getPixel(stack, x - 1, y - 1, z) == -1) nFaceVertices++; else if (getPixel(stack, x - 1, y, z) == -1) nFaceVertices++; } } } // left and right faces (2 vertical edges) for (int x = 0; x < width; x += xInc) { for (int y = 0; y <= height; y++) { for (int z = 1; z < depth; z++) { // if the voxel or any of its neighbours are foreground, the // vertex is counted if (getPixel(stack, x, y, z) == -1) nFaceVertices++; else if (getPixel(stack, x, y - 1, z) == -1) nFaceVertices++; else if (getPixel(stack, x, y - 1, z - 1) == -1) nFaceVertices++; else if (getPixel(stack, x, y, z - 1) == -1) nFaceVertices++; } } } // back and front faces (0 vertical edges) for (int y = 0; y < height; y += yInc) { for (int x = 1; x < width; x++) { for (int z = 1; z < depth; z++) { // if the voxel or any of its neighbours are foreground, the // vertex is counted if (getPixel(stack, x, y, z) == -1) nFaceVertices++; else if (getPixel(stack, x, y, z - 1) == -1) nFaceVertices++; else if (getPixel(stack, x - 1, y, z - 1) == -1) nFaceVertices++; else if (getPixel(stack, x - 1, y, z) == -1) nFaceVertices++; } } } return nFaceVertices; }/* end getFaceVertices */ /** * Count the number of intersections between voxel edges and stack faces. * This is part of &#967;<sub>2</sub>, in my working it's called <i>b</i> * * @param stack * @return number of intersections between voxel edges and stack faces */ private long getFaceEdges(final ImageStack stack) { final int xInc = Math.max(1, width - 1); final int yInc = Math.max(1, height - 1); final int zInc = Math.max(1, depth - 1); long nFaceEdges = 0; // top and bottom faces (all 4 edges) // check 2 edges per voxel for (int z = 0; z < depth; z += zInc) { for (int y = 0; y <= height; y++) { for (int x = 0; x <= width; x++) { // if the voxel or any of its neighbours are foreground, the // vertex is counted if (getPixel(stack, x, y, z) == -1) { nFaceEdges += 2; } else { if (getPixel(stack, x, y - 1, z) == -1) { nFaceEdges++; } if (getPixel(stack, x - 1, y, z) == -1) { nFaceEdges++; } } } } } // back and front faces, horizontal edges for (int y = 0; y < height; y += yInc) { for (int z = 1; z < depth; z++) { for (int x = 0; x < width; x++) { if (getPixel(stack, x, y, z) == -1) nFaceEdges++; else if (getPixel(stack, x, y, z - 1) == -1) nFaceEdges++; } } } // back and front faces, vertical edges for (int y = 0; y < height; y += yInc) { for (int z = 0; z < depth; z++) { for (int x = 0; x <= width; x++) { if (getPixel(stack, x, y, z) == -1) nFaceEdges++; else if (getPixel(stack, x - 1, y, z) == -1) nFaceEdges++; } } } // left and right stack faces, horizontal edges for (int x = 0; x < width; x += xInc) { for (int z = 1; z < depth; z++) { for (int y = 0; y < height; y++) { if (getPixel(stack, x, y, z) == -1) nFaceEdges++; else if (getPixel(stack, x, y, z - 1) == -1) nFaceEdges++; } } } // left and right stack faces, vertical voxel edges for (int x = 0; x < width; x += xInc) { for (int z = 0; z < depth; z++) { for (int y = 1; y < height; y++) { if (getPixel(stack, x, y, z) == -1) nFaceEdges++; else if (getPixel(stack, x, y - 1, z) == -1) nFaceEdges++; } } } return nFaceEdges; }/* end getFaceEdges */ /** * Count number of voxel vertices intersecting stack edges. It contributes * to &#967;<sub>1</sub>, and I call it <i>d</i> in my working * * @param stack * @return number of voxel vertices intersecting stack edges */ private long getEdgeVertices(final ImageStack stack) { final int xInc = Math.max(1, width - 1); final int yInc = Math.max(1, height - 1); final int zInc = Math.max(1, depth - 1); long nEdgeVertices = 0; // left->right edges for (int z = 0; z < depth; z += zInc) { for (int y = 0; y < height; y += yInc) { for (int x = 1; x < width; x++) { if (getPixel(stack, x, y, z) == -1) nEdgeVertices++; else if (getPixel(stack, x - 1, y, z) == -1) nEdgeVertices++; } } } // back->front edges for (int z = 0; z < depth; z += zInc) { for (int x = 0; x < width; x += xInc) { for (int y = 1; y < height; y++) { if (getPixel(stack, x, y, z) == -1) nEdgeVertices++; else if (getPixel(stack, x, y - 1, z) == -1) nEdgeVertices++; } } } // top->bottom edges for (int x = 0; x < width; x += xInc) { for (int y = 0; y < height; y += yInc) { for (int z = 1; z < depth; z++) { if (getPixel(stack, x, y, z) == -1) nEdgeVertices++; else if (getPixel(stack, x, y, z - 1) == -1) nEdgeVertices++; } } } return nEdgeVertices; }/* end getEdgeVertices */ /** * <p> * Calculate a correction value to convert the Euler number of a stack to * the stack's contribution to the Euler number of whatever it is cut from. * <ol type="a"> * <li>Number of voxel vertices on stack faces</li> * <li>Number of voxel edges on stack faces</li> * <li>Number of voxel faces on stack faces</li> * <li>Number of voxel vertices on stack edges</li> * <li>Number of voxel edges on stack edges</li> * <li>Number of voxel vertices on stack vertices</li> * </ol> * </p> * <p> * Subtract the returned value from the Euler number prior to calculation of * connectivity * </p> * * @param stack * @return edgeCorrection for subtraction from the stack's Euler number */ private double correctForEdges(final ImageStack stack) { final long f = getStackVertices(stack); final long e = getStackEdges(stack) + 3 * f; final long c = getStackFaces(stack) + 2 * e - 3 * f; final long d = getEdgeVertices(stack) + f; final long a = getFaceVertices(stack); final long b = getFaceEdges(stack); final double chiZero = f; final double chiOne = (double) d - (double) e; final double chiTwo = (double) a - (double) b + c; final double edgeCorrection = chiTwo / 2 + chiOne / 4 + chiZero / 8; return edgeCorrection; }/* end correctForEdges */ /** * Fill Euler LUT Only odd indices are needed because we only check object * voxels' neighbours, so there is always a 1 in each index. * * This is derived from Toriwaki & Yonekura (2002) Table 2 for 26-connected * images. */ private final static int[] fillEulerLUT() { final int[] lut = new int[256]; lut[1] = 1; lut[3] = 0; lut[5] = 0; lut[7] = -1; lut[9] = -2; lut[11] = -1; lut[13] = -1; lut[15] = 0; lut[17] = 0; lut[19] = -1; lut[21] = -1; lut[23] = -2; lut[25] = -3; lut[27] = -2; lut[29] = -2; lut[31] = -1; lut[33] = -2; lut[35] = -1; lut[37] = -3; lut[39] = -2; lut[41] = -1; lut[43] = -2; lut[45] = 0; lut[47] = -1; lut[49] = -1; lut[51] = 0; lut[53] = -2; lut[55] = -1; lut[57] = 0; lut[59] = -1; lut[61] = 1; lut[63] = 0; lut[65] = -2; lut[67] = -3; lut[69] = -1; lut[71] = -2; lut[73] = -1; lut[75] = 0; lut[77] = -2; lut[79] = -1; lut[81] = -1; lut[83] = -2; lut[85] = 0; lut[87] = -1; lut[89] = 0; lut[91] = 1; lut[93] = -1; lut[95] = 0; lut[97] = -1; lut[99] = 0; lut[101] = 0; lut[103] = 1; lut[105] = 4; lut[107] = 3; lut[109] = 3; lut[111] = 2; lut[113] = -2; lut[115] = -1; lut[117] = -1; lut[119] = 0; lut[121] = 3; lut[123] = 2; lut[125] = 2; lut[127] = 1; lut[129] = -6; lut[131] = -3; lut[133] = -3; lut[135] = 0; lut[137] = -3; lut[139] = -2; lut[141] = -2; lut[143] = -1; lut[145] = -3; lut[147] = 0; lut[149] = 0; lut[151] = 3; lut[153] = 0; lut[155] = 1; lut[157] = 1; lut[159] = 2; lut[161] = -3; lut[163] = -2; lut[165] = 0; lut[167] = 1; lut[169] = 0; lut[171] = -1; lut[173] = 1; lut[175] = 0; lut[177] = -2; lut[179] = -1; lut[181] = 1; lut[183] = 2; lut[185] = 1; lut[187] = 0; lut[189] = 2; lut[191] = 1; lut[193] = -3; lut[195] = 0; lut[197] = -2; lut[199] = 1; lut[201] = 0; lut[203] = 1; lut[205] = -1; lut[207] = 0; lut[209] = -2; lut[211] = 1; lut[213] = -1; lut[215] = 2; lut[217] = 1; lut[219] = 2; lut[221] = 0; lut[223] = 1; lut[225] = 0; lut[227] = 1; lut[229] = 1; lut[231] = 2; lut[233] = 3; lut[235] = 2; lut[237] = 2; lut[239] = 1; lut[241] = -1; lut[243] = 0; lut[245] = 0; lut[247] = 1; lut[249] = 2; lut[251] = 1; lut[253] = 1; lut[255] = 0; return lut; }/* end fillEulerLUT */ }
package se.jabberwocky.ccrypt; import java.io.IOException; import java.io.InputStream; import javax.crypto.SecretKey; import org.bouncycastle.crypto.BufferedBlockCipher; import org.bouncycastle.crypto.CipherParameters; import org.bouncycastle.crypto.DataLengthException; import org.bouncycastle.crypto.InvalidCipherTextException; import org.bouncycastle.crypto.engines.RijndaelEngine; import org.bouncycastle.crypto.modes.CFBBlockCipher; import org.bouncycastle.crypto.params.KeyParameter; import org.bouncycastle.crypto.params.ParametersWithIV; import se.jabberwocky.ccrypt.jce.CCryptConstants; /** * Decrypts a ccrypt InputStream. */ public final class CCryptInputStream extends InputStream { private final InputStream source; private final BufferedBlockCipher blockCipher; private byte[] cipherText = new byte[32]; private byte[] plainText = new byte[32]; private int index; private int bytesInBuffer; private final boolean verifyMagic; public CCryptInputStream(InputStream source, SecretKey key) throws IOException { this(source, key, true); } public CCryptInputStream(InputStream source, SecretKey key, boolean verify) throws IOException { RijndaelEngine rijndael = new RijndaelEngine(256); rijndael.reset(); this.source = source; this.verifyMagic = verify; CFBBlockCipher cfb = new CFBBlockCipher(rijndael, 256); blockCipher = new BufferedBlockCipher(cfb); CipherParameters keyParam = new KeyParameter(key.getEncoded()); blockCipher.init(false, keyParam); readAndDecryptCipherBlock(); byte[] iv = extractIV(keyParam); assertMagic(iv); // Initialize cipher with key and IV CipherParameters params = new ParametersWithIV(keyParam, iv); blockCipher.init(false, params); readAndDecryptCipherBlock(); } private void assertMagic(byte[] iv) { if(verifyMagic) { for(int i=0; i<CCryptConstants.CCRYPT_MAGIC_NUMBER.length; i++) { if(CCryptConstants.CCRYPT_MAGIC_NUMBER[i] != plainText[i]) { throw new IllegalArgumentException("InputStream Magic " + "Number does not match, wrong version of ccrypt?"); } } } } protected byte[] extractIV(CipherParameters keyParam) throws IOException { if (bytesInBuffer < 32) { throw new IOException("Could only read " + bytesInBuffer + " bytes from ccrypt InputStream for the " + "Initializing Vector (IV) before end of file was" + "reached; the ccrypt stream should be at least " + "32 bytes long, i.e. larger than the size of the IV"); } byte[] iv = cipherText.clone(); // first 32 bytes of InputStream return iv; } // -- InputStream @Override public int read() throws IOException { if (index < bytesInBuffer) { return plainText[index++]; } if (index == 32) { readAndDecryptCipherBlock(); if (bytesInBuffer == 0) { return -1; } else { return plainText[index++]; } } return -1; } // -- CCryptInputStream public boolean isVerifyMagic() { return verifyMagic; } private final void readAndDecryptCipherBlock() throws IOException { bytesInBuffer = 0; index = 0; int len = 0; while (len != -1 && bytesInBuffer < 32) { len = source.read(cipherText, bytesInBuffer, 32 - bytesInBuffer); if (len == -1) { break; } bytesInBuffer += len; } len = blockCipher.processBytes(cipherText, 0, bytesInBuffer, plainText, 0); if (len < 32) { try { blockCipher.doFinal(plainText, len); } catch (DataLengthException | IllegalStateException | InvalidCipherTextException e) { throw new IOException("Could not process final byte", e); } } } }
package solver.variables.fast; import choco.kernel.common.util.iterators.DisposableRangeIterator; import choco.kernel.common.util.iterators.DisposableValueIterator; import choco.kernel.memory.IEnvironment; import choco.kernel.memory.IStateBitSet; import choco.kernel.memory.IStateInt; import com.sun.istack.internal.NotNull; import solver.Cause; import solver.ICause; import solver.Solver; import solver.exception.ContradictionException; import solver.explanations.Explanation; import solver.explanations.OffsetIStateBitset; import solver.explanations.VariableState; import solver.search.strategy.enumerations.values.heuristics.HeuristicVal; import solver.variables.AbstractVariable; import solver.variables.EventType; import solver.variables.IntVar; import solver.variables.delta.Delta; import solver.variables.delta.IntDelta; import solver.variables.delta.NoDelta; import solver.variables.view.IntView; /** * <br/> * * @author Charles Prud'homme * @since 18 nov. 2010 */ public final class BitsetIntVarImpl extends AbstractVariable<IntDelta, IntView, IntVar> implements IntVar { private static final long serialVersionUID = 1L; protected boolean reactOnRemoval = false; // Bitset of available values -- includes offset private final IStateBitSet VALUES; // Lower bound of the current domain -- includes offset private final IStateInt LB; // Upper bound of the current domain -- includes offset private final IStateInt UB; private final IStateInt SIZE; //offset of the lower bound and the first value in the domain private final int OFFSET; private final int LENGTH; private IntDelta delta = NoDelta.singleton; protected HeuristicVal heuristicVal; private DisposableValueIterator _viterator; private DisposableRangeIterator _riterator; public BitsetIntVarImpl(String name, int[] sortedValues, Solver solver) { super(name, solver); solver.associates(this); IEnvironment env = solver.getEnvironment(); OFFSET = sortedValues[0]; int capacity = sortedValues[sortedValues.length - 1] - OFFSET + 1; this.VALUES = env.makeBitSet(capacity); for (int i = 0; i < sortedValues.length; i++) { this.VALUES.set(sortedValues[i] - OFFSET); } this.LB = env.makeInt(0); this.UB = env.makeInt(capacity - 1); this.SIZE = env.makeInt(sortedValues.length); LENGTH = capacity; this.makeList(this); } public BitsetIntVarImpl(String name, int offset, IStateBitSet values, Solver solver) { super(name, solver); solver.associates(this); IEnvironment env = solver.getEnvironment(); OFFSET = offset; int cardinality = values.cardinality(); this.VALUES = values.copy(); this.LB = env.makeInt(0); this.UB = env.makeInt(values.prevSetBit(values.size())); this.SIZE = env.makeInt(cardinality); LENGTH = this.UB.get(); this.makeList(this); } public BitsetIntVarImpl(String name, int min, int max, Solver solver) { super(name, solver); solver.associates(this); IEnvironment env = solver.getEnvironment(); this.OFFSET = min; int capacity = max - min + 1; this.VALUES = env.makeBitSet(capacity); for (int i = 0; i <= max - min; i++) { this.VALUES.set(i); } this.LB = env.makeInt(0); this.UB = env.makeInt(max - min); this.SIZE = env.makeInt(capacity); assert capacity == VALUES.capacity(); LENGTH = capacity; this.makeList(this); } @Override public void setHeuristicVal(HeuristicVal heuristicVal) { this.heuristicVal = heuristicVal; } @Override public HeuristicVal getHeuristicVal() { return heuristicVal; } /** * Removes <code>value</code>from the domain of <code>this</code>. The instruction comes from <code>propagator</code>. * <ul> * <li>If <code>value</code> is out of the domain, nothing is done and the return value is <code>false</code>,</li> * <li>if removing <code>value</code> leads to a dead-end (domain wipe-out), * a <code>ContradictionException</code> is thrown,</li> * <li>otherwise, if removing <code>value</code> from the domain can be done safely, * the event type is created (the original event can be promoted) and observers are notified * and the return value is <code>true</code></li> * </ul> * * @param value value to remove from the domain (int) * @param cause removal releaser * @return true if the value has been removed, false otherwise * @throws solver.exception.ContradictionException * if the domain become empty due to this action */ public boolean removeValue(int value, ICause cause) throws ContradictionException { // BEWARE: THIS CODE SHOULD NOT BE MOVED TO THE DOMAIN TO NOT DECREASE PERFORMANCES! records.forEach(beforeModification.set(this, EventType.REMOVE, cause)); ICause antipromo = cause; int aValue = value - OFFSET; boolean change = aValue >= 0 && aValue <= LENGTH && VALUES.get(aValue); if (change) { if (SIZE.get() == 1) { solver.getExplainer().removeValue(this, value, antipromo); // monitors.forEach(onContradiction.set(this, EventType.REMOVE, cause)); this.contradiction(cause, EventType.REMOVE, MSG_REMOVE); } EventType e = EventType.REMOVE; this.VALUES.clear(aValue); this.SIZE.add(-1); if (reactOnRemoval) { delta.add(aValue + OFFSET, cause); } if (value == getLB()) { LB.set(VALUES.nextSetBit(aValue)); e = EventType.INCLOW; if (cause.reactOnPromotion()) { cause = Cause.Null; } } else if (value == getUB()) { UB.set(VALUES.prevSetBit(aValue)); e = EventType.DECUPP; if (cause.reactOnPromotion()) { cause = Cause.Null; } } assert !VALUES.isEmpty(); if (this.instantiated()) { e = EventType.INSTANTIATE; if (cause.reactOnPromotion()) { cause = Cause.Null; } } this.notifyMonitors(e, cause); solver.getExplainer().removeValue(this, value, antipromo); } return change; } /** * {@inheritDoc} */ @Override public boolean removeInterval(int from, int to, ICause cause) throws ContradictionException { if (from <= getLB()) return updateLowerBound(to + 1, cause); else if (getUB() <= to) return updateUpperBound(from - 1, cause); else { // TODO: really ugly ......... boolean anyChange = false; for (int v = this.nextValue(from - 1); v <= to; v = nextValue(v)) { anyChange |= removeValue(v, cause); } return anyChange; } } /** * Instantiates the domain of <code>this</code> to <code>value</code>. The instruction comes from <code>propagator</code>. * <ul> * <li>If the domain of <code>this</code> is already instantiated to <code>value</code>, * nothing is done and the return value is <code>false</code>,</li> * <li>If the domain of <code>this</code> is already instantiated to another value, * then a <code>ContradictionException</code> is thrown,</li> * <li>Otherwise, the domain of <code>this</code> is restricted to <code>value</code> and the observers are notified * and the return value is <code>true</code>.</li> * </ul> * * @param value instantiation value (int) * @param cause instantiation releaser * @return true if the instantiation is done, false otherwise * @throws solver.exception.ContradictionException * if the domain become empty due to this action */ public boolean instantiateTo(int value, ICause cause) throws ContradictionException { // BEWARE: THIS CODE SHOULD NOT BE MOVED TO THE DOMAIN TO NOT DECREASE PERFORMANCES! solver.getExplainer().instantiateTo(this, value, cause); // the explainer is informed before the actual instantiation is performed if (this.instantiated()) { if (value != this.getValue()) { this.contradiction(cause, EventType.INSTANTIATE, MSG_INST); } return false; } else if (contains(value)) { int aValue = value - OFFSET; if (reactOnRemoval) { int i = VALUES.nextSetBit(this.LB.get()); for (; i < aValue; i = VALUES.nextSetBit(i + 1)) { delta.add(i + OFFSET, cause); } i = VALUES.nextSetBit(aValue + 1); for (; i >= 0; i = VALUES.nextSetBit(i + 1)) { delta.add(i + OFFSET, cause); } } this.VALUES.clear(); this.VALUES.set(aValue); this.LB.set(aValue); this.UB.set(aValue); this.SIZE.set(1); if (VALUES.isEmpty()) { this.contradiction(cause, EventType.INSTANTIATE, MSG_EMPTY); } this.notifyMonitors(EventType.INSTANTIATE, cause); return true; } else { this.contradiction(cause, EventType.INSTANTIATE, MSG_UNKNOWN); return false; } } /** * Updates the lower bound of the domain of <code>this</code> to <code>value</code>. * The instruction comes from <code>propagator</code>. * <ul> * <li>If <code>value</code> is smaller than the lower bound of the domain, nothing is done and the return value is <code>false</code>,</li> * <li>if updating the lower bound to <code>value</code> leads to a dead-end (domain wipe-out), * a <code>ContradictionException</code> is thrown,</li> * <li>otherwise, if updating the lower bound to <code>value</code> can be done safely, * the event type is created (the original event can be promoted) and observers are notified * and the return value is <code>true</code></li> * </ul> * * @param value new lower bound (included) * @param cause updating releaser * @return true if the lower bound has been updated, false otherwise * @throws solver.exception.ContradictionException * if the domain become empty due to this action */ public boolean updateLowerBound(int value, ICause cause) throws ContradictionException { boolean change; ICause antipromo = cause; int old = this.getLB(); if (old < value) { if (this.getUB() < value) { solver.getExplainer().updateLowerBound(this, old, value, antipromo); this.contradiction(cause, EventType.INCLOW, MSG_LOW); } else { EventType e = EventType.INCLOW; int aValue = value - OFFSET; if (reactOnRemoval) { //BEWARE: this loop significantly decreases performances for (int i = old - OFFSET; i < aValue; i = VALUES.nextSetBit(i + 1)) { delta.add(i + OFFSET, cause); } } VALUES.clear(old - OFFSET, aValue); LB.set(VALUES.nextSetBit(aValue)); int _size = SIZE.get(); int card = VALUES.cardinality(); SIZE.set(card); change = _size - card > 0; if (instantiated()) { e = EventType.INSTANTIATE; if (cause.reactOnPromotion()) { cause = Cause.Null; } } assert (change); this.notifyMonitors(e, cause); solver.getExplainer().updateLowerBound(this, old, value, antipromo); return change; } } return false; } /** * Updates the upper bound of the domain of <code>this</code> to <code>value</code>. * The instruction comes from <code>propagator</code>. * <ul> * <li>If <code>value</code> is greater than the upper bound of the domain, nothing is done and the return value is <code>false</code>,</li> * <li>if updating the upper bound to <code>value</code> leads to a dead-end (domain wipe-out), * a <code>ContradictionException</code> is thrown,</li> * <li>otherwise, if updating the upper bound to <code>value</code> can be done safely, * the event type is created (the original event can be promoted) and observers are notified * and the return value is <code>true</code></li> * </ul> * * @param value new upper bound (included) * @param cause update releaser * @return true if the upper bound has been updated, false otherwise * @throws solver.exception.ContradictionException * if the domain become empty due to this action */ public boolean updateUpperBound(int value, ICause cause) throws ContradictionException { boolean change; ICause antipromo = cause; int old = this.getUB(); if (old > value) { if (this.getLB() > value) { solver.getExplainer().updateUpperBound(this, old, value, antipromo); this.contradiction(cause, EventType.DECUPP, MSG_UPP); } else { EventType e = EventType.DECUPP; int aValue = value - OFFSET; if (reactOnRemoval) { //BEWARE: this loop significantly decreases performances for (int i = old - OFFSET; i > aValue; i = VALUES.prevSetBit(i - 1)) { delta.add(i + OFFSET, cause); } } VALUES.clear(aValue + 1, old - OFFSET + 1); UB.set(VALUES.prevSetBit(aValue)); int _size = SIZE.get(); int card = VALUES.cardinality(); SIZE.set(card); change = _size - card > 0; if (card == 1) { e = EventType.INSTANTIATE; if (cause.reactOnPromotion()) { cause = Cause.Null; } } assert (change); this.notifyMonitors(e, cause); solver.getExplainer().updateUpperBound(this, old, value, antipromo); return change; } } return false; } public boolean instantiated() { return SIZE.get() == 1; } @Override public boolean instantiatedTo(int value) { return instantiated() && contains(value); } public boolean contains(int aValue) { aValue -= OFFSET; return aValue >= 0 && this.VALUES.get(aValue); } /** * Retrieves the current value of the variable if instantiated, otherwier the lower bound. * * @return the current value (or lower bound if not yet instantiated). */ public int getValue() { assert instantiated() : name + " not instantiated"; return getLB(); } /** * Retrieves the lower bound of the variable * * @return the lower bound */ public int getLB() { return this.LB.get() + OFFSET; } /** * Retrieves the upper bound of the variable * * @return the upper bound */ public int getUB() { return this.UB.get() + OFFSET; } public int getDomainSize() { return SIZE.get(); } public int nextValue(int aValue) { aValue -= OFFSET; int lb = LB.get(); if (aValue < 0 || aValue < lb) return lb + OFFSET; aValue = VALUES.nextSetBit(aValue + 1); if (aValue > -1) return aValue + OFFSET; return Integer.MAX_VALUE; } @Override public int previousValue(int aValue) { aValue -= OFFSET; int ub = UB.get(); if (aValue > ub) return ub + OFFSET; aValue = VALUES.prevSetBit(aValue - 1); if (aValue > -1) return aValue + OFFSET; return Integer.MIN_VALUE; } @Override public boolean hasEnumeratedDomain() { return true; } @Override public IntDelta getDelta() { return delta; } public String toString() { StringBuilder s = new StringBuilder(20); s.append(name).append(" = "); if (SIZE.get() == 1) { s.append(this.getLB()); } else { s.append('{').append(getLB()); int nb = 5; for (int i = nextValue(getLB()); i < Integer.MAX_VALUE && nb > 0; i = nextValue(i)) { s.append(',').append(i); nb } if (nb == 0) { s.append("...,").append(this.getUB()); } s.append('}'); } return s.toString(); } ///// methode liees au fait qu'une variable est observable ///// @Override public void analyseAndAdapt(int mask) { super.analyseAndAdapt(mask); if (!reactOnRemoval && ((modificationEvents & EventType.REMOVE.mask) != 0)) { delta = new Delta(); reactOnRemoval = true; } } public void notifyMonitors(EventType event, @NotNull ICause cause) throws ContradictionException { if ((modificationEvents & event.mask) != 0) { records.forEach(afterModification.set(this, event, cause)); } notifyViews(event, cause); } public Explanation explain(VariableState what) { Explanation expl = new Explanation(null, null); OffsetIStateBitset invdom = solver.getExplainer().getRemovedValues(this); DisposableValueIterator it = invdom.getValueIterator(); while (it.hasNext()) { int val = it.next(); if ((what == VariableState.LB && val < this.getLB()) || (what == VariableState.UB && val > this.getUB()) || (what == VariableState.DOM)) { // System.out.println("solver.explainer.explain(this,"+ val +") = " + solver.explainer.explain(this, val)); expl.add(solver.getExplainer().explain(this, val)); } } // System.out.println("BitsetIntVarImpl.explain " + this + invdom + " expl: " + expl); return expl; } @Override public Explanation explain(VariableState what, int val) { Explanation expl = new Explanation(); expl.add(solver.getExplainer().explain(this, val)); return expl; } @Override public void contradiction(ICause cause, EventType event, String message) throws ContradictionException { records.forEach(onContradiction.set(this, event, cause)); solver.getEngine().fails(cause, this, message); } @Override public int getTypeAndKind() { return VAR + INT; } @Override public DisposableValueIterator getValueIterator(boolean bottomUp) { if (_viterator == null || !_viterator.isReusable()) { _viterator = new DisposableValueIterator() { int value; @Override public void bottomUpInit() { super.bottomUpInit(); this.value = LB.get(); } @Override public void topDownInit() { super.topDownInit(); this.value = UB.get(); } @Override public boolean hasNext() { return this.value != -1; } @Override public boolean hasPrevious() { return this.value != -1; } @Override public int next() { int old = this.value; this.value = VALUES.nextSetBit(this.value + 1); return old + OFFSET; } @Override public int previous() { int old = this.value; this.value = VALUES.prevSetBit(this.value - 1); return old + OFFSET; } }; } if (bottomUp) { _viterator.bottomUpInit(); } else { _viterator.topDownInit(); } return _viterator; } @Override public DisposableRangeIterator getRangeIterator(boolean bottomUp) { if (_riterator == null || !_riterator.isReusable()) { _riterator = new DisposableRangeIterator() { int from; int to; @Override public void bottomUpInit() { super.bottomUpInit(); this.from = VALUES.nextSetBit(0); this.to = VALUES.nextClearBit(from + 1) - 1; } @Override public void topDownInit() { super.topDownInit(); this.to = VALUES.prevSetBit(VALUES.size() - 1); this.from = VALUES.prevClearBit(to) + 1; } public boolean hasNext() { return this.from != -1; } @Override public boolean hasPrevious() { return this.to != -1; } public void next() { this.from = VALUES.nextSetBit(this.to + 1); this.to = VALUES.nextClearBit(this.from) - 1; } @Override public void previous() { this.to = VALUES.prevSetBit(this.from - 1); this.from = VALUES.prevClearBit(this.to) + 1; } @Override public int min() { return from + OFFSET; } @Override public int max() { return to + OFFSET; } }; } if (bottomUp) { _riterator.bottomUpInit(); } else { _riterator.topDownInit(); } return _riterator; } }
package org.batfish.client; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintStream; import java.io.PrintWriter; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.UUID; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.io.output.WriterOutputStream; import org.apache.commons.lang.exception.ExceptionUtils; import org.batfish.client.Settings.RunMode; import org.batfish.common.BatfishException; import org.batfish.common.BfConsts; import org.batfish.common.BatfishLogger; import org.batfish.common.WorkItem; import org.batfish.common.CoordConsts.WorkStatusCode; import org.batfish.common.util.BatfishObjectMapper; import org.batfish.common.util.CommonUtil; import org.batfish.common.util.ZipUtility; import org.batfish.datamodel.answers.Answer; import org.batfish.datamodel.questions.EnvironmentCreationQuestion; import org.batfish.datamodel.questions.QuestionType; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import jline.console.ConsoleReader; import jline.console.completer.Completer; import jline.console.completer.StringsCompleter; public class Client { private static final String COMMAND_ANSWER = "answer"; private static final String COMMAND_ANSWER_DELTA = "answer-delta"; private static final String COMMAND_CAT = "cat"; private static final String COMMAND_CHECK_API_KEY = "checkapikey"; private static final String COMMAND_CLEAR_SCREEN = "cls"; private static final String COMMAND_DEL_CONTAINER = "del-container"; private static final String COMMAND_DEL_ENVIRONMENT = "del-environment"; private static final String COMMAND_DEL_QUESTION = "del-question"; private static final String COMMAND_DEL_TESTRIG = "del-testrig"; private static final String COMMAND_DIR = "dir"; private static final String COMMAND_ECHO = "echo"; private static final String COMMAND_EXIT = "exit"; private static final String COMMAND_GEN_DELTA_DP = "generate-delta-dataplane"; private static final String COMMAND_GEN_DP = "generate-dataplane"; private static final String COMMAND_GET = "get"; private static final String COMMAND_GET_DELTA = "get-delta"; private static final String COMMAND_HELP = "help"; private static final String COMMAND_INIT_CONTAINER = "init-container"; private static final String COMMAND_INIT_DELTA_ENV = "init-delta-environment"; private static final String COMMAND_INIT_DELTA_TESTRIG = "init-delta-testrig"; private static final String COMMAND_INIT_TESTRIG = "init-testrig"; private static final String COMMAND_LIST_CONTAINERS = "list-containers"; private static final String COMMAND_LIST_ENVIRONMENTS = "list-environments"; private static final String COMMAND_LIST_QUESTIONS = "list-questions"; private static final String COMMAND_LIST_TESTRIGS = "list-testrigs"; private static final String COMMAND_PROMPT = "prompt"; private static final String COMMAND_PWD = "pwd"; private static final String COMMAND_QUIT = "quit"; private static final String COMMAND_SET_BATFISH_LOGLEVEL = "set-batfish-loglevel"; private static final String COMMAND_SET_CONTAINER = "set-container"; private static final String COMMAND_SET_DELTA_ENV = "set-delta-environment"; private static final String COMMAND_SET_DELTA_TESTRIG = "set-delta-testrig"; private static final String COMMAND_SET_ENV = "set-environment"; private static final String COMMAND_SET_LOGLEVEL = "set-loglevel"; private static final String COMMAND_SET_PRETTY_PRINT = "set-pretty-print"; private static final String COMMAND_SET_TESTRIG = "set-testrig"; private static final String COMMAND_SHOW_API_KEY = "show-api-key"; private static final String COMMAND_SHOW_BATFISH_LOGLEVEL = "show-batfish-loglevel"; private static final String COMMAND_SHOW_CONTAINER = "show-container"; private static final String COMMAND_SHOW_COORDINATOR_HOST = "show-coordinator-host"; private static final String COMMAND_SHOW_DELTA_TESTRIG = "show-delta-testrig"; private static final String COMMAND_SHOW_LOGLEVEL = "show-loglevel"; private static final String COMMAND_SHOW_TESTRIG = "show-testrig"; private static final String COMMAND_TEST = "test"; private static final String COMMAND_UPLOAD_CUSTOM_OBJECT = "upload-custom"; private static final String DEFAULT_CONTAINER_PREFIX = "cp"; private static final String DEFAULT_DELTA_ENV_PREFIX = "env_"; private static final String DEFAULT_ENV_NAME = BfConsts.RELPATH_DEFAULT_ENVIRONMENT_NAME; private static final String DEFAULT_QUESTION_PREFIX = "q"; private static final String DEFAULT_TESTRIG_PREFIX = "tr_"; private static final String FLAG_FAILING_TEST = "-error"; private static final String FLAG_NO_DATAPLANE = "-nodataplane"; private static final Map<String, String> MAP_COMMANDS = initCommands(); private static Map<String, String> initCommands() { Map<String, String> descs = new TreeMap<>(); descs.put(COMMAND_ANSWER, COMMAND_ANSWER + " <question-file> [param1=value1 [param2=value2] ...]\n" + "\t Answer the question in the file for the default environment"); descs.put(COMMAND_ANSWER_DELTA, COMMAND_ANSWER_DELTA + " <question-file> [param1=value1 [param2=value2] ...]\n" + "\t Answer the question in the file for the delta environment"); descs.put(COMMAND_CAT, COMMAND_CAT + " <filename>\n" + "\t Print the contents of the file"); // descs.put(COMMAND_CHANGE_DIR, COMMAND_CHANGE_DIR // + " <dirname>\n" // + "\t Change the working directory"); descs.put(COMMAND_CLEAR_SCREEN, COMMAND_CLEAR_SCREEN + "\n" + "\t Clear screen"); descs.put(COMMAND_DEL_CONTAINER, COMMAND_DEL_CONTAINER + "<container-name>" + "\t Delete the specified container"); descs.put(COMMAND_DEL_ENVIRONMENT, COMMAND_DEL_ENVIRONMENT + "<environment-name>" + "\t Delete the specified environment"); descs.put(COMMAND_DEL_QUESTION, COMMAND_DEL_QUESTION + "<question-name>" + "\t Delete the specified question"); descs.put(COMMAND_DEL_TESTRIG, COMMAND_DEL_TESTRIG + "<testrig-name>" + "\t Delete the specified testrig"); descs.put(COMMAND_DIR, COMMAND_DIR + "<dir>" + "\t List directory contents"); descs.put(COMMAND_ECHO, COMMAND_ECHO + "<message>" + "\t Echo the message"); descs.put(COMMAND_EXIT, COMMAND_EXIT + "\n" + "\t Terminate interactive client session"); descs.put(COMMAND_GEN_DELTA_DP, COMMAND_GEN_DELTA_DP + "\n" + "\t Generate dataplane for the delta environment"); descs.put(COMMAND_GEN_DP, COMMAND_GEN_DP + "\n" + "\t Generate dataplane for the default environment"); descs.put(COMMAND_GET, COMMAND_GET + " <question-type> [param1=value1 [param2=value2] ...]\n" + "\t Answer the question by type for the delta environment"); descs.put(COMMAND_GET_DELTA, COMMAND_GET_DELTA + " <question-file> [param1=value1 [param2=value2] ...]\n" + "\t Answer the question by type for the delta environment"); descs.put(COMMAND_HELP, COMMAND_HELP + "\n" + "\t Print the list of supported commands"); descs.put(COMMAND_CHECK_API_KEY, COMMAND_CHECK_API_KEY + "\t Check if API Key is valid"); descs.put(COMMAND_INIT_CONTAINER, COMMAND_INIT_CONTAINER + " [<container-name-prefix>]\n" + "\t Initialize a new container"); descs.put(COMMAND_INIT_DELTA_ENV, COMMAND_INIT_DELTA_ENV + " [" + FLAG_NO_DATAPLANE + "] <environment zipfile or directory> [<environment-name>]\n" + "\t Initialize the delta environment"); descs.put(COMMAND_INIT_DELTA_TESTRIG, COMMAND_INIT_DELTA_TESTRIG + " [" + FLAG_NO_DATAPLANE + "] <testrig zipfile or directory> [<environment name>]\n" + "\t Initialize the delta testrig with default environment"); descs.put(COMMAND_INIT_TESTRIG, COMMAND_INIT_TESTRIG + " [" + FLAG_NO_DATAPLANE + "] <testrig zipfile or directory> [<environment name>]\n" + "\t Initialize the testrig with default environment"); descs.put(COMMAND_LIST_CONTAINERS, COMMAND_LIST_CONTAINERS + "\n" + "\t List the containers to which you have access"); descs.put(COMMAND_LIST_ENVIRONMENTS, COMMAND_LIST_ENVIRONMENTS + "\n" + "\t List the environments under current container and testrig"); descs.put(COMMAND_LIST_QUESTIONS, COMMAND_LIST_QUESTIONS + "\n" + "\t List the questions under current container and testrig"); descs.put(COMMAND_LIST_TESTRIGS, COMMAND_LIST_TESTRIGS + "\n" + "\t List the testrigs within the current container"); descs.put(COMMAND_PROMPT, COMMAND_PROMPT + "\n" + "\t Prompts for user to press enter"); descs.put(COMMAND_PWD, COMMAND_PWD + "\n" + "\t Prints the working directory"); descs.put(COMMAND_QUIT, COMMAND_QUIT + "\n" + "\t Terminate interactive client session"); descs.put(COMMAND_SET_BATFISH_LOGLEVEL, COMMAND_SET_BATFISH_LOGLEVEL + " <debug|info|output|warn|error>\n" + "\t Set the batfish loglevel. Default is warn"); descs.put(COMMAND_SET_CONTAINER, COMMAND_SET_CONTAINER + " <container-name>\n" + "\t Set the current container"); descs.put(COMMAND_SET_DELTA_ENV, COMMAND_SET_DELTA_ENV + " <environment-name>\n" + "\t Set the delta environment"); descs.put(COMMAND_SET_DELTA_TESTRIG, COMMAND_SET_DELTA_TESTRIG + " <testrig-name> [environment name]\n" + "\t Set the delta testrig"); descs.put(COMMAND_SET_ENV, COMMAND_SET_ENV + " <environment-name>\n" + "\t Set the current base environment"); descs.put(COMMAND_SET_LOGLEVEL, COMMAND_SET_LOGLEVEL + " <debug|info|output|warn|error>\n" + "\t Set the client loglevel. Default is output"); descs.put(COMMAND_SET_PRETTY_PRINT, COMMAND_SET_PRETTY_PRINT + " <true|false>\n" + "\t Whether to pretty print answers"); descs.put(COMMAND_SET_TESTRIG, COMMAND_SET_TESTRIG + " <testrig-name> [environment name]\n" + "\t Set the base testrig"); descs.put(COMMAND_SHOW_API_KEY, COMMAND_SHOW_API_KEY + "\n" + "\t Show API Key"); descs.put(COMMAND_SHOW_BATFISH_LOGLEVEL, COMMAND_SHOW_BATFISH_LOGLEVEL + "\n" + "\t Show current batfish loglevel"); descs.put(COMMAND_SHOW_CONTAINER, COMMAND_SHOW_CONTAINER + "\n" + "\t Show active container"); descs.put(COMMAND_SHOW_COORDINATOR_HOST, COMMAND_SHOW_COORDINATOR_HOST + "\n" + "\t Show coordinator host"); descs.put(COMMAND_SHOW_LOGLEVEL, COMMAND_SHOW_LOGLEVEL + "\n" + "\t Show current client loglevel"); descs.put(COMMAND_SHOW_DELTA_TESTRIG, COMMAND_SHOW_DELTA_TESTRIG + "\n" + "\t Show delta testrig and environment"); descs.put(COMMAND_SHOW_TESTRIG, COMMAND_SHOW_TESTRIG + "\n" + "\t Show base testrig and environment"); descs.put(COMMAND_TEST, COMMAND_TEST + " [-fail] <reference file> <command> \n" + "\t Show base testrig and environment"); descs.put(COMMAND_UPLOAD_CUSTOM_OBJECT, COMMAND_UPLOAD_CUSTOM_OBJECT + " <object-name> <object-file>\n" + "\t Uploads a custom object"); return descs; } private String _currContainerName = null; private String _currDeltaEnv = null; private String _currDeltaTestrig; private String _currEnv = null; private String _currTestrig = null; private BatfishLogger _logger; private BfCoordPoolHelper _poolHelper; private ConsoleReader _reader; private Settings _settings; private BfCoordWorkHelper _workHelper; public Client(Settings settings) { _settings = settings; switch (_settings.getRunMode()) { case batch: if (_settings.getBatchCommandFile() == null) { System.err.println( "org.batfish.client: Command file not specified while running in batch mode."); System.err.printf( "Use '-%s <cmdfile>' if you want batch mode, or '-%s interactive' if you want interactive mode\n", Settings.ARG_COMMAND_FILE, Settings.ARG_RUN_MODE); System.exit(1); } _logger = new BatfishLogger(_settings.getLogLevel(), false, _settings.getLogFile(), false, false); break; case genquestions: if (_settings.getQuestionsDir() == null) { System.err.println( "org.batfish.client: Out dir not specified while running in genquestions mode."); System.err.printf("Use '-%s <cmdfile>'\n", Settings.ARG_QUESTIONS_DIR); System.exit(1); } _logger = new BatfishLogger(_settings.getLogLevel(), false, _settings.getLogFile(), false, false); break; case interactive: try { _reader = new ConsoleReader(); _reader.setPrompt("batfish> "); _reader.setExpandEvents(false); List<Completer> completors = new LinkedList<>(); completors.add(new StringsCompleter(MAP_COMMANDS.keySet())); for (Completer c : completors) { _reader.addCompleter(c); } PrintWriter pWriter = new PrintWriter(_reader.getOutput(), true); OutputStream os = new WriterOutputStream(pWriter); PrintStream ps = new PrintStream(os, true); _logger = new BatfishLogger(_settings.getLogLevel(), false, ps); } catch (Exception e) { System.err.printf("Could not initialize client: %s\n", e.getMessage()); System.exit(1); } break; default: System.err.println("org.batfish.client: Unknown run mode."); System.exit(1); } } public Client(String[] args) throws Exception { this(new Settings(args)); } private boolean answerFile(String questionFile, String paramsLine, boolean isDelta, FileWriter outWriter) throws Exception { if (!new File(questionFile).exists()) { throw new FileNotFoundException( "Question file not found: " + questionFile); } String questionName = DEFAULT_QUESTION_PREFIX + "_" + UUID.randomUUID().toString(); File paramsFile = createTempFile("parameters", paramsLine); paramsFile.deleteOnExit(); // upload the question boolean resultUpload = _workHelper.uploadQuestion(_currContainerName, _currTestrig, questionName, questionFile, paramsFile.getAbsolutePath()); if (!resultUpload) { return false; } _logger.debug("Uploaded question. Answering now.\n"); // delete the temporary params file if (paramsFile != null) { paramsFile.delete(); } // answer the question WorkItem wItemAs = _workHelper.getWorkItemAnswerQuestion(questionName, _currContainerName, _currTestrig, _currEnv, _currDeltaTestrig, _currDeltaEnv, isDelta); return execute(wItemAs, outWriter); } private boolean answerType(String questionType, String paramsLine, boolean isDelta, FileWriter outWriter) throws Exception { Map<String, String> parameters = parseParams(paramsLine); String questionString; String parametersString = ""; if (questionType.startsWith(QuestionHelper.MACRO_PREFIX)) { try { questionString = QuestionHelper.resolveMacro(questionType, paramsLine); } catch (BatfishException e) { _logger.errorf("Could not resolve macro: %s\n", e.getMessage()); return false; } } else { questionString = QuestionHelper.getQuestionString(questionType); _logger.debugf("Question Json:\n%s\n", questionString); parametersString = QuestionHelper.getParametersString(parameters); _logger.debugf("Parameters Json:\n%s\n", parametersString); } File questionFile = createTempFile("question", questionString); boolean result = answerFile(questionFile.getAbsolutePath(), parametersString, isDelta, outWriter); if (questionFile != null) { questionFile.delete(); } return result; } private File createTempFile(String filePrefix, String content) throws IOException { File tempFile = Files.createTempFile(filePrefix, null).toFile(); tempFile.deleteOnExit(); _logger.debugf("Creating temporary %s file: %s\n", filePrefix, tempFile.getAbsolutePath()); FileWriter writer = new FileWriter(tempFile); writer.write(content + "\n"); writer.close(); return tempFile; } private boolean execute(WorkItem wItem, FileWriter outWriter) throws Exception { wItem.addRequestParam(BfConsts.ARG_LOG_LEVEL, _settings.getBatfishLogLevel()); _logger.info("work-id is " + wItem.getId() + "\n"); boolean queueWorkResult = _workHelper.queueWork(wItem); _logger.info("Queuing result: " + queueWorkResult + "\n"); if (!queueWorkResult) { return queueWorkResult; } WorkStatusCode status = _workHelper.getWorkStatus(wItem.getId()); while (status != WorkStatusCode.TERMINATEDABNORMALLY && status != WorkStatusCode.TERMINATEDNORMALLY && status != WorkStatusCode.ASSIGNMENTERROR) { _logger.output(". "); _logger.infof("status: %s\n", status); Thread.sleep(1 * 1000); status = _workHelper.getWorkStatus(wItem.getId()); } _logger.output("\n"); _logger.infof("final status: %s\n", status); // get the answer String ansFileName = wItem.getId() + BfConsts.SUFFIX_ANSWER_JSON_FILE; String downloadedAnsFile = _workHelper.getObject(wItem.getContainerName(), wItem.getTestrigName(), ansFileName); if (downloadedAnsFile == null) { _logger.errorf( "Failed to get answer file %s. Fix batfish and remove the statement below this line\n", ansFileName); // return false; } else { String answerString = CommonUtil .readFile(Paths.get(downloadedAnsFile)); // Check if we need to make things pretty // Don't if we are writing to FileWriter, because we need valid JSON in // that case String answerStringToPrint = answerString; if (outWriter == null && _settings.getPrettyPrintAnswers()) { ObjectMapper mapper = new BatfishObjectMapper(); Answer answer = mapper.readValue(answerString, Answer.class); answerStringToPrint = answer.prettyPrint(); } if (outWriter == null) { _logger.output(answerStringToPrint + "\n"); } else { outWriter.write(answerStringToPrint); } // tests serialization/deserialization when running in debug mode if (_logger.getLogLevel() >= BatfishLogger.LEVEL_DEBUG) { try { ObjectMapper mapper = new BatfishObjectMapper(); Answer answer = mapper.readValue(answerString, Answer.class); String newAnswerString = mapper.writeValueAsString(answer); JsonNode tree = mapper.readTree(answerString); JsonNode newTree = mapper.readTree(newAnswerString); if (!CommonUtil.checkJsonEqual(tree, newTree)) { // if (!tree.equals(newTree)) { _logger.errorf( "Original and recovered Json are different. Recovered = %s\n", newAnswerString); } } catch (Exception e) { _logger.outputf("Could NOT deserialize Json to Answer: %s\n", e.getMessage()); } } } // get and print the log when in debugging mode if (_logger.getLogLevel() >= BatfishLogger.LEVEL_DEBUG) { _logger.output(" String logFileName = wItem.getId() + BfConsts.SUFFIX_LOG_FILE; String downloadedFile = _workHelper.getObject(wItem.getContainerName(), wItem.getTestrigName(), logFileName); if (downloadedFile == null) { _logger.errorf("Failed to get log file %s\n", logFileName); return false; } else { try (BufferedReader br = new BufferedReader( new FileReader(downloadedFile))) { String line = null; while ((line = br.readLine()) != null) { _logger.output(line + "\n"); } } } } // TODO: remove the log file? if (status == WorkStatusCode.TERMINATEDNORMALLY) { return true; } else { // _logger.errorf("WorkItem failed: %s", wItem); return false; } } private boolean generateDataplane(FileWriter outWriter) throws Exception { if (!isSetTestrig() || !isSetContainer(true)) { return false; } // generate the data plane WorkItem wItemGenDp = _workHelper.getWorkItemGenerateDataPlane( _currContainerName, _currTestrig, _currEnv); return execute(wItemGenDp, outWriter); } private boolean generateDeltaDataplane(FileWriter outWriter) throws Exception { if (!isSetDeltaEnvironment() || !isSetTestrig() || !isSetContainer(true)) { return false; } WorkItem wItemGenDdp = _workHelper.getWorkItemGenerateDeltaDataPlane( _currContainerName, _currTestrig, _currEnv, _currDeltaEnv); return execute(wItemGenDdp, outWriter); } private void generateQuestions() { File questionsDir = Paths.get(_settings.getQuestionsDir()).toFile(); if (!questionsDir.exists()) { if (!questionsDir.mkdirs()) { _logger.errorf("Could not create questions dir %s\n", _settings.getQuestionsDir()); System.exit(1); } } for (QuestionType qType : QuestionType.values()) { try { String questionString = QuestionHelper.getQuestionString(qType); String qFile = Paths .get(_settings.getQuestionsDir(), qType.questionTypeName() + ".json") .toFile().getAbsolutePath(); PrintWriter writer = new PrintWriter(qFile); writer.write(questionString); writer.close(); } catch (Exception e) { _logger.errorf("Could not write question %s: %s\n", qType.questionTypeName(), e.getMessage()); } } } private List<String> getCommandOptions(String[] words) { List<String> options = new LinkedList<>(); int currIndex = 1; while (currIndex < words.length && words[currIndex].startsWith("-")) { options.add(words[currIndex]); currIndex++; } return options; } private List<String> getCommandParameters(String[] words, int numOptions) { List<String> parameters = new LinkedList<>(); for (int index = numOptions + 1; index < words.length; index++) { parameters.add(words[index]); } return parameters; } public BatfishLogger getLogger() { return _logger; } private void initHelpers() { String workMgr = _settings.getCoordinatorHost() + ":" + _settings.getCoordinatorWorkPort(); String poolMgr = _settings.getCoordinatorHost() + ":" + _settings.getCoordinatorPoolPort(); _workHelper = new BfCoordWorkHelper(workMgr, _logger, _settings); _poolHelper = new BfCoordPoolHelper(poolMgr); int numTries = 0; while (true) { try { numTries++; if (_workHelper.isReachable()) { // print this message only we might have printed unable to // connect message earlier if (numTries > 1) { _logger.outputf("Connected to coordinator after %d tries\n", numTries); } break; } Thread.sleep(1 * 1000); // 1 second } catch (Exception e) { _logger.errorf( "Exeption while checking reachability to coordinator: ", e.getMessage()); System.exit(1); } } } private boolean isSetContainer(boolean printError) { if (!_settings.getSanityCheck()) { return true; } if (_currContainerName == null) { if (printError) { _logger.errorf("Active container is not set\n"); } return false; } return true; } private boolean isSetDeltaEnvironment() { if (!_settings.getSanityCheck()) { return true; } if (_currDeltaTestrig == null) { _logger.errorf("Active delta testrig is not set\n"); return false; } if (_currDeltaEnv == null) { _logger.errorf("Active delta environment is not set\n"); return false; } return true; } private boolean isSetTestrig() { if (!_settings.getSanityCheck()) { return true; } if (_currTestrig == null) { _logger.errorf("Active testrig is not set.\n"); _logger.errorf( "Specify testrig on command line (-%s <testrigdir>) or use command (%s [%s] <testrigdir>)\n", Settings.ARG_TESTRIG_DIR, COMMAND_INIT_TESTRIG, FLAG_NO_DATAPLANE); return false; } return true; } private Map<String, String> parseParams(String paramsLine) { Map<String, String> parameters = new HashMap<>(); Pattern pattern = Pattern.compile("([\\w_]+)\\s*=\\s*(.+)"); String[] params = paramsLine.split("\\|"); _logger.debugf("Found %d parameters\n", params.length); for (String param : params) { Matcher matcher = pattern.matcher(param); while (matcher.find()) { String key = matcher.group(1).trim(); String value = matcher.group(2).trim(); _logger.debugf("key=%s value=%s\n", key, value); parameters.put(key, value); } } return parameters; } private void printUsage() { for (Map.Entry<String, String> entry : MAP_COMMANDS.entrySet()) { _logger.output(entry.getValue() + "\n\n"); } } private boolean processCommand(String command) { String line = command.trim(); if (line.length() == 0 || line.startsWith(" return true; } _logger.debug("Doing command: " + line + "\n"); String[] words = line.split("\\s+"); if (!validCommandUsage(words)) { return false; } return processCommand(words, null); } private boolean processCommand(String[] words, FileWriter outWriter) { try { List<String> options = getCommandOptions(words); List<String> parameters = getCommandParameters(words, options.size()); String command = words[0]; switch (command) { // this is a hidden command for testing case "add-worker": { boolean result = _poolHelper.addBatfishWorker(words[1]); _logger.output("Result: " + result + "\n"); return true; } case COMMAND_ANSWER: { if (!isSetTestrig() || !isSetContainer(true)) { return false; } String questionFile = parameters.get(0); String paramsLine = CommonUtil.joinStrings(" ", Arrays.copyOfRange(words, 2 + options.size(), words.length)); return answerFile(questionFile, paramsLine, false, outWriter); } case COMMAND_ANSWER_DELTA: { if (!isSetDeltaEnvironment() || !isSetTestrig() || !isSetContainer(true)) { return false; } String questionFile = parameters.get(0); String paramsLine = CommonUtil.joinStrings(" ", Arrays.copyOfRange(words, 2 + options.size(), words.length)); return answerFile(questionFile, paramsLine, true, outWriter); } case COMMAND_CAT: { String filename = words[1]; try (BufferedReader br = new BufferedReader( new FileReader(filename))) { String line = null; while ((line = br.readLine()) != null) { _logger.output(line + "\n"); } } return true; } case COMMAND_DEL_CONTAINER: { String containerName = parameters.get(0); boolean result = _workHelper.delContainer(containerName); _logger.outputf("Result of deleting container: %s\n", result); return true; } case COMMAND_DEL_ENVIRONMENT: { if (!isSetTestrig() || !isSetContainer(true)) { return false; } String envName = parameters.get(0); boolean result = _workHelper.delEnvironment(_currContainerName, _currTestrig, envName); _logger.outputf("Result of deleting environment: %s\n", result); return true; } case COMMAND_DEL_QUESTION: { if (!isSetTestrig() || !isSetContainer(true)) { return false; } String qName = parameters.get(0); boolean result = _workHelper.delQuestion(_currContainerName, _currTestrig, qName); _logger.outputf("Result of deleting question: %s\n", result); return true; } case COMMAND_DEL_TESTRIG: { if (!isSetContainer(true)) { return false; } String testrigName = parameters.get(0); boolean result = _workHelper.delTestrig(_currContainerName, testrigName); _logger.outputf("Result of deleting testrig: %s\n", result); return true; } case COMMAND_DIR: { String dirname = (parameters.size() == 1) ? parameters.get(0) : "."; File currDirectory = new File(dirname); for (File file : currDirectory.listFiles()) { _logger.output(file.getName() + "\n"); } return true; } case COMMAND_ECHO: { _logger.outputf("%s\n", CommonUtil.joinStrings(" ", Arrays.copyOfRange(words, 1, words.length))); return true; } case COMMAND_EXIT: case COMMAND_QUIT: { System.exit(0); return true; } case COMMAND_GEN_DP: { return generateDataplane(outWriter); } case COMMAND_GEN_DELTA_DP: { return generateDeltaDataplane(outWriter); } case COMMAND_GET: case COMMAND_GET_DELTA: { boolean isDelta = (command.equals(COMMAND_GET_DELTA)); if (!isSetTestrig() || !isSetContainer(true) || (isDelta && !isSetDeltaEnvironment())) { return false; } String qTypeStr = parameters.get(0); String paramsLine = CommonUtil.joinStrings(" ", Arrays.copyOfRange(words, 2 + options.size(), words.length)); if (!qTypeStr.startsWith(QuestionHelper.MACRO_PREFIX) && QuestionType.fromName( qTypeStr) == QuestionType.ENVIRONMENT_CREATION) { String deltaEnvName = DEFAULT_DELTA_ENV_PREFIX + UUID.randomUUID().toString(); String prefixString = (paramsLine.trim().length() > 0) ? " | " : ""; paramsLine += String.format("%s %s=%s", prefixString, EnvironmentCreationQuestion.ENVIRONMENT_NAME_VAR, deltaEnvName); if (!answerType(qTypeStr, paramsLine, isDelta, outWriter)) { return false; } _currDeltaEnv = deltaEnvName; _currDeltaTestrig = _currTestrig; _logger.outputf( "Active delta testrig->environment is now %s->%s\n", _currDeltaTestrig, _currDeltaEnv); return true; } else { return answerType(qTypeStr, paramsLine, isDelta, outWriter); } } case COMMAND_HELP: { printUsage(); return true; } case COMMAND_CHECK_API_KEY: { String isValid = _workHelper.checkApiKey(); _logger.outputf("Api key validitiy: %s\n", isValid); return true; } case COMMAND_INIT_CONTAINER: { String containerPrefix = (words.length > 1) ? words[1] : DEFAULT_CONTAINER_PREFIX; _currContainerName = _workHelper.initContainer(containerPrefix); _logger.outputf("Active container set to %s\n", _currContainerName); return true; } case COMMAND_INIT_DELTA_ENV: { if (!isSetTestrig() || !isSetContainer(true)) { return false; } // check if we are being asked to not generate the dataplane boolean generateDeltaDataplane = true; if (options.size() == 1) { if (options.get(0).equals(FLAG_NO_DATAPLANE)) { generateDeltaDataplane = false; } else { _logger.outputf("Unknown option %s\n", options.get(0)); return false; } } String deltaEnvLocation = parameters.get(0); String deltaEnvName = (parameters.size() > 1) ? parameters.get(1) : DEFAULT_DELTA_ENV_PREFIX + UUID.randomUUID().toString(); if (!uploadTestrigOrEnv(deltaEnvLocation, deltaEnvName, false)) { return false; } _currDeltaEnv = deltaEnvName; _currDeltaTestrig = _currTestrig; _logger.outputf("Active delta testrig->environment is now %s->%s\n", _currDeltaTestrig, _currDeltaEnv); WorkItem wItemGenDdp = _workHelper .getWorkItemCompileDeltaEnvironment(_currContainerName, _currDeltaTestrig, _currEnv, _currDeltaEnv); if (!execute(wItemGenDdp, outWriter)) { return false; } if (generateDeltaDataplane) { _logger.output("Generating delta dataplane\n"); if (!generateDeltaDataplane(outWriter)) { return false; } _logger.output("Generated delta dataplane\n"); } return true; } case COMMAND_INIT_DELTA_TESTRIG: case COMMAND_INIT_TESTRIG: { boolean generateDataplane = true; if (options.size() == 1) { if (options.get(0).equals(FLAG_NO_DATAPLANE)) { generateDataplane = false; } else { _logger.outputf("Unknown option %s\n", options.get(0)); return false; } } String testrigLocation = parameters.get(0); String testrigName = (parameters.size() > 1) ? parameters.get(1) : DEFAULT_TESTRIG_PREFIX + UUID.randomUUID().toString(); // initialize the container if it hasn't been init'd before if (!isSetContainer(false)) { _currContainerName = _workHelper .initContainer(DEFAULT_CONTAINER_PREFIX); _logger.outputf("Init'ed and set active container to %s\n", _currContainerName); } if (!uploadTestrigOrEnv(testrigLocation, testrigName, true)) { return false; } _logger.output("Uploaded testrig. Parsing now.\n"); WorkItem wItemParse = _workHelper .getWorkItemParse(_currContainerName, testrigName); if (!execute(wItemParse, outWriter)) { return false; } if (command.equals(COMMAND_INIT_TESTRIG)) { _currTestrig = testrigName; _currEnv = DEFAULT_ENV_NAME; _logger.outputf("Base testrig is now %s\n", _currTestrig); } else { _currDeltaTestrig = testrigName; _currDeltaEnv = DEFAULT_ENV_NAME; _logger.outputf("Delta testrig is now %s\n", _currTestrig); } if (generateDataplane) { _logger.output("Generating dataplane now\n"); if (!generateDataplane(outWriter)) { return false; } _logger.output("Generated dataplane\n"); } return true; } case COMMAND_LIST_CONTAINERS: { String[] containerList = _workHelper.listContainers(); _logger.outputf("Containers: %s\n", Arrays.toString(containerList)); return true; } case COMMAND_LIST_ENVIRONMENTS: { if (!isSetTestrig() || !isSetContainer(true)) { return false; } String[] environmentList = _workHelper .listEnvironments(_currContainerName, _currTestrig); _logger.outputf("Environments: %s\n", Arrays.toString(environmentList)); return true; } case COMMAND_LIST_QUESTIONS: { if (!isSetTestrig() || !isSetContainer(true)) { return false; } String[] questionList = _workHelper .listQuestions(_currContainerName, _currTestrig); _logger.outputf("Questions: %s\n", Arrays.toString(questionList)); return true; } case COMMAND_LIST_TESTRIGS: { Map<String, String> testrigs = _workHelper .listTestrigs(_currContainerName); if (testrigs != null) { for (String testrigName : testrigs.keySet()) { _logger.outputf("Testrig: %s\n%s\n", testrigName, testrigs.get(testrigName)); } } return true; } case COMMAND_PROMPT: { if (_settings.getRunMode() == RunMode.interactive) { _logger.output("\n\n[Press enter to proceed]\n\n"); BufferedReader in = new BufferedReader( new InputStreamReader(System.in)); in.readLine(); } return true; } case COMMAND_PWD: { final String dir = System.getProperty("user.dir"); _logger.output("working directory = " + dir + "\n"); return true; } case COMMAND_SET_BATFISH_LOGLEVEL: { String logLevelStr = parameters.get(0).toLowerCase(); if (!BatfishLogger.isValidLogLevel(logLevelStr)) { _logger.errorf("Undefined loglevel value: %s\n", logLevelStr); return false; } _settings.setBatfishLogLevel(logLevelStr); _logger.output("Changed batfish loglevel to " + logLevelStr + "\n"); return true; } case COMMAND_SET_CONTAINER: { _currContainerName = parameters.get(0); _logger.outputf("Active container is now set to %s\n", _currContainerName); return true; } case COMMAND_SET_DELTA_ENV: { _currDeltaEnv = parameters.get(0); if (_currDeltaTestrig == null) { _currDeltaTestrig = _currTestrig; } _logger.outputf("Active delta testrig->environment is now %s->%s\n", _currDeltaTestrig, _currDeltaEnv); return true; } case COMMAND_SET_ENV: { if (!isSetTestrig()) { return false; } _currEnv = parameters.get(0); _logger.outputf("Base testrig->env is now %s->%s\n", _currTestrig, _currEnv); return true; } case COMMAND_SET_DELTA_TESTRIG: { _currDeltaTestrig = parameters.get(0); _currDeltaEnv = (parameters.size() > 1) ? parameters.get(1) : DEFAULT_ENV_NAME; _logger.outputf("Delta testrig->env is now %s->%s\n", _currDeltaTestrig, _currDeltaEnv); return true; } case COMMAND_SET_LOGLEVEL: { String logLevelStr = parameters.get(0).toLowerCase(); if (!BatfishLogger.isValidLogLevel(logLevelStr)) { _logger.errorf("Undefined loglevel value: %s\n", logLevelStr); return false; } _logger.setLogLevel(logLevelStr); _settings.setLogLevel(logLevelStr); _logger.output("Changed client loglevel to " + logLevelStr + "\n"); return true; } case COMMAND_SET_PRETTY_PRINT: { String ppStr = parameters.get(0).toLowerCase(); boolean prettyPrint = Boolean.parseBoolean(ppStr); _settings.setPrettyPrintAnswers(prettyPrint); _logger.output("Set pretty printing answers to " + ppStr + "\n"); return true; } case COMMAND_SET_TESTRIG: { if (!isSetContainer(true)) { return false; } _currTestrig = parameters.get(0); _currEnv = (parameters.size() > 1) ? parameters.get(1) : DEFAULT_ENV_NAME; _logger.outputf("Base testrig->env is now %s->%s\n", _currTestrig, _currEnv); return true; } case COMMAND_SHOW_API_KEY: { _logger.outputf("Current API Key is %s\n", _settings.getApiKey()); return true; } case COMMAND_SHOW_BATFISH_LOGLEVEL: { _logger.outputf("Current batfish log level is %s\n", _settings.getBatfishLogLevel()); return true; } case COMMAND_SHOW_CONTAINER: { _logger.outputf("Current container is %s\n", _currContainerName); return true; } case COMMAND_SHOW_COORDINATOR_HOST: { _logger.outputf("Current coordinator host is %s\n", _settings.getCoordinatorHost()); return true; } case COMMAND_SHOW_LOGLEVEL: { _logger.outputf("Current client log level is %s\n", _logger.getLogLevelStr()); return true; } case COMMAND_SHOW_DELTA_TESTRIG: { if (!isSetDeltaEnvironment()) { return false; } _logger.outputf("Delta testrig->environment is %s->%s\n", _currDeltaTestrig, _currDeltaEnv); return true; } case COMMAND_SHOW_TESTRIG: { if (!isSetTestrig()) { return false; } _logger.outputf("Base testrig->environment is %s->%s\n", _currTestrig, _currEnv); return true; } case COMMAND_TEST: { boolean failingTest = false; int testCommandIndex = 1; if (parameters.get(testCommandIndex).equals(FLAG_FAILING_TEST)) { testCommandIndex++; failingTest = true; } String referenceFileName = parameters.get(0); String[] testCommand = parameters .subList(testCommandIndex, parameters.size()) .toArray(new String[0]); _logger.debugf("Ref file is %s. \n", referenceFileName, parameters.size()); _logger.debugf("Test command is %s\n", Arrays.toString(testCommand)); File referenceFile = new File(referenceFileName); if (!referenceFile.exists()) { _logger.errorf("Reference file does not exist: %s\n", referenceFileName); return false; } File testoutFile = Files.createTempFile("test", "out").toFile(); testoutFile.deleteOnExit(); FileWriter testoutWriter = new FileWriter(testoutFile); boolean testCommandSucceeded = processCommand(testCommand, testoutWriter); testoutWriter.close(); boolean testPassed = false; if (!failingTest && testCommandSucceeded) { try { String referenceOutput = CommonUtil .readFile(Paths.get(referenceFileName)); String testOutput = CommonUtil .readFile(Paths.get(testoutFile.getAbsolutePath())); ObjectMapper mapper = new BatfishObjectMapper(); JsonNode referenceJson = mapper.readTree(referenceOutput); JsonNode testJson = mapper.readTree(testOutput); if (CommonUtil.checkJsonEqual(referenceJson, testJson)) { testPassed = true; } } catch (Exception e) { _logger.errorf("Exception in comparing test results: " + ExceptionUtils.getStackTrace(e)); } } else if (failingTest) { testPassed = !testCommandSucceeded; } StringBuilder sb = new StringBuilder(); sb.append("'" + testCommand[0]); for (int i = 1; i < testCommand.length; i++) { sb.append(" " + testCommand[i]); } sb.append("'"); String testCommandText = sb.toString(); String message = "Test: " + testCommandText + (failingTest ? " results in error as expected" : " matches " + referenceFileName) + (testPassed ? ": Pass\n" : ": Fail\n"); _logger.output(message); if (!failingTest) { if (!testPassed) { String outFileName = referenceFile + ".testout"; Files.move(Paths.get(testoutFile.getAbsolutePath()), Paths.get(referenceFile + ".testout"), StandardCopyOption.REPLACE_EXISTING); _logger.outputf("Copied output to %s\n", outFileName); } } return true; } case COMMAND_UPLOAD_CUSTOM_OBJECT: { if (!isSetTestrig() || !isSetContainer(true)) { return false; } String objectName = parameters.get(0); String objectFile = parameters.get(1); // upload the object return _workHelper.uploadCustomObject(_currContainerName, _currTestrig, objectName, objectFile); } default: _logger.error("Unsupported command " + words[0] + "\n"); _logger.error("Type 'help' to see the list of valid commands\n"); return false; } } catch (Exception e) { e.printStackTrace(); return false; } } private boolean processCommands(List<String> commands) { for (String command : commands) { if (!processCommand(command)) { return false; } } return true; } public void run(List<String> initialCommands) { initHelpers(); _logger.debugf("Will use coordinator at %s: (_settings.getUseSsl()) ? "https" : "http", _settings.getCoordinatorHost()); if (!processCommands(initialCommands)) { return; } // set container if specified if (_settings.getContainerId() != null) { if (!processCommand( COMMAND_SET_CONTAINER + " " + _settings.getContainerId())) { return; } } // set testrig if dir or id is specified if (_settings.getTestrigDir() != null) { if (_settings.getTestrigId() != null) { System.err.println( "org.batfish.client: Cannot supply both testrigDir and testrigId."); System.exit(1); } if (!processCommand(COMMAND_INIT_TESTRIG + " " + FLAG_NO_DATAPLANE + " " + _settings.getTestrigDir())) { return; } } if (_settings.getTestrigId() != null) { if (!processCommand( COMMAND_SET_TESTRIG + " " + _settings.getTestrigId())) { return; } } switch (_settings.getRunMode()) { case batch: List<String> commands = null; try { commands = Files.readAllLines( Paths.get(_settings.getBatchCommandFile()), StandardCharsets.US_ASCII); } catch (Exception e) { System.err.printf("Exception in reading command file %s: %s", _settings.getBatchCommandFile(), e.getMessage()); System.exit(1); } processCommands(commands); break; case genquestions: generateQuestions(); break; case interactive: runInteractive(); break; default: System.err.println("org.batfish.client: Unknown run mode."); System.exit(1); } } private void runInteractive() { try { String rawLine; while ((rawLine = _reader.readLine()) != null) { String line = rawLine.trim(); if (line.length() == 0 || line.startsWith(" continue; } if (line.equals(COMMAND_CLEAR_SCREEN)) { _reader.clearScreen(); continue; } String[] words = line.split("\\s+"); if (words.length > 0) { if (validCommandUsage(words)) { processCommand(words, null); } } } } catch (Throwable t) { t.printStackTrace(); } } private boolean uploadTestrigOrEnv(String fileOrDir, String testrigOrEnvName, boolean isTestrig) throws Exception { File filePointer = new File(fileOrDir); String uploadFilename = fileOrDir; if (filePointer.isDirectory()) { File uploadFile = File.createTempFile("testrigOrEnv", "zip"); uploadFile.deleteOnExit(); uploadFilename = uploadFile.getAbsolutePath(); ZipUtility.zipFiles(filePointer.getAbsolutePath(), uploadFilename); } boolean result = (isTestrig) ? _workHelper.uploadTestrig(_currContainerName, testrigOrEnvName, uploadFilename) : _workHelper.uploadEnvironment(_currContainerName, _currTestrig, testrigOrEnvName, uploadFilename); // unequal means we must have created a temporary file if (uploadFilename != fileOrDir) { new File(uploadFilename).delete(); } return result; } private boolean validCommandUsage(String[] words) { return true; } }
package org.wings.io; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.Serializable; import java.io.UnsupportedEncodingException; /** * A Device encapsulating a StringBuilder * * @author <a href="mailto:[email protected]">Ole Langbehn</a> */ public final class StringBuilderDevice implements Device, Serializable { private StringBuilder builder; private transient ByteArrayOutputStream byteStream = null; public StringBuilderDevice() { builder = new StringBuilder(4 * 1024); } public StringBuilderDevice(int capacity) { builder = new StringBuilder(capacity); } public String toString() { flush(); return builder.toString(); } public boolean isSizePreserving() { return true; } /** * Flush this Stream. */ public void flush() { if (byteStream != null) { try { builder.append(byteStream.toString(IOUtil.getIOEncoding())); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } byteStream = null; } } public void close() { flush(); } public void reset() { flush(); builder.setLength(0); } private ByteArrayOutputStream getStream() { if (byteStream != null) return byteStream; byteStream = new ByteArrayOutputStream(); return byteStream; } /** * Print a String. */ public Device print(String s) { if (byteStream != null) flush(); builder.append(s); return this; } /** * Print a character. */ public Device print(char c) { if (byteStream != null) flush(); builder.append(c); return this; } /** * Print a character array. */ public Device print(char[] c) { if (byteStream != null) flush(); builder.append(c); return this; } /** * Print a character array. */ public Device print(char[] c, int start, int len) { if (byteStream != null) flush(); builder.append(c, start, len); return this; } /** * Print an integer. */ public Device print(int i) { if (byteStream != null) flush(); builder.append(i); return this; } /** * Print any Object */ public Device print(Object o) { if (byteStream != null) flush(); builder.append(o); return this; } /** * Writes the specified byte to this data output stream. */ public Device write(int c) { getStream().write(c); return this; } /** * Writes b.length bytes from the specified byte array to this * output stream. */ public Device write(byte b[]) throws IOException { getStream().write(b); return this; } /** * Writes len bytes from the specified byte array starting at offset * off to this output stream. */ public Device write(byte b[], int off, int len) { getStream().write(b, off, len); return this; } }
package com.sun.star.wizards.db; import java.util.Vector; import com.sun.star.awt.VclWindowPeerAttribute; import com.sun.star.beans.Property; import com.sun.star.beans.PropertyValue; import com.sun.star.beans.PropertyVetoException; import com.sun.star.beans.UnknownPropertyException; import com.sun.star.beans.XPropertySet; import com.sun.star.container.ContainerEvent; import com.sun.star.container.NoSuchElementException; import com.sun.star.container.XContainer; import com.sun.star.container.XContainerListener; import com.sun.star.container.XHierarchicalNameAccess; import com.sun.star.container.XIndexAccess; import com.sun.star.container.XNameAccess; import com.sun.star.lang.EventObject; import com.sun.star.lang.IllegalArgumentException; import com.sun.star.lang.IndexOutOfBoundsException; import com.sun.star.lang.WrappedTargetException; import com.sun.star.lang.XMultiServiceFactory; import com.sun.star.sdbc.ColumnValue; import com.sun.star.sdbc.SQLException; import com.sun.star.sdbcx.KeyType; import com.sun.star.sdbcx.XAppend; import com.sun.star.sdbcx.XColumnsSupplier; import com.sun.star.sdbcx.XDataDescriptorFactory; import com.sun.star.sdbcx.XDrop; import com.sun.star.sdbcx.XKeysSupplier; import com.sun.star.sdbcx.XTablesSupplier; import com.sun.star.uno.AnyConverter; import com.sun.star.uno.UnoRuntime; import com.sun.star.wizards.common.Desktop; import com.sun.star.wizards.common.JavaTools; import com.sun.star.wizards.common.Properties; public class TableDescriptor extends CommandMetaData implements XContainerListener{ XDataDescriptorFactory xTableDataDescriptorFactory; XPropertySet xPropTableDataDescriptor; private XNameAccess xNameAccessColumns; private XIndexAccess xIndexAccessKeys; public XDataDescriptorFactory xColumnDataDescriptorFactory; XContainer xTableContainer; XAppend xTableAppend; XDrop xTableDrop; private XAppend xKeyAppend; private XDrop xKeyDrop; private String[] sTableFilters = null; private Vector columncontainer; private Vector keycolumncontainer; public XHierarchicalNameAccess xTableHierarchicalNameAccess; private CommandName ComposedTableName; private XAppend xKeyColAppend; private XPropertySet xKey; private boolean bIDFieldisInserted = false; private String IDFieldName = ""; /** * @param xMSF */ public TableDescriptor(XMultiServiceFactory xMSF) { super(xMSF); columncontainer = new Vector(); keycolumncontainer = new Vector(); } private class ColumnDescriptor{ String Name; XPropertySet xColPropertySet; public ColumnDescriptor(XPropertySet _xColPropertySet, String _Name){ Name = _Name; xColPropertySet = _xColPropertySet; } } public boolean getConnection(PropertyValue[] _curPropertyValue){ if (super.getConnection(_curPropertyValue)){ XTablesSupplier xDBTables = (XTablesSupplier) UnoRuntime.queryInterface(XTablesSupplier.class, DBConnection); xTableNames = xDBTables.getTables(); xTableAppend = (XAppend) UnoRuntime.queryInterface(XAppend.class, xTableNames); xTableDrop = (XDrop) UnoRuntime.queryInterface(XDrop.class, xTableNames); xTableDataDescriptorFactory = (XDataDescriptorFactory) UnoRuntime.queryInterface(XDataDescriptorFactory.class, xTableNames); xPropTableDataDescriptor = xTableDataDescriptorFactory.createDataDescriptor(); XColumnsSupplier xColumnsSupplier = (XColumnsSupplier) UnoRuntime.queryInterface(XColumnsSupplier.class, xPropTableDataDescriptor); xNameAccessColumns = xColumnsSupplier.getColumns(); xColumnDataDescriptorFactory = (XDataDescriptorFactory) UnoRuntime.queryInterface(XDataDescriptorFactory.class, xNameAccessColumns); try { createTypeInspector(); sTableFilters = (String[]) AnyConverter.toArray(xDataSourcePropertySet.getPropertyValue("TableFilter")); } catch (Exception e) { e.printStackTrace(System.out); } return true; } else return false; } public boolean createPrimaryKeys(String[] _fieldnames, boolean _bAutoincrementation){ try { XKeysSupplier xKeySupplier = (XKeysSupplier)UnoRuntime.queryInterface(XKeysSupplier.class, xPropTableDataDescriptor); xIndexAccessKeys = xKeySupplier.getKeys(); XDataDescriptorFactory xKeyFac = (XDataDescriptorFactory)UnoRuntime.queryInterface(XDataDescriptorFactory.class,xIndexAccessKeys); xKeyDrop = (XDrop) UnoRuntime.queryInterface(XDrop.class, xIndexAccessKeys); xKeyAppend = (XAppend)UnoRuntime.queryInterface(XAppend.class, xKeyFac); xKey = xKeyFac.createDataDescriptor(); xKey.setPropertyValue("Type", new Integer(KeyType.PRIMARY)); XColumnsSupplier xKeyColumSup = (XColumnsSupplier)UnoRuntime.queryInterface(XColumnsSupplier.class, xKey); XDataDescriptorFactory xKeyColFac = (XDataDescriptorFactory)UnoRuntime.queryInterface(XDataDescriptorFactory.class,xKeyColumSup.getColumns()); xKeyColAppend = (XAppend)UnoRuntime.queryInterface(XAppend.class, xKeyColFac); if (keycolumncontainer.size() > 0){ for (int i = (keycolumncontainer.size()-1); i >= 0 ; i keycolumncontainer.remove(i); } } for (int i = 0; i < _fieldnames.length; i++){ XPropertySet xKeyColPropertySet = xKeyColFac.createDataDescriptor(); xKeyColPropertySet.setPropertyValue("Name", _fieldnames[i]); keycolumncontainer.add(xKeyColPropertySet); XPropertySet xColPropertySet = null; if (hasByName(_fieldnames[i])) xColPropertySet = getByName(_fieldnames[i]); else xColPropertySet = addPrimaryKeyColumn(_fieldnames[i]); xColPropertySet.setPropertyValue("IsNullable", new Integer(com.sun.star.sdbc.ColumnValue.NO_NULLS)); if (_bAutoincrementation){ int nDataType = oTypeInspector.getAutoIncrementIndex(xColPropertySet); if (nDataType != oTypeInspector.INVALID) if (xColPropertySet.getPropertySetInfo().hasPropertyByName("IsAutoIncrement")){ xColPropertySet.setPropertyValue("Type", new Integer(nDataType)); xColPropertySet.setPropertyValue("IsAutoIncrement", new Boolean(_bAutoincrementation)); } } modifyColumn(_fieldnames[i], xColPropertySet); } return true; } catch (Exception e) { showMessageBox("ErrorBox", VclWindowPeerAttribute.OK, e.getMessage()); e.printStackTrace(System.out); } return false; } /** * creates the table under the passed name * @param _tablename is made unique if necessary * @return true or false to indicate successful creation or not */ public boolean createTable(String _catalogname, String _schemaname, String _tablename, String[] _fieldnames){ try { XAppend xAppendColumns = (XAppend) UnoRuntime.queryInterface(XAppend.class, xNameAccessColumns); for (int i = 0; i < columncontainer.size(); i++){ XPropertySet xColPropertySet = getByIndex(i); xAppendColumns.appendByDescriptor(xColPropertySet); } assignTableProperty("Name", _tablename); assignTableProperty("CatalogName", _catalogname); assignTableProperty("SchemaName", _schemaname); xTableContainer = (XContainer) UnoRuntime.queryInterface(XContainer.class, xTableNames); xTableContainer.addContainerListener(this); if (keycolumncontainer.size() > 0){ for (int i = 0; i < keycolumncontainer.size(); i++){ XPropertySet xKeyColPropertySet = (XPropertySet) keycolumncontainer.get(i); xKeyColAppend.appendByDescriptor(xKeyColPropertySet); } xKeyAppend.appendByDescriptor(xKey); } xTableAppend.appendByDescriptor(xPropTableDataDescriptor); return true; } catch (Exception e) { e.printStackTrace(System.out); showMessageBox("ErrorBox", VclWindowPeerAttribute.OK, e.getMessage()); try { xPropTableDataDescriptor.setPropertyValue("Name", ""); if ((xKeyDrop != null) && (xIndexAccessKeys != null)){ int icount = xIndexAccessKeys.getCount(); if (icount > 0){ for (int i = xIndexAccessKeys.getCount()-1; i >= 0; i xKeyDrop.dropByIndex(i); } } } XDrop xColumnDrop = (XDrop) UnoRuntime.queryInterface(XDrop.class, xNameAccessColumns); for (int i = xNameAccessColumns.getElementNames().length - 1; i >= 0; i xColumnDrop.dropByIndex(i); if (xTableDrop != null) if (xTableNames.hasByName(_tablename)) xTableDrop.dropByName(_tablename); if (bIDFieldisInserted){ this.dropColumnbyName(this.IDFieldName); bIDFieldisInserted = false; } return false; } catch (Exception e1) { e1.printStackTrace(System.out); } return false; } } public boolean createTable(String _catalogname, String _schemaname, String _tablename, String[] _keycolumnnames, boolean _bAutoincrementation, String[] _fieldnames){ if (createPrimaryKeys(_keycolumnnames, _bAutoincrementation)) return createTable(_catalogname, _schemaname, _tablename, _fieldnames); return false; } private void assignTableProperty(String _spropname, String _svalue){ if (_svalue != null){ if (!_svalue.equals("")){ try { xPropTableDataDescriptor.setPropertyValue(_spropname, _svalue); } catch (Exception e) { e.printStackTrace(System.out); } } } } public boolean modifyColumnName(String _soldname, String _snewname){ try { if (hasByName(_soldname)){ ColumnDescriptor oColumnDescriptor = this.getColumnDescriptorByName(_soldname); oColumnDescriptor.xColPropertySet.setPropertyValue("Name", _snewname); oColumnDescriptor.Name = _snewname; } return true; } catch (Exception e) { e.printStackTrace(System.out); showMessageBox("ErrorBox", VclWindowPeerAttribute.OK, e.getMessage()); return false; }} public boolean modifyColumn(String _sname, String _spropname, Object _oValue){ try { if (this.columncontainer.size() > 0){ for (int i = 0; i < columncontainer.size(); i++){ ColumnDescriptor oColumnDescriptor = (ColumnDescriptor) columncontainer.get(i); if (oColumnDescriptor.Name.equals(_sname)){ oColumnDescriptor.xColPropertySet.setPropertyValue(_spropname, _oValue); if (_spropname.equals("Name")) oColumnDescriptor.Name = (String) _oValue; return true; } } } } catch (Exception e) { e.printStackTrace(System.out); showMessageBox("ErrorBox", VclWindowPeerAttribute.OK, e.getMessage()); } return false; } public boolean modifyColumn(String _sname, XPropertySet _xColPropertySet){ try { if (this.columncontainer.size() > 0){ for (int i = 0; i < columncontainer.size(); i++){ ColumnDescriptor oColumnDescriptor = (ColumnDescriptor) columncontainer.get(i); if (oColumnDescriptor.Name.equals(_sname)){ oColumnDescriptor.xColPropertySet = _xColPropertySet; oColumnDescriptor.Name = (String) _xColPropertySet.getPropertyValue("Name"); columncontainer.remove(i); columncontainer.insertElementAt(oColumnDescriptor, i); return true; } } } } catch (Exception e) { e.printStackTrace(System.out); showMessageBox("ErrorBox", VclWindowPeerAttribute.OK, e.getMessage()); } return false; } public void dropColumnbyName(String _sname){ try { if (columncontainer.size() > 0){ for (int i = 0; i < columncontainer.size(); i++){ ColumnDescriptor oColumnDescriptor = (ColumnDescriptor) columncontainer.get(i); if (oColumnDescriptor != null) if (oColumnDescriptor.Name.equals(_sname)) columncontainer.remove(i); } } } catch (Exception e) { e.printStackTrace(System.out); }} public String[] getColumnNames(){ if (columncontainer.size() > 0){ try { String[] fieldnames = new String[columncontainer.size()]; for (int i = 0; i < columncontainer.size(); i++){ ColumnDescriptor oColumnDescriptor = (ColumnDescriptor) columncontainer.get(i); fieldnames[i] = oColumnDescriptor.Name; } return fieldnames; } catch (RuntimeException e) { e.printStackTrace(System.out); } } return new String[]{}; } private boolean hasByName(String _fieldname){ try { if (columncontainer.size() > 0){ for (int i = 0; i < columncontainer.size(); i++){ ColumnDescriptor oColumnDescriptor = (ColumnDescriptor) columncontainer.get(i); if (oColumnDescriptor.Name.equals(_fieldname)){ return true; } } } } catch (RuntimeException e) { e.printStackTrace(System.out); } return false; } private ColumnDescriptor getColumnDescriptorByName(String _fieldname){ try { if (this.columncontainer.size() > 0){ for (int i = 0; i < columncontainer.size(); i++){ ColumnDescriptor oColumnDescriptor = (ColumnDescriptor) columncontainer.get(i); if (oColumnDescriptor.Name.equals(_fieldname)){ return oColumnDescriptor; } } } } catch (RuntimeException e) { e.printStackTrace(System.out); } return null; } public XPropertySet getByName(String _fieldname){ ColumnDescriptor oColumnDescriptor = getColumnDescriptorByName(_fieldname); if (oColumnDescriptor != null) return oColumnDescriptor.xColPropertySet; else return null; } private XPropertySet getByIndex(int _index){ try { if (columncontainer.size() > _index){ ColumnDescriptor oColumnDescriptor = (ColumnDescriptor) columncontainer.get(_index); return oColumnDescriptor.xColPropertySet; } } catch (RuntimeException e) { e.printStackTrace(System.out); } return null; } public XPropertySet clonePropertySet(String _snewname, XPropertySet _xnewPropertySet){ XPropertySet xRetPropertySet = xColumnDataDescriptorFactory.createDataDescriptor(); try { if (hasByName(_snewname)){ Object oColumn = getByName(_snewname); XPropertySet xPropertySet = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, oColumn); Property[] aColProperties = xPropertySet.getPropertySetInfo().getProperties(); for (int i = 0; i < aColProperties.length; i++){ String sPropName = aColProperties[i].Name; Object oColValue = _xnewPropertySet.getPropertyValue(sPropName); xRetPropertySet.setPropertyValue(sPropName, oColValue); } } } catch (Exception e) { e.printStackTrace(System.out); } return xRetPropertySet; } public boolean addColumn(PropertyValue[] _aNewPropertyValues){ try { String sname = (String) Properties.getPropertyValue(_aNewPropertyValues, "Name"); if (!hasByName(sname)){ ColumnPropertySet oPropertySet = new ColumnPropertySet(oTypeInspector, xColumnDataDescriptorFactory.createDataDescriptor()); oPropertySet.assignPropertyValues(_aNewPropertyValues, true); ColumnDescriptor oColumnDescriptor = new ColumnDescriptor(oPropertySet.xPropertySet, sname); this.columncontainer.add(oColumnDescriptor); return true; } } catch (Exception e) { e.printStackTrace(System.out); } return false; } public boolean addColumn(String _columnname, XPropertySet _xNewColPropertySet){ try { if (!hasByName(_columnname)){ if (_columnname.equals("")) return false; else{ ColumnPropertySet oPropertySet = new ColumnPropertySet(oTypeInspector, xColumnDataDescriptorFactory.createDataDescriptor()); oPropertySet.assignNewPropertySet(_columnname, _xNewColPropertySet); ColumnDescriptor oColumnDescriptor = new ColumnDescriptor(oPropertySet.xPropertySet, _columnname); columncontainer.add(oColumnDescriptor); return true; } } } catch (Exception e) { e.printStackTrace(System.out); showMessageBox("ErrorBox", VclWindowPeerAttribute.OK, e.getMessage()); } return false; } public XPropertySet addPrimaryKeyColumn(String _columnname){ try { if (!hasByName(_columnname)){ try { XPropertySet xColPropertySet = xColumnDataDescriptorFactory.createDataDescriptor(); IDFieldName = Desktop.getUniqueName(getColumnNames(), _columnname, ""); xColPropertySet.setPropertyValue("Name", IDFieldName); xColPropertySet.setPropertyValue("Type", new Integer(oTypeInspector.convertDataType(com.sun.star.sdbc.DataType.INTEGER))); ColumnDescriptor oColumnDescriptor = new ColumnDescriptor( xColPropertySet, IDFieldName); this.columncontainer.add(0, oColumnDescriptor); this.bIDFieldisInserted = true; return xColPropertySet; } catch (RuntimeException e1) { e1.printStackTrace(System.out); } } } catch (Exception e) { e.printStackTrace(System.out); showMessageBox("ErrorBox", VclWindowPeerAttribute.OK, e.getMessage()); } return null; } public String[] getNonBinaryFieldNames(){ Vector NonBinaryFieldNameVector = new Vector(); try { for (int i = 0; i < columncontainer.size(); i++){ ColumnDescriptor oColumnDescriptor = (ColumnDescriptor) columncontainer.get(i); XPropertySet xColPropertySet = getByName(oColumnDescriptor.Name); Property[] aProperties = xColPropertySet.getPropertySetInfo().getProperties(); int itype; try { itype = AnyConverter.toInt(xColPropertySet.getPropertyValue("Type")); if (!isBinaryDataType(itype)) NonBinaryFieldNameVector.addElement(oColumnDescriptor.Name); } catch (Exception e) { e.printStackTrace(System.out); } } } catch (RuntimeException e) { e.printStackTrace(System.out); } String[] sbinaryfieldnames = new String[NonBinaryFieldNameVector.size()]; NonBinaryFieldNameVector.toArray(sbinaryfieldnames); return sbinaryfieldnames; } public String getComposedTableName(String _scatalogname, String _sschemaname, String _stablename){ ComposedTableName = new CommandName(this, _scatalogname, _sschemaname, _stablename, false); return ComposedTableName.getComposedName(); } public String getComposedTableName(){ if (ComposedTableName != null) return this.ComposedTableName.getComposedName(); else return null; } /* (non-Javadoc) * @see com.sun.star.container.XContainerListener#elementInserted(com.sun.star.container.ContainerEvent) */ public void elementInserted(ContainerEvent arg0) { try { XPropertySet xTablePropertySet = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, arg0.Element); String stablename = AnyConverter.toString(xTablePropertySet.getPropertyValue("Name")); String sschemaname = AnyConverter.toString(xPropTableDataDescriptor.getPropertyValue("SchemaName")); String scatalogname = AnyConverter.toString(xPropTableDataDescriptor.getPropertyValue("CatalogName")); ComposedTableName = new CommandName(this, scatalogname, sschemaname, stablename, false); appendTableNameToFilter(ComposedTableName.getComposedName()); } catch (Exception e) { e.printStackTrace(System.out); }} /* (non-Javadoc) * @see com.sun.star.container.XContainerListener#elementRemoved(com.sun.star.container.ContainerEvent) */ public void elementRemoved(ContainerEvent arg0) { } /* (non-Javadoc) * @see com.sun.star.container.XContainerListener#elementReplaced(com.sun.star.container.ContainerEvent) */ public void elementReplaced(ContainerEvent arg0) { } /* (non-Javadoc) * @see com.sun.star.lang.XEventListener#disposing(com.sun.star.lang.EventObject) */ public void disposing(EventObject arg0) { } /** * @param _stablename * @return */ public boolean appendTableNameToFilter(String _scomposedtablename){ boolean bhastoinsert = true; for (int i = 0; i < sTableFilters.length; i++){ if (sTableFilters[i].compareTo("%") > -1){ if (sTableFilters[i].endsWith("." + _scomposedtablename)) bhastoinsert = false; else if (sTableFilters[i].length() == 1) bhastoinsert = false; } else if (sTableFilters[i].equals(_scomposedtablename)) bhastoinsert = false; if (!bhastoinsert) break; } if (bhastoinsert){ String[] sNewTableFilters = new String[sTableFilters.length + 1]; System.arraycopy(sTableFilters, 0, sNewTableFilters, 0, sTableFilters.length); sNewTableFilters[sTableFilters.length] = _scomposedtablename; sTableFilters = sNewTableFilters; try { xDataSourcePropertySet.setPropertyValue("TableFilter", sTableFilters); } catch (Exception e) { e.printStackTrace(System.out); bhastoinsert = false; } } return bhastoinsert; } }
package com.heaven7.java.mvcs; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import com.heaven7.java.base.anno.CalledInternal; import com.heaven7.java.base.anno.Nullable; import com.heaven7.java.base.util.Throwables; import com.heaven7.java.mvcs.TeamDelegate.StateListener; import com.heaven7.java.mvcs.util.SparseArray; /** * the team manager. which can communication with multi controller. * * @author heaven7 * * @param * <P> * the parameter type * @since 1.1.8 */ public final class TeamManager<P> implements StateListener<P> { /*** * the cooperate method: just base. (can't listen mutex state, but include * current state) */ public static final byte COOPERATE_METHOD_BASE = 1; /*** * the cooperate method: all. */ public static final byte COOPERATE_METHOD_ALL = 3; /** the member scope of formal member*/ public static final byte FLAG_MEMBER_FORMAL = 0x0001; /** the member scope of outer member*/ public static final byte FLAG_MEMBER_OUTER = 0x0002; private static final SimpleTeamCllback<Object> sDEFAULT_CALLBACK = new SimpleTeamCllback<Object>(); /** a map contains multi teams. */ private final SparseArray<Team<P>> mMap; private int mLastTeamId; /** * the callback of team * * @author heaven7 * * @param * <P> * the parameter type * @since 1.1.8 */ public static abstract class TeamCallback<P> { /** * called on team enter. * * @param team * the team * @param trigger * the trigger state. */ public void onTeamEnter(Team<P> team, AbstractState<P> trigger) { } /** * called on team exit. * * @param team * the team * @param trigger * the trigger state. */ public void onTeamExit(Team<P> team, AbstractState<P> trigger) { } /** * called on team reenter. * * @param team * the team * @param trigger * the trigger state. */ public void onTeamReenter(Team<P> team, AbstractState<P> trigger) { } } public TeamManager() { mMap = new SparseArray<>(); } /** * create a member . * @param <P> the parameter type. * @param controller the target controller * @param states the target states. * @param cooperateMethod the cooperate method between member and team. * @return the member. */ public static <P> Member<P> createMember(IController<? extends AbstractState<P>, P> controller, int states, byte cooperateMethod) { return new Member<P>(controller, states, cooperateMethod); } /** * create a member . * @param <P> the parameter type. * @param controller the target controller * @param states the target states. * @return the member. */ public static <P> Member<P> createMember(IController<? extends AbstractState<P>, P> controller, int states) { return new Member<P>(controller, states, COOPERATE_METHOD_BASE); } /** * create team with formal members and outer members. then register it to * team manager. Among them, if state is in outer members, it can be * notifier state. That means only formal member can notify others(other * formal members or outer members). * * @param formal * the formal members * @return the id of the team. */ public int registerTeam(List<Member<P>> formal) { return registerTeam(formal, null); } /** * create team with formal members , outer members and default team * callback. then register it to team manager. . Among them, if state is in * outer members, it can be notifier state. That means only formal member * can notify others(other formal members or outer members). * * @param formal * the formal members * @param outer * the outer members. can be null or empty. * @return the id of the team. >0 */ @SuppressWarnings("unchecked") public int registerTeam(List<Member<P>> formal, @Nullable List<Member<P>> outer) { return registerTeam(formal, outer, (TeamCallback<P>)sDEFAULT_CALLBACK); } /** * create team with formal members , outer members and target team callback, * then register it to team manager. Among them, if state is in outer * members, it can be notifier state. That means only formal member can * notify others(other formal members or outer members). * * @param formal * the formal members * @param outer * the outer members. can be null or empty. * @param callback * the callback of team. * @return the id of the team. >0 */ public int registerTeam(List<Member<P>> formal, @Nullable List<Member<P>> outer, TeamCallback<P> callback) { Throwables.checkEmpty(formal); Throwables.checkNull(callback); Team<P> team = new Team<P>(); team.formal = formal; team.outer = outer; team.callback = callback; mMap.put(++mLastTeamId, team); return mLastTeamId; } /** * unregister the team which is assigned by target team id. * @param teamId the target team id. */ public void unregisterTeam(int teamId){ mMap.remove(teamId); } /** * delete formal member which is indicated by target controller. And default member flags is * "{@linkplain FLAG_MEMBER_FORMAL} | {@linkplain FLAG_MEMBER_OUTER}" * @param teamId the team id. * @param controller the controller * @return true of delete member success. or false if don't have. */ public boolean deleteOuterMember(int teamId, IController<? extends AbstractState<P>, P> controller){ return deleteMember(teamId, controller, FLAG_MEMBER_OUTER); } /** * delete formal member which is indicated by target controller. And default member flags is * "{@linkplain FLAG_MEMBER_FORMAL} | {@linkplain FLAG_MEMBER_OUTER}" * @param teamId the team id. * @param controller the controller * @return true of delete member success. or false if don't have. */ public boolean deleteFormalMember(int teamId, IController<? extends AbstractState<P>, P> controller){ return deleteMember(teamId, controller, FLAG_MEMBER_FORMAL); } /** * delete the member which is indicated by target controller. And default member flags is * "{@linkplain FLAG_MEMBER_FORMAL} | {@linkplain FLAG_MEMBER_OUTER}" * @param teamId the team id. * @param controller the controller * @return true of delete member success. or false if don't have. */ public boolean deleteMember(int teamId, IController<? extends AbstractState<P>, P> controller){ return deleteMember(teamId, controller,(byte) (FLAG_MEMBER_FORMAL | FLAG_MEMBER_OUTER)); } /** * delete the member which is indicated by target controller. * @param teamId the team id. * @param controller the controller * @param memberFlags the member flags .see {@linkplain TeamManager#FLAG_MEMBER_FORMAL} * and {@linkplain TeamManager#FLAG_MEMBER_OUTER}. * @return true of delete member success. or false if don't have. */ private boolean deleteMember(int teamId, IController<? extends AbstractState<P>, P> controller, byte memberFlags){ Throwables.checkNull(controller); Team<P> team = mMap.get(teamId); if(team == null){ return false; } return team.deleteMember(controller, -1, memberFlags); } /** * delete the outer member states which is indicated by target controller and states. * And default member flags is "{@linkplain FLAG_MEMBER_FORMAL} | {@linkplain FLAG_MEMBER_OUTER}" * @param teamId the team id. * @param controller the controller * @param targetStates the target states to delete. must >0 * @return true of delete member state success. or false if don't have. */ public boolean deleteOuterMembeStates(int teamId, IController<? extends AbstractState<P>, P> controller, int targetStates){ return deleteMembeStates(teamId, controller, targetStates, FLAG_MEMBER_OUTER); } /** * delete the formal member states which is indicated by target controller and states. * And default member flags is "{@linkplain FLAG_MEMBER_FORMAL} | {@linkplain FLAG_MEMBER_OUTER}" * @param teamId the team id. * @param controller the controller * @param targetStates the target states to delete. must >0 * @return true of delete member state success. or false if don't have. */ public boolean deleteFormalMembeStates(int teamId, IController<? extends AbstractState<P>, P> controller, int targetStates){ return deleteMembeStates(teamId, controller, targetStates, FLAG_MEMBER_FORMAL); } /** * delete the member states which is indicated by target controller and states. * And default member flags is "{@linkplain FLAG_MEMBER_FORMAL} | {@linkplain FLAG_MEMBER_OUTER}" * @param teamId the team id. * @param controller the controller * @param targetStates the target states to delete. must >0 * @return true of delete member state success. or false if don't have. */ public boolean deleteMembeStates(int teamId, IController<? extends AbstractState<P>, P> controller, int targetStates){ return deleteMembeStates(teamId, controller, targetStates, (byte)(FLAG_MEMBER_FORMAL | FLAG_MEMBER_OUTER)); } /** * delete the member states which is indicated by target controller and states. * @param teamId the team id. * @param controller the controller * @param targetStates the target states to delete. must >0 * @param memberFlags the member flags .see {@linkplain TeamManager#FLAG_MEMBER_FORMAL} * and {@linkplain TeamManager#FLAG_MEMBER_OUTER}. * @return true of delete member state success. or false if don't have. */ private boolean deleteMembeStates(int teamId, IController<? extends AbstractState<P>, P> controller, int targetStates, byte memberFlags){ Throwables.checkNull(controller); if(targetStates <= 0 ){ throw new IllegalArgumentException("targetStates must be positive."); } Team<P> team = mMap.get(teamId); if(team == null){ return false; } return team.deleteMember(controller, targetStates, memberFlags); } /** * add a formal member for team which is assigned by target teamId. * @param teamId the team id * @param member the formal member * @return true if add success. */ public boolean addFormalMember(int teamId, Member<P> member){ Throwables.checkNull(member); Team<P> team = mMap.get(teamId); if(team == null){ return false; } return team.formal.add(member); } /** * add a outer member for team which is assigned by target teamId. * @param teamId the team id * @param member the outer member * @return true if add success. */ public boolean addOuterMember(int teamId, Member<P> member){ Throwables.checkNull(member); Team<P> team = mMap.get(teamId); if(team == null){ return false; } if(team.outer == null){ team.outer = new ArrayList<>(4); } return team.outer.add(member); } /** * add a formal member states for team which is assigned by target teamId and controller. * @param teamId the team id * @param controller the controller * @param states the states to add. * @return true if add success. */ public boolean addFormalMemberStates(int teamId, IController<? extends AbstractState<P>, P> controller, int states){ if(states <= 0 ){ throw new IllegalArgumentException("targetStates must be positive."); } Team<P> team = mMap.get(teamId); if(team == null){ return false; } return team.addMemberStates(controller, states, FLAG_MEMBER_FORMAL); } /** * add a outer member states for team which is assigned by target teamId and controller. * @param teamId the team id * @param controller the controller * @param states the states to add. * @return true if add success. */ public boolean addOuterMemberStates(int teamId, IController<? extends AbstractState<P>, P> controller, int states){ if(states <= 0 ){ throw new IllegalArgumentException("targetStates must be positive."); } Team<P> team = mMap.get(teamId); if(team == null){ return false; } return team.addMemberStates(controller, states, FLAG_MEMBER_OUTER); } /** * get the team for target team id. * @param teamId the team id. * @return the team. */ public Team<P> getTeam(int teamId){ return mMap.get(teamId); } /** * indicate the target member is a formal member or not. * @param member the member * @return true if is in a team and is formal member. */ public boolean isFormalMember(Member<P> member){ Throwables.checkNull(member); final int size = mMap.size(); for(int i = size - 1 ; i >= 0 ; i if(mMap.get(i).isFormalMember(member)){ return true; } } return false; } /** * indicate the target member is a outer member or not. * @param member the member * @return true if is in a team and is outer member. */ public boolean isOuterMember(Member<P> member){ Throwables.checkNull(member); final int size = mMap.size(); for(int i = size - 1 ; i >= 0 ; i if(mMap.get(i).isOuterMember(member)){ return true; } } return false; } /** * get teams for target formal member. * @param member the member * @param outList the out list, can be null * @return the teams */ public List<Team<P>> getTeamsAsFormal(Member<P> member, @Nullable List<Team<P>> outList){ return getTeams(member, FLAG_MEMBER_FORMAL, outList); } /** * get teams for target outer member. * @param member the member * @param outList the out list, can be null * @return the teams */ public List<Team<P>> getTeamsAsOuter(Member<P> member, @Nullable List<Team<P>> outList){ return getTeams(member, FLAG_MEMBER_OUTER, outList); } /** * get teams for target member(may be formal or outer member). * @param member the member * @param outList the out list, can be null * @return the teams */ public List<Team<P>> getTeams(Member<P> member, @Nullable List<Team<P>> outList){ return getTeams(member, FLAG_MEMBER_FORMAL | FLAG_MEMBER_OUTER, outList); } /** * update the all teams. * * @param deltaTime * the delta time between last update and this. * @param param * the parameter. */ public void update(long deltaTime, P param) { final int size = mMap.size(); for (int i = size - 1; i >= 0; i mMap.valueAt(i).update(deltaTime, param); } } @CalledInternal @Override public void onEnterState(int stateFlag, AbstractState<P> state) { final int size = mMap.size(); for (int i = size - 1; i >= 0; i mMap.valueAt(i).onEnter(stateFlag, state); } } @CalledInternal @Override public void onExitState(int stateFlag, AbstractState<P> state) { final int size = mMap.size(); for (int i = size - 1; i >= 0; i mMap.valueAt(i).onExit(stateFlag, state); } } @CalledInternal @Override public void onReenterState(int stateFlag, AbstractState<P> state) { final int size = mMap.size(); for (int i = size - 1; i >= 0; i mMap.valueAt(i).onReenter(stateFlag, state); } } private List<Team<P>> getTeams(Member<P> member, int memberFlags, @Nullable List<Team<P>> outList){ Throwables.checkNull(member); final boolean hasFormal = (memberFlags & FLAG_MEMBER_FORMAL) == FLAG_MEMBER_FORMAL; final boolean hasOuter = (memberFlags & FLAG_MEMBER_OUTER) == FLAG_MEMBER_OUTER; //no formal and no outer. if(!hasFormal && !hasOuter){ return null; } if(outList == null){ outList = new ArrayList<>(5); } final int size = mMap.size(); Team<P> team; for(int i = size - 1 ; i >= 0 ; i team = mMap.get(i); if(hasFormal && team.isFormalMember(member)){ outList.add(team); }else{ if(hasOuter && team.isOuterMember(member)){ outList.add(team); } } } return outList; } /** * one controller corresponding one member. But can have multi states. * * @author heaven7 * * @param * <P> * the parameter type * @since 1.1.8 */ public static class Member<P> { WeakReference<IController<? extends AbstractState<P>, P>> WeakController; int states; // can be multi /** the cooperate method with other member(or whole team). */ byte cooperateMethod = COOPERATE_METHOD_BASE; Member(IController<? extends AbstractState<P>, P> controller, int states, byte cooperateMethod) { super(); switch (cooperateMethod) { case COOPERATE_METHOD_ALL: case COOPERATE_METHOD_BASE: break; default: throw new IllegalArgumentException( "caused by cooperateMethod is error. cooperateMethod = " + cooperateMethod); } if (states <= 0) { throw new IllegalArgumentException("caused by states is error. states = " + states); } this.WeakController = new WeakReference<IController<? extends AbstractState<P>, P>>(controller); this.states = states; this.cooperateMethod = cooperateMethod; } /** * get the controller * @return the controller */ public IController<? extends AbstractState<P>, P> getController() { return WeakController.get(); } /** * get the states * @return the states */ public int getStates() { return states; } /** * get the cooperate method. * @return the cooperate method. * @see TeamManager#COOPERATE_METHOD_ALL * @see TeamManager#COOPERATE_METHOD_BASE */ public byte getCooperateMethod() { return cooperateMethod; } void update(long deltaTime, P param) { IController<? extends AbstractState<P>, P> controller = getController(); if (controller != null) { controller.update(states, deltaTime, param); } } @SuppressWarnings("unchecked") @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Member<P> other = (Member<P>) obj; if(getController()== null){ return false; } if(other.getController() == null){ return false; } if(getController() != other.getController()){ return false; } if (cooperateMethod != other.cooperateMethod) return false; if (states != other.states) return false; return true; } } /** * the team of members. * * @author heaven7 * * @param * <P> * the parameter type * @since 1.1.8 * @see {@linkplain Member} */ public static class Team<P> { List<Member<P>> formal; List<Member<P>> outer; TeamCallback<P> callback; Team() { } /** * indicate the target member is a formal member or not. * @param member the member. * @return true if is formal member. */ public boolean isFormalMember(Member<P> member) { return formal.contains(member); } /** * indicate the target member is a outer member or not. * @param member the member. * @return true if is outer member. */ public boolean isOuterMember(Member<P> member) { return outer != null && outer.contains(member); } /** * get the formal members * @return the formal members */ public List<Member<P>> getFormalMembers() { return formal; } /** * get the outer members * @return the outer members */ public List<Member<P>> getOuterMembers() { return outer; } /** * add member states. * @param controller the controller. * @param states the states * @param memberFlags the member flags * @return true if add success. false otherwise. */ public boolean addMemberStates(IController<? extends AbstractState<P>, P> controller, int states, byte memberFlags) { boolean success = false; if((memberFlags & FLAG_MEMBER_FORMAL) == FLAG_MEMBER_FORMAL ){ success |= addMemberStates0(controller, states, formal); } /** * formal and outer member may use same controller. */ if((memberFlags & FLAG_MEMBER_OUTER) == FLAG_MEMBER_OUTER ){ if(outer != null && !outer.isEmpty()){ success |= addMemberStates0(controller, states, outer); } } return success; } private boolean addMemberStates0(IController<? extends AbstractState<P>, P> controller, int states, List<Member<P>> members) { IController<? extends AbstractState<P>, P> temp; Member<P> member; Iterator<Member<P>> it = members.iterator(); for(; it.hasNext() ;){ member = it.next(); temp = member.getController(); //if controller is empty or controller is the target want to delete. if(temp == null ){ it.remove(); continue; } if(temp == controller){ member.states |= states; return true; } } return false; } /** * delete member by target controller and states. May just delete states. * @param controller the controller * @param states the states to delete, if == -1. means remove whole member of controller * @param memberFlags the member flags * @return true if delete success. * @see TeamManager#FLAG_MEMBER_FORMAL * @see TeamManager#FLAG_MEMBER_OUTER */ boolean deleteMember(IController<? extends AbstractState<P>, P> controller, int states, byte memberFlags) { boolean success = false; if((memberFlags & FLAG_MEMBER_FORMAL) == FLAG_MEMBER_FORMAL ){ success |= deleteMember0(controller, states, formal); } /** * formal and outer member may use same controller. */ if((memberFlags & FLAG_MEMBER_OUTER) == FLAG_MEMBER_OUTER ){ if(outer != null && !outer.isEmpty()){ success |= deleteMember0(controller, states, outer); } } return success; } private static <P> boolean deleteMember0(IController<? extends AbstractState<P>, P> controller, int states, List<Member<P>> members) { IController<? extends AbstractState<P>, P> temp; Member<P> member; Iterator<Member<P>> it = members.iterator(); for(; it.hasNext() ;){ member = it.next(); temp = member.getController(); //if controller is empty or controller is the target want to delete. if(temp == null ){ it.remove(); continue; } if(temp == controller){ if(states == -1){ it.remove(); }else{ member.states &= ~states; if(member.states <= 0){ it.remove(); } } return true; } } return false; } void update(long deltaTime, P param) { for (Member<P> member : formal) { member.update(deltaTime, param); } if (outer != null) { for (Member<P> member : outer) { member.update(deltaTime, param); } } } void onEnter(int state, AbstractState<P> trigger) { if (hasMember(trigger.getController(), state)) { callback.onTeamEnter(this, trigger); } } void onExit(int state, AbstractState<P> trigger) { if (hasMember(trigger.getController(), state)) { callback.onTeamExit(this, trigger); } } void onReenter(int state, AbstractState<P> trigger) { if (hasMember(trigger.getController(), state)) { callback.onTeamReenter(this, trigger); } } private boolean hasMember(IController<?, P> target, int state) { for (Member<P> member : formal) { if (member.getController() == target) { if ((member.states & state) != 0) { return true; } break; } } return false; } } }
package com.ardrumoid; import java.io.IOException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import com.ardrumoid.data.SelectMusicData; import com.ardrumoid.surface.GameThread; import com.ardrumoid.surface.GameView; import com.hoho.android.usbserial.driver.UsbSerialPort; import com.hoho.android.usbserial.util.SerialInputOutputManager; import android.annotation.SuppressLint; import android.content.Context; import android.content.Intent; import android.graphics.Point; import android.hardware.usb.UsbDeviceConnection; import android.hardware.usb.UsbManager; import android.media.AudioManager; import android.media.MediaPlayer; import android.media.MediaPlayer.OnCompletionListener; import android.media.MediaPlayer.OnPreparedListener; import android.media.SoundPool; import android.media.SoundPool.Builder; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.Display; import android.view.View; import android.view.WindowManager; import android.widget.Toast; public class MusicPlayActivity extends AppCompatActivity { private static final String LOG_TAG = "MusicPlayActivity"; public static int deviceWidth, deviceHeight; public static int score = 0; public static long musicStartTime = 0; private GameView mGameView; private SoundPool mSoundPool; private SelectMusicData mData; private int SnareId, KickId, CymbalId, TomId, HihatId; private SerialInputOutputManager mSerialIoManager; private static final ExecutorService mExecutor = Executors.newSingleThreadExecutor(); private SerialInputOutputManager.Listener mListener; @SuppressLint("NewApi") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mListener = new SerialInputOutputManager.Listener() { @Override public void onRunError(Exception e) { Log.d("MenuActivity.SerialInputOutputManager", "Runner stopped."); } @Override public void onNewData(final byte[] data) { MusicPlayActivity.this.runOnUiThread(new Runnable() { @Override public void run() { MusicPlayActivity.this.updateReceivedData(data); } }); } }; mData = getIntent().getParcelableExtra("data"); getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); mGameView = new GameView(getApplicationContext(), mData.dataUrl); score = 0; setContentView(mGameView); mGameView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int j; for (j = 0; j < GameThread.note[0].size(); j++) { if (deviceHeight * 0.7 < GameThread.note[0].get(j).dY && GameThread.note[0].get(j).dY < deviceHeight * 0.9) { long score = Math .abs(300 - Math.abs((int) (deviceHeight * 0.8 - 25) - GameThread.note[0].get(j).dY)); // Toast.makeText(getApplicationContext(), "TT" + score, // Toast.LENGTH_SHORT).show(); // GameThread.note[0].get(j).dY = deviceHeight + 100; GameThread.note[0].get(j).isChecked = true; GameThread.judgeTimeArray[0] = System.currentTimeMillis(); break; } } } }); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB_MR2) { Display display = getWindowManager().getDefaultDisplay(); deviceWidth = display.getWidth(); deviceHeight = display.getHeight(); } else { Display display = getWindowManager().getDefaultDisplay(); Point size = new Point(); display.getSize(size); deviceWidth = size.x; deviceHeight = size.y; } Log.d(LOG_TAG, "W // " + deviceWidth + " H // " + deviceHeight); if (Build.VERSION.SDK_INT < 21) { mSoundPool = new SoundPool(5, AudioManager.STREAM_MUSIC, 0); } else { mSoundPool = new Builder().setMaxStreams(5).build(); } SnareId = mSoundPool.load(this, R.raw.snare1, 1); KickId = mSoundPool.load(this, R.raw.kick1, 1); CymbalId = mSoundPool.load(this, R.raw.cymbal1, 1); TomId = mSoundPool.load(this, R.raw.tom1, 1); HihatId = mSoundPool.load(this, R.raw.hihat1, 1); new MPAsyncTask().execute(mData.bgUrl); } public static MediaPlayer mp = null; private class MPAsyncTask extends AsyncTask<String, Boolean, String> { @Override protected String doInBackground(String... params) { if (params[0].equalsIgnoreCase("1")) { mp = MediaPlayer.create(getApplicationContext(), R.raw.up_above_short); } else { mp = MediaPlayer.create(getApplicationContext(), R.raw.up_above); } mp.setOnPreparedListener(new OnPreparedListener() { @Override public void onPrepared(MediaPlayer player) { // player.start(); // musicStartTime = System.currentTimeMillis(); } }); mp.setOnCompletionListener(new OnCompletionListener() { @Override public void onCompletion(MediaPlayer player) { if (mp != null) { mp.release(); mp = null; } Intent intent = new Intent(MusicPlayActivity.this, MusicResultActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY); intent.putExtra("isFinished", true); intent.putExtra("score", score); startActivity(intent); finish(); } }); try { mp.prepare(); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(String result) { // TODO Auto-generated method stub super.onPostExecute(result); if (MainApp.getPort() == null) { // playDataText.setText("No serial device."); Toast.makeText(getApplicationContext(), " .\nport", Toast.LENGTH_SHORT).show(); return; } else { final UsbManager usbManager = (UsbManager) getSystemService( Context.USB_SERVICE); UsbDeviceConnection connection = usbManager .openDevice(MainApp.getPort().getDriver().getDevice()); MainApp.setConnection(connection); if (connection == null) { // playDataText.setText("Opening device failed"); Toast.makeText(getApplicationContext(), " .\nconn", Toast.LENGTH_SHORT).show(); return; } } try { MainApp.getPort().open(MainApp.getConnection()); MainApp.getPort().setParameters(115200, 8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE); } catch (IOException e) { // Log.e(TAG, "Error setting up device: " + e.getMessage(), e); // playDataText.setText("Error opening device: " + // e.getMessage()); Toast.makeText(getApplicationContext(), " .\nio", Toast.LENGTH_SHORT).show(); try { MainApp.getPort().close(); } catch (IOException e2) { // Ignore. } // MainApp.setPort(null); return; } onDeviceStateChange(); } } @Override public void onBackPressed() { Intent intent = new Intent(MusicPlayActivity.this, MusicResultActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY); intent.putExtra("isFinished", false); intent.putExtra("score", score); startActivity(intent); super.onBackPressed(); } @Override protected void onPause() { super.onPause(); if (mp != null && mp.isPlaying()) { mp.pause(); } try { MainApp.getPort().close(); } catch (IOException e2) { // Ignore. } } @Override protected void onDestroy() { super.onDestroy(); if (mp != null) { mp.release(); mp = null; } } @Override protected void onResume() { // TODO Auto-generated method stub super.onResume(); if (mp != null && !mp.isPlaying()) { mp.start(); } // playDataText.setText("Serial device: " + // MainApp.getPort().getClass().getSimpleName()); } private void onDeviceStateChange() { stopIoManager(); startIoManager(); } private void stopIoManager() { if (mSerialIoManager != null) { Log.i("MusicPlayActivity.OnResume.stopIoManager", "Stopping io manager .."); mSerialIoManager.stop(); mSerialIoManager = null; } } private void startIoManager() { if (MainApp.getPort() != null) { Log.i("MusicPlayActivity.OnResume.startIoManager", "Starting io manager .."); mSerialIoManager = new SerialInputOutputManager(MainApp.getPort(), mListener); mExecutor.submit(mSerialIoManager); } } public void onTempBtnClick(View v) { Intent intent = new Intent(this, MusicResultActivity.class); startActivity(intent); } private void updateReceivedData(byte[] data) { // final String message = "Read " + data.length + " bytes: \n" // + HexDump.dumpHexString(data) + "\n\n"; // final String message = "Read " + data.length + " bytes: \n" + new // String(data); // playDataText.append(message); char dataArray[] = new String(data).toCharArray(); int num = 0; if (dataArray[num] == '0') { mSoundPool.play(CymbalId, 0.5F, 0.5F, 1, 0, 1.0F); checkNote(2); num++; } if (dataArray.length > num && dataArray[num] == '1') { mSoundPool.play(HihatId, 0.7F, 0.7F, 1, 0, 1.0F); checkNote(0); num++; } if (dataArray.length > num && dataArray[num] == '2') { mSoundPool.play(SnareId, 0.7F, 0.7F, 1, 0, 1.0F); checkNote(1); num++; } if (dataArray.length > num && dataArray[num] == '3') { mSoundPool.play(TomId, 0.7F, 0.7F, 1, 0, 1.0F); checkNote(3); } if (dataArray.length > num && dataArray[num] == '4') { mSoundPool.play(KickId, 1.0F, 1.0F, 1, 0, 1.0F); checkNote(4); } } public void checkNote(int note_num) { if (GameThread.note[note_num] != null) { for (int j = 0; j < GameThread.note[note_num].size(); j++) { if (deviceHeight * 0.7 < GameThread.note[note_num].get(j).dY && GameThread.note[note_num].get(j).dY < deviceHeight * 0.9) { score += Math.abs(200 - Math.abs((int) (deviceHeight * 0.8 - 25) - GameThread.note[note_num].get(j).dY)); GameThread.note[note_num].get(j).dY = deviceHeight + 100; GameThread.note[note_num].get(j).isChecked = true; GameThread.judgeTimeArray[note_num] = System.currentTimeMillis(); break; } } } } }
package com.daexsys.sbc.entity; import com.daexsys.ijen3D.entity.Entity; import com.daexsys.sbc.world.chunk.Chunk; import com.daexsys.sbc.world.planet.Planet; public class SBEntity extends Entity { private Planet planet; public SBEntity(float x, float y, float z) { super(x, y, z); } public SBEntity(float x, float y, float z, float width, float height, float length) { super(x, y, z, width, height, length); } /** * Sets the planet that the player is currently on. * @param planet the planet that the player is currenlty on. */ public void setPlanet(Planet planet) { this.planet = planet; } /** * The current planet the entity is on * @return the entity's current entity */ public Planet getPlanet() { return planet; } /** * The current chunk the entity is in * @return the entity's current chunk */ public Chunk getCurrentChunk() { return getPlanet().getChunk(getChunkX(), getChunkY(), getChunkZ()); } /** * Gets the X coordinate of the current chunk the entity is in * @return the X coordinate of the chunk the entity is in */ public int getChunkX() { return (int) getX() / 32; } /** * Gets the Y coordinate of the current chunk the entity is in. * @return the Y coordinate of the chunk the entity is in */ public int getChunkY() { return (int) getY() / 32; } /** * Gets the Z coordinate fo the current chunk the entity is in. * @return the Z coordinate fo the chunk the entity is in */ public int getChunkZ() { return (int) getZ() / 32; } }
package com.dmdirc.ui.swing; import com.dmdirc.plugins.Plugin; import com.dmdirc.plugins.PluginInfo; import com.dmdirc.plugins.PluginManager; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.HashMap; import java.util.Map; import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.JSeparator; import javax.swing.event.MenuEvent; import javax.swing.event.MenuListener; /** * Dynamic plugins menu. */ public class PluginsMenu extends JMenu implements ActionListener { /** * A version number for this class. It should be changed whenever the class * structure is changed (or anything else that would prevent serialized * objects being unserialized with the new class). */ private static final long serialVersionUID = 1; /** Configure plugins menu. */ private JMenu configure; /** Plugins list. */ private Map<JMenuItem, String> pluginList; /** * Instantiates a new plugins menu. */ public PluginsMenu() { setText("Plugins"); setMnemonic('p'); pluginList = new HashMap<JMenuItem, String>(); JMenuItem manage = new JMenuItem("Manage Plugins"); manage.setMnemonic('m'); manage.setActionCommand("ManagePlugins"); manage.addActionListener(this); add(manage); configure = new JMenu("Configure plugins"); configure.setMnemonic('c'); add(configure); addMenuListener(new MenuListener() { @Override public void menuSelected(final MenuEvent e) { populateConfigurePluginsMenu(); } @Override public void menuDeselected(final MenuEvent e) { //Ignore } @Override public void menuCanceled(final MenuEvent e) { //Ignore } }); } /** * Populated the configure plugin menu. */ private void populateConfigurePluginsMenu() { pluginList.clear(); configure.removeAll(); for (PluginInfo pluginInfo : PluginManager.getPluginManager(). getPluginInfos()) { if (pluginInfo.isLoaded()) { Plugin plugin = pluginInfo.getPlugin(); if (plugin.isConfigurable()) { final JMenuItem mi = new JMenuItem(pluginInfo.getNiceName()); mi.setActionCommand("configurePlugin"); mi.addActionListener(this); configure.add(mi); pluginList.put(mi, pluginInfo.getFilename()); } } } if (configure.getItemCount() == 0) { configure.setEnabled(false); } else { configure.setEnabled(true); } } /** * Adds a JMenuItem to the plugin menu. * * @param menuItem The menu item to be added. */ public void addPluginMenu(final JMenuItem menuItem) { if (getComponents().length == 1) { final JSeparator seperator = new JSeparator(); add(seperator); } add(menuItem); } /** * Removes a JMenuItem from the plugin menu. * * @param menuItem The menu item to be removed. */ public void removePluginMenu(final JMenuItem menuItem) { remove(menuItem); if (getComponents().length == 2) { remove(2); } } /** * {@inheritDoc} * * @param e Action event */ @Override public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals("configurePlugin")) { PluginManager.getPluginManager(). getPluginInfo(pluginList.get(e.getSource())).getPlugin(). showConfig(); } } }
package org.apache.batik.svggen; import java.awt.Graphics2D; import java.awt.Image; import java.awt.image.RenderedImage; import java.awt.image.BufferedImage; import java.awt.image.renderable.RenderableImage; import java.awt.geom.AffineTransform; import java.io.File; import java.net.MalformedURLException; import java.awt.Dimension; import org.w3c.dom.Element; import org.apache.batik.ext.awt.image.GraphicsUtil; public abstract class AbstractImageHandlerEncoder extends DefaultImageHandler { private static final AffineTransform IDENTITY = new AffineTransform(); /** * Directory where all images are placed */ private String imageDir = ""; /** * Value for the url root corresponding to the directory */ private String urlRoot = ""; public AbstractImageHandlerEncoder(String imageDir, String urlRoot) throws SVGGraphics2DIOException { if (imageDir == null) throw new SVGGraphics2DRuntimeException(ERR_IMAGE_DIR_NULL); File imageDirFile = new File(imageDir); if (!imageDirFile.exists()) throw new SVGGraphics2DRuntimeException(ERR_IMAGE_DIR_DOES_NOT_EXIST); this.imageDir = imageDir; if (urlRoot != null) this.urlRoot = urlRoot; else { try{ this.urlRoot = imageDirFile.toURL().toString(); } catch (MalformedURLException e) { throw new SVGGraphics2DIOException(ERR_CANNOT_USE_IMAGE_DIR+ e.getMessage(), e); } } } /** * This template method should set the xlink:href attribute on the input * Element parameter */ protected void handleHREF(Image image, Element imageElement, SVGGeneratorContext generatorContext) throws SVGGraphics2DIOException { // Create an buffered image where the image will be drawn Dimension size = new Dimension(image.getWidth(null), image.getHeight(null)); BufferedImage buf = buildBufferedImage(size); Graphics2D g = GraphicsUtil.createGraphics(buf); g.drawImage(image, 0, 0, null); g.dispose(); // Save image into file saveBufferedImageToFile(imageElement, buf, generatorContext); } /** * This template method should set the xlink:href attribute on the input * Element parameter */ protected void handleHREF(RenderedImage image, Element imageElement, SVGGeneratorContext generatorContext) throws SVGGraphics2DIOException { // Create an buffered image where the image will be drawn Dimension size = new Dimension(image.getWidth(), image.getHeight()); BufferedImage buf = buildBufferedImage(size); Graphics2D g = GraphicsUtil.createGraphics(buf); g.drawRenderedImage(image, IDENTITY); g.dispose(); // Save image into file saveBufferedImageToFile(imageElement, buf, generatorContext); } /** * This template method should set the xlink:href attribute on the input * Element parameter */ protected void handleHREF(RenderableImage image, Element imageElement, SVGGeneratorContext generatorContext) throws SVGGraphics2DIOException { // Create an buffered image where the image will be drawn Dimension size = new Dimension((int)Math.ceil(image.getWidth()), (int)Math.ceil(image.getHeight())); BufferedImage buf = buildBufferedImage(size); Graphics2D g = GraphicsUtil.createGraphics(buf); g.drawRenderableImage(image, IDENTITY); g.dispose(); // Save image into file saveBufferedImageToFile(imageElement, buf, generatorContext); } private void saveBufferedImageToFile(Element imageElement, BufferedImage buf, SVGGeneratorContext generatorContext) throws SVGGraphics2DIOException { if (generatorContext == null) throw new SVGGraphics2DRuntimeException(ERR_CONTEXT_NULL); // Create a new file in image directory File imageFile = null; // While the files we are generating exist, try to create another // id that is unique. while (imageFile == null) { String fileId = generatorContext.idGenerator.generateID(getPrefix()); imageFile = new File(imageDir, fileId + getSuffix()); if (imageFile.exists()) imageFile = null; } // Encode image here encodeImage(buf, imageFile); // Update HREF imageElement.setAttributeNS(XLINK_NAMESPACE_URI, ATTR_XLINK_HREF, urlRoot + "/" + imageFile.getName()); } /** * @return the suffix used by this encoder. E.g., ".jpg" for * ImageHandlerJPEGEncoder */ public abstract String getSuffix(); /** * @return the prefix used by this encoder. E.g., "jpegImage" for * ImageHandlerJPEGEncoder */ public abstract String getPrefix(); /** * Derived classes should implement this method and encode the input * BufferedImage as needed */ public abstract void encodeImage(BufferedImage buf, File imageFile) throws SVGGraphics2DIOException; /** * This method creates a BufferedImage of the right size and type * for the derived class. */ public abstract BufferedImage buildBufferedImage(Dimension size); }
package com.humbughq.mobile; import java.net.SocketTimeoutException; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.util.Log; class AsyncPoller extends HumbugAsyncPushTask { private Message[] receivedMessages; private boolean continuePolling; /** * Initialises an AsyncPoller object and sets execution defaults. * * @param humbugActivity * The calling Activity. * @param continuePolling * Whether to start up a new AsyncPoller task * @param updatePointer */ public AsyncPoller(HumbugActivity humbugActivity, boolean continuePolling) { super(humbugActivity); this.continuePolling = continuePolling; } /** * Longpoll for messages after a specified last received message. * * @param lastMessage * Last message received. More specifically, longpolling will * return once messages after this message ID are available for * consumption. */ public final void execute(int lastMessage) { this.setProperty("last", Integer.toString(lastMessage)); this.execute("api/v1/get_messages"); Log.v("poll", "longpolling started from " + lastMessage); } /** * Get messages surrounding a specified anchor message ID, inclusive of both * endpoints and the anchor. * * @param anchor * Message ID of the message to fetch around * @param before * Number of messages after the anchor to return * @param after * Number of messages before the anchor to return */ public final void execute(int anchor, int before, int after) { this.setProperty("anchor", Integer.toString(anchor)); this.setProperty("num_before", Integer.toString(before)); this.setProperty("num_after", Integer.toString(after)); // We don't support narrowing at all, so always specify we're // unnarrowed. this.setProperty("narrow", "{}"); this.execute("api/v1/get_old_messages"); Log.v("poll", "get_old_messages called"); } @Override protected String doInBackground(String... api_path) { String result = super.doInBackground(api_path); if (result != null) { try { JSONObject response = new JSONObject(result); JSONArray objects = response.getJSONArray("messages"); receivedMessages = new Message[objects.length()]; for (int i = 0; i < objects.length(); i++) { Log.i("json-iter", "" + i); Message message = new Message(context.you, objects.getJSONObject(i)); /* * Add to the local message array and the global ArrayList * of all messages. * * We do this because we want to process JSON here, but do * manipulation of the UI on the UI thread. */ receivedMessages[i] = message; this.context.messageIndex.append(message.getID(), message); } } catch (JSONException e) { Log.e("json", "parsing error"); e.printStackTrace(); } catch (NullPointerException e) { Log.e("poll", "No data returned?"); e.printStackTrace(); } } else { Log.i("poll", "got nothing from the server"); } return null; // since onPostExecute doesn't use the result } @Override protected void onPostExecute(String result) { super.onPostExecute(result); Log.v("poll", "Longpolling finished."); // Duplicate thread detection if (this.context.current_poll != this) { Log.w("poll", "Thread still running, but we're not the active poll! Bailing..."); return; } if (receivedMessages != null) { Log.v("poll", "Processing messages received."); try { this.context.adapter.addAll(receivedMessages); } catch (NoSuchMethodError e) { /* * Older versions of Android do not have .addAll, so we fall * back to manually looping here. */ for (Message message : receivedMessages) { this.context.adapter.add(message); } } } else { Log.v("poll", "No messages returned."); } if (this.continuePolling) { restart(); } callback.onTaskComplete(result); } private void restart() { Log.v("poll", "Starting new longpoll."); this.context.current_poll = new AsyncPoller(this.context, true); // Start polling from the last received message ID this.context.current_poll.execute((int) context.adapter .getItemId(context.adapter.getCount() - 1)); } protected void handleError(Exception e) { if (e instanceof SocketTimeoutException && this.continuePolling) { Log.i("poll", "Timed out."); restart(); this.cancel(true); } else { super.handleError(e); } } }
package com.jmex.awt.swingui; import java.awt.AWTEvent; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.Frame; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.KeyboardFocusManager; import java.awt.Point; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.event.FocusEvent; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseWheelEvent; import java.lang.reflect.InvocationTargetException; import java.util.HashMap; import java.util.Map; import javax.swing.JComponent; import javax.swing.JDesktopPane; import javax.swing.JInternalFrame; import javax.swing.JPanel; import javax.swing.JRootPane; import javax.swing.JTabbedPane; import javax.swing.Popup; import javax.swing.PopupFactory; import javax.swing.RepaintManager; import javax.swing.SwingUtilities; import javax.swing.plaf.basic.BasicInternalFrameUI; import com.jme.bounding.OrientedBoundingBox; import com.jme.image.Texture; import com.jme.input.InputHandler; import com.jme.input.KeyInput; import com.jme.input.MouseInput; import com.jme.input.action.InputAction; import com.jme.input.action.InputActionEvent; import com.jme.math.Ray; import com.jme.math.Vector2f; import com.jme.math.Vector3f; import com.jme.renderer.Renderer; import com.jme.scene.shape.Quad; import com.jme.scene.state.AlphaState; import com.jme.scene.state.TextureState; import com.jme.system.DisplaySystem; import com.jme.util.LoggingSystem; import com.jmex.awt.input.AWTKeyInput; import com.jmex.awt.input.AWTMouseInput; /** * A quad that displays a {@link JDesktopPane} as texture. It also converts jME mouse and keyboard events to Swing * events. The latter does work for ortho mode only. There are some issues with using multiple of this desktops. * * @see ImageGraphics */ public class JMEDesktop extends Quad { private static final long serialVersionUID = 1L; private ImageGraphics graphics; private JDesktopPane desktop; private Texture texture; private boolean initialized; private int width; private int height; private boolean showingJFrame = false; private final Frame awtWindow; private int desktopWidth; private int desktopHeight; private static final int DOUBLE_CLICK_TIME = 300; private final InputHandler inputHandler; private JMEDesktop.XUpdateAction xUpdateAction; private JMEDesktop.YUpdateAction yUpdateAction; private WheelUpdateAction wheelUpdateAction; private JMEDesktop.ButtonAction allButtonsUpdateAction; private InputAction keyUpdateAction; /** * @see #setShowingJFrame */ public boolean isShowingJFrame() { return showingJFrame; } /** * @param showingJFrame true to display the desktop in a JFrame instead on this quad. * @deprecated for debuggin only */ public void setShowingJFrame( boolean showingJFrame ) { this.showingJFrame = showingJFrame; awtWindow.setVisible( showingJFrame ); awtWindow.repaint(); } /** * Allows to disable input for the whole desktop and to add custom input actions. * * @return this desktops input hander for input bindings * @see #getXUpdateAction() * @see #getYUpdateAction() * @see #getWheelUpdateAction() * @see #getButtonUpdateAction(int) * @see #getKeyUpdateAction() */ public InputHandler getInputHandler() { return inputHandler; } /** * Create a quad with a Swing-Texture. Creates the quad and the JFrame but do not setup the rest. * Call {@link #setup(int, int, boolean, InputHandler)} to finish setup. * * @param name name of this desktop */ public JMEDesktop( String name ) { super( name ); inputHandler = new InputHandler(); awtWindow = new Frame() { public boolean isShowing() { return true; } public boolean isVisible() { if ( awtWindow.isFocusableWindow() && new Throwable().getStackTrace()[1].getMethodName().startsWith( "requestFocus" ) ) { return false; } return initialized || super.isVisible(); } public Graphics getGraphics() { if ( !showingJFrame ) { return graphics == null ? super.getGraphics() : graphics.create(); } else { return super.getGraphics(); } } }; awtWindow.setFocusableWindowState( false ); Container contentPane = awtWindow; awtWindow.setUndecorated( true ); dontDrawBackground( contentPane ); // ( (JComponent) contentPane ).setOpaque( false ); desktop = new JDesktopPane() { public void paint( Graphics g ) { if ( !isShowingJFrame() ) { g.clearRect( 0, 0, getWidth(), getHeight() ); } super.paint( g ); } public boolean isOptimizedDrawingEnabled() { return false; } }; final Color transparent = new Color( 0, 0, 0, 0 ); desktop.setBackground( transparent ); desktop.setFocusable( true ); desktop.addMouseListener( new MouseAdapter() { public void mousePressed( MouseEvent e ) { desktop.requestFocusInWindow(); } } ); // this internal frame is a workaround for key binding problems in JDK1.5 // todo: this workaround does not seem to work on mac if ( System.getProperty( "os.name" ).toLowerCase().indexOf( "mac" ) < 0 ) { final JInternalFrame internalFrame = new JInternalFrame(); internalFrame.setUI( new BasicInternalFrameUI( internalFrame ) { protected void installComponents() { } } ); internalFrame.setOpaque( false ); internalFrame.setBackground( null ); internalFrame.getContentPane().setLayout( new BorderLayout() ); internalFrame.getContentPane().add( desktop, BorderLayout.CENTER ); internalFrame.setVisible( true ); internalFrame.setBorder( null ); contentPane.add( internalFrame ); } else { // this would have suited for JDK1.4: contentPane.add( desktop ); } awtWindow.pack(); RepaintManager.currentManager( null ).setDoubleBufferingEnabled( false ); } /** * Create a quad with a Swing-Texture. * Note that for the texture a width and height that is a power of 2 is used if the graphics card does * not support the specified size for textures. E.g. this results in a 1024x512 * texture for a 640x480 desktop (consider using a 512x480 desktop in that case). * * @param name name of the spatial * @param width desktop width * @param height desktop height * @param inputHandlerParent InputHandler where the InputHandler of this desktop should be added as subhandler, * may be null to provide custom input handling or later adding of InputHandler(s) * @see #getInputHandler() */ public JMEDesktop( String name, final int width, final int height, InputHandler inputHandlerParent ) { this( name, width, height, false, inputHandlerParent ); } /** * Create a quad with a Swing-Texture. * Note that for the texture a width and height that is a power of 2 is used if the graphics card does * not support the specified size for textures or mipMapping is true. E.g. this results in a 1024x512 * texture for a 640x480 desktop (consider using a 512x480 desktop in that case). * * @param name name of the spatial * @param width desktop width * @param height desktop hieght * @param mipMapping true to compute mipmaps for the desktop (not recommended), false for creating * a single image texture * @param inputHandlerParent InputHandler where the InputHandler of this desktop should be added as subhandler, * may be null to provide custom input handling or later adding of InputHandler(s) * @see #getInputHandler() */ public JMEDesktop( String name, final int width, final int height, boolean mipMapping, InputHandler inputHandlerParent ) { this( name ); setup( width, height, mipMapping, inputHandlerParent ); } /** * Set up the desktop quad - may be called only once. * Note that for the texture a width and height that is a power of 2 is used if the graphics card does * not support the specified size for textures or mipMapping is true. E.g. this results in a 1024x512 * texture for a 640x480 desktop (consider using a 512x480 desktop in that case). * * @param width desktop width * @param height desktop hieght * @param mipMapping true to compute mipmaps for the desktop (not recommended), false for creating * a single image texture * @param inputHandlerParent InputHandler where the InputHandler of this desktop should be added as subhandler, * may be null to provide custom input handling or later adding of InputHandler(s) * @see #getInputHandler() */ public void setup( int width, int height, boolean mipMapping, InputHandler inputHandlerParent ) { reconstruct( null, null, null, null ); if ( inputHandlerParent != null ) { inputHandlerParent.addToAttachedHandlers( inputHandler ); } if ( initialized ) { throw new IllegalStateException( "may be called only once" ); } initialize( powerOf2SizeIfNeeded( width, mipMapping ), powerOf2SizeIfNeeded( height, mipMapping ) ); this.width = powerOf2SizeIfNeeded( width, mipMapping ); this.height = powerOf2SizeIfNeeded( height, mipMapping ); setModelBound( new OrientedBoundingBox() ); updateModelBound(); desktop.setPreferredSize( new Dimension( width, height ) ); desktopWidth = width; desktopHeight = height; awtWindow.pack(); TextureState ts = DisplaySystem.getDisplaySystem().getRenderer().createTextureState(); texture = new Texture(); texture.setCorrection( Texture.CM_PERSPECTIVE ); texture.setFilter( Texture.FM_LINEAR ); texture.setMipmapState( mipMapping ? Texture.MM_LINEAR_LINEAR : Texture.MM_LINEAR ); texture.setWrap( Texture.WM_WRAP_S_WRAP_T ); graphics = ImageGraphics.createInstance( this.width, this.height, mipMapping ? 2 : 0 ); enableAntiAlias( graphics ); graphics.translate( ( this.width - width ) * 0.5f, ( this.height - height ) * 0.5f ); texture.setImage( graphics.getImage() ); texture.setScale( new Vector3f( 1, -1, 1 ) ); ts.setTexture( texture ); ts.apply(); this.setRenderState( ts ); AlphaState alpha = DisplaySystem.getDisplaySystem().getRenderer().createAlphaState(); alpha.setEnabled( true ); alpha.setBlendEnabled( true ); alpha.setSrcFunction( AlphaState.SB_SRC_ALPHA ); alpha.setDstFunction( AlphaState.DB_ONE_MINUS_SRC_ALPHA ); alpha.setTestEnabled( true ); alpha.setTestFunction( AlphaState.TF_GREATER ); this.setRenderState( alpha ); // Toolkit.getDefaultToolkit().addAWTEventListener( new AWTEventListener() { // public void eventDispatched( AWTEvent event ) { // if ( isShowingJFrame() ) { // System.out.println( event ); // }, 0xFFFFFFFFFFFFFFFFl ); xUpdateAction = new XUpdateAction(); yUpdateAction = new YUpdateAction(); wheelUpdateAction = new WheelUpdateAction(); wheelUpdateAction.setSpeed( AWTMouseInput.WHEEL_AMP ); allButtonsUpdateAction = new ButtonAction( InputHandler.BUTTON_ALL ); keyUpdateAction = new KeyUpdateAction(); setupDefaultInputBindings(); PopupFactory.setSharedInstance( new MyPopupFactory() ); initialized = true; setSynchronizingThreadsOnUpdate( true ); } protected void setupDefaultInputBindings() { getInputHandler().addAction( getButtonUpdateAction( InputHandler.BUTTON_ALL ), InputHandler.DEVICE_MOUSE, InputHandler.BUTTON_ALL, InputHandler.AXIS_NONE, false ); getInputHandler().addAction( getXUpdateAction(), InputHandler.DEVICE_MOUSE, InputHandler.BUTTON_NONE, 0, false ); getInputHandler().addAction( getYUpdateAction(), InputHandler.DEVICE_MOUSE, InputHandler.BUTTON_NONE, 1, false ); getInputHandler().addAction( getWheelUpdateAction(), InputHandler.DEVICE_MOUSE, InputHandler.BUTTON_NONE, 2, false ); getInputHandler().addAction( getKeyUpdateAction(), InputHandler.DEVICE_KEYBOARD, InputHandler.BUTTON_ALL, InputHandler.AXIS_NONE, false ); } //todo: reuse the runnables //todo: possibly reuse events, too? public void onKey( final char character, final int keyCode, final boolean pressed ) { try { SwingUtilities.invokeAndWait( new Runnable() { public void run() { sendAWTKeyEvent( keyCode, pressed, character ); } } ); } catch ( InterruptedException e ) { e.printStackTrace(); } catch ( InvocationTargetException e ) { e.printStackTrace(); } } public void onButton( final int button, final boolean pressed, final int x, final int y ) { convert( x, y, location ); final int awtX = (int) location.x; final int awtY = (int) location.y; try { SwingUtilities.invokeAndWait( new Runnable() { public void run() { sendAWTMouseEvent( awtX, awtY, pressed, button ); } } ); } catch ( InterruptedException e ) { e.printStackTrace(); } catch ( InvocationTargetException e ) { e.printStackTrace(); } } public void onWheel( final int wheelDelta, final int x, final int y ) { convert( x, y, location ); final int awtX = (int) location.x; final int awtY = (int) location.y; try { SwingUtilities.invokeAndWait( new Runnable() { public void run() { sendAWTWheelEvent( wheelDelta, awtX, awtY ); } } ); } catch ( InterruptedException e ) { e.printStackTrace(); } catch ( InvocationTargetException e ) { e.printStackTrace(); } } public void onMove( int xDelta, int yDelta, final int newX, final int newY ) { convert( newX, newY, location ); final int awtX = (int) location.x; final int awtY = (int) location.y; try { SwingUtilities.invokeAndWait( new Runnable() { public void run() { sendAWTMouseEvent( awtX, awtY, false, -1 ); } } ); } catch ( InterruptedException e ) { e.printStackTrace(); } catch ( InvocationTargetException e ) { e.printStackTrace(); } } private boolean synchronizingThreadsOnUpdate; /** * @return true if update and swing thread should be synchronized (avoids flickering, eats some performance) */ public boolean isSynchronizingThreadsOnUpdate() { return synchronizingThreadsOnUpdate; } /** * Choose if update and swing thread should be synchronized (avoids flickering, eats some performance) * * @param synchronizingThreadsOnUpdate true to synchronize */ public void setSynchronizingThreadsOnUpdate( boolean synchronizingThreadsOnUpdate ) { if ( this.synchronizingThreadsOnUpdate != synchronizingThreadsOnUpdate ) { this.synchronizingThreadsOnUpdate = synchronizingThreadsOnUpdate; } } private void enableAntiAlias( Graphics2D graphics ) { RenderingHints hints = graphics.getRenderingHints(); if ( hints == null ) { hints = new RenderingHints( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON ); } else { hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON ); } graphics.setRenderingHints( hints ); } /** * @return an action that should be invoked to generate an awt event when the mouse x-coordinate is changed */ public XUpdateAction getXUpdateAction() { return xUpdateAction; } /** * @return an action that should be invoked to generate an awt event when the mouse y-coordinate is changed */ public YUpdateAction getYUpdateAction() { return yUpdateAction; } /** * @return an action that should be invoked to generate an awt event when the mouse wheel position is changed */ public WheelUpdateAction getWheelUpdateAction() { return wheelUpdateAction; } /** * @param swingButtonIndex button index sent in generated swing event, InputHandler.BUTTON_ALL for using trigger index * @return an action that should be invoked to generate an awt event for a pressed/released mouse button */ public ButtonAction getButtonUpdateAction( int swingButtonIndex ) { if ( swingButtonIndex == InputHandler.BUTTON_ALL ) { return allButtonsUpdateAction; } else { return new ButtonAction( swingButtonIndex ); } } /** * @return an action that should be invoked to generate an awt event for a pressed/released key */ public InputAction getKeyUpdateAction() { return keyUpdateAction; } private static class LightWeightPopup extends Popup { public LightWeightPopup( JComponent desktop ) { this.desktop = desktop; } private final JComponent desktop; JPanel panel = new JPanel( new BorderLayout() ); public void adjust( Component owner, Component contents, int x, int y ) { panel.setVisible( false ); desktop.add( panel, 0 ); panel.removeAll(); panel.add( contents, BorderLayout.CENTER ); if ( contents instanceof JComponent ) { JComponent jComponent = (JComponent) contents; jComponent.setDoubleBuffered( false ); } panel.setSize( panel.getPreferredSize() ); panel.setLocation( x, y ); contents.invalidate(); panel.validate(); } public void show() { panel.setVisible( true ); } public void hide() { Rectangle bounds = panel.getBounds(); desktop.remove( panel ); desktop.repaint( bounds ); } } private void sendAWTKeyEvent( int keyCode, boolean pressed, char character ) { keyCode = AWTKeyInput.toAWTCode( keyCode ); if ( keyCode != 0 ) { Component focusOwner = getFocusOwner(); if ( focusOwner == null ) { focusOwner = desktop; } if ( focusOwner != null ) { if ( pressed ) { KeyEvent event = new KeyEvent( focusOwner, KeyEvent.KEY_PRESSED, System.currentTimeMillis(), getCurrentModifiers( -1 ), keyCode, character ); dispatchEvent( focusOwner, event ); anInt.value = keyCode; Char c = (Char) characters.get( anInt ); if ( c == null ) { characters.put( new Int( keyCode ), new Char( character ) ); } else { c.value = character; } } if ( !pressed ) { anInt.value = keyCode; Char c = (Char) characters.get( anInt ); if ( c != null ) { character = c.value; //TODO: repeat input if ( character != '\0' ) { dispatchEvent( focusOwner, new KeyEvent( focusOwner, KeyEvent.KEY_TYPED, System.currentTimeMillis(), getCurrentModifiers( -1 ), 0, character ) ); } } dispatchEvent( focusOwner, new KeyEvent( focusOwner, KeyEvent.KEY_RELEASED, System.currentTimeMillis(), getCurrentModifiers( -1 ), keyCode, character ) ); } } } } private void dispatchEvent( final Component receiver, final AWTEvent event ) { if ( getModalComponent() == null || SwingUtilities.isDescendingFrom( receiver, getModalComponent() ) ) { if ( !SwingUtilities.isEventDispatchThread() ) { throw new IllegalStateException( "not in swing thread!" ); } receiver.dispatchEvent( event ); } } private static Int anInt = new Int( 0 ); private static class Int { public Int( int value ) { this.value = value; } public boolean equals( Object obj ) { if ( obj instanceof Int ) { return ( (Int) obj ).value == value; } else { return false; } } public int hashCode() { return value; } int value; } private static class Char { public Char( char value ) { this.value = value; } char value; } /** * From keyCode (Int) to character (Char) */ private Map characters = new HashMap(); private static void dontDrawBackground( Container container ) { if ( container != null ) { container.setBackground( null ); if ( container instanceof JComponent ) { final JComponent component = ( (JComponent) container ); component.setOpaque( false ); } dontDrawBackground( container.getParent() ); } } private static int powerOf2SizeIfNeeded( int size, boolean generateMipMaps ) { if ( generateMipMaps || !TextureState.isSupportingNonPowerOfTwoTextureSize() ) { int powerOf2Size = 1; while ( powerOf2Size < size ) { powerOf2Size <<= 1; } return powerOf2Size; } else { return size; } } private Component lastComponent; private Component grabbedMouse; private int grabbedMouseButton; private int downX = 0; private int downY = 0; private long lastClickTime = 0; private int clickCount = 0; private static final int MAX_CLICKED_OFFSET = 4; private Vector2f location = new Vector2f(); private void sendAWTWheelEvent( int wheelDelta, int x, int y ) { Component comp = lastComponent != null ? lastComponent : componentAt( x, y, desktop, false ); if ( comp == null ) { comp = desktop; } final Point pos = SwingUtilities.convertPoint( desktop, x, y, comp ); final MouseWheelEvent event = new MouseWheelEvent( comp, MouseEvent.MOUSE_WHEEL, System.currentTimeMillis(), getCurrentModifiers( -1 ), pos.x, pos.y, 1, false, MouseWheelEvent.WHEEL_UNIT_SCROLL, Math.abs( wheelDelta ), wheelDelta > 0 ? -1 : 1 ); dispatchEvent( comp, event ); } private void sendAWTMouseEvent( int x, int y, boolean pressed, int button ) { Component comp = componentAt( x, y, desktop, false ); final int eventType; if ( button >= 0 ) { eventType = pressed ? MouseEvent.MOUSE_PRESSED : MouseEvent.MOUSE_RELEASED; } else { eventType = getButtonMask( -1 ) == 0 ? MouseEvent.MOUSE_MOVED : MouseEvent.MOUSE_DRAGGED; } final long time = System.currentTimeMillis(); if ( lastComponent != comp ) { //enter/leave events while ( lastComponent != null && ( comp == null || !SwingUtilities.isDescendingFrom( comp, lastComponent ) ) ) { final Point pos = SwingUtilities.convertPoint( desktop, x, y, lastComponent ); sendExitedEvent( lastComponent, getCurrentModifiers( button ), pos ); lastComponent = lastComponent.getParent(); } final Point pos = SwingUtilities.convertPoint( desktop, x, y, lastComponent ); if ( lastComponent == null ) { lastComponent = desktop; } sendEnteredEvent( comp, lastComponent, getCurrentModifiers( button ), pos ); lastComponent = comp; downX = Integer.MIN_VALUE; downY = Integer.MIN_VALUE; lastClickTime = 0; } boolean clicked = false; if ( comp != null ) { if ( button >= 0 ) { if ( pressed ) { grabbedMouse = comp; grabbedMouseButton = button; downX = x; downY = y; setFocusOwner( componentAt( x, y, desktop, true ) ); } else if ( grabbedMouseButton == button && grabbedMouse != null ) { comp = grabbedMouse; grabbedMouse = null; if ( Math.abs( downX - x ) <= MAX_CLICKED_OFFSET && Math.abs( downY - y ) < MAX_CLICKED_OFFSET ) { if ( lastClickTime + DOUBLE_CLICK_TIME > time ) { clickCount++; } else { clickCount = 1; } clicked = true; lastClickTime = time; } downX = Integer.MIN_VALUE; downY = Integer.MIN_VALUE; } } else if ( grabbedMouse != null ) { comp = grabbedMouse; } final Point pos = SwingUtilities.convertPoint( desktop, x, y, comp ); final MouseEvent event = new MouseEvent( comp, eventType, time, getCurrentModifiers( button ), pos.x, pos.y, clickCount, button == 1 && pressed, button >= 0 ? button : 0 ); dispatchEvent( comp, event ); if ( clicked ) { // CLICKED seems to need special glass pane handling o_O comp = componentAt( x, y, desktop, true ); final Point clickedPos = SwingUtilities.convertPoint( desktop, x, y, comp ); final MouseEvent clickedEvent = new MouseEvent( comp, MouseEvent.MOUSE_CLICKED, time, getCurrentModifiers( button ), clickedPos.x, clickedPos.y, clickCount, false, button ); dispatchEvent( comp, clickedEvent ); } } else if ( pressed ) { // clicked no component at all setFocusOwner( null ); } } private boolean focusCleared = false; public void setFocusOwner( Component comp ) { focusCleared = comp == null; if ( comp != null ) { for ( Container p = comp.getParent(); p != null; p = p.getParent() ) { if ( p instanceof JInternalFrame ) { setFocusOwner( p ); } } } if ( comp == null || comp.isFocusable() ) { awtWindow.setFocusableWindowState( true ); Component oldFocusOwner = getFocusOwner(); if ( comp == desktop ) { comp = null; } if ( oldFocusOwner != comp ) { if ( oldFocusOwner != null ) { dispatchEvent( oldFocusOwner, new FocusEvent( oldFocusOwner, FocusEvent.FOCUS_LOST, false, comp ) ); } if ( comp != null ) { dispatchEvent( comp, new FocusEvent( comp, FocusEvent.FOCUS_GAINED, false, oldFocusOwner ) ); } else { if ( getFocusOwner() != null ) { KeyboardFocusManager.getCurrentKeyboardFocusManager().clearGlobalFocusOwner(); } } } awtWindow.setFocusableWindowState( false ); } } private int getCurrentModifiers( int button ) { int modifiers = 0; if ( isKeyDown( KeyInput.KEY_LMENU ) ) { modifiers |= KeyEvent.ALT_DOWN_MASK; modifiers |= KeyEvent.ALT_MASK; } if ( isKeyDown( KeyInput.KEY_RMENU ) ) { modifiers |= KeyEvent.ALT_GRAPH_DOWN_MASK; modifiers |= KeyEvent.ALT_GRAPH_MASK; } if ( isKeyDown( KeyInput.KEY_LCONTROL ) || isKeyDown( KeyInput.KEY_RCONTROL ) ) { modifiers |= KeyEvent.CTRL_DOWN_MASK; modifiers |= KeyEvent.CTRL_MASK; } if ( isKeyDown( KeyInput.KEY_LSHIFT ) || isKeyDown( KeyInput.KEY_RSHIFT ) ) { modifiers |= KeyEvent.SHIFT_DOWN_MASK; modifiers |= KeyEvent.SHIFT_MASK; } return modifiers | getButtonMask( button ); } private boolean isKeyDown( int key ) { return KeyInput.get().isKeyDown( key ); } private int getButtonMask( int button ) { int buttonMask = 0; if ( MouseInput.get().isButtonDown( 0 ) || button == 0 ) { buttonMask |= MouseEvent.BUTTON1_MASK; buttonMask |= MouseEvent.BUTTON1_DOWN_MASK; } if ( MouseInput.get().isButtonDown( 1 ) || button == 1 ) { buttonMask |= MouseEvent.BUTTON2_MASK; buttonMask |= MouseEvent.BUTTON2_DOWN_MASK; } if ( MouseInput.get().isButtonDown( 2 ) || button == 2 ) { buttonMask |= MouseEvent.BUTTON3_MASK; buttonMask |= MouseEvent.BUTTON3_DOWN_MASK; } return buttonMask; } private int lastXin = -1; private int lastXout = -1; private int lastYin = -1; private int lastYout = -1; private Ray pickRay = new Ray(); private Vector3f bottomLeft = new Vector3f(); private Vector3f topLeft = new Vector3f(); private Vector3f topRight = new Vector3f(); private Vector3f bottomRight = new Vector3f(); private Vector3f tuv = new Vector3f(); private void convert( int x, int y, Vector2f store ) { if ( lastXin == x && lastYin == y ) { store.x = lastXout; store.y = lastYout; } else { lastXin = x; lastYin = y; if ( getRenderQueueMode() == Renderer.QUEUE_ORTHO ) { //TODO: occlusion by other quads (JMEFrames) x = (int) ( x - getWorldTranslation().x + desktopWidth / 2 ); y = (int) ( DisplaySystem.getDisplaySystem().getHeight() - y - getWorldTranslation().y + desktopHeight / 2 ); } else { store.set( x, y ); DisplaySystem.getDisplaySystem().getWorldCoordinates( store, 0, pickRay.origin ); DisplaySystem.getDisplaySystem().getWorldCoordinates( store, 0.3f, pickRay.direction ).subtractLocal( pickRay.origin ).normalizeLocal(); applyWorld( bottomLeft.set( -width * 0.5f, -height * 0.5f, 0 ) ); applyWorld( topLeft.set( -width * 0.5f, height * 0.5f, 0 ) ); applyWorld( topRight.set( width * 0.5f, height * 0.5f, 0 ) ); applyWorld( bottomRight.set( width * 0.5f, -height * 0.5f, 0 ) ); if ( pickRay.intersectWherePlanarQuad( topLeft, topRight, bottomLeft, tuv ) ) { x = (int) ( ( tuv.y - 0.5f ) * width ) + desktopWidth / 2; y = (int) ( ( tuv.z - 0.5f ) * height ) + desktopHeight / 2; } else { x = -1; y = -1; } } lastYout = y; lastXout = x; store.set( x, y ); } } private void applyWorld( Vector3f point ) { getWorldRotation().multLocal( point.multLocal( getWorldScale() ) ).addLocal( getWorldTranslation() ); } private Component componentAt( int x, int y, Component parent, boolean scanRootPanes ) { if ( scanRootPanes && parent instanceof JRootPane ) { JRootPane rootPane = (JRootPane) parent; parent = rootPane.getContentPane(); } Component child = parent.getComponentAt( x, y ); if ( child != null ) { if ( parent instanceof JTabbedPane && child != parent ) { child = ( (JTabbedPane) parent ).getSelectedComponent(); } x -= child.getX(); y -= child.getY(); } return child != parent && child != null ? componentAt( x, y, child, scanRootPanes ) : child; } private void sendEnteredEvent( Component comp, Component lastComponent, int buttonMask, Point pos ) { if ( comp != null && comp != lastComponent ) { sendEnteredEvent( comp.getParent(), lastComponent, buttonMask, pos ); pos = SwingUtilities.convertPoint( lastComponent, pos.x, pos.y, comp ); final MouseEvent event = new MouseEvent( comp, MouseEvent.MOUSE_ENTERED, System.currentTimeMillis(), buttonMask, pos.x, pos.y, 0, false, 0 ); dispatchEvent( comp, event ); } } private void sendExitedEvent( Component lastComponent, int buttonMask, Point pos ) { final MouseEvent event = new MouseEvent( lastComponent, MouseEvent.MOUSE_EXITED, System.currentTimeMillis(), buttonMask, pos.x, pos.y, 1, false, 0 ); dispatchEvent( lastComponent, event ); } private final LockRunnable paintLockRunnable = new LockRunnable(); public void draw( Renderer r ) { if ( graphics.isDirty() ) { final boolean synchronizingThreadsOnUpdate = this.synchronizingThreadsOnUpdate; if ( synchronizingThreadsOnUpdate ) { synchronized ( paintLockRunnable ) { try { paintLockRunnable.wait = true; SwingUtilities.invokeLater( paintLockRunnable ); paintLockRunnable.wait( 100 ); } catch ( InterruptedException e ) { e.printStackTrace(); } } } try { if ( graphics != null ) { graphics.update( texture ); } } finally { if ( synchronizingThreadsOnUpdate ) { synchronized ( paintLockRunnable ) { paintLockRunnable.notifyAll(); } } } } super.draw( r ); } public JDesktopPane getJDesktop() { return desktop; } public Component getFocusOwner() { if ( !focusCleared ) { return this.awtWindow.getFocusOwner(); } else { return null; } } private class LockRunnable implements Runnable { private boolean wait = false; public void run() { synchronized ( paintLockRunnable ) { notifyAll(); if ( wait ) { try { //wait for repaint to finish wait = false; paintLockRunnable.wait( 200 ); } catch ( InterruptedException e ) { e.printStackTrace(); } } } } } private static class MyPopupFactory extends PopupFactory { public Popup getPopup( Component owner, Component contents, int x, int y ) throws IllegalArgumentException { while ( !( owner instanceof JDesktopPane ) ) { owner = owner.getParent(); if ( owner == null ) { LoggingSystem.getLogger().severe( "Popup creation failed - desktop not found in component hierarchy of " + owner ); return null; } } JMEDesktop.LightWeightPopup popup = new JMEDesktop.LightWeightPopup( (JComponent) owner ); popup.adjust( owner, contents, x, y ); return popup; } } private class ButtonAction extends InputAction { private final int swingButtonIndex; /** * @param swingButtonIndex button index sent in generated swing event, InputHandler.BUTTON_ALL for using trigger index */ public ButtonAction( int swingButtonIndex ) { this.swingButtonIndex = swingButtonIndex; } public void performAction( InputActionEvent evt ) { onButton( swingButtonIndex != InputHandler.BUTTON_ALL ? swingButtonIndex : evt.getTriggerIndex(), evt.getTriggerPressed(), lastXin, lastYin ); } } private class XUpdateAction extends InputAction { public XUpdateAction() { setSpeed( 1 ); } public void performAction( InputActionEvent evt ) { int screenWidth = DisplaySystem.getDisplaySystem().getWidth(); onMove( (int) ( screenWidth * evt.getTriggerDelta() * getSpeed() ), 0, (int) ( screenWidth * evt.getTriggerPosition() * getSpeed() ), lastYin ); } } private class YUpdateAction extends InputAction { public YUpdateAction() { setSpeed( 1 ); } public void performAction( InputActionEvent evt ) { int screenHeight = DisplaySystem.getDisplaySystem().getHeight(); onMove( 0, (int) ( screenHeight * evt.getTriggerDelta() * getSpeed() ), lastXin, (int) ( screenHeight * evt.getTriggerPosition() * getSpeed() ) ); } } private class WheelUpdateAction extends InputAction { public WheelUpdateAction() { setSpeed( 1 ); } public void performAction( InputActionEvent evt ) { onWheel( (int) ( evt.getTriggerDelta() * getSpeed() ), lastXin, lastYin ); } } private class KeyUpdateAction extends InputAction { public void performAction( InputActionEvent evt ) { onKey( evt.getTriggerCharacter(), evt.getTriggerIndex(), evt.getTriggerPressed() ); } } /** * @return current modal component * @see #setModalComponent(java.awt.Component) */ public Component getModalComponent() { return this.modalComponent; } /** * @see #setModalComponent(java.awt.Component) */ private Component modalComponent; /** * Filter the swing event to allow events to the specified component and its children only. * Note: this does not prevent shortcuts and mnemonics to work for the other components! * @param value component that can be exclusively accessed (including children) */ public void setModalComponent( final Component value ) { this.modalComponent = value; } }
package com.reason.merlin; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.intellij.notification.NotificationType; import com.intellij.notification.Notifications; import com.reason.Platform; import com.reason.ide.ReasonMLNotification; import org.jetbrains.annotations.Nullable; import java.io.*; import java.util.List; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; public class MerlinProcess implements Closeable { static final String NO_CONTEXT = null; private ObjectMapper m_objectMapper; private Process m_merlin; private BufferedWriter m_writer; private BufferedReader m_reader; private BufferedReader m_errorReader; MerlinProcess(String merlinBin) throws IOException { List<String> commands; if (Platform.isWindows()) { commands = singletonList(merlinBin); } else { String absolutePath = new File(merlinBin).getAbsoluteFile().getParent(); commands = asList("bash", "-c", "export PATH=" + absolutePath + ":$PATH && ocamlmerlin"); } ProcessBuilder processBuilder = new ProcessBuilder(commands).redirectErrorStream(true); m_merlin = processBuilder.start(); m_writer = new BufferedWriter(new OutputStreamWriter(m_merlin.getOutputStream())); m_reader = new BufferedReader(new InputStreamReader(m_merlin.getInputStream())); m_errorReader = new BufferedReader(new InputStreamReader(m_merlin.getErrorStream())); m_objectMapper = new ObjectMapper(); } @Override public void close() throws IOException { if (m_merlin != null && m_merlin.isAlive()) { try { m_writer.close(); m_reader.close(); m_errorReader.close(); } catch (IOException e) { // nothing to do } m_merlin.destroyForcibly(); m_merlin = null; } } @Nullable synchronized <R> R makeRequest(TypeReference<R> type, @Nullable String filename, String query) { if (m_merlin == null) { return null; } try { String request; if (filename == NO_CONTEXT) { request = query; } else { request = "{\"context\": [\"auto\", " + m_objectMapper.writeValueAsString(filename) + "], " + "\"query\": " + query + "}"; } // System.out.println("=> " + request); m_writer.write(request); m_writer.flush(); if (m_errorReader.ready()) { StringBuilder errorBuffer = new StringBuilder(); m_errorReader.lines().forEach(l -> errorBuffer.append(l).append(System.lineSeparator())); throw new RuntimeException(errorBuffer.toString()); } else { String content = m_reader.readLine(); // System.out.println("<= content: " + content); JsonNode jsonNode = m_objectMapper.readTree(content); JsonNode responseNode = extractResponse(jsonNode); if (responseNode == null) { return null; } //System.out.println("<= " + responseNode); try { return m_objectMapper.convertValue(responseNode, type); } catch (RuntimeException e) { System.err.println("!! Request conversion error"); System.err.println(" file: " + filename); System.err.println(" request: " + query); System.err.println(" content: " + content); System.err.println(" msg: " + e.getMessage()); throw e; } } } catch (IOException e) { System.err.println("!! Request IO error"); System.err.println(" file: " + filename); System.err.println(" request: " + query); System.err.println(" msg: " + e.getMessage()); throw new UncheckedIOException(e); } } @Nullable private JsonNode extractResponse(JsonNode merlinResult) { JsonNode classField = merlinResult.get("class"); if (classField == null) { return null; } JsonNode value = merlinResult.get("value"); String responseType = classField.textValue(); if ("return".equals(responseType)) { return value; } // Something went wrong with merlin, it can be: failure|error|exception // https://github.com/ocaml/merlin/blob/master/doc/dev/PROTOCOL.md#answers if ("error".equals(responseType)) { Notifications.Bus.notify(new ReasonMLNotification("Merlin", responseType, value.toString(), NotificationType.ERROR, null)); } // failure or error should not be reported to the user return null; } String writeValueAsString(Object value) { try { return m_objectMapper.writeValueAsString(value); } catch (JsonProcessingException e) { throw new RuntimeException(e); } } }
package com.untamedears.citadel; import java.util.ArrayList; import java.util.Arrays; import java.util.ConcurrentModificationException; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.UUID; import org.bukkit.ChatColor; import org.bukkit.DyeColor; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; import org.bukkit.material.MaterialData; import org.bukkit.material.Wool; import com.untamedears.citadel.Citadel.VerboseMsg; import com.untamedears.citadel.access.AccessDelegate; import com.untamedears.citadel.entity.Faction; import com.untamedears.citadel.entity.IReinforcement; import com.untamedears.citadel.entity.NaturalReinforcement; import com.untamedears.citadel.entity.PlayerReinforcement; import com.untamedears.citadel.entity.PlayerState; import com.untamedears.citadel.entity.ReinforcementKey; import com.untamedears.citadel.entity.ReinforcementMaterial; import com.untamedears.citadel.events.CreateReinforcementEvent; import com.valadian.nametracker.NameAPI; public class Utility { private static Map<SecurityLevel, MaterialData> securityMaterial; private static Random rng = new Random(); static { securityMaterial = new HashMap<SecurityLevel, MaterialData>(); securityMaterial.put(SecurityLevel.PUBLIC, new Wool(DyeColor.GREEN)); securityMaterial.put(SecurityLevel.GROUP, new Wool(DyeColor.YELLOW)); securityMaterial.put(SecurityLevel.PRIVATE, new Wool(DyeColor.RED)); } public static Block getAttachedChest(Block block) { Material mat = block.getType(); if (mat == Material.CHEST || mat == Material.TRAPPED_CHEST) { for (BlockFace face : new BlockFace[]{BlockFace.NORTH, BlockFace.EAST, BlockFace.SOUTH, BlockFace.WEST}) { Block b = block.getRelative(face); if (b.getType() == mat) { return b; } } } return null; } public static IReinforcement createNaturalReinforcement(Block block, Player player) { Material material = block.getType(); int breakCount = Citadel .getConfigManager() .getMaterialBreakCount(material.getId(), block.getY()); if (breakCount <= 1) { return null; } NaturalReinforcement nr = new NaturalReinforcement(block, breakCount); CreateReinforcementEvent event = new CreateReinforcementEvent(nr, block, player); Citadel.getStaticServer().getPluginManager().callEvent(event); if (event.isCancelled()) { return null; } Citadel.getReinforcementManager().addReinforcement(nr); return nr; } @SuppressWarnings("deprecation") public static IReinforcement createPlayerReinforcement(Player player, Block block) { int blockTypeId = block.getTypeId(); if (PlayerReinforcement.NON_REINFORCEABLE.contains(blockTypeId)) return null; PlayerState state = PlayerState.get(player); Faction group = state.getFaction(); if(group == null) { try { group = Faction.getPersonalGroup(player.getUniqueId()); } catch (NullPointerException e){ sendMessage(player, ChatColor.RED, "You don't seem to have a personal group. Try logging out and back in first"); } } if(group == null) { return null; } if (group.isDisciplined()) { sendMessage(player, ChatColor.RED, Faction.kDisciplineMsg); return null; } ReinforcementMaterial material; switch (state.getMode()) { case REINFORCEMENT: case REINFORCEMENT_SINGLE_BLOCK: Material inHand = player.getItemInHand().getType(); material = ReinforcementMaterial.get(inHand); if (material == null) { sendMessage(player, ChatColor.RED, "Material in hand %s is not a valid reinforcement material.", inHand.name()); state.reset(); return null; } break; case FORTIFICATION: material = state.getReinforcementMaterial(); break; default: return null; } // Find necessary itemstacks final PlayerInventory inv = player.getInventory(); final int invSize = inv.getSize(); final Material materialType = material.getMaterial(); List<Integer> slots = new ArrayList<Integer>(material.getRequirements()); int requirements = material.getRequirements(); if (requirements <= 0) { Citadel.severe("Reinforcement requirements too low for " + materialType); return null; } try { for (int slot = 0; slot < invSize && requirements > 0; ++slot) { final ItemStack slotItem = inv.getItem(slot); if (slotItem == null) { continue; } if (!slotItem.getType().equals(materialType)) { continue; } requirements -= slotItem.getAmount(); slots.add(slot); } } catch (Exception ex) { // Eat any inventory size mis-match exceptions, like with the Anvil } if (requirements > 0) { // Not enough reinforcement material return null; } // Fire the creation event PlayerReinforcement reinforcement = new PlayerReinforcement(block, material, group, state.getSecurityLevel()); CreateReinforcementEvent event = new CreateReinforcementEvent(reinforcement, block, player); Citadel.getStaticServer().getPluginManager().callEvent(event); if (event.isCancelled()) { return null; } // Now eat the materials requirements = material.getRequirements(); for (final int slot : slots) { if (requirements <= 0) { break; } final ItemStack slotItem = inv.getItem(slot); final int stackSize = slotItem.getAmount(); final int deduction = Math.min(stackSize, requirements); if (deduction < stackSize) { slotItem.setAmount(stackSize - deduction); } else { inv.clear(slot); } requirements -= deduction; } if (requirements != 0) { Citadel.warning(String.format( "Reinforcement material out of sync %d vs %d", requirements, material.getRequirements())); } //TODO: there will eventually be a better way to flush inventory changes to the client player.updateInventory(); reinforcement = (PlayerReinforcement)Citadel.getReinforcementManager().addReinforcement(reinforcement); String securityLevelText = state.getSecurityLevel().name(); if(securityLevelText.equalsIgnoreCase("group")){ securityLevelText = securityLevelText + "-" + group.getName(); } sendThrottledMessage(player, ChatColor.GREEN, "Reinforced with %s at security level %s", material.getMaterial().name(), securityLevelText); Citadel.verbose( VerboseMsg.ReinCreated, player.getDisplayName(), material.getMaterialId(), block.getWorld().getName(), block.getX(), block.getY(), block.getZ()); // TODO: enable chained flashers, they're pretty cool //new BlockFlasher(block, material.getFlasher()).start(getPlugin()); //new BlockFlasher(block, material.getFlasher()).chain(securityMaterial.get(state.getSecurityLevel())).start(); return reinforcement; } public static void sendMessage(CommandSender sender, ChatColor color, String messageFormat, Object... params) { sender.sendMessage(color + String.format(messageFormat, params)); } public static void sendThrottledMessage(CommandSender sender, ChatColor color, String messageFormat, Object... params) { if (sender instanceof Player) { Player player = (Player) sender; PlayerState state = PlayerState.get(player); if (System.currentTimeMillis() - state.getLastThrottledMessage() > (1000 * 30)) { sendMessage(player, color, messageFormat, params); } state.setLastThrottledMessage(System.currentTimeMillis()); } } public static boolean explodeReinforcement(Block block) { AccessDelegate delegate = AccessDelegate.getDelegate(block); IReinforcement reinforcement = delegate.getReinforcement(); if (reinforcement == null) { reinforcement = createNaturalReinforcement(block, null); } if (reinforcement == null) { return false; } return reinforcementDamaged(reinforcement); } public static boolean isReinforced(Location location) { return getReinforcement(location) != null; } public static boolean isReinforced(Block block) { return getReinforcement(block) != null; } public static IReinforcement getReinforcement(Location location) { return getReinforcement(location.getBlock()); } public static IReinforcement getReinforcement(Block block) { AccessDelegate delegate = AccessDelegate.getDelegate(block); IReinforcement reinforcement = delegate.getReinforcement(); return reinforcement; } public static IReinforcement addReinforcement(IReinforcement reinforcement) { return Citadel.getReinforcementManager().addReinforcement(reinforcement); } public static void removeReinforcement(IReinforcement reinforcement) { Citadel.getReinforcementManager().removeReinforcement(reinforcement); } public static boolean isAuthorizedPlayerNear(PlayerReinforcement reinforcement, double distance) { ReinforcementKey key = reinforcement.getId(); World reinWorld = Citadel.getPlugin().getServer().getWorld(key.getWorld()); Location reinLocation = new Location( reinWorld, (double)key.getX(), (double)key.getY(), (double)key.getZ()); double min_x = reinLocation.getX() - distance; double min_z = reinLocation.getZ() - distance; double max_x = reinLocation.getX() + distance; double max_z = reinLocation.getZ() + distance; List<Player> onlinePlayers = reinWorld.getPlayers(); boolean result = false; try { for (Player player : onlinePlayers) { if (player.isDead()) { continue; } Location playerLocation = player.getLocation(); double player_x = playerLocation.getX(); double player_z = playerLocation.getZ(); // Simple bounding box check to quickly rule out Players // before doing the more expensive playerLocation.distance if (player_x < min_x || player_x > max_x || player_z < min_z || player_z > max_z) { continue; } if (!reinforcement.isAccessible(player) && !player.hasPermission("citadel.admin.accesssecurable")) { continue; } double distanceSquared = playerLocation.distance(reinLocation); if (distanceSquared <= distance) { result = true; break; } } } catch (ConcurrentModificationException e) { Citadel.warning("ConcurrentModificationException at redstonePower() in BlockListener"); } return result; } public static boolean maybeReinforcementDamaged(Block block) { AccessDelegate delegate = AccessDelegate.getDelegate(block); IReinforcement reinforcement = delegate.getReinforcement(); return reinforcement != null && reinforcementDamaged(reinforcement); } public static int timeUntilMature(IReinforcement reinforcement) { // Doesn't explicitly save the updated Maturation time into the cache. // That's the responsibility of the caller. if (reinforcement instanceof PlayerReinforcement) { int maturationTime = reinforcement.getMaturationTime(); if (maturationTime > 0) { final int curMinute = (int)(System.currentTimeMillis() / 60000L); if (curMinute >= maturationTime) { maturationTime = 0; reinforcement.setMaturationTime(0); } else { maturationTime = maturationTime - curMinute; } } return maturationTime; } return 0; } public static boolean reinforcementDamaged(IReinforcement reinforcement) { int durability = reinforcement.getDurability(); int durabilityLoss = 1; if (reinforcement instanceof PlayerReinforcement && Citadel.getConfigManager().maturationEnabled()) { final int maturationTime = timeUntilMature(reinforcement); if (maturationTime > 0) { durabilityLoss = maturationTime / 60 + 1; int blockType = reinforcement.getBlock().getTypeId(); if (PlayerReinforcement.MATERIAL_SCALING.containsKey(blockType)) { final double scale = PlayerReinforcement.MATERIAL_SCALING.get(blockType); durabilityLoss = (int)((double)durabilityLoss * scale); if (durabilityLoss < 0) { durabilityLoss = 1; } } } if (durability < durabilityLoss) { durabilityLoss = durability; } } durability -= durabilityLoss; reinforcement.setDurability(durability); boolean cancelled = durability > 0; if (durability <= 0) { cancelled = reinforcementBroken(null, reinforcement); } else { if (reinforcement instanceof PlayerReinforcement) { Citadel.verbose( VerboseMsg.ReinDmg, reinforcement.getBlock().getLocation().toString()); } Citadel.getReinforcementManager().addReinforcement(reinforcement); } return cancelled; } public static boolean reinforcementBroken(Player player, IReinforcement reinforcement) { Citadel.getReinforcementManager().removeReinforcement(reinforcement); if (reinforcement instanceof PlayerReinforcement) { PlayerReinforcement pr = (PlayerReinforcement)reinforcement; Citadel.verbose(VerboseMsg.ReinDestroyed, pr.getBlock().getLocation().toString()); if (rng.nextDouble() <= pr.getHealth()) { Location location = pr.getBlock().getLocation(); ReinforcementMaterial material = pr.getMaterial(); if (player != null){ Inventory inv = player.getInventory(); boolean given = false; for (ItemStack stack: inv.getContents()){ if (stack != null && stack.getTypeId() == material.getMaterialId() && stack.getAmount() + material.getRequirements() <= stack.getMaxStackSize()){ stack.setAmount(stack.getAmount() + material.getRequirements()); given = true; break; } } int first = inv.firstEmpty(); if (!given && first == -1) location.getWorld().dropItem(location, material.getRequiredMaterials()); else inv.setItem(first, new ItemStack(material.getMaterial(), 1)); } else location.getWorld().dropItem(location, material.getRequiredMaterials()); } return pr.isSecurable(); } return false; // implicit isSecureable() == false } public static SecurityLevel getSecurityLevel(String[] args, Player player) { if (args.length > 0) { try { return SecurityLevel.valueOf(args[0].toUpperCase()); } catch (IllegalArgumentException e) { sendMessage(player, ChatColor.RED, "Invalid access level %s", args[0]); return null; } } return SecurityLevel.PRIVATE; } private static List<PlacementMode> MULTI_MODE = Arrays.asList(PlacementMode.FORTIFICATION, PlacementMode.INFO, PlacementMode.REINFORCEMENT, PlacementMode.INSECURE); public static void setMultiMode(PlacementMode mode, SecurityLevel securityLevel, String[] args, Player player, PlayerState state) { if (!MULTI_MODE.contains(mode)) return; Faction group = state.getFaction(); if (group != null && group.isDisciplined()) { sendMessage(player, ChatColor.RED, Faction.kDisciplineMsg); return; } if (state.getMode() == mode && state.getSecurityLevel() == securityLevel) { state.reset(); sendMessage(player, ChatColor.GREEN, "%s mode off", mode.name()); } else { state.setMode(mode); state.setSecurityLevel(securityLevel); switch (mode) { case REINFORCEMENT: sendMessage(player, ChatColor.GREEN, "%s mode %s", mode.name(), securityLevel.name()); break; case FORTIFICATION: sendMessage(player, ChatColor.GREEN, "%s mode %s, %s", mode.name(), state.getReinforcementMaterial().getMaterial().name(), securityLevel.name()); break; case INFO: case INSECURE: sendMessage(player, ChatColor.GREEN, "%s mode on", mode.name()); break; } state.checkResetMode(); } } public static void setSingleMode(SecurityLevel securityLevel, PlayerState state, Player player) { Faction group = state.getFaction(); if (group != null && group.isDisciplined()) { sendMessage(player, ChatColor.RED, Faction.kDisciplineMsg); return; } if (state.getMode() != PlacementMode.REINFORCEMENT_SINGLE_BLOCK) { state.setSecurityLevel(securityLevel); state.setMode(PlacementMode.REINFORCEMENT_SINGLE_BLOCK); sendMessage(player, ChatColor.GREEN, "Single block reinforcement mode %s", securityLevel.name() + "."); } } public static String getTruncatedMaterialMessage(String prefix, List<Integer> materials) { StringBuilder builder = new StringBuilder(); for (int materialId : materials) { if (builder.length() > 0) builder.append(", "); builder.append(Material.getMaterial(materialId).name()); } builder.insert(0, prefix); return builder.toString(); } public static Set<Material> getPlantSoilTypes(Material mat) { Set<Material> soilTypes = new HashSet<Material>(); if (isSoilPlant(mat)) { soilTypes.add(Material.SOIL); } if (isDirtPlant(mat)) { soilTypes.add(Material.DIRT); } if (isGrassPlant(mat)) { soilTypes.add(Material.GRASS); } if (isSandPlant(mat)) { soilTypes.add(Material.SAND); } if (isSoulSandPlant(mat)) { soilTypes.add(Material.SOUL_SAND); } return soilTypes; } public static Block findPlantSoil(Block plant) { final Set<Material> soilTypes = getPlantSoilTypes(plant.getType()); if (soilTypes.size() <= 0) { return null; } return findSoilBelow(plant, soilTypes); } public static boolean isSoilPlant(Material mat) { return mat.equals(Material.WHEAT) || mat.equals(Material.MELON_STEM) || mat.equals(Material.PUMPKIN_STEM) || mat.equals(Material.CARROT) || mat.equals(Material.POTATO) || mat.equals(Material.CROPS) || mat.equals(Material.MELON_BLOCK) || mat.equals(Material.PUMPKIN); } public static boolean isDirtPlant(Material mat) { return mat.equals(Material.SUGAR_CANE_BLOCK) || mat.equals(Material.MELON_BLOCK) || mat.equals(Material.PUMPKIN); } public static boolean isGrassPlant(Material mat) { return mat.equals(Material.SUGAR_CANE_BLOCK) || mat.equals(Material.MELON_BLOCK) || mat.equals(Material.PUMPKIN); } public static boolean isSandPlant(Material mat) { return mat.equals(Material.CACTUS) || mat.equals(Material.SUGAR_CANE_BLOCK); } public static boolean isSoulSandPlant(Material mat) { return mat.equals(Material.NETHER_WARTS); } public static boolean isPlant(Block plant) { return isPlant(plant.getType()); } public static boolean isPlant(Material mat) { return isSoilPlant(mat) || isDirtPlant(mat) || isGrassPlant(mat) || isSandPlant(mat) || isSoulSandPlant(mat); } public static boolean isReinforceablePlant(Material mat) { // If this list changes, update wouldPlantDoubleReinforce to account // for the new soil types. return mat.equals(Material.MELON_BLOCK) || mat.equals(Material.PUMPKIN); } public static int maxPlantHeight(Block plant) { switch(plant.getType()) { case CACTUS: case SUGAR_CANE_BLOCK: return 3; default: return 1; } } public static Block findSoilBelow(Block plant, Set<Material> desiredTypes) { Block down = plant; int max_depth = maxPlantHeight(plant); for (int i = 0; i < max_depth; ++i) { down = down.getRelative(BlockFace.DOWN); if (desiredTypes.contains(down.getType())) { return down; } } return null; } public static boolean isRail(Block block) { return isRail(block.getType()); } public static boolean isRail(Material mat) { return mat.equals(Material.RAILS) || mat.equals(Material.POWERED_RAIL) || mat.equals(Material.ACTIVATOR_RAIL) || mat.equals(Material.DETECTOR_RAIL); } public static boolean wouldPlantDoubleReinforce(final Block block) { final Material blockMat = block.getType(); if (isReinforceablePlant(blockMat) && AccessDelegate.getDelegate(block).getReinforcement() != null) { return true; } final Block above = block.getRelative(BlockFace.UP); final Material aboveMat = above.getType(); if (isReinforceablePlant(aboveMat)) { final Set<Material> soilTypes = getPlantSoilTypes(aboveMat); if (soilTypes.contains(blockMat) && Citadel.getReinforcementManager().getReinforcement(above) != null) { return true; } } return false; } // Given either a UUID or name, return the corresponding player's // account ID or null. public static UUID toAccountId(UUID id) { // See if it is a player UUID try { if (Citadel.getAccountIdManager().getPlayerName(id) != null) { return id; } } catch (Exception ex) {} return null; } public static UUID toAccountId(String name){ UUID uuid = NameAPI.getUUID(name); if (uuid == null) return null; return uuid; } }
package com.xruby.runtime.value; import java.io.File; import java.util.ArrayList; import java.util.List; import com.xruby.runtime.lang.RubyBasic; import com.xruby.runtime.lang.RubyBlock; import com.xruby.runtime.lang.RubyRuntime; import com.xruby.runtime.lang.RubyValue; public class RubyDir extends RubyBasic{ private File dir_; private boolean isOpen = true; private int curPos; private List<String> list = new ArrayList<String>(); public RubyDir(String path){ super(RubyRuntime.DirClass); dir_ = new File(path); list.add("."); list.add(".."); String[] contents = dir_.list(); if(contents != null){ for(int i=0;i<contents.length;i++){ list.add(contents[i]); } } curPos = 0; } public boolean isDirectory(){ return dir_.isDirectory(); } public void close(){ isOpen = false; } public boolean isOpen(){ return isOpen; } public String read(){ if(curPos >= list.size()) return null; String tmp = list.get(curPos); curPos++; return tmp; } public void setPos(int pos){ curPos = pos; } public int getPos(){ return curPos; } public RubyValue each(RubyValue receiver,RubyBlock block){ for (String item : list) { RubyValue v = block.invoke(receiver, new RubyArray(ObjectFactory.createString(item))); if (block.breakedOrReturned()) { return v; } } return this; } }
package org.nick.wwwjdic; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.acra.ACRA; import org.acra.ACRAConfiguration; import org.acra.ReportingInteractionMode; import org.acra.annotation.ReportsCrashes; import org.acra.sender.HttpPostSender; import org.nick.wwwjdic.model.Radicals; import org.nick.wwwjdic.updates.UpdateCheckService; import org.nick.wwwjdic.utils.FileUtils; import android.app.Application; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager.NameNotFoundException; import android.content.res.AssetManager; import android.location.Location; import android.location.LocationManager; import android.os.Environment; import android.preference.PreferenceManager; import android.util.Log; import com.flurry.android.FlurryAgent; @ReportsCrashes(formKey = "dEJzcGZKazRWVGRkRTR0X2JKN0ozWFE6MQ", mode = ReportingInteractionMode.TOAST) public class WwwjdicApplication extends Application { private static final String TAG = WwwjdicApplication.class.getSimpleName(); private static WwwjdicApplication instance; private static final String WWWJDIC_DIR = "wwwjdic"; private static final String OLD_JAPAN_MIRROR = "http: private static final String NEW_JAPAN_MIRROR = "http://wwwjdic.mygengo.com/cgi-data/wwwjdic"; private ExecutorService executorService; private LocationManager locationManager; private static String version; private static String flurryKey; // EDICT by default private String currentDictionary = "1"; private String currentDictionaryName = "General"; public static WwwjdicApplication getInstance() { return instance; } @Override public void onCreate() { instance = this; version = getVersionName(); flurryKey = readKey(); FlurryAgent.setCaptureUncaughtExceptions(false); ACRAConfiguration.setResToastText(R.string.crash_toast_text); ACRA.init(this); String bugsenseUrl = getResources().getString(R.string.bugsense_url); ACRA.getErrorReporter().addReportSender( new HttpPostSender(bugsenseUrl, null)); createWwwjdicDirIfNecessary(); updateJapanMirror(); initRadicals(); if (isAutoSelectMirror()) { try { setMirrorBasedOnLocation(); } catch (Exception e) { // workaround: parsing mirror coords fails on Xperia (SO-01B) with // StringIndexOutOfBoundsException Log.w(TAG, "Failed to set mirror based on location, setting default"); setDefaultMirror(); } } updateKanjiRecognizerUrl(); WwwjdicPreferences.setStrokeAnimationDelay(this, WwwjdicPreferences.DEFAULT_STROKE_ANIMATION_DELAY); startCheckUpdateService(); } private void updateJapanMirror() { String mirrorUlr = WwwjdicPreferences.getWwwjdicUrl(this); if (OLD_JAPAN_MIRROR.equals(mirrorUlr)) { WwwjdicPreferences.setWwwjdicUrl(NEW_JAPAN_MIRROR, this); } } private void startCheckUpdateService() { if (!WwwjdicPreferences.isUpdateCheckEnabled(this)) { return; } long now = new Date().getTime(); long lastCheck = WwwjdicPreferences.getLastUpdateCheck(this); long elapsed = now - lastCheck; if (elapsed >= WwwjdicPreferences.UPDATE_CHECK_INTERVAL_SECS * 1000L) { Intent intent = UpdateCheckService.createStartIntent(this, getResources().getString(R.string.versions_url), getResources().getString(R.string.market_name)); startService(intent); } } private void updateKanjiRecognizerUrl() { SharedPreferences prefs = PreferenceManager .getDefaultSharedPreferences(this); String krUrl = prefs.getString(WwwjdicPreferences.PREF_KR_URL_KEY, WwwjdicPreferences.KR_DEFAULT_URL); if (krUrl.contains("kanji.cgi")) { Log.d(TAG, "found old KR URL, will overwrite with " + WwwjdicPreferences.KR_DEFAULT_URL); prefs.edit() .putString(WwwjdicPreferences.PREF_KR_URL_KEY, WwwjdicPreferences.KR_DEFAULT_URL).commit(); } } private boolean isAutoSelectMirror() { SharedPreferences prefs = PreferenceManager .getDefaultSharedPreferences(this); return prefs.getBoolean(WwwjdicPreferences.PREF_AUTO_SELECT_MIRROR_KEY, true); } public synchronized void setMirrorBasedOnLocation() { Log.d(TAG, "auto selecting mirror..."); locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); Location myLocation = null; try { boolean isEnabled = locationManager .isProviderEnabled(LocationManager.NETWORK_PROVIDER); Log.d(TAG, LocationManager.NETWORK_PROVIDER + " enabled: " + isEnabled); if (!isEnabled) { Log.d(TAG, "provider not enabled, giving up"); return; } myLocation = locationManager .getLastKnownLocation(LocationManager.NETWORK_PROVIDER); if (myLocation == null) { Log.w(TAG, "failed to get cached location, giving up"); return; } } catch (Exception e) { Log.w(TAG, "error getting location, giving up", e); return; } Log.d(TAG, "my location: " + myLocation); String[] mirrorCoords = getResources().getStringArray( R.array.wwwjdic_mirror_coords); String[] mirrorNames = getResources().getStringArray( R.array.wwwjdic_mirror_names); String[] mirrorUrls = getResources().getStringArray( R.array.wwwjdic_mirror_urls); List<Float> distanceToMirrors = new ArrayList<Float>( mirrorCoords.length); for (int i = 0; i < mirrorCoords.length; i++) { String[] latlng = mirrorCoords[i].split("/"); double lat = Location.convert(latlng[0]); double lng = Location.convert(latlng[1]); float[] distance = new float[1]; Location.distanceBetween(myLocation.getLatitude(), myLocation.getLongitude(), lat, lng, distance); distanceToMirrors.add(distance[0]); Log.d(TAG, String.format("distance to %s: %f km", mirrorNames[i], distance[0] / 1000)); } float minDistance = Collections.min(distanceToMirrors); int mirrorIdx = distanceToMirrors.indexOf(minDistance); Log.d(TAG, String.format( "found closest mirror: %s (%s) (distance: %f km)", mirrorUrls[mirrorIdx], mirrorNames[mirrorIdx], minDistance / 1000)); SharedPreferences prefs = PreferenceManager .getDefaultSharedPreferences(this); prefs.edit() .putString(WwwjdicPreferences.PREF_WWWJDIC_MIRROR_URL_KEY, mirrorUrls[mirrorIdx]).commit(); } private void setDefaultMirror() { SharedPreferences prefs = PreferenceManager .getDefaultSharedPreferences(this); prefs.edit() .putString(WwwjdicPreferences.PREF_WWWJDIC_MIRROR_URL_KEY, WwwjdicPreferences.DEFAULT_WWWJDIC_URL).commit(); } private void createWwwjdicDirIfNecessary() { File wwwjdicDir = getWwwjdicDir(); if (!wwwjdicDir.exists()) { boolean success = wwwjdicDir.mkdir(); if (success) { Log.d(TAG, "successfully created " + wwwjdicDir.getAbsolutePath()); } else { Log.d(TAG, "failed to create " + wwwjdicDir.getAbsolutePath()); } } } public static File getWwwjdicDir() { return new File(Environment.getExternalStorageDirectory(), WWWJDIC_DIR); } private String getVersionName() { try { PackageInfo pinfo = getPackageManager().getPackageInfo( getPackageName(), 0); return pinfo.versionName; } catch (NameNotFoundException e) { return ""; } } private String readKey() { AssetManager assetManager = getAssets(); InputStream in = null; try { in = assetManager.open("keys"); return FileUtils.readTextFile(in).trim(); } catch (IOException e) { throw new RuntimeException(e); } finally { if (in != null) { try { in.close(); } catch (IOException ignored) { } } } } public WwwjdicApplication() { executorService = Executors.newSingleThreadExecutor(); } public ExecutorService getExecutorService() { return executorService; } public static String getVersion() { return version; } public static String getUserAgentString() { return "Android-WWWJDIC/" + getVersion(); } public static String getFlurryKey() { return flurryKey; } private void initRadicals() { Radicals radicals = Radicals.getInstance(); if (!radicals.isInitialized()) { radicals.addRadicals(1, getIntArray(R.array.one_stroke_radical_numbers), getStrArray(R.array.one_stroke_radicals)); radicals.addRadicals(2, getIntArray(R.array.two_stroke_radical_numbers), getStrArray(R.array.two_stroke_radicals)); radicals.addRadicals(3, getIntArray(R.array.three_stroke_radical_numbers), getStrArray(R.array.three_stroke_radicals)); radicals.addRadicals(4, getIntArray(R.array.four_stroke_radical_numbers), getStrArray(R.array.four_stroke_radicals)); radicals.addRadicals(5, getIntArray(R.array.five_stroke_radical_numbers), getStrArray(R.array.five_stroke_radicals)); radicals.addRadicals(6, getIntArray(R.array.six_stroke_radical_numbers), getStrArray(R.array.six_stroke_radicals)); radicals.addRadicals(7, getIntArray(R.array.seven_stroke_radical_numbers), getStrArray(R.array.seven_stroke_radicals)); radicals.addRadicals(8, getIntArray(R.array.eight_stroke_radical_numbers), getStrArray(R.array.eight_stroke_radicals)); radicals.addRadicals(9, getIntArray(R.array.nine_stroke_radical_numbers), getStrArray(R.array.nine_stroke_radicals)); radicals.addRadicals(10, getIntArray(R.array.ten_stroke_radical_numbers), getStrArray(R.array.ten_stroke_radicals)); radicals.addRadicals(11, getIntArray(R.array.eleven_stroke_radical_numbers), getStrArray(R.array.eleven_stroke_radicals)); radicals.addRadicals(12, getIntArray(R.array.twelve_stroke_radical_numbers), getStrArray(R.array.twelve_stroke_radicals)); radicals.addRadicals(13, getIntArray(R.array.thirteen_stroke_radical_numbers), getStrArray(R.array.thirteen_stroke_radicals)); radicals.addRadicals(14, getIntArray(R.array.fourteen_stroke_radical_numbers), getStrArray(R.array.fourteen_stroke_radicals)); radicals.addRadicals(15, getIntArray(R.array.fivteen_stroke_radical_numbers), getStrArray(R.array.fivteen_stroke_radicals)); radicals.addRadicals(16, getIntArray(R.array.sixteen_stroke_radical_numbers), getStrArray(R.array.sixteen_stroke_radicals)); radicals.addRadicals(17, getIntArray(R.array.seventeen_stroke_radical_numbers), getStrArray(R.array.seventeen_stroke_radicals)); } } private int[] getIntArray(int id) { return getResources().getIntArray(id); } private String[] getStrArray(int id) { return getResources().getStringArray(id); } public synchronized String getCurrentDictionary() { return currentDictionary; } public synchronized void setCurrentDictionary(String currentDictionary) { this.currentDictionary = currentDictionary; } public synchronized String getCurrentDictionaryName() { return currentDictionaryName; } public synchronized void setCurrentDictionaryName( String currentDictionaryName) { this.currentDictionaryName = currentDictionaryName; } }
package squidpony.squidmath; import squidpony.GwtCompatibility; import squidpony.squidai.AimLimit; import squidpony.squidai.Reach; import squidpony.squidgrid.Direction; import squidpony.squidgrid.Radius; import java.util.ArrayList; import java.util.Arrays; public class CoordPacker { public static final int DEPTH = 8; private static final int BITS = DEPTH << 1; public static short[] hilbertX = new short[0x10000], hilbertY = new short[0x10000], hilbertDistances = new short[0x10000], mooreX = new short[0x100], mooreY = new short[0x100], mooreDistances = new short[0x100], hilbert3X = new short[0x200], hilbert3Y = new short[0x200], hilbert3Z = new short[0x200], hilbert3Distances = new short[0x200], ALL_WALL = new short[0], ALL_ON = new short[]{0, -1}; static { Coord c; for (int i = 0; i < 0x10000; i++) { c = CoordPacker.hilbertToCoordNoLUT(i); hilbertX[i] = (short) c.x; hilbertY[i] = (short) c.y; hilbertDistances[c.x + (c.y << 8)] = (short) i; } for (int x = 0; x < 8; x++) { for (int y = 0; y < 8; y++) { for (int z = 0; z < 8; z++) { computeHilbert3D(x, y, z); } } } for (int i = 64; i < 128; i++) { mooreX[i - 64] = hilbertX[i]; mooreY[i - 64] = hilbertY[i]; mooreDistances[mooreX[i - 64] + (mooreY[i - 64] << 4)] = (short)(i - 64); mooreX[i] = hilbertX[i]; mooreY[i] = (short)(hilbertY[i] + 8); mooreDistances[mooreX[i] + (mooreY[i] << 4)] = (short)(i); mooreX[i + 64] = (short)(15 - hilbertX[i]); mooreY[i + 64] = (short)(15 - hilbertY[i]); mooreDistances[mooreX[i + 64] + (mooreY[i + 64] << 4)] = (short)(i + 64); mooreX[i + 128] = (short)(15 - hilbertX[i]); mooreY[i + 128] = (short)(7 - hilbertY[i]); mooreDistances[mooreX[i + 128] + (mooreY[i + 128] << 4)] = (short)(i + 128); } } /** * Compresses a double[][] (typically one generated by {@link squidpony.squidgrid.FOV}) that only stores two * relevant states (one of which should be 0 or less, the other greater than 0), returning a short[] as described in * the {@link CoordPacker} class documentation. This short[] can be passed to CoordPacker.unpack() to restore the * relevant states and their positions as a boolean[][] (with false meaning 0 or less and true being any double * greater than 0). As stated in the class documentation, the compressed result is intended to use as little memory * as possible for most roguelike FOV maps. *<br> * <b>To store more than two states</b>, you should use packMulti(). * * @param map a double[][] that probably was returned by FOV. If you obtained a double[][] from DijkstraMap, it * will not meaningfully compress with this method. * @return a packed short[] that should, in most circumstances, be passed to unpack() when it needs to be used. */ public static short[] pack(double[][] map) { if(map == null || map.length == 0) throw new ArrayIndexOutOfBoundsException("CoordPacker.pack() must be given a non-empty array"); int xSize = map.length, ySize = map[0].length; if(xSize > 256 || ySize > 256) throw new UnsupportedOperationException("Map size is too large to efficiently pack, aborting"); ShortVLA packing = new ShortVLA(64); boolean on = false, anyAdded = false, current; int skip = 0, limit = 0x10000, mapLimit = xSize * ySize; if(ySize <= 128) { limit >>= 1; if (xSize <= 128) { limit >>= 1; if (xSize <= 64) { limit >>= 1; if (ySize <= 64) { limit >>= 1; if (ySize <= 32) { limit >>= 1; if (xSize <= 32) { limit >>= 1; } } } } } } for(int i = 0, ml = 0; i < limit && ml < mapLimit; i++, skip++) { if(hilbertX[i] >= xSize || hilbertY[i] >= ySize) { if(on) { on = false; packing.add((short) skip); skip = 0; anyAdded = true; } continue; } ml++; current = map[hilbertX[i]][hilbertY[i]] > 0.0; if(current != on) { packing.add((short) skip); skip = 0; on = current; anyAdded = true; } } if(on) packing.add((short)skip); else if(!anyAdded) return ALL_WALL; return packing.toArray(); } /** * Compresses a double[][] (typically one generated by {@link squidpony.squidai.DijkstraMap}) that only stores two * relevant states (one of which should be equal to or less than threshold, the other greater than threshold), * returning a short[] as described in the {@link CoordPacker} class documentation. This short[] can be passed to * CoordPacker.unpack() to restore the relevant states and their positions as a boolean[][] (with true meaning * threshold or less and false being any double greater than threshold). As stated in the class documentation, the * compressed result is intended to use as little memory as possible for most roguelike FOV maps, but here is also * useful for compressing physical maps and gradient maps from DijkstraMap. * <br> * <b>To store more than two states</b>, you should use packMulti(). * * @param map a double[][] that probably relates in some way to DijkstraMap. * @param threshold any double greater than this will be off, any equal or less will be on * @return a packed short[] that should, in most circumstances, be passed to unpack() when it needs to be used. */ public static short[] pack(double[][] map, double threshold) { if(map == null || map.length == 0) throw new ArrayIndexOutOfBoundsException("CoordPacker.pack() must be given a non-empty array"); int xSize = map.length, ySize = map[0].length; if(xSize > 256 || ySize > 256) throw new UnsupportedOperationException("Map size is too large to efficiently pack, aborting"); ShortVLA packing = new ShortVLA(64); boolean on = false, anyAdded = false, current; int skip = 0, limit = 0x10000, mapLimit = xSize * ySize; if(ySize <= 128) { limit >>= 1; if (xSize <= 128) { limit >>= 1; if (xSize <= 64) { limit >>= 1; if (ySize <= 64) { limit >>= 1; if (ySize <= 32) { limit >>= 1; if (xSize <= 32) { limit >>= 1; } } } } } } for(int i = 0, ml = 0; i < limit && ml < mapLimit; i++, skip++) { if(hilbertX[i] >= xSize || hilbertY[i] >= ySize) { if(on) { on = false; packing.add((short) skip); skip = 0; anyAdded = true; } continue; } ml++; current = map[hilbertX[i]][hilbertY[i]] <= threshold; if(current != on) { packing.add((short) skip); skip = 0; on = current; anyAdded = true; } } if(on) packing.add((short)skip); else if(!anyAdded) return ALL_WALL; return packing.toArray(); } /** * Compresses a byte[][] (typically one generated by an FOV-like method) that only stores two * relevant states (one of which should be 0 or less, the other greater than 0), returning a short[] as described in * the {@link CoordPacker} class documentation. This short[] can be passed to CoordPacker.unpack() to restore the * relevant states and their positions as a boolean[][] (with false meaning 0 or less and true being any byte * greater than 0). As stated in the class documentation, the compressed result is intended to use as little memory * as possible for most roguelike FOV maps. *<br> * <b>To store more than two states</b>, you should use packMulti(). * * @param map a byte[][] that probably was returned by an FOV-like method. * @return a packed short[] that should, in most circumstances, be passed to unpack() when it needs to be used. */ public static short[] pack(byte[][] map) { if(map == null || map.length == 0) throw new ArrayIndexOutOfBoundsException("CoordPacker.pack() must be given a non-empty array"); int xSize = map.length, ySize = map[0].length; if(xSize > 256 || ySize > 256) throw new UnsupportedOperationException("Map size is too large to efficiently pack, aborting"); ShortVLA packing = new ShortVLA(64); boolean on = false, anyAdded = false, current; int skip = 0, limit = 0x10000, mapLimit = xSize * ySize; if(ySize <= 128) { limit >>= 1; if (xSize <= 128) { limit >>= 1; if (xSize <= 64) { limit >>= 1; if (ySize <= 64) { limit >>= 1; if (ySize <= 32) { limit >>= 1; if (xSize <= 32) { limit >>= 1; } } } } } } for(int i = 0, ml = 0; i < limit && ml < mapLimit; i++, skip++) { if(hilbertX[i] >= xSize || hilbertY[i] >= ySize) { if(on) { on = false; packing.add((short) skip); skip = 0; anyAdded = true; } continue; } ml++; current = map[hilbertX[i]][hilbertY[i]] > 0; if(current != on) { packing.add((short) skip); skip = 0; on = current; anyAdded = true; } } if(on) packing.add((short)skip); else if(!anyAdded) return ALL_WALL; return packing.toArray(); } /** * Compresses a boolean[][], returning a short[] as described in the {@link CoordPacker} class documentation. This * short[] can be passed to CoordPacker.unpack() to restore the relevant states and their positions as a boolean[][] * As stated in the class documentation, the compressed result is intended to use as little memory as possible for * most roguelike FOV maps. * * @param map a boolean[][] that should ideally be mostly false. * @return a packed short[] that should, in most circumstances, be passed to unpack() when it needs to be used. */ public static short[] pack(boolean[][] map) { if(map == null || map.length == 0) throw new ArrayIndexOutOfBoundsException("CoordPacker.pack() must be given a non-empty array"); int xSize = map.length, ySize = map[0].length; if(xSize > 256 || ySize > 256) throw new UnsupportedOperationException("Map size is too large to efficiently pack, aborting"); ShortVLA packing = new ShortVLA(64); boolean on = false, anyAdded = false, current; int skip = 0, limit = 0x10000, mapLimit = xSize * ySize; if(ySize <= 128) { limit >>= 1; if (xSize <= 128) { limit >>= 1; if (xSize <= 64) { limit >>= 1; if (ySize <= 64) { limit >>= 1; if (ySize <= 32) { limit >>= 1; if (xSize <= 32) { limit >>= 1; } } } } } } for(int i = 0, ml = 0; i < limit && ml < mapLimit; i++, skip++) { if(hilbertX[i] >= xSize || hilbertY[i] >= ySize) { if(on) { on = false; packing.add((short) skip); skip = 0; anyAdded = true; } continue; } ml++; current = map[hilbertX[i]][hilbertY[i]]; if(current != on) { packing.add((short) skip); skip = 0; on = current; anyAdded = true; } } if(on) packing.add((short)skip); else if(!anyAdded) return ALL_WALL; return packing.toArray(); } /** * Compresses a char[][] (typically one generated by a map generating method) sp only the cells that equal the yes * parameter will be encoded as "on", returning a short[] as described in * the {@link CoordPacker} class documentation. This short[] can be passed to CoordPacker.unpack() to restore the * positions of chars that equal the parameter yes as a boolean[][] (with false meaning not equal and true equal to * yes). As stated in the class documentation, the compressed result is intended to use as little memory * as possible for most roguelike FOV maps, but this will typically not be used for FOV (more typical uses are for * walls, floors, and so on). This can still be useful for certain kinds of processing that can be done more * efficiently on packed data than on 2D arrays, like unions, intersections, and random elements or subsets. * * @param map a char[][] that may contain some area of cells that you want stored as packed data * @param yes the char to encode as "on" in the result; all others are encoded as "off" * @return a packed short[] that should, in most circumstances, be passed to unpack() when it needs to be used. */ public static short[] pack(char[][] map, char yes) { if(map == null || map.length == 0) throw new ArrayIndexOutOfBoundsException("CoordPacker.pack() must be given a non-empty array"); int xSize = map.length, ySize = map[0].length; if(xSize > 256 || ySize > 256) throw new UnsupportedOperationException("Map size is too large to efficiently pack, aborting"); ShortVLA packing = new ShortVLA(64); boolean on = false, anyAdded = false, current; int skip = 0, limit = 0x10000, mapLimit = xSize * ySize; if(ySize <= 128) { limit >>= 1; if (xSize <= 128) { limit >>= 1; if (xSize <= 64) { limit >>= 1; if (ySize <= 64) { limit >>= 1; if (ySize <= 32) { limit >>= 1; if (xSize <= 32) { limit >>= 1; } } } } } } for(int i = 0, ml = 0; i < limit && ml < mapLimit; i++, skip++) { if(hilbertX[i] >= xSize || hilbertY[i] >= ySize) { if(on) { on = false; packing.add((short) skip); skip = 0; anyAdded = true; } continue; } ml++; current = map[hilbertX[i]][hilbertY[i]] == yes; if(current != on) { packing.add((short) skip); skip = 0; on = current; anyAdded = true; } } if(on) packing.add((short)skip); else if(!anyAdded) return ALL_WALL; return packing.toArray(); } /** * Given a number of total levels to consider separate in a double[][] such as an FOV result, this produces a levels * array that can be passed to packMulti() to ensure that you have the requested number of separate levels in the * multi-packed result. For example, if you pass 6 to this method, it will return a length-6 double array, and if * you pass that as the levels parameter to packMulti(), then that method will return a length-6 array of short * arrays that each encode a region that met a different minimum value in the originally packed double[][]. * The behavior of this method causes any doubles that are closer to 1.0 / totalLevels than they are to 0.0 to be * packed as "on" in at least one of packMulti()'s resultant sub-arrays. This allows Radius.CIRCLE or similar FOV * that produces cells with values that aren't evenly distributed between 0.0 and 1.0 to be used without causing an * explosion in the number of required levels. * <br> * <b>This method should not be used to generate levels for unpacking; it is only intended for packing.</b> Use the * similar method generateLightLevels() to generate a levels array that is suitable for unpacking FOV. * @param totalLevels the number of separate levels to group doubles into * @return a double[] suitable as a levels parameter for packMulti() */ public static double[] generatePackingLevels(int totalLevels) { if (totalLevels > 63 || totalLevels <= 0) throw new UnsupportedOperationException( "Bad totalLevels; should be 0 < totalLevels < 64 but was given " + totalLevels); double[] levels = new double[totalLevels]; for (int i = 0; i < totalLevels; i++) { levels[i] = 1.0 * i / totalLevels + 0.5 / totalLevels; } return levels; } /** * Given a number of total levels to consider separate in a double[][] such as an FOV result, this produces a levels * array that can be passed to unpackMultiDouble() to ensure that the minimum double returned for an "on" cell is * 1.0 / totalLevels, and every progressively tighter level in the short[][] being unpacked will be close to a * multiple of that minimum double value. This only applies to "on" cells; any cells that did not meet a minimum * value when packed will still be 0.0. For example, if you pass 6 to this method, it will return a length-6 double * array, and if you pass that as the levels parameter to unpackMultiDouble(), then that method will return a * double[][] with no more than totalLevels + 1 used values, ranging from 0.0 to 1.0 with evenly spaced values, all * multiples of 1.0 / totalLevels, in between. * <br> * <b>This method should not be used to generate levels for packing; it is only intended for unpacking.</b> Use the * similar method generatePackingLevels() to generate a levels array that is suitable for packing double[][] values. * @param totalLevels the number of separate levels to assign doubles; this MUST match the size of the levels * parameter used to pack a double[][] with packMulti() if this is used to unpack that data * @return a double[] suitable as a levels parameter for unpackMultiDouble() */ public static double[] generateLightLevels(int totalLevels) { if (totalLevels > 63 || totalLevels <= 0) throw new UnsupportedOperationException( "Bad totalLevels; should be 0 < totalLevels < 64 but was given " + totalLevels); double[] levels = new double[totalLevels]; for (int i = 0; i < totalLevels; i++) { levels[i] = (i + 1.0) / totalLevels; } return levels; } /** * Compresses a double[][] (typically one generated by {@link squidpony.squidgrid.FOV}) that stores any number of * states and a double[] storing up to 63 states, ordered from lowest to highest, returning a short[][] as described * in the {@link CoordPacker} class documentation. This short[][] can be passed to CoordPacker.unpackMultiDouble() * to restore the state at a position to the nearest state in levels, rounded down, and return a double[][] that * should preserve the states as closely as intended for most purposes. <b>For compressing FOV, you should generate * levels with CoordPacker.generatePackingLevels()</b> instead of manually creating the array, because some * imprecision is inherent in floating point math and comparisons are often incorrect between FOV with multiple * levels and exact levels generated as simply as possible. generatePackingLevels() adds a small correction to the * levels to compensate for floating-point math issues, which shouldn't affect the correctness of the results for * FOV radii under 100. *<br> * As stated in the class documentation, the compressed result is intended to use as little memory as possible for * most roguelike FOV maps. *<br> * <b>To store only two states</b>, you should use pack(), unless the double[][] divides data into on and off based * on a relationship to some number other than 0.0. To (probably poorly) pack all the walls (and any cells with * values higher than DijkstraMap.WALL) in a DijkstraMap's 2D array of doubles called dijkstraArray, you could call * <code>packMulti(dijkstraArray, new double[]{DijkstraMap.WALL});</code> * Then, you would use only the one sub-element of the returned short[][]. * * @param map a double[][] that probably was returned by FOV. If you obtained a double[][] from DijkstraMap, it * will not meaningfully compress with this method unless you have very specific needs. * @param levels a double[] starting with the lowest value that should be counted as "on" (the outermost cells of * an FOV map that has multiple grades of brightness would be counted by this) and ascending until the * last value; the last value should be highest (commonly 1.0 for FOV), and will be used for any cells * higher than all the other levels values. An example is an array of: 0.25, 0.5, 0.75, 1.0 * @return a packed short[][] that should, in most circumstances, be passed to unpackMultiDouble() or * unpackMultiByte() when it needs to be used. The 2D array will be jagged with an outer length equal * to the length of levels and sub-arrays that go from having longer lengths early on to very compact * lengths by the end of the short[][]. */ public static short[][] packMulti(double[][] map, double[] levels) { if (levels == null || levels.length == 0) throw new UnsupportedOperationException("Must be given at least one level"); if (levels.length > 63) throw new UnsupportedOperationException( "Too many levels to efficiently pack; should be less than 64 but was given " + levels.length); if (map == null || map.length == 0) throw new ArrayIndexOutOfBoundsException("CoordPacker.packMulti() must be given a non-empty array"); int xSize = map.length, ySize = map[0].length; if (xSize > 256 || ySize > 256) throw new UnsupportedOperationException("Map size is too large to efficiently pack, aborting"); int limit = 0x10000, llen = levels.length, mapLimit = xSize * ySize; long on = 0, current = 0; ShortVLA[] packing = new ShortVLA[llen]; int[] skip = new int[llen]; if(ySize <= 128) { limit >>= 1; if (xSize <= 128) { limit >>= 1; if (xSize <= 64) { limit >>= 1; if (ySize <= 64) { limit >>= 1; if (ySize <= 32) { limit >>= 1; if (xSize <= 32) { limit >>= 1; } } } } } } short[][] packed = new short[llen][]; for(int l = 0; l < llen; l++) { packing[l] = new ShortVLA(64); boolean anyAdded = false; for (int i = 0, ml = 0; i < limit && ml < mapLimit; i++, skip[l]++) { if (hilbertX[i] >= xSize || hilbertY[i] >= ySize) { if ((on & (1L << l)) != 0L) { on ^= (1L << l); packing[l].add((short) skip[l]); skip[l] = 0; anyAdded = true; } continue; } ml++; // sets the bit at position l in current to 1 if the following is true, 0 if it is false: // map[hilbertX[i]][hilbertY[i]] > levels[l] // looks more complicated than it is. current ^= ((map[hilbertX[i]][hilbertY[i]] > levels[l] ? -1 : 0) ^ current) & (1 << l); if (((current >> l) & 1L) != ((on >> l) & 1L)) { packing[l].add((short) skip[l]); skip[l] = 0; on = current; // sets the bit at position l in on to the same as the bit at position l in current. on ^= (-((current >> l) & 1L) ^ on) & (1L << l); anyAdded = true; } } if (((on >> l) & 1L) == 1L) { packing[l].add((short) skip[l]); anyAdded = true; } if(!anyAdded) packed[l] = ALL_WALL; else packed[l] = packing[l].toArray(); } return packed; } /** * Compresses a byte[][] (typically one generated by {@link squidpony.squidgrid.FOVCache}) that stores any number * of states and an int no more than 63, returning a short[][] as described in the {@link CoordPacker} class * documentation. This short[][] can be passed to CoordPacker.unpackMultiByte() to restore the state at a position * to the nearest state possible, capped at levelCount, and return a byte[][] that should preserve the states as * closely as intended for most purposes. *<br> * As stated in the class documentation, the compressed result is intended to use as little memory as possible for * most roguelike FOV maps. *<br> * <b>To store only two states</b>, you should use pack(). * * @param map a byte[][] that probably was returned by a specialized FOV. * @param levelCount an int expressing how many levels should be present in the output; values greater than * levelCount in map will be treated as the highest level. * @return a packed short[][] that should, in most circumstances, be passed to unpackMultiDouble() or * unpackMultiByte() when it needs to be used. The 2D array will be jagged with an outer length equal * to the length of levels and sub-arrays that go from having longer lengths early on to very compact * lengths by the end of the short[][]. */ public static short[][] packMulti(byte[][] map, int levelCount) { if (map == null || map.length == 0) throw new ArrayIndexOutOfBoundsException("CoordPacker.packMulti() must be given a non-empty array"); if (levelCount > 63) throw new UnsupportedOperationException( "Too many levels to efficiently pack; should be less than 64 but was given " + levelCount); int xSize = map.length, ySize = map[0].length; if (xSize > 256 || ySize > 256) throw new UnsupportedOperationException("Map size is too large to efficiently pack, aborting"); int limit = 0x10000, mapLimit = xSize * ySize; long on = 0, current = 0; ShortVLA[] packing = new ShortVLA[levelCount]; int[] skip = new int[levelCount]; if(ySize <= 128) { limit >>= 1; if (xSize <= 128) { limit >>= 1; if (xSize <= 64) { limit >>= 1; if (ySize <= 64) { limit >>= 1; if (ySize <= 32) { limit >>= 1; if (xSize <= 32) { limit >>= 1; } } } } } } short[][] packed = new short[levelCount][]; short x, y; for(int l = 0; l < levelCount; l++) { packing[l] = new ShortVLA(64); boolean anyAdded = false; for (int i = 0, ml = 0; i < limit && ml < mapLimit; i++, skip[l]++) { x = hilbertX[i]; y = hilbertY[i]; if (x >= xSize || y >= ySize) { if ((on & (1L << l)) != 0L) { on ^= (1L << l); packing[l].add((short) skip[l]); skip[l] = 0; anyAdded = true; } continue; } ml++; // sets the bit at position l in current to 1 if the following is true, 0 if it is false: // map[x][y] > l // looks more complicated than it is. current ^= ((map[x][y] > l ? -1L : 0L) ^ current) & (1L << l); if (((current >> l) & 1L) != ((on >> l) & 1L)) { packing[l].add((short) skip[l]); skip[l] = 0; on = current; // sets the bit at position l in on to the same as the bit at position l in current. on ^= (-((current >> l) & 1L) ^ on) & (1L << l); anyAdded = true; } } if (((on >> l) & 1L) == 1L) { packing[l].add((short) skip[l]); anyAdded = true; } if(!anyAdded) packed[l] = ALL_WALL; else packed[l] = packing[l].toArray(); } return packed; } /** * Decompresses a short[] returned by pack() or a sub-array of a short[][] returned by packMulti(), as described in * the {@link CoordPacker} class documentation. This returns a boolean[][] that stores the same values that were * packed if the overload of pack() taking a boolean[][] was used. If a double[][] was compressed with pack(), the * boolean[][] this returns will have true for all values greater than 0 and false for all others. If this is one * of the sub-arrays compressed by packMulti(), the index of the sub-array will correspond to an index in the levels * array passed to packMulti(), and any cells that were at least equal to the corresponding value in levels will be * true, while all others will be false. Width and height do not technically need to match the dimensions of the * original 2D array, but under most circumstances where they don't match, the data produced will be junk. * @param packed a short[] encoded by calling one of this class' packing methods on a 2D array. * @param width the width of the 2D array that will be returned; should match the unpacked array's width. * @param height the height of the 2D array that will be returned; should match the unpacked array's height. * @return a boolean[][] storing which cells encoded by packed are on (true) or off (false). */ public static boolean[][] unpack(short[] packed, int width, int height) { if(packed == null) throw new ArrayIndexOutOfBoundsException("CoordPacker.unpack() must be given a non-null array"); boolean[][] unpacked = new boolean[width][height]; if(packed.length == 0) return unpacked; boolean on = false; int idx = 0; short x =0, y = 0; for(int p = 0; p < packed.length; p++, on = !on) { if (on) { for (int toSkip = idx +(packed[p] & 0xffff); idx < toSkip && idx < 0x10000; idx++) { x = hilbertX[idx]; y = hilbertY[idx]; if(x >= width || y >= height) continue; unpacked[x][y] = true; } } else { idx += packed[p] & 0xffff; } } return unpacked; } /** * Decompresses a short[] returned by pack() or a sub-array of a short[][] returned by packMulti(), as described in * the {@link CoordPacker} class documentation. This returns a double[][] that stores 1.0 for true and 0.0 for * false if the overload of pack() taking a boolean[][] was used. If a double[][] was compressed with pack(), the * double[][] this returns will have 1.0 for all values greater than 0 and 0.0 for all others. If this is one * of the sub-arrays compressed by packMulti(), the index of the sub-array will correspond to an index in the levels * array passed to packMulti(), and any cells that were at least equal to the corresponding value in levels will be * 1.0, while all others will be 0.0. Width and height do not technically need to match the dimensions of the * original 2D array, but under most circumstances where they don't match, the data produced will be junk. * @param packed a short[] encoded by calling one of this class' packing methods on a 2D array. * @param width the width of the 2D array that will be returned; should match the unpacked array's width. * @param height the height of the 2D array that will be returned; should match the unpacked array's height. * @return a double[][] storing which cells encoded by packed are on (1.0) or off (0.0). */ public static double[][] unpackDouble(short[] packed, int width, int height) { if(packed == null) throw new ArrayIndexOutOfBoundsException("CoordPacker.unpack() must be given a non-null array"); double[][] unpacked = new double[width][height]; if(packed.length == 0) return unpacked; boolean on = false; int idx = 0; short x =0, y = 0; for(int p = 0; p < packed.length; p++, on = !on) { if (on) { for (int toSkip = idx +(packed[p] & 0xffff); idx < toSkip && idx < 0x10000; idx++) { x = hilbertX[idx]; y = hilbertY[idx]; if(x >= width || y >= height) continue; unpacked[x][y] = 1.0; } } else { idx += packed[p] & 0xffff; } } return unpacked; } /** * Decompresses a short[] returned by pack() or a sub-array of a short[][] returned by packMulti(), as described in * the {@link CoordPacker} class documentation. This returns a double[][] that stores 1.0 for true and 0.0 for * false if the overload of pack() taking a boolean[][] was used. If a double[][] was compressed with pack(), the * double[][] this returns will have 1.0 for all values greater than 0 and 0.0 for all others. If this is one * of the sub-arrays compressed by packMulti(), the index of the sub-array will correspond to an index in the levels * array passed to packMulti(), and any cells that were at least equal to the corresponding value in levels will be * 1.0, while all others will be 0.0. Width and height do not technically need to match the dimensions of the * original 2D array, but under most circumstances where they don't match, the data produced will be junk. * @param packed a short[] encoded by calling one of this class' packing methods on a 2D array. * @param width the width of the 2D array that will be returned; should match the unpacked array's width. * @param height the height of the 2D array that will be returned; should match the unpacked array's height. * @return a double[][] storing which cells encoded by packed are on (1.0) or off (0.0). */ public static double[][] unpackDoubleConical(short[] packed, int width, int height, int centerX, int centerY, double angle, double span) { if(packed == null) throw new ArrayIndexOutOfBoundsException("CoordPacker.unpack() must be given a non-null array"); double[][] unpacked = new double[width][height]; if(packed.length == 0) return unpacked; boolean on = false; int idx = 0; short x =0, y = 0; double angle2 = Math.toRadians((angle > 360.0 || angle < 0.0) ? GwtCompatibility.IEEEremainder(angle + 720.0, 360.0) : angle); double span2 = Math.toRadians(span); for(int p = 0; p < packed.length; p++, on = !on) { if (on) { for (int toSkip = idx +(packed[p] & 0xffff); idx < toSkip && idx < 0x10000; idx++) { x = hilbertX[idx]; y = hilbertY[idx]; if(x >= width || y >= height) continue; double newAngle = Math.atan2(y - centerY, x - centerX) + Math.PI * 2; if(Math.abs(GwtCompatibility.IEEEremainder(angle2 - newAngle, Math.PI * 2)) > span2 / 2.0) unpacked[x][y] = 0.0; else unpacked[x][y] = 1.0; } } else { idx += packed[p] & 0xffff; } } return unpacked; } /** * Decompresses a short[][] returned by packMulti() and produces an approximation of the double[][] it compressed * using the given levels double[] as the values to assign, as described in the {@link CoordPacker} class * documentation. The length of levels and the length of the outer array of packed must be equal. However, the * levels array passed to this method should not be identical to the levels array passed to packMulti(); for FOV * compression, you should get an array for levels using generatePackingLevels(), but for decompression, you should * create levels using generateLightLevels(), which should more appropriately fit the desired output. Reusing the * levels array used to pack the FOV will usually produce values at the edge of FOV that are less than 0.01 but * greater than 0, and will have a maximum value somewhat less than 1.0; neither are usually desirable, but using a * different array made with generateLightLevels() will produce doubles ranging from 1.0 / levels.length to 1.0 at * the highest. Width and height do not technically need to match the dimensions of the original 2D array, but under * most circumstances where they don't match, the data produced will be junk. * @param packed a short[][] encoded by calling this class' packMulti() method on a 2D array. * @param width the width of the 2D array that will be returned; should match the unpacked array's width. * @param height the height of the 2D array that will be returned; should match the unpacked array's height. * @param levels a double[] that must have the same length as packed, and will be used to assign cells in the * returned double[][] based on what levels parameter was used to compress packed * @return a double[][] where the values that corresponded to the nth value in the levels parameter used to * compress packed will now correspond to the nth value in the levels parameter passed to this method. */ public static double[][] unpackMultiDouble(short[][] packed, int width, int height, double[] levels) { if(packed == null || packed.length == 0) throw new ArrayIndexOutOfBoundsException( "CoordPacker.unpackMultiDouble() must be given a non-empty array"); if (levels == null || levels.length != packed.length) throw new UnsupportedOperationException("The lengths of packed and levels must be equal"); if (levels.length > 63) throw new UnsupportedOperationException( "Too many levels to be packed by CoordPacker; should be less than 64 but was given " + levels.length); double[][] unpacked = new double[width][height]; short x= 0, y = 0; for(int l = 0; l < packed.length; l++) { boolean on = false; int idx = 0; for (int p = 0; p < packed[l].length; p++, on = !on) { if (on) { for (int toSkip = idx + (packed[l][p] & 0xffff); idx < toSkip && idx < 0x10000; idx++) { x = hilbertX[idx]; y = hilbertY[idx]; if(x >= width || y >= height) continue; unpacked[x][y] = levels[l]; } } else { idx += packed[l][p] & 0xffff; } } } return unpacked; } /** * Decompresses a short[][] returned by packMulti() and produces an approximation of the double[][] it compressed * using the given levels double[] as the values to assign, but only using the innermost indices up to limit, as * described in the {@link CoordPacker} class documentation. The length of levels and the length of the outer array * of packed do not have to be equal. However, the levels array passed to this method should not be identical to the * levels array passed to packMulti(); for FOV compression, you should get an array for levels using * generatePackingLevels(), but for decompression, you should create levels using generateLightLevels(), which * should more appropriately fit the desired output. Reusing the levels array used to pack the FOV will usually * produce values at the edge of FOV that are less than 0.01 but greater than 0, and will have a maximum value * somewhat less than 1.0; neither are usually desirable, but using a different array made with * generateLightLevels() will produce doubles ranging from 1.0 / levels.length to 1.0 at the highest. Width and * height do not technically need to match the dimensions of the original 2D array, but under most circumstances * where they don't match, the data produced will be junk. * @param packed a short[][] encoded by calling this class' packMulti() method on a 2D array. * @param width the width of the 2D array that will be returned; should match the unpacked array's width. * @param height the height of the 2D array that will be returned; should match the unpacked array's height. * @param levels a double[] that must have the same length as packed, and will be used to assign cells in the * returned double[][] based on what levels parameter was used to compress packed * @param limit the number of elements to consider from levels and packed, starting from the innermost. * @return a double[][] where the values that corresponded to the nth value in the levels parameter used to * compress packed will now correspond to the nth value in the levels parameter passed to this method. */ public static double[][] unpackMultiDoublePartial(short[][] packed, int width, int height, double[] levels, int limit) { if(packed == null || packed.length == 0) throw new ArrayIndexOutOfBoundsException( "CoordPacker.unpackMultiDouble() must be given a non-empty array"); if (levels == null || levels.length != packed.length) throw new UnsupportedOperationException("The lengths of packed and levels must be equal"); if (levels.length > 63) throw new UnsupportedOperationException( "Too many levels to be packed by CoordPacker; should be less than 64 but was given " + levels.length); if(limit > levels.length) limit = levels.length; double[][] unpacked = new double[width][height]; short x= 0, y = 0; for(int l = packed.length - limit; l < packed.length; l++) { boolean on = false; int idx = 0; for (int p = 0; p < packed[l].length; p++, on = !on) { if (on) { for (int toSkip = idx + (packed[l][p] & 0xffff); idx < toSkip && idx < 0x10000; idx++) { x = hilbertX[idx]; y = hilbertY[idx]; if(x >= width || y >= height) continue; unpacked[x][y] = levels[l]; } } else { idx += packed[l][p] & 0xffff; } } } return unpacked; } /** * Decompresses a short[][] returned by packMulti() and produces an approximation of the double[][] it compressed * using the given levels double[] as the values to assign, but only using the innermost indices up to limit, as * described in the {@link CoordPacker} class documentation. The length of levels and the length of the outer array * of packed do not have to be equal. However, the levels array passed to this method should not be identical to the * levels array passed to packMulti(); for FOV compression, you should get an array for levels using * generatePackingLevels(), but for decompression, you should create levels using generateLightLevels(), which * should more appropriately fit the desired output. Reusing the levels array used to pack the FOV will usually * produce values at the edge of FOV that are less than 0.01 but greater than 0, and will have a maximum value * somewhat less than 1.0; neither are usually desirable, but using a different array made with * generateLightLevels() will produce doubles ranging from 1.0 / levels.length to 1.0 at the highest. This method * takes an angle and span as well as a centerX and centerY; the only values that will be greater than 0.0 in the * result will be within the round-based conical section that could be produced by traveling from (centerX,centerY) * along angle in a limitless line and expanding the cone to be span degrees broad (circularly), centered on angle. * Width and height do not technically need to match the dimensions of the original 2D array, but under most * circumstances where they don't match, the data produced will be junk. * @param packed a short[][] encoded by calling this class' packMulti() method on a 2D array. * @param width the width of the 2D array that will be returned; should match the unpacked array's width. * @param height the height of the 2D array that will be returned; should match the unpacked array's height. * @param levels a double[] that must have the same length as packed, and will be used to assign cells in the * returned double[][] based on what levels parameter was used to compress packed * @param limit the number of elements to consider from levels and packed, starting from the innermost. * @param centerX the x position of the corner or origin of the conical FOV * @param centerY the y position of the corner or origin of the conical FOV * @param angle the center of the conical area to limit this to, in degrees * @param span the total span of the conical area to limit this to, in degrees * @return a double[][] where the values that corresponded to the nth value in the levels parameter used to * compress packed will now correspond to the nth value in the levels parameter passed to this method. */ public static double[][] unpackMultiDoublePartialConical(short[][] packed, int width, int height, double[] levels, int limit, int centerX, int centerY, double angle, double span) { if(packed == null || packed.length == 0) throw new ArrayIndexOutOfBoundsException( "CoordPacker.unpackMultiDouble() must be given a non-empty array"); if (levels == null || levels.length != packed.length) throw new UnsupportedOperationException("The lengths of packed and levels must be equal"); if (levels.length > 63) throw new UnsupportedOperationException( "Too many levels to be packed by CoordPacker; should be less than 64 but was given " + levels.length); if(limit > levels.length) limit = levels.length; double angle2 = Math.toRadians((angle > 360.0 || angle < 0.0) ? GwtCompatibility.IEEEremainder(angle + 720.0, 360.0) : angle); double span2 = Math.toRadians(span); double[][] unpacked = new double[width][height]; short x= 0, y = 0; for(int l = packed.length - limit; l < packed.length; l++) { boolean on = false; int idx = 0; for (int p = 0; p < packed[l].length; p++, on = !on) { if (on) { for (int toSkip = idx + (packed[l][p] & 0xffff); idx < toSkip && idx < 0x10000; idx++) { x = hilbertX[idx]; y = hilbertY[idx]; if(x >= width || y >= height) continue; double newAngle = Math.atan2(y - centerY, x - centerX) + Math.PI * 2; if(Math.abs(GwtCompatibility.IEEEremainder(angle2 - newAngle, Math.PI * 2)) > span2 / 2.0) unpacked[x][y] = 0.0; else unpacked[x][y] = levels[l]; } } else { idx += packed[l][p] & 0xffff; } } } return unpacked; } /** * Decompresses a short[][] returned by packMulti() and produces a simple 2D array where the values are bytes * corresponding to 1 + the highest index into levels (that is, the original levels parameter passed to packMulti) * matched by a cell, or 0 if the cell didn't match any levels during compression, as described in the * {@link CoordPacker} class documentation. Width and height do not technically need to match the dimensions of * the original 2D array, but under most circumstances where they don't match, the data produced will be junk. * @param packed a short[][] encoded by calling this class' packMulti() method on a 2D array. * @param width the width of the 2D array that will be returned; should match the unpacked array's width. * @param height the height of the 2D array that will be returned; should match the unpacked array's height. * @return a byte[][] where the values that corresponded to the nth value in the levels parameter used to * compress packed will now correspond to bytes with the value n+1, or 0 if they were "off" in the original array. */ public static byte[][] unpackMultiByte(short[][] packed, int width, int height) { if(packed == null || packed.length == 0) throw new ArrayIndexOutOfBoundsException( "CoordPacker.unpackMultiByte() must be given a non-empty array"); byte[][] unpacked = new byte[width][height]; byte lPlus = 1; short x=0, y=0; for(int l = 0; l < packed.length; l++, lPlus++) { boolean on = false; int idx = 0; for (int p = 0; p < packed[l].length; p++, on = !on) { if (on) { for (int toSkip = idx + (packed[l][p] & 0xffff); idx < toSkip && idx <= 0xffff; idx++) { x = hilbertX[idx]; y = hilbertY[idx]; if(x >= width || y >= height) continue; unpacked[x][y] = lPlus; } } else { idx += packed[l][p] & 0xffff; } } } return unpacked; } /** * Quickly determines if an x,y position is true or false in the given packed array, without unpacking it. * @param packed a short[] returned by pack() or one of the sub-arrays in what is returned by packMulti(); must * not be null (this method does not check due to very tight performance constraints). * @param x between 0 and 255, inclusive * @param y between 0 and 255, inclusive * @return true if the packed data stores true at the given x,y location, or false in any other case. */ public static boolean queryPacked(short[] packed, int x, int y) { int hilbertDistance = posToHilbert(x, y), total = 0; boolean on = false; for(int p = 0; p < packed.length; p++, on = !on) { total += packed[p] & 0xffff; if(hilbertDistance < total) return on; } return false; } /** * Quickly determines if a Hilbert Curve index corresponds to true or false in the given packed array, without * unpacking it. * <br> * Typically this method will not be needed by library-consuming code unless that code deals with Hilbert Curves in * a frequent and deeply involved manner. It does have the potential to avoid converting to and from x,y coordinates * and Hilbert Curve indices unnecessarily, which could matter for high-performance code. * @param packed a short[] returned by pack() or one of the sub-arrays in what is returned by packMulti(); must * not be null (this method does not check due to very tight performance constraints). * @param hilbert a Hilbert Curve index, such as one taken directly from a packed short[] without extra processing * @return true if the packed data stores true at the given Hilbert Curve index, or false in any other case. */ public static boolean queryPackedHilbert(short[] packed, short hilbert) { int hilbertDistance = hilbert & 0xffff, total = 0; boolean on = false; for(int p = 0; p < packed.length; p++, on = !on) { total += packed[p] & 0xffff; if(hilbertDistance < total) return on; } return false; } /** * Quickly determines if an x,y position is true or false in one of the given packed arrays, without unpacking them, * and returns a List of all packed arrays that contain the position. * @param x between 0 and 255, inclusive * @param y between 0 and 255, inclusive * @param packed an array or vararg of short[], such as those returned by pack() or one of the sub-arrays in what is * returned by packMulti(); none of the arrays can be null. * @return an ArrayList of all packed arrays that store true at the given x,y location. */ public static ArrayList<short[]> findManyPacked(int x, int y, short[] ... packed) { ArrayList<short[]> packs = new ArrayList<short[]>(packed.length); int hilbertDistance = posToHilbert(x, y); for (int a = 0; a < packed.length; a++) { int total = 0; boolean on = false; for (int p = 0; p < packed[a].length; p++, on = !on) { total += packed[a][p] & 0xffff; if (hilbertDistance < total) { if(on) packs.add(packed[a]); break; } } } return packs; } /** * Quickly determines if a Hilbert Curve index corresponds to true or false in one of the given packed arrays, * without unpacking them, and returns a List of all packed arrays that contain the position. * <br> * Typically this method will not be needed by library-consuming code unless that code deals with Hilbert Curves in * a frequent and deeply involved manner. It does have the potential to avoid converting to and from x,y coordinates * and Hilbert Curve indices unnecessarily, which could matter for high-performance code. * @param hilbert a Hilbert Curve index, such as one taken directly from a packed short[] without extra processing * @param packed an array or vararg of short[], such as those returned by pack() or one of the sub-arrays in what is * returned by packMulti(); none of the arrays can be null. * @return an ArrayList of all packed arrays that store true at the given x,y location. */ public static ArrayList<short[]> findPackedHilbert(short hilbert, short[] ... packed) { ArrayList<short[]> packs = new ArrayList<short[]>(packed.length); int hilbertDistance = hilbert & 0xffff; for (int a = 0; a < packed.length; a++) { int total = 0; boolean on = false; for (int p = 0; p < packed[a].length; p++, on = !on) { total += packed[a][p] & 0xffff; if (hilbertDistance < total) { if(on) packs.add(packed[a]); break; } } } return packs; } /** * Gets all positions that are "on" in the given packed array, without unpacking it, and returns them as a Coord[]. * @param packed a short[] returned by pack() or one of the sub-arrays in what is returned by packMulti(); must * not be null (this method does not check due to very tight performance constraints). * @return a Coord[], ordered by distance along the Hilbert Curve, corresponding to all "on" cells in packed. */ public static Coord[] allPacked(short[] packed) { ShortVLA vla = new ShortVLA(64); boolean on = false; int idx = 0; for(int p = 0; p < packed.length; p++, on = !on) { if (on) { vla.addRange(idx, idx + (packed[p] & 0xffff)); } idx += packed[p] & 0xffff; } int[] distances = vla.asInts(); Coord[] cs = new Coord[distances.length]; for (int i = 0; i < distances.length; i++) { cs[i] = Coord.get(hilbertX[distances[i]], hilbertY[distances[i]]); } return cs; } /** * Gets all positions that are "on" in the given packed array, without unpacking it, and returns them as an array of * Hilbert Curve indices. * <br> * Typically this method will not be needed by library-consuming code unless that code deals with Hilbert Curves in * a frequent and deeply involved manner. It does have the potential to avoid converting to and from x,y coordinates * and Hilbert Curve indices unnecessarily, which could matter for high-performance code. * @param packed a short[] returned by pack() or one of the sub-arrays in what is returned by packMulti(); must * not be null (this method does not check due to very tight performance constraints). * @return a Hilbert Curve index array, in ascending distance order, corresponding to all "on" cells in packed. */ public static short[] allPackedHilbert(short[] packed) { ShortVLA vla = new ShortVLA(64); boolean on = false; int idx = 0; for(int p = 0; p < packed.length; p++, on = !on) { if (on) { vla.addRange(idx, idx + (packed[p] & 0xffff)); } idx += packed[p] & 0xffff; } return vla.toArray(); } private static int clamp(int n, int min, int max) { return Math.min(Math.max(min, n), max - 1); } /** * Move all "on" positions in packed by the number of cells given in xMove and yMove, unless the move * would take them further than 0, width - 1 (for xMove) or height - 1 (for yMove), in which case that * cell is stopped at the edge (moving any shape by an xMove greater than width or yMove greater than * height will move all "on" cells to that edge, in a 1-cell thick line). Returns a new packed short[] * and does not modify packed. * @param packed a short[] returned by pack() or one of the sub-arrays in what is returned by packMulti() * @param xMove distance to move the x-coordinate; can be positive or negative * @param yMove distance to move the y-coordinate; can be positive or negative * @param width the maximum width; if a cell would move to x at least equal to width, it stops at width - 1 * @param height the maximum height; if a cell would move to y at least equal to height, it stops at height - 1 * @return a packed array that encodes "on" for cells that were moved from cells that were "on" in packed */ public static short[] translate(short[] packed, int xMove, int yMove, int width, int height) { if(packed == null || packed.length <= 1) { return ALL_WALL; } ShortVLA vla = new ShortVLA(256); boolean on = false; int idx = 0, x, y; for(int p = 0; p < packed.length; p++, on = !on) { if (on) { for (int i = idx; i < idx + (packed[p] & 0xffff); i++) { x = clamp(hilbertX[i] + xMove, 0, width); y = clamp(hilbertY[i] + yMove, 0, height); vla.add(hilbertDistances[x + (y << 8)]); } } idx += packed[p] & 0xffff; } int[] indices = vla.asInts(); if(indices.length < 1) return ALL_WALL; Arrays.sort(indices); vla = new ShortVLA(128); int current, past = indices[0], skip = 0; vla.add((short)indices[0]); for (int i = 1; i < indices.length; i++) { current = indices[i]; if (current - past > 1) { vla.add((short) (skip+1)); skip = 0; vla.add((short)(current - past - 1)); } else if(current != past) skip++; past = current; } vla.add((short)(skip+1)); return vla.toArray(); } /** * Expand each "on" position in packed to cover a a square with side length equal to 1 + expansion * 2, * centered on the original "on" position, unless the expansion would take a cell further than 0, * width - 1 (for xMove) or height - 1 (for yMove), in which case that cell is stopped at the edge. * Uses 8-way movement (Chebyshev distance) unless the overload of this function that takes a boolean argument * eightWay is used and that argument is false. * Returns a new packed short[] and does not modify packed. * @param packed a short[] returned by pack() or one of the sub-arrays in what is returned by packMulti() * @param expansion the positive (square) radius, in cells, to expand each cell out by * @param width the maximum width; if a cell would move to x at least equal to width, it stops at width - 1 * @param height the maximum height; if a cell would move to y at least equal to height, it stops at height - 1 * @return a packed array that encodes "on" for packed and cells that expanded from cells that were "on" in packed */ public static short[] expand(short[] packed, int expansion, int width, int height) { if(packed == null || packed.length <= 1) { return ALL_WALL; } ShortVLA vla = new ShortVLA(256); ShortSet ss = new ShortSet(256); boolean on = false; int idx = 0, x, y; short dist; for(int p = 0; p < packed.length; p++, on = !on) { if (on) { for (int i = idx; i < idx + (packed[p] & 0xffff); i++) { x = hilbertX[i]; y = hilbertY[i]; for (int j = Math.max(0, x - expansion); j <= Math.min(width - 1, x + expansion); j++) { for (int k = Math.max(0, y - expansion); k <= Math.min(height - 1, y + expansion); k++) { dist = hilbertDistances[j + (k << 8)]; if (ss.add(dist)) vla.add(dist); } } } } idx += packed[p] & 0xffff; } int[] indices = vla.asInts(); if(indices.length < 1) return ALL_WALL; Arrays.sort(indices); vla = new ShortVLA(128); int current, past = indices[0], skip = 0; vla.add((short)indices[0]); for (int i = 1; i < indices.length; i++) { current = indices[i]; if (current - past > 1) { vla.add((short) (skip+1)); skip = 0; vla.add((short)(current - past - 1)); } else if(current != past) skip++; past = current; } vla.add((short)(skip+1)); return vla.toArray(); } /** * Expand each "on" position in packed to cover a a square with side length equal to 1 + expansion * 2, * centered on the original "on" position, unless the expansion would take a cell further than 0, * width - 1 (for xMove) or height - 1 (for yMove), in which case that cell is stopped at the edge. * Returns a new packed short[] and does not modify packed. * @param packed a short[] returned by pack() or one of the sub-arrays in what is returned by packMulti() * @param expansion the positive (square) radius, in cells, to expand each cell out by * @param width the maximum width; if a cell would move to x at least equal to width, it stops at width - 1 * @param height the maximum height; if a cell would move to y at least equal to height, it stops at height - 1 * @param eightWay true if the expansion should be both diagonal and orthogonal; false for just orthogonal * @return a packed array that encodes "on" for packed and cells that expanded from cells that were "on" in packed */ public static short[] expand(short[] packed, int expansion, int width, int height, boolean eightWay) { if(eightWay) return expand(packed, expansion, width, height); if(packed == null || packed.length <= 1) { return ALL_WALL; } ShortVLA vla = new ShortVLA(256); ShortSet ss = new ShortSet(256); boolean on = false; int idx = 0, x, y, j, k; short dist; int[] xOffsets = new int[]{0, 1, 0, -1, 0}, yOffsets = new int[]{1, 0, -1, 0, 1}; for(int p = 0; p < packed.length; p++, on = !on) { if (on) { for (int i = idx; i < idx + (packed[p] & 0xffff); i++) { x = hilbertX[i]; y = hilbertY[i]; for (int d = 0; d < 4; d++) { for (int e = 1; e <= expansion; e++) { for (int e2 = 0; e2 < expansion; e2++) { j = Math.min(width - 1, Math.max(0, x + xOffsets[d] * e + yOffsets[d + 1] * e2)); k = Math.min(height - 1, Math.max(0, y + yOffsets[d] * e + xOffsets[d + 1] * e2)); dist = hilbertDistances[j + (k << 8)]; if (ss.add(dist)) vla.add(dist); } } } } } idx += packed[p] & 0xffff; } int[] indices = vla.asInts(); if(indices.length < 1) return ALL_WALL; Arrays.sort(indices); vla = new ShortVLA(128); int current, past = indices[0], skip = 0; vla.add((short)indices[0]); for (int i = 1; i < indices.length; i++) { current = indices[i]; if (current - past > 1) { vla.add((short) (skip+1)); skip = 0; vla.add((short)(current - past - 1)); } else if(current != past) skip++; past = current; } vla.add((short)(skip+1)); return vla.toArray(); } /** * Finds the area made by removing the "on" positions in packed that are within the specified retraction distance of * an "off" position or the edge of the map. This essentially finds a shrunken version of packed. * Uses 8-way movement (Chebyshev distance) unless the overload of this function that takes a boolean argument * eightWay is used and that argument is false. * Returns a new packed short[] and does not modify packed. * @param packed a short[] returned by pack() or one of the sub-arrays in what is returned by packMulti() * @param retraction the positive (square) radius, in cells, to pull each cell in by * @param width the maximum width; if a cell would move to x at least equal to width, it stops at width - 1 * @param height the maximum height; if a cell would move to y at least equal to height, it stops at height - 1 * @return a short[] that encodes "on" for cells that were "on" in packed and were far enough from an "off" cell */ public static short[] retract(short[] packed, int retraction, int width, int height) { if(packed == null || packed.length <= 1) { return ALL_WALL; } ShortVLA vla = new ShortVLA(256); boolean on = false; int idx = 0, x, y; for(int p = 0; p < packed.length; p++, on = !on) { if (on) { INDICES: for (int i = idx; i < idx + (packed[p] & 0xffff); i++) { x = hilbertX[i]; y = hilbertY[i]; for (int j = x - retraction; j <= x + retraction; j++) { for (int k = y - retraction; k <= y + retraction; k++) { if(j < 0 || k < 0 || j >= width || k >= height || !queryPackedHilbert(packed, hilbertDistances[j + (k << 8)])) continue INDICES; } } vla.add((short)i); } } idx += packed[p] & 0xffff; } int[] indices = vla.asInts(); if(indices.length < 1) return ALL_WALL; Arrays.sort(indices); vla = new ShortVLA(128); int current, past = indices[0], skip = 0; vla.add((short)indices[0]); for (int i = 1; i < indices.length; i++) { current = indices[i]; if (current - past > 1) { vla.add((short) (skip+1)); skip = 0; vla.add((short)(current - past - 1)); } else if(current != past) skip++; past = current; } vla.add((short)(skip+1)); return vla.toArray(); } /** * Finds the area made by removing the "on" positions in packed that are within the specified retraction distance of * an "off" position or the edge of the map. This essentially finds a shrunken version of packed. * Returns a new packed short[] and does not modify packed. * @param packed a short[] returned by pack() or one of the sub-arrays in what is returned by packMulti() * @param retraction the positive (square) radius, in cells, to pull each cell in by * @param width the maximum width; cells outside this are considered "off" for this method's purposes * @param height the maximum height; cells outside this are considered "off" for this method's purposes * @param eightWay true if the retraction should be both diagonal and orthogonal; false for just orthogonal * @return a packed array that encodes "on" for packed and cells that expanded from cells that were "on" in packed */ public static short[] retract(short[] packed, int retraction, int width, int height, boolean eightWay) { if(eightWay) return retract(packed, retraction, width, height); if(packed == null || packed.length <= 1) { return ALL_WALL; } ShortVLA vla = new ShortVLA(256); boolean on = false; int idx = 0, x, y, j, k; int[] xOffsets = new int[]{0, 1, 0, -1, 0}, yOffsets = new int[]{1, 0, -1, 0, 1}; for(int p = 0; p < packed.length; p++, on = !on) { if (on) { INDICES: for (int i = idx; i < idx + (packed[p] & 0xffff); i++) { x = hilbertX[i]; y = hilbertY[i]; for (int d = 0; d < 4; d++) { for (int e = 1; e <= retraction; e++) { for (int e2 = 0; e2 < retraction; e2++) { j = x + xOffsets[d] * e + yOffsets[d + 1] * e2; k = y + yOffsets[d] * e + xOffsets[d + 1] * e2; if (j < 0 || k < 0 || j >= width || k >= height || !queryPackedHilbert(packed, hilbertDistances[j + (k << 8)])) continue INDICES; } } } vla.add((short)i); } } idx += packed[p] & 0xffff; } int[] indices = vla.asInts(); if(indices.length < 1) return ALL_WALL; Arrays.sort(indices); vla = new ShortVLA(128); int current, past = indices[0], skip = 0; vla.add((short)indices[0]); for (int i = 1; i < indices.length; i++) { current = indices[i]; if (current - past > 1) { vla.add((short) (skip+1)); skip = 0; vla.add((short)(current - past - 1)); } else if(current != past) skip++; past = current; } vla.add((short)(skip+1)); return vla.toArray(); } /** * Finds the area around the cells encoded in packed, without including those cells. For each "on" * position in packed, expand it to cover a a square with side length equal to 1 + expansion * 2, * centered on the original "on" position, unless the expansion would take a cell further than 0, * width - 1 (for xMove) or height - 1 (for yMove), in which case that cell is stopped at the edge. * If a cell is "on" in packed, it will always be "off" in the result. * Uses 8-way movement (Chebyshev distance) unless the overload of this function that takes a boolean argument * eightWay is used and that argument is false. * Returns a new packed short[] and does not modify packed. * @param packed a short[] returned by pack() or one of the sub-arrays in what is returned by packMulti() * @param expansion the positive (square-shaped) radius, in cells, to expand each cell out by * @param width the maximum width; if a cell would move to x at least equal to width, it stops at width - 1 * @param height the maximum height; if a cell would move to y at least equal to height, it stops at height - 1 * @return a packed array that encodes "on" for cells that were pushed from the edge of packed's "on" cells */ public static short[] fringe(short[] packed, int expansion, int width, int height) { if(packed == null || packed.length <= 1) { return ALL_WALL; } ShortVLA vla = new ShortVLA(256); ShortSet ss = new ShortSet(256); boolean on = false; int idx = 0; short x, y, dist; for(int p = 0; p < packed.length; p++, on = !on) { if (on) { for (int i = idx; i < idx + (packed[p] & 0xffff); i++) { ss.add((short) i); } } idx += packed[p] & 0xffff; } on = false; idx = 0; for(int p = 0; p < packed.length; p++, on = !on) { if (on) { for (int i = idx; i < idx + (packed[p] & 0xffff); i++) { x = hilbertX[i]; y = hilbertY[i]; for (int j = Math.max(0, x - expansion); j <= Math.min(width - 1, x + expansion); j++) { for (int k = Math.max(0, y - expansion); k <= Math.min(height - 1, y + expansion); k++) { dist = hilbertDistances[j + (k << 8)]; if (ss.add(dist)) vla.add(dist); } } } } idx += packed[p] & 0xffff; } int[] indices = vla.asInts(); if(indices.length < 1) return ALL_WALL; Arrays.sort(indices); vla = new ShortVLA(128); int current, past = indices[0], skip = 0; vla.add((short)indices[0]); for (int i = 1; i < indices.length; i++) { current = indices[i]; if (current - past > 1) { vla.add((short) (skip+1)); skip = 0; vla.add((short)(current - past - 1)); } else if(current != past) skip++; past = current; } vla.add((short)(skip+1)); return vla.toArray(); } /** * Finds the area around the cells encoded in packed, without including those cells. For each "on" * position in packed, expand it to cover a a square with side length equal to 1 + expansion * 2, * centered on the original "on" position, unless the expansion would take a cell further than 0, * width - 1 (for xMove) or height - 1 (for yMove), in which case that cell is stopped at the edge. * If a cell is "on" in packed, it will always be "off" in the result. * Returns a new packed short[] and does not modify packed. * @param packed a short[] returned by pack() or one of the sub-arrays in what is returned by packMulti() * @param expansion the positive (square-shaped) radius, in cells, to expand each cell out by * @param width the maximum width; if a cell would move to x at least equal to width, it stops at width - 1 * @param height the maximum height; if a cell would move to y at least equal to height, it stops at height - 1 * @param eightWay true if the expansion should be both diagonal and orthogonal; false for just orthogonal * @return a packed array that encodes "on" for cells that were pushed from the edge of packed's "on" cells */ public static short[] fringe(short[] packed, int expansion, int width, int height, boolean eightWay) { if(eightWay) return fringe(packed, expansion, width, height); if(packed == null || packed.length <= 1) { return ALL_WALL; } ShortVLA vla = new ShortVLA(256); ShortSet ss = new ShortSet(256); boolean on = false; int idx = 0; short x, y, dist; int[] xOffsets = new int[]{0, 1, 0, -1, 0}, yOffsets = new int[]{1, 0, -1, 0, 1}; for(int p = 0; p < packed.length; p++, on = !on) { if (on) { for (int i = idx; i < idx + (packed[p] & 0xffff); i++) { ss.add((short) i); } } idx += packed[p] & 0xffff; } on = false; idx = 0; for(int p = 0; p < packed.length; p++, on = !on) { if (on) { for (int i = idx; i < idx + (packed[p] & 0xffff); i++) { x = hilbertX[i]; y = hilbertY[i]; for (int d = 0; d < 4; d++) { for (int e = 1; e <= expansion; e++) { for (int e2 = 0; e2 < expansion; e2++) { int j = Math.min(width - 1, Math.max(0, x + xOffsets[d] * e + yOffsets[d + 1] * e2)); int k = Math.min(height - 1, Math.max(0, y + yOffsets[d] * e + xOffsets[d + 1] * e2)); dist = hilbertDistances[j + (k << 8)]; if (ss.add(dist)) vla.add(dist); } } } } } idx += packed[p] & 0xffff; } int[] indices = vla.asInts(); if(indices.length < 1) return ALL_WALL; Arrays.sort(indices); vla = new ShortVLA(128); int current, past = indices[0], skip = 0; vla.add((short)indices[0]); for (int i = 1; i < indices.length; i++) { current = indices[i]; if (current - past > 1) { vla.add((short) (skip+1)); skip = 0; vla.add((short)(current - past - 1)); } else if(current != past) skip++; past = current; } vla.add((short)(skip+1)); return vla.toArray(); } /** * Finds the concentric areas around the cells encoded in packed, without including those cells. For each "on" * position in packed, expand it to cover a a square with side length equal to 1 + n * 2, where n starts at 1 and * goes up to include the expansions parameter, with each expansion centered on the original "on" position, unless * the expansion would take a cell further than 0, width - 1 (for xMove) or height - 1 (for yMove), in which case * that cell is stopped at the edge. If a cell is "on" in packed, it will always be "off" in the results. * Returns a new packed short[][] where the outer array has length equal to expansions and the inner arrays are * packed data encoding a one-cell-wide concentric fringe region. Does not modify packed. * @param packed a short[] returned by pack() or one of the sub-arrays in what is returned by packMulti() * @param expansions the positive (square-shaped) radius, in cells, to expand each cell out by, also the length * of the outer array returned by this method * @param width the maximum width; if a cell would move to x at least equal to width, it stops at width - 1 * @param height the maximum height; if a cell would move to y at least equal to height, it stops at height - 1 * @return an array of packed arrays that encode "on" for cells that were pushed from the edge of packed's "on" * cells; the outer array will have length equal to expansions, and inner arrays will normal packed data */ public static short[][] fringes(short[] packed, int expansions, int width, int height) { short[][] finished = new short[expansions][]; if (packed == null || packed.length <= 1) { Arrays.fill(finished, ALL_WALL); return finished; } ShortSet ss = new ShortSet(256); boolean on = false; int idx = 0; short x, y, dist; for (int p = 0; p < packed.length; p++, on = !on) { if (on) { for (int i = idx; i < idx + (packed[p] & 0xffff); i++) { ss.add((short) i); } } idx += packed[p] & 0xffff; } for (int expansion = 1; expansion <= expansions; expansion++) { ShortVLA vla = new ShortVLA(256); on = false; idx = 0; for (int p = 0; p < packed.length; p++, on = !on) { if (on) { for (int i = idx; i < idx + (packed[p] & 0xffff); i++) { x = hilbertX[i]; y = hilbertY[i]; for (int j = Math.max(0, x - expansion); j <= Math.min(width - 1, x + expansion); j++) { for (int k = Math.max(0, y - expansion); k <= Math.min(height - 1, y + expansion); k++) { dist = hilbertDistances[j + (k << 8)]; if (ss.add(dist)) vla.add(dist); } } } } idx += packed[p] & 0xffff; } int[] indices = vla.asInts(); if(indices.length < 1) { finished[expansion - 1] = ALL_WALL; continue; } Arrays.sort(indices); vla = new ShortVLA(128); int current, past = indices[0], skip = 0; vla.add((short) indices[0]); for (int i = 1; i < indices.length; i++) { current = indices[i]; if (current != past) skip++; if (current - past > 1) { vla.add((short) (skip + 1)); skip = 0; vla.add((short) (current - past - 1)); } past = current; } vla.add((short) (skip + 1)); finished[expansion-1] = vla.toArray(); } return finished; } /** * Finds the concentric areas around the cells encoded in packed, without including those cells. For each "on" * position in packed, expand it to cover a a square with side length equal to 1 + n * 2, where n starts at 1 and * goes up to include the expansions parameter, with each expansion centered on the original "on" position, unless * the expansion would take a cell further than 0, width - 1 (for xMove) or height - 1 (for yMove), in which case * that cell is stopped at the edge. If a cell is "on" in packed, it will always be "off" in the results. * Returns a new packed short[][] where the outer array has length equal to expansions and the inner arrays are * packed data encoding a one-cell-wide concentric fringe region. Does not modify packed. * @param packed a short[] returned by pack() or one of the sub-arrays in what is returned by packMulti() * @param expansions the positive (square-shaped) radius, in cells, to expand each cell out by, also the length * of the outer array returned by this method * @param width the maximum width; if a cell would move to x at least equal to width, it stops at width - 1 * @param height the maximum height; if a cell would move to y at least equal to height, it stops at height - 1 * @param eightWay true if the expansion should be both diagonal and orthogonal; false for just orthogonal * @return an array of packed arrays that encode "on" for cells that were pushed from the edge of packed's "on" * cells; the outer array will have length equal to expansions, and inner arrays will normal packed data */ public static short[][] fringes(short[] packed, int expansions, int width, int height, boolean eightWay) { short[][] finished = new short[expansions][]; if (packed == null || packed.length <= 1) { Arrays.fill(finished, ALL_WALL); return finished; } ShortSet ss = new ShortSet(256); boolean on = false; int idx = 0; short x, y, dist; int[] xOffsets = new int[]{0, 1, 0, -1, 0}, yOffsets = new int[]{1, 0, -1, 0, 1}; for (int p = 0; p < packed.length; p++, on = !on) { if (on) { for (int i = idx; i < idx + (packed[p] & 0xffff); i++) { ss.add((short) i); } } idx += packed[p] & 0xffff; } for (int expansion = 1; expansion <= expansions; expansion++) { ShortVLA vla = new ShortVLA(256); on = false; idx = 0; for (int p = 0; p < packed.length; p++, on = !on) { if (on) { for (int i = idx; i < idx + (packed[p] & 0xffff); i++) { x = hilbertX[i]; y = hilbertY[i]; for (int d = 0; d < 4; d++) { for (int e = 1; e <= expansion; e++) { for (int e2 = 0; e2 < expansion; e2++) { int j = Math.min(width - 1, Math.max(0, x + xOffsets[d] * e + yOffsets[d + 1] * e2)); int k = Math.min(height - 1, Math.max(0, y + yOffsets[d] * e + xOffsets[d + 1] * e2)); dist = hilbertDistances[j + (k << 8)]; if (ss.add(dist)) vla.add(dist); } } } } } idx += packed[p] & 0xffff; } int[] indices = vla.asInts(); if(indices.length < 1) { finished[expansion - 1] = ALL_WALL; continue; } Arrays.sort(indices); vla = new ShortVLA(128); int current, past = indices[0], skip = 0; vla.add((short) indices[0]); for (int i = 1; i < indices.length; i++) { current = indices[i]; if (current != past) skip++; if (current - past > 1) { vla.add((short) (skip + 1)); skip = 0; vla.add((short) (current - past - 1)); } past = current; } vla.add((short) (skip + 1)); finished[expansion-1] = vla.toArray(); } return finished; } /** * Finds the area consisting of the "on" positions in packed that are within the specified depth distance of an * "off" position or the edge of the map. This essentially finds the part of packed that is close to its edge. * Uses 8-way movement (Chebyshev distance) unless the overload of this function that takes a boolean argument * eightWay is used and that argument is false. * Returns a new packed short[] and does not modify packed. * @param packed a short[] returned by pack() or one of the sub-arrays in what is returned by packMulti() * @param depth the positive (square) radius, in cells, to go inward from an "off" cell into the "in" cells * @param width the maximum width; if a cell would move to x at least equal to width, it stops at width - 1 * @param height the maximum height; if a cell would move to y at least equal to height, it stops at height - 1 * @return a short[] that encodes "on" for cells that were "on" in packed and were close enough to an "off" cell */ public static short[] surface(short[] packed, int depth, int width, int height) { if(packed == null || packed.length <= 1) { return ALL_WALL; } ShortVLA vla = new ShortVLA(256); boolean on = false; int idx = 0, x, y; for(int p = 0; p < packed.length; p++, on = !on) { if (on) { INDICES: for (int i = idx; i < idx + (packed[p] & 0xffff); i++) { x = hilbertX[i]; y = hilbertY[i]; for (int j = Math.max(0, x - depth); j <= Math.min(width - 1, x + depth); j++) { for (int k = Math.max(0, y - depth); k <= Math.min(height - 1, y + depth); k++) { if(!queryPackedHilbert(packed, hilbertDistances[j + (k << 8)])) { vla.add((short)i); continue INDICES; } } } } } idx += packed[p] & 0xffff; } int[] indices = vla.asInts(); if(indices.length < 1) return ALL_WALL; Arrays.sort(indices); vla = new ShortVLA(128); int current, past = indices[0], skip = 0; vla.add((short)indices[0]); for (int i = 1; i < indices.length; i++) { current = indices[i]; if (current - past > 1) { vla.add((short) (skip+1)); skip = 0; vla.add((short)(current - past - 1)); } else if(current != past) skip++; past = current; } vla.add((short)(skip+1)); return vla.toArray(); } /** * Finds the area consisting of the "on" positions in packed that are within the specified depth distance of an * "off" position or the edge of the map. This essentially finds the part of packed that is close to its edge. * Returns a new packed short[] and does not modify packed. * @param packed a short[] returned by pack() or one of the sub-arrays in what is returned by packMulti() * @param depth the positive (square) radius, in cells, to go inward from an "off" cell into the "in" cells * @param width the maximum width; if a cell would move to x at least equal to width, it stops at width - 1 * @param height the maximum height; if a cell would move to y at least equal to height, it stops at height - 1 * @param eightWay true if the retraction should be both diagonal and orthogonal; false for just orthogonal * @return a short[] that encodes "on" for cells that were "on" in packed and were close enough to an "off" cell */ public static short[] surface(short[] packed, int depth, int width, int height, boolean eightWay) { if(eightWay) return surface(packed, depth, width, height); if(packed == null || packed.length <= 1) { return ALL_WALL; } ShortVLA vla = new ShortVLA(256); boolean on = false; int idx = 0, x, y, j, k; int[] xOffsets = new int[]{0, 1, 0, -1, 0}, yOffsets = new int[]{1, 0, -1, 0, 1}; for(int p = 0; p < packed.length; p++, on = !on) { if (on) { INDICES: for (int i = idx; i < idx + (packed[p] & 0xffff); i++) { x = hilbertX[i]; y = hilbertY[i]; for (int d = 0; d < 4; d++) { for (int e = 1; e <= depth; e++) { for (int e2 = 0; e2 < depth; e2++) { j = x + xOffsets[d] * e + yOffsets[d + 1] * e2; k = y + yOffsets[d] * e + xOffsets[d + 1] * e2; if (j < 0 || k < 0 || j >= width || k >= height || !queryPackedHilbert(packed, hilbertDistances[j + (k << 8)])) { vla.add((short)i); continue INDICES; } } } } } } idx += packed[p] & 0xffff; } int[] indices = vla.asInts(); if(indices.length < 1) return ALL_WALL; Arrays.sort(indices); vla = new ShortVLA(128); int current, past = indices[0], skip = 0; vla.add((short)indices[0]); for (int i = 1; i < indices.length; i++) { current = indices[i]; if (current - past > 1) { vla.add((short) (skip+1)); skip = 0; vla.add((short)(current - past - 1)); } else if(current != past) skip++; past = current; } vla.add((short)(skip+1)); return vla.toArray(); } /** * Given a packed array encoding a larger area, a packed array encoding one or more points inside bounds, and an * amount of expansion, expands each cell in start by a Manhattan (diamond) radius equal to expansion, limiting any * expansion to within bounds and returning the final expanded (limited) packed data. Notably, if a small area is * not present within bounds, then the flood will move around the "hole" similarly to DijkstraMap's behavior; * essentially, it needs to expand around the hole to get to the other side, and this takes more steps of expansion * than crossing straight over. * Returns a new packed short[] and does not modify bounds or start. * @param bounds packed data representing the maximum extent of the region to flood-fill; often floors * @param start a packed array that encodes position(s) that the flood will spread outward from * @param expansion the positive (square) radius, in cells, to expand each cell out by * @return a packed array that encodes "on" for cells that are "on" in bounds and are within expansion Manhattan * distance from a Coord in start */ public static short[] flood(short[] bounds, short[] start, int expansion) { if(bounds == null || bounds.length <= 1) { return ALL_WALL; } int boundSize = count(bounds); ShortVLA vla = new ShortVLA(256); ShortSet ss = new ShortSet(boundSize), quickBounds = new ShortSet(boundSize); boolean on = false; int idx = 0; short x, y, dist; for(int p = 0; p < bounds.length; p++, on = !on) { if (on) { for (int i = idx; i < idx + (bounds[p] & 0xffff); i++) { quickBounds.add((short) i); } } idx += bounds[p] & 0xffff; } short[] s2 = allPackedHilbert(start); int[] xOffsets = new int[]{0, 1, 0, -1}, yOffsets = new int[]{1, 0, -1, 0}; for (int e = 0; e < expansion; e++) { ShortVLA edge = new ShortVLA(128); for (int s = 0; s < s2.length; s++) { int i = s2[s] & 0xffff; x = hilbertX[i]; y = hilbertY[i]; for (int d = 0; d < 4; d++) { int j = Math.min(255, Math.max(0, x + xOffsets[d])); int k = Math.min(255, Math.max(0, y + yOffsets[d])); dist = hilbertDistances[j + (k << 8)]; if (quickBounds.contains(dist)) { if (ss.add(dist)) { vla.add(dist); edge.add(dist); } } } } s2 = edge.toArray(); } int[] indices = vla.asInts(); if(indices.length < 1) return ALL_WALL; Arrays.sort(indices); vla = new ShortVLA(128); int current, past = indices[0], skip = 0; vla.add((short)indices[0]); for (int i = 1; i < indices.length; i++) { current = indices[i]; if (current - past > 1) { vla.add((short) (skip+1)); skip = 0; vla.add((short)(current - past - 1)); } else if(current != past) skip++; past = current; } vla.add((short)(skip+1)); return vla.toArray(); } /** * Given a packed array encoding a larger area, a packed array encoding one or more points inside bounds, and an * amount of expansion, expands each cell in start by a radius (if eightWay is true, it uses Chebyshev distance; if * it is false, it uses Manhattan distance) equal to expansion, limiting any expansion to within bounds and * returning the final expanded (limited) packed data. Notably, if a small area is not present within bounds, then * the flood will move around the "hole" similarly to DijkstraMap's behavior; essentially, it needs to expand around * the hole to get to the other side, and this takes more steps of expansion than crossing straight over. * Returns a new packed short[] and does not modify bounds or start. * @param bounds packed data representing the maximum extent of the region to flood-fill; often floors * @param start a packed array that encodes position(s) that the flood will spread outward from * @param expansion the positive (square) radius, in cells, to expand each cell out by * @param eightWay true to flood-fill out in all eight directions at each step, false for just orthogonal * @return a packed array that encodes "on" for cells that are "on" in bounds and are within expansion either * Chebyshev (if eightWay is true) or Manhattan (otherwise) distance from a Coord in start */ public static short[] flood(short[] bounds, short[] start, int expansion, boolean eightWay) { if(!eightWay) return flood(bounds, start, expansion); if(bounds == null || bounds.length <= 1) { return ALL_WALL; } int boundSize = count(bounds); ShortVLA vla = new ShortVLA(256); ShortSet ss = new ShortSet(boundSize), quickBounds = new ShortSet(boundSize); boolean on = false; int idx = 0; short x, y, dist; for(int p = 0; p < bounds.length; p++, on = !on) { if (on) { for (int i = idx; i < idx + (bounds[p] & 0xffff); i++) { quickBounds.add((short) i); } } idx += bounds[p] & 0xffff; } short[] s2 = allPackedHilbert(start); int[] xOffsets = new int[]{-1, 0, 1, -1, 1, -1, 0, 1}, yOffsets = new int[]{-1, -1, -1, 0, 0, 1, 1, 1}; for (int e = 0; e < expansion; e++) { ShortVLA edge = new ShortVLA(128); for (int s = 0; s < s2.length; s++) { int i = s2[s] & 0xffff; x = hilbertX[i]; y = hilbertY[i]; for (int d = 0; d < 8; d++) { int j = Math.min(255, Math.max(0, x + xOffsets[d])); int k = Math.min(255, Math.max(0, y + yOffsets[d])); dist = hilbertDistances[j + (k << 8)]; if (quickBounds.contains(dist)) { if (ss.add(dist)) { vla.add(dist); edge.add(dist); } } } } s2 = edge.toArray(); } int[] indices = vla.asInts(); if(indices.length < 1) return ALL_WALL; Arrays.sort(indices); vla = new ShortVLA(128); int current, past = indices[0], skip = 0; vla.add((short)indices[0]); for (int i = 1; i < indices.length; i++) { current = indices[i]; if (current - past > 1) { vla.add((short) (skip+1)); skip = 0; vla.add((short)(current - past - 1)); } else if(current != past) skip++; past = current; } vla.add((short)(skip+1)); return vla.toArray(); } private static void modifiedShadowFOV(int expansion, int viewerX, int viewerY, Radius metric, ShortSet bounds, ShortSet storedSet, ShortVLA vla) { if(expansion < 1) return; short start = hilbertDistances[viewerX + (viewerY << 8)]; if(storedSet.add(start)) vla.add(start); for (Direction d : Direction.DIAGONALS) { modifiedShadowCast(expansion, 1, 1.0, 0.0, 0, d.deltaX, d.deltaY, 0, viewerX, viewerY, metric, bounds, storedSet, vla); modifiedShadowCast(expansion, 1, 1.0, 0.0, d.deltaX, 0, 0, d.deltaY, viewerX, viewerY, metric, bounds, storedSet, vla); } } private static void modifiedShadowCast(int expansion, int row, double start, double end, int xx, int xy, int yx, int yy, int viewerX, int viewerY, Radius metric, ShortSet bounds, ShortSet storedSet, ShortVLA vla) { double newStart = 0; if (start < end) { return; } boolean blocked = false; int dist; short currentPos; for (int distance = row; distance <= expansion && !blocked; distance++) { int deltaY = -distance; for (int deltaX = -distance; deltaX <= 0; deltaX++) { int currentX = viewerX + deltaX * xx + deltaY * xy; int currentY = viewerY + deltaX * yx + deltaY * yy; double leftSlope = (deltaX - 0.5f) / (deltaY + 0.5f); double rightSlope = (deltaX + 0.5f) / (deltaY - 0.5f); currentPos = hilbertDistances[currentX + (currentY << 8)]; /* if (!bounds.contains(currentPos)) { newStart = rightSlope; continue; } else */ if(!(currentX - viewerX + expansion >= 0 && currentX - viewerX <= expansion && currentY - viewerY + expansion >= 0 && currentY - viewerY <= expansion) || start < rightSlope) { continue; } else if (end > leftSlope) { break; } if (blocked) { //previous cell was a blocking one if (!bounds.contains(currentPos)) {//hit a wall newStart = rightSlope; } else { blocked = false; start = newStart; dist = metric.roughDistance(currentX - viewerX, currentY - viewerY); //check if it's within the lightable area and light if needed if (dist <= expansion * 2) { if(storedSet.add(currentPos)) vla.add(currentPos); } } } else { if (!bounds.contains(currentPos) && distance < expansion) {//hit a wall within sight line blocked = true; modifiedShadowCast(expansion, distance + 1, start, leftSlope, xx, xy, yx, yy, viewerX, viewerY, metric, bounds, storedSet, vla); newStart = rightSlope; } else { if(bounds.contains(currentPos)) { dist = metric.roughDistance(currentX - viewerX, currentY - viewerY); //check if it's within the lightable area and light if needed if (dist <= expansion * 2) { if (storedSet.add(currentPos)) vla.add(currentPos); } } } } } } } /** * Given a packed array encoding a larger area, a packed array encoding one or more points inside bounds, and an * amount of expansion, expands each cell in start by a Manhattan (diamond) radius equal to expansion, limiting any * expansion to within bounds and returning the final expanded (limited) packed data. * Though this is otherwise similar to flood(), radiate() behaves like FOV and will not move around obstacles and * will instead avoid expanding if it would go into any cell that cannot be reached by a straight line (drawn * directly, not in grid steps) that is mostly unobstructed. * Returns a new packed short[] and does not modify bounds or start. * @param bounds packed data representing the maximum extent of the region to flood-fill; often floors * @param start a packed array that encodes position(s) that the flood will spread outward from * @param expansion the positive (square) radius, in cells, to expand each cell out by * @return a packed array that encodes "on" for cells that are "on" in bounds and are within expansion Manhattan * distance from a Coord in start */ public static short[] radiate(short[] bounds, short[] start, int expansion) { return radiate(bounds, start, expansion, Radius.DIAMOND); } /** * Given a packed array encoding a larger area, a packed array encoding one or more points inside bounds, and an * amount of expansion, expands each cell in start by a radius, with a shape determined by metric, equal to * expansion, limiting any expansion to within bounds and returning the final expanded (limited) packed data. * Though this is otherwise similar to flood(), radiate() behaves like FOV and will not move around obstacles and * will instead avoid expanding if it would go into any cell that cannot be reached by a straight line (drawn * directly, not in grid steps) that is mostly unobstructed. * Returns a new packed short[] and does not modify bounds or start. * @param bounds packed data representing the maximum extent of the region to flood-fill; often floors * @param start a packed array that encodes position(s) that the flood will spread outward from * @param expansion the positive (square) radius, in cells, to expand each cell out by * @param metric a Radius that defines how this should expand, SQUARE for 8-way, DIAMOND for 4-way, CIRCLE for * Euclidean expansion (not guaranteed to be perfectly circular) * @return a packed array that encodes "on" for cells that are "on" in bounds and are within expansion Manhattan * distance from a Coord in start */ public static short[] radiate(short[] bounds, short[] start, int expansion, Radius metric) { if(bounds == null || bounds.length <= 1) { return ALL_WALL; } int boundSize = count(bounds); ShortVLA vla = new ShortVLA(256); ShortSet storedSet = new ShortSet(boundSize), quickBounds = new ShortSet(boundSize); boolean on = false; int idx = 0, i; short x, y; for(int p = 0; p < bounds.length; p++, on = !on) { if (on) { for (i = idx; i < idx + (bounds[p] & 0xffff); i++) { quickBounds.add((short) i); } } idx += bounds[p] & 0xffff; } short[] s2 = allPackedHilbert(start); for (int s = 0; s < s2.length; s++) { i = s2[s] & 0xffff; x = hilbertX[i]; y = hilbertY[i]; modifiedShadowFOV(expansion, x, y, metric, quickBounds, storedSet, vla); } int[] indices = vla.asInts(); if(indices.length < 1) return ALL_WALL; Arrays.sort(indices); vla = new ShortVLA(128); int current, past = indices[0], skip = 0; vla.add((short)indices[0]); for (i = 1; i < indices.length; i++) { current = indices[i]; if (current - past > 1) { vla.add((short) (skip+1)); skip = 0; vla.add((short)(current - past - 1)); } else if(current != past) skip++; past = current; } vla.add((short)(skip+1)); return vla.toArray(); } /** * Given a packed array encoding a larger area, a packed array encoding one or more points inside bounds, and an * amount of expansion, expands each cell in start by a radius, with a square shape if eightWay is true or a diamond * otherwise, equal to expansion, limiting any expansion to within bounds and returning the final expanded (limited) * packed data. Though this is otherwise similar to flood(), radiate() behaves like FOV and will not move around * obstacles and will instead avoid expanding if it would go into any cell that cannot be reached by a straight line * (drawn directly, not in grid steps) that is mostly unobstructed. * Returns a new packed short[] and does not modify bounds or start. * @param bounds packed data representing the maximum extent of the region to flood-fill; often floors * @param start a packed array that encodes position(s) that the flood will spread outward from * @param expansion the positive (square) radius, in cells, to expand each cell out by * @param eightWay true to flood-fill out in all eight directions at each step, false for just orthogonal * @return a packed array that encodes "on" for cells that are "on" in bounds and are within expansion either * Chebyshev (if eightWay is true) or Manhattan (otherwise) distance from a Coord in start */ public static short[] radiate(short[] bounds, short[] start, int expansion, boolean eightWay) { if(eightWay) return radiate(bounds, start, expansion, Radius.SQUARE); return radiate(bounds, start, expansion, Radius.DIAMOND); } /** * Given a packed array encoding a larger area, a packed array encoding one or more points inside bounds, and a * Reach object that determines targeting constraints, gets all cells contained within bounds that can be targeted * from a cell in start using the rules defined by reach. * Though this is otherwise similar to flood(), reachable() behaves like FOV and will not move around obstacles and * will instead avoid expanding if it would go into any cell that cannot be reached by a straight line (drawn * directly, not in grid steps) that is mostly unobstructed. This does not behave quite like FOV if an AimLimit has * been set in reach to any value other than null or AimLimit.FREE; in these cases it requires an exactly straight * orthogonal or diagonal line without obstructions, checking only cells along the precise path. For diagonals and * eight-way targeting, this means it can target through walls that only meet at a perpendicular diagonal, such as * an X shape where one line is a one-cell-thick diagonal wall and the other is the targeting line. This is normally * only allowed in some games and only if they use Chebyshev (Radius.SQUARE) distance, so be advised that it may not * be desirable behavior. * Returns a new packed short[] and does not modify bounds or start. * @param bounds packed data representing the max extent of the region to check for reach-ability; often floors * @param start a packed array that encodes position(s) that the flood will spread outward from * @param reach a {@link Reach} object that determines minimum and maximum range, distance metric, and AimLimit * @return a packed array that encodes "on" for cells that are "on" in bounds and can be targeted from a cell in * start using the given Reach */ public static short[] reachable(short[] bounds, short[] start, Reach reach) { if(bounds == null || bounds.length <= 1) { return ALL_WALL; } int boundSize = count(bounds); ShortVLA vla = new ShortVLA(256), discard = new ShortVLA(128); ShortSet storedSet = new ShortSet(boundSize), quickBounds = new ShortSet(boundSize); boolean on = false; int idx = 0, i; short x, y; for(int p = 0; p < bounds.length; p++, on = !on) { if (on) { for (i = idx; i < idx + (bounds[p] & 0xffff); i++) { quickBounds.add((short) i); } } idx += bounds[p] & 0xffff; } short[] s2 = allPackedHilbert(start); if(reach.limit == null || reach.limit == AimLimit.FREE) { for (int s = 0; s < s2.length; s++) { i = s2[s] & 0xffff; x = hilbertX[i]; y = hilbertY[i]; //add all cells at less than minimum distance to storedSet. modifiedShadowFOV(reach.minDistance - 1, x, y, reach.metric, quickBounds, storedSet, discard); discard.clear(); modifiedShadowFOV(reach.maxDistance, x, y, reach.metric, quickBounds, storedSet, vla); } } else { for (int s = 0; s < s2.length; s++) { i = s2[s] & 0xffff; x = hilbertX[i]; y = hilbertY[i]; Direction[] dirs; switch (reach.limit) { case ORTHOGONAL: dirs = Direction.CARDINALS; break; case DIAGONAL: dirs = Direction.DIAGONALS; break; default: dirs = Direction.OUTWARDS; } Direction dir; DIRECTIONAL: for (int which = 0; which < dirs.length; which++) { dir = dirs[which]; int d; //add all cells at less than minimum distance to storedSet. for (d = 1; d < reach.minDistance; d++) { int extended = (x + dir.deltaX * d) + ((y + dir.deltaY * d) << 8); if (extended < 0 || extended > 0xffff) continue DIRECTIONAL; short next = hilbertDistances[extended]; if (quickBounds.contains(next)) storedSet.add(next); else continue DIRECTIONAL; } for (; d <= reach.maxDistance; d++) { int extended = (x + dir.deltaX * d) + ((y + dir.deltaY * d) << 8); if (extended < 0 || extended > 0xffff) continue DIRECTIONAL; short next = hilbertDistances[extended]; if (quickBounds.contains(next)) { if (storedSet.add(next)) vla.add(next); } else continue DIRECTIONAL; } } } } int[] indices = vla.asInts(); if(indices.length < 1) return ALL_WALL; Arrays.sort(indices); vla = new ShortVLA(128); int current, past = indices[0], skip = 0; vla.add((short)indices[0]); for (i = 1; i < indices.length; i++) { current = indices[i]; if (current - past > 1) { vla.add((short) (skip+1)); skip = 0; vla.add((short)(current - past - 1)); } else if(current != past) skip++; past = current; } vla.add((short)(skip+1)); return vla.toArray(); } /** * Given a width and height, returns a packed array that encodes "on" for the rectangle from (0,0) to * (width - 1, height - 1). Primarily useful with intersectPacked() to ensure things like negatePacked() that can * encode "on" cells in any position are instead limited to the bounds of the map. * @param width the width of the rectangle * @param height the height of the rectangle * @return a packed short[] encoding "on" for all cells with x less than width and y less than height. */ public static short[] rectangle(int width, int height) { if(width > 256 || height > 256) throw new UnsupportedOperationException("Map size is too large to efficiently pack, aborting"); boolean[][] rect = new boolean[width][height]; for (int i = 0; i < width; i++) { Arrays.fill(rect[i], true); } return pack(rect); } /** * Given x, y, width and height, returns a packed array that encodes "on" for the rectangle from (x,y) to * (width - 1, height - 1). Primarily useful with intersectPacked() to ensure things like negatePacked() that can * encode "on" cells in any position are instead limited to the bounds of the map, but also handy for basic "box * drawing" for other uses. * @param x the minimum x coordinate * @param y the minimum y coordinate * @param width the width of the rectangle * @param height the height of the rectangle * @return a packed short[] encoding "on" for all cells with x less than width and y less than height. */ public static short[] rectangle(int x, int y, int width, int height) { int width2 = width, height2 = height; if(x + width >= 256) width2 = 255 - x; if(y + height >= 256) height2 = 255 - y; if(width2 < 0 || height2 < 0 || x < 0 || y < 0) return ALL_WALL; boolean[][] rect = new boolean[x + width2][y + height2]; for (int i = x; i < x + width2; i++) { Arrays.fill(rect[i], y, y + height2, true); } return pack(rect); } /** * Given x, y, width and height, returns an array of all Hilbert distance within the rectangle from (x,y) to * (width - 1, height - 1). * @param x the minimum x coordinate * @param y the minimum y coordinate * @param width the width of the rectangle * @param height the height of the rectangle * @return a short[] that is not packed, and instead stores individual Hilbert distances in the rectangle */ public static short[] rectangleHilbert(int x, int y, int width, int height) { int width2 = width, height2 = height; if(x + width >= 256) width2 = 256 - x; if(y + height >= 256) height2 = 256 - y; if(width2 <= 0 || height2 <= 0 || x < 0 || y < 0) return new short[0]; short[] hilberts = new short[width2 * height2]; int idx = 0; for (int i = x; i < x + width2; i++) { for (int j = y; j < y + height2; j++) { hilberts[idx++] = hilbertDistances[i + (j << 8)]; } } return hilberts; } /** * Counts the number of "on" cells encoded in a packed array without unpacking it. * @param packed a packed short array, as produced by pack() * @return the number of "on" cells. */ public static int count(short[] packed) { return count(packed, true); } /** * Counts the number of cells encoding a boolean equal to wanted in a packed array without unpacking it. * @param packed a packed short array, as produced by pack() * @param wanted the boolean you want to count, true for "on" and false for "off" * @return the number of cells that encode a value equal to wanted. */ public static int count(short[] packed, boolean wanted) { int c = 0; boolean on = false; for (int i = 0; i < packed.length; i++, on = !on) { if(on == wanted) c += packed[i] & 0xffff; } return c; } /** * Finds how many cells are encoded in a packed array (both on and off) without unpacking it. * @param packed a packed short array, as produced by pack() * @return the number of cells that are encoded explicitly in the packed data as either on or off. */ public static int covered(short[] packed) { int c = 0; for (int i = 0; i < packed.length; i++) { c += packed[i] & 0xffff; } return c; } /** * Given two packed short arrays, left and right, this produces a packed short array that encodes "on" for any cell * that was "on" in either left or in right, and only encodes "off" for cells that were off in both. This method * does not do any unpacking (which can be somewhat computationally expensive) and so should be strongly preferred * when merging two pieces of packed data. * @param left A packed array such as one produced by pack() * @param right A packed array such as one produced by pack() * @return A packed array that encodes "on" for all cells that were "on" in either left or right */ public static short[] unionPacked(short[] left, short[] right) { if(left.length == 0) return right; if(right.length == 0) return left; ShortVLA packing = new ShortVLA(64); boolean on = false, onLeft = false, onRight = false; int idx = 0, skip = 0, elemLeft = 0, elemRight = 0, totalLeft = 0, totalRight = 0; while ((elemLeft < left.length || elemRight < right.length) && idx <= 0xffff) { if (elemLeft >= left.length) { totalLeft = 0xffff; onLeft = false; } else if(totalLeft <= idx) { totalLeft += left[elemLeft] & 0xffff; } if(elemRight >= right.length) { totalRight = 0xffff; onRight = false; } else if(totalRight <= idx) { totalRight += right[elemRight] & 0xffff; } // 300, 5, 6, 8, 2, 4 // 290, 12, 9, 1 // 290, 15, 6, 8, 2, 4 // 290 off in both, 10 in right, 2 in both, 3 in left, 6 off in both, 1 on in both, 7 on in left, 2 off in // both, 4 on in left if(totalLeft < totalRight) { onLeft = !onLeft; skip += totalLeft - idx; idx = totalLeft; if(on != (onLeft || onRight)) { packing.add((short) skip); skip = 0; on = !on; } elemLeft++; } else if(totalLeft == totalRight) { onLeft = !onLeft; onRight = !onRight; skip += totalLeft - idx; idx = totalLeft; if(on != (onLeft || onRight)) { packing.add((short) skip); skip = 0; on = !on; } elemLeft++; elemRight++; } else { onRight = !onRight; skip += totalRight - idx; idx = totalRight; if(on != (onLeft || onRight)) { packing.add((short) skip); skip = 0; on = !on; } elemRight++; } } return packing.toArray(); } /** * Given two packed short arrays, left and right, this produces a packed short array that encodes "on" for any cell * that was "on" in both left and in right, and encodes "off" for cells that were off in either array. This method * does not do any unpacking (which can be somewhat computationally expensive) and so should be strongly preferred * when finding the intersection of two pieces of packed data. * @param left A packed array such as one produced by pack() * @param right A packed array such as one produced by pack() * @return A packed array that encodes "on" for all cells that were "on" in both left and right */ public static short[] intersectPacked(short[] left, short[] right) { if(left.length == 0 || right.length == 0) return ALL_WALL; ShortVLA packing = new ShortVLA(64); boolean on = false, onLeft = false, onRight = false; int idx = 0, skip = 0, elemLeft = 0, elemRight = 0, totalLeft = 0, totalRight = 0; while ((elemLeft < left.length && elemRight < right.length) && idx <= 0xffff) { if (elemLeft >= left.length) { totalLeft = 0xffff; onLeft = false; } else if(totalLeft <= idx) { totalLeft += left[elemLeft] & 0xffff; } if(elemRight >= right.length) { totalRight = 0xffff; onRight = false; } else if(totalRight <= idx) { totalRight += right[elemRight] & 0xffff; } // 300, 5, 6, 8, 2, 4 // 290, 12, 9, 1 // 300, 2, 9, 1 // 300 off, 2 on, 9 off, 1 on if(totalLeft < totalRight) { onLeft = !onLeft; skip += totalLeft - idx; idx = totalLeft; if(on != (onLeft && onRight)) { packing.add((short) skip); skip = 0; on = !on; } elemLeft++; } else if(totalLeft == totalRight) { onLeft = !onLeft; onRight = !onRight; skip += totalLeft - idx; idx = totalLeft; if(on != (onLeft && onRight)) { packing.add((short) skip); skip = 0; on = !on; } elemLeft++; elemRight++; } else { onRight = !onRight; skip += totalRight - idx; idx = totalRight; if(on != (onLeft && onRight)) { packing.add((short) skip); skip = 0; on = !on; } elemRight++; } } return packing.toArray(); } /** * Given one packed short array, this produces a packed short array that is the exact opposite of the one passed in, * that is, every "on" cell becomes "off" and every "off" cell becomes "on", including cells that were "off" because * they were beyond the boundaries of the original 2D array passed to pack() or a similar method. This method does * not do any unpacking (which can be somewhat computationally expensive), and actually requires among the lowest * amounts of computation to get a result of any methods in CoordPacker. However, because it will cause cells to be * considered "on" that would cause an exception if directly converted to x,y positions and accessed in the source * 2D array, this method should primarily be used in conjunction with operations such as intersectPacked(), or have * the checking for boundaries handled internally by unpack() or related methods such as unpackMultiDouble(). * @param original A packed array such as one produced by pack() * @return A packed array that encodes "on" all cells that were "off" in original */ public static short[] negatePacked(short[] original) { if (original.length <= 1) { return ALL_ON; } if (original[0] == 0) { short[] copy = new short[original.length - 2]; System.arraycopy(original, 1, copy, 0, original.length - 2); return copy; } short[] copy = new short[original.length + 2]; copy[0] = 0; System.arraycopy(original, 0, copy, 1, original.length); copy[copy.length - 1] = (short) (0xFFFF - covered(copy)); return copy; } /** * Given two packed short arrays, left and right, this produces a packed short array that encodes "on" for any cell * that was "on" in left but "off" in right, and encodes "off" for cells that were "on" in right or "off" in left. * This method does not do any unpacking (which can be somewhat computationally expensive) and so should be strongly * preferred when finding a region of one packed array that is not contained in another packed array. * @param left A packed array such as one produced by pack() * @param right A packed array such as one produced by pack() * @return A packed array that encodes "on" for all cells that were "on" in left and "off" in right */ public static short[] differencePacked(short[] left, short[] right) { if(left.length <= 1) return ALL_WALL; if(right.length <= 1) return left; ShortVLA packing = new ShortVLA(64); boolean on = false, onLeft = false, onRight = false; int idx = 0, skip = 0, elemLeft = 0, elemRight = 0, totalLeft = 0, totalRight = 0; while ((elemLeft < left.length || elemRight < right.length) && idx <= 0xffff) { if (elemLeft >= left.length) { totalLeft = 0xffff; onLeft = false; } else if(totalLeft <= idx) { totalLeft += left[elemLeft] & 0xffff; } if(elemRight >= right.length) { totalRight = 0xffff; onRight = false; } else if(totalRight <= idx) { totalRight += right[elemRight] & 0xffff; } if(totalLeft < totalRight) { onLeft = !onLeft; skip += totalLeft - idx; idx = totalLeft; if(on != (onLeft && !onRight)) { packing.add((short) skip); skip = 0; on = !on; } elemLeft++; } else if(totalLeft == totalRight) { onLeft = !onLeft; onRight = !onRight; skip += totalLeft - idx; idx = totalLeft; if(on != (onLeft && !onRight)) { packing.add((short) skip); skip = 0; on = !on; } elemLeft++; elemRight++; } else { onRight = !onRight; skip += totalRight - idx; idx = totalRight; if(on != (onLeft && !onRight)) { packing.add((short) skip); skip = 0; on = !on; } elemRight++; } } return packing.toArray(); } /** * Given two packed short arrays, left and right, this produces a packed short array that encodes "on" for any cell * that was "on" only in left or only in right, but not a cell that was "off" in both or "on" in both. This method * does not do any unpacking (which can be somewhat computationally expensive) and so should be strongly preferred * when performing an exclusive-or operation on two pieces of packed data. * <br> * Could more-correctly be called exclusiveDisjunctionPacked to match the other terms, but... seriously? * @param left A packed array such as one produced by pack() * @param right A packed array such as one produced by pack() * @return A packed array that encodes "on" for all cells such that left's cell ^ right's cell returns true */ public static short[] xorPacked(short[] left, short[] right) { if(left.length == 0) return right; if(right.length == 0) return left; ShortVLA packing = new ShortVLA(64); boolean on = false, onLeft = false, onRight = false; int idx = 0, skip = 0, elemLeft = 0, elemRight = 0, totalLeft = 0, totalRight = 0; while ((elemLeft < left.length || elemRight < right.length) && idx <= 0xffff) { if (elemLeft >= left.length) { totalLeft = 0xffff; onLeft = false; } else if(totalLeft <= idx) { totalLeft += left[elemLeft] & 0xffff; } if(elemRight >= right.length) { totalRight = 0xffff; onRight = false; } else if(totalRight <= idx) { totalRight += right[elemRight] & 0xffff; } // 300, 5, 6, 8, 2, 4 // 290, 12, 9, 1 // 290, 15, 6, 8, 2, 4 // 290 off in both, 10 in right, 2 in both, 3 in left, 6 off in both, 1 on in both, 7 on in left, 2 off in // both, 4 on in left if(totalLeft < totalRight) { onLeft = !onLeft; skip += totalLeft - idx; idx = totalLeft; if(on != (onLeft ^ onRight)) { packing.add((short) skip); skip = 0; on = !on; } elemLeft++; } else if(totalLeft == totalRight) { onLeft = !onLeft; onRight = !onRight; skip += totalLeft - idx; idx = totalLeft; if(on != (onLeft ^ onRight)) { packing.add((short) skip); skip = 0; on = !on; } elemLeft++; elemRight++; } else { onRight = !onRight; skip += totalRight - idx; idx = totalRight; if(on != (onLeft ^ onRight)) { packing.add((short) skip); skip = 0; on = !on; } elemRight++; } } return packing.toArray(); } /** * Returns a new packed short[] containing the Hilbert distance hilbert as "on", and all other cells "off". * Much more efficient than packSeveral called with only one argument. * @param hilbert a Hilbert distance that will be encoded as "on" * @return the point given to this encoded as "on" in a packed short array */ public static short[] packOne(int hilbert) { return new short[]{(short) hilbert, 1}; } /** * Returns a new packed short[] containing the Coord point as "on", and all other cells "off". * Much more efficient than packSeveral called with only one argument. * @param point a Coord that will be encoded as "on" * @return the point given to this encoded as "on" in a packed short array */ public static short[] packOne(Coord point) { return new short[]{(short) coordToHilbert(point), 1}; } /** * Returns a new packed short[] containing the given x,y cell as "on", and all other cells "off". * Much more efficient than packSeveral called with only one argument. * @param x the x component of the point that will be encoded as "on" * @param y the y component of the point that will be encoded as "on" * @return the point given to this encoded as "on" in a packed short array */ public static short[] packOne(int x, int y) { return new short[]{(short) posToHilbert(x, y), 1}; } /** * Returns a new packed short[] containing the Hilbert distances in hilbert as "on" cells, and all other cells "off" * @param hilbert a vararg or array of Hilbert distances that will be encoded as "on" * @return the points given to this encoded as "on" in a packed short array */ public static short[] packSeveral(int... hilbert) { if(hilbert.length == 0) return ALL_WALL; Arrays.sort(hilbert); ShortVLA vla = new ShortVLA(128); int current, past = hilbert[0], skip = 0; vla.add((short)hilbert[0]); for (int i = 1; i < hilbert.length; i++) { current = hilbert[i]; if (current - past > 1) { vla.add((short) (skip+1)); skip = 0; vla.add((short)(current - past - 1)); } else if(current != past) skip++; past = current; } vla.add((short)(skip+1)); return vla.toArray(); } /** * Returns a new packed short[] containing the Coords in points as "on" cells, and all other cells "off" * @param points a vararg or array of Coords that will be encoded as "on" * @return the points given to this encoded as "on" in a packed short array */ public static short[] packSeveral(Coord... points) { if(points.length == 0) return ALL_WALL; int[] hilbert = new int[points.length]; for (int i = 0; i < points.length; i++) { hilbert[i] = coordToHilbert(points[i]); } Arrays.sort(hilbert); ShortVLA vla = new ShortVLA(128); int current, past = hilbert[0], skip = 0; vla.add((short)hilbert[0]); for (int i = 1; i < hilbert.length; i++) { current = hilbert[i]; if (current - past > 1) { vla.add((short) (skip+1)); skip = 0; vla.add((short)(current - past - 1)); } else if(current != past) skip++; past = current; } vla.add((short)(skip+1)); return vla.toArray(); } /** * Given one packed short array, original, and a Hilbert Curve index, hilbert, this produces a packed short array * that encodes "on" for any cell that was "on" in original, always encodes "on" for the position referred * to by hilbert, and encodes "off" for cells that were "off" in original and are not the cell hilbert refers to. * This method does not do any unpacking (which can be somewhat computationally expensive) and so should be strongly * preferred when finding a region of one packed array that is not contained in another packed array. * @param original A packed array such as one produced by pack() * @param hilbert A Hilbert Curve index that should be inserted into the result * @return A packed array that encodes "on" for all cells that are "on" in original or correspond to hilbert */ public static short[] insertPacked(short[] original, short hilbert) { return unionPacked(original, new short[]{hilbert, 1}); } /** * Given one packed short array, original, and a position as x,y numbers, this produces a packed short array * that encodes "on" for any cell that was "on" in original, always encodes "on" for the position referred * to by x and y, and encodes "off" for cells that were "off" in original and are not the cell x and y refer to. * This method does not do any unpacking (which can be somewhat computationally expensive) and so should be strongly * preferred when finding a region of one packed array that is not contained in another packed array. * @param original A packed array such as one produced by pack() * @param x The x position at which to insert the "on" cell * @param y The y position at which to insert the "on" cell * @return A packed array that encodes "on" for all cells that are "on" in original or correspond to x,y */ public static short[] insertPacked(short[] original, int x, int y) { return unionPacked(original, new short[]{(short)posToHilbert(x, y), 1}); } /** * Given one packed short array, original, and a number of Hilbert Curve indices, hilbert, this produces a packed * short array that encodes "on" for any cell that was "on" in original, always encodes "on" for the position * referred to by any element of hilbert, and encodes "off" for cells that were "off" in original and are not in any * cell hilbert refers to. This method does not do any unpacking (which can be somewhat computationally expensive) * and so should be strongly preferred when you have several Hilbert Curve indices, possibly nearby each other but * just as possibly not, that you need inserted into a packed array. * <br> * NOTE: this may not produce an optimally packed result, though the difference in memory consumption is likely * to be exceedingly small unless there are many nearby elements in hilbert (which may be a better use case for * unionPacked() anyway). * @param original A packed array such as one produced by pack() * @param hilbert an array or vararg of Hilbert Curve indices that should be inserted into the result * @return A packed array that encodes "on" for all cells that are "on" in original or are contained in hilbert */ public static short[] insertSeveralPacked(short[] original, int... hilbert) { return unionPacked(original, packSeveral(hilbert)); } /** * Given one packed short array, original, and a number of Coords, points, this produces a packed * short array that encodes "on" for any cell that was "on" in original, always encodes "on" for the position * referred to by any element of points, and encodes "off" for cells that were "off" in original and are not in any * cell points refers to. This method does not do any unpacking (which can be somewhat computationally expensive) * and so should be strongly preferred when you have several Coords, possibly nearby each other but * just as possibly not, that you need inserted into a packed array. * <br> * NOTE: this may not produce an optimally packed result, though the difference in memory consumption is likely * to be exceedingly small unless there are many nearby elements in hilbert (which may be a better use case for * unionPacked() anyway). * @param original A packed array such as one produced by pack() * @param points an array or vararg of Coords that should be inserted into the result * @return A packed array that encodes "on" for all cells that are "on" in original or are contained in hilbert */ public static short[] insertSeveralPacked(short[] original, Coord... points) { return unionPacked(original, packSeveral(points)); } /** * Given one packed short array, original, and a Hilbert Curve index, hilbert, this produces a packed short array * that encodes "on" for any cell that was "on" in original, unless it was the position referred to by hilbert, and * encodes "off" for cells that were "off" in original or are the cell hilbert refers to. * This method does not do any unpacking (which can be somewhat computationally expensive) and so should be strongly * preferred when finding a region of one packed array that is not contained in another packed array. * @param original A packed array such as one produced by pack() * @param hilbert A Hilbert Curve index that should be removed from the result * @return A packed array that encodes "on" for all cells that are "on" in original and don't correspond to hilbert */ public static short[] removePacked(short[] original, short hilbert) { return differencePacked(original, new short[]{hilbert, 1}); } /** * Given one packed short array, original, and a position as x,y numbers, this produces a packed short array that * encodes "on" for any cell that was "on" in original, unless it was the position referred to by x and y, and * encodes "off" for cells that were "off" in original or are the cell x and y refer to. * This method does not do any unpacking (which can be somewhat computationally expensive) and so should be strongly * preferred when finding a region of one packed array that is not contained in another packed array. * @param original A packed array such as one produced by pack() * @param x The x position at which to remove any "on" cell * @param y The y position at which to remove any "on" cell * @return A packed array that encodes "on" for all cells that are "on" in original and don't correspond to x,y */ public static short[] removePacked(short[] original, int x, int y) { int dist = posToHilbert(x, y); return differencePacked(original, new short[]{(short)dist, 1}); } /** * Given one packed short array, original, and a number of Hilbert Curve indices, hilbert, this produces a packed * short array that encodes "on" for any cell that was "on" in original, unless it was a position referred to by * hilbert, and encodes "off" for cells that were "off" in original and are a cell hilbert refers to. This method * does not do any unpacking (which can be somewhat computationally expensive) and so should be strongly preferred * when you have several Hilbert Curve indices, possibly nearby each other but just as possibly not, that you need * removed from a packed array. * <br> * NOTE: this may not produce an optimally packed result, though the difference in memory consumption is likely * to be exceedingly small unless there are many nearby elements in hilbert (which may be a better use case for * differencePacked() anyway). * @param original A packed array such as one produced by pack() * @param hilbert an array or vararg of Hilbert Curve indices that should be inserted into the result * @return A packed array that encodes "on" for all cells that are "on" in original and aren't contained in hilbert */ public static short[] removeSeveralPacked(short[] original, int... hilbert) { return differencePacked(original, packSeveral(hilbert)); } /** * Given one packed short array, original, and a number of Hilbert Curve indices, hilbert, this produces a packed * short array that encodes "on" for any cell that was "on" in original, unless it was a position referred to by * hilbert, and encodes "off" for cells that were "off" in original and are a cell hilbert refers to. This method * does not do any unpacking (which can be somewhat computationally expensive) and so should be strongly preferred * when you have several Hilbert Curve indices, possibly nearby each other but just as possibly not, that you need * removed from a packed array. * <br> * NOTE: this may not produce an optimally packed result, though the difference in memory consumption is likely * to be exceedingly small unless there are many nearby elements in hilbert (which may be a better use case for * differencePacked() anyway). * @param original A packed array such as one produced by pack() * @param points an array or vararg of Coords that should be inserted into the result * @return A packed array that encodes "on" for all cells that are "on" in original and aren't contained in points */ public static short[] removeSeveralPacked(short[] original, Coord... points) { return differencePacked(original, packSeveral(points)); } /** * Gets a random subset of positions that are "on" in the given packed array, without unpacking it, and returns * them as a Coord[]. Random numbers are generated by the rng parameter. * @param packed a short[] returned by pack() or one of the sub-arrays in what is returned by packMulti(); must * not be null (this method does not check). * @param fraction the likelihood to return one of the "on" cells, from 0.0 to 1.0 * @param rng the random number generator used to decide random factors. * @return a Coord[], ordered by distance along the Hilbert Curve, corresponding to a random section of "on" cells * in packed that has a random length approximately equal to the count of all "on" cells in packed times fraction. */ public static Coord[] randomSample(short[] packed, double fraction, RNG rng) { int counted = count(packed); ShortVLA vla = new ShortVLA((int)(counted * fraction) + 1); boolean on = false; int idx = 0; for(int p = 0; p < packed.length; p++, on = !on) { if (on) { for (int i = idx; i < idx + (packed[p] & 0xffff); i++) { if(rng.nextDouble() < fraction) vla.add((short)i); } } idx += packed[p] & 0xffff; } int[] distances = vla.asInts(); Coord[] cs = new Coord[distances.length]; for (int i = 0; i < distances.length; i++) { cs[i] = Coord.get(hilbertX[distances[i]], hilbertY[distances[i]]); } return cs; } /** * Gets a single randomly chosen position that is "on" in the given packed array, without unpacking it, and returns * it as a Coord or returns null of the array is empty. Random numbers are generated by the rng parameter. * More efficient in most cases than randomSample(), and will always return at least one Coord for non-empty arrays. * @param packed a short[] returned by pack() or one of the sub-arrays in what is returned by packMulti(); must * not be null (this method does not check). * @param rng the random number generator used to decide random factors * @return a Coord corresponding to a random "on" cell in packed, or the Coord (-1, -1) if packed is empty */ public static Coord singleRandom(short[] packed, RNG rng) { int counted = count(packed); if(counted == 0) return Coord.get(-1,-1); int r = rng.nextInt(counted); int c = 0, idx = 0; boolean on = false; for (int i = 0; i < packed.length; on = !on, idx += packed[i] & 0xFFFF, i++) { if (on) { if(c + (packed[i] & 0xFFFF) > r) { idx += r - c; return Coord.get(hilbertX[idx], hilbertY[idx]); } c += packed[i] & 0xFFFF; } } return Coord.get(-1,-1); } /** * Gets a fixed number of randomly chosen positions that are "on" in the given packed array, without unpacking it, * and returns a List of Coord with a count equal to size (or less if there aren't enough "on" cells). Random * numbers are generated by the rng parameter. This orders the returned array in the order the Hilbert Curve takes, * and you may want to call RNG.shuffle() with it as a parameter to randomize the order. * * @param packed a short[] returned by pack() or one of the sub-arrays in what is returned by packMulti(); must * not be null (this method does not check). * @param size the desired size of the List to return; may be smaller if there aren't enough elements * @param rng the random number generator used to decide random factors. * @return a List of Coords, ordered by distance along the Hilbert Curve, corresponding to randomly "on" cells in * packed, with a length equal to the smaller of size and the count of all "on" cells in packed */ public static ArrayList<Coord> randomPortion(short[] packed, int size, RNG rng) { int counted = count(packed); ArrayList<Coord> coords = new ArrayList<Coord>(Math.min(counted, size)); if(counted == 0 || size == 0) return coords; int[] data = rng.randomRange(0, counted, Math.min(counted, size)); Arrays.sort(data); int r = data[0]; int c = 0, idx = 0; boolean on = false; for (int i = 0, ri = 0; i < packed.length; on = !on, idx += packed[i] & 0xffff, i++) { if (on) { while (c + (packed[i] & 0xffff) > r) { int n = idx + r - c; coords.add(Coord.get(hilbertX[n], hilbertY[n])); if(++ri < data.length) r = data[ri]; else return coords; } c += packed[i] & 0xffff; } } return coords; } /** * Takes multiple pieces of packed data as short[], encoded by pack() or another similar method of this class, and * generates a 2D int array with the specified width and height and a starting value of 0 for all elements, then * where every occurrence of a cell as "on" in a piece of packed data increments the cell's value in the returned * array. Width and height do not technically need to match the dimensions of the original 2D array, but under most * circumstances where they don't match, the data produced will be junk. * @param width the width of the 2D array that will be returned; should match the unpacked array's width * @param height the height of the 2D array that will be returned; should match the unpacked array's height * @param many a vararg or array of short[] encoded by calling one of this class' packing methods on a 2D array * @return an int[][] storing at least 0 for all cells, plus 1 for every element of packed that has that cell "on" */ public static int[][] sumMany(int width, int height, short[] ... many) { if(many == null) throw new ArrayIndexOutOfBoundsException("CoordPacker.sumMany() must be given a non-null many arg"); int[][] unpacked = new int[width][height]; for (int e = 0; e < many.length; e++) { boolean on = false; int idx = 0; short x = 0, y = 0; for(int p = 0; p < many[e].length; p++, on = !on) { if (on) { for (int toSkip = idx + (many[e][p] & 0xffff); idx < toSkip && idx < 0x10000; idx++) { x = hilbertX[idx]; y = hilbertY[idx]; if(x >= width || y >= height) continue; unpacked[x][y]++; } } else { idx += many[e][p] & 0xffff; } } } return unpacked; } /** * Quick utility method for printing packed data as a grid of 1 (on) and/or 0 (off). Useful primarily for debugging. * @param packed a packed short[] such as one produced by pack() * @param width the width of the packed 2D array * @param height the height of the packed 2D array */ public static void printPacked(short[] packed, int width, int height) { boolean[][] unpacked = unpack(packed, width, height); for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { System.out.print(unpacked[x][y] ? '1' : '0'); } System.out.println(); } } public static void printCompressedData(short[] packed) { if(packed == null || packed.length == 0) { System.out.println("[]"); return; } System.out.print("[" + packed[0]); for (int i = 1; i < packed.length; i++) { System.out.print(", " + packed[i]); } System.out.println("]"); } /** * Encodes a short array of packed data as a (larger, more memory-hungry) ASCII string, which can be decoded using * CoordPacker.decodeASCII() . Uses 64 printable chars, from ';' (ASCII 59) to 'z' (ASCII 122). * @param packed a packed data item produced by pack() or some other method from this class. * @return a printable String, which can be decoded with CoordPacker.decodeASCII() */ public static String encodeASCII(short[] packed) { int len = packed.length * 3; char[] chars = new char[len]; for (int i = 0, c = 0; c < len; i++, c += 3) { chars[c] = (char)((packed[i] & 31) + 59); chars[c+1] = (char)(((packed[i] >> 5) & 31) + 59); chars[c+2] = (char)(((packed[i] >>> 10) & 63) + 59); } return new String(chars); } /** * Given a String specifically produced by CoordPacker.encodeASCII(), this will produce a packed data array. * @param text a String produced by CoordPacker.encodeASCII(); this will almost certainly fail on other strings. * @return the packed data as a short array that was originally used to encode text */ public static short[] decodeASCII(String text) { int len = text.length(); if(len % 3 != 0) return ALL_WALL; char[] chars = text.toCharArray(); short[] packed = new short[len / 3]; for (int c = 0, i = 0; c < len; i++, c += 3) { packed[i] = (short)(((chars[c] - 59) & 31) | (((chars[c+1] - 59) & 31) << 5) | (((chars[c+2] - 59) & 63) << 10)); } return packed; } public static int grayEncode(int n){ return n ^ (n >> 1); } public static int grayDecode(int n) { int p = n; while ((n >>= 1) != 0) p ^= n; return p; } public static int posToHilbert( final int x, final int y ) { //int dist = posToHilbertNoLUT(x, y); //return dist; return hilbertDistances[x + (y << 8)] & 0xffff; } public static int posToHilbert3D( final int x, final int y, final int z ) { return hilbert3Distances[x + (y << 5) + (z << 10)]; } /** * Takes an x, y position and returns the length to travel along the 16x16 Moore curve to reach that position. * This assumes x and y are between 0 and 15, inclusive. * This uses a lookup table for the 16x16 Moore Curve, which should make it faster than calculating the * distance along the Moore Curve repeatedly. * @param x between 0 and 15 inclusive * @param y between 0 and 15 inclusive * @return the distance to travel along the 16x16 Moore Curve to get to the given x, y point. */ public static int posToMoore( final int x, final int y ) { return mooreDistances[x + (y << 4)] & 0xff; } private static int posToHilbertNoLUT( final int x, final int y ) { int hilbert = 0, remap = 0xb4, mcode, hcode; /* while( block > 0 ) { --block; mcode = ( ( x >> block ) & 1 ) | ( ( ( y >> ( block ) ) & 1 ) << 1); hcode = ( ( remap >> ( mcode << 1 ) ) & 3 ); remap ^= ( 0x82000028 >> ( hcode << 3 ) ); hilbert = ( ( hilbert << 2 ) + hcode ); } */ mcode = ( ( x >> 7 ) & 1 ) | ( ( ( y >> ( 7 ) ) & 1 ) << 1); hcode = ( ( remap >> ( mcode << 1 ) ) & 3 ); remap ^= ( 0x82000028 >> ( hcode << 3 ) ); hilbert = ( ( hilbert << 2 ) + hcode ); mcode = ( ( x >> 6 ) & 1 ) | ( ( ( y >> ( 6 ) ) & 1 ) << 1); hcode = ( ( remap >> ( mcode << 1 ) ) & 3 ); remap ^= ( 0x82000028 >> ( hcode << 3 ) ); hilbert = ( ( hilbert << 2 ) + hcode ); mcode = ( ( x >> 5 ) & 1 ) | ( ( ( y >> ( 5 ) ) & 1 ) << 1); hcode = ( ( remap >> ( mcode << 1 ) ) & 3 ); remap ^= ( 0x82000028 >> ( hcode << 3 ) ); hilbert = ( ( hilbert << 2 ) + hcode ); mcode = ( ( x >> 4 ) & 1 ) | ( ( ( y >> ( 4 ) ) & 1 ) << 1); hcode = ( ( remap >> ( mcode << 1 ) ) & 3 ); remap ^= ( 0x82000028 >> ( hcode << 3 ) ); hilbert = ( ( hilbert << 2 ) + hcode ); mcode = ( ( x >> 3 ) & 1 ) | ( ( ( y >> ( 3 ) ) & 1 ) << 1); hcode = ( ( remap >> ( mcode << 1 ) ) & 3 ); remap ^= ( 0x82000028 >> ( hcode << 3 ) ); hilbert = ( ( hilbert << 2 ) + hcode ); mcode = ( ( x >> 2 ) & 1 ) | ( ( ( y >> ( 2 ) ) & 1 ) << 1); hcode = ( ( remap >> ( mcode << 1 ) ) & 3 ); remap ^= ( 0x82000028 >> ( hcode << 3 ) ); hilbert = ( ( hilbert << 2 ) + hcode ); mcode = ( ( x >> 1 ) & 1 ) | ( ( ( y >> ( 1 ) ) & 1 ) << 1); hcode = ( ( remap >> ( mcode << 1 ) ) & 3 ); remap ^= ( 0x82000028 >> ( hcode << 3 ) ); hilbert = ( ( hilbert << 2 ) + hcode ); mcode = ( x & 1 ) | ( ( y & 1 ) << 1); hcode = ( ( remap >> ( mcode << 1 ) ) & 3 ); hilbert = ( ( hilbert << 2 ) + hcode ); return hilbert; } public static int mortonToHilbert( final int morton ) { int hilbert = 0; int remap = 0xb4; int block = BITS; while( block > 0 ) { block -= 2; int mcode = ( ( morton >> block ) & 3 ); int hcode = ( ( remap >> ( mcode << 1 ) ) & 3 ); remap ^= ( 0x82000028 >> ( hcode << 3 ) ); hilbert = ( ( hilbert << 2 ) + hcode ); } return hilbert; } /** * Takes a distance to travel along the 256x256 Hilbert curve and returns a Morton code representing the position * in 2D space that corresponds to that point on the Hilbert Curve; the Morton code will have interleaved x and y * bits and x in the least significant bit. This uses a lookup table for the 256x256 Hilbert curve, which should * make it faster than calculating the position repeatedly. * The parameter hilbert is an int but only 16 unsigned bits are used. * @param hilbert a distance to travel down the Hilbert Curve * @return a Morton code that stores x and y interleaved; can be converted to a Coord with other methods. */ public static int hilbertToMorton( final int hilbert ) { return mortonEncode(hilbertX[hilbert], hilbertY[hilbert]); } /** * Takes a distance to travel along the 256x256 Hilbert curve and returns a Coord representing the position * in 2D space that corresponds to that point on the Hilbert curve. This uses a lookup table for the * 256x256 Hilbert curve, which should make it faster than calculating the position repeatedly. * The parameter hilbert is an int but only 16 unsigned bits are used. * @param hilbert a distance to travel down the Hilbert Curve * @return a Coord corresponding to the position in 2D space at the given distance down the Hilbert Curve */ public static Coord hilbertToCoord( final int hilbert ) { return Coord.get(hilbertX[hilbert], hilbertY[hilbert]); } /** * Takes a distance to travel along the 16x16 Hilbert curve and returns a Coord representing the position * in 2D space that corresponds to that point on the Hilbert curve. This uses a lookup table for the * 16x16 Hilbert curve, which should make it faster than calculating the position repeatedly. * The parameter moore is an int but only 8 unsigned bits are used, and since the Moore Curve loops, it is * calculated as {@code moore % 256}. * @param moore a distance to travel down the Moore Curve * @return a Coord corresponding to the position in 2D space at the given distance down the Hilbert Curve */ public static Coord mooreToCoord( final int moore ) { return Coord.get(mooreX[moore % 256], mooreY[moore % 256]); } /* * Takes a distance to travel along the 256x256 Hilbert curve and returns a Morton code representing the position * in 2D space that corresponds to that point on the Hilbert curve; the Morton code will have interleaved x and y * bits and x in the least significant bit. This variant does not use a lookup table, and is likely slower. * The parameter hilbert is an int but only 16 unsigned bits are used. * @param hilbert * @return */ /* public static int hilbertToMortonNoLUT( final int hilbert ) { int morton = 0; int remap = 0xb4; int block = BITS; while( block > 0 ) { block -= 2; int hcode = ( ( hilbert >> block ) & 3 ); int mcode = ( ( remap >> ( hcode << 1 ) ) & 3 ); remap ^= ( 0x330000cc >> ( hcode << 3 ) ); morton = ( ( morton << 2 ) + mcode ); } return morton; } */ /* * Takes a distance to travel along the 256x256 Hilbert curve and returns a Coord representing the position * in 2D space that corresponds to that point on the Hilbert curve. This variant does not use a lookup table, * and is likely slower. * The parameter hilbert is an int but only 16 unsigned bits are used. * @param hilbert * @return */ private static Coord hilbertToCoordNoLUT( final int hilbert ) { int x = 0, y = 0; int remap = 0xb4; int block = BITS; while( block > 0 ) { block -= 2; int hcode = ( ( hilbert >> block ) & 3 ); int mcode = ( ( remap >> ( hcode << 1 ) ) & 3 ); remap ^= ( 0x330000cc >> ( hcode << 3 ) ); x = (x << 1) + (mcode & 1); y = (y << 1) + ((mcode & 2) >> 1); } return Coord.get(x, y); } public static int coordToHilbert(final Coord pt) { return posToHilbert(pt.x, pt.y); } /** * Takes a position as a Coord called pt and returns the length to travel along the 16x16 Moore curve to reach * that position. * This assumes pt.x and pt.y are between 0 and 15, inclusive. * @param pt a Coord with values between 0 and 15, inclusive * @return a distance from the "start" of the 16x16 Moore curve to get to the position of pt */ public static int coordToMoore(final Coord pt) { return posToMoore(pt.x, pt.y); } private static int mortonEncode3D( int index1, int index2, int index3 ) { // pack 3 5-bit indices into a 15-bit Morton code index1 &= 0x0000001f; index2 &= 0x0000001f; index3 &= 0x0000001f; index1 *= 0x01041041; index2 *= 0x01041041; index3 *= 0x01041041; index1 &= 0x10204081; index2 &= 0x10204081; index3 &= 0x10204081; index1 *= 0x00011111; index2 *= 0x00011111; index3 *= 0x00011111; index1 &= 0x12490000; index2 &= 0x12490000; index3 &= 0x12490000; return( ( index1 >> 16 ) | ( index2 >> 15 ) | ( index3 >> 14 ) ); } private static void computeHilbert3D(int x, int y, int z) { int hilbert = mortonEncode3D(x, y, z); int block = 6; int hcode = ( ( hilbert >> block ) & 7 ); int mcode, shift, signs; shift = signs = 0; while( block > 0 ) { block -= 3; hcode <<= 2; mcode = ( ( 0x20212021 >> hcode ) & 3 ); shift = ( ( 0x48 >> ( 7 - shift - mcode ) ) & 3 ); signs = ( ( signs | ( signs << 3 ) ) >> mcode ); signs = ( ( signs ^ ( 0x53560300 >> hcode ) ) & 7 ); mcode = ( ( hilbert >> block ) & 7 ); hcode = mcode; hcode = ( ( ( hcode | ( hcode << 3 ) ) >> shift ) & 7 ); hcode ^= signs; hilbert ^= ( ( mcode ^ hcode ) << block ); } hilbert ^= ( ( hilbert >> 1 ) & 0x92492492 ); hilbert ^= ( ( hilbert & 0x92492492 ) >> 1 ); hilbert3X[hilbert] = (short)x; hilbert3Y[hilbert] = (short)y; hilbert3Z[hilbert] = (short)z; hilbert3Distances[x + (y << 3) + (z << 6)] = (short)hilbert; } /** * Gets the x coordinate for a given index into the 16x16x(8*n) Moore curve. Expects indices to touch the following * corners of the 16x16x(8*n) cube in this order, using x,y,z syntax: * (0,0,0) (0,0,(8*n)) (0,16,(8*n)) (0,16,0) (16,16,0) (16,16,(8*n)) (16,0,(8*n)) (16,0,0) * @param index the index into the 3D 16x16x(8*n) Moore Curve, must be less than 0x1000 * @param n the number of 8-deep layers to use as part of the box shape this travels through * @return the x coordinate of the given distance traveled through the 3D 16x16x(8*n) Moore Curve */ public static int getXMoore3D(final int index, final int n) { int hilbert = index & 0x1ff; int sector = index >> 9; if (sector < 2 * n) return 7 - hilbert3X[hilbert]; else return 8 + hilbert3X[hilbert]; } /** * Gets the y coordinate for a given index into the 16x16x(8*n) Moore curve. Expects indices to touch the following * corners of the 16x16x(8*n) cube in this order, using x,y,z syntax: * (0,0,0) (0,0,(8*n)) (0,16,(8*n)) (0,16,0) (16,16,0) (16,16,(8*n)) (16,0,(8*n)) (16,0,0) * @param index the index into the 3D 16x16x(8*n) Moore Curve, must be less than 0x1000 * @param n the number of 8-deep layers to use as part of the box shape this travels through * @return the y coordinate of the given distance traveled through the 3D 16x16x(8*n) Moore Curve */ public static int getYMoore3D(final int index, final int n) { int hilbert = index & 0x1ff; int sector = index >> 9; if (sector < n || sector >= 3 * n) return 7 - hilbert3Y[hilbert]; else return 8 + hilbert3Y[hilbert]; } /** * Gets the z coordinate for a given index into the 16x16x(8*n) Moore curve. Expects indices to touch the following * corners of the 16x16x(8*n) cube in this order, using x,y,z syntax: * (0,0,0) (0,0,(8*n)) (0,16,(8*n)) (0,16,0) (16,16,0) (16,16,(8*n)) (16,0,(8*n)) (16,0,0) * @param index the index into the 3D 16x16x(8*n) Moore Curve, must be less than 0x1000 * @param n the number of 8-deep layers to use as part of the box shape this travels through * @return the z coordinate of the given distance traveled through the 3D 16x16x(8*n) Moore Curve */ public static int getZMoore3D(final int index, final int n) { int hilbert = index & 0x1ff; int sector = index >> 9; if (sector / n < 2) return hilbert3Z[hilbert] + 8 * (sector % n); else return (8 * n - 1) - hilbert3Z[hilbert] - 8 * (sector % n); } public static short zEncode(short index1, short index2) { // pack 2 8-bit (unsigned) indices into a 16-bit (signed...) Morton code/Z-Code index1 &= 0x000000ff; index2 &= 0x000000ff; index1 |= ( index1 << 4 ); index2 |= ( index2 << 4 ); index1 &= 0x00000f0f; index2 &= 0x00000f0f; index1 |= ( index1 << 2 ); index2 |= ( index2 << 2 ); index1 &= 0x00003333; index2 &= 0x00003333; index1 |= ( index1 << 1 ); index2 |= ( index2 << 1 ); index1 &= 0x00005555; index2 &= 0x00005555; return (short)(index1 | ( index2 << 1 )); } public static int mortonEncode(int index1, int index2) { // pack 2 8-bit (unsigned) indices into a 32-bit (signed...) Morton code index1 &= 0x000000ff; index2 &= 0x000000ff; index1 |= ( index1 << 4 ); index2 |= ( index2 << 4 ); index1 &= 0x00000f0f; index2 &= 0x00000f0f; index1 |= ( index1 << 2 ); index2 |= ( index2 << 2 ); index1 &= 0x00003333; index2 &= 0x00003333; index1 |= ( index1 << 1 ); index2 |= ( index2 << 1 ); index1 &= 0x00005555; index2 &= 0x00005555; return index1 | ( index2 << 1 ); } public static Coord mortonDecode( final int morton ) { // unpack 2 8-bit (unsigned) indices from a 32-bit (signed...) Morton code int value1 = morton; int value2 = ( value1 >> 1 ); value1 &= 0x5555; value2 &= 0x5555; value1 |= ( value1 >> 1 ); value2 |= ( value2 >> 1 ); value1 &= 0x3333; value2 &= 0x3333; value1 |= ( value1 >> 2 ); value2 |= ( value2 >> 2 ); value1 &= 0x0f0f; value2 &= 0x0f0f; value1 |= ( value1 >> 4 ); value2 |= ( value2 >> 4 ); value1 &= 0x00ff; value2 &= 0x00ff; return Coord.get(value1, value2); } public static Coord zDecode( final short morton ) { // unpack 2 8-bit (unsigned) indices from a 32-bit (signed...) Morton code int value1 = morton & 0xffff; int value2 = ( value1 >> 1 ); value1 &= 0x5555; value2 &= 0x5555; value1 |= ( value1 >> 1 ); value2 |= ( value2 >> 1 ); value1 &= 0x3333; value2 &= 0x3333; value1 |= ( value1 >> 2 ); value2 |= ( value2 >> 2 ); value1 &= 0x0f0f; value2 &= 0x0f0f; value1 |= ( value1 >> 4 ); value2 |= ( value2 >> 4 ); value1 &= 0x00ff; value2 &= 0x00ff; return Coord.get(value1, value2); } }
package com.battlelancer.seriesguide.util; import com.battlelancer.seriesguide.Constants; import com.battlelancer.seriesguide.items.Series; import com.battlelancer.seriesguide.provider.SeriesContract; import com.battlelancer.seriesguide.provider.SeriesContract.EpisodeSearch; import com.battlelancer.seriesguide.provider.SeriesContract.Episodes; import com.battlelancer.seriesguide.provider.SeriesContract.Seasons; import com.battlelancer.seriesguide.provider.SeriesContract.Shows; import com.battlelancer.seriesguide.ui.SeriesGuidePreferences; import com.battlelancer.seriesguide.ui.UpcomingFragment.UpcomingQuery; import com.battlelancer.thetvdbapi.ImageCache; import android.content.ContentProviderOperation; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.content.OperationApplicationException; import android.content.SharedPreferences; import android.database.Cursor; import android.net.Uri; import android.os.RemoteException; import android.preference.PreferenceManager; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashSet; import java.util.TimeZone; public class DBUtils { static final String TAG = "SeriesDatabase"; /** * Use 9999 for unkown airdates/no next episodes, sorting then assumes year * 9999 and sorts these last. */ public static final String UNKNOWN_NEXT_AIR_DATE = "9999"; /** * Looks up the episodes of a given season and stores the count of already * aired, but not watched ones in the seasons watchcount. * * @param seasonid */ public static void updateUnwatchedCount(Context context, String seasonid) { ContentResolver resolver = context.getContentResolver(); Date date = new Date(); String today = Constants.theTVDBDateFormat.format(date); Uri episodesOfSeasonUri = Episodes.buildEpisodesOfSeasonUri(seasonid); // all a seasons episodes Cursor total = resolver.query(episodesOfSeasonUri, new String[] { Episodes._ID }, null, null, null); final int totalcount = total.getCount(); total.close(); // unwatched, aired episodes String selection = Episodes.WATCHED + "=? AND " + Episodes.FIRSTAIRED + " like '%-%'" + " AND " + Episodes.FIRSTAIRED + "<=?"; Cursor unwatched = resolver.query(episodesOfSeasonUri, new String[] { Episodes._ID }, selection, new String[] { "0", today }, null); final int count = unwatched.getCount(); unwatched.close(); // unwatched, aired in the future episodes selection = Episodes.WATCHED + "=? AND " + Episodes.FIRSTAIRED + ">?"; Cursor unaired = resolver.query(episodesOfSeasonUri, new String[] { Episodes._ID }, selection, new String[] { "0", today }, null); final int unaired_count = unaired.getCount(); unaired.close(); // unwatched, no airdate selection = Episodes.WATCHED + "=? AND " + Episodes.FIRSTAIRED + "=?"; Cursor noairdate = resolver.query(episodesOfSeasonUri, new String[] { Episodes._ID }, selection, new String[] { "0", "" }, null); final int noairdate_count = noairdate.getCount(); noairdate.close(); ContentValues update = new ContentValues(); update.put(Seasons.WATCHCOUNT, count); update.put(Seasons.UNAIREDCOUNT, unaired_count); update.put(Seasons.NOAIRDATECOUNT, noairdate_count); update.put(Seasons.TOTALCOUNT, totalcount); resolver.update(Seasons.buildSeasonUri(seasonid), update, null, null); } /** * Returns all episodes that air today or later. Using Pacific Time to * determine today. Excludes shows that are hidden. * * @return Cursor including episodes with show title, network, airtime and * posterpath. */ public static Cursor getUpcomingEpisodes(Context context) { // TODO check if changing the tz has any effect SimpleDateFormat pdtformat = Constants.theTVDBDateFormat; pdtformat.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles")); final Date date = new Date(); final String today = pdtformat.format(date); String query = UpcomingQuery.QUERY_UPCOMING; SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); boolean isOnlyFavorites = prefs.getBoolean(SeriesGuidePreferences.KEY_ONLYFAVORITES, false); String[] selectionArgs; if (isOnlyFavorites) { query += UpcomingQuery.SELECTION_ONLYFAVORITES; selectionArgs = new String[] { today, "0", "1" }; } else { selectionArgs = new String[] { today, "0" }; } return context.getContentResolver().query(Episodes.CONTENT_URI_WITHSHOW, UpcomingQuery.PROJECTION, query, selectionArgs, UpcomingQuery.SORTING_UPCOMING); } /** * Return all episodes that aired the day before and earlier. Using Pacific * Time to determine today. Excludes shows that are hidden. * * @param context * @return Cursor including episodes with show title, network, airtime and * posterpath. */ public static Cursor getRecentEpisodes(Context context) { // TODO check if changing the tz has any effect SimpleDateFormat pdtformat = Constants.theTVDBDateFormat; pdtformat.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles")); final Date date = new Date(); final String today = pdtformat.format(date); String query = UpcomingQuery.QUERY_RECENT; SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); boolean isOnlyFavorites = prefs.getBoolean(SeriesGuidePreferences.KEY_ONLYFAVORITES, false); String[] selectionArgs; if (isOnlyFavorites) { query += UpcomingQuery.SELECTION_ONLYFAVORITES; selectionArgs = new String[] { today, "0", "1" }; } else { selectionArgs = new String[] { today, "0" }; } return context.getContentResolver().query(Episodes.CONTENT_URI_WITHSHOW, UpcomingQuery.PROJECTION, query, selectionArgs, UpcomingQuery.SORTING_RECENT); } /** * Updates the given boolean to the EPISODE_WATCHED column of the given * episode row. Be aware that the database stores the value as an integer. * * @param rowid * @param state */ public static void markEpisode(Context context, String episodeId, boolean state) { ContentValues values = new ContentValues(); values.put(Episodes.WATCHED, state); context.getContentResolver() .update(Episodes.buildEpisodeUri(episodeId), values, null, null); context.getContentResolver().notifyChange(Episodes.CONTENT_URI, null); } /** * Marks the next episode (if there is one) of this show as watched. * * @param seriesid */ public static void markNextEpisode(Context context, long seriesid) { Cursor show = context.getContentResolver().query( Shows.buildShowUri(String.valueOf(seriesid)), new String[] { Shows.NEXTEPISODE }, null, null, null); show.moveToFirst(); ContentValues values = new ContentValues(); values.put(Episodes.WATCHED, true); String episodeid = show.getString(show.getColumnIndexOrThrow(Shows.NEXTEPISODE)); if (episodeid.length() != 0) { context.getContentResolver().update(Episodes.buildEpisodeUri(episodeid), values, null, null); } show.close(); } /** * Updates all EPISODE_WATCHED columns of the episodes of the given season * with the given boolean. Be aware that the database stores the value as an * integer. * * @param seasonid * @param state */ public static void markSeasonEpisodes(Context context, String seasonId, boolean state) { ContentValues values = new ContentValues(); values.put(Episodes.WATCHED, state); context.getContentResolver().update(Episodes.buildEpisodesOfSeasonUri(seasonId), values, null, null); } /** * Marks all episodes of a show that have aired before the air date of the * given episode. * * @param context * @param episodeId */ public static void markUntilHere(Context context, String episodeId) { Cursor episode = context.getContentResolver().query(Episodes.buildEpisodeUri(episodeId), new String[] { Episodes.FIRSTAIRED, Shows.REF_SHOW_ID }, null, null, null); episode.moveToFirst(); final String untilDate = episode.getString(0); final String showId = episode.getString(1); episode.close(); if (untilDate.length() != 0) { ContentValues values = new ContentValues(); values.put(Episodes.WATCHED, true); context.getContentResolver().update(Episodes.buildEpisodesOfShowUri(showId), values, Episodes.FIRSTAIRED + "<? AND " + Episodes.FIRSTAIRED + "!=''", new String[] { untilDate }); context.getContentResolver().notifyChange(Episodes.CONTENT_URI, null); } } /** * Fetches the row to a given show id and returns the results an Series * object. Returns {@code null} if there is no show with that id. * * @param seriesid * @return */ public static Series getShow(Context context, String showId) { Series show = new Series(); Cursor details = context.getContentResolver().query(Shows.buildShowUri(showId), null, null, null, null); if (details.moveToFirst()) { show.setActors(details.getString(details.getColumnIndexOrThrow(Shows.ACTORS))); show.setAirsDayOfWeek(details.getString(details .getColumnIndexOrThrow(Shows.AIRSDAYOFWEEK))); show.setAirsTime(details.getLong(details.getColumnIndexOrThrow(Shows.AIRSTIME))); show.setContentRating(details.getString(details .getColumnIndexOrThrow(Shows.CONTENTRATING))); show.setFirstAired(details.getString(details.getColumnIndexOrThrow(Shows.FIRSTAIRED))); show.setGenres(details.getString(details.getColumnIndexOrThrow(Shows.GENRES))); show.setId(details.getString(details.getColumnIndexOrThrow(Shows._ID))); show.setNetwork(details.getString(details.getColumnIndexOrThrow(Shows.NETWORK))); show.setOverview(details.getString(details.getColumnIndexOrThrow(Shows.OVERVIEW))); show.setPoster(details.getString(details.getColumnIndexOrThrow(Shows.POSTER))); show.setRating(details.getString(details.getColumnIndexOrThrow(Shows.RATING))); show.setRuntime(details.getString(details.getColumnIndexOrThrow(Shows.RUNTIME))); show.setSeriesId(details.getString(details.getColumnIndexOrThrow(Shows._ID))); show.setSeriesName(details.getString(details.getColumnIndexOrThrow(Shows.TITLE))); show.setStatus(details.getInt(details.getColumnIndexOrThrow(Shows.STATUS))); show.setImdbId(details.getString(details.getColumnIndexOrThrow(Shows.IMDBID))); show.setNextEpisode(details.getLong(details.getColumnIndexOrThrow(Shows.NEXTEPISODE))); } else { show = null; } details.close(); return show; } public static boolean isShowExists(String showId, Context context) { Cursor testsearch = context.getContentResolver().query(Shows.buildShowUri(showId), new String[] { Shows._ID }, null, null, null); boolean isShowExists = testsearch.getCount() != 0 ? true : false; testsearch.close(); return isShowExists; } /** * Builds a {@link ContentProviderOperation} for inserting or updating a * show (depending on {@code isNew}. * * @param show * @param context * @param isNew * @return */ public static ContentProviderOperation buildShowOp(Series show, Context context, boolean isNew) { ContentValues values = new ContentValues(); values = putCommonShowValues(show, values); if (isNew) { values.put(Shows._ID, show.getId()); return ContentProviderOperation.newInsert(Shows.CONTENT_URI).withValues(values).build(); } else { return ContentProviderOperation.newUpdate(Shows.buildShowUri(show.getId())) .withValues(values).build(); } } /** * Adds default show information from given Series object to given * ContentValues. * * @param show * @param values * @return */ private static ContentValues putCommonShowValues(Series show, ContentValues values) { values.put(Shows.TITLE, show.getSeriesName()); values.put(Shows.OVERVIEW, show.getOverview()); values.put(Shows.ACTORS, show.getActors()); values.put(Shows.AIRSDAYOFWEEK, show.getAirsDayOfWeek()); values.put(Shows.AIRSTIME, show.getAirsTime()); values.put(Shows.AIRTIME, show.getAirTime()); values.put(Shows.FIRSTAIRED, show.getFirstAired()); values.put(Shows.GENRES, show.getGenres()); values.put(Shows.NETWORK, show.getNetwork()); values.put(Shows.RATING, show.getRating()); values.put(Shows.RUNTIME, show.getRuntime()); values.put(Shows.STATUS, show.getStatus()); values.put(Shows.CONTENTRATING, show.getContentRating()); values.put(Shows.POSTER, show.getPoster()); values.put(Shows.IMDBID, show.getImdbId()); values.put(Shows.LASTUPDATED, new Date().getTime()); return values; } /** * Delete a show and manually delete its seasons and episodes. Also cleans * up the poster and images. * * @param context * @param id */ public static void deleteShow(Context context, String id) { final ArrayList<ContentProviderOperation> batch = Lists.newArrayList(); final String showId = String.valueOf(id); final ImageCache imageCache = ImageCache.getInstance(context); // delete images... // ...of show final Cursor poster = context.getContentResolver().query(Shows.buildShowUri(showId), new String[] { Shows.POSTER }, null, null, null); if (poster.moveToFirst()) { final String posterPath = poster.getString(0); imageCache.removeFromDisk(posterPath); } poster.close(); // ...of episodes final Cursor episodes = context.getContentResolver().query( Episodes.buildEpisodesOfShowUri(showId), new String[] { Episodes._ID, Episodes.IMAGE }, null, null, null); String[] episodeIDs = new String[episodes.getCount()]; episodes.moveToFirst(); int counter = 0; while (!episodes.isAfterLast()) { episodeIDs[counter++] = episodes.getString(0); imageCache.removeFromDisk(episodes.getString(1)); episodes.moveToNext(); } episodes.close(); // delete database entries for (String episodeID : episodeIDs) { batch.add(ContentProviderOperation.newDelete( EpisodeSearch.buildDocIdUri(String.valueOf(episodeID))).build()); } batch.add(ContentProviderOperation.newDelete(Shows.buildShowUri(showId)).build()); batch.add(ContentProviderOperation.newDelete(Seasons.buildSeasonsOfShowUri(showId)).build()); batch.add(ContentProviderOperation.newDelete(Episodes.buildEpisodesOfShowUri(showId)) .build()); try { context.getContentResolver().applyBatch(SeriesContract.CONTENT_AUTHORITY, batch); } catch (RemoteException e) { // Failed binder transactions aren't recoverable throw new RuntimeException("Problem applying batch operation", e); } catch (OperationApplicationException e) { // Failures like constraint violation aren't recoverable throw new RuntimeException("Problem applying batch operation", e); } } /** * Returns the episode IDs for a given show as a efficiently searchable * HashMap. * * @param seriesid * @return HashMap containing the shows existing episodes */ public static HashSet<Long> getEpisodeIDsForShow(String seriesid, Context context) { Cursor eptest = context.getContentResolver().query( Episodes.buildEpisodesOfShowUri(seriesid), new String[] { Episodes._ID }, null, null, null); HashSet<Long> episodeIDs = new HashSet<Long>(); eptest.moveToFirst(); while (!eptest.isAfterLast()) { episodeIDs.add(eptest.getLong(0)); eptest.moveToNext(); } eptest.close(); return episodeIDs; } /** * Returns the season IDs for a given show as a efficiently searchable * HashMap. * * @param seriesid * @return HashMap containing the shows existing seasons */ public static HashSet<Long> getSeasonIDsForShow(String seriesid, Context context) { Cursor setest = context.getContentResolver().query(Seasons.buildSeasonsOfShowUri(seriesid), new String[] { Seasons._ID }, null, null, null); HashSet<Long> seasonIDs = new HashSet<Long>(); while (setest.moveToNext()) { seasonIDs.add(setest.getLong(0)); } setest.close(); return seasonIDs; } /** * Creates a {@link ContentProviderOperation} for insert if isNew, or update * instead for with the given episode values. * * @param values * @param isNew * @return */ public static ContentProviderOperation buildEpisodeOp(ContentValues values, boolean isNew) { ContentProviderOperation op; if (isNew) { op = ContentProviderOperation.newInsert(Episodes.CONTENT_URI).withValues(values) .build(); } else { final String episodeId = values.getAsString(Episodes._ID); op = ContentProviderOperation.newUpdate(Episodes.buildEpisodeUri(episodeId)) .withValues(values).build(); } return op; } /** * Creates a {@link ContentProviderOperation} for insert if isNew, or update * instead for with the given season values. * * @param values * @param isNew * @return */ public static ContentProviderOperation buildSeasonOp(ContentValues values, boolean isNew) { ContentProviderOperation op; final String seasonId = values.getAsString(Seasons.REF_SEASON_ID); final ContentValues seasonValues = new ContentValues(); seasonValues.put(Seasons.COMBINED, values.getAsString(Episodes.SEASON)); if (isNew) { seasonValues.put(Seasons._ID, seasonId); seasonValues.put(Shows.REF_SHOW_ID, values.getAsString(Shows.REF_SHOW_ID)); op = ContentProviderOperation.newInsert(Seasons.CONTENT_URI).withValues(seasonValues) .build(); } else { op = ContentProviderOperation.newUpdate(Seasons.buildSeasonUri(seasonId)) .withValues(seasonValues).build(); } return op; } /** * Update the latest episode fields of the show where {@link Shows._ID} * equals the given {@code id}. * * @param id */ public static long updateLatestEpisode(Context context, String id) { final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); final boolean onlyFutureEpisodes = prefs.getBoolean( SeriesGuidePreferences.KEY_ONLY_FUTURE_EPISODES, false); final boolean onlySeasonEpisodes = prefs.getBoolean( SeriesGuidePreferences.KEY_ONLY_SEASON_EPISODES, false); final String[] projection = new String[] { Episodes._ID, Episodes.FIRSTAIRED, Episodes.SEASON, Episodes.NUMBER, Episodes.TITLE }; final String sortBy = Episodes.FIRSTAIRED + " ASC"; final StringBuilder selection = new StringBuilder(); String[] selectionArgs = null; selection.append(Episodes.WATCHED).append("=0"); if (onlySeasonEpisodes) { selection.append(" AND ").append(Episodes.SEASON).append("!=0"); } if (onlyFutureEpisodes) { selection.append(" AND ").append(Episodes.FIRSTAIRED).append(">=?"); Date date = new Date(); String today = Constants.theTVDBDateFormat.format(date); selectionArgs = new String[] { today }; } else { selection.append(" AND ").append(Episodes.FIRSTAIRED).append(" like '%-%'"); } final Cursor unwatched = context.getContentResolver().query( Episodes.buildEpisodesOfShowUri(id), projection, selection.toString(), selectionArgs, sortBy); // maybe there are no episodes due to errors, or airdates are just // unknown ("") long episodeid = 0; final ContentValues update = new ContentValues(); if (unwatched.getCount() != 0) { unwatched.moveToFirst(); // nexttext (0x12 Episode) final String season = unwatched.getString(unwatched .getColumnIndexOrThrow(Episodes.SEASON)); final String number = unwatched.getString(unwatched .getColumnIndexOrThrow(Episodes.NUMBER)); final String title = unwatched.getString(unwatched .getColumnIndexOrThrow(Episodes.TITLE)); String nextEpisodeString = Utils.getNextEpisodeString(prefs, season, number, title); // nextairdatetext String nextAirdateString = ""; final String firstAired = unwatched.getString(unwatched .getColumnIndexOrThrow(Episodes.FIRSTAIRED)); if (firstAired.length() != 0) { final Series show = getShow(context, id); if (show != null) { nextAirdateString += Utils.parseDateToLocalRelative(firstAired, show.getAirsTime(), context); } } episodeid = unwatched.getLong(unwatched.getColumnIndexOrThrow(Episodes._ID)); update.put(Shows.NEXTEPISODE, episodeid); update.put(Shows.NEXTAIRDATE, unwatched.getString(unwatched.getColumnIndexOrThrow(Episodes.FIRSTAIRED))); update.put(Shows.NEXTTEXT, nextEpisodeString); update.put(Shows.NEXTAIRDATETEXT, nextAirdateString); } else { update.put(Shows.NEXTEPISODE, ""); update.put(Shows.NEXTAIRDATE, UNKNOWN_NEXT_AIR_DATE); update.put(Shows.NEXTTEXT, ""); update.put(Shows.NEXTAIRDATETEXT, ""); } unwatched.close(); context.getContentResolver().update(Shows.buildShowUri(id), update, null, null); return episodeid; } }
package edu.rice.rubbos.servlets; import java.io.IOException; import java.net.URLEncoder; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class BrowseStoriesByCategory extends RubbosHttpServlet { public int getPoolSize() { return Config.BrowseCategoriesPoolSize; } private void closeConnection(PreparedStatement stmt, Connection conn) { try { if (stmt != null) stmt.close(); // close statement } catch (Exception ignore) { } try { if (conn != null) releaseConnection(conn); } catch (Exception ignore) { } } /** Build the html page for the response */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { ServletPrinter sp = null; PreparedStatement stmt = null; Connection conn = null; sp = new ServletPrinter(response, "BrowseStoriesByCategory"); String categoryName, username, categoryId, testpage, testnbOfStories; int page = 0, nbOfStories = 0; ResultSet rs = null; testpage = request.getParameter("page"); testnbOfStories = request.getParameter("nbOfStories"); if (testpage != null) { page = (Integer.valueOf(request.getParameter("page"))).intValue(); } if (testnbOfStories != null) { nbOfStories = (Integer.valueOf(request.getParameter("nbOfStories"))) .intValue(); } categoryId = request.getParameter("category"); categoryName = request.getParameter("categoryName"); if (categoryName == null) { sp.printHTML("Browse Stories By Category" + "You must provide a category name!<br>"); return; } if (categoryId == null) { sp.printHTML("Browse Stories By Category" + "You must provide a category identifier!<br>"); return; } if (page == 0) { page = 0; } if (nbOfStories == 0) { nbOfStories = 25; } sp.printHTMLheader("RUBBoS Browse Stories By Category"); sp.printHTML("<br><h2>Stories in category " + categoryName + "</h2><br>"); conn = getConnection(); try { stmt = conn.prepareStatement("SELECT * FROM stories WHERE category= " + categoryId + " ORDER BY date DESC LIMIT " + page * nbOfStories + "," + nbOfStories); rs = stmt.executeQuery(); } catch (Exception e) { sp.printHTML("Failed to execute Query for BrowseStoriesByCategory: " + e); closeConnection(stmt, conn); return; } try { if (!rs.first()) { if (page == 0) { sp .printHTML("<h2>Sorry, but there is no story available in this category !</h2>"); } else { sp .printHTML("<h2>Sorry, but there are no more stories available at this time.</h2><br>\n"); sp .printHTML("<p><CENTER>\n<a href=\"/rubbos/servlet/edu.rice.rubbos.servlets.BrowseStoriesByCategory?category=" + categoryId + "&categoryName=" + URLEncoder.encode(categoryName) + "&page=" + (page - 1) + "&nbOfStories="+nbOfStories+"\">Previous page</a>\n</CENTER>\n"); } sp.printHTMLfooter(); closeConnection(stmt, conn); return; } do { String title = rs.getString("title"); String date = rs.getString("date"); username = rs.getString("writer"); int id = rs.getInt("id"); sp .printHTML("<a href=\"/rubbos/servlet/edu.rice.rubbos.servlets.ViewStory?storyId=" + id + "\">" + title + "</a> by " + username + " on " + date + "<br>\n"); } while (rs.next()); } catch (Exception e) { sp.printHTML("Exception getting categories: " + e + "<br>"); } closeConnection(stmt, conn); if (page == 0) sp .printHTML("<p><CENTER>\n<a href=\"/rubbos/servlet/edu.rice.rubbos.servlets.BrowseStoriesByCategory?category=" + categoryId + "&categoryName=" + URLEncoder.encode(categoryName) + "&page=" + (page + 1) + "&nbOfStories="+nbOfStories+"\">Next page</a>\n</CENTER>\n"); else sp .printHTML("<p><CENTER>\n<a href=\"/rubbos/servlet/edu.rice.rubbos.servlets.BrowseStoriesByCategory?category=" + categoryId + "&categoryName=" + URLEncoder.encode(categoryName) + "&page=" + (page - 1) + "&nbOfStories="+nbOfStories+"\">Previous page</a>\n&nbsp&nbsp&nbsp" + "<a href=\"/rubbos/servlet/edu.rice.rubbos.servlets.BrowseStoriesByCategory?category=" + categoryId + "&categoryName=" + URLEncoder.encode(categoryName) + "&page=" + (page + 1) + "&nbOfStories="+nbOfStories+"\">Next page</a>\n\n</CENTER>\n"); sp.printHTMLfooter(); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { doGet(request, response); } }
package no.uio.ifi.alboc.syntax; /* * module Syntax */ import com.sun.org.apache.bcel.internal.generic.RETURN; import no.uio.ifi.alboc.alboc.AlboC; import no.uio.ifi.alboc.code.Code; import no.uio.ifi.alboc.error.Error; import no.uio.ifi.alboc.log.Log; import no.uio.ifi.alboc.scanner.Scanner; import no.uio.ifi.alboc.scanner.Token; import static no.uio.ifi.alboc.scanner.Token.*; import no.uio.ifi.alboc.types.*; /* * Creates a syntax tree by parsing an AlboC program; * prints the parse tree (if requested); * checks it; * generates executable code. */ public class Syntax { static DeclList library; static Program program; public static void init() { // -- Must be changed in part 1+2: } public static void finish() { // -- Must be changed in part 1+2: } public static void checkProgram() { program.check(library); } public static void genCode() { program.genCode(null); } public static void parseProgram() { program = Program.parse(); } public static void printProgram() { program.printTree(); } } /* * Super class for all syntactic units. (This class is not mentioned in the * syntax diagrams.) */ abstract class SyntaxUnit { int lineNum; SyntaxUnit() { lineNum = Scanner.curLine; } abstract void check(DeclList curDecls); abstract void genCode(FuncDecl curFunc); abstract void printTree(); void error(String message) { Error.error(lineNum, message); } } /* * A <program> */ class Program extends SyntaxUnit { DeclList progDecls; @Override void check(DeclList curDecls) { progDecls.check(curDecls); if (!AlboC.noLink) { // Check that 'main' has been declared properly: // -- Must be changed in part 2: } } @Override void genCode(FuncDecl curFunc) { progDecls.genCode(null); } static Program parse() { Log.enterParser("<program>"); Program p = new Program(); p.progDecls = GlobalDeclList.parse(); if (Scanner.curToken != eofToken) Error.expected("A declaration"); Log.leaveParser("</program>"); return p; } @Override void printTree() { progDecls.printTree(); } } /* * A declaration list. (This class is not mentioned in the syntax diagrams.) */ abstract class DeclList extends SyntaxUnit { Declaration firstDecl = null; DeclList outerScope; DeclList() { // -- Must be changed in part 1: } @Override void check(DeclList curDecls) { outerScope = curDecls; Declaration dx = firstDecl; while (dx != null) { dx.check(this); dx = dx.nextDecl; } } @Override void printTree() { // -- Must be changed in part 1: Declaration currDecl = firstDecl; while(currDecl != null){ currDecl.printTree(); currDecl = currDecl.nextDecl; } } void addDecl(Declaration d) { // -- Must be changed in part 1: if(firstDecl == null){ firstDecl = d; } else{ Declaration prevDecl = firstDecl; while(prevDecl.nextDecl != null) prevDecl = prevDecl.nextDecl; prevDecl.nextDecl = d; } } int dataSize() { Declaration dx = firstDecl; int res = 0; while (dx != null) { res += dx.declSize(); dx = dx.nextDecl; } return res; } Declaration findDecl(String name, SyntaxUnit use) { // -- Must be changed in part 2: return null; } } /* * A list of global declarations. (This class is not mentioned in the syntax * diagrams.) */ class GlobalDeclList extends DeclList { @Override void genCode(FuncDecl curFunc) { // -- Must be changed in part 2: } static GlobalDeclList parse() { GlobalDeclList gdl = new GlobalDeclList(); while (Scanner.curToken == intToken) { DeclType ts = DeclType.parse(); gdl.addDecl(Declaration.parse(ts)); } return gdl; } } /* * A list of local declarations. (This class is not mentioned in the syntax * diagrams.) */ class LocalDeclList extends DeclList { @Override void genCode(FuncDecl curFunc) { // -- Must be changed in part 2: } static LocalDeclList parse() { // -- Must be changed in part 1: LocalDeclList ldl = new LocalDeclList(); while(Scanner.curToken == intToken){ DeclType ts = DeclType.parse(); ldl.addDecl(Declaration.parse(ts)); } return ldl; } } /* * A list of parameter declarations. (This class is not mentioned in the syntax * diagrams.) */ class ParamDeclList extends DeclList { @Override void genCode(FuncDecl curFunc) { // -- Must be changed in part 2: } static ParamDeclList parse() { // -- Must be changed in part 1: ParamDeclList pdl = new ParamDeclList(); while(Scanner.curToken == intToken){ DeclType ts = DeclType.parse(); pdl.addDecl(Declaration.parse(ts)); } return pdl; } @Override void printTree() { Declaration px = firstDecl; while (px != null) { px.printTree(); px = px.nextDecl; if (px != null) Log.wTree(", "); } } } /* * A <type> */ class DeclType extends SyntaxUnit { int numStars = 0; Type type; @Override void check(DeclList curDecls) { type = Types.intType; for (int i = 1; i <= numStars; ++i) type = new PointerType(type); } @Override void genCode(FuncDecl curFunc) { } static DeclType parse() { Log.enterParser("<type>"); DeclType dt = new DeclType(); Scanner.skip(intToken); while (Scanner.curToken == starToken) { ++dt.numStars; Scanner.readNext(); } Log.leaveParser("</type>"); return dt; } @Override void printTree() { Log.wTree("int"); for (int i = 1; i <= numStars; ++i) Log.wTree("*"); } } /* * Any kind of declaration. */ abstract class Declaration extends SyntaxUnit { String name, assemblerName; DeclType typeSpec; Type type; boolean visible = false; Declaration nextDecl = null; Declaration(String n) { name = n; } abstract int declSize(); static Declaration parse(DeclType dt) { Declaration d = null; if (Scanner.curToken == nameToken && Scanner.nextToken == leftParToken) { d = FuncDecl.parse(dt); } else if (Scanner.curToken == nameToken) { d = GlobalVarDecl.parse(dt); } else { Error.expected("A declaration name"); } d.typeSpec = dt; return d; } abstract void checkWhetherVariable(SyntaxUnit use); /** * checkWhetherFunction: Utility method to check whether this Declaration is * really a function. * * @param nParamsUsed * Number of parameters used in the actual call. (The method will * give an error message if the function was used with too many * or too few parameters.) * @param use * From where is the check performed? * @see checkWhetherVariable */ abstract void checkWhetherFunction(int nParamsUsed, SyntaxUnit use); } /* * A <var decl> */ abstract class VarDecl extends Declaration { boolean isArray = false; int numElems = 0; VarDecl(String n) { super(n); } @Override void check(DeclList curDecls) { // -- Must be changed in part 2: } @Override void printTree() { // -- Must be changed in part 1: } @Override int declSize() { return type.size(); } @Override void checkWhetherFunction(int nParamsUsed, SyntaxUnit use) { use.error(name + " is a variable and no function!"); } @Override void checkWhetherVariable(SyntaxUnit use) { } } /* * A global <var decl>. */ class GlobalVarDecl extends VarDecl { GlobalVarDecl(String n) { super(n); assemblerName = (AlboC.underscoredGlobals() ? "_" : "") + n; } @Override void genCode(FuncDecl curFunc) { // -- Must be changed in part 2: } static GlobalVarDecl parse(DeclType dt) { Log.enterParser("<var decl>"); // -- Must be changed in part 1: return null; } } /* * A local variable declaration */ class LocalVarDecl extends VarDecl { LocalVarDecl(String n) { super(n); } @Override void genCode(FuncDecl curFunc) { // -- Must be changed in part 2: } static LocalVarDecl parse(DeclType dt) { Log.enterParser("<var decl>"); // -- Must be changed in part 1: return null; } } /* * A <param decl> */ class ParamDecl extends VarDecl { ParamDecl(String n) { super(n); } @Override void genCode(FuncDecl curFunc) { // -- Must be changed in part 2: } static ParamDecl parse(DeclType dt) { Log.enterParser("<param decl>"); // -- Must be changed in part 1: return null; } @Override void printTree() { typeSpec.printTree(); Log.wTree(" " + name); } } /* * A <func decl> */ class FuncDecl extends Declaration { ParamDeclList funcParams; String exitLabel; FuncDecl(String n) { // Used for user functions: super(n); assemblerName = (AlboC.underscoredGlobals() ? "_" : "") + n; // -- Must be changed in part 1: } @Override int declSize() { return 0; } @Override void check(DeclList curDecls) { // -- Must be changed in part 2: } @Override void checkWhetherFunction(int nParamsUsed, SyntaxUnit use) { // -- Must be changed in part 2: } @Override void checkWhetherVariable(SyntaxUnit use) { // -- Must be changed in part 2: } @Override void genCode(FuncDecl curFunc) { // -- Must be changed in part 2: } static FuncDecl parse(DeclType ts) { // -- Must be changed in part 1: return null; } @Override void printTree() { // -- Must be changed in part 1: } } /* * A <statm list>. */ class StatmList extends SyntaxUnit { // -- Must be changed in part 1: Statement first = null; @Override void check(DeclList curDecls) { // -- Must be changed in part 2: } @Override void genCode(FuncDecl curFunc) { // -- Must be changed in part 2: } static StatmList parse() { Log.enterParser("<statm list>"); StatmList sl = new StatmList(); Statement lastStatm = null; while (Scanner.curToken != rightCurlToken) { // -- Must be changed in part 1: if(sl.first == null){ sl.first = Statement.parse(); } else{ lastStatm = sl.first; while(lastStatm.nextStatm != null){ lastStatm = lastStatm.nextStatm; } lastStatm.nextStatm = Statement.parse(); } } Scanner.skip(rightCurlToken); Log.leaveParser("</statm list>"); return sl; } @Override void printTree() { // -- Must be changed in part 1: Statement currStatm = first; while(currStatm != null){ currStatm.printTree(); currStatm = currStatm.nextStatm; } } } /* * A <statement>. */ abstract class Statement extends SyntaxUnit { Statement nextStatm = null; static Statement parse() { Log.enterParser("<statement>"); Statement s = null; if (Scanner.curToken == nameToken && Scanner.nextToken == leftParToken) { // -- Must be changed in part 1: s = CallStatm.parse(); } else if (Scanner.curToken == nameToken || Scanner.curToken == starToken) { // -- Must be changed in part 1: s = AssignStatm.parse(); } else if (Scanner.curToken == forToken) { // -- Must be changed in part 1: s = ForStatm.parse(); } else if (Scanner.curToken == ifToken) { s = IfStatm.parse(); } else if (Scanner.curToken == returnToken) { // -- Must be changed in part 1: s = ReturnStatm.parse(); } else if (Scanner.curToken == whileToken) { s = WhileStatm.parse(); } else if (Scanner.curToken == semicolonToken) { s = EmptyStatm.parse(); } else { Error.expected("A statement"); } Log.leaveParser("</statement>"); return s; } } /* * An <call-statm>. */ class CallStatm extends Statement { // -- Must be changed in part 1+2: @Override void check(DeclList curDecls) { // -- Must be changed in part 2: } @Override void genCode(FuncDecl curFunc) { // -- Must be changed in part 2: } static CallStatm parse() { // -- Must be changed in part 1: return null; } @Override void printTree() { // -- Must be changed in part 1: } } /* * An <empty statm>. */ class EmptyStatm extends Statement { // -- Must be changed in part 1+2: @Override void check(DeclList curDecls) { // -- Must be changed in part 2: } @Override void genCode(FuncDecl curFunc) { // -- Must be changed in part 2: } static EmptyStatm parse() { // -- Must be changed in part 1: EmptyStatm es = new EmptyStatm(); Log.enterParser("<empty-statm>"); Scanner.skip(semicolonToken); Log.leaveParser("</empty-statm>"); return es; } @Override void printTree() { // -- Must be changed in part 1: } } /* * A <for-statm>. */ class ForStatm extends Statement { // -- Must be changed in part 1+2: ForControl control; StatmList statmlist; @Override void check(DeclList curDecls) { // -- Must be changed in part 2: } @Override void genCode(FuncDecl curFunc) { // -- Must be changed in part 2: } static ForStatm parse() { // -- Must be changed in part 1: Log.enterParser("<for-statm>"); ForStatm fs = new ForStatm(); Scanner.skip(forToken); Scanner.skip(leftParToken); fs.control = ForControl.parse(); Scanner.skip(rightParToken); Scanner.skip(leftCurlToken); fs.statmlist = StatmList.parse(); Scanner.skip(rightCurlToken); Log.leaveParser("</for-statm>"); return fs; } @Override void printTree() { // -- Must be changed in part 1: Log.wTree("for ("); control.printTree(); Log.wTreeLn(") {"); Log.indentTree(); statmlist.printTree(); Log.outdentTree(); Log.wTreeLn("}"); } } /* * a <for-control> */ class ForControl extends Statement { // -- Must be changed in part 1+2: Expression e; Assignment first, second; @Override void check(DeclList curDecls) { // -- Must be changed in part 2: } @Override void genCode(FuncDecl curFunc) { // -- Must be changed in part 2: } static ForControl parse() { // -- Must be changed in part 1: ForControl fc = new ForControl(); // Usikker om dette trengs? Greit aa dobbeltsjekke kanskje? if(Scanner.curToken == nameToken || Scanner.curToken == starToken){ fc.first = Assignment.parse(); } Scanner.skip(semicolonToken); fc.e = Expression.parse(); Scanner.skip(semicolonToken); if(Scanner.curToken == nameToken || Scanner.curToken == starToken){ fc.second = Assignment.parse(); } return fc; } @Override void printTree() { // -- Must be changed in part 1: first.printTree(); Log.wTree(";"); e.printTree(); Log.wTree("}"); second.printTree(); } } /* * An <if-statm>. */ class IfStatm extends Statement { // -- Must be changed in part 1+2: Expression e; StatmList ifList; StatmList elseList; @Override void check(DeclList curDecls) { // -- Must be changed in part 2: } @Override void genCode(FuncDecl curFunc) { // -- Must be changed in part 2: } static IfStatm parse() { // -- Must be changed in part 1: Log.enterParser("<if-statm>"); IfStatm is = new IfStatm(); Scanner.skip(ifToken); Scanner.skip(leftParToken); is.e = Expression.parse(); Scanner.skip(rightParToken); Scanner.skip(leftCurlToken); is.ifList = StatmList.parse(); Scanner.skip(rightCurlToken); if(Scanner.curToken == Token.elseToken){ Log.enterParser("<else-part>"); Scanner.skip(elseToken); Scanner.skip(leftCurlToken); is.elseList = StatmList.parse(); Scanner.skip(rightCurlToken); Log.leaveParser("</else-part>"); } Log.leaveParser("</if-statm>"); return is; } @Override void printTree() { // -- Must be changed in part 1: Log.wTree("if ("); e.printTree(); Log.wTreeLn(") {"); Log.indentTree(); ifList.printTree(); Log.outdentTree(); Log.wTreeLn("}"); if(elseList != null) { Log.wTreeLn("else {"); Log.indentTree(); elseList.printTree(); Log.outdentTree(); Log.wTreeLn("}"); } } } /* * A <return-statm>. */ class ReturnStatm extends Statement{ // -- mUST BE CHANGED IN PART 1+2 Expression e; @Override void check(DeclList curDecls) { // -- Must be changed in part 2: } @Override void genCode(FuncDecl curFunc) { // -- Must be changed in part 2: } static ReturnStatm parse() { // -- Must be changed in part 1: Log.enterParser("<return-statm>"); ReturnStatm rs = new ReturnStatm(); Scanner.skip(returnToken); rs.e = Expression.parse(); Scanner.skip(semicolonToken); Log.leaveParser("</return-statm>"); return rs; } @Override void printTree() { // -- Must be changed in part 1: Log.wTree("return "); e.printTree(); Log.wTree(";"); } } /* * A <while-statm>. */ class WhileStatm extends Statement { Expression test; StatmList body; @Override void check(DeclList curDecls) { test.check(curDecls); body.check(curDecls); Log.noteTypeCheck("while (t) ...", test.type, "t", lineNum); if (test.type instanceof ValueType) { } else { error("While-test must be a value."); } } @Override void genCode(FuncDecl curFunc) { String testLabel = Code.getLocalLabel(), endLabel = Code .getLocalLabel(); Code.genInstr(testLabel, "", "", "Start while-statement"); test.genCode(curFunc); Code.genInstr("", "cmpl", "$0,%eax", ""); Code.genInstr("", "je", endLabel, ""); body.genCode(curFunc); Code.genInstr("", "jmp", testLabel, ""); Code.genInstr(endLabel, "", "", "End while-statement"); } static WhileStatm parse() { Log.enterParser("<while-statm>"); WhileStatm ws = new WhileStatm(); Scanner.skip(whileToken); Scanner.skip(leftParToken); ws.test = Expression.parse(); Scanner.skip(rightParToken); Scanner.skip(leftCurlToken); ws.body = StatmList.parse(); Scanner.skip(rightCurlToken); Log.leaveParser("</while-statm>"); return ws; } @Override void printTree() { Log.wTree("while ("); test.printTree(); Log.wTreeLn(") {"); Log.indentTree(); body.printTree(); Log.outdentTree(); Log.wTreeLn("}"); } } /* * An <Lhs-variable> */ class LhsVariable extends SyntaxUnit { int numStars = 0; Variable var; Type type; @Override void check(DeclList curDecls) { var.check(curDecls); type = var.type; for (int i = 1; i <= numStars; ++i) { Type e = type.getElemType(); if (e == null) error("Type error in left-hand side variable!"); type = e; } } @Override void genCode(FuncDecl curFunc) { var.genAddressCode(curFunc); for (int i = 1; i <= numStars; ++i) Code.genInstr("", "movl", "(%eax),%eax", " *"); } static LhsVariable parse() { Log.enterParser("<lhs-variable>"); LhsVariable lhs = new LhsVariable(); while (Scanner.curToken == starToken) { ++lhs.numStars; Scanner.skip(starToken); } Scanner.check(nameToken); lhs.var = Variable.parse(); Log.leaveParser("</lhs-variable>"); return lhs; } @Override void printTree() { for (int i = 1; i <= numStars; ++i) Log.wTree("*"); var.printTree(); } } /* * An <assign-statm> */ class AssignStatm extends Statement{ // -- mUST BE CHANGED IN PART 1+2 Assignment a; @Override void check(DeclList curDecls) { // -- Must be changed in part 2: } @Override void genCode(FuncDecl curFunc) { // -- Must be changed in part 2: } static AssignStatm parse() { // -- Must be changed in part 1: Log.enterParser("<assign-statm>"); AssignStatm as = new AssignStatm(); as.a = Assignment.parse(); Scanner.skip(semicolonToken); return as; } @Override void printTree() { // -- Must be changed in part 1: a.printTree(); Log.wTree(";"); } } /* * An <assignment> */ class Assignment extends Statement{ // -- mUST BE CHANGED IN PART 1+2 Expression e; LhsVariable lhs; @Override void check(DeclList curDecls) { // -- Must be changed in part 2: } @Override void genCode(FuncDecl curFunc) { // -- Must be changed in part 2: } static Assignment parse() { // -- Must be changed in part 1: Log.enterParser("<assignment>"); Assignment ass = new Assignment(); ass.lhs = LhsVariable.parse(); Scanner.skip(assignToken); ass.e = Expression.parse(); Log.leaveParser("</assignment>"); return ass; } @Override void printTree() { // -- Must be changed in part 1: lhs.printTree(); Log.wTree("="); e.printTree(); } } /* * An <expression list>. */ class ExprList extends SyntaxUnit { Expression firstExpr = null; @Override void check(DeclList curDecls) { // -- Must be changed in part 2: } @Override void genCode(FuncDecl curFunc) { // -- Must be changed in part 2: } static ExprList parse() { Expression lastExpr = null; Log.enterParser("<expr list>"); // -- Must be changed in part 1: return null; } @Override void printTree() { // -- Must be changed in part 1: } // -- Must be changed in part 1: } /* * An <expression> */ class Expression extends SyntaxUnit { Expression nextExpr = null; Term firstTerm, secondTerm = null; Operator relOpr = null; Type type = null; @Override void check(DeclList curDecls) { // -- Must be changed in part 2: } @Override void genCode(FuncDecl curFunc) { // -- Must be changed in part 2: } static Expression parse() { Log.enterParser("<expression>"); Expression e = new Expression(); e.firstTerm = Term.parse(); if (Token.isRelOperator(Scanner.curToken)) { e.relOpr = RelOpr.parse(); e.secondTerm = Term.parse(); } Log.leaveParser("</expression>"); return e; } @Override void printTree() { // -- Must be changed in part 1: } } /* * A <term> */ class Term extends SyntaxUnit { // -- Must be changed in part 1+2: @Override void check(DeclList curDecls) { // -- Must be changed in part 2: } @Override void genCode(FuncDecl curFunc) { // -- Must be changed in part 2: } static Term parse() { // -- Must be changed in part 1: return null; } @Override void printTree() { // -- Must be changed in part 1: } } /* * A <factor> */ class Factor extends Term { // -- Must be changed in part 1+2: @Override void check(DeclList curDecls) { // -- Must be changed in part 2: } @Override void genCode(FuncDecl curFunc) { // -- Must be changed in part 2: } static Factor parse() { // -- Must be changed in part 1: return null; } @Override void printTree() { // -- Must be changed in part 1: } } /* * A <primary> */ class Primary extends SyntaxUnit { // -- Must be changed in part 1+2: @Override void check(DeclList curDecls) { // -- Must be changed in part 2: } @Override void genCode(FuncDecl curFunc) { // -- Must be changed in part 2: } static Primary parse() { // -- Must be changed in part 1: return null; } @Override void printTree() { // -- Must be changed in part 1: } } /* * An <operator> */ abstract class Operator extends SyntaxUnit { Operator nextOpr = null; Token oprToken; @Override void check(DeclList curDecls) { } // Never needed. } /* * A <term opr> (+ or -) */ class TermOpr extends Operator{ @Override void genCode(FuncDecl curFunc){ // PART 2 } static TermOpr parse(){ // PART 1 return null; } @Override void printTree(){ // MUST BE CHANGED IN PART 1 } } /* * A <factor opr> (* or /) */ class FactorOpr extends Operator{ @Override void genCode(FuncDecl curFunc){ // PART 2 } static FactorOpr parse(){ // PART 1 return null; } @Override void printTree(){ // MUST BE CHANGED IN PART 1 } } /* * A <prefix opr> (- or *) */ class PrefixOpr extends Operator{ @Override void genCode(FuncDecl curFunc){ // PART 2 } static PrefixOpr parse(){ // PART 1 return null; } @Override void printTree(){ // MUST BE CHANGED IN PART 1 } } /* * A <rel opr> (==, !=, <, <=, > or >=). */ class RelOpr extends Operator { @Override void genCode(FuncDecl curFunc) { Code.genInstr("", "popl", "%ecx", ""); Code.genInstr("", "cmpl", "%eax,%ecx", ""); Code.genInstr("", "movl", "$0,%eax", ""); switch (oprToken) { case equalToken: Code.genInstr("", "sete", "%al", "Test =="); break; case notEqualToken: Code.genInstr("", "setne", "%al", "Test !="); break; case lessToken: Code.genInstr("", "setl", "%al", "Test <"); break; case lessEqualToken: Code.genInstr("", "setle", "%al", "Test <="); break; case greaterToken: Code.genInstr("", "setg", "%al", "Test >"); break; case greaterEqualToken: Code.genInstr("", "setge", "%al", "Test >="); break; } } static RelOpr parse() { Log.enterParser("<rel opr>"); RelOpr ro = new RelOpr(); ro.oprToken = Scanner.curToken; Scanner.readNext(); Log.leaveParser("</rel opr>"); return ro; } @Override void printTree() { String op = "?"; switch (oprToken) { case equalToken: op = "=="; break; case notEqualToken: op = "!="; break; case lessToken: op = "<"; break; case lessEqualToken: op = "<="; break; case greaterToken: op = ">"; break; case greaterEqualToken: op = ">="; break; } Log.wTree(" " + op + " "); } } /* * An <operand> */ abstract class Operand extends SyntaxUnit { Operand nextOperand = null; Type type; static Operand parse() { Log.enterParser("<operand>"); Operand o = null; if (Scanner.curToken == numberToken) { o = Number.parse(); } else if (Scanner.curToken == nameToken && Scanner.nextToken == leftParToken) { o = FunctionCall.parse(); } else if (Scanner.curToken == nameToken) { o = Variable.parse(); } else if (Scanner.curToken == ampToken) { o = Address.parse(); } else if (Scanner.curToken == leftParToken) { o = InnerExpr.parse(); } else { Error.expected("An operand"); } Log.leaveParser("</operand>"); return o; } } /* * A <function call>. */ class FunctionCall extends Operand { // -- Must be changed in part 1+2: @Override void check(DeclList curDecls) { // -- Must be changed in part 2: } @Override void genCode(FuncDecl curFunc) { // -- Must be changed in part 2: } static FunctionCall parse() { // -- Must be changed in part 1: return null; } @Override void printTree() { // -- Must be changed in part 1: } // -- Must be changed in part 1+2: } /* * A <number>. */ class Number extends Operand { int numVal; @Override void check(DeclList curDecls) { // -- Must be changed in part 2: } @Override void genCode(FuncDecl curFunc) { Code.genInstr("", "movl", "$" + numVal + ",%eax", "" + numVal); } static Number parse() { // -- Must be changed in part 1: return null; } @Override void printTree() { Log.wTree("" + numVal); } } /* * A <variable>. */ class Variable extends Operand { String varName; VarDecl declRef = null; Expression index = null; @Override void check(DeclList curDecls) { Declaration d = curDecls.findDecl(varName, this); d.checkWhetherVariable(this); declRef = (VarDecl) d; if (index == null) { type = d.type; } else { index.check(curDecls); Log.noteTypeCheck("a[e]", d.type, "a", index.type, "e", lineNum); if (index.type == Types.intType) { } else { error("Only integers may be used as index."); } if (d.type.mayBeIndexed()) { } else { error("Only arrays and pointers may be indexed."); } type = d.type.getElemType(); } } @Override void genCode(FuncDecl curFunc) { // -- Must be changed in part 2: } void genAddressCode(FuncDecl curFunc) { // Generate code to load the _address_ of the variable // rather than its value. if (index == null) { Code.genInstr("", "leal", declRef.assemblerName + ",%eax", varName); } else { index.genCode(curFunc); if (declRef.type instanceof ArrayType) { Code.genInstr("", "leal", declRef.assemblerName + ",%edx", varName + "[...]"); } else { Code.genInstr("", "movl", declRef.assemblerName + ",%edx", varName + "[...]"); } Code.genInstr("", "leal", "(%edx,%eax,4),%eax", ""); } } static Variable parse() { Log.enterParser("<variable>"); // -- Must be changed in part 1: return null; } @Override void printTree() { // -- Must be changed in part 1: } } /* * An <address>. */ class Address extends Operand { Variable var; @Override void check(DeclList curDecls) { var.check(curDecls); type = new PointerType(var.type); } @Override void genCode(FuncDecl curFunc) { var.genAddressCode(curFunc); } static Address parse() { Log.enterParser("<address>"); Address a = new Address(); Scanner.skip(ampToken); a.var = Variable.parse(); Log.leaveParser("</address>"); return a; } @Override void printTree() { Log.wTree("&"); var.printTree(); } } /* * An <inner expr>. */ class InnerExpr extends Operand { Expression expr; @Override void check(DeclList curDecls) { expr.check(curDecls); type = expr.type; } @Override void genCode(FuncDecl curFunc) { expr.genCode(curFunc); } static InnerExpr parse() { Log.enterParser("<inner expr>"); InnerExpr ie = new InnerExpr(); Scanner.skip(leftParToken); ie.expr = Expression.parse(); Scanner.skip(rightParToken); Log.leaveParser("</inner expr>"); return ie; } @Override void printTree() { Log.wTree("("); expr.printTree(); Log.wTree(")"); } }
package org.rabix.engine; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import org.rabix.bindings.helper.URIHelper; import org.rabix.bindings.model.ApplicationPort; import org.rabix.bindings.model.Context; import org.rabix.bindings.model.Job; import org.rabix.bindings.model.Job.JobStatus; import org.rabix.bindings.model.dag.DAGLinkPort.LinkPortType; import org.rabix.bindings.model.dag.DAGNode; import org.rabix.common.helper.CloneHelper; import org.rabix.common.helper.InternalSchemaHelper; import org.rabix.engine.db.DAGNodeDB; import org.rabix.engine.model.ContextRecord; import org.rabix.engine.model.JobRecord; import org.rabix.engine.model.VariableRecord; import org.rabix.engine.service.ContextRecordService; import org.rabix.engine.service.JobRecordService; import org.rabix.engine.service.VariableRecordService; public class JobHelper { public static String generateId() { return UUID.randomUUID().toString(); } public static Set<Job> createReadyJobs(JobRecordService jobRecordService, VariableRecordService variableRecordService, ContextRecordService contextRecordService, DAGNodeDB dagNodeDB, String contextId) { Set<Job> jobs = new HashSet<>(); List<JobRecord> jobRecords = jobRecordService.findReady(contextId); if (!jobRecords.isEmpty()) { for (JobRecord job : jobRecords) { jobs.add(createJob(job, JobStatus.READY, jobRecordService, variableRecordService, contextRecordService, dagNodeDB)); } } return jobs; } public static Job createJob(JobRecord job, JobStatus status, JobRecordService jobRecordService, VariableRecordService variableRecordService, ContextRecordService contextRecordService, DAGNodeDB dagNodeDB) { DAGNode node = dagNodeDB.get(InternalSchemaHelper.normalizeId(job.getId()), job.getRootId()); boolean autoBoxingEnabled = true; // get from configuration Map<String, Object> inputs = new HashMap<>(); List<VariableRecord> inputVariables = variableRecordService.find(job.getId(), LinkPortType.INPUT, job.getRootId()); for (VariableRecord inputVariable : inputVariables) { Object value = CloneHelper.deepCopy(inputVariable.getValue()); ApplicationPort port = node.getApp().getInput(inputVariable.getPortId()); if (port != null && autoBoxingEnabled) { if (port.isList() && !(value instanceof List)) { List<Object> transformed = new ArrayList<>(); transformed.add(value); value = transformed; } } inputs.put(inputVariable.getPortId(), value); } ContextRecord contextRecord = contextRecordService.find(job.getRootId()); Context context = new Context(job.getRootId(), contextRecord.getConfig()); String encodedApp = URIHelper.createDataURI(node.getApp().serialize()); return new Job(job.getExternalId(), job.getParentId(), job.getRootId(), job.getId(), encodedApp, status, inputs, null, context, null); } public static Job fillOutputs(Job job, JobRecordService jobRecordService, VariableRecordService variableRecordService) { JobRecord jobRecord = jobRecordService.findRoot(job.getContext().getId()); List<VariableRecord> outputVariables = variableRecordService.find(jobRecord.getId(), LinkPortType.OUTPUT, job.getContext().getId()); Map<String, Object> outputs = new HashMap<>(); for (VariableRecord outputVariable : outputVariables) { outputs.put(outputVariable.getPortId(), outputVariable.getValue()); } return Job.cloneWithOutputs(job, outputs); } }
package com.validation.manager.core.db; import java.io.Serializable; import java.util.List; import javax.persistence.Column; import javax.persistence.EmbeddedId; import javax.persistence.Entity; import javax.persistence.JoinColumn; import javax.persistence.JoinColumns; import javax.persistence.Lob; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Table; import javax.validation.constraints.Size; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; import org.codehaus.jackson.annotate.JsonIgnore; /** * * @author Javier A. Ortiz Bultron <[email protected]> */ @Entity @Table(name = "step") @XmlRootElement @NamedQueries({ @NamedQuery(name = "Step.findAll", query = "SELECT s FROM Step s"), @NamedQuery(name = "Step.findByStepSequence", query = "SELECT s FROM Step s WHERE s.stepSequence = :stepSequence"), @NamedQuery(name = "Step.findByTestCaseTestId", query = "SELECT s FROM Step s WHERE s.stepPK.testCaseTestId = :testCaseTestId"), @NamedQuery(name = "Step.findById", query = "SELECT s FROM Step s WHERE s.stepPK.id = :id"), @NamedQuery(name = "Step.findByTestCaseId", query = "SELECT s FROM Step s WHERE s.stepPK.testCaseId = :testCaseId")}) public class Step implements Serializable { private static final long serialVersionUID = 1L; @EmbeddedId protected StepPK stepPK; @Lob @Column(name = "expected_result") private byte[] expectedResult; @Lob @Size(max = 2147483647) @Column(name = "notes") private String notes; @Column(name = "step_sequence") private Integer stepSequence; @Lob @Column(name = "text") private byte[] text; @ManyToMany(mappedBy = "stepList") private List<VmException> vmExceptionList; @ManyToMany(mappedBy = "stepList") private List<Requirement> requirementList; @JoinColumns({ @JoinColumn(name = "test_case_id", referencedColumnName = "id", insertable = false, updatable = false), @JoinColumn(name = "test_case_test_id", referencedColumnName = "test_id", insertable = false, updatable = false)}) @ManyToOne(optional = false) private TestCase testCase; public Step() { } public Step(StepPK stepPK) { this.stepPK = stepPK; } public Step(StepPK stepPK, int stepSequence, byte[] text) { this.stepPK = stepPK; this.stepSequence = stepSequence; this.text = text; } public Step(int testCaseId, int testCaseTestId) { this.stepPK = new StepPK(testCaseId, testCaseTestId); } public StepPK getStepPK() { return stepPK; } public void setStepPK(StepPK stepPK) { this.stepPK = stepPK; } public byte[] getExpectedResult() { return expectedResult; } public void setExpectedResult(byte[] expectedResult) { this.expectedResult = expectedResult; } public String getNotes() { return notes; } public void setNotes(String notes) { this.notes = notes; } public Integer getStepSequence() { return stepSequence; } public void setStepSequence(Integer stepSequence) { this.stepSequence = stepSequence; } public byte[] getText() { return text; } public void setText(byte[] text) { this.text = text; } @XmlTransient @JsonIgnore public List<VmException> getVmExceptionList() { return vmExceptionList; } public void setVmExceptionList(List<VmException> vmExceptionList) { this.vmExceptionList = vmExceptionList; } @XmlTransient @JsonIgnore public List<Requirement> getRequirementList() { return requirementList; } public void setRequirementList(List<Requirement> requirementList) { this.requirementList = requirementList; } public TestCase getTestCase() { return testCase; } public void setTestCase(TestCase testCase) { this.testCase = testCase; } @Override public int hashCode() { int hash = 0; hash += (stepPK != null ? stepPK.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Step)) { return false; } Step other = (Step) object; return (this.stepPK != null || other.stepPK == null) && (this.stepPK == null || this.stepPK.equals(other.stepPK)); } @Override public String toString() { return "com.validation.manager.core.db.Step[ stepPK=" + stepPK + " ]"; } }
package com.example.arkflash; import com.example.arkslash.R; import android.content.res.Resources; public class arcflashResult { private int id; public int getId() { return id; } public void setId(int id) { this.id = id; } private String title; private double lineVoltage; private double transformerKva; private int equipmentType; private double transformerZ; private double faultToleranceTime; private int grounding; private double incidentEnergy; private double ea18; private double ea12; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public double getIncidentEnergy() { return incidentEnergy; } public void setIncidentEnergy(double incidentEnergy) { this.incidentEnergy = incidentEnergy; } public double getEa18() { return ea18; } public void setEa18(double ea18) { this.ea18 = ea18; } public double getEa12() { return ea12; } public void setEa12(double ea12) { this.ea12 = ea12; } public double getLineVoltage() { return lineVoltage; } public void setLineVoltage(double lineVoltage) { this.lineVoltage = lineVoltage; } public double getTransformerKva() { return transformerKva; } public void setTransformerKva(double transformerKva) { this.transformerKva = transformerKva; } public int getEquipmentType() { return equipmentType; } public String getEquipmentTypeString() { switch (equipmentType) { case 1: return Resources.getSystem().getString(R.string.open_air); case 2: return Resources.getSystem().getString(R.string.switch_gears); case 3: return Resources.getSystem().getString(R.string.mcs_panels); case 4: return Resources.getSystem().getString(R.string.cables); default: return null; } } public void setEquipmentType(int equipmentType) { this.equipmentType = equipmentType; } public double getTransformerZ() { return transformerZ; } public void setTransformerZ(double transformerZ) { this.transformerZ = transformerZ; } public double getFaultToleranceTime() { return faultToleranceTime; } public void setFaultToleranceTime(double faultToleranceTime) { this.faultToleranceTime = faultToleranceTime; } public int getGrounding() { return grounding; } public String getGroundingString() { switch (grounding) { case 0: return Resources.getSystem().getString(R.string.grounded); case 1: return Resources.getSystem().getString(R.string.not_grounded); default: return null; } } public void setGrounding(int grounding) { this.grounding = grounding; } }
package org.objectweb.proactive.extra.scheduler; import java.lang.reflect.InvocationTargetException; import java.util.Vector; import org.apache.log4j.Logger; import org.objectweb.proactive.Body; import org.objectweb.proactive.ProActive; import org.objectweb.proactive.RunActive; import org.objectweb.proactive.Service; import org.objectweb.proactive.core.body.request.Request; import org.objectweb.proactive.core.body.request.RequestFilter; import org.objectweb.proactive.core.exceptions.proxy.SendRequestCommunicationException; import org.objectweb.proactive.core.node.Node; import org.objectweb.proactive.core.util.log.Loggers; import org.objectweb.proactive.core.util.log.ProActiveLogger; import org.objectweb.proactive.core.util.wrapper.BooleanWrapper; import org.objectweb.proactive.core.util.wrapper.GenericTypeWrapper; import org.objectweb.proactive.extra.scheduler.policy.GenericPolicy; import org.objectweb.proactive.extra.scheduler.resourcemanager.GenericResourceManager; /** * * <i><font size="-1" color="#FF0000">**For internal use only** </font></i> * Scheduler core this is the main active object, it commnicates with resource manager to acquire nodes and with the policy to insert and get jobs from the queue * @author walzouab * */ public class Scheduler implements RunActive, RequestFilter { private static Logger logger = ProActiveLogger.getLogger(Loggers.SCHEDULER); private GenericPolicy policy; //holds the policy used private GenericResourceManager resourceManager; //TODO: change running tasks and finished tasks to hash maps for bettter performance private Vector<InternalTask> runningTasks; private Vector<InternalTask> finishedTasks; private long previousRunOfPingAll; private long TIME_BEFORE_TEST_ALIVE; private long SCHEDULER_TIMEOUT; /* * the following two parameters will be useful in case a nodepool was introduced again in the future * they are kept in the proactive configuration xml file and the will be commented out in the fct configrescheudler private long TIME_BEFORE_RETURNING_NODES_TO_RM; private double PERCENTAGE_OF_RESOURCES_TO_RETURN;*/ private boolean shutdown; private boolean hardShutdown; /** * NoArg Constructor Required By ProActive * */ public Scheduler() { } /** * Creates a new scheduler * @param policy name is a string that referes to the class's formal name and package * @param resourceManager */ public Scheduler(String p, GenericResourceManager rm, String policyFactory) throws Exception { //TODO : this point here creates the policy , changes must be accomoated for here try { //the policy factory is inovked here using reflection policy = (GenericPolicy) Class.forName(p) .getMethod(policyFactory, GenericResourceManager.class).invoke(null, rm); } catch (java.lang.ClassNotFoundException e) { logger.error("The policy class couldn't be found " + e.toString()); throw e; } catch (java.lang.IllegalAccessException e) { logger.error("The method cannot be acessed " + e.toString()); throw e; } catch (java.lang.ClassCastException e) { logger.error( "The policy class doesn't implement Interface GenericPolicy " + e.toString()); throw e; } catch (java.lang.NoClassDefFoundError e) { logger.error( "Couldnt find the class defintion, its a serious error, it might be however due to case sentivity " + e.toString()); throw e; } catch (IllegalArgumentException e) { logger.error("The argument passed isnt correct" + e.toString()); throw e; } catch (InvocationTargetException e) { logger.error("policy constructor threw an exception" + e.toString()); throw e; } catch (NoSuchMethodException e) { logger.error( "Error:Must provide a static policy factory of signature GenericPolicy foo(GenericResourceManager) " + e.toString()); throw e; } catch (Exception e) { logger.error( "An error occured trying to instantiate policy class, please revise it. " + e.toString()); throw e; } resourceManager = rm; runningTasks = new Vector<InternalTask>(); finishedTasks = new Vector<InternalTask>(); previousRunOfPingAll = System.currentTimeMillis(); shutdown = false; hardShutdown = false; configureScheduler(); logger.info("Scheduler intialized in Stop Mode."); } /** * a function that configures scheduler paramters * @throws Exception */ public void configureScheduler() throws Exception { try { SCHEDULER_TIMEOUT = Long.parseLong(System.getProperty( "proactive.scheduler.scheduler_timeout")); TIME_BEFORE_TEST_ALIVE = Long.parseLong(System.getProperty( "proactive.scheduler.time_before_test_alive")); if (this.SCHEDULER_TIMEOUT < 1) { throw new Exception( "SCHEDULER_TIMEOUT must be a positive integer"); } if (this.TIME_BEFORE_TEST_ALIVE < 1) { throw new Exception( "TIME_BEFORE_TEST_ALIVE must be a positive integer"); } } catch (Exception e) { logger.error("An error trying to parse scheduler arguments " + e.toString()); throw e; } } /** * This fucntion is the main thread of the scheduler, it is called automatically by proactive. * A high priortiy given to submission of requests ad checking if execution is finished because they * WARNING, very important. This filter must be used by every single call to any kind of general serve request(ie serve request without mentioned a request name) otherwise the scheduler might crash * @author walzouab */ public void runActivity(Body body) { Service service = new Service(body); while (!shutdown) { //serve all available submit and isfinished requests--nonblocking service.serveAll("submit"); service.serveAll("isFinished"); //if softshutdown has been initiated, it stops scheduling. if resources are returned and runiing tasks finished execution schedule(); manageRunningTasks(); pingAll(); //serve all available submit and isfinished requests--nonblocking service.serveAll("submit"); service.serveAll("isFinished"); //serveone request service.blockingServeOldest(this, SCHEDULER_TIMEOUT); } //if it reaches this pooint thsi means sfotshutdown was intiated and must clean up logger.info("Shutdown Started"); //now set all get result requests that cann never be served to killed boolean onlyTerminateLeft; //this field indicates that all requests other than terminate has been served if (logger.isDebugEnabled()) { onlyTerminateLeft = ((service.getRequestCount() == 1) && service.hasRequestToServe("terminateScheduler")) || (service.getRequestCount() == 0); logger.debug("running tasks size " + runningTasks.size()); logger.debug("service request count " + service.getRequestCount()); if (service.getOldest() != null) { logger.debug("oldest method is " + service.getOldest().getMethodName()); } else { logger.debug("terminate not called yet!!"); } logger.debug("only terminate left? " + onlyTerminateLeft); } int i = 0; do { try { Thread.sleep(SCHEDULER_TIMEOUT); } catch (Exception e) { } manageRunningTasks(); pingAll(); service.serveAll(this); //FIXME:must check for the case where more than one terminate was submitted onlyTerminateLeft = ((service.getRequestCount() == 1) && service.hasRequestToServe("terminateScheduler")) || (service.getRequestCount() == 0); if (logger.isDebugEnabled() && (service.getRequestCount() > 0)) { logger.debug( "Warning: must check for the case where more than one terminate was submitted" + (i++) + " " + runningTasks.size() + " " + service.getRequestCount() + service.getOldest().getMethodName() + " " + onlyTerminateLeft); } } while (!(runningTasks.isEmpty() && onlyTerminateLeft)); handlePolicyNFinishedTasks(); service.blockingServeOldest("terminateScheduler"); } /** * use this function to handle the finished tasks and the policy. * if hard shutdown intiated, will flush both , other wise , it needs to be implemented * */ private void handlePolicyNFinishedTasks() { if (hardShutdown) { this.flushqueue(); finishedTasks.clear(); } else { //TODO:in case of soft shutdown, what do u want to do, maybe save the queue and finished task??? logger.warn( "this is a soft shutdown, what do u want to do with the queue and finished tasks??"); } } /** * does clean up after shceduler shutsdown * @param body */ /** * this function gets tasks it then schedules task on nodes if possible * <b>This is now used in pull method, it can be made into push be making Vector<InternalTask> tasks a parameter! </b> * @author walzouab */ private void schedule() { //TODO:this can be passed as a parameter if policy is in push mode Vector<InternalTask> tasks = policy.getReadyTasks(); ActiveExecuter AE; //to be used as a refernce to active executeras Vector<Node> troubledNodes = new Vector<Node>(); //avector of nodes to be freed if they cause trouble InternalTask taskRetrivedFromPolicy; while (!tasks.isEmpty()) { taskRetrivedFromPolicy = tasks.remove(0); try { //get executer object AE = taskRetrivedFromPolicy.nodeNExecuter.executer; //start the execution taskRetrivedFromPolicy.result = AE.start(taskRetrivedFromPolicy.getUserTask()); // set the time scheudled of the task and change status to running and add it to running tasks pool taskRetrivedFromPolicy.timeScheduled = System.currentTimeMillis(); taskRetrivedFromPolicy.status = Status.RUNNNING; //notice we will reach here only if it was launched sucessfully runningTasks.add(taskRetrivedFromPolicy); logger.info("Task " + taskRetrivedFromPolicy.getTaskID() + "started execution on " + taskRetrivedFromPolicy.nodeNExecuter.node.getNodeInformation() .getURL()); } catch (Exception e) { try { //try to kill the nodes, there is a high proability this will fail but it doesnt matter since its already troubled and will be returned taskRetrivedFromPolicy.nodeNExecuter.node.killAllActiveObjects(); } catch (Exception f) { /*the node is already troubled, it its pointless to handle it here */ } troubledNodes.add(taskRetrivedFromPolicy.nodeNExecuter.node); taskRetrivedFromPolicy.status = Status.FAILED; taskRetrivedFromPolicy.failures++; policy.failed(taskRetrivedFromPolicy); logger.error("Node " + taskRetrivedFromPolicy.nodeNExecuter.node.getNodeInformation() .getURL().toString() + " has problems, will be returned to resource manager, and task will be put at the end of the queue" + e.toString()); } } if (!troubledNodes.isEmpty()) { //There are troubled nodes to be freed if (logger.isDebugEnabled()) { logger.debug("will free from schedule"); } freeDeadNodes(troubledNodes); } } /** * returns a healthy nodeNExecuter back to source for recycling * @param healthy nodeNExecuter */ private void freeNodeNExecuter(NodeNExecuter executer) { Vector<Node> nodes = new Vector<Node>(); nodes.add(executer.node); resourceManager.freeNodes(nodes); } /** * returns a dead node back to the source for recycling, this is only added for convineince, because RM doesnt accept one node, * so it puts it in a vector and calls on the local free nodes fct * @param dead node */ private void freeDeadNode(Node node) { Vector<Node> nodesKilled = new Vector<Node>(); nodesKilled.add(node); freeDeadNodes(nodesKilled); } /** * returns a vector of dead nodes back to the source for recycling * @param dead nodes vector */ private void freeDeadNodes(Vector<Node> deadNodes) { resourceManager.freeNodes(deadNodes); } /** * This function manages running tasks and frees unused nodes * * @author walzouab */ private void manageRunningTasks() { //here check for the futures for (int i = 0; i < runningTasks.size(); i++) { InternalTask task = runningTasks.get(i); if (!ProActive.isAwaited(task.result)) { runningTasks.removeElementAt(i); task.timeFinished = System.currentTimeMillis(); task.status = Status.FINISHED; //error message set to empty to indicate no errors task.result.setErrorMessage(""); policy.finished(task); freeNodeNExecuter(task.nodeNExecuter); finishedTasks.add(task); logger.info("Task " + task.getTaskID() + " has finished"); if (logger.isDebugEnabled()) { logger.debug("1 node freed after finishing execution"); } } } } /** * takes a vector of iternal tasks and inserts them in the policy * @param tasks */ public void submit(Vector<InternalTask> tasks) { for (int i = 0; i < tasks.size(); i++) { tasks.get(i).status = Status.QUEUED; tasks.get(i).timeInsertedInQueue = System.currentTimeMillis(); } policy.insert(tasks); logger.info(tasks.size() + " tasks added."); } /** * checks if a certain task has finished execuution * @param taskID * @return */ public BooleanWrapper isFinished(String taskID) { for (int i = 0; i < finishedTasks.size(); i++) if (finishedTasks.get(i).getTaskID().equals(taskID)) { return new BooleanWrapper(true); } return new BooleanWrapper(false); } public Vector<Info> info_all() { Vector<Info> info = new Vector<Info>(); //get failed and queued from policy info.addAll(policy.getInfo_all()); for (int i = 0; i < runningTasks.size(); i++) { info.add(runningTasks.get(i).getTaskINFO()); } for (int i = 0; i < finishedTasks.size(); i++) { info.add(finishedTasks.get(i).getTaskINFO()); } return info; } public GenericTypeWrapper<Info> info(String taskID) { InternalTask task = getTask(taskID); if (task != null) { return new GenericTypeWrapper<Info>(task.getTaskINFO()); } //if it couldnt be found else { return new GenericTypeWrapper<Info>(new Info(Status.NEW, taskID, "unknown", "unknown", -1, -1, -1, -1, -1)); } } /** * checks if a certain task is queued * @param taskID * @return */ public BooleanWrapper isInTheQueue(String taskID) { if (policy.getTask(taskID).getObject() != null) { return new BooleanWrapper(true); } return new BooleanWrapper(false); } /** * gets a task as long as it exxists in the scheduler * @param taskID * @return the task , null if not in the three main queues ie it was either already collected or its is new and wasnt inserted in the scheduler yet */ private InternalTask getTask(String taskID) { if (isInTheQueue(taskID).booleanValue()) { return policy.getTask(taskID).getObject(); } for (int i = 0; i < runningTasks.size(); i++) if (runningTasks.get(i).getTaskID().equals(taskID)) { return runningTasks.get(i); } for (int i = 0; i < finishedTasks.size(); i++) if (finishedTasks.get(i).getTaskID().equals(taskID)&&finishedTasks.get(i).status!=Status.ERROR) { return finishedTasks.get(i); } return null; //its not queued or runing or finished } /** * checks if a certain task is running * @param taskID * @return */ public BooleanWrapper isRunning(String taskID) { for (int i = 0; i < runningTasks.size(); i++) if (runningTasks.get(i).getTaskID().equals(taskID)) { return new BooleanWrapper(true); } return new BooleanWrapper(false); } /** * This is the function that gets the result. * * @param taskID * @return */ //WARNING, very important. This function must be filtered by accept request to make sure the result is available before it is served otherwise the scheduler might crash public InternalResult getResult(String taskID, String userName) { InternalResult result = null; for (int i = 0; i < finishedTasks.size(); i++) if (finishedTasks.get(i).getTaskID().equals(taskID) && finishedTasks.get(i).getUserName().equals(userName)) { result = finishedTasks.remove(i).result; } return result; } /** * This the function that decides wether or not a request can be served * </br><b>WARNING, very important. This filter must be used by every single call to any kind of general serve request(ie serve request without mentioned a request name) otherwise the scheduler might crash</b> */ public boolean acceptRequest(Request request) { //serves get result only if the result is available if (request.getMethodName() == "getResult") { String taskID = (String) request.getMethodCall().getParameter(0); String userName = (String) request.getMethodCall().getParameter(1); InternalTask task = this.getTask(taskID); //task doesnt exist while shutting down if ((task == null) && shutdown) { createError(taskID, userName, "The Task doesnt exist in the scheduler or hasn't been added to the queue yet or already collected by the user"); return true; } //if the username isnt correct else if ((task != null) && !task.getUserName().equals(userName)) { createError(taskID, userName, "The User Name isnt correct."); return true; } //if it is finihsed, regardles of scheduler status , it must be served else if (isFinished(taskID).booleanValue()) { return true; } //check if the task is queued or failed and shutdown has started else if ((task != null) && (task.status == Status.QUEUED) && shutdown) { createError(taskID, userName, "Shcheduler is shutting down, task wont be scheduled"); return true; } else if ((task != null) && (task.status == Status.FAILED) && shutdown) { createError(taskID, userName, "Due to an internal error, task execution failed. However, sheduler is shutting down.task wont be scheduled"); return true; } //all other cases dont serve it else { return false; } } // the terminate scheduler case, if the scheduler is shutting down, it wont be served because it has to be the last function to be served else if (request.getMethodName() == "terminateScheduler") { if(this.shutdown==true||ProActive.getBodyOnThis().getRequestQueue().hasRequest("shutdown")) return false; else return true; } //all other functions are to be served else { return true; } } /** * kills all running tasks, and puts them inside the finished tasks queue after setting the internal result to show that it was killed * * * */ public void killAllRunning() { Vector<Node> nodesKilled = new Vector<Node>(); while (!runningTasks.isEmpty()) { if (ProActive.isAwaited(runningTasks.get(0).result)) { InternalTask toBeKilled = runningTasks.remove(0); nodesKilled.add(toBeKilled.nodeNExecuter.node); toBeKilled.status = Status.KILLED; policy.finished(toBeKilled); toBeKilled.result = new InternalResult(); toBeKilled.result.setErrorMessage( "Task Was killed before execution finished."); finishedTasks.add(toBeKilled); try { toBeKilled.nodeNExecuter.executer.kill(); } //it will always throw an exception because the kill methid kills the jvm, so it is actually normal catch (SendRequestCommunicationException e) { logger.info("Task " + toBeKilled.getTaskID() + "was killed"); } catch (Exception e) { e.printStackTrace(); logger.info("Something went wrong killing Task " + toBeKilled.getTaskID()); } } else //if result is available already just clean up { manageRunningTasks(); } } if (!nodesKilled.isEmpty()) { if (logger.isDebugEnabled()) { logger.debug("will frree from kill"); } freeDeadNodes(nodesKilled); } } /** * Asks the scheduler to terminate, in order to be sucessful and return true, it must be called after callling shutdown, other wise it will not have any effect * * @return true if sucessful and schedueler is shutdowne , false if asked to terminate while not shutdown or if an exception was raised during shutdown */ //Warning must be filtered so that it is called as the last function during shutdown public BooleanWrapper terminateScheduler() { if (shutdown == true) { try { ProActive.getBodyOnThis().terminate(); logger.info("Scheduler terminated successfully"); } catch (Exception e) { logger.info("error terminating scheudler, will return false" + e.toString()); return new BooleanWrapper(false); } return new BooleanWrapper(true); } else { return new BooleanWrapper(false); } } /** * if immidiate ,clears queue, kills all runing tasks, reutns nodes to resource manager and terminates * if not immediate, stops scheduling and waits for running tasks to finish * if shutdown already intiated further calls wont do anything. * * @param immediate-specifies wether or not to do an immediate shutdown */ public void shutdown(BooleanWrapper immediate) { if (shutdown == true) { return; // shutdown already intiated } if (immediate.booleanValue() == true) { hardShutdown = true; this.killAllRunning(); logger.info("Immediate ShutDown Intiated"); } else { logger.info("Soft ShutDown Intiated"); hardShutdown = false; } shutdown = true; } public void flushqueue() { Vector<String> queued = this.getQueuedID(); for (int i = 0; i < queued.size(); i++) this.del(queued.get(i), "admin"); logger.info("Policy has been flushed."); } /** * Checks if the all active executers are healthy each timeout. if not, tasks are returned to the policy and nodes are freed. * executes when timeout has passed and there are running tasks. * */ private void pingAll() { if (!runningTasks.isEmpty() && ((System.currentTimeMillis() - previousRunOfPingAll) > TIME_BEFORE_TEST_ALIVE)) { Vector<Node> troubledNodes = new Vector<Node>(); int i = 0; //counter while (i < runningTasks.size()) { try { //ping the executer to make sure its alive runningTasks.get(i).nodeNExecuter.executer.ping(); //notice that if there is an error , this part will be skipped //because the removal of an item decreases the size of the running tasks vector i++; } catch (Exception e) { InternalTask failed = runningTasks.remove(i); troubledNodes.add(failed.nodeNExecuter.node); failed.status = Status.FAILED; failed.failures++; policy.failed(failed); logger.error("Task " + failed.getTaskID() + " has failed and will be returned to policy for rescheduling"); } } //return troubled nodes if (!troubledNodes.isEmpty()) { if (logger.isDebugEnabled()) { logger.info("will freee from ping"); } freeDeadNodes(troubledNodes); if (logger.isDebugEnabled()) { logger.warn(troubledNodes.size() + " nodes are trobled and were returned to resource manager."); } } //set the time of this run previousRunOfPingAll = System.currentTimeMillis(); } } private void createError(String taskID, String userName, String Message) { InternalTask error = new InternalTask(null, taskID, userName); error.result = new InternalResult(); error.status = Status.ERROR; error.result.setErrorMessage(Message); finishedTasks.add(error); } /** * gets the IDS of queued tasks * @return */ public Vector<String> getQueuedID() { return policy.getQueuedID(); } /** * gets the IDS of failed tasks * @return */ public Vector<String> getFailedID() { return policy.getFailedID(); } public Vector<String> getRunningID() { Vector<String> result = new Vector<String>(); for (int i = 0; i < runningTasks.size(); i++) { result.add(runningTasks.get(i).getTaskID()); } return result; } /** * get all killed tasks * @return */ public Vector<String> getKilledID() { Vector<String> result = new Vector<String>(); for (int i = 0; i < finishedTasks.size(); i++) { if (finishedTasks.get(i).status == Status.KILLED) { result.add(finishedTasks.get(i).getTaskID()); } } return result; } /** * get all finished tasks that havent been collect by the user * @return */ public Vector<String> getFinishedID() { Vector<String> result = new Vector<String>(); for (int i = 0; i < finishedTasks.size(); i++) { if (finishedTasks.get(i).status == Status.FINISHED) { result.add(finishedTasks.get(i).getTaskID()); } } return result; } /** * Deletes a specfic task, only if it is either queued or running * If it is finished, it will return false * @param taskID * @param username * @return true if it is deleted else false */ public BooleanWrapper del(String taskID, String userName) { InternalTask toBeKilled = this.getTask(taskID); //this means it doesnt exist in the scheduler if (toBeKilled == null) { return new BooleanWrapper(false); } //if its not (the admin or the correct user decline it if (!(userName.equals(toBeKilled.getUserName()) || userName.equals("admin"))) { return new BooleanWrapper(false); } //notice that it wont be scheduled when running this fct becasue run activity runs schedule perdiodically after serving requests if (isInTheQueue(taskID).booleanValue()) { toBeKilled = policy.removeTask(taskID).getObject(); toBeKilled.status = Status.KILLED; toBeKilled.result = new InternalResult(); toBeKilled.result.setErrorMessage( "Task has been deleted from the scheduler queue"); finishedTasks.add(toBeKilled); return new BooleanWrapper(true); } if (isRunning(taskID).booleanValue()) { //run trying to locate the task for (int i = 0; i < runningTasks.size(); i++) { if (runningTasks.get(i).getTaskID().equals(taskID)) { if (ProActive.isAwaited(runningTasks.get(i).result)) { toBeKilled = runningTasks.remove(i); toBeKilled.status = Status.KILLED; policy.finished(toBeKilled); toBeKilled.result = new InternalResult(); toBeKilled.result.setErrorMessage( "Task Was killed before execution finished."); finishedTasks.add(toBeKilled); try { toBeKilled.nodeNExecuter.executer.kill(); } //it will always throw an exception because the kill methid kills the jvm, so it is actually normal catch (SendRequestCommunicationException e) { logger.info("Task " + toBeKilled.getTaskID() + "was killed"); } catch (Exception e) { e.printStackTrace(); logger.info("Something went wrong killing Task " + toBeKilled.getTaskID()); } if (logger.isDebugEnabled()) { logger.debug("will frree from kill"); } freeDeadNode(toBeKilled.nodeNExecuter.node); return new BooleanWrapper(true); } else //if result is available already just clean up { manageRunningTasks(); // it wasnt killed because it became finished return new BooleanWrapper(false); } } } } return new BooleanWrapper(false); } }
package com.ForgeEssentials.core.misc; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.CraftingManager; import net.minecraft.item.crafting.IRecipe; import net.minecraftforge.common.Configuration; import net.minecraftforge.event.EventPriority; import net.minecraftforge.event.ForgeSubscribe; import net.minecraftforge.event.entity.player.PlayerInteractEvent; import com.ForgeEssentials.api.permissions.IPermRegisterEvent; import com.ForgeEssentials.api.permissions.PermRegister; import com.ForgeEssentials.api.permissions.PermissionsAPI; import com.ForgeEssentials.api.permissions.RegGroup; import com.ForgeEssentials.api.permissions.ZoneManager; import com.ForgeEssentials.api.permissions.query.PermQueryPlayerZone; import com.ForgeEssentials.core.ForgeEssentials; import com.ForgeEssentials.util.OutputHandler; import com.ForgeEssentials.util.AreaSelector.WorldPoint; import com.google.common.collect.HashMultimap; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.event.FMLPostInitializationEvent; public class BannedItems { private static final String BYPASS = "ForgeEssentials.BannedItems.override"; HashMultimap<Integer, Integer> noUse = HashMultimap.create(); List<String> noCraft = new ArrayList<String>(); @PermRegister(ident = "FE-Core-bannedItems") public void registerPermissions(IPermRegisterEvent event) { event.registerPermissionLevel(BYPASS, RegGroup.OWNERS); } @ForgeSubscribe(priority = EventPriority.HIGHEST, receiveCanceled = true) public void click(PlayerInteractEvent e) { if (FMLCommonHandler.instance().getEffectiveSide().isClient()) return; if (PermissionsAPI.checkPermAllowed(new PermQueryPlayerZone(e.entityPlayer, BYPASS, ZoneManager.getWhichZoneIn(new WorldPoint(e.entityPlayer))))) return; ItemStack is = e.entityPlayer.inventory.getCurrentItem(); if (is != null) { if (noUse.containsKey(is.itemID)) { if (noUse.get(is.itemID).contains(is.getItemDamage())) { if (!PermissionsAPI.checkPermAllowed(new PermQueryPlayerZone(e.entityPlayer, BYPASS + "." + is.itemID + ":" + is.getItemDamage(), ZoneManager.getWhichZoneIn(new WorldPoint(e.entityPlayer))))) { e.entityPlayer.sendChatToPlayer("That item is banned."); e.setCanceled(true); } } if (noUse.get(is.itemID).contains(-1)) { if (!PermissionsAPI.checkPermAllowed(new PermQueryPlayerZone(e.entityPlayer, BYPASS + "." + is.itemID + ":-1", ZoneManager.getWhichZoneIn(new WorldPoint(e.entityPlayer))))) { e.entityPlayer.sendChatToPlayer("That item is banned."); e.setCanceled(true); } } } } } public void postLoad(FMLPostInitializationEvent e) { Configuration config = new Configuration(new File(ForgeEssentials.FEDIR, "banneditems.cfg")); config.addCustomCategoryComment("NoCraft", "Configuration options to remove an item's crafting recipe."); config.addCustomCategoryComment("NoUse", "Configuration options to make an item unusable."); noCraft = Arrays.asList(config.get("NoCraft", "List", new String[] {}, "Use this format: \"id:meta\". Use meta -1 to ban ALL variants of an item/block.").valueList); List<String> temp = Arrays.asList(config.get("NoUse", "List", new String[] {}, "Use this format: \"id:meta\". Use meta -1 to ban ALL variants of an item/block.").valueList); config.save(); int id; int meta; for (String s : temp) { id = meta = 0; String[] tmp = s.split(":"); if (tmp != null && tmp.length > 0) { try { id = Integer.parseInt(tmp[0]); if (tmp.length > 1) { try { meta = Integer.parseInt(tmp[1]); } catch (Exception ex) { meta = 0; } } } catch (Exception ex) { id = 0; } } if (id != 0) { noUse.put(id, meta); } } ArrayList<ItemStack> items = new ArrayList(); // Decompose list into (item ID, Meta) pairs. for (String s : noCraft) { id = meta = 0; String[] tmp = s.split(":"); if (tmp != null && tmp.length > 0) { try { id = Integer.parseInt(tmp[0]); if (tmp.length > 1) { try { meta = Integer.parseInt(tmp[1]); } catch (Exception ex) { meta = 0; } } } catch (Exception ex) { id = 0; } } if (id != 0) { items.add(new ItemStack(id, 1, meta)); } } // Iterate over recipe list, and remove a recipe when its output matches // one of our ItemStacks. List<IRecipe> minecraftRecipes = CraftingManager.getInstance().getRecipeList(); ItemStack result; for (int i = 0; i < minecraftRecipes.size(); ++i) { IRecipe tmp = minecraftRecipes.get(i); result = tmp.getRecipeOutput(); if (result != null) { for (ItemStack bannedItem : items) { // Remove the item if the ID & meta match, OR if the IDs // match, and banned meta is -1. if (result.itemID == bannedItem.itemID && (bannedItem.getItemDamage() == -1 || result.getItemDamage() == bannedItem.getItemDamage())) { minecraftRecipes.remove(i); OutputHandler.finer("Recipes removed for item " + bannedItem.itemID); --i; } } } } } }
package org.neo4j.server.database; import java.util.Map; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.PropertyContainer; import org.neo4j.helpers.collection.MapUtil; import org.neo4j.index.IndexService; import org.neo4j.kernel.EmbeddedGraphDatabase; import org.neo4j.server.logging.Logger; public class Database { public static Logger log = Logger.getLogger(Database.class); public GraphDatabaseService db; public IndexService indexService; public IndexService fulltextIndexService; public Map<String, Index<? extends PropertyContainer>> indicies; private String databaseStoreDirectory; public Database(String databaseStoreDirectory) { this(new EmbeddedGraphDatabase(databaseStoreDirectory, MapUtil.stringMap( "enable_remote_shell", "true" )), null, null, null); this.databaseStoreDirectory = databaseStoreDirectory; } public Database(GraphDatabaseService db, IndexService indexService, IndexService fulltextIndexService, Map<String, Index<? extends PropertyContainer>> indices) { this.db = db; this.indexService = indexService; this.fulltextIndexService = fulltextIndexService; indicies = indices; } public void startup() { log.info("Successfully started database"); } public void shutdown() { try { if(db != null) { db.shutdown(); } log.info("Successfully shutdown database"); } catch(Exception e) { log.error("Database did not shut down cleanly. Reason [%s]", e.getMessage()); throw new RuntimeException(e); } } public String getLocation() { return databaseStoreDirectory; } }
package com.adyen.v6.commands; import java.math.BigDecimal; import java.util.Currency; import java.util.Date; import org.apache.log4j.Logger; import org.springframework.util.Assert; import com.adyen.model.modification.ModificationResult; import com.adyen.v6.factory.AdyenPaymentServiceFactory; import com.adyen.v6.repository.OrderRepository; import com.adyen.v6.service.AdyenPaymentService; import de.hybris.platform.core.model.order.OrderModel; import de.hybris.platform.core.model.order.payment.PaymentInfoModel; import de.hybris.platform.payment.commands.CaptureCommand; import de.hybris.platform.payment.commands.request.CaptureRequest; import de.hybris.platform.payment.commands.result.CaptureResult; import de.hybris.platform.payment.dto.TransactionStatus; import de.hybris.platform.payment.dto.TransactionStatusDetails; import de.hybris.platform.store.BaseStoreModel; /** * Issues a Capture request */ public class AdyenCaptureCommand implements CaptureCommand { private static final Logger LOG = Logger.getLogger(AdyenCaptureCommand.class); private AdyenPaymentServiceFactory adyenPaymentServiceFactory; private OrderRepository orderRepository; /** * {@inheritDoc} * * @see de.hybris.platform.payment.commands.Command#perform(java.lang.Object) */ @Override public CaptureResult perform(final CaptureRequest request) { CaptureResult result = createCaptureResultFromRequest(request); LOG.info("Capture request received with requestId: " + request.getRequestId() + ", requestToken: " + request.getRequestToken()); String originalPSPReference = request.getRequestId(); String reference = request.getRequestToken(); final BigDecimal amount = request.getTotalAmount(); final Currency currency = request.getCurrency(); OrderModel order = orderRepository.getOrderModel(reference); if (order == null) { LOG.error("Order model with code: " + reference + " cannot be found"); result.setTransactionStatus(TransactionStatus.ERROR); return result; } BaseStoreModel baseStore = order.getStore(); Assert.notNull(baseStore); AdyenPaymentService adyenPaymentService = adyenPaymentServiceFactory.createFromBaseStore(baseStore); final PaymentInfoModel paymentInfo = order.getPaymentInfo(); Assert.notNull(paymentInfo); boolean isImmediateCapture = baseStore.getAdyenImmediateCapture(); Assert.notNull(isImmediateCapture); boolean autoCapture = isImmediateCapture || ! supportsManualCapture(paymentInfo.getAdyenPaymentMethod()); if (autoCapture) { result.setTransactionStatus(TransactionStatus.ACCEPTED); result.setTransactionStatusDetails(TransactionStatusDetails.SUCCESFULL); } else { try { ModificationResult modificationResult = adyenPaymentService.capture(amount, currency, originalPSPReference, reference); if (modificationResult.getResponse() == ModificationResult.ResponseEnum.CAPTURE_RECEIVED_) { result.setTransactionStatus(TransactionStatus.ACCEPTED); //Accepted so that TakePaymentAction doesn't fail result.setTransactionStatusDetails(TransactionStatusDetails.REVIEW_NEEDED); } else { result.setTransactionStatus(TransactionStatus.REJECTED); result.setTransactionStatusDetails(TransactionStatusDetails.UNKNOWN_CODE); } } catch (Exception e) { LOG.error("Capture Exception: " + e, e); } } LOG.info("Capture status: " + result.getTransactionStatus().name() + ":" + result.getTransactionStatusDetails().name()); return result; } private CaptureResult createCaptureResultFromRequest(CaptureRequest request) { CaptureResult result = new CaptureResult(); result.setCurrency(request.getCurrency()); result.setTotalAmount(request.getTotalAmount()); result.setRequestTime(new Date()); result.setMerchantTransactionCode(request.getMerchantTransactionCode()); result.setRequestId(request.getRequestId()); result.setRequestToken(request.getRequestToken()); //Default status = ERROR result.setTransactionStatus(TransactionStatus.ERROR); result.setTransactionStatusDetails(TransactionStatusDetails.UNKNOWN_CODE); return result; } private boolean supportsManualCapture(String paymentMethod) { switch (paymentMethod) { case "cup": case "cartebancaire": case "visa": case "visadankort": case "mc": case "uatp": case "amex": case "maestro": case "maestrouk": case "diners": case "discover": case "jcb": case "laser": case "paypal": case "klarna": case "afterpay": case "ratepay": case "afterpay_default": case "sepadirectdebit": case "dankort": case "elo": case "hipercard": case "mc_applepay": case "visa_applepay": case "amex_applepay": case "discover_applepay": case "maestro_applepay": case "paywithgoogle": return true; } return false; } public AdyenPaymentServiceFactory getAdyenPaymentServiceFactory() { return adyenPaymentServiceFactory; } public void setAdyenPaymentServiceFactory(AdyenPaymentServiceFactory adyenPaymentServiceFactory) { this.adyenPaymentServiceFactory = adyenPaymentServiceFactory; } public OrderRepository getOrderRepository() { return orderRepository; } public void setOrderRepository(OrderRepository orderRepository) { this.orderRepository = orderRepository; } }
public class HelloDataTypesInteger { public static void main(String... args) { System.out.println("Hello Data Types Integer!"); System.out.printf("size: %s\n", Integer.SIZE); // 1. Value by Assigning a Literal int in1 = Integer.MIN_VALUE; int in2 = Integer.MAX_VALUE; int in3 = (int) -Math.pow(2, 32); int in4 = (int) Math.pow(2, 32); int in5 = -0x8000_0000; int in6 = 0x7fff_ffff; int in7 = -0b1000_0000_0000_0000_0000_0000_0000_0000; int in8 = 0b0111_1111_1111_1111_1111_1111_1111_1111; System.out.printf("Integer.MIN_VALUE; \t\t\t%e\n", (float) in1); System.out.printf("Integer.MAX_VALUE; \t\t\t %e\n", (float) in2); System.out.printf("int in3 = -Math.pow(2, 32); \t\t%s\n", in3); System.out.printf("int in4 = Math.pow(2, 32); \t\t %s\n", in4); System.out.printf("int in5 = -0x8000; \t\t\t%s\n", in5); System.out.printf("int in6 = 0x7fff; \t\t\t %s\n", in6); System.out.printf("int in7 = -0b1000_0000_0000_0000; \t%s\n", in7); System.out.printf("int in8 = 0b111_1111_1111_1111; \t %s\n", in8); // 2. Value by Instantiation Integer in9 = new Integer(in1); Integer in19 = Integer.valueOf(in1); System.out.printf("Integer in9 = new Integer(in1); \t%s\n", in9); System.out.printf("Integer in19 = Integer.valueOf(in1); \t%s\n", in19); // 3. Value by Explicit Conversion int in10 = in9.intValue(); Byte by1 = (byte) -128; int in10x = by1.intValue(); Short sh1 = -32768; int in10b = sh1.intValue(); Long lo1 = -2147483648L; int in10c = lo1.intValue(); Float fl1 = -2147483648.0f; int in10d = fl1.intValue(); Double db1 = -2147483648.0d; int in10e = db1.intValue(); System.out.printf(" int in10 = in9.intValue(); \t%s\n", in10); System.out.printf("Byte by1 = (byte) -128; int in10x = by1.intValue(); \t%s\n", in10x); System.out.printf("Short sh1 = -32768; int in10b = sh1.intValue(); \t%s\n", in10b); System.out.printf("Long lo1 = -2147483648L; int in10c = lo1.intValue(); \t%s\n", in10c); System.out.printf("Float fl1 = -2147483648.0f; int in10d = fl1.intValue(); \t%s\n", in10d); System.out.printf("Double db1 = -2147483648.0d; int in10e = db1.intValue(); \t%s\n", in10e); // 4. Value in Autoboxing (Implicit Conversion) Integer in11 = in1; int in12 = in9; System.out.printf("Integer in11 = in1; \t\t\t%s\n", in11); System.out.printf("int in12 = in9; \t\t\t\t%s\n", in12); // 5. Value By Parsing int in13 = Integer.parseInt("-2147483648"); int in14 = Integer.parseInt("-80000000", 16); int in15 = Integer.parseInt("-10000000000000000000000000000000", 2); System.out.printf("Integer in13 = Integer.parseInteger(\"-2147483648\"); \t\t\t\t%s\n", in13); System.out.printf("Integer in14 = Integer.parseInteger(\"-80000000\", 16); \t\t\t\t%s\n", in14); System.out.printf("Integer in15 = Integer.parseInteger(\"-10000000000000000000000000000000\", 2); \t%s\n", in15); int in16 = Integer.decode("-2147483648"); int in17 = Integer.decode("-0x80000000"); int in18 = Integer.decode("-020000000000"); System.out.printf("Integer in16 = Integer.decode(\"-2147483648\"); \t\t\t\t\t%s\n", in16); System.out.printf("Integer in17 = Integer.decode(\"-0x80000000\"); \t\t\t\t\t%s\n", in17); System.out.printf("Integer in18 = Integer.decode(\"-020000000000\"); \t\t\t\t\t%s\n", in18); Integer in20 = Integer.valueOf("-2147483648"); int in21 = Integer.valueOf("-80000000", 16); int in22 = Integer.valueOf("-10000000000000000000000000000000", 2); System.out.printf("Integer in20 = Integer.valueOf(\"-2147483648\"); \t\t\t\t\t%s\n", in20); System.out.printf("Integer in21 = Integer.valueOf(\"-80000000\", 16); \t\t\t\t%s\n", in21); System.out.printf("Integer in22 = Integer.valueOf(\"-10000000000000000000000000000000\", 2); \t\t%s\n", in22); // 6. Value By Casting byte by2 = (byte) -128; int in23 = (int) by2; short sh2 = (short) -32768; int in24 = (int) sh2; long lo2 = -2147483648L; int in25 = (int) lo2; float fl2 = -2147483648.0f; int in26 = (int) fl2; double db2 = -2147483648.0d; int in27 = (int) db2; System.out.printf("byte by2 = (byte) -128; int in23 = (int) by2; \t\t%s\n", in23); System.out.printf("short sh2 = (short) -32768; int in24 = (int) sh2; \t\t%s\n", in24); System.out.printf("long lo2 = -2147483648L; int in25 = (int) lo2; \t\t%s\n", in25); System.out.printf("float fl2 = -2147483648.0f; int sh26 = (int) fl2; \t\t%s\n", in26); System.out.printf("double db2 = -2147483648.0d; int sh27 = (int) db2; \t\t%s\n", in27); } }
package de.diddiz.utils.iter; import java.io.File; import java.util.Iterator; import java.util.LinkedList; /** * Creates an {@link java.util.Iterator Iterator} that iterates over all sub files of a folder recursively. * * Opens directories as needed while iterating, not ahead of. */ public class FileWalker implements Iterable<File> { private final File[] roots; /** * @param root May be a directory, a file, or point to nothing. Respectively, the {@code Iterator} will iterate over all sub files in all sub directories, exactly the specified file, or nothing. */ public FileWalker(File... roots) { this.roots = roots; } @Override public Iterator<File> iterator() { return new FileWalkerIterator(roots); } private static class FileWalkerIterator extends ComputeNextIterator<File> { private final LinkedList<File> folders = new LinkedList<>(), files = new LinkedList<>(); public FileWalkerIterator(File... roots) { for (final File root : roots) add(root); computeFirst(); } @Override protected File computeNext() { while (files.size() == 0 && folders.size() > 0) { final File[] subFiles = folders.poll().listFiles(); if (subFiles != null && subFiles.length > 0) // listFiles may return null. for (final File file : subFiles) add(file); } if (files.size() > 0) return files.poll(); return null; } private void add(File file) { if (file.isDirectory()) folders.add(file); else if (file.isFile()) files.add(file); } } }
package de.st_ddt.crazylogin; import java.io.File; import java.security.NoSuchAlgorithmException; import java.util.Date; import java.util.List; import org.bukkit.OfflinePlayer; import org.bukkit.command.CommandSender; import org.bukkit.command.ConsoleCommandSender; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.entity.Player; import org.bukkit.plugin.PluginManager; import de.st_ddt.crazylogin.crypt.AuthMeCrypt; import de.st_ddt.crazylogin.crypt.CrazyCrypt1; import de.st_ddt.crazylogin.crypt.CustomEncryptor; import de.st_ddt.crazylogin.crypt.DefaultCrypt; import de.st_ddt.crazylogin.crypt.Encryptor; import de.st_ddt.crazylogin.crypt.PlainCrypt; import de.st_ddt.crazylogin.crypt.WhirlPoolCrypt; import de.st_ddt.crazylogin.databases.CrazyLoginConfigurationDatabase; import de.st_ddt.crazylogin.databases.CrazyLoginFlatDatabase; import de.st_ddt.crazylogin.databases.CrazyLoginMySQLDatabase; import de.st_ddt.crazylogin.tasks.DropInactiveAccountsTask; import de.st_ddt.crazyplugin.CrazyPlugin; import de.st_ddt.crazyplugin.exceptions.CrazyCommandException; import de.st_ddt.crazyplugin.exceptions.CrazyCommandExecutorException; import de.st_ddt.crazyplugin.exceptions.CrazyCommandNoSuchException; import de.st_ddt.crazyplugin.exceptions.CrazyCommandParameterException; import de.st_ddt.crazyplugin.exceptions.CrazyCommandPermissionException; import de.st_ddt.crazyplugin.exceptions.CrazyCommandUsageException; import de.st_ddt.crazyplugin.exceptions.CrazyException; import de.st_ddt.crazyutil.ChatHelper; import de.st_ddt.crazyutil.ObjectSaveLoadHelper; import de.st_ddt.crazyutil.PairList; import de.st_ddt.crazyutil.databases.Database; import de.st_ddt.crazyutil.databases.MySQLConnection; public class CrazyLogin extends CrazyPlugin { private static CrazyLogin plugin; protected final PairList<String, LoginPlayerData> datas = new PairList<String, LoginPlayerData>(); private CrazyLoginPlayerListener playerListener; private CrazyLoginVehicleListener vehicleListener; protected boolean alwaysNeedPassword; protected int autoLogout; protected int autoKick; protected List<String> commandWhiteList; protected boolean autoKickCommandUsers; protected String uniqueIDKey; protected boolean doNotSpamRequests; protected boolean forceSingleSession; protected Encryptor encryptor; // Database protected String saveType; protected String tableName; protected Database<LoginPlayerData> database; protected int autoDelete; public static CrazyLogin getPlugin() { return plugin; } @Override public void onEnable() { plugin = this; registerHooks(); super.onEnable(); } public void registerHooks() { this.playerListener = new CrazyLoginPlayerListener(this); this.vehicleListener = new CrazyLoginVehicleListener(this); PluginManager pm = this.getServer().getPluginManager(); pm.registerEvents(playerListener, this); pm.registerEvents(vehicleListener, this); } @Override public void load() { super.load(); FileConfiguration config = getConfig(); if (config.getBoolean("autoLogout", false)) autoLogout = 0; else autoLogout = config.getInt("autoLogout", 60 * 60 * 12); alwaysNeedPassword = config.getBoolean("alwaysNeedPassword", true); autoKick = Math.max(config.getInt("autoKick", -1), -1); doNotSpamRequests = config.getBoolean("doNotSpamRequests", false); commandWhiteList = config.getStringList("commandWhitelist"); autoKickCommandUsers = config.getBoolean("autoKickCommandUsers", false); forceSingleSession = config.getBoolean("forceSingleSession", true); autoDelete = Math.max(config.getInt("autoDelete", -1), -1); if (autoDelete != -1) getServer().getScheduler().scheduleAsyncRepeatingTask(this, new DropInactiveAccountsTask(this), 20 * 60 * 60, 20 * 60 * 60 * 6); if (commandWhiteList.size() == 0) { commandWhiteList.add("/login"); commandWhiteList.add("/register"); commandWhiteList.add("/crazylogin password"); } uniqueIDKey = config.getString("uniqueIDKey"); String algorithm = config.getString("algorithm", "CrazyCrypt1"); if (algorithm.equalsIgnoreCase("CrazyCrypt1")) { encryptor = new CrazyCrypt1(); } else if (algorithm.equalsIgnoreCase("Whirlpool")) { encryptor = new WhirlPoolCrypt(); } else if (algorithm.equalsIgnoreCase("Plaintext")) { encryptor = new PlainCrypt(); } else if (algorithm.equalsIgnoreCase("AuthMe")) { encryptor = new AuthMeCrypt(); } else if (algorithm.equalsIgnoreCase("Custom")) { String encryption = config.getString("customEncryptor.class"); encryptor = ObjectSaveLoadHelper.load(encryption, CustomEncryptor.class, new Class[0], new Object[0]); } else { try { encryptor = new DefaultCrypt(algorithm); } catch (NoSuchAlgorithmException e) { broadcastLocaleMessage(true, "crazylogin.warnalgorithm", "ALGORITHM.MISSING", algorithm); encryptor = new CrazyCrypt1(); } } setupDatabase(); datas.clear(); if (database != null) for (LoginPlayerData data : database.getAllEntries()) datas.setDataVia1(data.getName().toLowerCase(), data); dropInactiveAccounts(); } public void setupDatabase() { FileConfiguration config = getConfig(); saveType = config.getString("database.saveType", "flat").toLowerCase(); tableName = config.getString("database.tableName", "players"); // Columns String colName = config.getString("database.columns.name", "name"); config.set("database.columns.name", colName); String colPassword = config.getString("database.columns.password", "password"); config.set("database.columns.password", colPassword); String colIPs = config.getString("database.columns.ips", "ips"); config.set("database.columns.ips", colIPs); String colLastAction = config.getString("database.columns.lastAction", "lastAction"); config.set("database.columns.lastAction", colLastAction); try { if (saveType.equals("config")) { database = new CrazyLoginConfigurationDatabase(config, tableName, colName, colPassword, colIPs, colLastAction); } else if (saveType.equals("mysql")) { String host = config.getString("database.host", "localhost"); config.set("database.host", host); String port = config.getString("database.port", "3306"); config.set("database.port", port); String databasename = config.getString("database.dbname", "Crazy"); config.set("database.dbname", databasename); String user = config.getString("database.user", "root"); config.set("database.user", user); String password = config.getString("database.password", ""); config.set("database.password", password); MySQLConnection connection = new MySQLConnection(host, port, databasename, user, password); database = new CrazyLoginMySQLDatabase(connection, tableName, colName, colPassword, colIPs, colLastAction); } else if (saveType.equals("flat")) { File file = new File(getDataFolder().getPath() + "/" + tableName + ".db"); database = new CrazyLoginFlatDatabase(file, colName, colPassword, colIPs, colLastAction); } } catch (Exception e) { e.printStackTrace(); database = null; } finally { if (database == null) broadcastLocaleMessage(true, "crazylogin.warndatabase", "CRAZYLOGIN.DATABASE.ACCESSWARN", saveType); } } @Override public void save() { FileConfiguration config = getConfig(); config.set("database.saveType", saveType); config.set("database.tableName", tableName); dropInactiveAccounts(); if (database != null) database.saveAll(datas.getData2List()); saveConfiguration(); super.save(); } public int dropInactiveAccounts() { if (autoDelete != -1) return dropInactiveAccounts(autoDelete); return -1; } protected int dropInactiveAccounts(int age) { Date compare = new Date(); compare.setTime(compare.getTime() - age * 1000 * 60 * 60 * 24); return dropInactiveAccounts(compare); } protected int dropInactiveAccounts(Date limit) { int amount = 0; for (LoginPlayerData data : datas.getData2List()) if (data.getLastActionTime().before(limit)) { datas.removeDataVia2(data); amount++; if (database != null) database.delete(data.getName()); } return amount; } public void saveConfiguration() { ConfigurationSection config = getConfig(); config.set("alwaysNeedPassword", alwaysNeedPassword); config.set("autoLogout", autoLogout); config.set("autoKick", autoKick); config.set("doNotSpamRequests", doNotSpamRequests); config.set("commandWhitelist", commandWhiteList); config.set("autoKickCommandUsers", autoKickCommandUsers); config.set("uniqueIDKey", uniqueIDKey); config.set("algorithm", encryptor.getAlgorithm()); config.set("autoDelete", autoDelete); } @Override public boolean command(final CommandSender sender, final String commandLabel, final String[] args) throws CrazyException { if (commandLabel.equalsIgnoreCase("login")) { commandLogin(sender, args); return true; } if (commandLabel.equalsIgnoreCase("logout")) { commandLogout(sender, args); return true; } if (commandLabel.equalsIgnoreCase("register")) { commandMainPassword(sender, args); return true; } return false; } private void commandLogin(final CommandSender sender, final String[] args) throws CrazyCommandException { if (sender instanceof ConsoleCommandSender) throw new CrazyCommandExecutorException(false); if (args.length == 0) throw new CrazyCommandUsageException("/login <Passwort...>"); Player player = (Player) sender; String password = ChatHelper.listToString(args); LoginPlayerData data = datas.findDataVia1(player.getName().toLowerCase()); if (data == null) { sendLocaleMessage("REGISTER.HEADER", player); sendLocaleMessage("REGISTER.MESSAGE", player); return; } if (!data.login(password)) { sendLocaleMessage("LOGIN.FAILED", player); broadcastLocaleMessage(true, "crazylogin.warnloginfailure", "LOGIN.FAILEDWARN", player.getName(), player.getAddress().getAddress().getHostAddress()); return; } sendLocaleMessage("LOGIN.SUCCESS", player); data.addIP(player.getAddress().getAddress().getHostAddress()); if (database != null) database.save(data); } private void commandLogout(final CommandSender sender, final String[] args) throws CrazyCommandException { if (sender instanceof ConsoleCommandSender) throw new CrazyCommandExecutorException(false); Player player = (Player) sender; if (!isLoggedIn(player)) throw new CrazyCommandPermissionException(); LoginPlayerData data = datas.findDataVia1(player.getName().toLowerCase()); if (data != null) data.logout(); player.kickPlayer(locale.getLanguageEntry("LOGOUT.SUCCESS").getLanguageText(player)); if (database != null) database.save(data); } @Override public boolean commandMain(final CommandSender sender, final String commandLabel, final String[] args) throws CrazyException { if (commandLabel.equalsIgnoreCase("password")) { commandMainPassword(sender, args); return true; } if (commandLabel.equalsIgnoreCase("admin")) { commandMainAdmin(sender, args); return true; } if (commandLabel.equalsIgnoreCase("mode")) { commandMainMode(sender, args); return true; } if (commandLabel.equalsIgnoreCase("delete")) { commandMainDelete(sender, args); return true; } return false; } private void commandMainPassword(final CommandSender sender, final String[] args) throws CrazyCommandException { if (sender instanceof ConsoleCommandSender) throw new CrazyCommandExecutorException(false); Player player = (Player) sender; if (!isLoggedIn(player) && hasAccount(player)) throw new CrazyCommandPermissionException(); if (args.length == 0) { if (alwaysNeedPassword) throw new CrazyCommandUsageException("/crazylogin password <Passwort...>"); datas.removeDataVia1(player.getName().toLowerCase()); sendLocaleMessage("PASSWORDDELETE.SUCCESS", sender); if (database != null) database.delete(player.getName()); return; } LoginPlayerData data = datas.findDataVia1(player.getName().toLowerCase()); if (data == null) { if (!sender.hasPermission("crazylogin.register")) throw new CrazyCommandPermissionException(); data = new LoginPlayerData(player); datas.setDataVia1(player.getName().toLowerCase(), data); } String password = ChatHelper.listToString(args); data.setPassword(password); data.login(password); sendLocaleMessage("PASSWORDCHANGE.SUCCESS", player); if (database != null) database.save(data); } private void commandMainAdmin(final CommandSender sender, final String[] args) throws CrazyCommandException { if (sender instanceof Player) { Player player = (Player) sender; if (!isLoggedIn(player)) throw new CrazyCommandPermissionException(); } if (!sender.hasPermission("crazylogin.admin")) throw new CrazyCommandPermissionException(); switch (args.length) { case 0: throw new CrazyCommandUsageException("/crazylogin admin <Player> <Passwort...>"); case 1: OfflinePlayer target = getServer().getPlayerExact(args[0]); if (target == null) { target = getServer().getPlayer(args[0]); if (target == null) target = getServer().getOfflinePlayer(args[0]); } if (target == null) throw new CrazyCommandNoSuchException("Player", args[0]); datas.removeDataVia1(target.getName().toLowerCase()); sendLocaleMessage("PASSWORDDELETE.SUCCESS", sender); if (database != null) database.delete(target.getName()); return; } OfflinePlayer target = getServer().getPlayerExact(args[0]); if (target == null) { target = getServer().getPlayer(args[0]); if (target == null) target = getServer().getOfflinePlayer(args[0]); } if (target == null) throw new CrazyCommandNoSuchException("Player", args[0]); LoginPlayerData data = datas.findDataVia1(target.getName().toLowerCase()); if (data == null) throw new CrazyCommandNoSuchException("Player", args[0]); String password = ChatHelper.listToString(ChatHelper.shiftArray(args, 1)); data.setPassword(password); sendLocaleMessage("PASSWORDCHANGE.SUCCESS", sender); if (database != null) database.save(data); } private void commandMainDelete(CommandSender sender, String[] args) throws CrazyCommandException { if (sender instanceof Player) { Player player = (Player) sender; if (!isLoggedIn(player)) throw new CrazyCommandPermissionException(); } if (!sender.hasPermission("crazylogin.delete")) { String days = "(-)"; if (args.length != 0) days = args[0]; broadcastLocaleMessage(true, "crazylogin.warndelete", "ACCOUNTS.DELETEWARN", sender.getName(), days); throw new CrazyCommandPermissionException(); } if (args.length < 2) if (sender instanceof ConsoleCommandSender) throw new CrazyCommandUsageException("/crazylogin delete <DaysToKeep> CONSOLE_CONFIRM"); else throw new CrazyCommandUsageException("/crazylogin delete <DaysToKeep> <Password>"); int days = 0; try { days = Integer.parseInt(args[0]); } catch (NumberFormatException e) { throw new CrazyCommandParameterException(0, "Integer"); } if (days < 0) return; String password = ChatHelper.listToString(ChatHelper.shiftArray(args, 1), " "); if (sender instanceof ConsoleCommandSender) { if (!password.equals("CONSOLE_CONFIRM")) throw new CrazyCommandUsageException("/crazylogin delete <DaysToKeep> CONSOLE_CONFIRM"); } else { if (!getPlayerData(sender.getName().toLowerCase()).isPassword(password)) throw new CrazyCommandUsageException("/crazylogin delete <DaysToKeep> <Password>"); } int amount = dropInactiveAccounts(days); broadcastLocaleMessage(true, "crazylogin.warndelete", "ACCOUNTS.DELETED", sender.getName(), days, amount); } private void commandMainMode(final CommandSender sender, final String[] args) throws CrazyCommandException { if (sender instanceof Player) { Player player = (Player) sender; if (!isLoggedIn(player)) throw new CrazyCommandPermissionException(); } if (!sender.hasPermission("crazylogin.mode")) throw new CrazyCommandPermissionException(); switch (args.length) { case 2: if (args[0].equalsIgnoreCase("alwaysNeedPassword")) { boolean newValue = false; if (args[1].equalsIgnoreCase("1") || args[1].equalsIgnoreCase("true") || args[1].equalsIgnoreCase("on") || args[1].equalsIgnoreCase("yes")) newValue = true; alwaysNeedPassword = newValue; sendLocaleMessage("MODE.CHANGE", sender, "alwaysNeedPassword", alwaysNeedPassword ? "True" : "False"); saveConfiguration(); return; } else if (args[0].equalsIgnoreCase("autoLogout")) { int newValue = 0; try { newValue = Integer.parseInt(args[1]); if (newValue < -1) throw new Exception(); } catch (Exception e) { throw new CrazyCommandParameterException(1, "Integer", "-1 = disabled", "0 = instant", "1... time in seconds"); } autoLogout = newValue; sendLocaleMessage("MODE.CHANGE", sender, "autoLogout", autoLogout); saveConfiguration(); return; } else if (args[0].equalsIgnoreCase("autoKick")) { int time = autoKick; try { time = Integer.parseInt(args[1]); } catch (NumberFormatException e) { throw new CrazyCommandParameterException(1, "Integer", "-1 = disabled", "Time in Seconds > 60"); } autoKick = time; sendLocaleMessage("MODE.CHANGE", sender, "autoKick", autoKick == -1 ? "disabled" : autoKick + " seconds"); saveConfiguration(); return; } else if (args[0].equalsIgnoreCase("saveType")) { String newValue = args[1]; boolean changed = saveType.equals(newValue); if (newValue.equalsIgnoreCase("config")) saveType = "config"; else if (newValue.equalsIgnoreCase("mysql")) saveType = "mysql"; else if (newValue.equalsIgnoreCase("flat")) saveType = "flat"; else throw new CrazyCommandNoSuchException("SaveType", newValue); sendLocaleMessage("MODE.CHANGE", sender, "saveType", saveType); if (changed) return; getConfig().set("database.saveType", saveType); setupDatabase(); save(); return; } else if (args[0].equalsIgnoreCase("autoDelete")) { int time = autoDelete; try { time = Integer.parseInt(args[1]); } catch (NumberFormatException e) { throw new CrazyCommandParameterException(1, "Integer", "-1 = disabled", "Time in Days"); } autoDelete = time; sendLocaleMessage("MODE.CHANGE", sender, "autoDelete", autoDelete == -1 ? "disabled" : autoKick + " days"); saveConfiguration(); if (autoDelete != -1) getServer().getScheduler().scheduleAsyncRepeatingTask(this, new DropInactiveAccountsTask(this), 20 * 60 * 60, 20 * 60 * 60 * 6); return; } throw new CrazyCommandNoSuchException("Mode", args[0]); case 1: if (args[0].equalsIgnoreCase("alwaysNeedPassword")) { sendLocaleMessage("MODE.CHANGE", sender, "alwaysNeedPassword", alwaysNeedPassword ? "True" : "False"); return; } else if (args[0].equalsIgnoreCase("autoLogout")) { sendLocaleMessage("MODE.CHANGE", sender, "autoLogout", autoLogout); return; } else if (args[0].equalsIgnoreCase("autoKick")) { sendLocaleMessage("MODE.CHANGE", sender, "autoKick", autoKick == -1 ? "disabled" : autoKick + " seconds"); return; } else if (args[0].equalsIgnoreCase("algorithm")) { sendLocaleMessage("MODE.CHANGE", sender, "algorithm", encryptor.getAlgorithm()); return; } else if (args[0].equalsIgnoreCase("saveType")) { sendLocaleMessage("MODE.CHANGE", sender, "saveType", saveType); return; } else if (args[0].equalsIgnoreCase("autoDelete")) { sendLocaleMessage("MODE.CHANGE", sender, "autoDelete", autoDelete == -1 ? "disabled" : autoKick + " days"); return; } throw new CrazyCommandNoSuchException("Mode", args[0]); default: throw new CrazyCommandUsageException("/crazylogin mode <Mode> <Value>"); } } public boolean isLoggedIn(final Player player) { LoginPlayerData data = datas.findDataVia1(player.getName().toLowerCase()); if (data == null) return !alwaysNeedPassword; return data.isOnline() && player.isOnline(); } public boolean hasAccount(final OfflinePlayer player) { return (datas.findDataVia1(player.getName().toLowerCase()) != null); } public boolean isAlwaysNeedPassword() { return alwaysNeedPassword; } public int getAutoLogoutTime() { return autoLogout; } public int getAutoKick() { return autoKick; } public List<String> getCommandWhiteList() { return commandWhiteList; } public boolean isAutoKickCommandUsers() { return autoKickCommandUsers; } public String getUniqueIDKey() { if (uniqueIDKey == null) try { uniqueIDKey = new CrazyCrypt1().encrypt(getServer().getName(), null, "randomKeyGen" + (Math.random() * Integer.MAX_VALUE) + "V:" + getServer().getBukkitVersion() + "'_+' } catch (Exception e) { e.printStackTrace(); return null; } return uniqueIDKey; } public Encryptor getEncryptor() { return encryptor; } public int getAutoDelete() { return autoDelete; } public void setAutoDelete(int autoDelete) { this.autoDelete = autoDelete; } public PairList<String, LoginPlayerData> getPlayerData() { return datas; } public LoginPlayerData getPlayerData(String name) { return datas.findDataVia1(name); } public LoginPlayerData getPlayerData(OfflinePlayer player) { return getPlayerData(player.getName().toLowerCase()); } public void requestLogin(Player player) { if (doNotSpamRequests) return; if (datas.findDataVia1(player.getName().toLowerCase()) == null) sendLocaleMessage("REGISTER.REQUEST", player); else sendLocaleMessage("LOGIN.REQUEST", player); } public boolean isForceSingleSessionEnabled() { return forceSingleSession; } }
package io.rong.util; import io.rong.models.SdkHttpResult; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; public class HttpUtil { private static final String APPKEY = "App-Key"; private static final String NONCE = "Nonce"; private static final String TIMESTAMP = "Timestamp"; private static final String SIGNATURE = "Signature"; //body public static void setBodyParameter(StringBuilder sb, HttpURLConnection conn) throws IOException { DataOutputStream out = new DataOutputStream(conn.getOutputStream()); out.writeBytes(sb.toString()); out.flush(); out.close(); } //header public static HttpURLConnection CreatePostHttpConnection(String appKey, String appSecret, String uri) throws MalformedURLException, IOException, ProtocolException { String nonce = String.valueOf(Math.random() * 1000000); String timestamp = String.valueOf(System.currentTimeMillis()/1000); StringBuilder toSign = new StringBuilder(appSecret).append(nonce) .append(timestamp); String sign = CodeUtil.hexSHA1(toSign.toString()); URL url = new URL(uri); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setUseCaches(false); conn.setDoInput(true); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setInstanceFollowRedirects(true); conn.setRequestProperty(APPKEY, appKey); conn.setRequestProperty(NONCE, nonce); conn.setRequestProperty(TIMESTAMP, timestamp); conn.setRequestProperty(SIGNATURE, sign); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); return conn; } public static byte[] readInputStream(InputStream inStream) throws Exception { ByteArrayOutputStream outStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0; while ((len = inStream.read(buffer)) != -1) { outStream.write(buffer, 0, len); } byte[] data = outStream.toByteArray(); outStream.close(); inStream.close(); return data; } public static SdkHttpResult returnResult(HttpURLConnection conn) throws Exception, IOException { String result = new String(readInputStream(conn.getInputStream())); return new SdkHttpResult(conn.getResponseCode(),result); } }
package minesweeper.logic; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author veeti "walther" haapsamo */ public class GameTest { private Game instance; public GameTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { // Set up a 3x1 board: // [mine, number 1, empty] instance = new Game(3,1,0); instance.board.getSquare(0,0).setMine(); instance.board.recountMines(); instance.board.addNumbers(); } @After public void tearDown() { } /** * Test of turn method, of class Game. */ @Test public void testTurnOnMine() { System.out.println("testTurnOnMine"); int x = 0; int y = 0; instance.turn(x, y); assert(instance.playing == false); assert(instance.won == false); } @Test public void testTurnOnNumber() { System.out.println("testTurnOnNumber"); int x = 1; int y = 0; instance.turn(x, y); assert(instance.playing == true); assert(instance.won == false); } @Test public void testWin() { System.out.println("testTurnOnEmpty"); int x = 2; int y = 0; instance.turn(x, y); instance.board.getSquare(0, 0).toggleFlag(); instance.checkWon(); System.out.println("playing, won: " + instance.playing + "," + instance.won); System.out.println("this.mines, getMines: " + instance.board.mines + "," + instance.board.getMineCount()); System.out.println("invisiblecount: " + instance.board.invisibleCount()); assert(instance.playing == false); assert(instance.won == true); } }
package jade.core; import jade.util.leap.Properties; import jade.util.leap.List; import jade.util.leap.ArrayList; import jade.util.leap.Iterator; import jade.util.BasicProperties; import java.io.IOException; import java.net.*; import java.util.Hashtable; /** * This class allows the JADE core to retrieve configuration-dependent classes * and boot parameters. * <p> * Take care of using different instances of this class when launching * different containers/main-containers on the same JVM otherwise * they would conflict! * * @author Federico Bergenti * @author Giovanni Caire - TILAB * @author Giovanni Rimassa - Universita` di Parma * @version 1.0, 22/11/00 * */ public class ProfileImpl extends Profile { private BasicProperties props = null; // private Properties props = null; /** * Default communication port number. */ public static final int DEFAULT_PORT = 1099; /** This constant is the key of the property whose value is the class name of the mobility manager. **/ public static final String MOBILITYMGRCLASSNAME = "mobility"; private Platform myPlatform = null; private IMTPManager myIMTPManager = null; private acc myACC = null; private MobilityManager myMobilityManager = null; private NotificationManager myNotificationManager = null; private ResourceManager myResourceManager = null; public ProfileImpl(BasicProperties aProp) { props = aProp; try { // Set default values String host = InetAddress.getLocalHost().getHostName(); props.setProperty(MAIN, "true"); props.setProperty(MAIN_PROTO, "rmi"); props.setProperty(MAIN_HOST, host); props.setProperty(MAIN_PORT, Integer.toString(DEFAULT_PORT)); updatePlatformID(); Specifier s = new Specifier(); s.setClassName("jade.mtp.iiop.MessageTransportProtocol"); List l = new ArrayList(1); l.add(s); props.put(MTPS, l); } catch (UnknownHostException uhe) { uhe.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } } /** * Creates a Profile implementation with the default configuration * for launching a main-container on the localhost, * RMI internal Message Transport Protocol, port number 1099, * iiop MTP. */ public ProfileImpl() { this(new BasicProperties()); } /** * This constructor creates a default Profile for launching a platform. * @param host is the name of the host where the main-container should * be listen to. A null value means use the default (i.e. localhost) * @param port is the port number where the main-container should be * listen * for other containers. A negative value should be used for using * the default port number. * @param platformID is the synbolic name of the platform, if * different from default. A null value means use the default * (i.e. localhost) **/ public ProfileImpl(String host, int port, String platformID) { this(); // Call default constructor if(host != null) props.setProperty(MAIN_HOST, host); if(port > 0) props.setIntProperty(MAIN_PORT, port); if(platformID != null) props.setProperty(PLATFORM_ID, platformID); else updatePlatformID(); } public void updatePlatformID() { String h = props.getProperty(MAIN_HOST); String p = props.getProperty(MAIN_PORT); props.setProperty(PLATFORM_ID, h + ":" + p + "/JADE"); } /** * Copy a collection of properties into this profile. * @param source The collection to be copied. */ void copyProperties(BasicProperties source) { props.copyProperties(source); } /** * Return the underlying properties collection. * @return BasicProperties The properties collection. */ public BasicProperties getProperties() { return props; } /** HP. private MainContainerImpl theMainContainer = null; public void addPlatformListener(AgentManager.Listener aListener) throws NotFoundException { if (theMainContainer == null) { throw new NotFoundException("Unable to add listener, main container not set"); } theMainContainer.addListener(aListener); } public void removePlatformListener(AgentManager.Listener aListener) throws NotFoundException { if (theMainContainer == null) { throw new NotFoundException("Unable to remove listener, main container not set"); } theMainContainer.removeListener(aListener); } **/ /** * Assign the given value to the given property name. * * @param key is the property name * @param value is the property value */ public void setParameter(String key, String value) { props.put(key, value); } /** * Assign the given property value to the given property name * * @param key is the property name * @param value is the property value */ public void setSpecifiers(String key, List value) { props.put(key, value); } protected Platform getPlatform() throws ProfileException { if (myPlatform == null) { createPlatform(); } return myPlatform; } protected IMTPManager getIMTPManager() throws ProfileException { if (myIMTPManager == null) { createIMTPManager(); } return myIMTPManager; } protected acc getAcc() throws ProfileException { if (myACC == null) { createACC(); } return myACC; } protected MobilityManager getMobilityManager() throws ProfileException { if (myMobilityManager == null) { createMobilityManager(); } return myMobilityManager; } protected ResourceManager getResourceManager() throws ProfileException { if (myResourceManager == null) { createResourceManager(); } return myResourceManager; } protected NotificationManager getNotificationManager() throws ProfileException { if (myNotificationManager == null) { createNotificationManager(); } return myNotificationManager; } public jade.security.PwdDialog getPwdDialog() throws ProfileException { //default is GUI swing password dialog String className = getParameter(PWD_DIALOG_CLASS, "jade.security.impl.PwdDialogSwingImpl"); jade.security.PwdDialog dialog=null; try { dialog = (jade.security.PwdDialog) Class.forName(className).newInstance(); } catch (Exception e) { //throw new ProfileException("Error loading jade.security password dialog:"+className); //e.printStackTrace(); System.out.println("\nError: Could not load jade.security password dialog class: '"+PWD_DIALOG_CLASS+"' "); System.out.println("\n Check parameter: '"+Profile.PWD_DIALOG_CLASS+"' in your JADE config file." ); System.out.println("\n Its default value is: jade.security.impl.PwdDialogSwingImpl" ); System.exit(-1); } return dialog; } /** * Method declaration * * @throws ProfileException * * @see */ private void createPlatform() throws ProfileException { try { String isMain = props.getProperty(MAIN); if (isMain == null || CaseInsensitiveString.equalsIgnoreCase(isMain, "true")) { // The real Main myPlatform = new MainContainerImpl(this); // HP myPlatform = theMainContainer = new MainContainerImpl(this); } else { // A proxy to the Main myPlatform = new MainContainerProxy(this); } } catch (IMTPException imtpe) { throw new ProfileException("Can't get a stub of the MainContainer: "+imtpe.getMessage()); } } /** * Method declaration * * @throws ProfileException * * @see */ private void createIMTPManager() throws ProfileException { // Get the parameter from the profile, use the RMI IMTP by default String className = getParameter(IMTP, "jade.imtp.rmi.RMIIMTPManager"); try { myIMTPManager = (IMTPManager) Class.forName(className).newInstance(); } catch (Exception e) { e.printStackTrace(); throw new ProfileException("Error loading IMTPManager class "+className); } } /** * Method declaration * * @throws ProfileException * * @see */ private void createACC() throws ProfileException { // Use the Full ACC by default String className = new String("jade.core.FullAcc"); try { myACC = (acc) Class.forName(className).newInstance(); } catch (Exception e) { throw new ProfileException("Error loading acc class "+className); } } /** * Method declaration * * @throws ProfileException * * @see */ private void createMobilityManager() throws ProfileException { String className = getParameter(MOBILITYMGRCLASSNAME, "jade.core.RealMobilityManager"); // default is real mobility manager try { myMobilityManager = (MobilityManager) Class.forName(className).newInstance(); } catch (Exception e) { throw new ProfileException("Error loading MobilityManager class "+className); } } private void createResourceManager() throws ProfileException { myResourceManager = new FullResourceManager(); } private void createNotificationManager() throws ProfileException { myNotificationManager = new RealNotificationManager(); } /** * Retrieve a String value from the configuration properties. * If no parameter corresponding to the specified key is found, * return the provided default. * @param key The key identifying the parameter to be retrieved * among the configuration properties. */ public String getParameter(String key, String aDefault) { return props.getProperty(key, aDefault); } /** * Retrieve a list of Specifiers from the configuration properties. * Agents, MTPs and other items are specified among the configuration * properties in this way. * If no list of Specifiers corresponding to the specified key is found, * an empty list is returned. * @param key The key identifying the list of Specifiers to be retrieved * among the configuration properties. */ public List getSpecifiers(String key) throws ProfileException { List l = (List)props.get(key); if(l == null) l = new ArrayList(0); return l; } public String toString() { StringBuffer str = new StringBuffer("(Profile"); String[] properties = props.toStringArray(); if (properties != null) for (int i=0; i<properties.length; i++) str.append(" "+properties[i]); str.append(")"); return str.toString(); } }
package com.cradle.iitc_mobile; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.content.res.AssetManager; import android.net.Uri; import android.net.http.SslError; import android.os.Environment; import android.preference.PreferenceManager; import android.util.Log; import android.webkit.SslErrorHandler; import android.webkit.WebResourceResponse; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Toast; import com.cradle.iitc_mobile.async.UrlContentToString; import org.json.JSONObject; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.net.URL; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Scanner; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; public class IITC_WebViewClient extends WebViewClient { private static final ByteArrayInputStream STYLE = new ByteArrayInputStream( "body, #dashboard_container, #map_canvas { background: #000 !important; }" .getBytes()); private static final ByteArrayInputStream EMPTY = new ByteArrayInputStream( "".getBytes()); private String mIitcScript = null; private String mIitcPath = null; private final Context mContext; public IITC_WebViewClient(Context c) { this.mContext = c; this.mIitcPath = Environment.getExternalStorageDirectory().getPath() + "/IITC_Mobile/"; } public String getIITCVersion() { HashMap<String, String> map = getScriptInfo(mIitcScript); return map.get("version"); } public HashMap<String, String> getScriptInfo(String js) { HashMap<String, String> map = new HashMap<String, String>(); String header = ""; if (js != null) { header = js.substring(js.indexOf("==UserScript=="), js.indexOf("==/UserScript==")); } // remove new line comments header = header.replace("\n // get a list of key-value String[] attributes = header.split(" +"); String iitc_version = "not found"; for (int i = 0; i < attributes.length; i++) { // search for attributes and use the value if (attributes[i].equals("@version")) { map.put("version", attributes[i + 1]); } if (attributes[i].equals("@name")) { map.put("name", attributes[i + 1]); } if (attributes[i].equals("@description")) { map.put("description", attributes[i + 1]); } } return map; } public String getGmInfoJson(HashMap<String, String> map) { JSONObject jObject = new JSONObject(map); return "{\"script\":" + jObject.toString() + "}"; } public void loadIITC_JS(Context c) throws java.io.IOException { // You are able to load the script from external source // if a http address is given, use script from this address. else use // the local script SharedPreferences sharedPref = PreferenceManager .getDefaultSharedPreferences(c); String iitc_source = sharedPref.getString("pref_iitc_source", "local"); String js = ""; // if developer mode are enabled, load all iitc script from external // storage Log.d("iitcm", "adding iitc main script"); if (sharedPref.getBoolean("pref_dev_checkbox", false)) { js = this.fileToString(mIitcPath + "dev/total-conversion-build.user.js", false); if (js.equals("false")) { Toast.makeText(mContext, "File " + mIitcPath + "dev/total-conversion-build.user.js not found. " + "Disable developer mode or add iitc files to the dev folder.", Toast.LENGTH_LONG).show(); return; } else { Toast.makeText(mContext, "Developer mode enabled", Toast.LENGTH_SHORT).show(); } } else { // load iitc script from web or asset folder if (iitc_source.contains("http")) { URL url = new URL(iitc_source); // if parsing of the online iitc source timed out, use the script from assets try { js = new UrlContentToString().execute(url).get(5, TimeUnit.SECONDS); } catch (InterruptedException e) { e.printStackTrace(); js = this.fileToString("total-conversion-build.user.js", true); } catch (ExecutionException e) { e.printStackTrace(); js = this.fileToString("total-conversion-build.user.js", true); } catch (TimeoutException e) { e.printStackTrace(); js = this.fileToString("total-conversion-build.user.js", true); } } else { js = this.fileToString("total-conversion-build.user.js", true); } } PackageManager pm = mContext.getPackageManager(); boolean hasMultitouch = pm .hasSystemFeature(PackageManager.FEATURE_TOUCHSCREEN_MULTITOUCH); boolean forcedZoom = sharedPref.getBoolean("pref_user_zoom", false); if (hasMultitouch && !forcedZoom) { js = js.replace("window.showZoom = true;", "window.showZoom = false;"); } // hide layer chooser on desktop mode // on mobile mode it is hidden via smartphone.css boolean desktopMode = sharedPref.getBoolean("pref_force_desktop", false); if (desktopMode) { js = js.replace("window.showLayerChooser = true;", "window.showLayerChooser = false"); } String gmInfo = "GM_info=" + getGmInfoJson(getScriptInfo(js)).toString() + "\n"; this.mIitcScript = gmInfo + js; } // enable https @Override public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) { handler.proceed(); } @Override public void onPageFinished(WebView view, String url) { if (url.startsWith("http: || url.startsWith("https: Log.d("iitcm", "injecting iitc.."); view.loadUrl("javascript: " + this.mIitcScript); loadPlugins(view); } super.onPageFinished(view, url); } /** * this method is called automatically when the Google login form is opened. */ @Override public void onReceivedLoginRequest(WebView view, String realm, String account, String args) { Log.d("iitcm", "Login requested: " + realm + " " + account + " " + args); Log.d("iitcm", "logging in...updating caching mode"); ((IITC_WebView) view).updateCaching(true); //((IITC_Mobile) mContext).onReceivedLoginRequest(this, view, realm, account, args); } public void loadPlugins(WebView view) { // get the plugin preferences SharedPreferences sharedPref = PreferenceManager .getDefaultSharedPreferences(mContext); boolean dev_enabled = sharedPref.getBoolean("pref_dev_checkbox", false); String path = (dev_enabled) ? mIitcPath + "dev/plugins/" : "plugins/"; Map<String, ?> all_prefs = sharedPref.getAll(); // iterate through all plugins for (Map.Entry<String, ?> entry : all_prefs.entrySet()) { String plugin = entry.getKey(); if (plugin.endsWith("user.js") && entry.getValue().toString().equals("true")) { if (!plugin.startsWith(mIitcPath)) { // load default iitc plugins Log.d("iitcm", "adding plugin " + plugin); loadJS(path + plugin, !dev_enabled, view); } else { // load user iitc plugins Log.d("iitcm", "adding user plugin " + plugin); loadJS(plugin, false, view); } } } // inject the user location script if enabled in settings if (sharedPref.getBoolean("pref_user_loc", false)) { path = path.replace("plugins/", ""); loadJS(path + "user-location.user.js", !dev_enabled, view); } } // read a file into a string // load it as javascript public boolean loadJS(String file, boolean asset, WebView view) { String js = fileToString(file, asset); if (js.equals("false")) { return false; } else { String gmInfo = "GM_info=" + getGmInfoJson(getScriptInfo(js)) + "\n"; view.loadUrl("javascript:" + gmInfo + js); } return true; } // read a file into a string // use the full path for File // if asset == true use the asset manager to open file public String fileToString(String file, boolean asset) { Scanner s = null; String src = ""; if (!asset) { File js_file = new File(file); try { s = new Scanner(js_file).useDelimiter("\\A"); } catch (FileNotFoundException e) { e.printStackTrace(); Log.d("iitcm", "failed to parse file " + file); return "false"; } } else { // load plugins from asset folder AssetManager am = mContext.getAssets(); try { s = new Scanner(am.open(file)).useDelimiter("\\A"); } catch (IOException e) { e.printStackTrace(); Log.d("iitcm", "failed to parse file assets/" + file); return "false"; } } if (s != null) { src = s.hasNext() ? s.next() : ""; } return src; } // with our own content. This is used to block loading Niantic resources @Override public WebResourceResponse shouldInterceptRequest(final WebView view, String url) { if (url.contains("/css/common.css")) { return new WebResourceResponse("text/css", "UTF-8", STYLE); // } else if (url.contains("gen_dashboard.js")) { // // define initialize function to get rid of JS ReferenceError on intel page's 'onLoad' // String gen_dashboad_replacement = "window.initialize = function() {}"; // return new WebResourceResponse("text/javascript", "UTF-8", // new ByteArrayInputStream(gen_dashboad_replacement.getBytes())); } else if (url.contains("/css/ap_icons.css") || url.contains("/css/map_icons.css") || url.contains("/css/common.css") || url.contains("/css/misc_icons.css") || url.contains("/css/style_full.css") || url.contains("/css/style_mobile.css") || url.contains("/css/portalrender.css") || url.contains("/css/portalrender_mobile.css") || url.contains("js/analytics.js") || url.contains("google-analytics.com/ga.js")) { return new WebResourceResponse("text/plain", "UTF-8", EMPTY); } else { return super.shouldInterceptRequest(view, url); } } // start non-ingress-intel-urls in another app... @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { if (url.contains("ingress.com") || url.contains("appengine.google.com")) { // reload iitc if a poslink is clicked inside the app if (url.contains("intel?ll=") || (url.contains("latE6") && url.contains("lngE6"))) { Log.d("iitcm", "should be an internal clicked position link...reload script for: " + url); ((IITC_Mobile) mContext).loadUrl(url); } if (url.contains("logout")) { Log.d("iitcm", "logging out...updating caching mode"); ((IITC_WebView) view).updateCaching(true); } return false; } else { Log.d("iitcm", "no ingress intel link, start external app to load url: " + url); Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); mContext.startActivity(intent); return true; } } }
package com.brentvatne.react; import android.content.res.AssetFileDescriptor; import android.graphics.Matrix; import android.media.MediaPlayer; import android.net.Uri; import android.os.Handler; import android.util.Log; import android.view.MotionEvent; import android.webkit.CookieManager; import android.widget.MediaController; import com.danikula.videocache.HttpProxyCacheServer; import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.LifecycleEventListener; import com.facebook.react.bridge.WritableMap; import com.facebook.react.uimanager.ThemedReactContext; import com.facebook.react.uimanager.events.RCTEventEmitter; import com.yqritc.scalablevideoview.ScalableType; import com.yqritc.scalablevideoview.ScalableVideoView; import com.android.vending.expansion.zipfile.APKExpansionSupport; import com.android.vending.expansion.zipfile.ZipResourceFile; import com.yqritc.scalablevideoview.ScaleManager; import com.yqritc.scalablevideoview.Size; import java.io.IOException; import java.util.HashMap; import java.util.Map; public class ReactVideoView extends ScalableVideoView implements MediaPlayer.OnPreparedListener, MediaPlayer .OnErrorListener, MediaPlayer.OnBufferingUpdateListener, MediaPlayer.OnCompletionListener, MediaPlayer.OnInfoListener, LifecycleEventListener, MediaController.MediaPlayerControl { public enum Events { EVENT_LOAD_START("onVideoLoadStart"), EVENT_LOAD("onVideoLoad"), EVENT_ERROR("onVideoError"), EVENT_PROGRESS("onVideoProgress"), EVENT_SEEK("onVideoSeek"), EVENT_END("onVideoEnd"), EVENT_STALLED("onPlaybackStalled"), EVENT_RESUME("onPlaybackResume"), EVENT_READY_FOR_DISPLAY("onReadyForDisplay"); private final String mName; Events(final String name) { mName = name; } @Override public String toString() { return mName; } } public static final String EVENT_PROP_FAST_FORWARD = "canPlayFastForward"; public static final String EVENT_PROP_SLOW_FORWARD = "canPlaySlowForward"; public static final String EVENT_PROP_SLOW_REVERSE = "canPlaySlowReverse"; public static final String EVENT_PROP_REVERSE = "canPlayReverse"; public static final String EVENT_PROP_STEP_FORWARD = "canStepForward"; public static final String EVENT_PROP_STEP_BACKWARD = "canStepBackward"; public static final String EVENT_PROP_DURATION = "duration"; public static final String EVENT_PROP_PLAYABLE_DURATION = "playableDuration"; public static final String EVENT_PROP_CURRENT_TIME = "currentTime"; public static final String EVENT_PROP_SEEK_TIME = "seekTime"; public static final String EVENT_PROP_NATURALSIZE = "naturalSize"; public static final String EVENT_PROP_WIDTH = "width"; public static final String EVENT_PROP_HEIGHT = "height"; public static final String EVENT_PROP_ORIENTATION = "orientation"; public static final String EVENT_PROP_ERROR = "error"; public static final String EVENT_PROP_WHAT = "what"; public static final String EVENT_PROP_EXTRA = "extra"; private ThemedReactContext mThemedReactContext; private RCTEventEmitter mEventEmitter; private Handler mProgressUpdateHandler = new Handler(); private Runnable mProgressUpdateRunnable = null; private Handler videoControlHandler = new Handler(); private MediaController mediaController; private String mSrcUriString = null; private String mSrcType = "mp4"; private boolean mSrcIsNetwork = false; private boolean mSrcIsAsset = false; private ScalableType mResizeMode = ScalableType.LEFT_TOP; private boolean mRepeat = false; private boolean mPaused = false; private boolean mMuted = false; private float mVolume = 1.0f; private float mRate = 1.0f; private boolean mPlayInBackground = false; private boolean mActiveStatePauseStatus = false; private int mMainVer = 0; private int mPatchVer = 0; private boolean mMediaPlayerValid = false; // True if mMediaPlayer is in prepared, started, paused or completed state. private int mVideoDuration = 0; private int mVideoBufferedDuration = 0; private boolean isCompleted = false; private boolean mUseNativeControls = false; public ReactVideoView(ThemedReactContext themedReactContext) { super(themedReactContext); mThemedReactContext = themedReactContext; mEventEmitter = themedReactContext.getJSModule(RCTEventEmitter.class); themedReactContext.addLifecycleEventListener(this); initializeMediaPlayerIfNeeded(); setSurfaceTextureListener(this); mProgressUpdateRunnable = new Runnable() { @Override public void run() { if (mMediaPlayerValid &&!mPaused) { WritableMap event = Arguments.createMap(); event.putDouble(EVENT_PROP_CURRENT_TIME, mMediaPlayer.getCurrentPosition() / 1000.0); event.putDouble(EVENT_PROP_PLAYABLE_DURATION, mVideoBufferedDuration / 1000.0); //TODO:mBufferUpdateRunnable mEventEmitter.receiveEvent(getId(), Events.EVENT_PROGRESS.toString(), event); // Check for update after an interval // TODO: The update interval is fixed at 250. There is a property in React component that defines this value. Totally ignored !!! mProgressUpdateHandler.postDelayed(mProgressUpdateRunnable, 250); } } }; } @Override public boolean onTouchEvent(MotionEvent event) { if (mUseNativeControls) { initializeMediaControllerIfNeeded(); mediaController.show(); } return super.onTouchEvent(event); } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); if (!changed || !mMediaPlayerValid) { return; } int videoWidth = getVideoWidth(); int videoHeight = getVideoHeight(); if (videoWidth == 0 || videoHeight == 0) { return; } Size viewSize = new Size(getWidth(), getHeight()); Size videoSize = new Size(videoWidth, videoHeight); ScaleManager scaleManager = new ScaleManager(viewSize, videoSize); Matrix matrix = scaleManager.getScaleMatrix(mScalableType); if (matrix != null) { setTransform(matrix); } } private void initializeMediaPlayerIfNeeded() { if (mMediaPlayer == null) { mMediaPlayerValid = false; mMediaPlayer = new MediaPlayer(); mMediaPlayer.setScreenOnWhilePlaying(true); mMediaPlayer.setOnVideoSizeChangedListener(this); mMediaPlayer.setOnErrorListener(this); mMediaPlayer.setOnPreparedListener(this); mMediaPlayer.setOnBufferingUpdateListener(this); mMediaPlayer.setOnCompletionListener(this); mMediaPlayer.setOnInfoListener(this); } } private void initializeMediaControllerIfNeeded() { if (mediaController == null) { mediaController = new MediaController(this.getContext()); } } public void cleanupMediaPlayerResources() { if ( mediaController != null ) { mediaController.hide(); } if ( mMediaPlayer != null ) { mMediaPlayerValid = false; mMediaPlayer.stop(); mMediaPlayer.release(); } } public void setSrc(final String uriString, final String type, final boolean isNetwork, final boolean isAsset) { setSrc(uriString,type,isNetwork,isAsset,0,0); } public void setSrc(final String uriString, final String type, final boolean isNetwork, final boolean isAsset, final int expansionMainVersion, final int expansionPatchVersion) { mSrcUriString = uriString; mSrcType = type; mSrcIsNetwork = isNetwork; mSrcIsAsset = isAsset; mMainVer = expansionMainVersion; mPatchVer = expansionPatchVersion; mMediaPlayerValid = false; mVideoDuration = 0; mVideoBufferedDuration = 0; initializeMediaPlayerIfNeeded(); mMediaPlayer.reset(); try { if (isNetwork) { HttpProxyCacheServer proxy = ProxyFactory.getProxy(this.getContext()); String proxyUrl = proxy.getProxyUrl(uriString); // Use the shared CookieManager to access the cookies // set by WebViews inside the same app CookieManager cookieManager = CookieManager.getInstance(); Uri parsedUrl = Uri.parse(proxyUrl); Uri.Builder builtUrl = parsedUrl.buildUpon(); String cookie = cookieManager.getCookie(builtUrl.build().toString()); Map<String, String> headers = new HashMap<String, String>(); if (cookie != null) { headers.put("Cookie", cookie); } setDataSource(mThemedReactContext, parsedUrl, headers); } else if (isAsset) { if (uriString.startsWith("content: Uri parsedUrl = Uri.parse(uriString); setDataSource(mThemedReactContext, parsedUrl); } else { setDataSource(uriString); } } else { ZipResourceFile expansionFile= null; AssetFileDescriptor fd= null; if(mMainVer>0) { try { expansionFile = APKExpansionSupport.getAPKExpansionZipFile(mThemedReactContext, mMainVer, mPatchVer); fd = expansionFile.getAssetFileDescriptor(uriString.replace(".mp4","") + ".mp4"); } catch (IOException e) { e.printStackTrace(); } catch (NullPointerException e) { e.printStackTrace(); } } if(fd==null) { int identifier = mThemedReactContext.getResources().getIdentifier( uriString, "drawable", mThemedReactContext.getPackageName() ); if (identifier == 0) { identifier = mThemedReactContext.getResources().getIdentifier( uriString, "raw", mThemedReactContext.getPackageName() ); } setRawData(identifier); } else { setDataSource(fd.getFileDescriptor(), fd.getStartOffset(),fd.getLength()); } } } catch (Exception e) { e.printStackTrace(); return; } WritableMap src = Arguments.createMap(); src.putString(ReactVideoViewManager.PROP_SRC_URI, uriString); src.putString(ReactVideoViewManager.PROP_SRC_TYPE, type); src.putBoolean(ReactVideoViewManager.PROP_SRC_IS_NETWORK, isNetwork); if(mMainVer>0) { src.putInt(ReactVideoViewManager.PROP_SRC_MAINVER, mMainVer); if(mPatchVer>0) { src.putInt(ReactVideoViewManager.PROP_SRC_PATCHVER, mPatchVer); } } WritableMap event = Arguments.createMap(); event.putMap(ReactVideoViewManager.PROP_SRC, src); mEventEmitter.receiveEvent(getId(), Events.EVENT_LOAD_START.toString(), event); // not async to prevent random crashes on Android playback from local resource due to race conditions try { prepareAsync(this); } catch (Exception e) { e.printStackTrace(); } } public void setResizeModeModifier(final ScalableType resizeMode) { mResizeMode = resizeMode; if (mMediaPlayerValid) { setScalableType(resizeMode); invalidate(); } } public void setRepeatModifier(final boolean repeat) { mRepeat = repeat; if (mMediaPlayerValid) { setLooping(repeat); } } public void setPausedModifier(final boolean paused) { mPaused = paused; if (!mMediaPlayerValid) { return; } if (mPaused) { if (mMediaPlayer.isPlaying()) { pause(); } } else { if (!mMediaPlayer.isPlaying()) { start(); // Also Start the Progress Update Handler mProgressUpdateHandler.post(mProgressUpdateRunnable); } } } public void setMutedModifier(final boolean muted) { mMuted = muted; if (!mMediaPlayerValid) { return; } if (mMuted) { setVolume(0, 0); } else { setVolume(mVolume, mVolume); } } public void setVolumeModifier(final float volume) { mVolume = volume; setMutedModifier(mMuted); } public void setRateModifier(final float rate) { mRate = rate; if (mMediaPlayerValid) { // TODO: Implement this. Log.e(ReactVideoViewManager.REACT_CLASS, "Setting playback rate is not yet supported on Android"); } } public void applyModifiers() { setResizeModeModifier(mResizeMode); setRepeatModifier(mRepeat); setPausedModifier(mPaused); setMutedModifier(mMuted); // setRateModifier(mRate); } public void setPlayInBackground(final boolean playInBackground) { mPlayInBackground = playInBackground; } public void setControls(boolean controls) { this.mUseNativeControls = controls; } @Override public void onPrepared(MediaPlayer mp) { mMediaPlayerValid = true; mVideoDuration = mp.getDuration(); WritableMap naturalSize = Arguments.createMap(); naturalSize.putInt(EVENT_PROP_WIDTH, mp.getVideoWidth()); naturalSize.putInt(EVENT_PROP_HEIGHT, mp.getVideoHeight()); if (mp.getVideoWidth() > mp.getVideoHeight()) naturalSize.putString(EVENT_PROP_ORIENTATION, "landscape"); else naturalSize.putString(EVENT_PROP_ORIENTATION, "portrait"); WritableMap event = Arguments.createMap(); event.putDouble(EVENT_PROP_DURATION, mVideoDuration / 1000.0); event.putDouble(EVENT_PROP_CURRENT_TIME, mp.getCurrentPosition() / 1000.0); event.putMap(EVENT_PROP_NATURALSIZE, naturalSize); // TODO: Actually check if you can. event.putBoolean(EVENT_PROP_FAST_FORWARD, true); event.putBoolean(EVENT_PROP_SLOW_FORWARD, true); event.putBoolean(EVENT_PROP_SLOW_REVERSE, true); event.putBoolean(EVENT_PROP_REVERSE, true); event.putBoolean(EVENT_PROP_FAST_FORWARD, true); event.putBoolean(EVENT_PROP_STEP_BACKWARD, true); event.putBoolean(EVENT_PROP_STEP_FORWARD, true); mEventEmitter.receiveEvent(getId(), Events.EVENT_LOAD.toString(), event); applyModifiers(); if (mUseNativeControls) { initializeMediaControllerIfNeeded(); mediaController.setMediaPlayer(this); mediaController.setAnchorView(this); videoControlHandler.post(new Runnable() { @Override public void run() { mediaController.setEnabled(true); mediaController.show(); } }); } } @Override public boolean onError(MediaPlayer mp, int what, int extra) { WritableMap error = Arguments.createMap(); error.putInt(EVENT_PROP_WHAT, what); error.putInt(EVENT_PROP_EXTRA, extra); WritableMap event = Arguments.createMap(); event.putMap(EVENT_PROP_ERROR, error); mEventEmitter.receiveEvent(getId(), Events.EVENT_ERROR.toString(), event); return true; } @Override public boolean onInfo(MediaPlayer mp, int what, int extra) { switch (what) { case MediaPlayer.MEDIA_INFO_BUFFERING_START: mEventEmitter.receiveEvent(getId(), Events.EVENT_STALLED.toString(), Arguments.createMap()); break; case MediaPlayer.MEDIA_INFO_BUFFERING_END: mEventEmitter.receiveEvent(getId(), Events.EVENT_RESUME.toString(), Arguments.createMap()); break; case MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START: mEventEmitter.receiveEvent(getId(), Events.EVENT_READY_FOR_DISPLAY.toString(), Arguments.createMap()); break; default: } return false; } @Override public void onBufferingUpdate(MediaPlayer mp, int percent) { mVideoBufferedDuration = (int) Math.round((double) (mVideoDuration * percent) / 100.0); } @Override public void seekTo(int msec) { if (mMediaPlayerValid) { WritableMap event = Arguments.createMap(); event.putDouble(EVENT_PROP_CURRENT_TIME, getCurrentPosition() / 1000.0); event.putDouble(EVENT_PROP_SEEK_TIME, msec / 1000.0); mEventEmitter.receiveEvent(getId(), Events.EVENT_SEEK.toString(), event); super.seekTo(msec); if (isCompleted && mVideoDuration != 0 && msec < mVideoDuration) { isCompleted = false; } if (!mPaused) { start(); } } } @Override public int getBufferPercentage() { return 0; } @Override public boolean canPause() { return true; } @Override public boolean canSeekBackward() { return true; } @Override public boolean canSeekForward() { return true; } @Override public int getAudioSessionId() { return 0; } @Override public void onCompletion(MediaPlayer mp) { isCompleted = true; mEventEmitter.receiveEvent(getId(), Events.EVENT_END.toString(), null); } @Override protected void onDetachedFromWindow() { mMediaPlayerValid = false; super.onDetachedFromWindow(); } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); if(mMainVer>0) { setSrc(mSrcUriString, mSrcType, mSrcIsNetwork,mSrcIsAsset,mMainVer,mPatchVer); } else { setSrc(mSrcUriString, mSrcType, mSrcIsNetwork,mSrcIsAsset); } } @Override public void onHostPause() { if (mMediaPlayer != null && !mPlayInBackground) { mActiveStatePauseStatus = mPaused; // Pause the video in background setPausedModifier(true); } } @Override public void onHostResume() { if (mMediaPlayer != null && !mPlayInBackground) { new Handler().post(new Runnable() { @Override public void run() { // Restore original state setPausedModifier(mActiveStatePauseStatus); } }); } } @Override public void onHostDestroy() { } }
package edu.nyu.cs.omnidroid.ui; import java.util.ArrayList; import java.util.HashMap; import android.app.Activity; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.content.ContentValues; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.text.Html; import android.view.ContextMenu; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ContextMenu.ContextMenuInfo; import android.view.View.OnClickListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.Toast; import android.widget.AdapterView.AdapterContextMenuInfo; import edu.nyu.cs.omnidroid.R; import edu.nyu.cs.omnidroid.core.CP; import edu.nyu.cs.omnidroid.util.AGParser; import edu.nyu.cs.omnidroid.util.UGParser; /** * List current applications that should be called when the event passed to us occurs. Allow the * user to add more applications to this list. * * @author acase * */ public class Actions extends Activity implements OnClickListener { // Menu Options of the Context variety (Android menus require int) //TODO: private static final int MENU_EDIT = 0; private static final int MENU_DELETE = 1; // Menu options of the Standard variety (Android menus require int) private static final int MENU_HELP = 3; // Intent data passed along private String eventApp; private String eventName; private String filterType; private String filterData; private String throwerApp; private String throwerAction; private String throwerData1; private String throwerData2; private int throwerData1Type; private int throwerData2Type; // List of applications to notify private static final int MAX_NUM_THROWERS = 1; private ListView throwerListView; private ArrayList<String> throwerList = new ArrayList<String>(); // Name to save this OmniHandler as private String omniHandlerName; /* * (non-Javadoc) * * @see android.app.Activity#onCreate(android.os.Bundle) */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.actions); throwerListView = (ListView) findViewById(R.id.throwers_list); // Present the save button Button save = (Button) findViewById(R.id.throwers_save); save.setOnClickListener(this); Button add = (Button) findViewById(R.id.throwers_add); add.setOnClickListener(this); // See what application we want to handle events for from the getIntentData(getIntent()); // Present an updated list of filters we have applied update(); } private void update() { // Clear the list so that it's empty, then it can be filled throwerList.clear(); // Populate a list of active filters if (throwerApp != null) { throwerList.add(throwerApp); } // Display a list of active filters ArrayAdapter<String> listadpt = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, throwerList); throwerListView.setAdapter(listadpt); throwerListView.setTextFilterEnabled(true); registerForContextMenu(throwerListView); // TODO(acase): Allow more than MAX_NUM_DATA // Disable the add button if we've reached the maximum number of thrower apps Button add = (Button) findViewById(R.id.throwers_add); if (throwerList.size() < MAX_NUM_THROWERS) { add.setEnabled(true); } else { add.setEnabled(false); } // Disable the save button if haven't added any throwers yet Button save = (Button) findViewById(R.id.throwers_save); if (throwerList.size() > 0 ) { save.setEnabled(true); } else { save.setEnabled(false); } } /** * Get the data passed in and store it in our class variables * @param i - intent containing data to fill our User Config with. */ private void getIntentData(Intent i) { // intent data passed to us. Bundle extras = i.getExtras(); if (extras != null) { eventApp = extras.getString(AGParser.KEY_APPLICATION); eventName = extras.getString(UGParser.KEY_EVENT_TYPE); filterType = extras.getString(UGParser.KEY_FILTER_TYPE); filterData = extras.getString(UGParser.KEY_FILTER_DATA); throwerApp = extras.getString(UGParser.KEY_ACTION_APP); throwerAction = extras.getString(UGParser.KEY_ACTION_TYPE); throwerData1 = extras.getString(UGParser.KEY_ACTION_DATA1); throwerData2 = extras.getString(UGParser.KEY_ACTION_DATA2); throwerData1Type = extras.getInt(ActionData.KEY_DATA1_TYPE); throwerData2Type = extras.getInt(ActionData.KEY_DATA2_TYPE); } } /* * (non-Javadoc) If an item is selected, go to it's edit page. * * @see android.app.ListActivity#onListItemClick(android.widget.ListView, android.view.View, int, * long) */ protected void onListItemClick(ListView l, View v, int position, long id) { Uri data = getIntent().getData(); editThrower(data, id); } /* * (non-Javadoc) * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu) */ public boolean onCreateOptionsMenu(Menu menu) { menu.add(0, MENU_HELP, 0, R.string.help).setIcon(android.R.drawable.ic_menu_help); return true; } /* * (non-Javadoc) * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem) */ public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case MENU_HELP: help(); return true; } return false; } /* * (non-Javadoc) * * @see android.app.Activity#onCreateContextMenu(android.view.ContextMenu, android.view.View, * android.view.ContextMenu.ContextMenuInfo) */ public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); // TODO(acase): Edit // menu.add(0, MENU_EDIT, 0, R.string.edit); menu.add(0, MENU_DELETE, 0, R.string.del); } /* * (non-Javadoc) * * @see android.app.Activity#onContextItemSelected(android.view.MenuItem) */ public boolean onContextItemSelected(MenuItem item) { switch(item.getItemId()) { case MENU_DELETE: AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo(); deleteThrower(info.id); return true; } return super.onContextItemSelected(item); } /** * Delete the thrower from this omnihandler * * @param id * - the item id selected */ private void deleteThrower(long id) { // Remove item from the list throwerList.remove((int)id); // Clear it from our intents // TODO(acase): this will need to be changed once we support more than one thrower throwerApp = null; throwerAction = null; throwerData1 = null; throwerData2 = null; // Update our UI update(); } /** * TODO(acase): Allow edit of already set filters * * @param data * @param l * - the item id selected * @return void */ private void editThrower(Uri data, long l) { } /** * Add a new filter to this OmniHandler * * @return void */ private void addThrower() { Intent i = new Intent(); i.setClass(this.getApplicationContext(), ActionAdd.class); i.putExtra(AGParser.KEY_APPLICATION, eventApp); i.putExtra(UGParser.KEY_EVENT_TYPE, eventName); i.putExtra(UGParser.KEY_FILTER_TYPE, filterType); i.putExtra(UGParser.KEY_FILTER_DATA, filterData); startActivityForResult(i, Constants.RESULT_ADD_THROWER); } /** * Call our Help dialog * * @return void */ private void help() { Builder help = new AlertDialog.Builder(this); // TODO(acase): Move to some kind of resource String help_msg = "Use the 'Menu' button followed by 'Add Thrower' to add throwers that " + "the OmniHandler will fire of when the previously selected event occurs.\n" + "When done adding throwers, select 'Next' to proceed."; help.setTitle(R.string.help); help.setIcon(android.R.drawable.ic_menu_help); help.setMessage(Html.fromHtml(help_msg)); help.setPositiveButton(R.string.okay, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { } }); help.show(); } /* * (non-Javadoc) * * @see android.view.View.OnClickListener#onClick(android.view.View) */ /* * (non-Javadoc) Add OmniHandler to OmniDroid if appropriate * * @see android.view.View.OnClickListener#onClick(android.view.View) */ public void onClick(View v) { switch (v.getId()) { case R.id.throwers_add: addThrower(); break; case R.id.throwers_save: saveDialog(); break; } } private void saveDialog() { LayoutInflater factory = LayoutInflater.from(this); final View textEntryView = factory.inflate(R.layout.save_dialog, null); Builder save_dialog = new AlertDialog.Builder(this); save_dialog.setIcon(android.R.drawable.ic_dialog_alert); save_dialog.setTitle(R.string.save_as); save_dialog.setView(textEntryView); save_dialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { } }); save_dialog.setPositiveButton(R.string.save, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { EditText v = (EditText) textEntryView.findViewById(R.id.save_dialog_name); omniHandlerName = v.getText().toString(); save(); } }); save_dialog.create(); save_dialog.show(); } /** * Save this OmniHandler. * * Side effects: * + Adds data to Content Provider * + Adds data to UGParser */ private void save() { // Add OmniHandler to OmniDroid if (omniHandlerName.length() < 1) { Toast.makeText(getBaseContext(), R.string.missing_name, Toast.LENGTH_LONG).show(); return; } if (throwerApp == null) { Toast.makeText(getBaseContext(), R.string.missing_thrower, Toast.LENGTH_LONG).show(); return; } ContentValues values; Uri uri1 = null; Uri uri2 = null; // Store in CP if necessary if (throwerData1 != null) { if (throwerData1Type == ActionData.DATA_TYPE_MANUAL) { // Add OmniHandler Data1 to the CP values = new ContentValues(); values.put(CP.INSTANCE_NAME, omniHandlerName); values.put(CP.ACTION_DATA, throwerData1.toString()); uri1 = getContentResolver().insert(CP.CONTENT_URI, values); } } // Store in CP if necessary if (throwerData2 != null) { if (throwerData2Type == ActionData.DATA_TYPE_MANUAL) { // Add OmniHandler Data1 to the CP values = new ContentValues(); values.put(CP.INSTANCE_NAME, omniHandlerName); values.put(CP.ACTION_DATA, throwerData2.toString()); uri2 = getContentResolver().insert(CP.CONTENT_URI, values); } } // Add OmniHandler to the UGConfig UGParser ug = new UGParser(getApplicationContext()); HashMap<String, String> HM = new HashMap<String, String>(); HM.put(UGParser.KEY_INSTANCE_NAME, omniHandlerName); HM.put(UGParser.KEY_EVENT_TYPE, eventName); HM.put(UGParser.KEY_EVENT_APP, eventApp); HM.put(UGParser.KEY_ACTION_APP, throwerApp); HM.put(UGParser.KEY_ACTION_TYPE, throwerAction); HM.put(UGParser.KEY_ENABLE_INSTANCE, "True"); if (uri1 != null) { HM.put(UGParser.KEY_ACTION_DATA1, uri1.toString()); } else { HM.put(UGParser.KEY_ACTION_DATA1, throwerData1); } if (uri2 != null) { HM.put(UGParser.KEY_ACTION_DATA2, uri2.toString()); } else { HM.put(UGParser.KEY_ACTION_DATA2, throwerData2); } if ((filterType != null) && (filterData != null)) { HM.put(UGParser.KEY_FILTER_TYPE, filterType); HM.put(UGParser.KEY_FILTER_DATA, filterData); } else { HM.put(UGParser.KEY_FILTER_TYPE, ""); HM.put(UGParser.KEY_FILTER_DATA, ""); } ug.writeRecord(HM); // We've added a new OmniHandler so we need to restart our service to register it Intent i = new Intent(); i.setAction("OmniRestart"); sendBroadcast(i); // Go back to our start page i = new Intent(); setResult(Constants.RESULT_SUCCESS, i); finish(); } /* * (non-Javadoc) * * @see android.app.Activity#onActivityResult(int, int, android.content.Intent) */ protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case Constants.RESULT_ADD_THROWER: switch (resultCode) { case Constants.RESULT_SUCCESS: getIntentData(data); update(); break; } break; } } }
package edu.stuy.goldfish.rules; import edu.stuy.goldfish.Grid; import edu.stuy.goldfish.Patch; // An implementation of conway using von Neumann Neighborhoods. public class Conway4 extends RuleSet { public static int states = 2; public static Grid run(Grid g) { Grid newGrid = new Grid(g.getWidth(), g.getHeight(), false); for (int i = 0; i < g.getWidth(); i++) { for (int j = 0; j < g.getHeight(); j++) { Patch orig = g.getPatch(i, j); int numAlive = orig.get4Neighbors(1); Patch p = orig.clone(newGrid); if (numAlive < 2) p.setState(0); // Dies by underpopulation else if (numAlive > 3) p.setState(0); // Dies by overpopulation else if (numAlive == 3) p.setState(1); // Born with 3 neighbors newGrid.setPatch(i, j, p); } } return newGrid; } public static void setup(Grid g) { int[][] pattern = { {1,1,1,1,1,1,1,1,1,1,1,1,0,1}, {1,0,0,0,0,0,0,0,0,0,0,1,0,1}, {1,0,1,1,1,1,1,1,1,1,0,1,0,1}, {1,0,1,0,0,0,0,0,0,1,0,1,0,1}, {1,0,1,0,1,1,1,1,0,1,0,1,0,1}, {1,0,1,0,1,0,0,1,0,1,0,1,0,1}, {1,0,1,0,1,0,0,1,0,1,0,1,0,1}, {1,0,1,0,1,0,1,1,0,1,0,1,0,1}, {1,0,1,0,1,0,0,0,0,1,0,1,0,1}, {1,0,1,0,1,1,1,1,1,1,0,1,0,1}, {1,0,1,0,0,0,0,0,0,0,0,1,0,1}, {1,0,1,1,1,1,1,1,1,1,1,1,0,1}, {1,0,0,0,0,0,0,0,0,0,0,0,0,1}, {1,1,1,1,1,1,1,1,1,1,1,1,1,1} }; for (int i = 0; i < 14; i++) { for (int j = 0; j < 14; j++) { g.getPatch(i + ((g.getWidth() - 14) / 2), j + ((g.getHeight() - 14) / 2)).setState(pattern[j][i]); } } } }
package layout; import android.content.Context; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import ie.dit.societiesapp.R; /** * A simple {@link Fragment} subclass. * Activities that contain this fragment must implement the * {@link SocietyFragment.OnFragmentInteractionListener} interface * to handle interaction events. * Use the {@link SocietyFragment#newInstance} factory method to * create an instance of this fragment. */ public class SocietyFragment extends Fragment implements View.OnClickListener { // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private static final String ARG_PARAM1 = "param1"; private static final String ARG_PARAM2 = "param2"; // TODO: Rename and change types of parameters private String mParam1; private String mParam2; private OnFragmentInteractionListener mListener; public SocietyFragment() { // Required empty public constructor } /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment SocietyFragment. */ // TODO: Rename and change types and number of parameters public static SocietyFragment newInstance(String param1, String param2) { SocietyFragment fragment = new SocietyFragment(); Bundle args = new Bundle(); args.putString(ARG_PARAM1, param1); args.putString(ARG_PARAM2, param2); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { mParam1 = getArguments().getString(ARG_PARAM1); mParam2 = getArguments().getString(ARG_PARAM2); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment // Create a listener for the search button View v = inflater.inflate(R.layout.fragment_society, container, false); Button button = (Button) v.findViewById(R.id.qr_gen_button); button.setOnClickListener(this); return v; } // TODO: Rename method, update argument and hook method into UI event public void onButtonPressed(Uri uri) { if (mListener != null) { mListener.onFragmentInteraction(uri); } } @Override public void onAttach(Context context) { super.onAttach(context); if (context instanceof OnFragmentInteractionListener) { mListener = (OnFragmentInteractionListener) context; } else { throw new RuntimeException(context.toString() + " must implement OnFragmentInteractionListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; } public interface OnFragmentInteractionListener { // TODO: Update argument type and name void onFragmentInteraction(Uri uri); } public void onClick(View v) { switch(v.getId()) { case R.id.qr_gen_button: break; } } }
/** * Restaurant Inventory Management * Group 7 */ package edu.uic.cs342.group7.rim; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.Iterator; //Java 8 routines //import java.io.IOException; //import java.nio.charset.StandardCharsets; //import java.nio.file.Files; //import java.nio.file.Paths; import java.util.Scanner; /** * @authors * Adrian Pasciak, * Chase Lee, * Christopher Schultz, * Nerijus Gelezinis (no-show), * Patrick Tam * */ public class Client { static ArrayList<Ingredient> ingreds = new ArrayList<Ingredient>(); static ArrayList<Dish> dishes = new ArrayList<Dish>(); static Api connection = new Api(); static HashMap<String, String> dishSizes = new HashMap<String, String>(); static GregorianCalendar cal = new GregorianCalendar(); static ArrayList<DishIngredient> currentInventory = new ArrayList<DishIngredient>(); /** * This function will print out the menu for the user to select from. * There are no arguments for this function. */ private static void printMenu() { printHeader("Menu"); cal.setTime(connection.getDate()); System.out.println("Current Date: " + cal.get(GregorianCalendar.YEAR) + "/" + ((cal.get(GregorianCalendar.MONTH))+1) + "/" + cal.get(GregorianCalendar.DAY_OF_MONTH)); System.out.println("1. Order Dish"); System.out.println("2. Add Items to Inventory"); System.out.println("3. Current Inventory"); System.out.println("4. End Day"); System.out.println("5. Forecast Shopping List (based on previous day's ordered dishes)"); System.out.println("6. Load data from file (This will reset the system completely!!!)"); System.out.println("q. Quit"); } /** * This function wll print out a header for a given text string. * @param text - A string to place within the header flag. */ public static void printHeader(String text) { int count = text.length(); String dash = "-"; for (int i = 0; i < count-1; i++) { dash = dash.concat("-"); } System.out.println("+" + dash + "+"); System.out.println("+" + text + "+"); System.out.println("+" + dash + "+"); } /** * This will determine if a ingredient is in the larger list of ingredients, identified by name. * @param haystack - The list of all ingredients * @param needle - The string you are looking for, identifying the ingredient * @return - true if the ingredient is found, false if not. */ public static boolean ingredientExists(ArrayList<Ingredient> haystack, String needle) { for (Ingredient item : haystack) { if (item.getName().equalsIgnoreCase(needle)) { return true; } } return false; } /** * This will return the Ingredient object that is in the larger list of ingredients, identified by name. * @param haystack - The list of all ingredients. * @param needle - The string you are looking for, identifying the ingredient. * @return - Returns the Ingredient instance that was found in the haystack. */ public static Ingredient getIngredient(ArrayList<Ingredient> haystack, String needle) { for (Ingredient item : haystack) { if (item.getName().equalsIgnoreCase(needle)) { return item; } } return null; } /** * Determines if a string is a number * @param str - A string to be determined to be a number or not. * @return - True if the string is parsable into a number. False if not a string parsable into a number. */ public static boolean isNumeric(String str) { return str.matches("-?\\d+(\\.\\d+)?"); //match a number with optional '-' and decimal. } /** * Loads a dishes file to be added into the running database. * @param file - the filename / filepath from the current working directory. (one directory above the src folder) */ private static void loadDishesFile(String file) { // This is Java 8... 5 lines to read the file... // try { // Files.lines(Paths.get(input), StandardCharsets.UTF_8).forEach(System.out::println); // } catch (IOException e) { // e.printStackTrace(); BufferedReader br = null; String line = null; try { br = new BufferedReader(new FileReader(file)); while ((line = br.readLine()) != null) { if (line.startsWith(" continue; // Comment detection } String[] elements = line.split(","); ArrayList<DishIngredient> dishRecipe = new ArrayList<DishIngredient>(); /** * For each line: * - Add an Ingredient if not exists in array * - Make a dishIngredient and append to list * - Create a Dish * - Add dish to dishArray */ for (int i = 1; i < elements.length; i++) { String[] elemquant = elements[i].split(":"); Ingredient currentIngredient = new Ingredient(elemquant[0]); if(!ingredientExists(ingreds, elemquant[0])) { ingreds.add(currentIngredient); //System.out.println("Added " + currentIngredient.getName()); }else { //System.out.println("Skipping ingredient."); } DishIngredient currentDishIngredient = new DishIngredient(getIngredient(ingreds, elemquant[0]), Integer.parseInt(elemquant[1])); dishRecipe.add(currentDishIngredient); } Dish currentDish = new Dish(dishRecipe, elements[0]); dishes.add(currentDish); } connection.loadIngredients(ingreds); connection.loadDishes(dishes); System.out.println("Loaded Dishes: " + dishes.size() + " dishes loaded..."); System.out.println("Loaded Ingredients: " + ingreds.size() + " recipe ingredients loaded..."); } catch (FileNotFoundException e) { System.out.println("File Not Found. Skipped dishes loading."); } catch (IOException e) { e.printStackTrace(); } finally { if (br != null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } } /** * Loads a inventory file to be added into the running database. * @param file - the filename / filepath from the current working directory. (one directory above the src folder) */ private static void loadInventoryFile(String file) { BufferedReader br2 = null; String line2 = null; ArrayList<Ingredient> toBeAdded2 = new ArrayList<Ingredient>(); try { br2 = new BufferedReader(new FileReader(file)); while ((line2 = br2.readLine()) != null) { if (line2.startsWith(" continue; // Comment detection } String[] elements = line2.split(","); String ingredientName = elements[0]; int curQuantity = Integer.parseInt(elements[1]); String[] parseDate = elements[2].split("/"); GregorianCalendar date2 = new GregorianCalendar(Integer.parseInt(parseDate[0]),Integer.parseInt(parseDate[1]),Integer.parseInt(parseDate[2])); if (ingredientExists(ingreds,ingredientName)) { Ingredient ingredientToAdd2 = new Ingredient(ingredientName); Quantity newQuantity2 = new Quantity(); newQuantity2.setCount(curQuantity); newQuantity2.setDate(date2.getTime()); ingredientToAdd2.addQuantity(newQuantity2); toBeAdded2.add(ingredientToAdd2); //System.out.println("Added: " + newQuantity2.getCount() + " " + ingredientName + "(s) set to expire on " + newQuantity2.getDate().toString()); } } System.out.println("Loading Inventory: Committed " + toBeAdded2.size() + " distinct items"); connection.addItemsToInventory(toBeAdded2); } catch (FileNotFoundException e) { System.out.println("File Not Found. Skipped inventory loading."); } catch (IOException e) { e.printStackTrace(); } finally { if (br2 != null) { try { br2.close(); } catch (IOException e) { e.printStackTrace(); } } } } /** * Calls the API and determines what we need to buy. * @param api - the connection/instance of the api. */ public static void forecastApi(Api api, boolean autoIncludeInventory) { ArrayList<Ingredient> list = null; try { list = api.getShoppingList(autoIncludeInventory); } catch (NullPointerException e) { System.out.println("There is nothing on the shopping list."); } if (list != null) { //api.addItemsToInventory(list); Iterator<Ingredient> itr = list.iterator(); Ingredient ingredient; System.out.println("******** Shopping List **********"); while(itr.hasNext()) { ingredient = itr.next(); System.out.println("Ingredient: " + ingredient.getName() + " Quantity: " + ingredient.getTotalQuantityOfIngredient()); } System.out.println("\n"); } } /** * This function is the main driver and client for the our project. This * main function will handle all the interface logic with the user. * @param args - This parameter is not used. */ public static void main(String[] args) { String version = "1.10"; loadDishesFile("data.csv"); loadInventoryFile("inventory.csv"); System.out.println("+ System.out.format("+ Restaurant Inventory Management v%s +\n", version); System.out.println("+ Authors: Adrian Pasciak, Chase Lee, Christopher Schultz, +"); System.out.println("+ Nerijus Gelezinis (no-show), Patrick Tam +"); System.out.println("+ dishSizes.put("F", "Full order"); dishSizes.put("S", "Super size order"); dishSizes.put("H", "Half order"); printMenu(); System.out.println("\nSelect a menu option: "); boolean runflag = true; int count = 0; Scanner s = new Scanner(System.in); String input = s.nextLine(); while (!("q".equalsIgnoreCase(input))) { while (!isNumeric(input)) { input = s.nextLine(); // Grab any stay lines. } switch(Integer.parseInt(input)) { case 1: printHeader("Order Dish"); System.out.println("Please select the dish you would like to order:"); count = 0; for(Dish item : dishes) { System.out.println(count +") "+ item.getName()); count++; } input = null; input = s.nextLine(); while ((input.length() >= 1) && (Integer.parseInt(input) > dishes.size())) { System.out.println("Invalid option. Try again:"); input = s.nextLine(); } int getDish = Integer.parseInt(input); System.out.println("Please select a dish size:"); System.out.println("S) Super Size Order"); System.out.println("F) Full Size Order (Normal)"); System.out.println("H) Half Size Order"); input = null; input = s.nextLine(); while (input.length() <= 0) { input = s.nextLine(); } String dSize = input; boolean result = connection.orderDish(dishes.get(getDish).getName(), dSize.substring(0, 1).toUpperCase()); if (result) { System.out.println(dishSizes.get(dSize.substring(0, 1).toUpperCase()) + " of " + dishes.get(getDish).getName() + " ordered successfully."); }else { System.out.println(dishSizes.get(dSize.substring(0, 1).toUpperCase()) + " of " + dishes.get(getDish).getName() + " order failed. System does not have enough ingredients to fulfill the order."); System.out.println("A "+ dishSizes.get(dSize.substring(0, 1).toUpperCase()) +" of '" + dishes.get(getDish).getName() + "' requires the following ingredients: "); Dish curDish = dishes.get(getDish); for(DishIngredient item : curDish.getIngredients()) { if (dSize.substring(0, 1).toUpperCase().equalsIgnoreCase("F")) { System.out.format("Item: %s, Quantity: %d\n", item.getIngredient().getName(), item.getQuantity()); } else if (dSize.substring(0, 1).toUpperCase().equalsIgnoreCase("S")) { System.out.format("Item: %s, Quantity: %d\n", item.getIngredient().getName(), (item.getQuantity()*2)); } else { System.out.format("Item: %s, Quantity: %d\n", item.getIngredient().getName(), ((int)Math.ceil(((double)item.getQuantity())/2))); } } } break; case 2: printHeader("Add Items to Inventory Quantity"); count = 0; for(Ingredient item : ingreds) { System.out.println(count + ") " + item.getName()); count++; } System.out.println("Please select the ingredient you would like to add quantity to:"); int ingredientToAdd = s.nextInt(); while(ingredientToAdd >= ingreds.size() || ingredientToAdd < 0) { System.out.println("Invalid option, try again:"); ingredientToAdd = s.nextInt(); } System.out.println("How many would you like to add?:"); int quantityToAdd = s.nextInt(); while(quantityToAdd < 0) { System.out.println("Invalid quantity, try again:"); quantityToAdd = s.nextInt(); } input = s.nextLine(); // Eat up new line. System.out.println("When is the expiration?: yyyy/mm/dd"); input = s.nextLine(); String[] ymd = input.split("/"); ArrayList<Ingredient> toBeAdded = new ArrayList<Ingredient>(); Ingredient ingredientStaged = new Ingredient(ingreds.get(ingredientToAdd).getName()); Quantity newQuantity = new Quantity(); newQuantity.setCount(quantityToAdd); GregorianCalendar itemDate = new GregorianCalendar(Integer.parseInt(ymd[0]),Integer.parseInt(ymd[1]) - 1,Integer.parseInt(ymd[2])); newQuantity.setDate(itemDate.getTime()); ingredientStaged.addQuantity(newQuantity); toBeAdded.add(ingredientStaged); connection.addItemsToInventory(toBeAdded); System.out.println(newQuantity.getCount() + " " + ingreds.get(ingredientToAdd).getName() + " have been added to the inventory!"); break; case 3: printHeader("Current Inventory Listing"); currentInventory = connection.getCurrentInventory(); System.out.format("%15s | %8s\n for(DishIngredient item : currentInventory) { System.out.format("%15s | %7d\n", item.getIngredient().getName(), item.getQuantity()); } break; case 4: printHeader("End Day"); connection.updateDate(); System.out.println("Moved on to the next day!"); break; case 5: printHeader("Forecast Shopping List"); System.out.println("Would you like to auto-add the shopping list to the inventory?: (Y/N)"); System.out.println("Note the auto-added ingredients have a 7-day expiration."); input = s.nextLine(); while(!input.equalsIgnoreCase("Y") && !input.equalsIgnoreCase("N")) { System.out.println("Invalid input. Try again.:"); input = s.nextLine(); } if (input.equalsIgnoreCase("Y")) { forecastApi(connection, true); } else { forecastApi(connection, false); } break; case 6: printHeader("Load Data from file"); connection = new Api(); System.out.println("Would you like to load from default files?: (Y/N)"); input = s.nextLine(); if (input.equalsIgnoreCase("Y")) { loadDishesFile("data.csv"); loadInventoryFile("inventory.csv"); }else { System.out.println("Please specify a file name to load for DISHES: "); input = s.nextLine(); loadDishesFile(input); System.out.println("Please specify a file name to load for INVENTORY: "); input = s.nextLine(); loadInventoryFile(input); } break; default: System.out.println("***Incorrect input, try again.***"); break; } printMenu(); System.out.println("\nSelect a menu option: "); input = s.nextLine(); } } }
package com.kii.thingif.command; import android.os.Parcel; import android.os.Parcelable; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.text.TextUtils; import android.util.Pair; import com.google.gson.annotations.SerializedName; import com.kii.thingif.Alias; import com.kii.thingif.TypedID; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; /** * Represents a command that is executed by the thing */ public class Command implements Parcelable { private String commandID; @SerializedName("schema") private final String schemaName; private final int schemaVersion; @SerializedName("target") private final TypedID targetID; @SerializedName("issuer") private final TypedID issuerID; private final List<Pair<Alias, List<Action>>> actions; private final List<Pair<Alias,List<ActionResult>>> actionResults; @SerializedName("commandState") private final CommandState commandState; private final String firedByTriggerID; @SerializedName("createdAt") private final Long created; @SerializedName("modifiedAt") private final Long modified; private final String title; private final String description; private final JSONObject metadata; public Command(@NonNull String schemaName, int schemaVersion, @Nullable TypedID targetID, @NonNull TypedID issuerID, @NonNull List<Pair<Alias, List<Action>>> actions, @Nullable List<Pair<Alias,List<ActionResult>>> actonResults, @Nullable CommandState commandState, @Nullable String firedByTriggerID, @Nullable Long created, @Nullable Long modified, @Nullable String title, @Nullable String description, @Nullable JSONObject metadata ) { if (TextUtils.isEmpty(schemaName)) { throw new IllegalArgumentException("schemaName is null or empty"); } if (targetID == null) { throw new IllegalArgumentException("targetID is null"); } if (issuerID == null) { throw new IllegalArgumentException("issuerID is null"); } if (actions == null || actions.size() == 0) { throw new IllegalArgumentException("actions is null or empty"); } this.schemaName = schemaName; this.schemaVersion = schemaVersion; this.targetID = targetID; this.issuerID = issuerID; this.actions = actions; this.actionResults = actonResults; this.commandState = commandState; this.firedByTriggerID = firedByTriggerID; this.created = created; this.modified = modified; this.title = title; this.metadata = metadata; this.description = description; } /** Get ID of the command. * @return ID of the command. */ public String getCommandID() { return this.commandID; } /** Get name of the schema in which command is defined. * @return name of the schema. */ public String getSchemaName() { return this.schemaName; } /** Get version of the schema in which command is defined. * @return version of the schema. */ public int getSchemaVersion() { return this.schemaVersion; } /** * Get ID of the target thing. * @return target thing ID which is issued this command. */ public TypedID getTargetID() { return this.targetID; } /** * Get ID of the issuer user. * @return issuer ID by which this command is issued. */ public TypedID getIssuerID() { return this.issuerID; } /** * Get list of actions * @return action of this command. */ public List<Pair<Alias, List<Action>>> getActions() { return this.actions; } /** * Get list of action result * @return action results of this command. */ public List<Pair<Alias,List<ActionResult>>> getActionResults() { return this.actionResults; } /** * Get a action result associated with specified action * * @param alias alias to find action. * @param action action to specify action result. * @return action reuslt specified with parameter's action. */ public List<ActionResult> getActionResult( @NonNull Alias alias, @NonNull Action action) { if (action == null) { throw new IllegalArgumentException("action is null"); } //TODO: // FIXME: 12/14/16 // if (this.getActionResults() != null) { // for (ActionResult result : this.getActionResults()) { // if (TextUtils.equals(action.getActionName(), result.getActionName())) { // return result; return null; } /** * Get status of command * @return status of this command. */ public CommandState getCommandState() { return this.commandState; } /** * Get ID of trigger which fired this command * @return trigger ID which fired this command. */ public String getFiredByTriggerID() { return this.firedByTriggerID; } /** * Get creation time * @return creation time of this command. */ public Long getCreated() { return this.created; } /** * Get modification time * @return modification time of this command. */ public Long getModified() { return this.modified; } /** * Get title. * @return title of this command. */ public String getTitle() { return this.title; } /** * Get description. * @return description of this command. */ public String getDescription() { return this.description; } /** * Get meta data * @return meta data of this command. */ public JSONObject getMetadata() { return this.metadata; } // Implementation of Parcelable protected Command(Parcel in) throws Exception{ this.commandID = in.readString(); this.schemaName = in.readString(); this.schemaVersion = in.readInt(); this.targetID = in.readParcelable(TypedID.class.getClassLoader()); this.issuerID = in.readParcelable(TypedID.class.getClassLoader()); this.actions = new ArrayList<Pair<Alias, List<Action>>>(); in.readList(this.actions, Command.class.getClassLoader()); this.actionResults = new ArrayList<Pair<Alias, List<ActionResult>>>(); in.readList(this.actionResults, Command.class.getClassLoader()); this.commandState = (CommandState)in.readSerializable(); this.firedByTriggerID = in.readString(); this.created = (Long)in.readValue(Command.class.getClassLoader()); this.modified = (Long)in.readValue(Command.class.getClassLoader()); this.title = in.readString(); this.description = in.readString(); String metadata = in.readString(); if (!TextUtils.isEmpty(metadata)) { this.metadata = new JSONObject(metadata); }else{ this.metadata = null; } } public static final Creator<Command> CREATOR = new Creator<Command>() { @Override public Command createFromParcel(Parcel in) { try { return new Command(in); }catch (Exception ex){ return null; } } @Override public Command[] newArray(int size) { return new Command[size]; } }; @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(this.commandID); dest.writeString(this.schemaName); dest.writeInt(this.schemaVersion); dest.writeParcelable(this.targetID, flags); dest.writeParcelable(this.issuerID, flags); dest.writeList(this.actions); dest.writeList(this.actionResults); dest.writeSerializable(this.commandState); dest.writeString(this.firedByTriggerID); dest.writeValue(this.created); dest.writeValue(this.modified); dest.writeString(this.title); dest.writeString(this.description); dest.writeString(this.metadata == null ? null : this.metadata.toString()); } }
package org.spine3.tools.gcs; import com.google.cloud.storage.Blob; import com.google.cloud.storage.BlobInfo; import com.google.cloud.storage.Storage; import com.google.cloud.storage.contrib.nio.testing.LocalStorageHelper; import org.gradle.api.Project; import org.gradle.testfixtures.ProjectBuilder; import org.joda.time.DateTime; import org.junit.Before; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.mockito.ArgumentMatchers; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import static com.google.common.collect.Iterables.size; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import static org.spine3.tools.gcs.CleanGcsTask.FOLDER_DELIMITER; import static org.spine3.tools.gcs.Given.createCleanGcsTask; import static org.spine3.tools.gcs.Given.newProject; /** * @author Dmytro Grankin */ public class CleanGcsTaskShould { private final Project project = newProject(); private final CleanGcsTask task = createCleanGcsTask(project); private final CleanGcsTask taskSpy = spy(task); private final Storage storage = LocalStorageHelper.getOptions() .getService(); @Before public void setUp() throws Exception { doReturn(storage).when(taskSpy) .getStorage(); // FakeStorageRpc does not support bucket creation. doNothing().when(taskSpy) .checkBucketExists(storage); doReturn(DateTime.now() .minusDays(1)).when(taskSpy) .getOldestBlobCreationDate( ArgumentMatchers.<Blob>anyIterable()); } @Test public void delete_specified_folder_if_threshold_exceeded() { storage.create(BlobInfo.newBuilder(task.getBucketName(), task.getTargetFolder() + 1) .build()); storage.create(BlobInfo.newBuilder(task.getBucketName(), task.getTargetFolder() + 2) .build()); storage.create(BlobInfo.newBuilder(task.getBucketName(), "text.txt") .build()); taskSpy.setThreshold(0); taskSpy.cleanGcs(); assertEquals(1, size(storage.list(task.getBucketName()) .iterateAll())); } @Test public void not_delete_specified_folder_if_threshold_is_not_exceeded() { storage.create(BlobInfo.newBuilder(task.getBucketName(), task.getTargetFolder()) .build()); taskSpy.setThreshold(10); taskSpy.cleanGcs(); assertEquals(1, size(storage.list(task.getBucketName()) .iterateAll())); } @Test public void do_nothing_if_cleaningFolder_is_not_exists() { taskSpy.setThreshold(0); taskSpy.cleanGcs(); verify(taskSpy, never()).getOldestBlobCreationDate(ArgumentMatchers.<Blob>anyIterable()); } @Test public void append_delimiter_to_folder_name_without_trailing_delimiter() { final String folderName = "just-folder-name"; task.setTargetFolder(folderName); assertEquals(folderName + FOLDER_DELIMITER, task.getTargetFolder()); } @Test public void not_append_delimiter_to_folder_name_with_trailing_delimiter() { final String folderName = "delimiter-at-the-end" + FOLDER_DELIMITER; task.setTargetFolder(folderName); assertEquals(folderName, task.getTargetFolder()); } @Test public void properly_read_keyFile_content() throws IOException { final String keyFile = "keys.txt"; final String keyFileContent = "Key file content."; final TemporaryFolder projectDir = new TemporaryFolder(); projectDir.create(); final Path keyFilePath = projectDir.getRoot() .toPath() .resolve(keyFile); final Project project = ProjectBuilder.builder() .withProjectDir(projectDir.getRoot()) .build(); Files.write(keyFilePath, keyFileContent.getBytes()); final CleanGcsTask task = createCleanGcsTask(project); task.setKeyFile(keyFile); assertEquals(keyFileContent, task.getKeyFileContent()); } }
package tlc2.tool.impl; import java.io.File; import java.util.HashSet; import java.util.List; import tla2sany.parser.SyntaxTreeNode; import tla2sany.semantic.APSubstInNode; import tla2sany.semantic.ExprNode; import tla2sany.semantic.ExprOrOpArgNode; import tla2sany.semantic.FormalParamNode; import tla2sany.semantic.LabelNode; import tla2sany.semantic.LetInNode; import tla2sany.semantic.LevelConstants; import tla2sany.semantic.LevelNode; import tla2sany.semantic.OpApplNode; import tla2sany.semantic.OpArgNode; import tla2sany.semantic.OpDeclNode; import tla2sany.semantic.OpDefNode; import tla2sany.semantic.OpDefOrDeclNode; import tla2sany.semantic.SemanticNode; import tla2sany.semantic.Subst; import tla2sany.semantic.SubstInNode; import tla2sany.semantic.SymbolNode; import tla2sany.semantic.ThmOrAssumpDefNode; import tlc2.TLCGlobals; import tlc2.output.EC; import tlc2.output.MP; import tlc2.tool.Action; import tlc2.tool.BuiltInOPs; import tlc2.tool.EvalControl; import tlc2.tool.EvalException; import tlc2.tool.IActionItemList; import tlc2.tool.IContextEnumerator; import tlc2.tool.INextStateFunctor; import tlc2.tool.IStateFunctor; import tlc2.tool.ITool; import tlc2.tool.StateVec; import tlc2.tool.TLCState; import tlc2.tool.TLCStateFun; import tlc2.tool.TLCStateInfo; import tlc2.tool.TLCStateMut; import tlc2.tool.TLCStateMutExt; import tlc2.tool.ToolGlobals; import tlc2.tool.coverage.CostModel; import tlc2.util.Context; import tlc2.util.ExpectInlined; import tlc2.util.IdThread; import tlc2.util.RandomGenerator; import tlc2.util.Vect; import tlc2.value.IFcnLambdaValue; import tlc2.value.IMVPerm; import tlc2.value.IValue; import tlc2.value.ValueConstants; import tlc2.value.Values; import tlc2.value.impl.Applicable; import tlc2.value.impl.BoolValue; import tlc2.value.impl.Enumerable; import tlc2.value.impl.Enumerable.Ordering; import tlc2.value.impl.EvaluatingValue; import tlc2.value.impl.FcnLambdaValue; import tlc2.value.impl.FcnParams; import tlc2.value.impl.FcnRcdValue; import tlc2.value.impl.LazyValue; import tlc2.value.impl.MVPerm; import tlc2.value.impl.MVPerms; import tlc2.value.impl.MethodValue; import tlc2.value.impl.ModelValue; import tlc2.value.impl.OpLambdaValue; import tlc2.value.impl.OpValue; import tlc2.value.impl.RecordValue; import tlc2.value.impl.Reducible; import tlc2.value.impl.SetCapValue; import tlc2.value.impl.SetCupValue; import tlc2.value.impl.SetDiffValue; import tlc2.value.impl.SetEnumValue; import tlc2.value.impl.SetOfFcnsValue; import tlc2.value.impl.SetOfRcdsValue; import tlc2.value.impl.SetOfTuplesValue; import tlc2.value.impl.SetPredValue; import tlc2.value.impl.StringValue; import tlc2.value.impl.SubsetValue; import tlc2.value.impl.TupleValue; import tlc2.value.impl.UnionValue; import tlc2.value.impl.Value; import tlc2.value.impl.ValueEnumeration; import tlc2.value.impl.ValueExcept; import tlc2.value.impl.ValueVec; import util.Assert; import util.Assert.TLCRuntimeException; import util.FilenameToStream; import util.TLAConstants; import util.UniqueString; /** * This class provides useful methods for tools like model checker * and simulator. * * It's instance serves as a spec handle * This is one of two places in TLC, where not all messages are retrieved from the message printer, * but constructed just here in the code. */ public abstract class Tool extends Spec implements ValueConstants, ToolGlobals, ITool { public static final String PROBABLISTIC_KEY = Tool.class.getName() + ".probabilistic"; /* * Prototype, do *not* activate when checking safety or liveness!!!: * For simulation that is not meant as a substitute of exhaustive checking for too * large models, it can be useful to generate behaviors as quickly as possible, * i.e. without checking all successor states along the states of the behavior. * This flag activates the code path that efficiently generate only a single * successor state during simulation. It does not let the user parameterize * the code with a particular distribution, but instead draws from the uniform * distribution. * * In its current form, it only handles non-determinism expressed with opcode * OPCODE_be (bounded exist), i.e. (which simply happened to be the primary * expression that we encountered in the SWIM spec during this work): * * VARIABLE x * \E n \in S: x' = n * * Activate with: -Dtlc2.tool.impl.Tool.probabilistic=true */ private static final boolean PROBABLISTIC = Boolean.getBoolean(PROBABLISTIC_KEY); public enum Mode { Simulation, MC, MC_DEBUG, Executor; } public static final Value[] EmptyArgs = new Value[0]; protected final Action[] actions; // the list of TLA actions. private Vect<Action> actionVec = new Vect<>(10); protected final Mode toolMode; /** * Creates a new tool handle */ public Tool(String specFile, String configFile) { this(new File(specFile), specFile, configFile, null); } public Tool(String specFile, String configFile, FilenameToStream resolver) { this(new File(specFile), specFile, configFile, resolver); } public Tool(String specFile, String configFile, FilenameToStream resolver, Mode mode) { this(new File(specFile), specFile, configFile, resolver, mode); } private Tool(File specDir, String specFile, String configFile, FilenameToStream resolver) { this(specDir.isAbsolute() ? specDir.getParent() : "", specFile, configFile, resolver); } private Tool(File specDir, String specFile, String configFile, FilenameToStream resolver, Mode mode) { this(specDir.isAbsolute() ? specDir.getParent() : "", specFile, configFile, resolver, mode); } public Tool(String specDir, String specFile, String configFile, FilenameToStream resolver) { this(specDir, specFile, configFile, resolver, Mode.MC); } public Tool(String specDir, String specFile, String configFile, FilenameToStream resolver, Mode mode) { super(specDir, specFile, configFile, resolver, mode); this.toolMode = mode; // set variables to the static filed in the state if (mode == Mode.Simulation || mode == Mode.Executor || mode == Mode.MC_DEBUG) { assert TLCState.Empty instanceof TLCStateMutExt; TLCStateMutExt.setTool(this); } else { // Initialize state. assert TLCState.Empty instanceof TLCStateMut; TLCStateMut.setTool(this); } Action next = this.getNextStateSpec(); if (next == null) { this.actions = new Action[0]; } else { this.getActions(next); int sz = this.actionVec.size(); this.actions = new Action[sz]; for (int i = 0; i < sz; i++) { this.actions[i] = (Action) this.actionVec.elementAt(i); } } } Tool(Tool other) { super(other); this.actions = other.actions; this.actionVec = other.actionVec; this.toolMode = other.toolMode; } @Override public Mode getMode() { return this.toolMode; } /** * This method returns the set of all possible actions of the * spec, and sets the actions field of this object. In fact, we * could simply treat the next predicate as one "giant" action. * But for efficiency, we preprocess the next state predicate by * splitting it into a set of actions for the maximum prefix * of disjunction and existential quantification. */ @Override public final Action[] getActions() { return this.actions; } private final void getActions(final Action next) { this.getActions(next.pred, next.con, next.getOpDef(), next.cm); } private final void getActions(SemanticNode next, Context con, final OpDefNode opDefNode, CostModel cm) { switch (next.getKind()) { case OpApplKind: { OpApplNode next1 = (OpApplNode)next; this.getActionsAppl(next1, con, opDefNode, cm); return; } case LetInKind: { LetInNode next1 = (LetInNode)next; this.getActions(next1.getBody(), con, opDefNode, cm); return; } case SubstInKind: { SubstInNode next1 = (SubstInNode)next; Subst[] substs = next1.getSubsts(); if (substs.length == 0) { this.getActions(next1.getBody(), con, opDefNode, cm); } else { Action action = new Action(next1, con, opDefNode); this.actionVec.addElement(action); } return; } // Added by LL on 13 Nov 2009 to handle theorem and assumption names. case APSubstInKind: { APSubstInNode next1 = (APSubstInNode)next; Subst[] substs = next1.getSubsts(); if (substs.length == 0) { this.getActions(next1.getBody(), con, opDefNode, cm); } else { Action action = new Action(next1, con, opDefNode); this.actionVec.addElement(action); } return; } case LabelKind: { LabelNode next1 = (LabelNode)next; this.getActions(next1.getBody(), con, opDefNode, cm); return; } default: { Assert.fail("The next state relation is not a boolean expression.\n" + next, next, con); } } } private final void getActionsAppl(OpApplNode next, Context con, final OpDefNode actionName, CostModel cm) { ExprOrOpArgNode[] args = next.getArgs(); SymbolNode opNode = next.getOperator(); int opcode = BuiltInOPs.getOpCode(opNode.getName()); if (opcode == 0) { Object val = this.lookup(opNode, con, false); if (val instanceof OpDefNode) { OpDefNode opDef = (OpDefNode)val; opcode = BuiltInOPs.getOpCode(opDef.getName()); if (opcode == 0) { try { FormalParamNode[] formals = opDef.getParams(); int alen = args.length; int argLevel = 0; for (int i = 0; i < alen; i++) { argLevel = args[i].getLevel(); if (argLevel != 0) break; } if (argLevel == 0) { Context con1 = con; for (int i = 0; i < alen; i++) { IValue aval = this.eval(args[i], con, TLCState.Empty, cm); con1 = con1.cons(formals[i], aval); } this.getActions(opDef.getBody(), con1, opDef, cm); return; } } catch (Throwable e) { /*SKIP*/ } } } if (opcode == 0) { Action action = new Action(next, con, (OpDefNode) opNode); this.actionVec.addElement(action); return; } } switch (opcode) { case OPCODE_be: // BoundedExists { final int cnt = this.actionVec.size(); try { ContextEnumerator Enum = this.contexts(next, con, TLCState.Empty, TLCState.Empty, EvalControl.Clear, cm); if (Enum.isDone()) { // No exception and no actions created implies Enum was empty: // \E i \in {} : ... // \E i \in Nat: FALSE this.actionVec.addElement(new Action(next, con, actionName)); return; } Context econ; while ((econ = Enum.nextElement()) != null) { this.getActions(args[0], econ, actionName, cm); } assert (cnt < this.actionVec.size()) : "AssertionError when creating Actions. This case should have been handled by Enum.isDone conditional above!"; } catch (Throwable e) { Action action = new Action(next, con, actionName); this.actionVec.removeAll(cnt); this.actionVec.addElement(action); } return; } case OPCODE_dl: // DisjList case OPCODE_lor: { for (int i = 0; i < args.length; i++) { this.getActions(args[i], con, actionName, cm); } return; } default: { // We handle all the other builtin operators here. Action action = new Action(next, con, actionName); this.actionVec.addElement(action); return; } } } /* * This method returns the set of possible initial states that * satisfies the initial state predicate. Initial state predicate * can be under-specified. Too many possible initial states will * probably make tools like TLC useless. */ @Override public final StateVec getInitStates() { final StateVec initStates = new StateVec(0); getInitStates(initStates); return initStates; } @Override public final void getInitStates(IStateFunctor functor) { Vect<Action> init = this.getInitStateSpec(); ActionItemList acts = ActionItemListExt.Empty; // MAK 09/11/2018: Tail to head iteration order cause the first elem added with // acts.cons to be acts tail. This fixes the bug/funny behavior that the init // predicate Init == A /\ B /\ C /\ D was evaluated in the order A, D, C, B (A // doesn't get added to acts at all). for (int i = (init.size() - 1); i > 0; i Action elem = (Action)init.elementAt(i); acts = (ActionItemList) acts.cons(elem, IActionItemList.PRED); } if (init.size() != 0) { Action elem = (Action)init.elementAt(0); TLCState ps = TLCState.Empty.createEmpty(); if (acts.isEmpty()) { acts.setAction(elem); } this.getInitStates(elem.pred, acts, elem.con, ps, functor, elem.cm); } } /* Create the state specified by pred. */ @Override public final TLCState makeState(SemanticNode pred) { ActionItemList acts = ActionItemList.Empty; TLCState ps = TLCState.Empty.createEmpty(); StateVec states = new StateVec(0); this.getInitStates(pred, acts, Context.Empty, ps, states, acts.cm); if (states.size() != 1) { Assert.fail("The predicate does not specify a unique state." + pred, pred); } TLCState state = states.elementAt(0); if (!this.isGoodState(state)) { Assert.fail("The state specified by the predicate is not complete." + pred, pred); } return state; } protected void getInitStates(SemanticNode init, ActionItemList acts, Context c, TLCState ps, IStateFunctor states, CostModel cm) { switch (init.getKind()) { case OpApplKind: { OpApplNode init1 = (OpApplNode)init; this.getInitStatesAppl(init1, acts, c, ps, states, cm); return; } case LetInKind: { LetInNode init1 = (LetInNode)init; this.getInitStates(init1.getBody(), acts, c, ps, states, cm); return; } case SubstInKind: { SubstInNode init1 = (SubstInNode)init; Subst[] subs = init1.getSubsts(); Context c1 = c; for (int i = 0; i < subs.length; i++) { Subst sub = subs[i]; c1 = c1.cons(sub.getOp(), this.getVal(sub.getExpr(), c, false, coverage ? sub.getCM() : cm, toolId)); } this.getInitStates(init1.getBody(), acts, c1, ps, states, cm); return; } // Added by LL on 13 Nov 2009 to handle theorem and assumption names. case APSubstInKind: { APSubstInNode init1 = (APSubstInNode)init; Subst[] subs = init1.getSubsts(); Context c1 = c; for (int i = 0; i < subs.length; i++) { Subst sub = subs[i]; c1 = c1.cons(sub.getOp(), this.getVal(sub.getExpr(), c, false, cm, toolId)); } this.getInitStates(init1.getBody(), acts, c1, ps, states, cm); return; } // LabelKind class added by LL on 13 Jun 2007 case LabelKind: { LabelNode init1 = (LabelNode)init; this.getInitStates(init1.getBody(), acts, c, ps, states, cm); return; } default: { Assert.fail("The init state relation is not a boolean expression.\n" + init, init, c); } } } protected void getInitStates(ActionItemList acts, TLCState ps, IStateFunctor states, CostModel cm) { if (acts.isEmpty()) { if (coverage) { cm.incInvocations(); cm.getRoot().incInvocations(); } states.addElement(ps.copy().setAction(acts.getAction())); return; } else if (ps.allAssigned()) { // MAK 05/25/2018: If all values of the initial state have already been // assigned, there is no point in further trying to assign values. Instead, all // remaining statements (ActionItemList) can just be evaluated for their boolean // value. // This optimization is especially useful to check inductive invariants which // require TLC to generate a very large set of initial states. while (!acts.isEmpty()) { final Value bval = this.eval(acts.carPred(), acts.carContext(), ps, TLCState.Empty, EvalControl.Init, acts.cm); if (!(bval instanceof BoolValue)) { //TODO Choose more fitting error message. Assert.fail(EC.TLC_EXPECTED_EXPRESSION_IN_COMPUTING, new String[] { "initial states", "boolean", bval.toString(), acts.pred.toString() }, acts.carPred(), acts.carContext()); } if (!((BoolValue) bval).val) { if (coverage) { // Increase "states found". cm.getRoot().incSecondary(); } return; } // Move on to the next action in the ActionItemList. acts = acts.cdr(); } if (coverage) { cm.incInvocations(); cm.getRoot().incInvocations(); } states.addElement(ps.copy().setAction(acts.getAction())); return; } // Assert.check(act.kind > 0 || act.kind == -1); ActionItemList acts1 = acts.cdr(); this.getInitStates(acts.carPred(), acts1, acts.carContext(), ps, states, acts.cm); } protected void getInitStatesAppl(OpApplNode init, ActionItemList acts, Context c, TLCState ps, IStateFunctor states, CostModel cm) { if (coverage) {cm = cm.get(init);} ExprOrOpArgNode[] args = init.getArgs(); int alen = args.length; SymbolNode opNode = init.getOperator(); int opcode = BuiltInOPs.getOpCode(opNode.getName()); if (opcode == 0) { // This is a user-defined operator with one exception: it may // be substed by a builtin operator. This special case occurs // when the lookup returns an OpDef with opcode Object val = this.lookup(opNode, c, ps, false); if (val instanceof OpDefNode) { OpDefNode opDef = (OpDefNode)val; opcode = BuiltInOPs.getOpCode(opDef.getName()); if (opcode == 0) { // Context c1 = this.getOpContext(opDef, args, c, false); Context c1 = this.getOpContext(opDef, args, c, true, cm, toolId); this.getInitStates(opDef.getBody(), acts, c1, ps, states, cm); return; } } // Added 13 Nov 2009 by LL to fix Yuan's fix. if (val instanceof ThmOrAssumpDefNode) { ThmOrAssumpDefNode opDef = (ThmOrAssumpDefNode)val; opcode = BuiltInOPs.getOpCode(opDef.getName()); Context c1 = this.getOpContext(opDef, args, c, true); this.getInitStates(opDef.getBody(), acts, c1, ps, states, cm); return; } if (val instanceof LazyValue) { LazyValue lv = (LazyValue)val; if (lv.getValue() == null || lv.isUncachable()) { this.getInitStates(lv.expr, acts, lv.con, ps, states, cm); return; } val = lv.getValue(); } Object bval = val; if (alen == 0) { if (val instanceof MethodValue) { bval = ((MethodValue)val).apply(EmptyArgs, EvalControl.Init); } else if (val instanceof EvaluatingValue) { // Allow EvaluatingValue overwrites to have zero arity. bval = ((EvaluatingValue) val).eval(this, args, c, ps, TLCState.Empty, EvalControl.Init, cm); } } else { if (val instanceof OpValue) { bval = ((OpValue) val).eval(this, args, c, ps, TLCState.Empty, EvalControl.Init, cm); } } if (opcode == 0) { if (!(bval instanceof BoolValue)) { Assert.fail(EC.TLC_EXPECTED_EXPRESSION_IN_COMPUTING, new String[] { "initial states", "boolean", bval.toString(), init.toString() }, init, c); } if (((BoolValue) bval).val) { this.getInitStates(acts, ps, states, cm); } return; } } switch (opcode) { case OPCODE_dl: // DisjList case OPCODE_lor: { for (int i = 0; i < alen; i++) { this.getInitStates(args[i], acts, c, ps, states, cm); } return; } case OPCODE_cl: // ConjList case OPCODE_land: { for (int i = alen-1; i > 0; i acts = (ActionItemList) acts.cons(args[i], c, cm, i); } this.getInitStates(args[0], acts, c, ps, states, cm); return; } case OPCODE_be: // BoundedExists { SemanticNode body = args[0]; ContextEnumerator Enum = this.contexts(init, c, ps, TLCState.Empty, EvalControl.Init, cm); Context c1; while ((c1 = Enum.nextElement()) != null) { this.getInitStates(body, acts, c1, ps, states, cm); } return; } case OPCODE_bf: // BoundedForall { SemanticNode body = args[0]; ContextEnumerator Enum = this.contexts(init, c, ps, TLCState.Empty, EvalControl.Init, cm); Context c1 = Enum.nextElement(); if (c1 == null) { this.getInitStates(acts, ps, states, cm); } else { ActionItemList acts1 = acts; Context c2; while ((c2 = Enum.nextElement()) != null) { acts1 = (ActionItemList) acts1.cons(body, c2, cm, IActionItemList.PRED); } this.getInitStates(body, acts1, c1, ps, states, cm); } return; } case OPCODE_ite: // IfThenElse { Value guard = this.eval(args[0], c, ps, TLCState.Empty, EvalControl.Init, cm); if (!(guard instanceof BoolValue)) { Assert.fail("In computing initial states, a non-boolean expression (" + guard.getKindString() + ") was used as the condition " + "of an IF.\n" + init, init, c); } int idx = (((BoolValue)guard).val) ? 1 : 2; this.getInitStates(args[idx], acts, c, ps, states, cm); return; } case OPCODE_case: // Case { SemanticNode other = null; for (int i = 0; i < alen; i++) { OpApplNode pair = (OpApplNode)args[i]; ExprOrOpArgNode[] pairArgs = pair.getArgs(); if (pairArgs[0] == null) { other = pairArgs[1]; } else { Value bval = this.eval(pairArgs[0], c, ps, TLCState.Empty, EvalControl.Init, cm); if (!(bval instanceof BoolValue)) { Assert.fail("In computing initial states, a non-boolean expression (" + bval.getKindString() + ") was used as a guard condition" + " of a CASE.\n" + pairArgs[1], pairArgs[1], c); } if (((BoolValue)bval).val) { this.getInitStates(pairArgs[1], acts, c, ps, states, cm); return; } } } if (other == null) { Assert.fail("In computing initial states, TLC encountered a CASE with no" + " conditions true.\n" + init, init, c); } this.getInitStates(other, acts, c, ps, states, cm); return; } case OPCODE_fa: // FcnApply { Value fval = this.eval(args[0], c, ps, TLCState.Empty, EvalControl.Init, cm); if (fval instanceof FcnLambdaValue) { FcnLambdaValue fcn = (FcnLambdaValue)fval; if (fcn.fcnRcd == null) { Context c1 = this.getFcnContext(fcn, args, c, ps, TLCState.Empty, EvalControl.Init, cm); this.getInitStates(fcn.body, acts, c1, ps, states, cm); return; } fval = fcn.fcnRcd; } else if (!(fval instanceof Applicable)) { Assert.fail("In computing initial states, a non-function (" + fval.getKindString() + ") was applied as a function.\n" + init, init, c); } Applicable fcn = (Applicable) fval; Value argVal = this.eval(args[1], c, ps, TLCState.Empty, EvalControl.Init, cm); Value bval = fcn.apply(argVal, EvalControl.Init); if (!(bval instanceof BoolValue)) { Assert.fail(EC.TLC_EXPECTED_EXPRESSION_IN_COMPUTING2, new String[] { "initial states", "boolean", init.toString() }, args[1], c); } if (((BoolValue)bval).val) { this.getInitStates(acts, ps, states, cm); } return; } case OPCODE_eq: { SymbolNode var = this.getVar(args[0], c, false, toolId); if (var == null || var.getName().getVarLoc() < 0) { Value bval = this.eval(init, c, ps, TLCState.Empty, EvalControl.Init, cm); if (!((BoolValue)bval).val) { return; } } else { UniqueString varName = var.getName(); IValue lval = ps.lookup(varName); Value rval = this.eval(args[1], c, ps, TLCState.Empty, EvalControl.Init, cm); if (lval == null) { ps = ps.bind(varName, rval); this.getInitStates(acts, ps, states, cm); ps.unbind(varName); return; } else { if (!lval.equals(rval)) { return; } } } this.getInitStates(acts, ps, states, cm); return; } case OPCODE_in: { SymbolNode var = this.getVar(args[0], c, false, toolId); if (var == null || var.getName().getVarLoc() < 0) { Value bval = this.eval(init, c, ps, TLCState.Empty, EvalControl.Init, cm); if (!((BoolValue)bval).val) { return; } } else { UniqueString varName = var.getName(); Value lval = (Value) ps.lookup(varName); Value rval = this.eval(args[1], c, ps, TLCState.Empty, EvalControl.Init, cm); if (lval == null) { if (!(rval instanceof Enumerable)) { Assert.fail("In computing initial states, the right side of \\IN" + " is not enumerable.\n" + init, init, c); } ValueEnumeration Enum = ((Enumerable)rval).elements(); Value elem; while ((elem = Enum.nextElement()) != null) { ps.bind(varName, elem); this.getInitStates(acts, ps, states, cm); ps.unbind(varName); } return; } else { if (!rval.member(lval)) { return; } } } this.getInitStates(acts, ps, states, cm); return; } case OPCODE_implies: { Value lval = this.eval(args[0], c, ps, TLCState.Empty, EvalControl.Init, cm); if (!(lval instanceof BoolValue)) { Assert.fail("In computing initial states of a predicate of form" + " P => Q, P was " + lval.getKindString() + "\n." + init, init, c); } if (((BoolValue)lval).val) { this.getInitStates(args[1], acts, c, ps, states, cm); } else { this.getInitStates(acts, ps, states, cm); } return; } // The following case added by LL on 13 Nov 2009 to handle subexpression names. case OPCODE_nop: { this.getInitStates(args[0], acts, c, ps, states, cm); return; } default: { // For all the other builtin operators, simply evaluate: Value bval = this.eval(init, c, ps, TLCState.Empty, EvalControl.Init, cm); if (!(bval instanceof BoolValue)) { Assert.fail("In computing initial states, TLC expected a boolean expression," + "\nbut instead found " + bval + ".\n" + init, init, c); } if (((BoolValue)bval).val) { this.getInitStates(acts, ps, states, cm); } return; } } } /** * This method returns the set of next states when taking the action * in the given state. */ @Override public final StateVec getNextStates(Action action, TLCState state) { return getNextStates(action, action.con, state); } public final StateVec getNextStates(final Action action, final Context ctx, final TLCState state) { ActionItemList acts = ActionItemList.Empty; TLCState s1 = TLCState.Empty.createEmpty(); StateVec nss = new StateVec(0); this.getNextStates(action, action.pred, acts, ctx, state, s1.setPredecessor(state).setAction(action), nss, action.cm); if (coverage) { action.cm.incInvocations(nss.size()); } if (PROBABLISTIC && nss.size() > 1) {System.err.println("Simulator generated more than one next state");} return nss; } @Override public boolean getNextStates(final INextStateFunctor functor, final TLCState state) { for (int i = 0; i < actions.length; i++) { this.getNextStates(functor, state, actions[i]); } return false; } public boolean getNextStates(final INextStateFunctor functor, final TLCState state, final Action action) { this.getNextStates(action, action.pred, ActionItemList.Empty, action.con, state, TLCState.Empty.createEmpty().setPredecessor(state).setAction(action), functor, action.cm); return false; } protected abstract TLCState getNextStates(final Action action, SemanticNode pred, ActionItemList acts, Context c, TLCState s0, TLCState s1, INextStateFunctor nss, CostModel cm); protected final TLCState getNextStatesImpl(final Action action, SemanticNode pred, ActionItemList acts, Context c, TLCState s0, TLCState s1, INextStateFunctor nss, CostModel cm) { switch (pred.getKind()) { case OpApplKind: { OpApplNode pred1 = (OpApplNode)pred; if (coverage) {cm = cm.get(pred);} return this.getNextStatesAppl(action, pred1, acts, c, s0, s1, nss, cm); } case LetInKind: { LetInNode pred1 = (LetInNode)pred; return this.getNextStates(action, pred1.getBody(), acts, c, s0, s1, nss, cm); } case SubstInKind: { return getNextStatesImplSubstInKind(action, (SubstInNode) pred, acts, c, s0, s1, nss, cm); } // Added by LL on 13 Nov 2009 to handle theorem and assumption names. case APSubstInKind: { return getNextStatesImplApSubstInKind(action, (APSubstInNode) pred, acts, c, s0, s1, nss, cm); } // LabelKind class added by LL on 13 Jun 2007 case LabelKind: { LabelNode pred1 = (LabelNode)pred; return this.getNextStates(action, pred1.getBody(), acts, c, s0, s1, nss, cm); } default: { Assert.fail("The next state relation is not a boolean expression.\n" + pred, pred, c); } } return s1; } @ExpectInlined private final TLCState getNextStatesImplSubstInKind(final Action action, SubstInNode pred1, ActionItemList acts, Context c, TLCState s0, TLCState s1, INextStateFunctor nss, final CostModel cm) { Subst[] subs = pred1.getSubsts(); int slen = subs.length; Context c1 = c; for (int i = 0; i < slen; i++) { Subst sub = subs[i]; c1 = c1.cons(sub.getOp(), this.getVal(sub.getExpr(), c, false, coverage ? sub.getCM() : cm, toolId)); } return this.getNextStates(action, pred1.getBody(), acts, c1, s0, s1, nss, cm); } @ExpectInlined private final TLCState getNextStatesImplApSubstInKind(final Action action, APSubstInNode pred1, ActionItemList acts, Context c, TLCState s0, TLCState s1, INextStateFunctor nss, final CostModel cm) { Subst[] subs = pred1.getSubsts(); int slen = subs.length; Context c1 = c; for (int i = 0; i < slen; i++) { Subst sub = subs[i]; c1 = c1.cons(sub.getOp(), this.getVal(sub.getExpr(), c, false, cm, toolId)); } return this.getNextStates(action, pred1.getBody(), acts, c1, s0, s1, nss, cm); } @ExpectInlined private final TLCState getNextStates(final Action action, ActionItemList acts, final TLCState s0, final TLCState s1, final INextStateFunctor nss, CostModel cm) { final TLCState copy = getNextStates0(action, acts, s0, s1, nss, cm); if (coverage && copy != s1) { cm.incInvocations(); } return copy; } @ExpectInlined private final TLCState getNextStates0(final Action action, ActionItemList acts, final TLCState s0, final TLCState s1, final INextStateFunctor nss, CostModel cm) { if (acts.isEmpty()) { nss.addElement(s0, action, s1); return s1.copy(); } else if (TLCGlobals.warn && s1.allAssigned()) { // If all variables have been assigned and warnings are turned off, Tool can // execute the fast-path that avoids generating known successor states, but // doesn't trigger a warning in cases like: // VARIABLES x // Init == x = 0 // Next == x' = 42 /\ UNCHANGED x \* UNCHANGED and changed! // => "Warning: The variable x was changed while it is specified as UNCHANGED" return getNextStatesAllAssigned(action, acts, s0, s1, nss, cm); } final int kind = acts.carKind(); SemanticNode pred = acts.carPred(); Context c = acts.carContext(); ActionItemList acts1 = acts.cdr(); cm = acts.cm; if (kind > 0) { return this.getNextStates(action, pred, acts1, c, s0, s1, nss, cm); } else if (kind == -1) { return this.getNextStates(action, pred, acts1, c, s0, s1, nss, cm); } else if (kind == -2) { return this.processUnchanged(action, pred, acts1, c, s0, s1, nss, cm); } else { IValue v1 = this.eval(pred, c, s0, cm); IValue v2 = this.eval(pred, c, s1, cm); if (!v1.equals(v2)) { if (coverage) { return this.getNextStates(action, acts1, s0, s1, nss, cm); } else { return this.getNextStates0(action, acts1, s0, s1, nss, cm); } } } return s1; } private final TLCState getNextStatesAllAssigned(final Action action, ActionItemList acts, final TLCState s0, final TLCState s1, final INextStateFunctor nss, final CostModel cm) { int kind = acts.carKind(); SemanticNode pred = acts.carPred(); Context c = acts.carContext(); CostModel cm2 = acts.cm; while (!acts.isEmpty()) { if (kind > 0 || kind == -1) { final Value bval = this.eval(pred, c, s0, s1, EvalControl.Clear, cm2); if (!(bval instanceof BoolValue)) { // TODO Choose more fitting error message. Assert.fail(EC.TLC_EXPECTED_EXPRESSION_IN_COMPUTING, new String[] { "next states", "boolean", bval.toString(), acts.pred.toString() }, pred, c); } if (!((BoolValue) bval).val) { return s1; } } else if (kind == -2) { // Identical to default handling below (line 876). Ignored during this optimization. return this.processUnchanged(action, pred, acts.cdr(), c, s0, s1, nss, cm2); } else { final IValue v1 = this.eval(pred, c, s0, cm2); final IValue v2 = this.eval(pred, c, s1, cm2); if (v1.equals(v2)) { return s1; } } // Move on to the next action in the ActionItemList. acts = acts.cdr(); pred = acts.carPred(); c = acts.carContext(); kind = acts.carKind(); cm2 = acts.cm; } nss.addElement(s0, action, s1); return s1.copy(); } /* getNextStatesAppl */ @ExpectInlined protected abstract TLCState getNextStatesAppl(final Action action, OpApplNode pred, ActionItemList acts, Context c, TLCState s0, TLCState s1, INextStateFunctor nss, final CostModel cm); protected final TLCState getNextStatesApplImpl(final Action action, final OpApplNode pred, final ActionItemList acts, final Context c, final TLCState s0, final TLCState s1, final INextStateFunctor nss, final CostModel cm) { final ExprOrOpArgNode[] args = pred.getArgs(); final int alen = args.length; final SymbolNode opNode = pred.getOperator(); int opcode = BuiltInOPs.getOpCode(opNode.getName()); if (opcode == 0) { // This is a user-defined operator with one exception: it may // be substed by a builtin operator. This special case occurs // when the lookup returns an OpDef with opcode Object val = this.lookup(opNode, c, s0, false); if (val instanceof OpDefNode) { final OpDefNode opDef = (OpDefNode) val; opcode = BuiltInOPs.getOpCode(opDef.getName()); if (opcode == 0) { return this.getNextStates(action, opDef.getBody(), acts, this.getOpContext(opDef, args, c, true, cm, toolId), s0, s1, nss, cm); } } // Added by LL 13 Nov 2009 to fix Yuan's fix if (val instanceof ThmOrAssumpDefNode) { final ThmOrAssumpDefNode opDef = (ThmOrAssumpDefNode)val; return this.getNextStates(action, opDef.getBody(), acts, this.getOpContext(opDef, args, c, true), s0, s1, nss, cm); } if (val instanceof LazyValue) { final LazyValue lv = (LazyValue)val; if (lv.getValue() == null || lv.isUncachable()) { return this.getNextStates(action, lv.expr, acts, lv.con, s0, s1, nss, lv.cm); } val = lv.getValue(); } //TODO If all eval/apply in getNextStatesApplEvalAppl would be side-effect free (ie. not mutate args, c, s0,...), // this call could be moved into the if(opcode==0) branch below. However, opcode!=0 will only be the case if // OpDefNode above has been substed with a built-in operator. In other words, a user defines an operator Op1, // and re-defines Op1 with a TLA+ built-in one in a TLC model (not assumed to be common). => No point in trying // to move this call into if(opcode==0) because this will be the case most of the time anyway. final Object bval = getNextStatesApplEvalAppl(alen, args, c, s0, s1, cm, val); // opcode == 0 is a user-defined operator. if (opcode == 0) { return getNextStatesApplUsrDefOp(action, pred, acts, s0, s1, nss, cm, bval); } } return getNextStatesApplSwitch(action, pred, acts, c, s0, s1, nss, cm, args, alen, opcode); } private final Object getNextStatesApplEvalAppl(final int alen, final ExprOrOpArgNode[] args, final Context c, final TLCState s0, final TLCState s1, final CostModel cm, final Object val) { if (alen == 0) { if (val instanceof MethodValue) { return ((MethodValue)val).apply(EmptyArgs, EvalControl.Clear); } else if (val instanceof EvaluatingValue) { return ((EvaluatingValue)val).eval(this, args, c, s0, s1, EvalControl.Clear, cm); } } else { if (val instanceof OpValue) { // EvaluatingValue sub-class of OpValue! return ((OpValue) val).eval(this, args, c, s0, s1, EvalControl.Clear, cm); } } return val; } private final TLCState getNextStatesApplUsrDefOp(final Action action, final OpApplNode pred, final ActionItemList acts, final TLCState s0, final TLCState s1, final INextStateFunctor nss, final CostModel cm, final Object bval) { if (!(bval instanceof BoolValue)) { Assert.fail(EC.TLC_EXPECTED_EXPRESSION_IN_COMPUTING, new String[] { "next states", "boolean", bval.toString(), pred.toString() }, pred); } if (((BoolValue) bval).val) { if (coverage) { return this.getNextStates(action, acts, s0, s1, nss, cm); } else { return this.getNextStates0(action, acts, s0, s1, nss, cm); } } return s1; } private final TLCState getNextStatesApplSwitch(final Action action, final OpApplNode pred, final ActionItemList acts, final Context c, final TLCState s0, final TLCState s1, final INextStateFunctor nss, final CostModel cm, final ExprOrOpArgNode[] args, final int alen, final int opcode) { TLCState resState = s1; switch (opcode) { case OPCODE_cl: // ConjList case OPCODE_land: { ActionItemList acts1 = acts; for (int i = alen - 1; i > 0; i acts1 = (ActionItemList) acts1.cons(args[i], c, cm, i); } return this.getNextStates(action, args[0], acts1, c, s0, s1, nss, cm); } case OPCODE_dl: // DisjList case OPCODE_lor: { if (PROBABLISTIC) { // probabilistic (return after a state has been generated, ordered is randomized) final RandomGenerator rng = TLCGlobals.simulator.getRNG(); int index = (int) Math.floor(rng.nextDouble() * alen); final int p = rng.nextPrime(); for (int i = 0; i < alen; i++) { resState = this.getNextStates(action, args[index], acts, c, s0, resState, nss, cm); if (nss.hasStates()) { return resState; } index = (index + p) % alen; } } else { for (int i = 0; i < alen; i++) { resState = this.getNextStates(action, args[i], acts, c, s0, resState, nss, cm); } } return resState; } case OPCODE_be: // BoundedExists { SemanticNode body = args[0]; if (PROBABLISTIC) { // probabilistic (return after a state has been generated, ordered is randomized) final ContextEnumerator Enum = this.contexts(Ordering.RANDOMIZED, pred, c, s0, s1, EvalControl.Clear, cm); Context c1; while ((c1 = Enum.nextElement()) != null) { resState = this.getNextStates(action, body, acts, c1, s0, resState, nss, cm); if (nss.hasStates()) { return resState; } } } else { // non-deterministically generate successor states (potentially many) ContextEnumerator Enum = this.contexts(pred, c, s0, s1, EvalControl.Clear, cm); Context c1; while ((c1 = Enum.nextElement()) != null) { resState = this.getNextStates(action, body, acts, c1, s0, resState, nss, cm); } } return resState; } case OPCODE_bf: // BoundedForall { SemanticNode body = args[0]; ContextEnumerator Enum = this.contexts(pred, c, s0, s1, EvalControl.Clear, cm); Context c1 = Enum.nextElement(); if (c1 == null) { resState = this.getNextStates(action, acts, s0, s1, nss, cm); } else { ActionItemList acts1 = acts; Context c2; while ((c2 = Enum.nextElement()) != null) { acts1 = (ActionItemList) acts1.cons(body, c2, cm, IActionItemList.PRED); } resState = this.getNextStates(action, body, acts1, c1, s0, s1, nss, cm); } return resState; } case OPCODE_fa: // FcnApply { Value fval = this.eval(args[0], c, s0, s1, EvalControl.KeepLazy, cm); if (fval instanceof FcnLambdaValue) { FcnLambdaValue fcn = (FcnLambdaValue)fval; if (fcn.fcnRcd == null) { Context c1 = this.getFcnContext(fcn, args, c, s0, s1, EvalControl.Clear, cm); return this.getNextStates(action, fcn.body, acts, c1, s0, s1, nss, fcn.cm); } fval = fcn.fcnRcd; } if (!(fval instanceof Applicable)) { Assert.fail("In computing next states, a non-function (" + fval.getKindString() + ") was applied as a function.\n" + pred, pred, c); } Applicable fcn = (Applicable)fval; Value argVal = this.eval(args[1], c, s0, s1, EvalControl.Clear, cm); Value bval = fcn.apply(argVal, EvalControl.Clear); if (!(bval instanceof BoolValue)) { Assert.fail(EC.TLC_EXPECTED_EXPRESSION_IN_COMPUTING2, new String[] { "next states", "boolean", pred.toString() }, args[1], c); } if (((BoolValue)bval).val) { return this.getNextStates(action, acts, s0, s1, nss, cm); } return resState; } case OPCODE_aa: // AngleAct <A>_e { ActionItemList acts1 = (ActionItemList) acts.cons(args[1], c, cm, IActionItemList.CHANGED); return this.getNextStates(action, args[0], acts1, c, s0, s1, nss, cm); } case OPCODE_sa: { /* The following two lines of code did not work, and were changed by * YuanYu to mimic the way \/ works. Change made * 11 Mar 2009, with LL sitting next to him. */ // this.getNextStates(action, args[0], acts, c, s0, s1, nss); // return this.processUnchanged(args[1], acts, c, s0, s1, nss); resState = this.getNextStates(action, args[0], acts, c, s0, resState, nss, cm); return this.processUnchanged(action, args[1], acts, c, s0, resState, nss, cm); } case OPCODE_ite: // IfThenElse { Value guard = this.eval(args[0], c, s0, s1, EvalControl.Clear, cm); if (!(guard instanceof BoolValue)) { Assert.fail("In computing next states, a non-boolean expression (" + guard.getKindString() + ") was used as the condition of" + " an IF." + pred, pred, c); } if (((BoolValue)guard).val) { return this.getNextStates(action, args[1], acts, c, s0, s1, nss, cm); } else { return this.getNextStates(action, args[2], acts, c, s0, s1, nss, cm); } } case OPCODE_case: // Case { SemanticNode other = null; if (PROBABLISTIC) { // See Bounded exists above! throw new UnsupportedOperationException( "Probabilistic evaluation of next-state relation not implemented for CASE yet."); } for (int i = 0; i < alen; i++) { OpApplNode pair = (OpApplNode)args[i]; ExprOrOpArgNode[] pairArgs = pair.getArgs(); if (pairArgs[0] == null) { other = pairArgs[1]; } else { Value bval = this.eval(pairArgs[0], c, s0, s1, EvalControl.Clear, coverage ? cm.get(args[i]) : cm); if (!(bval instanceof BoolValue)) { Assert.fail("In computing next states, a non-boolean expression (" + bval.getKindString() + ") was used as a guard condition" + " of a CASE.\n" + pairArgs[1], pairArgs[1], c); } if (((BoolValue)bval).val) { return this.getNextStates(action, pairArgs[1], acts, c, s0, s1, nss, coverage ? cm.get(args[i]) : cm); } } } if (other == null) { Assert.fail("In computing next states, TLC encountered a CASE with no" + " conditions true.\n" + pred, pred, c); } return this.getNextStates(action, other, acts, c, s0, s1, nss, coverage ? cm.get(args[alen - 1]) : cm); } case OPCODE_eq: { SymbolNode var = this.getPrimedVar(args[0], c, false); // Assert.check(var.getName().getVarLoc() >= 0); if (var == null) { Value bval = this.eval(pred, c, s0, s1, EvalControl.Clear, cm); if (!((BoolValue)bval).val) { return resState; } } else { UniqueString varName = var.getName(); IValue lval = s1.lookup(varName); Value rval = this.eval(args[1], c, s0, s1, EvalControl.Clear, cm); if (lval == null) { resState.bind(varName, rval); resState = this.getNextStates(action, acts, s0, resState, nss, cm); resState.unbind(varName); return resState; } else if (!lval.equals(rval)) { return resState; } } return this.getNextStates(action, acts, s0, s1, nss, cm); } case OPCODE_in: { SymbolNode var = this.getPrimedVar(args[0], c, false); // Assert.check(var.getName().getVarLoc() >= 0); if (var == null) { Value bval = this.eval(pred, c, s0, s1, EvalControl.Clear, cm); if (!((BoolValue)bval).val) { return resState; } } else { UniqueString varName = var.getName(); Value lval = (Value) s1.lookup(varName); Value rval = this.eval(args[1], c, s0, s1, EvalControl.Clear, cm); if (lval == null) { if (!(rval instanceof Enumerable)) { Assert.fail("In computing next states, the right side of \\IN" + " is not enumerable.\n" + pred, pred, c); } if (PROBABLISTIC) { final ValueEnumeration Enum = ((Enumerable)rval).elements(Ordering.RANDOMIZED); Value elem; while ((elem = Enum.nextElement()) != null) { resState.bind(varName, elem); resState = this.getNextStates(action, acts, s0, resState, nss, cm); resState.unbind(varName); if (nss.hasStates()) { return resState; } } } ValueEnumeration Enum = ((Enumerable)rval).elements(); Value elem; while ((elem = Enum.nextElement()) != null) { resState.bind(varName, elem); resState = this.getNextStates(action, acts, s0, resState, nss, cm); resState.unbind(varName); } return resState; } else if (!rval.member(lval)) { return resState; } } return this.getNextStates(action, acts, s0, s1, nss, cm); } case OPCODE_implies: { Value bval = this.eval(args[0], c, s0, s1, EvalControl.Clear, cm); if (!(bval instanceof BoolValue)) { Assert.fail("In computing next states of a predicate of the form" + " P => Q, P was\n" + bval.getKindString() + ".\n" + pred, pred, c); } if (((BoolValue)bval).val) { return this.getNextStates(action, args[1], acts, c, s0, s1, nss, cm); } else { return this.getNextStates(action, acts, s0, s1, nss, cm); } } case OPCODE_unchanged: { return this.processUnchanged(action, args[0], acts, c, s0, s1, nss, cm); } case OPCODE_cdot: { Assert.fail("The current version of TLC does not support action composition.", pred, c); return s1; } // The following case added by LL on 13 Nov 2009 to handle subexpression names. case OPCODE_nop: { return this.getNextStates(action, args[0], acts, c, s0, s1, nss, cm); } default: { // We handle all the other builtin operators here. Value bval = this.eval(pred, c, s0, s1, EvalControl.Clear, cm); if (!(bval instanceof BoolValue)) { Assert.fail(EC.TLC_EXPECTED_EXPRESSION_IN_COMPUTING, new String[] { "next states", "boolean", bval.toString(), pred.toString() }, pred, c); } if (((BoolValue)bval).val) { resState = this.getNextStates(action, acts, s0, s1, nss, cm); } return resState; } } } /* processUnchanged */ @ExpectInlined protected abstract TLCState processUnchanged(final Action action, SemanticNode expr, ActionItemList acts, Context c, TLCState s0, TLCState s1, INextStateFunctor nss, CostModel cm); protected final TLCState processUnchangedImpl(final Action action, SemanticNode expr, ActionItemList acts, Context c, TLCState s0, TLCState s1, INextStateFunctor nss, CostModel cm) { if (coverage){cm = cm.get(expr);} SymbolNode var = this.getVar(expr, c, false, toolId); TLCState resState = s1; if (var != null) { return processUnchangedImplVar(action, expr, acts, s0, s1, nss, var, cm); } if (expr instanceof OpApplNode) { OpApplNode expr1 = (OpApplNode)expr; ExprOrOpArgNode[] args = expr1.getArgs(); int alen = args.length; SymbolNode opNode = expr1.getOperator(); UniqueString opName = opNode.getName(); int opcode = BuiltInOPs.getOpCode(opName); if (opcode == OPCODE_tup) { return processUnchangedImplTuple(action, acts, c, s0, s1, nss, args, alen, cm, coverage ? cm.get(expr1) : cm); } if (opcode == 0 && alen == 0) { // a 0-arity operator: return processUnchangedImpl0Arity(action, expr, acts, c, s0, s1, nss, cm, opNode, opName); } } IValue v0 = this.eval(expr, c, s0, cm); Value v1 = this.eval(expr, c, s1, TLCState.Null, EvalControl.Clear, cm); if (v0.equals(v1)) { resState = this.getNextStates(action, acts, s0, s1, nss, cm); } return resState; } @ExpectInlined private final TLCState processUnchangedImpl0Arity(final Action action, final SemanticNode expr, final ActionItemList acts, final Context c, final TLCState s0, final TLCState s1, final INextStateFunctor nss, final CostModel cm, final SymbolNode opNode, final UniqueString opName) { final Object val = this.lookup(opNode, c, false); if (val instanceof OpDefNode) { return this.processUnchanged(action, ((OpDefNode)val).getBody(), acts, c, s0, s1, nss, cm); } else if (val instanceof LazyValue) { final LazyValue lv = (LazyValue)val; return this.processUnchanged(action, lv.expr, acts, lv.con, s0, s1, nss, cm); } else { Assert.fail("In computing next states, TLC found the identifier\n" + opName + " undefined in an UNCHANGED expression at\n" + expr, expr, c); } return this.getNextStates(action, acts, s0, s1, nss, cm); } @Override public IValue eval(SemanticNode expr, Context c, TLCState s0) { return this.eval(expr, c, s0, TLCState.Empty, EvalControl.Clear, CostModel.DO_NOT_RECORD); } @Override public IValue eval(SemanticNode expr, Context c) { return this.eval(expr, c, TLCState.Empty); } @Override public IValue eval(SemanticNode expr) { return this.eval(expr, Context.Empty); } @ExpectInlined private final TLCState processUnchangedImplTuple(final Action action, ActionItemList acts, Context c, TLCState s0, TLCState s1, INextStateFunctor nss, ExprOrOpArgNode[] args, int alen, CostModel cm, CostModel cmNested) { // a tuple: if (alen != 0) { ActionItemList acts1 = acts; for (int i = alen-1; i > 0; i acts1 = (ActionItemList) acts1.cons(args[i], c, cmNested, IActionItemList.UNCHANGED); } return this.processUnchanged(action, args[0], acts1, c, s0, s1, nss, cmNested); } return this.getNextStates(action, acts, s0, s1, nss, cm); } @ExpectInlined private final TLCState processUnchangedImplVar(final Action action, SemanticNode expr, ActionItemList acts, TLCState s0, TLCState s1, INextStateFunctor nss, SymbolNode var, final CostModel cm) { TLCState resState = s1; // expr is a state variable: final UniqueString varName = var.getName(); final IValue val0 = s0.lookup(varName); final IValue val1 = s1.lookup(varName); if (val1 == null) { resState.bind(varName, val0); if (coverage) { resState = this.getNextStates(action, acts, s0, resState, nss, cm); } else { resState = this.getNextStates0(action, acts, s0, resState, nss, cm); } resState.unbind(varName); } else if (val0.equals(val1)) { if (coverage) { resState = this.getNextStates(action, acts, s0, s1, nss, cm); } else { resState = this.getNextStates0(action, acts, s0, s1, nss, cm); } } else { MP.printWarning(EC.TLC_UNCHANGED_VARIABLE_CHANGED, new String[]{varName.toString(), expr.toString()}); } return resState; } /* eval */ public TLCState evalAlias(TLCState current, TLCState successor) { if ("".equals(this.config.getAlias())) { return current; } // see getState(..) IdThread.setCurrentState(current); // See asserts in tlc2.debug.TLCActionStackFrame.TLCActionStackFrame(TLCStackFrame, SemanticNode, Context, Tool, TLCState, Action, TLCState, RuntimeException) if (successor.getLevel() != current.getLevel()) { // Calling setPrecessor when the levels are equal would increase the level of // successor. successor.setPredecessor(current); } try { final TLCState alias = eval(getAliasSpec(), Context.Empty, current, successor, EvalControl.Clear).toState(); if (alias != null) { return alias; } } catch (EvalException | TLCRuntimeException e) { // Fall back to original state if eval fails. return current; } return current; } public TLCStateInfo evalAlias(TLCStateInfo current, TLCState successor) { if ("".equals(this.config.getAlias())) { return current; } // see getState(..) IdThread.setCurrentState(current.state); // See asserts in // tlc2.debug.TLCActionStackFrame.TLCActionStackFrame(TLCStackFrame, // SemanticNode, Context, Tool, TLCState, Action, TLCState, RuntimeException) if (successor.getLevel() != current.state.getLevel()) { // Calling setPrecessor when the levels are equal would increase the level of // successor. successor.setPredecessor(current); } try { final TLCState alias = eval(getAliasSpec(), Context.Empty, current.state, successor, EvalControl.Clear).toState(); if (alias != null) { return new AliasTLCStateInfo(alias, current); } } catch (EvalException | TLCRuntimeException e) { // Fall back to original state if eval fails. return current; // TODO We have to somehow communicate this exception back to the user. // Unfortunately, the alias cannot be validated by SpecProcess (unless pure // constant expression who are too simple to be used in trace expressions). // Throwing the exception would be possible, but pretty annoying if TLC fails // to print an error trace because of a bogus alias after hours of model // checking (this is the very reason why the code falls back to return the // original/current state). Printing the exception to stdout/stderr here // would mess with the Toolbox's parsing that reads stdout back in. It would // also look bad because we would print the error on every evaluation of the // alias and it's conceivable that -in most cases- evaluation would fail for // all evaluations. This suggests that we have to defer reporting of evaluation // and runtime exception until after the error-trace has been printed. If // evaluation only failed for some invocations of evalAlias, the user will // be able to figure out the ones that failed by looking at the trace. This // state should not be kept in Tool, because it doesn't know how to group // sequences of evalAlias invocations. // We could avoid keeping state entirely, if the exception was attached as an // "auxiliary" variable to the TLCStateInfo and printed as part of the error // trace. The error trace would look strange, but it appears to be the best // compromise, especially if only some of the evaluations fail. } return current; } /* Special version of eval for state expressions. */ @Override public IValue eval(SemanticNode expr, Context c, TLCState s0, CostModel cm) { return this.eval(expr, c, s0, TLCState.Empty, EvalControl.Clear, cm); } @Override public final IValue eval(SemanticNode expr, Context c, TLCState s0, TLCState s1, final int control) { return eval(expr, c, s0, s1, control, CostModel.DO_NOT_RECORD); } /* * This method evaluates the expression expr in the given context, * current state, and partial next state. */ public abstract Value eval(SemanticNode expr, Context c, TLCState s0, TLCState s1, final int control, final CostModel cm); @ExpectInlined protected Value evalImpl(final SemanticNode expr, final Context c, final TLCState s0, final TLCState s1, final int control, CostModel cm) { switch (expr.getKind()) { case LabelKind: { LabelNode expr1 = (LabelNode) expr; return this.eval(expr1.getBody(), c, s0, s1, control, cm); } case OpApplKind: { OpApplNode expr1 = (OpApplNode)expr; if (coverage) {cm = cm.get(expr);} return this.evalAppl(expr1, c, s0, s1, control, cm); } case LetInKind: { return evalImplLetInKind((LetInNode) expr, c, s0, s1, control, cm); } case SubstInKind: { return evalImplSubstInKind((SubstInNode) expr, c, s0, s1, control, cm); } // Added by LL on 13 Nov 2009 to handle theorem and assumption names. case APSubstInKind: { return evalImplApSubstInKind((APSubstInNode) expr, c, s0, s1, control, cm); } case NumeralKind: case DecimalKind: case StringKind: { return (Value) WorkerValue.mux(expr.getToolObject(toolId)); } case AtNodeKind: { return (Value)c.lookup(EXCEPT_AT); } case OpArgKind: { return evalImplOpArgKind((OpArgNode) expr, c, s0, s1, cm); } default: { Assert.fail("Attempted to evaluate an expression that cannot be evaluated.\n" + expr, expr, c); return null; // make compiler happy } } } @ExpectInlined private final Value evalImplLetInKind(LetInNode expr1, Context c, TLCState s0, TLCState s1, final int control, final CostModel cm) { OpDefNode[] letDefs = expr1.getLets(); int letLen = letDefs.length; Context c1 = c; for (int i = 0; i < letLen; i++) { OpDefNode opDef = letDefs[i]; if (opDef.getArity() == 0) { Value rhs = new LazyValue(opDef.getBody(), c1, cm); c1 = c1.cons(opDef, rhs); } } return this.eval(expr1.getBody(), c1, s0, s1, control, cm); } @ExpectInlined private final Value evalImplSubstInKind(SubstInNode expr1, Context c, TLCState s0, TLCState s1, final int control, final CostModel cm) { Subst[] subs = expr1.getSubsts(); int slen = subs.length; Context c1 = c; for (int i = 0; i < slen; i++) { Subst sub = subs[i]; c1 = c1.cons(sub.getOp(), this.getVal(sub.getExpr(), c, true, coverage ? sub.getCM() : cm, toolId)); } return this.eval(expr1.getBody(), c1, s0, s1, control, cm); } @ExpectInlined private final Value evalImplApSubstInKind(APSubstInNode expr1, Context c, TLCState s0, TLCState s1, final int control, final CostModel cm) { Subst[] subs = expr1.getSubsts(); int slen = subs.length; Context c1 = c; for (int i = 0; i < slen; i++) { Subst sub = subs[i]; c1 = c1.cons(sub.getOp(), this.getVal(sub.getExpr(), c, true, cm, toolId)); } return this.eval(expr1.getBody(), c1, s0, s1, control, cm); } @ExpectInlined private final Value evalImplOpArgKind(OpArgNode expr1, Context c, TLCState s0, TLCState s1, final CostModel cm) { SymbolNode opNode = expr1.getOp(); Object val = this.lookup(opNode, c, false); if (val instanceof OpDefNode) { return setSource(expr1, new OpLambdaValue((OpDefNode)val, this, c, s0, s1, cm)); } return (Value)val; } /* evalAppl */ @ExpectInlined protected abstract Value evalAppl(final OpApplNode expr, Context c, TLCState s0, TLCState s1, final int control, final CostModel cm); protected final Value evalApplImpl(final OpApplNode expr, Context c, TLCState s0, TLCState s1, final int control, CostModel cm) { if (coverage){ cm = cm.getAndIncrement(expr); } ExprOrOpArgNode[] args = expr.getArgs(); SymbolNode opNode = expr.getOperator(); int opcode = BuiltInOPs.getOpCode(opNode.getName()); if (opcode == 0) { // This is a user-defined operator with one exception: it may // be substed by a builtin operator. This special case occurs // when the lookup returns an OpDef with opcode Object val = this.lookup(opNode, c, s0, EvalControl.isPrimed(control)); // First, unlazy if it is a lazy value. We cannot use the cached // value when s1 == null or isEnabled(control). if (val instanceof LazyValue) { final LazyValue lv = (LazyValue) val; if (s1 == null) { val = this.eval(lv.expr, lv.con, s0, TLCState.Null, control, lv.getCostModel()); } else if (lv.isUncachable() || EvalControl.isEnabled(control)) { // Never use cached LazyValues in an ENABLED expression. This is why all // this.enabled* methods pass EvalControl.Enabled (the only exception being the // call on line line 2799 which passes EvalControl.Primed). This is why we can // be sure that ENALBED expressions are not affected by the caching bug tracked // in Github issue 113 (see below). val = this.eval(lv.expr, lv.con, s0, s1, control, lv.getCostModel()); } else { val = lv.getValue(); if (val == null) { final Value res = this.eval(lv.expr, lv.con, s0, s1, control, lv.getCostModel()); // This check has been suggested by Yuan Yu on 01/15/2018: // If init-states are being generated, level has to be <= ConstantLevel for // caching/LazyValue to be allowed. If next-states are being generated, level // has to be <= VariableLevel. The level indicates if the expression to be // evaluated contains only constants, constants & variables, constants & // variables and primed variables (thus action) or is a temporal formula. // This restriction is in place to fix Github issue 113 // TLC can generate invalid sets of init or next-states caused by broken // LazyValue evaluation. The related tests are AssignmentInit* and // AssignmentNext*. Without this fix TLC essentially reuses a stale lv.val when // it needs to re-evaluate res because the actual operands to eval changed. // Below is Leslie's formal description of the bug: // The possible initial values of some variable var are specified by a subformula // F(..., var, ...) // in the initial predicate, for some operator F such that expanding the // definition of F results in a formula containing more than one occurrence of // var , not all occurring in separate disjuncts of that formula. // The possible next values of some variable var are specified by a subformula // F(..., var', ...) // in the next-state relation, for some operator F such that expanding the // definition of F results in a formula containing more than one occurrence of // var' , not all occurring in separate disjuncts of that formula. // An example of the first case is an initial predicate Init defined as follows: // VARIABLES x, ... // F(var) == \/ var \in 0..99 /\ var % 2 = 0 // \/ var = -1 // Init == /\ F(x) // The error would not appear if F were defined by: // F(var) == \/ var \in {i \in 0..99 : i % 2 = 0} // \/ var = -1 // or if the definition of F(x) were expanded in Init : // Init == /\ \/ x \in 0..99 /\ x % 2 = 0 // \/ x = -1 // A similar example holds for case 2 with the same operator F and the // next-state formula // Next == /\ F(x') // The workaround is to rewrite the initial predicate or next-state relation so // it is not in the form that can cause the bug. The simplest way to do that is // to expand (in-line) the definition of F in the definition of the initial // predicate or next-state relation. // Note that EvalControl.Init is only set in the scope of this.getInitStates*, // but not in the scope of methods such as this.isInModel, this.isGoodState... // which are invoked by DFIDChecker and ModelChecker#doInit and doNext. These // invocation however don't pose a problem with regards to issue 113 because // they don't generate the set of initial or next states but get passed fully // generated/final states. // !EvalControl.isInit(control) means Tool is either processing the spec in // this.process* as part of initialization or that next-states are being // generated. The latter case has to restrict usage of cached LazyValue as // discussed above. final int level = ((LevelNode) lv.expr).getLevel(); // cast to LevelNode is safe because LV only subclass of SN. if ((EvalControl.isInit(control) && level <= LevelConstants.ConstantLevel) || (!EvalControl.isInit(control) && level <= LevelConstants.VariableLevel)) { // The performance benefits of caching values is generally debatable. The time // it takes TLC to check a reasonable sized model of the PaxosCommit [1] spec is // ~2h with, with limited caching due to the fix for issue 113 or without // caching. There is no measurable performance difference even though the change // for issue 113 reduces the cache hits from ~13 billion to ~4 billion. This was // measured with an instrumented version of TLC. // [1] general/performance/PaxosCommit/ lv.setValue(res); } val = res; } } } Value res = null; if (val instanceof OpDefNode) { OpDefNode opDef = (OpDefNode)val; opcode = BuiltInOPs.getOpCode(opDef.getName()); if (opcode == 0) { Context c1 = this.getOpContext(opDef, args, c, true, cm, toolId); res = this.eval(opDef.getBody(), c1, s0, s1, control, cm); } } else if (val instanceof Value) { res = (Value)val; int alen = args.length; if (alen == 0) { if (val instanceof MethodValue) { res = ((MethodValue)val).apply(EmptyArgs, EvalControl.Clear); } else if (val instanceof EvaluatingValue) { // Allow EvaluatingValue overwrites to have zero arity. res = ((EvaluatingValue) val).eval(this, args, c, s0, s1, control, cm); } } else { if (val instanceof OpValue) { res = ((OpValue) val).eval(this, args, c, s0, s1, control, cm); } } } else if (val instanceof ThmOrAssumpDefNode) { // Assert.fail("Trying to evaluate the theorem or assumption name `" // + opNode.getName() + "'. \nUse `" + opNode.getName() // + "!:' instead.\n" +expr); ThmOrAssumpDefNode opDef = (ThmOrAssumpDefNode) val ; Context c1 = this.getOpContext(opDef, args, c, true); return this.eval(opDef.getBody(), c1, s0, s1, control, cm); } else { if (!EvalControl.isEnabled(control) && EvalControl.isPrimed(control) && opNode instanceof OpDeclNode) { // We end up here if fairness is declared on a sub-action that doesn't define // the value of all variables given in the subscript vars (state pred) part of // the (weak or strong) fairness operator: // VARIABLES a,b \* opNode is b up here. // vars == <<a,b>> // A == a' = 42 // Next == A /\ b = b' \* Do something with b. // Spec == ... /\ WF_vars(A) // Variants: // /\ WF_b(TRUE) // /\ WF_vars(TRUE) // This variant is debatable. It triggers the "generic" exception below: // /\ WF_vars(a' = b') // For larger specs, this is obviously difficult to debug. Especially, // because opNode usually points to b on the vars == <<...>> line. // The following issues confirm that even seasoned users run into this: Assert.fail(EC.TLC_STATE_NOT_COMPLETELY_SPECIFIED_LIVE, new String[] { opNode.getName().toString(), expr.toString() }, expr, c); // Assert#fail throws exception, thus, no need for an else. } // EV#Enabled /\ EV#Prime /\ OpDeclNode is the case when A is an action (a boolean // valued transition function (see page 312 in Specifying Systems) appearing in an // invariant that TLC cannot evaluate. E.g.: // Spec == Init /\ [][a' = a + 1]_a // Inv == ENABLED a' > a // EV#Clear /\ OpDeclNode is the case when A is an action that TLC // cannot evaluate. E.g.: // Spec == Init /\ [][a' > a]_a Assert.fail(EC.TLC_CONFIG_UNDEFINED_OR_NO_OPERATOR, new String[] { opNode.getName().toString(), expr.toString() }, expr, c); } if (opcode == 0) { return res; } } switch (opcode) { case OPCODE_bc: // BoundedChoose { SemanticNode pred = args[0]; SemanticNode inExpr = expr.getBdedQuantBounds()[0]; Value inVal = this.eval(inExpr, c, s0, s1, control, cm); if (!(inVal instanceof Enumerable)) { Assert.fail("Attempted to compute the value of an expression of\n" + "form CHOOSE x \\in S: P, but S was not enumerable.\n" + expr, expr, c); } // To fix Bugzilla Bug 279 : TLC bug caused by TLC's not preserving the semantics of CHOOSE // (@see tlc2.tool.BugzillaBug279Test), // the statement // inVal.normalize(); // was replaced by the following by LL on 7 Mar 2012. This fix has not yet received // the blessing of Yuan Yu, so it should be considered to be provisional. // Value convertedVal = inVal.ToSetEnum(); // if (convertedVal != null) { // inVal = convertedVal; // } else { // inVal.normalize(); // end of fix. // MAK 09/22/2018: // The old fix above has the undesired side effect of enumerating inVal. In // other words, e.g. a SUBSET 1..8 would be enumerated and normalized into a // SetEnumValue. This is expensive and especially overkill, if the CHOOSE // predicate holds for most if not all elements of inVal. In this case, we // don't want to fully enumerate inVal but instead return the first element // obtained from Enumerable#elements for which the predicate holds. Thus, // Enumerable#elements(Ordering) has been added by which we make the requirement // for elements to be normalized explicit. Implementor of Enumerable, such as // SubsetValue are then free to implement elements that returns elements in // normalized order without converting SubsetValue into SetEnumValue first. inVal.normalize(); ValueEnumeration enumSet = ((Enumerable)inVal).elements(Enumerable.Ordering.NORMALIZED); FormalParamNode[] bvars = expr.getBdedQuantSymbolLists()[0]; boolean isTuple = expr.isBdedQuantATuple()[0]; if (isTuple) { // Identifier tuple case: int cnt = bvars.length; Value val; while ((val = enumSet.nextElement()) != null) { TupleValue tv = (TupleValue) val.toTuple(); if (tv == null || tv.size() != cnt) { Assert.fail("Attempted to compute the value of an expression of form\n" + "CHOOSE <<x1, ... , xN>> \\in S: P, but S was not a set\n" + "of N-tuples.\n" + expr, expr, c); } Context c1 = c; for (int i = 0; i < cnt; i++) { c1 = c1.cons(bvars[i], tv.elems[i]); } Value bval = this.eval(pred, c1, s0, s1, control, cm); if (!(bval instanceof BoolValue)) { Assert.fail(EC.TLC_EXPECTED_VALUE, new String[]{"boolean", expr.toString()}, pred, c1); } if (((BoolValue)bval).val) { return (Value) val; } } } else { // Simple identifier case: SymbolNode name = bvars[0]; Value val; while ((val = enumSet.nextElement()) != null) { Context c1 = c.cons(name, val); Value bval = this.eval(pred, c1, s0, s1, control, cm); if (!(bval instanceof BoolValue)) { Assert.fail(EC.TLC_EXPECTED_VALUE, new String[]{"boolean", expr.toString()}, pred, c1); } if (((BoolValue)bval).val) { return (Value) val; } } } Assert.fail("Attempted to compute the value of an expression of form\n" + "CHOOSE x \\in S: P, but no element of S satisfied P.\n" + expr, expr, c); return null; // make compiler happy } case OPCODE_be: // BoundedExists { ContextEnumerator Enum = this.contexts(expr, c, s0, s1, control, cm); SemanticNode body = args[0]; Context c1; while ((c1 = Enum.nextElement()) != null) { Value bval = this.eval(body, c1, s0, s1, control, cm); if (!(bval instanceof BoolValue)) { Assert.fail(EC.TLC_EXPECTED_VALUE, new String[]{"boolean", expr.toString()}, body, c1); } if (((BoolValue)bval).val) { return BoolValue.ValTrue; } } return BoolValue.ValFalse; } case OPCODE_bf: // BoundedForall { ContextEnumerator Enum = this.contexts(expr, c, s0, s1, control, cm); SemanticNode body = args[0]; Context c1; while ((c1 = Enum.nextElement()) != null) { Value bval = this.eval(body, c1, s0, s1, control, cm); if (!(bval instanceof BoolValue)) { Assert.fail(EC.TLC_EXPECTED_VALUE, new String[]{"boolean", expr.toString()}, body, c1); } if (!((BoolValue)bval).val) { return BoolValue.ValFalse; } } return BoolValue.ValTrue; } case OPCODE_case: // Case { int alen = args.length; SemanticNode other = null; for (int i = 0; i < alen; i++) { OpApplNode pairNode = (OpApplNode)args[i]; ExprOrOpArgNode[] pairArgs = pairNode.getArgs(); if (pairArgs[0] == null) { other = pairArgs[1]; if (coverage) { cm = cm.get(pairNode); } } else { Value bval = this.eval(pairArgs[0], c, s0, s1, control, coverage ? cm.get(pairNode) : cm); if (!(bval instanceof BoolValue)) { Assert.fail("A non-boolean expression (" + bval.getKindString() + ") was used as a condition of a CASE. " + pairArgs[0], pairArgs[0], c); } if (((BoolValue)bval).val) { return this.eval(pairArgs[1], c, s0, s1, control, coverage ? cm.get(pairNode) : cm); } } } if (other == null) { Assert.fail("Attempted to evaluate a CASE with no conditions true.\n" + expr, expr, c); } return this.eval(other, c, s0, s1, control, cm); } case OPCODE_cp: // CartesianProd { int alen = args.length; Value[] sets = new Value[alen]; for (int i = 0; i < alen; i++) { sets[i] = this.eval(args[i], c, s0, s1, control, cm); } return setSource(expr, new SetOfTuplesValue(sets, cm)); } case OPCODE_cl: // ConjList { int alen = args.length; for (int i = 0; i < alen; i++) { Value bval = this.eval(args[i], c, s0, s1, control, cm); if (!(bval instanceof BoolValue)) { Assert.fail("A non-boolean expression (" + bval.getKindString() + ") was used as a formula in a conjunction.\n" + args[i], args[i], c); } if (!((BoolValue)bval).val) { return BoolValue.ValFalse; } } return BoolValue.ValTrue; } case OPCODE_dl: // DisjList { int alen = args.length; for (int i = 0; i < alen; i++) { Value bval = this.eval(args[i], c, s0, s1, control, cm); if (!(bval instanceof BoolValue)) { Assert.fail("A non-boolean expression (" + bval.getKindString() + ") was used as a formula in a disjunction.\n" + args[i], args[i], c); } if (((BoolValue)bval).val) { return BoolValue.ValTrue; } } return BoolValue.ValFalse; } case OPCODE_exc: // Except { int alen = args.length; Value result = this.eval(args[0], c, s0, s1, control, cm); // SZ: variable not used ValueExcept[] expts = new ValueExcept[alen-1]; for (int i = 1; i < alen; i++) { OpApplNode pairNode = (OpApplNode)args[i]; ExprOrOpArgNode[] pairArgs = pairNode.getArgs(); SemanticNode[] cmpts = ((OpApplNode)pairArgs[0]).getArgs(); Value[] lhs = new Value[cmpts.length]; for (int j = 0; j < lhs.length; j++) { lhs[j] = this.eval(cmpts[j], c, s0, s1, control, coverage ? cm.get(pairNode).get(pairArgs[0]) : cm); } Value atVal = result.select(lhs); if (atVal == null) { // Do nothing but warn: MP.printWarning(EC.TLC_EXCEPT_APPLIED_TO_UNKNOWN_FIELD, new String[]{args[0].toString()}); } else { Context c1 = c.cons(EXCEPT_AT, atVal); Value rhs = this.eval(pairArgs[1], c1, s0, s1, control, coverage ? cm.get(pairNode) : cm); ValueExcept vex = new ValueExcept(lhs, rhs); result = (Value) result.takeExcept(vex); } } return result; } case OPCODE_fa: // FcnApply { Value result = null; Value fval = this.eval(args[0], c, s0, s1, EvalControl.setKeepLazy(control), cm); if ((fval instanceof FcnRcdValue) || (fval instanceof FcnLambdaValue)) { Applicable fcn = (Applicable)fval; Value argVal = this.eval(args[1], c, s0, s1, control, cm); result = fcn.apply(argVal, control); } else if ((fval instanceof TupleValue) || (fval instanceof RecordValue)) { Applicable fcn = (Applicable)fval; if (args.length != 2) { Assert.fail("Attempted to evaluate an expression of form f[e1, ... , eN]" + "\nwith f a tuple or record and N > 1.\n" + expr, expr, c); } Value aval = this.eval(args[1], c, s0, s1, control, cm); result = fcn.apply(aval, control); } else { Assert.fail("A non-function (" + fval.getKindString() + ") was applied" + " as a function.\n" + expr, expr, c); } return result; } case OPCODE_fc: // FcnConstructor case OPCODE_nrfs: // NonRecursiveFcnSpec case OPCODE_rfs: // RecursiveFcnSpec { FormalParamNode[][] formals = expr.getBdedQuantSymbolLists(); boolean[] isTuples = expr.isBdedQuantATuple(); ExprNode[] domains = expr.getBdedQuantBounds(); Value[] dvals = new Value[domains.length]; boolean isFcnRcd = true; for (int i = 0; i < dvals.length; i++) { dvals[i] = this.eval(domains[i], c, s0, s1, control, cm); isFcnRcd = isFcnRcd && (dvals[i] instanceof Reducible); } FcnParams params = new FcnParams(formals, isTuples, dvals); SemanticNode fbody = args[0]; FcnLambdaValue fval = (FcnLambdaValue) setSource(expr, new FcnLambdaValue(params, fbody, this, c, s0, s1, control, cm)); if (opcode == OPCODE_rfs) { SymbolNode fname = expr.getUnbdedQuantSymbols()[0]; fval.makeRecursive(fname); isFcnRcd = false; } if (isFcnRcd && !EvalControl.isKeepLazy(control)) { return (Value) fval.toFcnRcd(); } return fval; } case OPCODE_ite: // IfThenElse { Value bval = this.eval(args[0], c, s0, s1, control, cm); if (!(bval instanceof BoolValue)) { Assert.fail("A non-boolean expression (" + bval.getKindString() + ") was used as the condition of an IF.\n" + expr, expr, c); } if (((BoolValue)bval).val) { return this.eval(args[1], c, s0, s1, control, cm); } return this.eval(args[2], c, s0, s1, control, cm); } case OPCODE_rc: // RcdConstructor { int alen = args.length; UniqueString[] names = new UniqueString[alen]; Value[] vals = new Value[alen]; for (int i = 0; i < alen; i++) { OpApplNode pairNode = (OpApplNode)args[i]; ExprOrOpArgNode[] pair = pairNode.getArgs(); names[i] = ((StringValue)pair[0].getToolObject(toolId)).getVal(); vals[i] = this.eval(pair[1], c, s0, s1, control, coverage ? cm.get(pairNode) : cm); } return setSource(expr, new RecordValue(names, vals, false, cm)); } case OPCODE_rs: // RcdSelect { Value rval = this.eval(args[0], c, s0, s1, control, cm); Value sval = (Value) WorkerValue.mux(args[1].getToolObject(toolId)); if (rval instanceof RecordValue) { Value result = (Value) ((RecordValue)rval).select(sval); if (result == null) { Assert.fail("Attempted to select nonexistent field " + sval + " from the" + " record\n" + Values.ppr(rval.toString()) + "\n" + expr, expr, c); } return result; } else { FcnRcdValue fcn = (FcnRcdValue) rval.toFcnRcd(); if (fcn == null) { Assert.fail("Attempted to select field " + sval + " from a non-record" + " value " + Values.ppr(rval.toString()) + "\n" + expr, expr, c); } return fcn.apply(sval, control); } } case OPCODE_se: // SetEnumerate { int alen = args.length; ValueVec vals = new ValueVec(alen); for (int i = 0; i < alen; i++) { vals.addElement(this.eval(args[i], c, s0, s1, control, cm)); } return setSource(expr, new SetEnumValue(vals, false, cm)); } case OPCODE_soa: // SetOfAll: {e(x) : x \in S} { ValueVec vals = new ValueVec(); ContextEnumerator Enum = this.contexts(expr, c, s0, s1, control, cm); SemanticNode body = args[0]; Context c1; while ((c1 = Enum.nextElement()) != null) { Value val = this.eval(body, c1, s0, s1, control, cm); vals.addElement(val); // vals.addElement1(val); } return setSource(expr, new SetEnumValue(vals, false, cm)); } case OPCODE_sor: // SetOfRcds { int alen = args.length; UniqueString names[] = new UniqueString[alen]; Value vals[] = new Value[alen]; for (int i = 0; i < alen; i++) { OpApplNode pairNode = (OpApplNode)args[i]; ExprOrOpArgNode[] pair = pairNode.getArgs(); names[i] = ((StringValue)pair[0].getToolObject(toolId)).getVal(); vals[i] = this.eval(pair[1], c, s0, s1, control, coverage ? cm.get(pairNode) : cm); } return setSource(expr, new SetOfRcdsValue(names, vals, false, cm)); } case OPCODE_sof: // SetOfFcns { Value lhs = this.eval(args[0], c, s0, s1, control, cm); Value rhs = this.eval(args[1], c, s0, s1, control, cm); return setSource(expr, new SetOfFcnsValue(lhs, rhs, cm)); } case OPCODE_sso: // SubsetOf { SemanticNode pred = args[0]; SemanticNode inExpr = expr.getBdedQuantBounds()[0]; Value inVal = this.eval(inExpr, c, s0, s1, control, cm); boolean isTuple = expr.isBdedQuantATuple()[0]; FormalParamNode[] bvars = expr.getBdedQuantSymbolLists()[0]; if (inVal instanceof Reducible) { ValueVec vals = new ValueVec(); ValueEnumeration enumSet = ((Enumerable)inVal).elements(); Value elem; if (isTuple) { while ((elem = enumSet.nextElement()) != null) { Context c1 = c; Value[] tuple = ((TupleValue)elem).elems; for (int i = 0; i < bvars.length; i++) { c1 = c1.cons(bvars[i], tuple[i]); } Value bval = this.eval(pred, c1, s0, s1, control, cm); if (!(bval instanceof BoolValue)) { Assert.fail("Attempted to evaluate an expression of form {x \\in S : P(x)}" + " when P was " + bval.getKindString() + ".\n" + pred, pred, c1); } if (((BoolValue)bval).val) { vals.addElement(elem); } } } else { SymbolNode idName = bvars[0]; while ((elem = enumSet.nextElement()) != null) { Context c1 = c.cons(idName, elem); Value bval = this.eval(pred, c1, s0, s1, control, cm); if (!(bval instanceof BoolValue)) { Assert.fail("Attempted to evaluate an expression of form {x \\in S : P(x)}" + " when P was " + bval.getKindString() + ".\n" + pred, pred, c1); } if (((BoolValue)bval).val) { vals.addElement(elem); } } } return setSource(expr, new SetEnumValue(vals, inVal.isNormalized(), cm)); } else if (isTuple) { return setSource(expr, new SetPredValue(bvars, inVal, pred, this, c, s0, s1, control, cm)); } else { return setSource(expr, new SetPredValue(bvars[0], inVal, pred, this, c, s0, s1, control, cm)); } } case OPCODE_tup: // Tuple { int alen = args.length; Value[] vals = new Value[alen]; for (int i = 0; i < alen; i++) { vals[i] = this.eval(args[i], c, s0, s1, control, cm); } return setSource(expr, new TupleValue(vals, cm)); } case OPCODE_uc: // UnboundedChoose { Assert.fail("TLC attempted to evaluate an unbounded CHOOSE.\n" + "Make sure that the expression is of form CHOOSE x \\in S: P(x).\n" + expr, expr, c); return null; // make compiler happy } case OPCODE_ue: // UnboundedExists { Assert.fail("TLC attempted to evaluate an unbounded \\E.\n" + "Make sure that the expression is of form \\E x \\in S: P(x).\n" + expr, expr, c); return null; // make compiler happy } case OPCODE_uf: // UnboundedForall { Assert.fail("TLC attempted to evaluate an unbounded \\A.\n" + "Make sure that the expression is of form \\A x \\in S: P(x).\n" + expr, expr, c); return null; // make compiler happy } case OPCODE_lnot: { Value arg = this.eval(args[0], c, s0, s1, control, cm); if (!(arg instanceof BoolValue)) { Assert.fail("Attempted to apply the operator ~ to a non-boolean\n(" + arg.getKindString() + ")\n" + expr, args[0], c); } return (((BoolValue)arg).val) ? BoolValue.ValFalse : BoolValue.ValTrue; } case OPCODE_subset: { Value arg = this.eval(args[0], c, s0, s1, control, cm); return setSource(expr, new SubsetValue(arg, cm)); } case OPCODE_union: { Value arg = this.eval(args[0], c, s0, s1, control, cm); return setSource(expr, UnionValue.union(arg)); } case OPCODE_domain: { Value arg = this.eval(args[0], c, s0, s1, control, cm); if (!(arg instanceof Applicable)) { Assert.fail("Attempted to apply the operator DOMAIN to a non-function\n(" + arg.getKindString() + ")\n" + expr, expr, c); } return setSource(expr, ((Applicable)arg).getDomain()); } case OPCODE_enabled: { TLCState sfun = TLCStateFun.Empty; Context c1 = Context.branch(c); sfun = this.enabled(args[0], ActionItemList.Empty, c1, s0, sfun, cm); return (sfun != null) ? BoolValue.ValTrue : BoolValue.ValFalse; } case OPCODE_eq: { Value arg1 = this.eval(args[0], c, s0, s1, control, cm); Value arg2 = this.eval(args[1], c, s0, s1, control, cm); return (arg1.equals(arg2)) ? BoolValue.ValTrue : BoolValue.ValFalse; } case OPCODE_land: { Value arg1 = this.eval(args[0], c, s0, s1, control, cm); if (!(arg1 instanceof BoolValue)) { Assert.fail("Attempted to evaluate an expression of form P /\\ Q" + " when P was\n" + arg1.getKindString() + ".\n" + expr, expr, c); } if (((BoolValue)arg1).val) { Value arg2 = this.eval(args[1], c, s0, s1, control, cm); if (!(arg2 instanceof BoolValue)) { Assert.fail("Attempted to evaluate an expression of form P /\\ Q" + " when Q was\n" + arg2.getKindString() + ".\n" + expr, expr, c); } return arg2; } return BoolValue.ValFalse; } case OPCODE_lor: { Value arg1 = this.eval(args[0], c, s0, s1, control, cm); if (!(arg1 instanceof BoolValue)) { Assert.fail("Attempted to evaluate an expression of form P \\/ Q" + " when P was\n" + arg1.getKindString() + ".\n" + expr, expr, c); } if (((BoolValue)arg1).val) { return BoolValue.ValTrue; } Value arg2 = this.eval(args[1], c, s0, s1, control, cm); if (!(arg2 instanceof BoolValue)) { Assert.fail("Attempted to evaluate an expression of form P \\/ Q" + " when Q was\n" + arg2.getKindString() + ".\n" + expr, expr, c); } return arg2; } case OPCODE_implies: { Value arg1 = this.eval(args[0], c, s0, s1, control, cm); if (!(arg1 instanceof BoolValue)) { Assert.fail("Attempted to evaluate an expression of form P => Q" + " when P was\n" + arg1.getKindString() + ".\n" + expr, expr, c); } if (((BoolValue)arg1).val) { Value arg2 = this.eval(args[1], c, s0, s1, control, cm); if (!(arg2 instanceof BoolValue)) { Assert.fail("Attempted to evaluate an expression of form P => Q" + " when Q was\n" + arg2.getKindString() + ".\n" + expr, expr, c); } return arg2; } return BoolValue.ValTrue; } case OPCODE_equiv: { Value arg1 = this.eval(args[0], c, s0, s1, control, cm); Value arg2 = this.eval(args[1], c, s0, s1, control, cm); if (!(arg1 instanceof BoolValue) || !(arg2 instanceof BoolValue)) { Assert.fail("Attempted to evaluate an expression of form P <=> Q" + " when P or Q was not a boolean.\n" + expr, expr, c); } BoolValue bval1 = (BoolValue)arg1; BoolValue bval2 = (BoolValue)arg2; return (bval1.val == bval2.val) ? BoolValue.ValTrue : BoolValue.ValFalse; } case OPCODE_noteq: { Value arg1 = this.eval(args[0], c, s0, s1, control, cm); Value arg2 = this.eval(args[1], c, s0, s1, control, cm); return arg1.equals(arg2) ? BoolValue.ValFalse : BoolValue.ValTrue; } case OPCODE_subseteq: { Value arg1 = this.eval(args[0], c, s0, s1, control, cm); Value arg2 = this.eval(args[1], c, s0, s1, control, cm); if (!(arg1 instanceof Enumerable)) { Assert.fail("Attempted to evaluate an expression of form S \\subseteq T," + " but S was not enumerable.\n" + expr, expr, c); } return ((Enumerable) arg1).isSubsetEq(arg2); } case OPCODE_in: { Value arg1 = this.eval(args[0], c, s0, s1, control, cm); Value arg2 = this.eval(args[1], c, s0, s1, control, cm); return (arg2.member(arg1)) ? BoolValue.ValTrue : BoolValue.ValFalse; } case OPCODE_notin: { Value arg1 = this.eval(args[0], c, s0, s1, control, cm); Value arg2 = this.eval(args[1], c, s0, s1, control, cm); return (arg2.member(arg1)) ? BoolValue.ValFalse : BoolValue.ValTrue; } case OPCODE_setdiff: { Value arg1 = this.eval(args[0], c, s0, s1, control, cm); Value arg2 = this.eval(args[1], c, s0, s1, control, cm); if (arg1 instanceof Reducible) { return setSource(expr, ((Reducible)arg1).diff(arg2)); } return setSource(expr, new SetDiffValue(arg1, arg2)); } case OPCODE_cap: { Value arg1 = this.eval(args[0], c, s0, s1, control, cm); Value arg2 = this.eval(args[1], c, s0, s1, control, cm); if (arg1 instanceof Reducible) { return setSource(expr, ((Reducible)arg1).cap(arg2)); } else if (arg2 instanceof Reducible) { return setSource(expr, ((Reducible)arg2).cap(arg1)); } return setSource(expr, new SetCapValue(arg1, arg2)); } case OPCODE_nop: // Added by LL on 2 Aug 2007 { return eval(args[0], c, s0, s1, control, cm); } case OPCODE_cup: { Value arg1 = this.eval(args[0], c, s0, s1, control, cm); Value arg2 = this.eval(args[1], c, s0, s1, control, cm); if (arg1 instanceof Reducible) { return setSource(expr, ((Reducible)arg1).cup(arg2)); } else if (arg2 instanceof Reducible) { return setSource(expr, ((Reducible)arg2).cup(arg1)); } return setSource(expr, new SetCupValue(arg1, arg2, cm)); } case OPCODE_prime: { // MAK 03/2019: Cannot reproduce this but without this check the nested evaluation // fails with a NullPointerException which subsequently is swallowed. This makes it // impossible for a user to diagnose what is going on. Since I cannot reproduce the // actual expression, I leave this commented for. I recall an expression along the // lines of: // TLCSet(23, CHOOSE p \in pc: pc[p] # pc[p]') // The fail statement below is obviously too generic to be useful and needs to be // clarified if the actual cause has been identified. // if (s1 == null) { // Assert.fail("Attempted to evaluate the following expression," + // " but expression failed to evaluate.\n" + expr); return this.eval(args[0], c, s1, TLCState.Null, EvalControl.setPrimedIfEnabled(control), cm); } case OPCODE_unchanged: { Value v0 = this.eval(args[0], c, s0, TLCState.Empty, control, cm); Value v1 = this.eval(args[0], c, s1, TLCState.Null, EvalControl.setPrimedIfEnabled(control), cm); return (v0.equals(v1)) ? BoolValue.ValTrue : BoolValue.ValFalse; } case OPCODE_aa: { Value res = this.eval(args[0], c, s0, s1, control, cm); if (!(res instanceof BoolValue)) { Assert.fail("Attempted to evaluate an expression of form <A>_e," + " but A was not a boolean.\n" + expr, expr, c); } if (!((BoolValue)res).val) { return BoolValue.ValFalse; } Value v0 = this.eval(args[1], c, s0, TLCState.Empty, control, cm); Value v1 = this.eval(args[1], c, s1, TLCState.Null, EvalControl.setPrimedIfEnabled(control), cm); return v0.equals(v1) ? BoolValue.ValFalse : BoolValue.ValTrue; } case OPCODE_sa: { Value res = this.eval(args[0], c, s0, s1, control, cm); if (!(res instanceof BoolValue)) { Assert.fail("Attempted to evaluate an expression of form [A]_e," + " but A was not a boolean.\n" + expr, expr, c); } if (((BoolValue)res).val) { return BoolValue.ValTrue; } Value v0 = this.eval(args[1], c, s0, TLCState.Empty, control, cm); Value v1 = this.eval(args[1], c, s1, TLCState.Null, EvalControl.setPrimedIfEnabled(control), cm); return (v0.equals(v1)) ? BoolValue.ValTrue : BoolValue.ValFalse; } case OPCODE_cdot: { Assert.fail("The current version of TLC does not support action composition.", expr, c); return null; // make compiler happy } case OPCODE_sf: { Assert.fail(EC.TLC_ENCOUNTERED_FORMULA_IN_PREDICATE, new String[]{"SF", expr.toString()}, expr, c); return null; // make compiler happy } case OPCODE_wf: { Assert.fail(EC.TLC_ENCOUNTERED_FORMULA_IN_PREDICATE, new String[]{"WF", expr.toString()}, expr, c); return null; // make compiler happy } case OPCODE_te: // TemporalExists { Assert.fail(EC.TLC_ENCOUNTERED_FORMULA_IN_PREDICATE, new String[]{"\\EE", expr.toString()}, expr, c); return null; // make compiler happy } case OPCODE_tf: // TemporalForAll { Assert.fail(EC.TLC_ENCOUNTERED_FORMULA_IN_PREDICATE, new String[]{"\\AA", expr.toString()}, expr, c); return null; // make compiler happy } case OPCODE_leadto: { Assert.fail(EC.TLC_ENCOUNTERED_FORMULA_IN_PREDICATE, new String[]{"a ~> b", expr.toString()}, expr, c); return null; // make compiler happy } case OPCODE_arrow: { Assert.fail(EC.TLC_ENCOUNTERED_FORMULA_IN_PREDICATE, new String[]{"a -+-> formula", expr.toString()}, expr, c); return null; // make compiler happy } case OPCODE_box: { Assert.fail(EC.TLC_ENCOUNTERED_FORMULA_IN_PREDICATE, new String[]{"[]A", expr.toString()}, expr, c); return null; // make compiler happy } case OPCODE_diamond: { Assert.fail(EC.TLC_ENCOUNTERED_FORMULA_IN_PREDICATE, new String[]{"<>A", expr.toString()}, expr, c); return null; // make compiler happy } default: { Assert.fail("TLC BUG: could not evaluate this expression.\n" + expr, expr, c); return null; } } } protected abstract Value setSource(final SemanticNode expr, final Value value); @Override public final boolean isGoodState(TLCState state) { return state.allAssigned(); } /* This method determines if a state satisfies the model constraints. */ @Override public final boolean isInModel(TLCState state) throws EvalException { ExprNode[] constrs = this.getModelConstraints(); for (int i = 0; i < constrs.length; i++) { final CostModel cm = coverage ? ((Action) constrs[i].getToolObject(toolId)).cm : CostModel.DO_NOT_RECORD; IValue bval = this.eval(constrs[i], Context.Empty, state, cm); if (!(bval instanceof BoolValue)) { Assert.fail(EC.TLC_EXPECTED_VALUE, new String[]{"boolean", constrs[i].toString()}, constrs[i]); } if (!((BoolValue)bval).val) { if (coverage) { cm.incInvocations(); } return false; } else { if (coverage) { cm.incSecondary(); } } } return true; } /* This method determines if a pair of states satisfy the action constraints. */ @Override public final boolean isInActions(TLCState s1, TLCState s2) throws EvalException { ExprNode[] constrs = this.getActionConstraints(); for (int i = 0; i < constrs.length; i++) { final CostModel cm = coverage ? ((Action) constrs[i].getToolObject(toolId)).cm : CostModel.DO_NOT_RECORD; Value bval = this.eval(constrs[i], Context.Empty, s1, s2, EvalControl.Clear, cm); if (!(bval instanceof BoolValue)) { Assert.fail(EC.TLC_EXPECTED_VALUE, new String[]{"boolean", constrs[i].toString()}, constrs[i]); } if (!((BoolValue)bval).val) { if (coverage) { cm.incInvocations(); } return false; } else { if (coverage) { cm.incSecondary(); } } } return true; } @Override public final boolean hasStateOrActionConstraints() { return this.getModelConstraints().length > 0 || this.getActionConstraints().length > 0; } @Override public final TLCState enabled(SemanticNode pred, Context c, TLCState s0, TLCState s1) { return enabled(pred, ActionItemList.Empty, c, s0, s1, CostModel.DO_NOT_RECORD); } @Override public final TLCState enabled(SemanticNode pred, Context c, TLCState s0, TLCState s1, ExprNode subscript, final int ail) { ActionItemList acts = (ActionItemList) ActionItemList.Empty.cons(subscript, c, CostModel.DO_NOT_RECORD, ail); return enabled(pred, acts, c, s0, s1, CostModel.DO_NOT_RECORD); } @Override public final TLCState enabled(SemanticNode pred, IActionItemList acts, Context c, TLCState s0, TLCState s1) { return enabled(pred, acts, c, s0, s1, CostModel.DO_NOT_RECORD); } /** * This method determines if an action is enabled in the given state. * More precisely, it determines if (act.pred /\ (sub' # sub)) is * enabled in the state s and context act.con. */ @Override public abstract TLCState enabled(SemanticNode pred, IActionItemList acts, Context c, TLCState s0, TLCState s1, CostModel cm); protected final TLCState enabledImpl(SemanticNode pred, ActionItemList acts, Context c, TLCState s0, TLCState s1, CostModel cm) { switch (pred.getKind()) { case OpApplKind: { OpApplNode pred1 = (OpApplNode)pred; return this.enabledAppl(pred1, acts, c, s0, s1, cm); } case LetInKind: { LetInNode pred1 = (LetInNode)pred; OpDefNode[] letDefs = pred1.getLets(); Context c1 = c; for (int i = 0; i < letDefs.length; i++) { OpDefNode opDef = letDefs[i]; if (opDef.getArity() == 0) { Value rhs = new LazyValue(opDef.getBody(), c1, cm); c1 = c1.cons(opDef, rhs); } } return this.enabled(pred1.getBody(), acts, c1, s0, s1, cm); } case SubstInKind: { SubstInNode pred1 = (SubstInNode)pred; Subst[] subs = pred1.getSubsts(); int slen = subs.length; Context c1 = c; for (int i = 0; i < slen; i++) { Subst sub = subs[i]; c1 = c1.cons(sub.getOp(), this.getVal(sub.getExpr(), c, false, coverage ? sub.getCM() : cm, toolId)); } return this.enabled(pred1.getBody(), acts, c1, s0, s1, cm); } // Added by LL on 13 Nov 2009 to handle theorem and assumption names. case APSubstInKind: { APSubstInNode pred1 = (APSubstInNode)pred; Subst[] subs = pred1.getSubsts(); int slen = subs.length; Context c1 = c; for (int i = 0; i < slen; i++) { Subst sub = subs[i]; c1 = c1.cons(sub.getOp(), this.getVal(sub.getExpr(), c, false, cm, toolId)); } return this.enabled(pred1.getBody(), acts, c1, s0, s1, cm); } // LabelKind class added by LL on 13 Jun 2007 case LabelKind: { LabelNode pred1 = (LabelNode)pred; return this.enabled(pred1.getBody(), acts, c, s0, s1, cm); } default: { // We should not compute enabled on anything else. Assert.fail("Attempted to compute ENABLED on a non-boolean expression.\n" + pred, pred, c); return null; // make compiler happy } } } private final TLCState enabled(ActionItemList acts, TLCState s0, TLCState s1, CostModel cm) { if (acts.isEmpty()) return s1; final int kind = acts.carKind(); SemanticNode pred = acts.carPred(); Context c = acts.carContext(); cm = acts.cm; ActionItemList acts1 = acts.cdr(); if (kind > IActionItemList.CONJUNCT) { TLCState res = this.enabled(pred, acts1, c, s0, s1, cm); return res; } else if (kind == IActionItemList.PRED) { TLCState res = this.enabled(pred, acts1, c, s0, s1, cm); return res; } if (kind == IActionItemList.UNCHANGED) { TLCState res = this.enabledUnchanged(pred, acts1, c, s0, s1, cm); return res; } Value v1 = this.eval(pred, c, s0, TLCState.Empty, EvalControl.Enabled, cm); // We are now in ENABLED and primed state. Second TLCState parameter being null // effectively disables LazyValue in evalAppl (same effect as // EvalControl.setPrimed(EvalControl.Enabled)). Value v2 = this.eval(pred, c, s1, TLCState.Null, EvalControl.Primed, cm); if (v1.equals(v2)) return null; TLCState res = this.enabled(acts1, s0, s1, cm); return res; } protected abstract TLCState enabledAppl(OpApplNode pred, ActionItemList acts, Context c, TLCState s0, TLCState s1, CostModel cm); protected final TLCState enabledApplImpl(OpApplNode pred, ActionItemList acts, Context c, TLCState s0, TLCState s1, CostModel cm) { if (coverage) {cm = cm.get(pred);} ExprOrOpArgNode[] args = pred.getArgs(); int alen = args.length; SymbolNode opNode = pred.getOperator(); int opcode = BuiltInOPs.getOpCode(opNode.getName()); if (opcode == 0) { // This is a user-defined operator with one exception: it may // be substed by a builtin operator. This special case occurs // when the lookup returns an OpDef with opcode Object val = this.lookup(opNode, c, s0, false); if (val instanceof OpDefNode) { OpDefNode opDef = (OpDefNode) val; opcode = BuiltInOPs.getOpCode(opDef.getName()); if (opcode == 0) { // Context c1 = this.getOpContext(opDef, args, c, false); Context c1 = this.getOpContext(opDef, args, c, true, cm, toolId); return this.enabled(opDef.getBody(), acts, c1, s0, s1, cm); } } // Added 13 Nov 2009 by LL to handle theorem or assumption names if (val instanceof ThmOrAssumpDefNode) { ThmOrAssumpDefNode opDef = (ThmOrAssumpDefNode) val; Context c1 = this.getOpContext(opDef, args, c, true); return this.enabled(opDef.getBody(), acts, c1, s0, s1, cm); } if (val instanceof LazyValue) { LazyValue lv = (LazyValue) val; return this.enabled(lv.expr, acts, lv.con, s0, s1, lv.cm); } Object bval = val; if (alen == 0) { if (val instanceof MethodValue) { bval = ((MethodValue) val).apply(EmptyArgs, EvalControl.Clear); // EvalControl.Clear is ignored by MethodValuea#apply } else if (val instanceof EvaluatingValue) { bval = ((EvaluatingValue) val).eval(this, args, c, s0, s1, EvalControl.Enabled, cm); } } else { if (val instanceof OpValue) { bval = ((OpValue) val).eval(this, args, c, s0, s1, EvalControl.Enabled, cm); } } if (opcode == 0) { if (!(bval instanceof BoolValue)) { Assert.fail(EC.TLC_EXPECTED_EXPRESSION_IN_COMPUTING, new String[] { "ENABLED", "boolean", bval.toString(), pred.toString() }, pred, c); } if (((BoolValue) bval).val) { return this.enabled(acts, s0, s1, cm); } return null; } } switch (opcode) { case OPCODE_aa: // AngleAct <A>_e { ActionItemList acts1 = (ActionItemList) acts.cons(args[1], c, cm, IActionItemList.CHANGED); return this.enabled(args[0], acts1, c, s0, s1, cm); } case OPCODE_be: // BoundedExists { SemanticNode body = args[0]; ContextEnumerator Enum = this.contexts(pred, c, s0, s1, EvalControl.Enabled, cm); Context c1; while ((c1 = Enum.nextElement()) != null) { TLCState s2 = this.enabled(body, acts, c1, s0, s1, cm); if (s2 != null) { return s2; } } return null; } case OPCODE_bf: // BoundedForall { SemanticNode body = args[0]; ContextEnumerator Enum = this.contexts(pred, c, s0, s1, EvalControl.Enabled, cm); Context c1 = Enum.nextElement(); if (c1 == null) { return this.enabled(acts, s0, s1, cm); } ActionItemList acts1 = acts; Context c2; while ((c2 = Enum.nextElement()) != null) { acts1 = (ActionItemList) acts1.cons(body, c2, cm, IActionItemList.PRED); } return this.enabled(body, acts1, c1, s0, s1, cm); } case OPCODE_case: // Case { SemanticNode other = null; for (int i = 0; i < alen; i++) { OpApplNode pair = (OpApplNode) args[i]; ExprOrOpArgNode[] pairArgs = pair.getArgs(); if (pairArgs[0] == null) { other = pairArgs[1]; } else { Value bval = this.eval(pairArgs[0], c, s0, s1, EvalControl.Enabled, cm); if (!(bval instanceof BoolValue)) { Assert.fail("In computing ENABLED, a non-boolean expression(" + bval.getKindString() + ") was used as a guard condition" + " of a CASE.\n" + pairArgs[1], pairArgs[1], c); } if (((BoolValue) bval).val) { return this.enabled(pairArgs[1], acts, c, s0, s1, cm); } } } if (other == null) { Assert.fail("In computing ENABLED, TLC encountered a CASE with no" + " conditions true.\n" + pred, pred, c); } return this.enabled(other, acts, c, s0, s1, cm); } case OPCODE_cl: // ConjList case OPCODE_land: { ActionItemList acts1 = acts; for (int i = alen - 1; i > 0; i { acts1 = (ActionItemList) acts1.cons(args[i], c, cm, i); } return this.enabled(args[0], acts1, c, s0, s1, cm); } case OPCODE_dl: // DisjList case OPCODE_lor: { for (int i = 0; i < alen; i++) { TLCState s2 = this.enabled(args[i], acts, c, s0, s1, cm); if (s2 != null) { return s2; } } return null; } case OPCODE_fa: // FcnApply { Value fval = this.eval(args[0], c, s0, s1, EvalControl.setKeepLazy(EvalControl.Enabled), cm); // KeepLazy does not interfere with EvalControl.Enabled in this.evalAppl if (fval instanceof FcnLambdaValue) { FcnLambdaValue fcn = (FcnLambdaValue) fval; if (fcn.fcnRcd == null) { Context c1 = this.getFcnContext(fcn, args, c, s0, s1, EvalControl.Enabled, cm); // EvalControl.Enabled passed on to nested this.evalAppl return this.enabled(fcn.body, acts, c1, s0, s1, cm); } fval = fcn.fcnRcd; } if (fval instanceof Applicable) { Applicable fcn = (Applicable) fval; Value argVal = this.eval(args[1], c, s0, s1, EvalControl.Enabled, cm); Value bval = fcn.apply(argVal, EvalControl.Enabled); // EvalControl.Enabled not taken into account by any subclass of Applicable if (!(bval instanceof BoolValue)) { Assert.fail(EC.TLC_EXPECTED_EXPRESSION_IN_COMPUTING2, new String[] { "ENABLED", "boolean", pred.toString() }, args[1], c); } if (!((BoolValue) bval).val) { return null; } } else { Assert.fail("In computing ENABLED, a non-function (" + fval.getKindString() + ") was applied as a function.\n" + pred, pred, c); } return this.enabled(acts, s0, s1, cm); } case OPCODE_ite: // IfThenElse { Value guard = this.eval(args[0], c, s0, s1, EvalControl.Enabled, cm); if (!(guard instanceof BoolValue)) { Assert.fail("In computing ENABLED, a non-boolean expression(" + guard.getKindString() + ") was used as the guard condition" + " of an IF.\n" + pred, pred, c); } int idx = (((BoolValue) guard).val) ? 1 : 2; return this.enabled(args[idx], acts, c, s0, s1, cm); } case OPCODE_sa: // SquareAct [A]_e { TLCState s2 = this.enabled(args[0], acts, c, s0, s1, cm); if (s2 != null) { return s2; } return this.enabledUnchanged(args[1], acts, c, s0, s1, cm); } case OPCODE_te: // TemporalExists case OPCODE_tf: // TemporalForAll { Assert.fail("In computing ENABLED, TLC encountered temporal quantifier.\n" + pred, pred, c); return null; // make compiler happy } case OPCODE_uc: // UnboundedChoose { Assert.fail("In computing ENABLED, TLC encountered unbounded CHOOSE. " + "Make sure that the expression is of form CHOOSE x \\in S: P(x).\n" + pred, pred, c); return null; // make compiler happy } case OPCODE_ue: // UnboundedExists { Assert.fail("In computing ENABLED, TLC encountered unbounded quantifier. " + "Make sure that the expression is of form \\E x \\in S: P(x).\n" + pred, pred, c); return null; // make compiler happy } case OPCODE_uf: // UnboundedForall { Assert.fail("In computing ENABLED, TLC encountered unbounded quantifier. " + "Make sure that the expression is of form \\A x \\in S: P(x).\n" + pred, pred, c); return null; // make compiler happy } case OPCODE_sf: { Assert.fail(EC.TLC_ENABLED_WRONG_FORMULA, new String[]{ "SF", pred.toString()}, pred, c); return null; // make compiler happy } case OPCODE_wf: { Assert.fail(EC.TLC_ENABLED_WRONG_FORMULA, new String[] { "WF", pred.toString() }, pred, c); return null; // make compiler happy } case OPCODE_box: { Assert.fail(EC.TLC_ENABLED_WRONG_FORMULA, new String[] { "[]", pred.toString() }, pred, c); return null; // make compiler happy } case OPCODE_diamond: { Assert.fail(EC.TLC_ENABLED_WRONG_FORMULA, new String[] { "<>", pred.toString() }, pred, c); return null; // make compiler happy } case OPCODE_unchanged: { return this.enabledUnchanged(args[0], acts, c, s0, s1, cm); } case OPCODE_eq: { SymbolNode var = this.getPrimedVar(args[0], c, true); if (var == null) { Value bval = this.eval(pred, c, s0, s1, EvalControl.Enabled, cm); if (!((BoolValue) bval).val) { return null; } } else { UniqueString varName = var.getName(); IValue lval = s1.lookup(varName); Value rval = this.eval(args[1], c, s0, s1, EvalControl.Enabled, cm); if (lval == null) { TLCState s2 = s1.bind(var, rval); return this.enabled(acts, s0, s2, cm); } else { if (!lval.equals(rval)) { return null; } } } return this.enabled(acts, s0, s1, cm); } case OPCODE_implies: { Value bval = this.eval(args[0], c, s0, s1, EvalControl.Enabled, cm); if (!(bval instanceof BoolValue)) { Assert.fail("While computing ENABLED of an expression of the form" + " P => Q, P was " + bval.getKindString() + ".\n" + pred, pred, c); } if (((BoolValue) bval).val) { return this.enabled(args[1], acts, c, s0, s1, cm); } return this.enabled(acts, s0, s1, cm); } case OPCODE_cdot: { Assert.fail("The current version of TLC does not support action composition.", pred, c); return null; // make compiler happy } case OPCODE_leadto: { Assert.fail("In computing ENABLED, TLC encountered a temporal formula" + " (a ~> b).\n" + pred, pred, c); return null; // make compiler happy } case OPCODE_arrow: { Assert.fail("In computing ENABLED, TLC encountered a temporal formula" + " (a -+-> formula).\n" + pred, pred, c); return null; // make compiler happy } case OPCODE_in: { SymbolNode var = this.getPrimedVar(args[0], c, true); if (var == null) { Value bval = this.eval(pred, c, s0, s1, EvalControl.Enabled, cm); if (!((BoolValue) bval).val) { return null; } } else { UniqueString varName = var.getName(); Value lval = (Value) s1.lookup(varName); Value rval = this.eval(args[1], c, s0, s1, EvalControl.Enabled, cm); if (lval == null) { if (!(rval instanceof Enumerable)) { Assert.fail("The right side of \\IN is not enumerable.\n" + pred, pred, c); } ValueEnumeration Enum = ((Enumerable) rval).elements(); Value val; while ((val = Enum.nextElement()) != null) { TLCState s2 = s1.bind(var, val); s2 = this.enabled(acts, s0, s2, cm); if (s2 != null) { return s2; } } return null; } else { if (!rval.member(lval)) { return null; } } } return this.enabled(acts, s0, s1, cm); } // The following case added by LL on 13 Nov 2009 to handle subexpression names. case OPCODE_nop: { return this.enabled(args[0], acts, c, s0, s1, cm); } default: { // We handle all the other builtin operators here. Value bval = this.eval(pred, c, s0, s1, EvalControl.Enabled, cm); if (!(bval instanceof BoolValue)) { Assert.fail(EC.TLC_EXPECTED_EXPRESSION_IN_COMPUTING, new String[] { "ENABLED", "boolean", bval.toString(), pred.toString() }, pred, c); } if (((BoolValue) bval).val) { return this.enabled(acts, s0, s1, cm); } return null; } } } protected abstract TLCState enabledUnchanged(SemanticNode expr, ActionItemList acts, Context c, TLCState s0, TLCState s1, CostModel cm); protected final TLCState enabledUnchangedImpl(SemanticNode expr, ActionItemList acts, Context c, TLCState s0, TLCState s1, CostModel cm) { if (coverage) {cm = cm.get(expr);} SymbolNode var = this.getVar(expr, c, true, toolId); if (var != null) { // a state variable, e.g. UNCHANGED var1 UniqueString varName = var.getName(); Value v0 = this.eval(expr, c, s0, s1, EvalControl.Enabled, cm); IValue v1 = s1.lookup(varName); if (v1 == null) { s1 = s1.bind(var, v0); return this.enabled(acts, s0, s1, cm); } if (v1.equals(v0)) { return this.enabled(acts, s0, s1, cm); } MP.printWarning(EC.TLC_UNCHANGED_VARIABLE_CHANGED, new String[]{varName.toString() , expr.toString()}); return null; } if (expr instanceof OpApplNode) { OpApplNode expr1 = (OpApplNode)expr; ExprOrOpArgNode[] args = expr1.getArgs(); int alen = args.length; SymbolNode opNode = expr1.getOperator(); UniqueString opName = opNode.getName(); int opcode = BuiltInOPs.getOpCode(opName); if (opcode == OPCODE_tup) { // a tuple, e.g. UNCHANGED <<var1, var2>> if (alen != 0) { ActionItemList acts1 = acts; for (int i = 1; i < alen; i++) { acts1 = (ActionItemList) acts1.cons(args[i], c, cm, IActionItemList.UNCHANGED); } return this.enabledUnchanged(args[0], acts1, c, s0, s1, cm); } return this.enabled(acts, s0, s1, cm); } if (opcode == 0 && alen == 0) { // a 0-arity operator: Object val = this.lookup(opNode, c, false); if (val instanceof LazyValue) { LazyValue lv = (LazyValue)val; return this.enabledUnchanged(lv.expr, acts, lv.con, s0, s1, cm); } else if (val instanceof OpDefNode) { return this.enabledUnchanged(((OpDefNode)val).getBody(), acts, c, s0, s1, cm); } else if (val == null) { Assert.fail("In computing ENABLED, TLC found the undefined identifier\n" + opName + " in an UNCHANGED expression at\n" + expr, expr ,c); } return this.enabled(acts, s0, s1, cm); } } final Value v0 = this.eval(expr, c, s0, TLCState.Empty, EvalControl.Enabled, cm); // We are in ENABLED and primed but why pass only primed? This appears to // be the only place where we call eval from the ENABLED scope without // additionally passing EvalControl.Enabled. Not passing Enabled allows a // cached LazyValue could be used (see comments above on line 1384). // The current scope is a nested UNCHANGED in an ENABLED and evaluation is set // to primed. However, UNCHANGED e equals e' = e , so anything primed in e // which is rejected by SANY's level checking. A perfectly valid spec - where // e is not primed - but that also causes this code path to be taken is 23 below: // VARIABLE t // op(var) == var // Next == /\ (ENABLED (UNCHANGED op(t))) // /\ (t'= t) // Spec == (t = 0) /\ [][Next]_t // However, spec 23 causes the call to this.eval(...) below to throw an // EvalException either with EvalControl.Primed. The exception's message is // "In evaluation, the identifier t is either undefined or not an operator." // indicating that this code path is buggy. // If this bug is ever fixed to make TLC accept spec 23, EvalControl.Primed // should likely be rewritten to EvalControl.setPrimed(EvalControl.Enabled) // to disable reusage of LazyValues on line ~1384 above. final Value v1 = this.eval(expr, c, s1, TLCState.Empty, EvalControl.Primed, cm); if (!v0.equals(v1)) { return null; } return this.enabled(acts, s0, s1, cm); } /* This method determines if the action predicate is valid in (s0, s1). */ @Override public final boolean isValid(Action act, TLCState s0, TLCState s1) { Value val = this.eval(act.pred, act.con, s0, s1, EvalControl.Clear, act.cm); if (!(val instanceof BoolValue)) { Assert.fail(EC.TLC_EXPECTED_VALUE, new String[]{"boolean", act.pred.toString()}, act.pred, act.con); } return ((BoolValue)val).val; } /* Returns true iff the predicate is valid in the state. */ @Override public boolean isValid(Action act, TLCState state) { return this.isValid(act, state, TLCState.Empty); } /* Returns true iff the predicate is valid in the state. */ @Override public final boolean isValid(Action act) { return this.isValid(act, TLCState.Empty, TLCState.Empty); } @Override public final boolean isValid(ExprNode expr) { IValue val = this.eval(expr, Context.Empty, TLCState.Empty, TLCState.Empty, EvalControl.Const, CostModel.DO_NOT_RECORD); if (!(val instanceof BoolValue)) { Assert.fail(EC.TLC_EXPECTED_VALUE, new String[]{"boolean", expr.toString()}, expr); } return ((BoolValue)val).val; } @Override public final int checkAssumptions() { final ExprNode[] assumps = getAssumptions(); final boolean[] isAxiom = getAssumptionIsAxiom(); for (int i = 0; i < assumps.length; i++) { try { if ((!isAxiom[i]) && !isValid(assumps[i])) { return MP.printError(EC.TLC_ASSUMPTION_FALSE, assumps[i].toString()); } } catch (final Exception e) { // Assert.printStack(e); return MP.printError(EC.TLC_ASSUMPTION_EVALUATION_ERROR, new String[] { assumps[i].toString(), e.getMessage() }); } } return EC.NO_ERROR; } /* Reconstruct the initial state whose fingerprint is fp. */ @Override public final TLCStateInfo getState(final long fp) { class InitStateSelectorFunctor implements IStateFunctor { private final long fp; public TLCState state; public InitStateSelectorFunctor(long fp) { this.fp = fp; } @Override public Object addElement(TLCState state) { if (state == null) { return null; } else if (this.state != null) { // Always return the first match found. Do not let later matches override // this.state. This is in line with the original implementation that called // getInitStates(). return null; } else if (fp == state.fingerPrint()) { this.state = state; // TODO Stop generation of initial states preemptively. E.g. make the caller of // addElement check for a special return value such as this (the functor). } return null; } } // Registry a selector that extract out of the (possibly) large set of initial // states the one identified by fp. The functor pattern has the advantage // compared to this.getInitStates(), that it kind of streams the initial states // to the functor whereas getInitStates() stores _all_ init states in a set // which is traversed afterwards. This is also consistent with // ModelChecker#DoInitFunctor. Using the functor pattern for the processing of // init states in ModelChecker#doInit but calling getInitStates() here results // in a bug during error trace generation when the set of initial states is too // large for getInitStates(). Earlier TLC would have refused to run the model // during ModelChecker#doInit. final InitStateSelectorFunctor functor = new InitStateSelectorFunctor(fp); this.getInitStates(functor); final TLCState state = functor.state; if (state != null) { assert state.isInitial(); final TLCStateInfo info = new TLCStateInfo(state); info.fp = fp; return info; } return null; } /** * Reconstruct the next state of state s whose fingerprint is fp. * * @return Returns the TLCState wrapped in TLCStateInfo. TLCStateInfo stores * the stateNumber (relative to the given sinfo) and a pointer to * the predecessor. */ @Override public final TLCStateInfo getState(long fp, TLCStateInfo sinfo) { final TLCStateInfo tlcStateInfo = getState(fp, sinfo.state); if (tlcStateInfo == null) { throw new EvalException(EC.TLC_FAILED_TO_RECOVER_NEXT); } tlcStateInfo.stateNumber = sinfo.stateNumber + 1; tlcStateInfo.predecessorState = sinfo; tlcStateInfo.fp = fp; return tlcStateInfo; } /* Reconstruct the next state of state s whose fingerprint is fp. */ @Override public final TLCStateInfo getState(long fp, TLCState s) { IdThread.setCurrentState(s); for (int i = 0; i < this.actions.length; i++) { Action curAction = this.actions[i]; StateVec nextStates = this.getNextStates(curAction, s); for (int j = 0; j < nextStates.size(); j++) { TLCState state = nextStates.elementAt(j); long nfp = state.fingerPrint(); if (fp == nfp) { state.setPredecessor(s); assert !state.isInitial(); return new TLCStateInfo(state, curAction); } } } return null; } /* Reconstruct the info for s1. */ @Override public final TLCStateInfo getState(TLCState s1, TLCState s) { IdThread.setCurrentState(s); for (int i = 0; i < this.actions.length; i++) { Action curAction = this.actions[i]; StateVec nextStates = this.getNextStates(curAction, s); for (int j = 0; j < nextStates.size(); j++) { TLCState state = nextStates.elementAt(j); if (s1.equals(state)) { state.setPredecessor(s); assert !state.isInitial(); return new TLCStateInfo(state, curAction); } } } return null; } /* Return the set of all permutations under the symmetry assumption. */ @Override public final IMVPerm[] getSymmetryPerms() { final String name = this.config.getSymmetry(); if (name.length() == 0) { return null; } final Object symm = this.unprocessedDefns.get(name); if (symm == null) { Assert.fail(EC.TLC_CONFIG_SPECIFIED_NOT_DEFINED, new String[] { "symmetry function", name}); } if (!(symm instanceof OpDefNode)) { Assert.fail("The symmetry function " + name + " must specify a set of permutations."); } final OpDefNode opDef = (OpDefNode)symm; // This calls tlc2.module.TLC.Permutations(Value) and returns a Value of |fcns| // = n! where n is the capacity of the symmetry set. final IValue fcns = this.eval(opDef.getBody(), Context.Empty, TLCState.Empty, CostModel.DO_NOT_RECORD); if (!(fcns instanceof Enumerable) || !(fcns instanceof SetEnumValue)) { Assert.fail("The symmetry operator must specify a set of functions.", opDef.getBody()); } final List<Value> values = ((SetEnumValue)fcns).elements().all(); for (final Value v : values) { if (!(v instanceof FcnRcdValue)) { Assert.fail("The symmetry values must be function records.", opDef.getBody()); } } final ExprOrOpArgNode[] argNodes = ((OpApplNode)opDef.getBody()).getArgs(); // In the case where the config defines more than one set which is symmetric, they will pass through the // enumerable size() check even if they are single element sets final StringBuilder cardinalityOneSetList = new StringBuilder(); int offenderCount = 0; if (argNodes.length >= values.size()) { // If equal, we have as many values as we have permuted sets => we have all 1-element sets; // if greater than, then we have a heterogenous cardinality of sets, including 0 element sets. for (final ExprOrOpArgNode node : argNodes) { addToSubTwoSizedSymmetrySetList(node, cardinalityOneSetList); offenderCount++; } } final IMVPerm[] subgroup; if (offenderCount == 0) { subgroup = MVPerms.permutationSubgroup((Enumerable)fcns); final HashSet<ModelValue> subgroupMembers = new HashSet<>(); for (final IMVPerm imvp : subgroup) { if (imvp instanceof MVPerm) { // should always be the case subgroupMembers.addAll(((MVPerm)imvp).getAllModelValues()); } } for (final ExprOrOpArgNode node : argNodes) { final SetEnumValue enumValue = getSetEnumValueFromArgumentNode(node); if (enumValue != null) { final ValueEnumeration ve = enumValue.elements(); boolean found = false; Value v; while ((v = ve.nextElement()) != null) { if ((v instanceof ModelValue) && subgroupMembers.contains(v)) { found = true; break; } } if (!found) { addToSubTwoSizedSymmetrySetList(node, cardinalityOneSetList); offenderCount++; } } } } else { subgroup = null; } if (offenderCount > 0) { final String plurality = (offenderCount > 1) ? "s" : ""; final String antiPlurality = (offenderCount > 1) ? "" : "s"; final String toHaveConjugation = (offenderCount > 1) ? "have" : "has"; MP.printWarning(EC.TLC_SYMMETRY_SET_TOO_SMALL, new String[] { plurality, cardinalityOneSetList.toString(), toHaveConjugation, antiPlurality }); } return subgroup; } /** * Teases the original spec name for the set out of node and appends it to the {@code StringBuilder} instance. */ private void addToSubTwoSizedSymmetrySetList(final ExprOrOpArgNode node, final StringBuilder cardinalityOneSetList) { final SyntaxTreeNode tn = (SyntaxTreeNode)node.getTreeNode(); final String image = tn.getHumanReadableImage(); final String alias; if (image.startsWith(TLAConstants.BuiltInOperators.PERMUTATIONS)) { final int imageLength = image.length(); alias = image.substring((TLAConstants.BuiltInOperators.PERMUTATIONS.length() + 1), (imageLength - 1)); } else { alias = image; } final String specDefinitionName = this.config.getOverridenSpecNameForConfigName(alias); final String displayDefinition = (specDefinitionName != null) ? specDefinitionName : alias; if (cardinalityOneSetList.length() > 0) { cardinalityOneSetList.append(", and "); } cardinalityOneSetList.append(displayDefinition); } /** * @param node * @return if the node represents a permutation, this will return the {@link SetEnumValue} instance contains its * model values */ private SetEnumValue getSetEnumValueFromArgumentNode(final ExprOrOpArgNode node) { if (node instanceof OpApplNode) { final OpApplNode permutationNode = (OpApplNode)node; if (permutationNode.getOperator() instanceof OpDefNode) { final OpDefNode operator = (OpDefNode)permutationNode.getOperator(); if (TLAConstants.BuiltInOperators.PERMUTATIONS.equals(operator.getName().toString())) { final ExprOrOpArgNode[] operands = permutationNode.getArgs(); if ((operands.length == 1) && (operands[0] instanceof OpApplNode) && (((OpApplNode)operands[0]).getOperator() instanceof OpDefOrDeclNode)) { final Object o = ((OpDefOrDeclNode)((OpApplNode)operands[0]).getOperator()).getToolObject(toolId); if (o instanceof SetEnumValue) { return (SetEnumValue)o; } else if (o instanceof WorkerValue) { // If TLC was started with a -workers N specification, N > 1, o will be a WorkerValue instance final WorkerValue wv = (WorkerValue)o; final Object unwrapped = WorkerValue.mux(wv); if (unwrapped instanceof SetEnumValue) { return (SetEnumValue)unwrapped; } } } } } } return null; } @Override public final boolean hasSymmetry() { if (this.config == null) { return false; } final String name = this.config.getSymmetry(); return name.length() > 0; } @Override public final Context getFcnContext(IFcnLambdaValue fcn, ExprOrOpArgNode[] args, Context c, TLCState s0, TLCState s1, final int control) { return getFcnContext(fcn, args, c, s0, s1, control, CostModel.DO_NOT_RECORD); } @Override public final Context getFcnContext(IFcnLambdaValue fcn, ExprOrOpArgNode[] args, Context c, TLCState s0, TLCState s1, final int control, CostModel cm) { Context fcon = fcn.getCon(); int plen = fcn.getParams().length(); FormalParamNode[][] formals = fcn.getParams().getFormals(); Value[] domains = (Value[]) fcn.getParams().getDomains(); boolean[] isTuples = fcn.getParams().isTuples(); Value argVal = this.eval(args[1], c, s0, s1, control, cm); if (plen == 1) { if (!domains[0].member(argVal)) { Assert.fail("In applying the function\n" + Values.ppr(fcn.toString()) + ",\nthe first argument is:\n" + Values.ppr(argVal.toString()) + "which is not in its domain.\n" + args[0], args[0], c); } if (isTuples[0]) { FormalParamNode[] ids = formals[0]; TupleValue tv = (TupleValue) argVal.toTuple(); if (tv == null || argVal.size() != ids.length) { Assert.fail("In applying the function\n" + Values.ppr(this.toString()) + ",\nthe argument is:\n" + Values.ppr(argVal.toString()) + "which does not match its formal parameter.\n" + args[0], args[0], c); } Value[] elems = tv.elems; for (int i = 0; i < ids.length; i++) { fcon = fcon.cons(ids[i], elems[i]); } } else { fcon = fcon.cons(formals[0][0], argVal); } } else { TupleValue tv = (TupleValue) argVal.toTuple(); if (tv == null) { Assert.fail("Attempted to apply a function to an argument not in its" + " domain.\n" + args[0], args[0], c); } int argn = 0; Value[] elems = tv.elems; for (int i = 0; i < formals.length; i++) { FormalParamNode[] ids = formals[i]; Value domain = domains[i]; if (isTuples[i]) { if (!domain.member(elems[argn])) { Assert.fail("In applying the function\n" + Values.ppr(fcn.toString()) + ",\nthe argument number " + (argn+1) + " is:\n" + Values.ppr(elems[argn].toString()) + "\nwhich is not in its domain.\n" + args[0], args[0], c); } TupleValue tv1 = (TupleValue) elems[argn++].toTuple(); if (tv1 == null || tv1.size() != ids.length) { Assert.fail("In applying the function\n" + Values.ppr(fcn.toString()) + ",\nthe argument number " + argn + " is:\n" + Values.ppr(elems[argn-1].toString()) + "which does not match its formal parameter.\n" + args[0], args[0], c); } Value[] avals = tv1.elems; for (int j = 0; j < ids.length; j++) { fcon = fcon.cons(ids[j], avals[j]); } } else { for (int j = 0; j < ids.length; j++) { if (!domain.member(elems[argn])) { Assert.fail("In applying the function\n" + Values.ppr(fcn.toString()) + ",\nthe argument number " + (argn+1) + " is:\n" + Values.ppr(elems[argn].toString()) + "which is not in its domain.\n" + args[0], args[0], c); } fcon = fcon.cons(ids[j], elems[argn++]); } } } } return fcon; } @Override public final IContextEnumerator contexts(OpApplNode appl, Context c, TLCState s0, TLCState s1, final int control) { return contexts(appl, c, s0, s1, control, CostModel.DO_NOT_RECORD); } /* A context enumerator for an operator application. */ public final ContextEnumerator contexts(OpApplNode appl, Context c, TLCState s0, TLCState s1, final int control, CostModel cm) { return contexts(Ordering.NORMALIZED, appl, c, s0, s1, control, cm); } private final ContextEnumerator contexts(Ordering ordering, OpApplNode appl, Context c, TLCState s0, TLCState s1, final int control, CostModel cm) { FormalParamNode[][] formals = appl.getBdedQuantSymbolLists(); boolean[] isTuples = appl.isBdedQuantATuple(); ExprNode[] domains = appl.getBdedQuantBounds(); int flen = formals.length; int alen = 0; for (int i = 0; i < flen; i++) { alen += (isTuples[i]) ? 1 : formals[i].length; } Object[] vars = new Object[alen]; ValueEnumeration[] enums = new ValueEnumeration[alen]; int idx = 0; for (int i = 0; i < flen; i++) { Value boundSet = this.eval(domains[i], c, s0, s1, control, cm); if (!(boundSet instanceof Enumerable)) { Assert.fail("TLC encountered a non-enumerable quantifier bound\n" + Values.ppr(boundSet.toString()) + ".\n" + domains[i], domains[i], c); } FormalParamNode[] farg = formals[i]; if (isTuples[i]) { vars[idx] = farg; enums[idx++] = ((Enumerable)boundSet).elements(ordering); } else { for (int j = 0; j < farg.length; j++) { vars[idx] = farg[j]; enums[idx++] = ((Enumerable)boundSet).elements(ordering); } } } return new ContextEnumerator(vars, enums, c); } // These three are expected by implementing the {@link ITool} interface; they used // to mirror exactly methods that our parent class ({@link Spec}) implemented // however those methods have changed signature with refactoring done for // Issue #393 @Override public Context getOpContext(OpDefNode odn, ExprOrOpArgNode[] args, Context ctx, boolean b) { return getOpContext(odn, args, ctx, b, toolId); } @Override public Object lookup(SymbolNode opNode, Context con, boolean b) { return lookup(opNode, con, b, toolId); } @Override public Object getVal(ExprOrOpArgNode expr, Context con, boolean b) { return getVal(expr, con, b, toolId); } public static boolean isProbabilistic() { return PROBABLISTIC; } }
package org.jpmml.evaluator; import java.util.*; import org.jpmml.manager.*; import org.dmg.pmml.*; import com.google.common.collect.*; public class MeasureUtil { private MeasureUtil(){ } static public boolean isDistance(Measure measure){ return (measure instanceof Euclidean || measure instanceof SquaredEuclidean || measure instanceof Chebychev || measure instanceof CityBlock || measure instanceof Minkowski); } static public Double evaluateDistance(ComparisonMeasure comparisonMeasure, List<? extends ComparisonField> comparisonFields, List<FieldValue> values, List<FieldValue> referenceValues, Double adjustment){ double innerPower; double outerPower; Measure measure = comparisonMeasure.getMeasure(); if(measure instanceof Euclidean){ innerPower = outerPower = 2; } else if(measure instanceof SquaredEuclidean){ innerPower = 2; outerPower = 1; } else if(measure instanceof Chebychev || measure instanceof CityBlock){ innerPower = outerPower = 1; } else if(measure instanceof Minkowski){ Minkowski minkowski = (Minkowski)measure; double p = minkowski.getPParameter(); if(p < 0){ throw new InvalidFeatureException(minkowski); } innerPower = outerPower = p; } else { throw new UnsupportedFeatureException(measure); } List<Double> distances = Lists.newArrayList(); comparisonFields: for(int i = 0; i < comparisonFields.size(); i++){ ComparisonField comparisonField = comparisonFields.get(i); FieldValue value = values.get(i); if(value == null){ continue comparisonFields; } FieldValue referenceValue = referenceValues.get(i); Double distance = evaluateInnerFunction(comparisonMeasure, comparisonField, value, referenceValue, innerPower); distances.add(distance); } if(measure instanceof Euclidean || measure instanceof SquaredEuclidean || measure instanceof CityBlock || measure instanceof Minkowski){ double sum = 0; for(Double distance : distances){ sum += distance.doubleValue(); } return Math.pow(sum * adjustment.doubleValue(), 1d / outerPower); } else if(measure instanceof Chebychev){ Double max = Collections.max(distances); return max.doubleValue() * adjustment.doubleValue(); } else { throw new UnsupportedFeatureException(measure); } } static public boolean isSimilarity(Measure measure){ return (measure instanceof SimpleMatching || measure instanceof Jaccard || measure instanceof Tanimoto || measure instanceof BinarySimilarity); } static private double evaluateInnerFunction(ComparisonMeasure comparisonMeasure, ComparisonField comparisonField, FieldValue value, FieldValue referenceValue, Double power){ CompareFunctionType compareFunction = comparisonField.getCompareFunction(); if(compareFunction == null){ compareFunction = comparisonMeasure.getCompareFunction(); // The ComparisonMeasure element is limited to "attribute-less" comparison functions switch(compareFunction){ case ABS_DIFF: case DELTA: case EQUAL: break; case GAUSS_SIM: case TABLE: throw new InvalidFeatureException(comparisonMeasure); default: throw new UnsupportedFeatureException(comparisonMeasure, compareFunction); } } double distance; switch(compareFunction){ case ABS_DIFF: { double z = difference(value, referenceValue); distance = Math.abs(z); } break; case GAUSS_SIM: { Double similarityScale = comparisonField.getSimilarityScale(); if(similarityScale == null){ throw new InvalidFeatureException(comparisonField); } double z = difference(value, referenceValue); double s = similarityScale.doubleValue(); distance = Math.exp(-Math.log(2d) * Math.pow(z, 2d) / Math.pow(s, 2d)); } break; case DELTA: { boolean equals = equals(value, referenceValue); distance = (equals ? 0d : 1d); } break; case EQUAL: { boolean equals = equals(value, referenceValue); distance = (equals ? 1d : 0d); } break; case TABLE: throw new UnsupportedFeatureException(comparisonField, compareFunction); default: throw new UnsupportedFeatureException(comparisonField, compareFunction); } return comparisonField.getFieldWeight() * Math.pow(distance, power.doubleValue()); } static private double difference(FieldValue x, FieldValue y){ return ((x.asNumber()).doubleValue() - (y.asNumber()).doubleValue()); } static private boolean equals(FieldValue x, FieldValue y){ return (x).equalsValue(y); } static public Double calculateAdjustment(List<FieldValue> values, List<Double> adjustmentValues){ double sum = 0d; double nonmissingSum = 0d; for(int i = 0; i < values.size(); i++){ FieldValue value = values.get(i); Double adjustmentValue = adjustmentValues.get(i); sum += adjustmentValue.doubleValue(); nonmissingSum += (value != null ? adjustmentValue.doubleValue() : 0d); } return (sum / nonmissingSum); } static public Double calculateAdjustment(List<FieldValue> values){ double sum = 0d; double nonmissingSum = 0d; for(int i = 0; i < values.size(); i++){ FieldValue value = values.get(i); sum += 1d; nonmissingSum += (value != null ? 1d : 0d); } return (sum / nonmissingSum); } }
package joliex.surface; import java.net.URI; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import jolie.lang.NativeType; import jolie.lang.parse.ast.InputPortInfo; import jolie.lang.parse.ast.InterfaceDefinition; import jolie.lang.parse.ast.InterfaceExtenderDefinition; import jolie.lang.parse.ast.OneWayOperationDeclaration; import jolie.lang.parse.ast.OperationDeclaration; import jolie.lang.parse.ast.OutputPortInfo; import jolie.lang.parse.ast.RequestResponseOperationDeclaration; import jolie.lang.parse.ast.types.TypeDefinition; import jolie.lang.parse.ast.types.TypeDefinitionLink; import jolie.lang.parse.ast.types.TypeInlineDefinition; import jolie.lang.parse.util.Interfaces; import jolie.lang.parse.util.ProgramInspector; import jolie.runtime.typing.OneWayTypeDescription; import jolie.runtime.typing.RequestResponseTypeDescription; import jolie.util.Range; /** * * @author Claudio Guidi */ public class SurfaceCreator { private ProgramInspector inspector; private URI originalFile; private ArrayList<RequestResponseOperationDeclaration> rr_vector; private ArrayList<OneWayOperationDeclaration> ow_vector; private ArrayList<String> types_vector; private ArrayList<TypeDefinition> aux_types_vector; private int MAX_CARD = 2147483647; public SurfaceCreator( ProgramInspector inspector, URI originalFile ) { this.inspector = inspector; this.originalFile = originalFile; } public void ConvertDocument( String inputPortToCreate ) throws Exception { ArrayList<InterfaceDefinition> interface_vector = new ArrayList<InterfaceDefinition>(); rr_vector = new ArrayList<RequestResponseOperationDeclaration>(); ow_vector = new ArrayList<OneWayOperationDeclaration>(); types_vector = new ArrayList<String>(); aux_types_vector = new ArrayList<TypeDefinition>(); // find inputPort InputPortInfo[] inputPortList = inspector.getInputPorts( originalFile ); InputPortInfo inputPort = null; for( InputPortInfo iP : inputPortList ) { if ( iP.id().equals( inputPortToCreate ) ) { inputPort = iP; } } if ( inputPort == null ) { throw (new Exception( "Error! inputPort not found!" )); } // extracts the list of all the interfaces to be parsed // extracts interfaces declared into Interfaces for( InterfaceDefinition interfaceDefinition : inputPort.getInterfaceList() ) { interface_vector.add( interfaceDefinition ); } OutputPortInfo[] outputPortList = inspector.getOutputPorts( originalFile ); // extracts interfaces from aggregated outputPorts for( int x = 0; x < inputPort.aggregationList().length; x++ ) { int i = 0; while( !inputPort.aggregationList()[x].outputPortList()[0].equals( outputPortList[i].id() ) ) { i++; } for( InterfaceDefinition interfaceDefinition : outputPortList[i].getInterfaceList() ) { interface_vector.add( Interfaces.extend( interfaceDefinition, inputPort.aggregationList()[x].interfaceExtender(), inputPort.id() ) ); } } // for each interface extract the list of all the available operations and types for( InterfaceDefinition interfaceDefinition : interface_vector ) { addOperation( interfaceDefinition ); } // create oputput createOutput( inputPort ); } private void addOperation( InterfaceDefinition interfaceDefinition ) { for( OperationDeclaration op : interfaceDefinition.operationsMap().values() ) { if ( op instanceof RequestResponseOperationDeclaration ) { rr_vector.add( (RequestResponseOperationDeclaration) op ); } else { ow_vector.add( (OneWayOperationDeclaration) op ); } } } private String getOWString( OneWayOperationDeclaration ow ) { String ret = ow.id() + "( " + ow.requestType().id() + " )"; return ret; } private String getRRString( RequestResponseOperationDeclaration rr ) { String ret = rr.id() + "( " + rr.requestType().id() + " )( " + rr.responseType().id() + " )"; if ( rr.faults().size() > 0 ) { ret = ret + " throws "; boolean flag = false; for( Entry<String, TypeDefinition> fault : rr.faults().entrySet() ) { if ( flag == false ) { flag = true; } else { ret = ret + " "; } ret = ret + fault.getKey(); if ( fault.getValue() != null ) { ret = ret + "( " + fault.getValue().id() + " )"; } } } return ret; } private String getMax( int max ) { if ( max == MAX_CARD ) { return "*"; } else { return new Integer( max ).toString(); } } private String getCardinality( Range card ) { return "[" + card.min() + "," + getMax( card.max() ) + "]"; } private String getSubType( TypeDefinition type, int indent ) { String ret = ""; for( int y = 0; y < indent; y++ ) { ret = ret + "\t"; } ret = ret + "." + type.id() + getCardinality( type.cardinality() ) + ":"; if ( type instanceof TypeDefinitionLink ) { ret = ret + ((TypeDefinitionLink) type).linkedTypeName(); if ( !aux_types_vector.contains( ((TypeDefinitionLink) type).linkedType() ) ) { aux_types_vector.add( ((TypeDefinitionLink) type).linkedType() ); } } else { ret = ret + type.nativeType().id(); if ( ((TypeInlineDefinition) type).hasSubTypes() ) { ret = ret + "{ \n"; for( Entry<String, TypeDefinition> entry : ((TypeInlineDefinition) type).subTypes() ) { ret = ret + getSubType( entry.getValue(), indent + 1 ) + "\n"; } for( int y = 0; y < indent; y++ ) { ret = ret + "\t"; } ret = ret + "}"; } } ; return ret; } private String getType( TypeDefinition type ) { String ret = ""; if ( !types_vector.contains( type.id() ) && !NativeType.isNativeTypeKeyword( type.id() ) ) { System.out.print( "type " + type.id() + ":" ); if ( type instanceof TypeDefinitionLink ) { System.out.println( ((TypeDefinitionLink) type).linkedTypeName() ); if ( !aux_types_vector.contains( ((TypeDefinitionLink) type).linkedType() ) ) { aux_types_vector.add( ((TypeDefinitionLink) type).linkedType() ); } } else { System.out.print( type.nativeType().id() ); if ( ((TypeInlineDefinition) type).hasSubTypes() ) { System.out.println( "{" ); for( Entry<String, TypeDefinition> entry : ((TypeInlineDefinition) type).subTypes() ) { System.out.println( getSubType( entry.getValue(), 1 ) ); } System.out.println( "}" ); } else { System.out.println(); } } types_vector.add( type.id() ); } return ret; } private void printType( String type ) { if ( !type.equals( "" ) ) { System.out.println( type ); } } private void createOutput( InputPortInfo inputPort ) { // types creation if ( ow_vector.size() > 0 ) { for( int x = 0; x < ow_vector.size(); x++ ) { //System.out.println("// types for operation " + ow_vector.get(x).id() ); printType( getType( ow_vector.get( x ).requestType() ) ); } System.out.println(); } if ( rr_vector.size() > 0 ) { for( int x = 0; x < rr_vector.size(); x++ ) { //System.out.println("// types for operation " + rr_vector.get(x).id() ); printType( getType( rr_vector.get( x ).requestType() ) ); printType( getType( rr_vector.get( x ).responseType() ) ); for( Entry<String, TypeDefinition> fault : rr_vector.get( x ).faults().entrySet() ) { if ( !fault.getValue().id().equals( "undefined" ) ) { System.out.println( getType( fault.getValue() ) ); } } } System.out.println(); } // add auxiliary types while( !aux_types_vector.isEmpty() ) { ArrayList<TypeDefinition> aux_types_temp_vector = new ArrayList<TypeDefinition>(); aux_types_temp_vector.addAll( aux_types_vector ); aux_types_vector.clear(); Iterator it = aux_types_temp_vector.iterator(); while( it.hasNext() ) { printType( getType( (TypeDefinition) it.next() ) ); } } System.out.println(); // interface creation System.out.println( "interface " + inputPort.id() + "Surface {" ); // oneway declaration if ( ow_vector.size() > 0 ) { System.out.println( "OneWay:" ); for( int x = 0; x < ow_vector.size(); x++ ) { if ( x != 0 ) { System.out.println( "," ); } System.out.print( "\t" + getOWString( ow_vector.get( x ) ) ); } System.out.println(); } // request response declaration if ( rr_vector.size() > 0 ) { System.out.println( "RequestResponse:" ); for( int x = 0; x < rr_vector.size(); x++ ) { if ( x != 0 ) { System.out.println( "," ); } System.out.print( "\t" + getRRString( rr_vector.get( x ) ) ); } System.out.println(); } System.out.println( "}" ); System.out.println(); // outputPort definition System.out.println( "outputPort " + inputPort.id() + "{" ); System.out.println( "\tLocation:\"" + inputPort.location() + "\"" ); System.out.println( "\tProtocol:" + inputPort.protocolId() ); System.out.println( "\tInterfaces:" + inputPort.id() + "Surface" ); System.out.println( "}" ); } }
package GHRestaurant.roles; import restaurant.Restaurant; import restaurant.interfaces.*; import GHRestaurant.gui.*; import java.util.*; import java.util.concurrent.Semaphore; import market.interfaces.DeliveryMan; import city.MarketAgent; import city.PersonAgent; import city.gui.Gui; import city.roles.Role; /** * Restaurant Cook Agent */ public class GHCookRole extends Role implements Cook { public List<Order> orders = Collections.synchronizedList(new ArrayList<Order>()); public List<MarketOrder> marketOrders = Collections.synchronizedList(new ArrayList<MarketOrder>()); static final int ORDERAMOUNT = 30; int nextmarket; private Timer timer = new Timer(); public enum OrderState {PENDING,COOKING,DONECOOKING} public enum marketOrderState {waiting, ordering,ordered,waitingForBill, paying}; //public String name; private GHCookGui cookgui = null; Map<String,Food> Inventory = new HashMap<String,Food>(); public List<MarketAgent> markets = new ArrayList<MarketAgent>(); private Semaphore atDestination = new Semaphore(0,true); private Restaurant restaurant; public GHCookRole(int amount) { super(); //this.name = name; nextmarket = 0; Inventory.put("steak", new Food("steak",5000)); Inventory.put("chicken", new Food("chicken",5000)); Inventory.put("salad", new Food("salad",amount)); Inventory.put("pizza", new Food("pizza",7000)); /*Inventory.get("Steak").setAmount(10); Inventory.get("Chicken").setAmount(10); Inventory.get("Salad").setAmount(10); Inventory.get("Pizza").setAmount(10);*/ } /*public String getName() { return name; }*/ public List<Order> getOrders() { return orders; } /* public void setMarket(MarketAgent ma){ markets.add(ma); }*/ // Messages public void msgAtTable(){//from animation atDestination.release(); stateChanged(); } public void msgHereIsAnOrder(Waiter waiter, String choice, int tablenumber){ print("Recieved msgHereIsAnOrder"); orders.add(new Order(waiter,choice,tablenumber,OrderState.PENDING)); stateChanged(); } public void msgFoodDone(Order o){ o.os = OrderState.DONECOOKING; stateChanged(); } public void msgDelivery(String choice, int amount){ print("Recieved order form market"); Inventory.get(choice).addFoodAmount(amount); stateChanged(); } public void msgOutOfOrder(){ print("Recieved msgOutOfOrder"); stateChanged(); } @Override public void msgCanIHelpYou(DeliveryMan DM, MarketAgent M) { for (MarketOrder order: marketOrders){ if(order.Market==M){ order.deliveryMan=DM; order.marketState=marketOrderState.ordering; } } stateChanged(); } /** * Scheduler. Determine what action is called for, and do it. */ public boolean pickAndExecuteAnAction() { synchronized(orders){ for (Order o : orders) { if (o.getState() == OrderState.PENDING) { CookIt(o);//the action return true;//return true to the abstract agent to reinvoke the scheduler. } } } synchronized(orders){ for (Order o : orders) { if (o.getState() == OrderState.DONECOOKING) { PlateIt(o);//the action return true;//return true to the abstract agent to reinvoke the scheduler. } } } for (MarketOrder mOrder : marketOrders) { if(mOrder.marketState == marketOrderState.paying) { SendInvoiceToCashier(mOrder); return true; } } for (MarketOrder mOrder : marketOrders) { if(mOrder.marketState == marketOrderState.ordering) { mOrder.marketState = marketOrderState.ordered; GiveOrderToDeliverMan(mOrder); return true; } } //cookgui.DoGoHome(); return false; //we have tried all our rules and found //nothing to do. So return false to main loop of abstract agent //and wait. } // Actions private void CookIt(final Order o){ //The cook has ran out of the order amount and the customer must reorder if(Inventory.get(o.choice).getAmount() <= 0){ print("Out of order! Please go back to customer and ask to reorder"); Order temp = o; orders.remove(o); ((GHWaiterRole) temp.waiter).msgOutOfOrder(temp.tablenumber, temp.choice); } else{ //if food is "low" then the cook orders from different market. if(Inventory.get(o.choice).getAmount() <= Inventory.get(o.choice).getThreshold()){ Map<String,Integer>foodToOrder=new HashMap<String,Integer>(); foodToOrder.put(o.choice, 20); marketOrders.add(new MarketOrder(foodToOrder, markets.get(nextmarket), marketOrderState.waiting)); markets.get(nextmarket).msgPlaceDeliveryOrder(this); nextmarket = (nextmarket+1)%markets.size(); } DoCookIt(o); try { atDestination.acquire(); } catch (InterruptedException e) { e.printStackTrace(); } o.os = OrderState.COOKING; Inventory.get(o.choice).decAmount(); timer.schedule(new TimerTask(){ public void run(){ msgFoodDone(o); } },Inventory.get(o.choice).cookingtime); } } private void GiveOrderToDeliverMan(MarketOrder mo) { mo.deliveryMan.msgHereIsOrder(mo.order); } private void DoCookIt(Order o){ print("cooking " + o.choice); cookgui.DoCookIt(); } private void PlateIt(Order o){ DoPlating(o); try { atDestination.acquire(); } catch (InterruptedException e) { e.printStackTrace(); } ((GHWaiterRole) o.waiter).msgOrderIsReady(o.choice, o.tablenumber); orders.remove(o); } private void DoPlating(Order o){ print(o.choice + " is ready!"); cookgui.DoPlateIt(); } private void SendInvoiceToCashier(MarketOrder mo) { ((GHCashierRole) restaurant.cashier).msgHereIsInvoice(mo.deliveryMan, mo.cost); } //utilities public void setGui(GHCookGui cg){ cookgui = cg; } public class Order { Waiter waiter; int tablenumber; String choice; OrderState os; Order(Waiter w, String c, int t, OrderState o){ waiter = w; choice = c; tablenumber = t; os = o; } public OrderState getState(){ return os; } } private class Food{ String foodtype; int cookingtime; int amount; int threshold; //int capacity; Food(String choice, int ct){ foodtype = choice; cookingtime = ct; amount = 20; threshold = 10; //capacity = 100; } public void decAmount(){ amount } public void addFoodAmount(int a){ amount += a; } public int getAmount(){ return amount; } public int getThreshold(){ return threshold; } public void setAmount(int a){ amount = a; } public String getFoodType(){ return foodtype; } } private class MarketOrder{ public MarketOrder(Map<String, Integer> food,MarketAgent m, marketOrderState mos) { order=food; Market=m; marketState=mos; } Map<String,Integer> order; marketOrderState marketState; DeliveryMan deliveryMan; MarketAgent Market; double cost; } @Override public void msgNeverOrderFromMarketAgain(MarketAgent market) { if(markets.size()==0){ for(MarketAgent ma: restaurant.insideAnimationPanel.simCityGui.getMarkets()){ this.addMarket(ma); } } else { for(MarketAgent ma : markets){ if(ma.equals(market)){ markets.remove(ma); } } } } @Override public void msgHereIsOrderFromMarket(DeliveryMan Dm, Map<String, Integer> choices, double cost) { for (MarketOrder order:marketOrders){ if(order.deliveryMan==Dm){ order.cost=cost; order.marketState=marketOrderState.paying; } } for(String s : choices.keySet()) { Food food = findFood(s); food.addFoodAmount(choices.get(s)); } } private Food findFood(String s) { Food food = null; for(String i : Inventory.keySet()){ if(i.equals(s)){ food = Inventory.get(i); } } return food; } @Override public void msgIncompleteOrder(DeliveryMan deliveryMan, List<String> outOf) { // TODO Auto-generated method stub } @Override public void msgRelieveFromDuty(PersonAgent p) { // TODO Auto-generated method stub } @Override public void goesToWork() { // TODO Auto-generated method stub } @Override public void addMarket(MarketAgent m) { markets.add(m); } @Override public void setGui(Gui g) { cookgui = (GHCookGui) g; } @Override public Gui getGui() { return cookgui; } public void setRestaurant(Restaurant r) { restaurant = r; } @Override public void msgMarketClosed(MarketAgent market) { // TODO Auto-generated method stub } }
package GHRestaurant.roles; import GHRestaurant.gui.GHHostGui; import restaurant.Restaurant; import restaurant.interfaces.*; import java.util.*; import java.util.concurrent.Semaphore; import city.PersonAgent; import city.gui.Gui; import city.roles.Role; /** * Restaurant Host Agent */ //We only have 2 types of agents in this prototype. A customer and an agent that //does all the rest. Rather than calling the other agent a waiter, we called him //the HostAgent. A Host is the manager of a restaurant who sees that all //is proceeded as he wishes. public class GHHostRole extends Role implements Host{ static final int NTABLES = 3;//a global for the number of tables. //Notice that we implement waitingCustomers using ArrayList, but type it //with List semantics. public List<Customer> waitingCustomers = Collections.synchronizedList(new ArrayList<Customer>()); public List<Waiter> waiters = Collections.synchronizedList(new ArrayList<Waiter>()); public Collection<Table> tables; //note that tables is typed with Collection semantics. //Later we will see how it is implemented private int nextwaiter = 0; private Restaurant restaurant; //private String name; private Semaphore atDestination = new Semaphore(0,true); public GHHostGui hostGui = null; public GHHostRole() { super(); //this.name = name; // make some tables tables = new ArrayList<Table>(NTABLES); for (int ix = 1; ix <= NTABLES; ix++) { tables.add(new Table(ix));//how you add to a collections } } /*public String getMaitreDName() { return name; } public String getName() { return name; }*/ public List getWaitingCustomers() { return waitingCustomers; } public Collection getTables() { return tables; } // Messages public void msgIWantFood(Customer cust) { waitingCustomers.add(cust); print("msgIWantFood"); stateChanged(); } public void msgSetWaiter(Waiter wait){ waiters.add(wait); print("msgGoingToWork"); stateChanged(); } public void msgLeavingTable(Customer cust) { for (Table table : tables) { if (table.getOccupant() == cust) { print("customer leaving " + table); table.setUnoccupied(); stateChanged(); } } } public void msgCanIGoOnBreak(Waiter w){ print("Recieved msgCanIGoOnBreak"); if(waiters.size() > 1){ ((GHWaiterRole) w).setWantToGoOnBreak(false); ((GHWaiterRole) w).setOnBreak(true); waiters.remove(w); nextwaiter = (nextwaiter+1)%waiters.size(); } else{ print("Cannot give break go back to work please"); ((GHWaiterRole) w).setWantToGoOnBreak(false); } stateChanged(); } public void msgAtTable() {//from animation //print("msgAtTable() called"); atDestination.release();// = true; stateChanged(); } /** * Scheduler. Determine what action is called for, and do it. */ public boolean pickAndExecuteAnAction() { /* Think of this next rule as: Does there exist a table and customer, so that table is unoccupied and customer is waiting. If so seat him at the table. */ if(!waitingCustomers.isEmpty() && !waiters.isEmpty()){ for(Table table: tables){ if(!table.isOccupied()){ seatCustomer(waitingCustomers.get(0),table); return true; } } } return false; //we have tried all our rules and found //nothing to do. So return false to main loop of abstract agent //and wait. } // Actions private void seatCustomer(Customer customer, Table table) { ((GHWaiterRole) waiters.get(nextwaiter)).msgSitAtTable(customer, table.tableNumber); table.setOccupant(customer); waitingCustomers.remove(customer); nextwaiter = (nextwaiter+1)%waiters.size(); } //utilities public void setGui(GHHostGui gui) { hostGui = gui; } public GHHostGui getGui() { return hostGui; } private class Table { Customer occupiedBy; int tableNumber; Table(int tableNumber) { this.tableNumber = tableNumber; } void setOccupant(Customer cust) { occupiedBy = cust; } void setUnoccupied() { occupiedBy = null; } Customer getOccupant() { return occupiedBy; } boolean isOccupied() { return occupiedBy != null; } public String toString() { return "table " + tableNumber; } } @Override public void msgReleaveFromDuty(PersonAgent p) { // TODO Auto-generated method stub } @Override public void msgReadyToWork(Waiter w) { // TODO Auto-generated method stub } @Override public void msgIWantToEat(Customer c) { // TODO Auto-generated method stub } @Override public void msgLeavingRestaurant(Customer c) { // TODO Auto-generated method stub } @Override public void msgCanIBreak(Waiter w) { // TODO Auto-generated method stub } @Override public void msgDoneWorking(Waiter w) { // TODO Auto-generated method stub } @Override public void goesToWork() { // TODO Auto-generated method stub } @Override public void setGui(Gui g) { hostGui = (GHHostGui) g; } public void setRestaurant(Restaurant r) { restaurant = r; } @Override public void msgCloseRestaurant() { // TODO Auto-generated method stub } }
package ucar.nc2.ui; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import thredds.featurecollection.FeatureCollectionConfig; import thredds.inventory.bdb.MetadataManager; import ucar.httpservices.HTTPSession; import ucar.nc2.*; import ucar.nc2.constants.CDM; import ucar.nc2.constants.FeatureType; import ucar.nc2.dataset.CoordSysBuilder; import ucar.nc2.dataset.NetcdfDataset; import ucar.nc2.dataset.NetcdfDatasetInfo; import ucar.nc2.dataset.VariableEnhanced; import ucar.nc2.dt.GridDataset; import ucar.nc2.dt.GridDatatype; import ucar.nc2.dt.RadialDatasetSweep; import ucar.nc2.ft.FeatureDataset; import ucar.nc2.ft.FeatureDatasetFactoryManager; import ucar.nc2.ft.FeatureDatasetPoint; import ucar.nc2.ft.grid.CoverageDataset; import ucar.nc2.ft.point.PointDatasetImpl; import ucar.nc2.geotiff.GeoTiff; import ucar.nc2.grib.GribData; import ucar.nc2.grib.collection.GribCollection; import ucar.nc2.grib.grib1.tables.Grib1ParamTables; import ucar.nc2.grib.grib2.table.WmoCodeTable; import ucar.nc2.grib.grib2.table.WmoTemplateTable; import ucar.nc2.iosp.bufr.tables.BufrTables; import ucar.nc2.jni.netcdf.Nc4Iosp; import ucar.nc2.ncml.Aggregation; import ucar.nc2.stream.CdmRemote; import ucar.nc2.thredds.ThreddsDataFactory; import ucar.nc2.time.CalendarDate; import ucar.nc2.time.CalendarDateUnit; import ucar.nc2.ui.coverage.CoverageDisplay; import ucar.nc2.ui.coverage.CoverageTable; import ucar.nc2.ui.dialog.DiskCache2Form; import ucar.nc2.ui.gis.shapefile.ShapeFileBean; import ucar.nc2.ui.gis.worldmap.WorldMapBean; import ucar.nc2.ui.grib.*; import ucar.nc2.ui.grid.GeoGridTable; import ucar.nc2.ui.grid.GridUI; import ucar.nc2.ui.image.ImageViewPanel; import ucar.nc2.ui.util.Resource; import ucar.nc2.ui.util.SocketMessage; import ucar.nc2.ui.widget.*; import ucar.nc2.ui.widget.ProgressMonitor; import ucar.nc2.units.*; import ucar.nc2.util.CancelTask; import ucar.nc2.util.DebugFlags; import ucar.nc2.util.DiskCache2; import ucar.nc2.util.IO; import ucar.nc2.util.cache.FileCache; import ucar.nc2.util.xml.RuntimeConfigParser; import ucar.util.prefs.PreferencesExt; import ucar.util.prefs.XMLStore; import ucar.util.prefs.ui.ComboBox; import ucar.util.prefs.ui.Debug; import javax.swing.*; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.MenuEvent; import javax.swing.event.MenuListener; import java.awt.*; import java.awt.event.*; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.*; import java.nio.file.Paths; import java.util.*; import java.util.List; /** * Netcdf Tools user interface. * * @author caron */ public class ToolsUI extends JPanel { static private org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(ToolsUI.class); static private final String WorldDetailMap = "/resources/nj22/ui/maps/Countries.zip"; static private final String USMap = "/resources/nj22/ui/maps/US.zip"; static private final String FRAME_SIZE = "FrameSize"; static private final String GRIDVIEW_FRAME_SIZE = "GridUIWindowSize"; static private final String GRIDIMAGE_FRAME_SIZE = "GridImageWindowSize"; static private boolean debugListen = false; private PreferencesExt mainPrefs; private AggPanel aggPanel; private BufrPanel bufrPanel; private BufrTableBPanel bufrTableBPanel; private BufrTableDPanel bufrTableDPanel; private ReportOpPanel bufrReportPanel; private BufrCdmIndexPanel bufrCdmIndexPanel; private BufrCodePanel bufrCodePanel; private CdmrFeature cdmremotePanel; private CdmIndex2Panel cdmIndex2Panel; private ReportOpPanel cdmIndexReportPanel; private CollectionSpecPanel fcPanel; private CoordSysPanel coordSysPanel; private CoveragePanel coveragePanel; private DatasetViewerPanel viewerPanel; private DatasetViewerPanel nc4viewer; private DatasetWriterPanel writerPanel; private DirectoryPartitionPanel dirPartPanel; private FeatureScanPanel ftPanel; private FmrcPanel fmrcPanel; private FmrcCollectionPanel fmrcCollectionPanel; private GeoGridPanel gridPanel; private GeotiffPanel geotiffPanel; private GribCodePanel gribCodePanel; private GribFilesPanel gribFilesPanel; private GribIndexPanel gribIdxPanel; private GribRenamePanel gribVariableRenamePanel; private GribRewritePanel gribRewritePanel; private GribTemplatePanel gribTemplatePanel; private Grib1CollectionPanel grib1CollectionPanel; private ReportOpPanel grib1ReportPanel; private Grib1TablePanel grib1TablePanel; private Grib2CollectionPanel grib2CollectionPanel; private Grib2TablePanel grib2TablePanel; private ReportOpPanel grib2ReportPanel; private Grib1DataPanel grib1DataPanel; private Grib2DataPanel grib2DataPanel; private Hdf5ObjectPanel hdf5ObjectPanel; private Hdf5DataPanel hdf5DataPanel; private Hdf4Panel hdf4Panel; private ImagePanel imagePanel; private NcStreamPanel ncStreamPanel; private NCdumpPanel ncdumpPanel; private NcmlEditorPanel ncmlEditorPanel; private PointFeaturePanel pointFeaturePanel; private StationRadialPanel stationRadialPanel; private RadialPanel radialPanel; private ThreddsUI threddsUI; private UnitsPanel unitsPanel; private URLDumpPane urlPanel; private WmoCCPanel wmoCommonCodePanel; private WmsPanel wmsPanel; private JTabbedPane tabbedPane; private JTabbedPane iospTabPane, bufrTabPane, gribTabPane, grib2TabPane, grib1TabPane, hdf5TabPane; private JTabbedPane ftTabPane, fcTabPane; private JTabbedPane fmrcTabPane; private JTabbedPane ncmlTabPane; private JFrame parentFrame; private FileManager fileChooser; private AboutWindow aboutWindow = null; // data private ucar.nc2.thredds.ThreddsDataFactory threddsDataFactory = new ucar.nc2.thredds.ThreddsDataFactory(); private DateFormatter formatter = new DateFormatter(); private boolean setUseRecordStructure = false; // debugging private JMenu debugFlagMenu; private DebugFlags debugFlags; private boolean debug = false, debugTab = false, debugCB = false; public ToolsUI(PreferencesExt prefs, JFrame parentFrame) { this.mainPrefs = prefs; this.parentFrame = parentFrame; // FileChooser is shared javax.swing.filechooser.FileFilter[] filters = new javax.swing.filechooser.FileFilter[2]; filters[0] = new FileManager.HDF5ExtFilter(); filters[1] = new FileManager.NetcdfExtFilter(); fileChooser = new FileManager(parentFrame, null, filters, (PreferencesExt) prefs.node("FileManager")); // all the tabbed panes tabbedPane = new JTabbedPane(JTabbedPane.TOP); iospTabPane = new JTabbedPane(JTabbedPane.TOP); gribTabPane = new JTabbedPane(JTabbedPane.TOP); grib2TabPane = new JTabbedPane(JTabbedPane.TOP); grib1TabPane = new JTabbedPane(JTabbedPane.TOP); bufrTabPane = new JTabbedPane(JTabbedPane.TOP); ftTabPane = new JTabbedPane(JTabbedPane.TOP); fcTabPane = new JTabbedPane(JTabbedPane.TOP); fmrcTabPane = new JTabbedPane(JTabbedPane.TOP); hdf5TabPane = new JTabbedPane(JTabbedPane.TOP); ncmlTabPane = new JTabbedPane(JTabbedPane.TOP); // the widgets in the top level tabbed pane viewerPanel = new DatasetViewerPanel((PreferencesExt) mainPrefs.node("varTable"), false); tabbedPane.addTab("Viewer", viewerPanel); // all the other component are deferred construction for fast startup tabbedPane.addTab("Writer", new JLabel("Writer")); tabbedPane.addTab("NCDump", new JLabel("NCDump")); tabbedPane.addTab("Iosp", iospTabPane); tabbedPane.addTab("CoordSys", new JLabel("CoordSys")); tabbedPane.addTab("FeatureTypes", ftTabPane); tabbedPane.addTab("THREDDS", new JLabel("THREDDS")); tabbedPane.addTab("Fmrc", fmrcTabPane); tabbedPane.addTab("GeoTiff", new JLabel("GeoTiff")); tabbedPane.addTab("Units", new JLabel("Units")); tabbedPane.addTab("NcML", ncmlTabPane); tabbedPane.addTab("URLdump", new JLabel("URLdump")); tabbedPane.setSelectedIndex(0); tabbedPane.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { Component c = tabbedPane.getSelectedComponent(); if (c instanceof JLabel) { int idx = tabbedPane.getSelectedIndex(); String title = tabbedPane.getTitleAt(idx); makeComponent(tabbedPane, title); } } }); setLayout(new BorderLayout()); add(tabbedPane, BorderLayout.CENTER); // nested tab - iosp iospTabPane.addTab("BUFR", bufrTabPane); iospTabPane.addTab("GRIB", gribTabPane); iospTabPane.addTab("GRIB2", grib2TabPane); iospTabPane.addTab("GRIB1", grib1TabPane); iospTabPane.addTab("HDF5", hdf5TabPane); iospTabPane.addTab("HDF4", new JLabel("HDF4")); iospTabPane.addTab("NcStream", new JLabel("NcStream")); iospTabPane.addTab("CdmrFeature", new JLabel("CdmrFeature")); addListeners(iospTabPane); // nested-2 tab - bufr bufrTabPane.addTab("BUFR", new JLabel("BUFR")); bufrTabPane.addTab("BufrCdmIndex", new JLabel("BufrCdmIndex")); bufrTabPane.addTab("BUFRTableB", new JLabel("BUFRTableB")); bufrTabPane.addTab("BUFRTableD", new JLabel("BUFRTableD")); bufrTabPane.addTab("BUFR-CODES", new JLabel("BUFR-CODES")); bufrTabPane.addTab("BufrReports", new JLabel("BufrReports")); addListeners(bufrTabPane); // nested-2 tab - grib //gribTabPane.addTab("CdmIndex", new JLabel("CdmIndex")); gribTabPane.addTab("CdmIndex2", new JLabel("CdmIndex2")); gribTabPane.addTab("CdmIndexReport", new JLabel("CdmIndexReport")); gribTabPane.addTab("GribIndex", new JLabel("GribIndex")); gribTabPane.addTab("WMO-COMMON", new JLabel("WMO-COMMON")); gribTabPane.addTab("WMO-CODES", new JLabel("WMO-CODES")); gribTabPane.addTab("WMO-TEMPLATES", new JLabel("WMO-TEMPLATES")); gribTabPane.addTab("GRIB-Rename", new JLabel("GRIB-Rename")); gribTabPane.addTab("GRIB-Rewrite", new JLabel("GRIB-Rewrite")); addListeners(gribTabPane); // nested-2 tab - grib-2 grib2TabPane.addTab("GRIB2collection", new JLabel("GRIB2collection")); grib2TabPane.addTab("GRIB2rectilyze", new JLabel("GRIB2rectilyze")); grib2TabPane.addTab("GRIB2-REPORT", new JLabel("GRIB2-REPORT")); grib2TabPane.addTab("GRIB2data", new JLabel("GRIB2data")); grib2TabPane.addTab("GRIB2-TABLES", new JLabel("GRIB2-TABLES")); addListeners(grib2TabPane); // nested-2 tab - grib-1 grib1TabPane.addTab("GRIB1collection", new JLabel("GRIB1collection")); grib1TabPane.addTab("GRIB-FILES", new JLabel("GRIB-FILES")); grib1TabPane.addTab("GRIB1-REPORT", new JLabel("GRIB1-REPORT")); grib1TabPane.addTab("GRIB1data", new JLabel("GRIB1data")); grib1TabPane.addTab("GRIB1-TABLES", new JLabel("GRIB1-TABLES")); addListeners(grib1TabPane); // nested-2 tab - hdf5 hdf5TabPane.addTab("HDF5-Objects", new JLabel("HDF5-Objects")); hdf5TabPane.addTab("HDF5-Data", new JLabel("HDF5-Data")); hdf5TabPane.addTab("Netcdf4-JNI", new JLabel("Netcdf4-JNI")); addListeners(hdf5TabPane); // nested tab - features ftTabPane.addTab("Grids", new JLabel("Grids")); ftTabPane.addTab("Coverages", new JLabel("Coverages")); ftTabPane.addTab("WMS", new JLabel("WMS")); ftTabPane.addTab("PointFeature", new JLabel("PointFeature")); ftTabPane.addTab("Images", new JLabel("Images")); ftTabPane.addTab("Radial", new JLabel("Radial")); ftTabPane.addTab("FeatureScan", new JLabel("FeatureScan")); ftTabPane.addTab("FeatureCollection", fcTabPane); addListeners(ftTabPane); // nested tab - feature collection fcTabPane.addTab("DirectoryPartition", new JLabel("DirectoryPartition")); // fcTabPane.addTab("PartitionReport", new JLabel("PartitionReport")); fcTabPane.addTab("CollectionSpec", new JLabel("CollectionSpec")); addListeners(fcTabPane); // nested tab - fmrc fmrcTabPane.addTab("Fmrc", new JLabel("Fmrc")); fmrcTabPane.addTab("Collections", new JLabel("Collections")); addListeners(fmrcTabPane); // nested tab - ncml ncmlTabPane.addTab("NcmlEditor", new JLabel("NcmlEditor")); ncmlTabPane.addTab("Aggregation", new JLabel("Aggregation")); addListeners(ncmlTabPane); // dynamic proxy for DebugFlags debugFlags = (DebugFlags) java.lang.reflect.Proxy.newProxyInstance(DebugFlags.class.getClassLoader(), new Class[]{DebugFlags.class}, new DebugProxyHandler()); makeMenuBar(); setDebugFlags(); } private void addListeners(final JTabbedPane tabPane ) { tabPane.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { Component c = tabPane.getSelectedComponent(); if (c instanceof JLabel) { int idx = tabPane.getSelectedIndex(); String title = tabPane.getTitleAt(idx); makeComponent(tabPane, title); } } }); tabPane.addComponentListener(new ComponentAdapter() { public void componentShown(ComponentEvent e) { Component c = tabPane.getSelectedComponent(); if (c instanceof JLabel) { int idx = tabPane.getSelectedIndex(); String title = tabPane.getTitleAt(idx); makeComponent(tabPane, title); } } }); } // deferred creation of components to minimize startup private void makeComponent(JTabbedPane parent, String title) { if (parent == null) parent = tabbedPane; // find the correct index int n = parent.getTabCount(); int idx; for (idx = 0; idx < n; idx++) { String cTitle = parent.getTitleAt(idx); if (cTitle.equals(title)) break; } if (idx >= n) { if (debugTab) System.out.println("Cant find " + title + " in " + parent); return; } Component c; switch (title) { case "Aggregation": aggPanel = new AggPanel((PreferencesExt) mainPrefs.node("NcMLAggregation")); c = aggPanel; break; case "BUFR": bufrPanel = new BufrPanel((PreferencesExt) mainPrefs.node("bufr")); c = bufrPanel; break; case "BUFRTableB": bufrTableBPanel = new BufrTableBPanel((PreferencesExt) mainPrefs.node("bufr2")); c = bufrTableBPanel; break; case "BUFRTableD": bufrTableDPanel = new BufrTableDPanel((PreferencesExt) mainPrefs.node("bufrD")); c = bufrTableDPanel; break; case "BufrReports": { PreferencesExt prefs = (PreferencesExt) mainPrefs.node("bufrReports"); ReportPanel rp = new BufrReportPanel(prefs); bufrReportPanel = new ReportOpPanel(prefs, rp); c = bufrReportPanel; break; } case "BUFR-CODES": bufrCodePanel = new BufrCodePanel((PreferencesExt) mainPrefs.node("bufr-codes")); c = bufrCodePanel; break; case "CdmrFeature": cdmremotePanel = new CdmrFeature((PreferencesExt) mainPrefs.node("CdmrFeature")); c = cdmremotePanel; break; case "CollectionSpec": fcPanel = new CollectionSpecPanel((PreferencesExt) mainPrefs.node("collSpec")); c = fcPanel; break; case "DirectoryPartition": dirPartPanel = new DirectoryPartitionPanel((PreferencesExt) mainPrefs.node("dirPartition")); c = dirPartPanel; break; case "NcStream": ncStreamPanel = new NcStreamPanel((PreferencesExt) mainPrefs.node("NcStream")); c = ncStreamPanel; break; case "GRIB1collection": grib1CollectionPanel = new Grib1CollectionPanel((PreferencesExt) mainPrefs.node("grib1raw")); c = grib1CollectionPanel; break; case "GRIB1data": grib1DataPanel = new Grib1DataPanel((PreferencesExt) mainPrefs.node("grib1Data")); c = grib1DataPanel; break; case "GRIB-FILES": gribFilesPanel = new GribFilesPanel((PreferencesExt) mainPrefs.node("gribFiles")); c = gribFilesPanel; break; case "GRIB2collection": grib2CollectionPanel = new Grib2CollectionPanel((PreferencesExt) mainPrefs.node("gribNew")); c = grib2CollectionPanel; break; case "GRIB2data": grib2DataPanel = new Grib2DataPanel((PreferencesExt) mainPrefs.node("grib2Data")); c = grib2DataPanel; break; case "BufrCdmIndex": bufrCdmIndexPanel = new BufrCdmIndexPanel((PreferencesExt) mainPrefs.node("bufrCdmIdx")); c = bufrCdmIndexPanel; /* } else if (title.equals("CdmIndex")) { gribCdmIndexPanel = new GribCdmIndexPanel((PreferencesExt) mainPrefs.node("cdmIdx")); c = gribCdmIndexPanel; */ break; case "CdmIndex2": cdmIndex2Panel = new CdmIndex2Panel((PreferencesExt) mainPrefs.node("cdmIdx2")); c = cdmIndex2Panel; break; case "CdmIndexReport": { PreferencesExt prefs = (PreferencesExt) mainPrefs.node("CdmIndexReport"); ReportPanel rp = new CdmIndexReportPanel(prefs); cdmIndexReportPanel = new ReportOpPanel(prefs, rp); c = cdmIndexReportPanel; break; } case "GribIndex": gribIdxPanel = new GribIndexPanel((PreferencesExt) mainPrefs.node("gribIdx")); c = gribIdxPanel; break; case "GRIB1-REPORT": { PreferencesExt prefs = (PreferencesExt) mainPrefs.node("grib1Report"); ReportPanel rp = new Grib1ReportPanel(prefs); grib1ReportPanel = new ReportOpPanel(prefs, rp); c = grib1ReportPanel; break; } case "GRIB2-REPORT": { PreferencesExt prefs = (PreferencesExt) mainPrefs.node("gribReport"); ReportPanel rp = new Grib2ReportPanel(prefs); grib2ReportPanel = new ReportOpPanel(prefs, rp); c = grib2ReportPanel; break; } case "WMO-COMMON": wmoCommonCodePanel = new WmoCCPanel((PreferencesExt) mainPrefs.node("wmo-common")); c = wmoCommonCodePanel; break; case "WMO-CODES": gribCodePanel = new GribCodePanel((PreferencesExt) mainPrefs.node("wmo-codes")); c = gribCodePanel; break; case "WMO-TEMPLATES": gribTemplatePanel = new GribTemplatePanel((PreferencesExt) mainPrefs.node("wmo-templates")); c = gribTemplatePanel; break; case "GRIB1-TABLES": grib1TablePanel = new Grib1TablePanel((PreferencesExt) mainPrefs.node("grib1-tables")); c = grib1TablePanel; break; case "GRIB2-TABLES": grib2TablePanel = new Grib2TablePanel((PreferencesExt) mainPrefs.node("grib2-tables")); c = grib2TablePanel; break; case "GRIB-Rename": gribVariableRenamePanel = new GribRenamePanel((PreferencesExt) mainPrefs.node("grib-rename")); c = gribVariableRenamePanel; break; case "GRIB-Rewrite": gribRewritePanel = new GribRewritePanel((PreferencesExt) mainPrefs.node("grib-rewrite")); c = gribRewritePanel; break; case "CoordSys": coordSysPanel = new CoordSysPanel((PreferencesExt) mainPrefs.node("CoordSys")); c = coordSysPanel; break; case "FeatureScan": ftPanel = new FeatureScanPanel((PreferencesExt) mainPrefs.node("ftPanel")); c = ftPanel; break; case "GeoTiff": geotiffPanel = new GeotiffPanel((PreferencesExt) mainPrefs.node("WCS")); c = geotiffPanel; break; case "Grids": gridPanel = new GeoGridPanel((PreferencesExt) mainPrefs.node("grid")); c = gridPanel; break; case "Coverages": coveragePanel = new CoveragePanel((PreferencesExt) mainPrefs.node("coverage")); c = coveragePanel; break; case "HDF5-Objects": hdf5ObjectPanel = new Hdf5ObjectPanel((PreferencesExt) mainPrefs.node("hdf5")); c = hdf5ObjectPanel; break; case "HDF5-Data": hdf5DataPanel = new Hdf5DataPanel((PreferencesExt) mainPrefs.node("hdf5data")); c = hdf5DataPanel; break; case "Netcdf4-JNI": nc4viewer = new DatasetViewerPanel((PreferencesExt) mainPrefs.node("nc4viewer"), true); c = nc4viewer; break; case "HDF4": hdf4Panel = new Hdf4Panel((PreferencesExt) mainPrefs.node("hdf4")); c = hdf4Panel; break; case "Images": imagePanel = new ImagePanel((PreferencesExt) mainPrefs.node("images")); c = imagePanel; break; case "Fmrc": fmrcPanel = new FmrcPanel((PreferencesExt) mainPrefs.node("fmrc2")); c = fmrcPanel; break; case "Collections": fmrcCollectionPanel = new FmrcCollectionPanel((PreferencesExt) mainPrefs.node("collections")); c = fmrcCollectionPanel; break; case "NCDump": ncdumpPanel = new NCdumpPanel((PreferencesExt) mainPrefs.node("NCDump")); c = ncdumpPanel; break; case "NcmlEditor": ncmlEditorPanel = new NcmlEditorPanel((PreferencesExt) mainPrefs.node("NcmlEditor")); c = ncmlEditorPanel; break; case "PointFeature": pointFeaturePanel = new PointFeaturePanel((PreferencesExt) mainPrefs.node("pointFeature")); c = pointFeaturePanel; break; case "Radial": radialPanel = new RadialPanel((PreferencesExt) mainPrefs.node("radial")); c = radialPanel; break; case "StationRadial": stationRadialPanel = new StationRadialPanel((PreferencesExt) mainPrefs.node("stationRadar")); c = stationRadialPanel; break; case "THREDDS": threddsUI = new ThreddsUI(ToolsUI.this.parentFrame, (PreferencesExt) mainPrefs.node("thredds")); threddsUI.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent e) { if (e.getPropertyName().equals("InvAccess")) { thredds.catalog.InvAccess access = (thredds.catalog.InvAccess) e.getNewValue(); jumptoThreddsDatatype(access); } if (e.getPropertyName().equals("Dataset") || e.getPropertyName().equals("CoordSys") || e.getPropertyName().equals("File")) { thredds.catalog.InvDataset ds = (thredds.catalog.InvDataset) e.getNewValue(); setThreddsDatatype(ds, e.getPropertyName()); } } }); c = threddsUI; break; case "Units": unitsPanel = new UnitsPanel((PreferencesExt) mainPrefs.node("units")); c = unitsPanel; break; case "URLdump": urlPanel = new URLDumpPane((PreferencesExt) mainPrefs.node("urlDump")); c = urlPanel; break; case "Viewer": c = viewerPanel; break; case "Writer": writerPanel = new DatasetWriterPanel((PreferencesExt) mainPrefs.node("writer")); c = writerPanel; break; case "WMS": wmsPanel = new WmsPanel((PreferencesExt) mainPrefs.node("wms")); c = wmsPanel; break; default: System.out.println("tabbedPane unknown component " + title); return; } parent.setComponentAt(idx, c); if (debugTab) System.out.println("tabbedPane changed " + title + " added "); } private void makeMenuBar() { JMenuBar mb = new JMenuBar(); JRootPane rootPane = parentFrame.getRootPane(); rootPane.setJMenuBar(mb); /// System menu JMenu sysMenu = new JMenu("System"); sysMenu.setMnemonic('S'); mb.add(sysMenu); //BAMutil.addActionToMenu( sysMenu, printAction); AbstractAction act = new AbstractAction() { public void actionPerformed(ActionEvent e) { MetadataManager.closeAll(); // shutdown bdb } }; BAMutil.setActionProperties(act, null, "Close BDB database", false, 'S', -1); BAMutil.addActionToMenu(sysMenu, act); AbstractAction clearHttpStateAction = new AbstractAction() { public void actionPerformed(ActionEvent e) { // IGNORE HttpClientManager.clearState(); } }; BAMutil.setActionProperties(clearHttpStateAction, null, "Clear Http State", false, 'S', -1); BAMutil.addActionToMenu(sysMenu, clearHttpStateAction); AbstractAction showCacheAction = new AbstractAction() { public void actionPerformed(ActionEvent e) { Formatter f = new Formatter(); f.format("NetcdfFileCache contents%n"); ucar.nc2.util.cache.FileCacheIF cache = NetcdfDataset.getNetcdfFileCache(); if (null != cache) cache.showCache(f); viewerPanel.detailTA.setText(f.toString()); viewerPanel.detailWindow.show(); } }; BAMutil.setActionProperties(showCacheAction, null, "Show Caches", false, 'S', -1); BAMutil.addActionToMenu(sysMenu, showCacheAction); AbstractAction clearCacheAction = new AbstractAction() { public void actionPerformed(ActionEvent e) { ucar.nc2.util.cache.FileCacheIF cache = NetcdfDataset.getNetcdfFileCache(); if (cache != null) cache.clearCache(true); } }; BAMutil.setActionProperties(clearCacheAction, null, "Clear NetcdfDatasetCache", false, 'C', -1); BAMutil.addActionToMenu(sysMenu, clearCacheAction); AbstractAction enableCache = new AbstractAction() { public void actionPerformed(ActionEvent e) { Boolean state = (Boolean) getValue(BAMutil.STATE); if (state == isCacheInit) return; isCacheInit = state; if (isCacheInit) { ucar.nc2.util.cache.FileCacheIF cache = NetcdfDataset.getNetcdfFileCache(); if (cache != null) cache.enable(); else NetcdfDataset.initNetcdfFileCache(10, 20, 10 * 60); } else { ucar.nc2.util.cache.FileCacheIF cache = NetcdfDataset.getNetcdfFileCache(); if (cache != null) cache.disable(); } } }; BAMutil.setActionPropertiesToggle(enableCache, null, "enable NetcdfDatasetCache", isCacheInit, 'N', -1); BAMutil.addActionToMenu(sysMenu, enableCache); AbstractAction showPropertiesAction = new AbstractAction() { public void actionPerformed(ActionEvent e) { viewerPanel.detailTA.setText("System Properties\n"); Properties sysp = System.getProperties(); java.util.Enumeration eprops = sysp.propertyNames(); ArrayList<String> list = Collections.list(eprops); Collections.sort(list); for (Object aList : list) { String name = (String) aList; String value = System.getProperty(name); viewerPanel.detailTA.appendLine(" " + name + " = " + value); } viewerPanel.detailWindow.show(); } }; BAMutil.setActionProperties(showPropertiesAction, null, "System Properties", false, 'P', -1); BAMutil.addActionToMenu(sysMenu, showPropertiesAction); /* AbstractAction enableDiskCache = new AbstractAction() { public void actionPerformed(ActionEvent e) { Boolean state = (Boolean) getValue(BAMutil.STATE); if (state == isDiskCacheInit) return; isDiskCacheInit = state; if (isDiskCacheInit) { ucar.nc2.util.cache.FileCache cache = NetcdfDataset.getNetcdfFileCache(); if (cache != null) cache.enable(); else NetcdfDataset.initNetcdfFileCache(10,20,10*60); } else { ucar.nc2.util.cache.FileCache cache = NetcdfDataset.getNetcdfFileCache(); if (cache != null) cache.disable(); } } }; BAMutil.setActionPropertiesToggle(enableDiskCache, null, "enable Aggregation DiskCache", isDiskCacheInit, 'N', -1); BAMutil.addActionToMenu(sysMenu, enableDiskCache); */ /* AbstractAction showLoggingAction = new AbstractAction() { public void actionPerformed(ActionEvent e) { viewerPanel.detailTA.setText("Logging Information\n"); static private org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(Level2VolumeScan.class); org.apache.commons.logging.LogFactory logf = org.apache.commons.logging.LogFactory.getFactory(); org.apache.commons.logging.Log log = logf.getInstance(this.getClass()); viewerPanel.detailTA.appendLine(" Log implementation class= " + log.getClass().getName()); viewerPanel.detailTA.appendLine(" Log Attributes= "); String[] atts = logf.getAttributeNames(); for (int i = 0; i < atts.length; i++) { viewerPanel.detailTA.appendLine(" " + atts[i]); } viewerPanel.detailWindow.show(); } }; BAMutil.setActionProperties(showLoggingAction, null, "Logging Information", false, 'L', -1); BAMutil.addActionToMenu(sysMenu, showLoggingAction); */ JMenu plafMenu = new JMenu("Look and Feel"); plafMenu.setMnemonic('L'); sysMenu.add(plafMenu); PLAF plaf = new PLAF(rootPane); plaf.addToMenu(plafMenu); AbstractAction exitAction = new AbstractAction() { public void actionPerformed(ActionEvent e) { exit(); } }; BAMutil.setActionProperties(exitAction, "Exit", "Exit", false, 'X', -1); BAMutil.addActionToMenu(sysMenu, exitAction); // Modes Menu JMenu modeMenu = new JMenu("Modes"); modeMenu.setMnemonic('M'); mb.add(modeMenu); makeModesMenu(modeMenu); // Debug Menu JMenu debugMenu = new JMenu("Debug"); debugMenu.setMnemonic('D'); mb.add(debugMenu); // the list of debug flags are in a pull-aside menu // they are dynamically discovered, and persisted debugFlagMenu = (JMenu) debugMenu.add(new JMenu("Debug Flags")); debugFlagMenu.addMenuListener(new MenuListener() { public void menuSelected(MenuEvent e) { setDebugFlags(); // let Debug know about the flag names ucar.util.prefs.ui.Debug.constructMenu(debugFlagMenu); // now construct the menu } public void menuDeselected(MenuEvent e) { setDebugFlags(); // transfer menu values } public void menuCanceled(MenuEvent e) { } }); // this deletes all the flags, then they start accumulating again AbstractAction clearDebugFlagsAction = new AbstractAction() { public void actionPerformed(ActionEvent e) { ucar.util.prefs.ui.Debug.removeAll(); } }; BAMutil.setActionProperties(clearDebugFlagsAction, null, "Delete All Debug Flags", false, 'C', -1); BAMutil.addActionToMenu(debugMenu, clearDebugFlagsAction); JMenu helpMenu = new JMenu("Help"); helpMenu.setMnemonic('H'); mb.add(helpMenu); // "about" this application AbstractAction aboutAction = new AbstractAction() { public void actionPerformed(ActionEvent evt) { if (aboutWindow == null) aboutWindow = new AboutWindow(); aboutWindow.setVisible(true); } }; BAMutil.setActionProperties(aboutAction, null, "About", false, 'A', 0); BAMutil.addActionToMenu(helpMenu, aboutAction); AbstractAction logoAction = new AbstractAction() { public void actionPerformed(ActionEvent evt) { new MySplashScreen(); /* final SplashScreen splash = SplashScreen.getSplashScreen(); if (splash == null) { System.out.println("SplashScreen.getSplashScreen() returned null"); return; } Graphics2D g = splash.createGraphics(); if (g == null) { System.out.println("g is null"); return; } Image image = Resource.getImage("/resources/nj22/ui/pix/ring2.jpg"); g.drawImage(image, null, null); */ } }; BAMutil.setActionProperties(logoAction, null, "Logo", false, 'L', 0); BAMutil.addActionToMenu(helpMenu, logoAction); } public void setDebugFlags() { if (debug) System.out.println("checkDebugFlags "); NetcdfFile.setDebugFlags(debugFlags); ucar.nc2.iosp.hdf5.H5iosp.setDebugFlags(debugFlags); ucar.nc2.ncml.NcMLReader.setDebugFlags(debugFlags); ucar.nc2.dods.DODSNetcdfFile.setDebugFlags(debugFlags); CdmRemote.setDebugFlags(debugFlags); Nc4Iosp.setDebugFlags(debugFlags); ucar.nc2.thredds.ThreddsDataFactory.setDebugFlags(debugFlags); ucar.nc2.FileWriter2.setDebugFlags(debugFlags); ucar.nc2.ft.point.standard.PointDatasetStandardFactory.setDebugFlags(debugFlags); ucar.nc2.grib.collection.GribIosp.setDebugFlags(debugFlags); } /*public void setDebugOutputStream(boolean b) { // System.out.println("setDebugOutputStream "+b); if (b) { if (debugOS == null) debugOS = new PrintStream(debugPane.getOutputStream()); NetcdfFile.setDebugOutputStream(debugOS); } else { NetcdfFile.setDebugOutputStream(System.out); } } */ private void makeModesMenu(JMenu modeMenu) { AbstractAction a; JMenu ncMenu = new JMenu("NetcdfFile"); modeMenu.add(ncMenu); a = new AbstractAction() { public void actionPerformed(ActionEvent e) { setUseRecordStructure = (Boolean) getValue(BAMutil.STATE); } }; BAMutil.setActionPropertiesToggle(a, null, "nc3UseRecords", setUseRecordStructure, 'V', -1); BAMutil.addActionToMenu(ncMenu, a); JMenu dsMenu = new JMenu("NetcdfDataset"); modeMenu.add(dsMenu); a = new AbstractAction() { public void actionPerformed(ActionEvent e) { Boolean state = (Boolean) getValue(BAMutil.STATE); CoordSysBuilder.setUseMaximalCoordSys(state); } }; BAMutil.setActionPropertiesToggle(a, null, "set Use Maximal CoordSystem", CoordSysBuilder.getUseMaximalCoordSys(), 'N', -1); BAMutil.addActionToMenu(dsMenu, a); a = new AbstractAction() { public void actionPerformed(ActionEvent e) { Boolean state = (Boolean) getValue(BAMutil.STATE); NetcdfDataset.setUseNaNs(state); } }; BAMutil.setActionPropertiesToggle(a, null, "set NaNs for missing values", NetcdfDataset.getUseNaNs(), 'N', -1); BAMutil.addActionToMenu(dsMenu, a); a = new AbstractAction() { public void actionPerformed(ActionEvent e) { Boolean state = (Boolean) getValue(BAMutil.STATE); NetcdfDataset.setFillValueIsMissing(state); } }; BAMutil.setActionPropertiesToggle(a, null, "use _FillValue attribute for missing values", NetcdfDataset.getFillValueIsMissing(), 'F', -1); BAMutil.addActionToMenu(dsMenu, a); a = new AbstractAction() { public void actionPerformed(ActionEvent e) { Boolean state = (Boolean) getValue(BAMutil.STATE); NetcdfDataset.setInvalidDataIsMissing(state); } }; BAMutil.setActionPropertiesToggle(a, null, "use valid_range attribute for missing values", NetcdfDataset.getInvalidDataIsMissing(), 'V', -1); BAMutil.addActionToMenu(dsMenu, a); a = new AbstractAction() { public void actionPerformed(ActionEvent e) { Boolean state = (Boolean) getValue(BAMutil.STATE); NetcdfDataset.setMissingDataIsMissing(state); } }; BAMutil.setActionPropertiesToggle(a, null, "use missing_value attribute for missing values", NetcdfDataset.getMissingDataIsMissing(), 'M', -1); BAMutil.addActionToMenu(dsMenu, a); JMenu subMenu = new JMenu("GRIB"); modeMenu.add(subMenu); a = new AbstractAction() { public void actionPerformed(ActionEvent e) { setGribDiskCache(); } }; BAMutil.setActionProperties(a, null, "set Grib disk cache...", false, 'G', -1); BAMutil.addActionToMenu(subMenu, a); a = new AbstractAction() { public void actionPerformed(ActionEvent e) { Boolean state = (Boolean) getValue(BAMutil.STATE); Grib1ParamTables.setStrict(state); } }; boolean strictMode = Grib1ParamTables.isStrict(); a.putValue(BAMutil.STATE, strictMode); BAMutil.setActionPropertiesToggle(a, null, "GRIB1 strict", strictMode, 'S', -1); BAMutil.addActionToMenu(subMenu, a); a = new AbstractAction() { public void actionPerformed(ActionEvent e) { Boolean state = (Boolean) getValue(BAMutil.STATE); GribData.setInterpolationMethod( state ? GribData.InterpolationMethod.cubic : GribData.InterpolationMethod.linear); } }; boolean useCubic = GribData.getInterpolationMethod() == GribData.InterpolationMethod.cubic; a.putValue(BAMutil.STATE, useCubic); BAMutil.setActionPropertiesToggle(a, null, "Use Cubic Interpolation on Thin Grids", useCubic, 'I', -1); BAMutil.addActionToMenu(subMenu, a); subMenu = new JMenu("FMRC"); modeMenu.add(subMenu); a = new AbstractAction() { public void actionPerformed(ActionEvent e) { Boolean state = (Boolean) getValue(BAMutil.STATE); FeatureCollectionConfig.setRegularizeDefault(state); } }; // ToolsUI default is to regularize the FMRC FeatureCollectionConfig.setRegularizeDefault(true); a.putValue(BAMutil.STATE, true); BAMutil.setActionPropertiesToggle(a, null, "regularize", true, 'R', -1); BAMutil.addActionToMenu(subMenu, a); a = new AbstractAction() { public void actionPerformed(ActionEvent e) { Boolean state = (Boolean) getValue(BAMutil.STATE); ThreddsDataFactory.setPreferCdm(state); } }; // ToolsUI default is to use cdmRemote access ThreddsDataFactory.setPreferCdm(true); a.putValue(BAMutil.STATE, true); BAMutil.setActionPropertiesToggle(a, null, "preferCdm", true, 'P', -1); BAMutil.addActionToMenu(subMenu, a); } DiskCache2Form diskCache2Form = null; private void setGribDiskCache() { if (diskCache2Form == null) { diskCache2Form = new DiskCache2Form(parentFrame, GribCollection.getDiskCache2()); } diskCache2Form.setVisible(true); } public void save() { fileChooser.save(); if (aggPanel != null) aggPanel.save(); if (bufrFileChooser != null) bufrFileChooser.save(); if (bufrPanel != null) bufrPanel.save(); if (bufrTableBPanel != null) bufrTableBPanel.save(); if (bufrTableDPanel != null) bufrTableDPanel.save(); if (bufrReportPanel != null) bufrReportPanel.save(); if (bufrCodePanel != null) bufrCodePanel.save(); if (coordSysPanel != null) coordSysPanel.save(); if (coveragePanel != null) coveragePanel.save(); if (cdmIndex2Panel != null) cdmIndex2Panel.save(); if (cdmIndexReportPanel != null) cdmIndexReportPanel.save(); if (cdmremotePanel != null) cdmremotePanel.save(); if (dirPartPanel != null) dirPartPanel.save(); if (bufrCdmIndexPanel != null) bufrCdmIndexPanel.save(); //if (gribCdmIndexPanel != null) gribCdmIndexPanel.save(); if (fmrcCollectionPanel != null) fmrcCollectionPanel.save(); if (fcPanel != null) fcPanel.save(); if (ftPanel != null) ftPanel.save(); if (fmrcPanel != null) fmrcPanel.save(); if (geotiffPanel != null) geotiffPanel.save(); if (gribFilesPanel != null) gribFilesPanel.save(); if (grib2CollectionPanel != null) grib2CollectionPanel.save(); // if (grib2RectilyzePanel != null) grib2RectilyzePanel.save(); if (grib2DataPanel != null) grib2DataPanel.save(); if (grib1DataPanel != null) grib1DataPanel.save(); if (gribCodePanel != null) gribCodePanel.save(); if (gribIdxPanel != null) gribIdxPanel.save(); if (gribTemplatePanel != null) gribTemplatePanel.save(); if (grib1CollectionPanel != null) grib1CollectionPanel.save(); if (grib1ReportPanel != null) grib1ReportPanel.save(); if (grib2ReportPanel != null) grib2ReportPanel.save(); if (grib1TablePanel != null) grib1TablePanel.save(); if (grib2TablePanel != null) grib2TablePanel.save(); if (gribVariableRenamePanel != null) gribVariableRenamePanel.save(); if (gribRewritePanel != null) gribRewritePanel.save(); if (gridPanel != null) gridPanel.save(); if (hdf5ObjectPanel != null) hdf5ObjectPanel.save(); if (hdf5DataPanel != null) hdf5DataPanel.save(); if (hdf4Panel != null) hdf4Panel.save(); if (imagePanel != null) imagePanel.save(); if (ncdumpPanel != null) ncdumpPanel.save(); if (ncdumpPanel != null) ncdumpPanel.save(); if (nc4viewer != null) nc4viewer.save(); if (ncmlEditorPanel != null) ncmlEditorPanel.save(); if (pointFeaturePanel != null) pointFeaturePanel.save(); //if (pointObsPanel != null) pointObsPanel.save(); if (radialPanel != null) radialPanel.save(); // if (stationObsPanel != null) stationObsPanel.save(); if (stationRadialPanel != null) stationRadialPanel.save(); // if (trajTablePanel != null) trajTablePanel.save(); if (threddsUI != null) threddsUI.storePersistentData(); if (unitsPanel != null) unitsPanel.save(); if (urlPanel != null) urlPanel.save(); if (viewerPanel != null) viewerPanel.save(); if (writerPanel != null) writerPanel.save(); if (wmoCommonCodePanel != null) wmoCommonCodePanel.save(); if (wmsPanel != null) wmsPanel.save(); } private void openNetcdfFile(String datasetName) { makeComponent(tabbedPane, "Viewer"); viewerPanel.doit(datasetName); tabbedPane.setSelectedComponent(viewerPanel); } private void openNetcdfFile(NetcdfFile ncfile) { makeComponent(tabbedPane, "Viewer"); viewerPanel.setDataset(ncfile); tabbedPane.setSelectedComponent(viewerPanel); } private void openCoordSystems(String datasetName) { makeComponent(tabbedPane, "CoordSys"); coordSysPanel.doit(datasetName); tabbedPane.setSelectedComponent(coordSysPanel); } private void openCoordSystems(NetcdfDataset dataset) { makeComponent(tabbedPane, "CoordSys"); coordSysPanel.setDataset(dataset); tabbedPane.setSelectedComponent(coordSysPanel); } private void openNcML(String datasetName) { makeComponent(ncmlTabPane, "NcmlEditor"); ncmlEditorPanel.doit(datasetName); tabbedPane.setSelectedComponent(ncmlTabPane); ncmlTabPane.setSelectedComponent(ncmlEditorPanel); } private void openPointFeatureDataset(String datasetName) { makeComponent(ftTabPane, "PointFeature"); pointFeaturePanel.setPointFeatureDataset(null, datasetName); tabbedPane.setSelectedComponent(ftTabPane); ftTabPane.setSelectedComponent(pointFeaturePanel); } private void openGrib1Collection(String collection) { makeComponent(grib1TabPane, "GRIB1collection"); // LOOK - does this aleays make component ? grib1CollectionPanel.setCollection(collection); tabbedPane.setSelectedComponent(iospTabPane); iospTabPane.setSelectedComponent(grib1TabPane); grib1TabPane.setSelectedComponent(grib1CollectionPanel); } private void openGrib2Collection(String collection) { makeComponent(grib2TabPane, "GRIB2collection"); grib2CollectionPanel.setCollection(collection); tabbedPane.setSelectedComponent(iospTabPane); iospTabPane.setSelectedComponent(grib2TabPane); grib2TabPane.setSelectedComponent(grib2CollectionPanel); } private void openGrib2Data(String datasetName) { makeComponent(grib2TabPane, "GRIB2data"); grib2DataPanel.doit(datasetName); tabbedPane.setSelectedComponent(iospTabPane); iospTabPane.setSelectedComponent(grib2TabPane); grib2TabPane.setSelectedComponent(grib2DataPanel); } private void openGrib1Data(String datasetName) { makeComponent(grib1TabPane, "GRIB1data"); grib1DataPanel.doit(datasetName); tabbedPane.setSelectedComponent(iospTabPane); iospTabPane.setSelectedComponent(grib1TabPane); grib1TabPane.setSelectedComponent(grib1DataPanel); } private void openGridDataset(String datasetName) { makeComponent(ftTabPane, "Grids"); gridPanel.doit(datasetName); tabbedPane.setSelectedComponent(ftTabPane); ftTabPane.setSelectedComponent(gridPanel); } private void openCoverageDataset(String datasetName) { makeComponent(ftTabPane, "Coverages"); coveragePanel.doit(datasetName); tabbedPane.setSelectedComponent(ftTabPane); ftTabPane.setSelectedComponent(coveragePanel); } private void openGridDataset(NetcdfDataset dataset) { makeComponent(ftTabPane, "Grids"); gridPanel.setDataset(dataset); tabbedPane.setSelectedComponent(ftTabPane); ftTabPane.setSelectedComponent(gridPanel); } private void openGridDataset(GridDataset dataset) { makeComponent(ftTabPane, "Grids"); gridPanel.setDataset(dataset); tabbedPane.setSelectedComponent(ftTabPane); ftTabPane.setSelectedComponent(gridPanel); } private void openRadialDataset(String datasetName) { makeComponent(ftTabPane, "Radial"); radialPanel.doit(datasetName); tabbedPane.setSelectedComponent(ftTabPane); ftTabPane.setSelectedComponent(radialPanel); } private void openWMSDataset(String datasetName) { makeComponent(ftTabPane, "WMS"); wmsPanel.doit(datasetName); tabbedPane.setSelectedComponent(ftTabPane); ftTabPane.setSelectedComponent(wmsPanel); } // jump to the appropriate tab based on datatype of InvDataset private void setThreddsDatatype(thredds.catalog.InvDataset invDataset, String wants) { if (invDataset == null) return; boolean wantsViewer = wants.equals("File"); boolean wantsCoordSys = wants.equals("CoordSys"); try { // just open as a NetcdfDataset if (wantsViewer) { openNetcdfFile(threddsDataFactory.openDataset(invDataset, true, null, null)); return; } if (wantsCoordSys) { NetcdfDataset ncd = threddsDataFactory.openDataset(invDataset, true, null, null); ncd.enhance(); // make sure its enhanced openCoordSystems(ncd); return; } // otherwise do the datatype thing ThreddsDataFactory.Result threddsData = threddsDataFactory.openFeatureDataset(invDataset, null); if (threddsData == null) { JOptionPane.showMessageDialog(null, "Unknown datatype"); return; } jumptoThreddsDatatype(threddsData); } catch (IOException ioe) { JOptionPane.showMessageDialog(null, "Error on setThreddsDatatype = " + ioe.getMessage()); ioe.printStackTrace(); } } // jump to the appropriate tab based on datatype of InvAccess private void jumptoThreddsDatatype(thredds.catalog.InvAccess invAccess) { if (invAccess == null) return; thredds.catalog.InvService s = invAccess.getService(); if (s.getServiceType() == thredds.catalog.ServiceType.HTTPServer) { downloadFile(invAccess.getStandardUrlName()); return; } if (s.getServiceType() == thredds.catalog.ServiceType.WMS) { openWMSDataset(invAccess.getStandardUrlName()); return; } thredds.catalog.InvDataset ds = invAccess.getDataset(); if (ds.getDataType() == null) { // if no feature type, just open as a NetcdfDataset try { openNetcdfFile(threddsDataFactory.openDataset(invAccess, true, null, null)); } catch (IOException ioe) { JOptionPane.showMessageDialog(null, "Error on setThreddsDatatype = " + ioe.getMessage()); } return; } try { ThreddsDataFactory.Result threddsData = threddsDataFactory.openFeatureDataset(invAccess, null); jumptoThreddsDatatype(threddsData); } catch (IOException ioe) { ioe.printStackTrace(); JOptionPane.showMessageDialog(null, "Error on setThreddsDatatype = " + ioe.getMessage()); } } // jump to the appropriate tab based on datatype of threddsData private void jumptoThreddsDatatype(ThreddsDataFactory.Result threddsData) { if (threddsData.fatalError) { JOptionPane.showMessageDialog(this, "Cant open dataset=" + threddsData.errLog); return; } if (threddsData.featureType == FeatureType.GRID) { makeComponent(ftTabPane, "Grids"); gridPanel.setDataset((NetcdfDataset) threddsData.featureDataset.getNetcdfFile()); tabbedPane.setSelectedComponent(ftTabPane); ftTabPane.setSelectedComponent(gridPanel); } else if (threddsData.featureType == FeatureType.IMAGE) { makeComponent(ftTabPane, "Images"); imagePanel.setImageLocation(threddsData.imageURL); tabbedPane.setSelectedComponent(ftTabPane); ftTabPane.setSelectedComponent(imagePanel); } else if (threddsData.featureType == FeatureType.RADIAL) { makeComponent(ftTabPane, "Radial"); radialPanel.setDataset((RadialDatasetSweep) threddsData.featureDataset); tabbedPane.setSelectedComponent(ftTabPane); ftTabPane.setSelectedComponent(radialPanel); } else if (threddsData.featureType.isPointFeatureType()) { makeComponent(ftTabPane, "PointFeature"); pointFeaturePanel.setPointFeatureDataset((PointDatasetImpl) threddsData.featureDataset); tabbedPane.setSelectedComponent(ftTabPane); ftTabPane.setSelectedComponent(pointFeaturePanel); } else if (threddsData.featureType == FeatureType.STATION_RADIAL) { makeComponent(ftTabPane, "StationRadial"); stationRadialPanel.setStationRadialDataset(threddsData.featureDataset); tabbedPane.setSelectedComponent(ftTabPane); ftTabPane.setSelectedComponent(stationRadialPanel); } } /* else if (dtype == thredds.catalog.DataType.STATION) { makeComponent("StationDataset"); stnTablePanel.setStationObsDataset( ds); tabbedPane.setSelectedComponent( stnTablePanel); return; } * else { makeComponent("Viewer"); viewerPanel.setDataset(ds); tabbedPane.setSelectedComponent(viewerPanel); return; } } */ private NetcdfFile openFile(String location, boolean addCoords, CancelTask task) { NetcdfFile ncfile = null; try { if (addCoords) ncfile = NetcdfDataset.acquireDataset(location, task); else ncfile = NetcdfDataset.acquireFile(location, task); if (ncfile == null) JOptionPane.showMessageDialog(null, "NetcdfDataset.open cant open " + location); else if (setUseRecordStructure) ncfile.sendIospMessage(NetcdfFile.IOSP_MESSAGE_ADD_RECORD_STRUCTURE); } catch (IOException ioe) { String message = ioe.getMessage(); if ((null == message) && (ioe instanceof EOFException)) message = "Premature End of File"; JOptionPane.showMessageDialog(null, "NetcdfDataset.open cant open " + location + "\n" + message); if (!(ioe instanceof FileNotFoundException)) ioe.printStackTrace(); ncfile = null; } catch (Exception e) { JOptionPane.showMessageDialog(null, "NetcdfDataset.open cant open " + location + "\n" + e.getMessage()); log.error("NetcdfDataset.open cant open " + location, e); e.printStackTrace(); try { if (ncfile != null) ncfile.close(); } catch (IOException ee) { System.out.printf("close failed%n"); } ncfile = null; } return ncfile; } private String downloadStatus = null; private void downloadFile(String urlString) { int pos = urlString.lastIndexOf('/'); String defFilename = (pos >= 0) ? urlString.substring(pos) : urlString; String fileOutName = fileChooser.chooseFilename(defFilename); if (fileOutName == null) return; String[] values = new String[2]; values[0] = fileOutName; values[1] = urlString; // put in background thread with a ProgressMonitor window GetDataRunnable runner = new GetDataRunnable() { public void run(Object o) { String[] values = (String[]) o; BufferedOutputStream out; try ( FileOutputStream fos = new FileOutputStream(values[0])) { out = new BufferedOutputStream(fos, 60000); IO.copyUrlB(values[1], out, 60000); downloadStatus = values[1] + " written to " + values[0]; } catch (IOException ioe) { downloadStatus = "Error opening " + values[0] + " and reading " + values[1] + "\n" + ioe.getMessage(); } } }; GetDataTask task = new GetDataTask(runner, urlString, values); ProgressMonitor pm = new ProgressMonitor(task); pm.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(null, e.getActionCommand() + "\n" + downloadStatus); downloadStatus = null; } }); pm.start(this, "Download", 30); } // the panel contents // abstract superclass // subclasses must implement process() private abstract class OpPanel extends JPanel { PreferencesExt prefs; ComboBox cb; JPanel buttPanel, topPanel; AbstractButton coordButt = null; StopButton stopButton; boolean addCoords, defer, busy; long lastEvent = -1; boolean eventOK = true; IndependentWindow detailWindow; TextHistoryPane detailTA; OpPanel(PreferencesExt prefs, String command) { this(prefs, command, true, true); } OpPanel(PreferencesExt prefs, String command, boolean addFileButton, boolean addCoordButton) { this(prefs, command, true, addFileButton, addCoordButton); } OpPanel(PreferencesExt prefs, String command, boolean addComboBox, boolean addFileButton, boolean addCoordButton) { this.prefs = prefs; buttPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 5, 0)); cb = new ComboBox(prefs); cb.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (debugCB) System.out.println(" doit " + cb.getSelectedItem() + " cmd=" + e.getActionCommand() + " when=" + e.getWhen() + " class=" + OpPanel.this.getClass().getName()); // eliminate multiple events from same selection if (eventOK) { // && (e.getWhen() > lastEvent + 10000)) { // not sure of units - must be nanosecs - ?? platform dependednt ?? doit(cb.getSelectedItem()); lastEvent = e.getWhen(); } } }); AbstractAction closeAction = new AbstractAction() { public void actionPerformed(ActionEvent e) { try { closeOpenFiles(); } catch (IOException e1) { System.out.printf("close failed"); } } }; BAMutil.setActionProperties(closeAction, "Close", "release files", false, 'L', -1); BAMutil.addActionToContainer(buttPanel, closeAction); if (addFileButton) { AbstractAction fileAction = new AbstractAction() { public void actionPerformed(ActionEvent e) { String filename = fileChooser.chooseFilename(); if (filename == null) return; cb.setSelectedItem(filename); } }; BAMutil.setActionProperties(fileAction, "FileChooser", "open Local dataset...", false, 'L', -1); BAMutil.addActionToContainer(buttPanel, fileAction); } if (addCoordButton) { AbstractAction coordAction = new AbstractAction() { public void actionPerformed(ActionEvent e) { addCoords = (Boolean) getValue(BAMutil.STATE); String tooltip = addCoords ? "add Coordinates is ON" : "add Coordinates is OFF"; coordButt.setToolTipText(tooltip); //doit( cb.getSelectedItem()); // called from cb action listener } }; addCoords = prefs.getBoolean("coordState", false); String tooltip2 = addCoords ? "add Coordinates is ON" : "add Coordinates is OFF"; BAMutil.setActionProperties(coordAction, "addCoords", tooltip2, true, 'C', -1); coordAction.putValue(BAMutil.STATE, Boolean.valueOf(addCoords)); coordButt = BAMutil.addActionToContainer(buttPanel, coordAction); } if (this instanceof GetDataRunnable) { stopButton = new StopButton("Stop"); buttPanel.add(stopButton); } topPanel = new JPanel(new BorderLayout()); if (addComboBox) { topPanel.add(new JLabel(command), BorderLayout.WEST); topPanel.add(cb, BorderLayout.CENTER); topPanel.add(buttPanel, BorderLayout.EAST); } else { topPanel.add(buttPanel, BorderLayout.EAST); } setLayout(new BorderLayout()); add(topPanel, BorderLayout.NORTH); detailTA = new TextHistoryPane(); detailTA.setFont(new Font("Monospaced", Font.PLAIN, 12)); detailWindow = new IndependentWindow("Details", BAMutil.getImage("netcdfUI"), new JScrollPane(detailTA)); Rectangle bounds = (Rectangle) prefs.getBean(FRAME_SIZE, new Rectangle(200, 50, 500, 700)); detailWindow.setBounds(bounds); } void doit(Object command) { if (busy) return; if (command == null) return; if (command instanceof String) command = ((String) command).trim(); if (debug) System.out.println(getClass().getName() + " process=" + command); busy = true; if (process(command)) { if (!defer) cb.addItem(command); } busy = false; } abstract boolean process(Object command); void closeOpenFiles() throws IOException { } void save() { cb.save(); if (coordButt != null) prefs.putBoolean("coordState", coordButt.getModel().isSelected()); if (detailWindow != null) prefs.putBeanObject(FRAME_SIZE, detailWindow.getBounds()); } void setSelectedItem(Object item) { eventOK = false; cb.addItem(item); eventOK = true; } } private class NCdumpPanel extends OpPanel implements GetDataRunnable { private GetDataTask task; NetcdfFile ncfile = null; String filename = null; String command = null; String result; TextHistoryPane ta; NCdumpPanel(PreferencesExt prefs) { super(prefs, "command:"); ta = new TextHistoryPane(true); add(ta, BorderLayout.CENTER); stopButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (task.isSuccess()) ta.setText(result); else ta.setText(task.errMsg); if (task.isCancel()) ta.appendLine("\n***Cancelled by User"); ta.gotoTop(); if (task.isSuccess() && !task.isCancel()) cb.setSelectedItem(filename); } }); } void closeOpenFiles() throws IOException { if (ncfile != null) ncfile.close(); ncfile = null; } boolean process(Object o) { int pos; String input = ((String) o).trim(); // deal with possibility of blanks in the filename if ((input.indexOf('"') == 0) && ((pos = input.indexOf('"', 1)) > 0)) { filename = input.substring(1, pos); command = input.substring(pos + 1); } else if ((input.indexOf('\'') == 0) && ((pos = input.indexOf('\'', 1)) > 0)) { filename = input.substring(1, pos); command = input.substring(pos + 1); } else { pos = input.indexOf(' '); if (pos > 0) { filename = input.substring(0, pos); command = input.substring(pos); } else { filename = input; command = null; } } task = new GetDataTask(this, filename, null); stopButton.startProgressMonitorTask(task); //defer = true; return true; } public void run(Object o) throws IOException { try { if (addCoords) ncfile = NetcdfDataset.openDataset(filename, true, null); else ncfile = NetcdfDataset.openFile(filename, null); StringWriter writer = new StringWriter(50000); NCdumpW.print(ncfile, command, writer, task); result = writer.toString(); } finally { try { if (ncfile != null) ncfile.close(); ncfile = null; } catch (IOException ioe) { System.out.printf("Error closing %n"); } } } // allow calling from outside void setNetcdfFile(NetcdfFile ncf) { this.ncfile = ncf; this.filename = ncf.getLocation(); GetDataRunnable runner = new GetDataRunnable() { public void run(Object o) throws IOException { StringWriter writer = new StringWriter(50000); NCdumpW.print(ncfile, command, writer, task); result = writer.toString(); } }; task = new GetDataTask(runner, filename, null); stopButton.startProgressMonitorTask(task); } } private class UnitsPanel extends JPanel { PreferencesExt prefs; JSplitPane split, split2; UnitDatasetCheck unitDataset; UnitConvert unitConvert; DateFormatMark dateFormatMark; UnitsPanel(PreferencesExt prefs) { super(); this.prefs = prefs; unitDataset = new UnitDatasetCheck((PreferencesExt) prefs.node("unitDataset")); unitConvert = new UnitConvert((PreferencesExt) prefs.node("unitConvert")); dateFormatMark = new DateFormatMark((PreferencesExt) prefs.node("dateFormatMark")); split2 = new JSplitPane(JSplitPane.VERTICAL_SPLIT, unitConvert, dateFormatMark); split2.setDividerLocation(prefs.getInt("splitPos2", 500)); split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, new JScrollPane(unitDataset), split2); split.setDividerLocation(prefs.getInt("splitPos", 500)); setLayout(new BorderLayout()); add(split, BorderLayout.CENTER); } void save() { prefs.putInt("splitPos", split.getDividerLocation()); prefs.putInt("splitPos2", split2.getDividerLocation()); unitConvert.save(); unitDataset.save(); } } private class UnitDatasetCheck extends OpPanel { TextHistoryPane ta; UnitDatasetCheck(PreferencesExt p) { super(p, "dataset:"); ta = new TextHistoryPane(true); add(ta, BorderLayout.CENTER); } boolean process(Object o) { String command = (String) o; boolean err = false; try (NetcdfFile ncfile = NetcdfDataset.openDataset(command, addCoords, null)) { ta.setText("Variables for " + command + ":"); for (Variable o1 : ncfile.getVariables()) { VariableEnhanced vs = (VariableEnhanced) o1; String units = vs.getUnitsString(); StringBuilder sb = new StringBuilder(); sb.append(" ").append(vs.getShortName()).append(" has unit= <").append(units).append(">"); if (units != null) { try { SimpleUnit su = SimpleUnit.factoryWithExceptions(units); sb.append(" unit convert = ").append(su.toString()); if (su.isUnknownUnit()) sb.append(" UNKNOWN UNIT"); } catch (Exception ioe) { sb.append(" unit convert failed "); sb.insert(0, "**** Fail "); } } ta.appendLine(sb.toString()); } } catch (FileNotFoundException ioe) { ta.setText("Failed to open <" + command + ">"); err = true; } catch (IOException ioe) { ioe.printStackTrace(); err = true; } return !err; } void closeOpenFiles() throws IOException { ta.clear(); } } private class UnitConvert extends OpPanel { TextHistoryPane ta; UnitConvert(PreferencesExt prefs) { super(prefs, "unit:", false, false); ta = new TextHistoryPane(true); add(ta, BorderLayout.CENTER); JButton compareButton = new JButton("Compare"); compareButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { compare(cb.getSelectedItem()); } }); buttPanel.add(compareButton); JButton dateButton = new JButton("UdunitDate"); dateButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { checkUdunits(cb.getSelectedItem()); } }); buttPanel.add(dateButton); JButton cdateButton = new JButton("CalendarDate"); cdateButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { checkCalendarDate(cb.getSelectedItem()); } }); buttPanel.add(cdateButton); } boolean process(Object o) { String command = (String) o; try { SimpleUnit su = SimpleUnit.factoryWithExceptions(command); ta.setText("parse=" + command + "\n"); ta.appendLine("SimpleUnit.toString() =" + su.toString() + "\n"); ta.appendLine("SimpleUnit.getCanonicalString =" + su.getCanonicalString()); ta.appendLine("SimpleUnit.getImplementingClass= " + su.getImplementingClass()); ta.appendLine("SimpleUnit.isUnknownUnit = " + su.isUnknownUnit()); return true; } catch (Exception e) { if (Debug.isSet("Xdeveloper")) { StringWriter sw = new StringWriter(10000); e.printStackTrace(new PrintWriter(sw)); ta.setText(sw.toString()); } else { ta.setText(e.getClass().getName() + ":" + e.getMessage() + "\n" + command); } return false; } } void closeOpenFiles() { } void compare(Object o) { String command = (String) o; StringTokenizer stoke = new StringTokenizer(command); List<String> list = new ArrayList<>(); while (stoke.hasMoreTokens()) list.add(stoke.nextToken()); try { String unitS1 = list.get(0); String unitS2 = list.get(1); SimpleUnit su1 = SimpleUnit.factoryWithExceptions(unitS1); SimpleUnit su2 = SimpleUnit.factoryWithExceptions(unitS2); ta.setText("<" + su1.toString() + "> isConvertable to <" + su2.toString() + ">=" + SimpleUnit.isCompatibleWithExceptions(unitS1, unitS2)); } catch (Exception e) { if (Debug.isSet("Xdeveloper")) { StringWriter sw = new StringWriter(10000); e.printStackTrace(new PrintWriter(sw)); ta.setText(sw.toString()); } else { ta.setText(e.getClass().getName() + ":" + e.getMessage() + "\n" + command); } } } void checkUdunits(Object o) { String command = (String) o; boolean isDate = false; try { DateUnit du = new DateUnit(command); ta.appendLine("\nFrom udunits:\n <" + command + "> isDateUnit = " + du); Date d = du.getDate(); ta.appendLine("getStandardDateString = " + formatter.toDateTimeString(d)); ta.appendLine("getDateOrigin = " + formatter.toDateTimeString(du.getDateOrigin())); isDate = true; Date d2 = DateUnit.getStandardOrISO(command); if (d2 == null) ta.appendLine("\nDateUnit.getStandardOrISO = false"); else ta.appendLine("\nDateUnit.getStandardOrISO = " + formatter.toDateTimeString(d2)); } catch (Exception e) { // ok to fall through } ta.appendLine("isDate = " + isDate); if (!isDate) { try { SimpleUnit su = SimpleUnit.factory(command); boolean isTime = su instanceof TimeUnit; ta.setText("<" + command + "> isTimeUnit= " + isTime); if (isTime) { TimeUnit du = (TimeUnit) su; ta.appendLine("\nTimeUnit = " + du); } } catch (Exception e) { if (Debug.isSet("Xdeveloper")) { StringWriter sw = new StringWriter(10000); e.printStackTrace(new PrintWriter(sw)); ta.setText(sw.toString()); } else { ta.setText(e.getClass().getName() + ":" + e.getMessage() + "\n" + command); } } } } void checkCalendarDate(Object o) { String command = (String) o; try { ta.setText("\nParse CalendarDate: <" + command + ">\n"); CalendarDate cd = CalendarDate.parseUdunits(null, command); ta.appendLine("CalendarDate = " + cd); } catch (Throwable t) { ta.appendLine("not a CalendarDateUnit= " + t.getMessage()); } try { /* int pos = command.indexOf(' '); if (pos < 0) return; String valString = command.substring(0, pos).trim(); String unitString = command.substring(pos+1).trim(); */ ta.appendLine("\nParse CalendarDateUnit: <" + command + ">\n"); CalendarDateUnit cdu = CalendarDateUnit.of(null, command); ta.appendLine("CalendarDateUnit = " + cdu); ta.appendLine(" Calendar = " + cdu.getCalendar()); ta.appendLine(" PeriodField = " + cdu.getTimeUnit().getField()); ta.appendLine(" PeriodValue = " + cdu.getTimeUnit().getValue()); ta.appendLine(" Base = " + cdu.getBaseCalendarDate()); ta.appendLine(" isCalendarField = " + cdu.isCalendarField()); } catch (Exception e) { ta.appendLine("not a CalendarDateUnit= " + e.getMessage()); try { String[] s = command.split("%"); if (s.length == 2) { Double val = Double.parseDouble(s[0].trim()); ta.appendLine("\nval= " + val + " unit=" + s[1]); CalendarDateUnit cdu = CalendarDateUnit.of(null, s[1].trim()); ta.appendLine("CalendarDateUnit= " + cdu); CalendarDate cd = cdu.makeCalendarDate(val); ta.appendLine(" CalendarDate = " + cd); Date d = cd.toDate(); ta.appendLine(" Date.toString() = " + d); DateFormatter format = new DateFormatter(); ta.appendLine(" DateFormatter= " + format.toDateTimeString(cd.toDate())); } } catch (Exception ee) { ta.appendLine("Failed on CalendarDateUnit " + ee.getMessage()); } } } } private class DateFormatMark extends OpPanel { ComboBox testCB; DateFormatter dateFormatter = new DateFormatter(); TextHistoryPane ta; DateFormatMark(PreferencesExt prefs) { super(prefs, "dateFormatMark:", false, false); ta = new TextHistoryPane(true); add(ta, BorderLayout.CENTER); testCB = new ComboBox(prefs); buttPanel.add(testCB); JButton compareButton = new JButton("Apply"); compareButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { apply(cb.getSelectedItem(), testCB.getSelectedItem()); } }); buttPanel.add(compareButton); } boolean process(Object o) { return false; } void closeOpenFiles() { } void apply(Object mark, Object testo) { String dateFormatMark = (String) mark; String filename = (String) testo; try { Date coordValueDate = DateFromString.getDateUsingDemarkatedCount(filename, dateFormatMark, ' String coordValue = dateFormatter.toDateTimeStringISO(coordValueDate); ta.setText("got date= " + coordValue); } catch (Exception e) { StringWriter sw = new StringWriter(5000); e.printStackTrace(new PrintWriter(sw)); ta.setText(sw.toString()); } } } private class CoordSysPanel extends OpPanel { NetcdfDataset ds = null; CoordSysTable coordSysTable; void closeOpenFiles() throws IOException { if (ds != null) ds.close(); ds = null; coordSysTable.clear(); } CoordSysPanel(PreferencesExt p) { super(p, "dataset:", true, false); coordSysTable = new CoordSysTable(prefs, buttPanel); add(coordSysTable, BorderLayout.CENTER); AbstractButton infoButton = BAMutil.makeButtcon("Information", "Parse Info", false); infoButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (ds != null) { try (NetcdfDatasetInfo info = new NetcdfDatasetInfo( ds)) { detailTA.setText(info.writeXML()); detailTA.appendLine(" detailTA.appendLine(info.getParseInfo()); detailTA.gotoTop(); } catch (IOException e1) { StringWriter sw = new StringWriter(5000); e1.printStackTrace(new PrintWriter(sw)); detailTA.setText(sw.toString()); } detailWindow.show(); } } }); buttPanel.add(infoButton); JButton dsButton = new JButton("Object dump"); dsButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (ds != null) { StringWriter sw = new StringWriter(5000); NetcdfDataset.debugDump(new PrintWriter(sw), ds); detailTA.setText(sw.toString()); detailTA.gotoTop(); detailWindow.show(); } } }); buttPanel.add(dsButton); } boolean process(Object o) { String command = (String) o; boolean err = false; // close previous file try { if (ds != null) ds.close(); } catch (IOException ioe) { System.out.printf("close failed %n"); } Object spiObject = null; try { ds = NetcdfDataset.openDataset(command, true, -1, null, spiObject); if (ds == null) { JOptionPane.showMessageDialog(null, "Failed to open <" + command + ">"); } else { coordSysTable.setDataset(ds); } } catch (FileNotFoundException ioe) { JOptionPane.showMessageDialog(null, "NetcdfDataset cant open " + command + "\n" + ioe.getMessage()); err = true; } catch (Exception e) { StringWriter sw = new StringWriter(5000); e.printStackTrace(new PrintWriter(sw)); detailTA.setText(sw.toString()); detailWindow.show(); err = true; } return !err; } void setDataset(NetcdfDataset ncd) { try { if (ds != null) ds.close(); ds = null; } catch (IOException ioe) { System.out.printf("close failed %n"); } ds = ncd; coordSysTable.setDataset(ds); setSelectedItem(ds.getLocation()); } void save() { coordSysTable.save(); super.save(); } } private class AggPanel extends OpPanel { AggTable aggTable; NetcdfDataset ncd; void closeOpenFiles() throws IOException { if (ncd != null) ncd.close(); ncd = null; } AggPanel(PreferencesExt p) { super(p, "file:", true, false); aggTable = new AggTable(prefs, buttPanel); aggTable.addPropertyChangeListener(new java.beans.PropertyChangeListener() { public void propertyChange(java.beans.PropertyChangeEvent e) { if (e.getPropertyName().equals("openNetcdfFile")) { NetcdfFile ncfile = (NetcdfFile) e.getNewValue(); if (ncfile != null) openNetcdfFile(ncfile); } else if (e.getPropertyName().equals("openCoordSystems")) { NetcdfFile ncfile = (NetcdfFile) e.getNewValue(); if (ncfile == null) return; try { NetcdfDataset ncd = NetcdfDataset.wrap(ncfile, NetcdfDataset.getDefaultEnhanceMode()); openCoordSystems(ncd); } catch (IOException e1) { e1.printStackTrace(); } } else if (e.getPropertyName().equals("openGridDataset")) { NetcdfFile ncfile = (NetcdfFile) e.getNewValue(); if (ncfile == null) return; try { NetcdfDataset ncd = NetcdfDataset.wrap(ncfile, NetcdfDataset.getDefaultEnhanceMode()); openGridDataset(ncd); } catch (IOException e1) { e1.printStackTrace(); } } } }); add(aggTable, BorderLayout.CENTER); } boolean process(Object o) { String command = (String) o; boolean err = false; try { if (ncd != null) { try { ncd.close(); } catch (IOException ioe) { ioe.printStackTrace(); } } ncd = NetcdfDataset.openDataset(command); aggTable.setAggDataset(ncd); } catch (FileNotFoundException ioe) { JOptionPane.showMessageDialog(null, "NetcdfDataset cant open " + command + "\n" + ioe.getMessage()); err = true; } catch (Throwable e) { e.printStackTrace(); StringWriter sw = new StringWriter(5000); e.printStackTrace(new PrintWriter(sw)); detailTA.setText(sw.toString()); detailTA.gotoTop(); detailWindow.show(); err = true; } return !err; } void save() { aggTable.save(); super.save(); } } private class BufrPanel extends OpPanel { ucar.unidata.io.RandomAccessFile raf = null; BufrMessageViewer bufrTable; void closeOpenFiles() throws IOException { if (raf != null) raf.close(); raf = null; } BufrPanel(PreferencesExt p) { super(p, "file:", true, false); bufrTable = new BufrMessageViewer(prefs, buttPanel); add(bufrTable, BorderLayout.CENTER); } boolean process(Object o) { String command = (String) o; boolean err = false; try { if (raf != null) raf.close(); raf = new ucar.unidata.io.RandomAccessFile(command, "r"); bufrTable.setBufrFile(raf); } catch (FileNotFoundException ioe) { JOptionPane.showMessageDialog(null, "NetcdfDataset cant open " + command + "\n" + ioe.getMessage()); err = true; } catch (Exception e) { e.printStackTrace(); StringWriter sw = new StringWriter(5000); e.printStackTrace(new PrintWriter(sw)); detailTA.setText(sw.toString()); detailWindow.show(); err = true; } return !err; } void save() { bufrTable.save(); super.save(); } } private FileManager bufrFileChooser = null; private void initBufrFileChooser() { bufrFileChooser = new FileManager(parentFrame, null, null, (PreferencesExt) prefs.node("bufrFileManager")); } private class BufrTableBPanel extends OpPanel { BufrTableBViewer bufrTable; JComboBox<BufrTables.Format> modes; JComboBox<BufrTables.TableConfig> tables; BufrTableBPanel(PreferencesExt p) { super(p, "tableB:", false, false); AbstractAction fileAction = new AbstractAction() { public void actionPerformed(ActionEvent e) { if (bufrFileChooser == null) initBufrFileChooser(); String filename = bufrFileChooser.chooseFilename(); if (filename == null) return; cb.setSelectedItem(filename); } }; BAMutil.setActionProperties(fileAction, "FileChooser", "open Local table...", false, 'L', -1); BAMutil.addActionToContainer(buttPanel, fileAction); modes = new JComboBox<>(BufrTables.Format.values()); buttPanel.add(modes); JButton accept = new JButton("Accept"); buttPanel.add(accept); accept.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { accept(); } }); tables = new JComboBox<>(BufrTables.getTableConfigsAsArray()); buttPanel.add(tables); tables.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { acceptTable((BufrTables.TableConfig) tables.getSelectedItem()); } }); bufrTable = new BufrTableBViewer(prefs, buttPanel); add(bufrTable, BorderLayout.CENTER); } boolean process(Object command) { return true; } void closeOpenFiles() { } void accept() { String command = (String) cb.getSelectedItem(); try { Object format = modes.getSelectedItem(); bufrTable.setBufrTableB(command, (BufrTables.Format) format); } catch (FileNotFoundException ioe) { JOptionPane.showMessageDialog(null, "BufrTableViewer cant open " + command + "\n" + ioe.getMessage()); detailTA.setText("Failed to open <" + command + ">\n" + ioe.getMessage()); detailTA.setVisible(true); } catch (Exception e) { e.printStackTrace(); StringWriter sw = new StringWriter(5000); e.printStackTrace(new PrintWriter(sw)); detailTA.setText(sw.toString()); detailTA.setVisible(true); } } void acceptTable(BufrTables.TableConfig tc) { try { bufrTable.setBufrTableB(tc.getTableBname(), tc.getTableBformat()); } catch (FileNotFoundException ioe) { JOptionPane.showMessageDialog(null, "BufrTableViewer cant open " + tc + "\n" + ioe.getMessage()); detailTA.setText("Failed to open <" + tc + ">\n" + ioe.getMessage()); detailTA.setVisible(true); } catch (Exception e) { e.printStackTrace(); StringWriter sw = new StringWriter(5000); e.printStackTrace(new PrintWriter(sw)); detailTA.setText(sw.toString()); detailTA.setVisible(true); } } void save() { bufrTable.save(); super.save(); } } private class BufrTableDPanel extends OpPanel { BufrTableDViewer bufrTable; JComboBox<BufrTables.Format> modes; JComboBox<BufrTables.TableConfig> tables; BufrTableDPanel(PreferencesExt p) { super(p, "tableD:", false, false); AbstractAction fileAction = new AbstractAction() { public void actionPerformed(ActionEvent e) { if (bufrFileChooser == null) initBufrFileChooser(); String filename = bufrFileChooser.chooseFilename(); if (filename == null) return; cb.setSelectedItem(filename); } }; BAMutil.setActionProperties(fileAction, "FileChooser", "open Local table...", false, 'L', -1); BAMutil.addActionToContainer(buttPanel, fileAction); modes = new JComboBox<>(BufrTables.Format.values()); buttPanel.add(modes); JButton accept = new JButton("Accept"); buttPanel.add(accept); accept.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { accept(); } }); tables = new JComboBox<>(BufrTables.getTableConfigsAsArray()); buttPanel.add(tables); tables.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { acceptTable((BufrTables.TableConfig) tables.getSelectedItem()); } }); bufrTable = new BufrTableDViewer(prefs, buttPanel); add(bufrTable, BorderLayout.CENTER); } boolean process(Object command) { return true; } void closeOpenFiles() { } void accept() { String command = (String) cb.getSelectedItem(); if (command == null) return; try { Object mode = modes.getSelectedItem(); bufrTable.setBufrTableD(command, (BufrTables.Format) mode); } catch (FileNotFoundException ioe) { JOptionPane.showMessageDialog(null, "BufrTableViewer cant open " + command + "\n" + ioe.getMessage()); detailTA.setText("Failed to open <" + command + ">\n" + ioe.getMessage()); detailTA.setVisible(true); } catch (Exception e) { e.printStackTrace(); StringWriter sw = new StringWriter(5000); e.printStackTrace(new PrintWriter(sw)); detailTA.setText(sw.toString()); detailTA.setVisible(true); } } void acceptTable(BufrTables.TableConfig tc) { try { bufrTable.setBufrTableD(tc.getTableDname(), tc.getTableDformat()); } catch (FileNotFoundException ioe) { JOptionPane.showMessageDialog(null, "BufrTableViewer cant open " + tc + "\n" + ioe.getMessage()); detailTA.setText("Failed to open <" + tc + ">\n" + ioe.getMessage()); detailTA.setVisible(true); } catch (Exception e) { e.printStackTrace(); StringWriter sw = new StringWriter(5000); e.printStackTrace(new PrintWriter(sw)); detailTA.setText(sw.toString()); detailTA.setVisible(true); } } void save() { bufrTable.save(); super.save(); } } /* private class BufrReportPanel extends OpPanel { ucar.nc2.ui.BufrReportPanel reportPanel; boolean useIndex = true; JComboBox reports; BufrReportPanel(PreferencesExt p) { super(p, "collection:", true, false); reportPanel = new ucar.nc2.ui.BufrReportPanel(prefs, buttPanel); add(reportPanel, BorderLayout.CENTER); reports = new JComboBox(ucar.nc2.ui.BufrReportPanel.Report.values()); buttPanel.add(reports); AbstractAction useIndexButt = new AbstractAction() { public void actionPerformed(ActionEvent e) { Boolean state = (Boolean) getValue(BAMutil.STATE); useIndex = state.booleanValue(); } }; useIndexButt.putValue(BAMutil.STATE, useIndex); BAMutil.setActionProperties(useIndexButt, "Doit", "use default table", true, 'C', -1); BAMutil.addActionToContainer(buttPanel, useIndexButt); AbstractAction doitButt = new AbstractAction() { public void actionPerformed(ActionEvent e) { process(); } }; BAMutil.setActionProperties(doitButt, "alien", "make report", false, 'C', -1); BAMutil.addActionToContainer(buttPanel, doitButt); } boolean process(Object o) { return reportPanel.setCollection((String) o); } boolean process() { boolean err = false; String command = (String) cb.getSelectedItem(); ByteArrayOutputStream bos = new ByteArrayOutputStream(10000); try { reportPanel.doReport(command, useIndex, (ucar.nc2.ui.BufrReportPanel.Report) reports.getSelectedItem()); } catch (IOException ioe) { JOptionPane.showMessageDialog(null, "Grib2ReportPanel cant open " + command + "\n" + ioe.getMessage()); ioe.printStackTrace(); err = true; } catch (Exception e) { e.printStackTrace(); e.printStackTrace(new PrintStream(bos)); detailTA.setText(bos.toString()); detailWindow.show(); err = true; } return !err; } void save() { reportPanel.save(); super.save(); } } */ private class GribFilesPanel extends OpPanel { ucar.nc2.ui.grib.GribFilesPanel gribTable; void closeOpenFiles() throws IOException { } GribFilesPanel(PreferencesExt p) { super(p, "collection:", true, false); gribTable = new ucar.nc2.ui.grib.GribFilesPanel(prefs); add(gribTable, BorderLayout.CENTER); gribTable.addPropertyChangeListener(new java.beans.PropertyChangeListener() { public void propertyChange(java.beans.PropertyChangeEvent e) { if (e.getPropertyName().equals("openGrib1Collection")) { String filename = (String) e.getNewValue(); openGrib1Collection(filename); } } }); AbstractButton showButt = BAMutil.makeButtcon("Information", "Show Collection", false); showButt.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Formatter f = new Formatter(); gribTable.showCollection(f); detailTA.setText(f.toString()); detailTA.gotoTop(); detailWindow.show(); } }); buttPanel.add(showButt); } boolean process(Object o) { String command = (String) o; boolean err = false; try { gribTable.setCollection(command); } catch (FileNotFoundException ioe) { JOptionPane.showMessageDialog(null, "NetcdfDataset cant open " + command + "\n" + ioe.getMessage()); err = true; } catch (Exception e) { e.printStackTrace(); StringWriter sw = new StringWriter(5000); e.printStackTrace(new PrintWriter(sw)); detailTA.setText(sw.toString()); detailWindow.show(); err = true; } return !err; } void save() { gribTable.save(); super.save(); } } // GRIB2 private class Grib2CollectionPanel extends OpPanel { ucar.nc2.ui.grib.Grib2CollectionPanel gribTable; void closeOpenFiles() throws IOException { gribTable.closeOpenFiles(); } Grib2CollectionPanel(PreferencesExt p) { super(p, "collection:", true, false); gribTable = new ucar.nc2.ui.grib.Grib2CollectionPanel(prefs, buttPanel); add(gribTable, BorderLayout.CENTER); gribTable.addPropertyChangeListener(new java.beans.PropertyChangeListener() { public void propertyChange(java.beans.PropertyChangeEvent e) { if (e.getPropertyName().equals("openGrib2Collection")) { String collectionName = (String) e.getNewValue(); openGrib2Collection(collectionName); } } }); AbstractButton showButt = BAMutil.makeButtcon("Information", "Show Collection", false); showButt.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Formatter f = new Formatter(); gribTable.showCollection(f); detailTA.setText(f.toString()); detailTA.gotoTop(); detailWindow.show(); } }); buttPanel.add(showButt); AbstractButton infoButton = BAMutil.makeButtcon("Information", "Check Problems", false); infoButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Formatter f = new Formatter(); gribTable.checkProblems(f); detailTA.setText(f.toString()); detailTA.gotoTop(); detailWindow.show(); } }); buttPanel.add(infoButton); AbstractButton gdsButton = BAMutil.makeButtcon("Information", "Show GDS use", false); gdsButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Formatter f = new Formatter(); gribTable.showGDSuse(f); detailTA.setText(f.toString()); detailTA.gotoTop(); detailWindow.show(); } }); buttPanel.add(gdsButton); AbstractButton writeButton = BAMutil.makeButtcon("netcdf", "Write index", false); writeButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Formatter f = new Formatter(); try { if (!gribTable.writeIndex(f)) return; } catch (IOException e1) { e1.printStackTrace(); } detailTA.setText(f.toString()); detailTA.gotoTop(); detailWindow.show(); } }); buttPanel.add(writeButton); } void setCollection(String collection) { if (process(collection)) { if (!defer) cb.addItem(collection); } } boolean process(Object o) { String command = (String) o; boolean err = false; try { gribTable.setCollection(command); } catch (FileNotFoundException ioe) { JOptionPane.showMessageDialog(null, "NetcdfDataset cant open " + command + "\n" + ioe.getMessage()); err = true; } catch (Exception e) { e.printStackTrace(); StringWriter sw = new StringWriter(5000); e.printStackTrace(new PrintWriter(sw)); detailTA.setText(sw.toString()); detailWindow.show(); err = true; } return !err; } void save() { gribTable.save(); super.save(); } } /* private class Grib2RectilyzePanel extends OpPanel { ucar.nc2.ui.Grib2RectilyzePanel gribTable; void closeOpenFiles() throws IOException { gribTable.closeOpenFiles(); } Grib2RectilyzePanel(PreferencesExt p) { super(p, "collection:", false, false); gribTable = new ucar.nc2.ui.Grib2RectilyzePanel(prefs, buttPanel); add(gribTable, BorderLayout.CENTER); AbstractAction fileAction = new AbstractAction() { public void actionPerformed(ActionEvent e) { String filename = fileChooser.chooseFilename(); if (filename == null) return; cb.setSelectedItem("file:"+filename); } }; BAMutil.setActionProperties(fileAction, "FileChooser", "open Local dataset...", false, 'L', -1); BAMutil.addActionToContainer(buttPanel, fileAction); gribTable.addPropertyChangeListener(new java.beans.PropertyChangeListener() { public void propertyChange(java.beans.PropertyChangeEvent e) { if (e.getPropertyName().equals("openGrib2Collection")) { String collectionName = (String) e.getNewValue(); openGrib2Collection(collectionName); } } }); AbstractButton showButt = BAMutil.makeButtcon("Information", "Show Collection", false); showButt.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Formatter f = new Formatter(); gribTable.showCollection(f); detailTA.setText(f.toString()); detailTA.gotoTop(); detailWindow.show(); } }); buttPanel.add(showButt); AbstractButton aggButton = BAMutil.makeButtcon("V3", "Show Statistics", false); aggButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Formatter f = new Formatter(); try { gribTable.showStats(f); } catch (IOException e1) { e1.printStackTrace(); } detailTA.setText(f.toString()); detailTA.gotoTop(); detailWindow.show(); } }); buttPanel.add(aggButton); AbstractButton writeButton = BAMutil.makeButtcon("netcdf", "Write index", false); writeButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Formatter f = new Formatter(); try { if (!gribTable.writeIndex(f)) return; } catch (IOException e1) { e1.printStackTrace(); } detailTA.setText(f.toString()); detailTA.gotoTop(); detailWindow.show(); } }); buttPanel.add(writeButton); } void setCollection(String collection) { if (process(collection)) { if (!defer) cb.addItem(collection); } } boolean process(Object o) { String command = (String) o; boolean err = false; ByteArrayOutputStream bos = new ByteArrayOutputStream(10000); try { gribTable.setCollection(command); } catch (FileNotFoundException ioe) { JOptionPane.showMessageDialog(null, "NetcdfDataset cant open " + command + "\n" + ioe.getMessage()); err = true; } catch (Exception e) { e.printStackTrace(); e.printStackTrace(new PrintStream(bos)); detailTA.setText(bos.toString()); detailWindow.show(); err = true; } return !err; } void save() { gribTable.save(); super.save(); } } */ private class Grib2DataPanel extends OpPanel { ucar.nc2.ui.grib.Grib2DataPanel gribTable; void closeOpenFiles() throws IOException { } Grib2DataPanel(PreferencesExt p) { super(p, "collection:", true, false); gribTable = new ucar.nc2.ui.grib.Grib2DataPanel(prefs); add(gribTable, BorderLayout.CENTER); gribTable.addPropertyChangeListener(new java.beans.PropertyChangeListener() { public void propertyChange(java.beans.PropertyChangeEvent e) { if (e.getPropertyName().equals("openGrib2Collection")) { String collectionName = (String) e.getNewValue(); openGrib2Collection(collectionName); } } }); AbstractButton infoButton = BAMutil.makeButtcon("Information", "Show Info", false); infoButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Formatter f = new Formatter(); gribTable.showInfo(f); detailTA.setText(f.toString()); detailTA.gotoTop(); detailWindow.show(); } }); buttPanel.add(infoButton); AbstractButton checkButton = BAMutil.makeButtcon("Information", "Check Problems", false); checkButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Formatter f = new Formatter(); gribTable.checkProblems(f); detailTA.setText(f.toString()); detailTA.gotoTop(); detailWindow.show(); } }); buttPanel.add(checkButton); } void setCollection(String collection) { if (process(collection)) { if (!defer) cb.addItem(collection); } } boolean process(Object o) { String command = (String) o; boolean err = false; try { gribTable.setCollection(command); } catch (FileNotFoundException ioe) { JOptionPane.showMessageDialog(null, "NetcdfDataset cant open " + command + "\n" + ioe.getMessage()); err = true; } catch (Exception e) { e.printStackTrace(); StringWriter sw = new StringWriter(5000); e.printStackTrace(new PrintWriter(sw)); detailTA.setText(sw.toString()); detailWindow.show(); err = true; } return !err; } void save() { gribTable.save(); super.save(); } } private class Grib1DataPanel extends OpPanel { Grib1DataTable gribTable; void closeOpenFiles() throws IOException { } Grib1DataPanel(PreferencesExt p) { super(p, "collection:", true, false); gribTable = new Grib1DataTable(prefs); add(gribTable, BorderLayout.CENTER); gribTable.addPropertyChangeListener(new java.beans.PropertyChangeListener() { public void propertyChange(java.beans.PropertyChangeEvent e) { if (e.getPropertyName().equals("openGrib1Collection")) { String collectionName = (String) e.getNewValue(); openGrib1Collection(collectionName); } } }); AbstractButton infoButton = BAMutil.makeButtcon("Information", "Check Problems", false); infoButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Formatter f = new Formatter(); gribTable.checkProblems(f); detailTA.setText(f.toString()); detailTA.gotoTop(); detailWindow.show(); } }); buttPanel.add(infoButton); } void setCollection(String collection) { if (process(collection)) { if (!defer) cb.addItem(collection); } } boolean process(Object o) { String command = (String) o; boolean err = false; try { gribTable.setCollection(command); } catch (FileNotFoundException ioe) { JOptionPane.showMessageDialog(null, "NetcdfDataset cant open " + command + "\n" + ioe.getMessage()); err = true; } catch (Exception e) { e.printStackTrace(); StringWriter sw = new StringWriter(5000); e.printStackTrace(new PrintWriter(sw)); detailTA.setText(sw.toString()); detailWindow.show(); err = true; } return !err; } void save() { gribTable.save(); super.save(); } } private class BufrCdmIndexPanel extends OpPanel { ucar.nc2.ui.BufrCdmIndexPanel table; void closeOpenFiles() throws IOException { //table.closeOpenFiles(); } BufrCdmIndexPanel(PreferencesExt p) { super(p, "index file:", true, false); table = new ucar.nc2.ui.BufrCdmIndexPanel(prefs, buttPanel); add(table, BorderLayout.CENTER); } boolean process(Object o) { String command = (String) o; boolean err = false; try { table.setIndexFile(command); } catch (FileNotFoundException ioe) { JOptionPane.showMessageDialog(null, "BufrCdmIndexPanel cant open " + command + "\n" + ioe.getMessage()); err = true; } catch (Exception e) { e.printStackTrace(); StringWriter sw = new StringWriter(5000); e.printStackTrace(new PrintWriter(sw)); detailTA.setText(sw.toString()); detailWindow.show(); err = true; } return !err; } void save() { table.save(); super.save(); } } /* ///////////////////////////////////////////////////////////////////// private class GribCdmIndexPanel extends OpPanel { ucar.nc2.ui.GribCdmIndexPanel gribTable; void closeOpenFiles() throws IOException { gribTable.closeOpenFiles(); } GribCdmIndexPanel(PreferencesExt p) { super(p, "index file:", true, false); gribTable = new ucar.nc2.ui.GribCdmIndexPanel(prefs, buttPanel); gribTable.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent e) { if (e.getPropertyName().equals("openGrib2Collection")) { String collectionName = (String) e.getNewValue(); openGrib2Collection(collectionName); } } }); add(gribTable, BorderLayout.CENTER); } boolean process(Object o) { String command = (String) o; boolean err = false; ByteArrayOutputStream bos = new ByteArrayOutputStream(10000); try { gribTable.setIndexFile(Paths.get(command), null); } catch (FileNotFoundException ioe) { JOptionPane.showMessageDialog(null, "GribCdmIndexPanel cant open " + command + "\n" + ioe.getMessage()); err = true; } catch (Exception e) { e.printStackTrace(); e.printStackTrace(new PrintStream(bos)); detailTA.setText(bos.toString()); detailWindow.show(); err = true; } return !err; } void save() { gribTable.save(); super.save(); } } */ private class CdmIndex2Panel extends OpPanel { ucar.nc2.ui.CdmIndex2Panel indexPanel; void closeOpenFiles() throws IOException { indexPanel.clear(); } CdmIndex2Panel(PreferencesExt p) { super(p, "index file:", true, false); indexPanel = new ucar.nc2.ui.CdmIndex2Panel(prefs, buttPanel); indexPanel.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent e) { if (e.getPropertyName().equals("openGrib2Collection")) { String collectionName = (String) e.getNewValue(); openGrib2Collection(collectionName); } } }); add(indexPanel, BorderLayout.CENTER); } boolean process(Object o) { String command = (String) o; boolean err = false; try { indexPanel.setIndexFile(Paths.get(command), new FeatureCollectionConfig()); } catch (FileNotFoundException ioe) { JOptionPane.showMessageDialog(null, "GribCdmIndexPanel cant open " + command + "\n" + ioe.getMessage()); err = true; } catch (Throwable e) { e.printStackTrace(); StringWriter sw = new StringWriter(5000); e.printStackTrace(new PrintWriter(sw)); detailTA.setText(sw.toString()); detailWindow.show(); err = true; } return !err; } void save() { indexPanel.save(); super.save(); } } private class GribIndexPanel extends OpPanel { ucar.nc2.ui.grib.GribIndexPanel gribTable; void closeOpenFiles() throws IOException { gribTable.closeOpenFiles(); } GribIndexPanel(PreferencesExt p) { super(p, "index file:", true, false); gribTable = new ucar.nc2.ui.grib.GribIndexPanel(prefs, buttPanel); add(gribTable, BorderLayout.CENTER); } boolean process(Object o) { String command = (String) o; boolean err = false; try { gribTable.setIndexFile(command); } catch (FileNotFoundException ioe) { JOptionPane.showMessageDialog(null, "NetcdfDataset cant open " + command + "\n" + ioe.getMessage()); err = true; } catch (Exception e) { e.printStackTrace(); StringWriter sw = new StringWriter(5000); e.printStackTrace(new PrintWriter(sw)); detailTA.setText(sw.toString()); detailWindow.show(); err = true; } return !err; } void save() { gribTable.save(); super.save(); } } // raw grib access - dont go through the IOSP private class Grib1CollectionPanel extends OpPanel { //ucar.unidata.io.RandomAccessFile raf = null; ucar.nc2.ui.grib.Grib1CollectionPanel gribTable; void closeOpenFiles() throws IOException { } Grib1CollectionPanel(PreferencesExt p) { super(p, "collection:", true, false); gribTable = new ucar.nc2.ui.grib.Grib1CollectionPanel(buttPanel, prefs); add(gribTable, BorderLayout.CENTER); AbstractButton showButt = BAMutil.makeButtcon("Information", "Show Collection", false); showButt.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Formatter f = new Formatter(); gribTable.showCollection(f); detailTA.setText(f.toString()); detailTA.gotoTop(); detailWindow.show(); } }); buttPanel.add(showButt); AbstractButton writeButton = BAMutil.makeButtcon("netcdf", "Write index", false); writeButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Formatter f = new Formatter(); try { if (!gribTable.writeIndex(f)) return; } catch (IOException e1) { e1.printStackTrace(); } detailTA.setText(f.toString()); detailTA.gotoTop(); detailWindow.show(); } }); buttPanel.add(writeButton); } void setCollection(String collection) { if (process(collection)) { if (!defer) cb.addItem(collection); } } boolean process(Object o) { String command = (String) o; boolean err = false; try { gribTable.setCollection(command); } catch (FileNotFoundException ioe) { JOptionPane.showMessageDialog(null, "NetcdfDataset cant open " + command + "\n" + ioe.getMessage()); err = true; } catch (Exception e) { e.printStackTrace(); StringWriter sw = new StringWriter(5000); e.printStackTrace(new PrintWriter(sw)); detailTA.setText(sw.toString()); detailWindow.show(); err = true; } return !err; } void save() { gribTable.save(); super.save(); } } private class ReportOpPanel extends OpPanel { ucar.nc2.ui.ReportPanel reportPanel; boolean useIndex = true; boolean eachFile = false; boolean extra = false; JComboBox reports; ReportOpPanel(PreferencesExt p, ReportPanel reportPanel) { super(p, "collection:", true, false); this.reportPanel = reportPanel; add(reportPanel, BorderLayout.CENTER); reportPanel.addOptions(buttPanel); reports = new JComboBox(reportPanel.getOptions()); buttPanel.add(reports); AbstractAction useIndexButt = new AbstractAction() { public void actionPerformed(ActionEvent e) { Boolean state = (Boolean) getValue(BAMutil.STATE); useIndex = state; } }; useIndexButt.putValue(BAMutil.STATE, useIndex); BAMutil.setActionProperties(useIndexButt, "Doit", "use Index", true, 'C', -1); BAMutil.addActionToContainer(buttPanel, useIndexButt); AbstractAction eachFileButt = new AbstractAction() { public void actionPerformed(ActionEvent e) { Boolean state = (Boolean) getValue(BAMutil.STATE); eachFile = state; } }; eachFileButt.putValue(BAMutil.STATE, eachFile); BAMutil.setActionProperties(eachFileButt, "Doit", "report on each file", true, 'E', -1); BAMutil.addActionToContainer(buttPanel, eachFileButt); AbstractAction extraButt = new AbstractAction() { public void actionPerformed(ActionEvent e) { Boolean state = (Boolean) getValue(BAMutil.STATE); extra = state; } }; extraButt.putValue(BAMutil.STATE, extra); BAMutil.setActionProperties(extraButt, "Doit", "extra info", true, 'X', -1); BAMutil.addActionToContainer(buttPanel, extraButt); AbstractAction doitButt = new AbstractAction() { public void actionPerformed(ActionEvent e) { process(); } }; BAMutil.setActionProperties(doitButt, "alien", "make report", false, 'C', -1); BAMutil.addActionToContainer(buttPanel, doitButt); } void closeOpenFiles() { } boolean process(Object o) { return reportPanel.showCollection((String) o); } boolean process() { boolean err = false; String command = (String) cb.getSelectedItem(); try { reportPanel.doReport(command, useIndex, eachFile, extra, reports.getSelectedItem()); } catch (IOException ioe) { JOptionPane.showMessageDialog(null, "Grib2ReportPanel cant open " + command + "\n" + ioe.getMessage()); ioe.printStackTrace(); err = true; } catch (Exception e) { StringWriter sw = new StringWriter(5000); e.printStackTrace(new PrintWriter(sw)); detailTA.setText(sw.toString()); detailWindow.show(); err = true; } return !err; } void save() { // reportPanel.save(); super.save(); } } /* private class Grib2ReportPanel extends OpPanel { ucar.nc2.ui.grib.Grib2ReportPanel gribReport; boolean useIndex = true; boolean eachFile = false; boolean extra = false; JComboBox reports; Grib2ReportPanel(PreferencesExt p) { super(p, "collection:", true, false); gribReport = new ucar.nc2.ui.grib.Grib2ReportPanel(prefs, buttPanel); add(gribReport, BorderLayout.CENTER); reports = new JComboBox(ucar.nc2.ui.grib.Grib2ReportPanel.Report.values()); buttPanel.add(reports); AbstractAction useIndexButt = new AbstractAction() { public void actionPerformed(ActionEvent e) { Boolean state = (Boolean) getValue(BAMutil.STATE); useIndex = state.booleanValue(); } }; useIndexButt.putValue(BAMutil.STATE, useIndex); BAMutil.setActionProperties(useIndexButt, "Doit", "use Index", true, 'C', -1); BAMutil.addActionToContainer(buttPanel, useIndexButt); AbstractAction eachFileButt = new AbstractAction() { public void actionPerformed(ActionEvent e) { Boolean state = (Boolean) getValue(BAMutil.STATE); eachFile = state.booleanValue(); } }; eachFileButt.putValue(BAMutil.STATE, eachFile); BAMutil.setActionProperties(eachFileButt, "Doit", "report on each file", true, 'E', -1); BAMutil.addActionToContainer(buttPanel, eachFileButt); AbstractAction extraButt = new AbstractAction() { public void actionPerformed(ActionEvent e) { Boolean state = (Boolean) getValue(BAMutil.STATE); extra = state.booleanValue(); } }; extraButt.putValue(BAMutil.STATE, extra); BAMutil.setActionProperties(extraButt, "Doit", "extra info", true, 'X', -1); BAMutil.addActionToContainer(buttPanel, extraButt); AbstractAction doitButt = new AbstractAction() { public void actionPerformed(ActionEvent e) { process(); } }; BAMutil.setActionProperties(doitButt, "alien", "make report", false, 'C', -1); BAMutil.addActionToContainer(buttPanel, doitButt); } void closeOpenFiles() { } boolean process(Object o) { return gribReport.setCollection((String) o); } boolean process() { boolean err = false; String command = (String) cb.getSelectedItem(); ByteArrayOutputStream bos = new ByteArrayOutputStream(10000); try { gribReport.doReport(command, useIndex, eachFile, extra, (ucar.nc2.ui.grib.Grib2ReportPanel.Report) reports.getSelectedItem()); } catch (IOException ioe) { JOptionPane.showMessageDialog(null, "Grib2ReportPanel cant open " + command + "\n" + ioe.getMessage()); ioe.printStackTrace(); err = true; } catch (Exception e) { e.printStackTrace(new PrintStream(bos)); detailTA.setText(bos.toString()); detailWindow.show(); err = true; } return !err; } void save() { gribReport.save(); super.save(); } } */ /* private class Grib1ReportPanel extends OpPanel { ucar.nc2.ui.grib.Grib1ReportPanel gribReport; boolean useIndex = true; JComboBox reports; Grib1ReportPanel(PreferencesExt p) { super(p, "collection:", true, false); gribReport = new ucar.nc2.ui.grib.Grib1ReportPanel(prefs, buttPanel); add(gribReport, BorderLayout.CENTER); reports = new JComboBox(ucar.nc2.ui.grib.Grib1ReportPanel.Report.values()); buttPanel.add(reports); AbstractAction useIndexButt = new AbstractAction() { public void actionPerformed(ActionEvent e) { Boolean state = (Boolean) getValue(BAMutil.STATE); useIndex = state.booleanValue(); } }; useIndexButt.putValue(BAMutil.STATE, useIndex); BAMutil.setActionProperties(useIndexButt, "Doit", "use default table", true, 'C', -1); BAMutil.addActionToContainer(buttPanel, useIndexButt); AbstractAction doitButt = new AbstractAction() { public void actionPerformed(ActionEvent e) { process(); } }; BAMutil.setActionProperties(doitButt, "alien", "make report", false, 'C', -1); BAMutil.addActionToContainer(buttPanel, doitButt); } boolean process(Object o) { return gribReport.setCollection((String) o); } boolean process() { boolean err = false; String command = (String) cb.getSelectedItem(); ByteArrayOutputStream bos = new ByteArrayOutputStream(10000); try { gribReport.doReport(command, useIndex, (ucar.nc2.ui.grib.Grib1ReportPanel.Report) reports.getSelectedItem()); } catch (IOException ioe) { JOptionPane.showMessageDialog(null, "Grib2ReportPanel cant open " + command + "\n" + ioe.getMessage()); ioe.printStackTrace(); err = true; } catch (Exception e) { e.printStackTrace(); e.printStackTrace(new PrintStream(bos)); detailTA.setText(bos.toString()); detailWindow.show(); err = true; } return !err; } void save() { gribReport.save(); super.save(); } } */ private class GribTemplatePanel extends OpPanel { GribWmoTemplatesPanel codeTable; GribTemplatePanel(PreferencesExt p) { super(p, "table:", false, false, false); final JComboBox<WmoTemplateTable.Version> modes = new JComboBox<>(WmoTemplateTable.Version.values()); modes.setSelectedItem(WmoTemplateTable.standard); topPanel.add(modes, BorderLayout.CENTER); modes.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { codeTable.setTable((WmoTemplateTable.Version) modes.getSelectedItem()); } }); codeTable = new GribWmoTemplatesPanel(prefs, buttPanel); add(codeTable, BorderLayout.CENTER); } boolean process(Object command) { return true; } void save() { codeTable.save(); super.save(); } void closeOpenFiles() { } } private class GribCodePanel extends OpPanel { GribWmoCodesPanel codeTable; GribCodePanel(PreferencesExt p) { super(p, "table:", false, false, false); final JComboBox<WmoCodeTable.Version> modes = new JComboBox<>(WmoCodeTable.Version.values()); modes.setSelectedItem(WmoCodeTable.standard); topPanel.add(modes, BorderLayout.CENTER); modes.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { codeTable.setTable((WmoCodeTable.Version) modes.getSelectedItem()); } }); codeTable = new GribWmoCodesPanel(prefs, buttPanel); add(codeTable, BorderLayout.CENTER); } boolean process(Object command) { return true; } void save() { codeTable.save(); super.save(); } void closeOpenFiles() { } } private class BufrCodePanel extends OpPanel { BufrWmoCodesPanel codeTable; BufrCodePanel(PreferencesExt p) { super(p, "table:", false, false, false); codeTable = new BufrWmoCodesPanel(prefs, buttPanel); add(codeTable, BorderLayout.CENTER); } boolean process(Object command) { return true; } void save() { codeTable.save(); super.save(); } void closeOpenFiles() { } } private class WmoCCPanel extends OpPanel { WmoCommonCodesPanel codeTable; WmoCCPanel(PreferencesExt p) { super(p, "table:", false, false); codeTable = new WmoCommonCodesPanel(prefs, buttPanel); add(codeTable, BorderLayout.CENTER); } boolean process(Object command) { return true; } void save() { codeTable.save(); super.save(); } void closeOpenFiles() { } } private class Grib1TablePanel extends OpPanel { Grib1TablesViewer codeTable; Grib1TablePanel(PreferencesExt p) { super(p, "table:", true, false); codeTable = new Grib1TablesViewer(prefs, buttPanel); add(codeTable, BorderLayout.CENTER); } boolean process(Object command) { try { codeTable.setTable((String) command); return true; } catch (IOException e) { return false; } } void save() { codeTable.save(); super.save(); } void closeOpenFiles() { } } private class Grib2TablePanel extends OpPanel { Grib2TableViewer2 codeTable; Grib2TablePanel(PreferencesExt p) { super(p, "table:", false, false); codeTable = new Grib2TableViewer2(prefs, buttPanel); add(codeTable, BorderLayout.CENTER); } boolean process(Object command) { return true; } void save() { codeTable.save(); super.save(); } void closeOpenFiles() { } } private class GribRenamePanel extends OpPanel { ucar.nc2.ui.grib.GribRenamePanel panel; GribRenamePanel(PreferencesExt p) { super(p, "matchNcepName: ", true, false, false); panel = new ucar.nc2.ui.grib.GribRenamePanel(prefs, buttPanel); add(panel, BorderLayout.CENTER); } boolean process(Object o) { return panel.matchNcepName((String) o); } void save() { panel.save(); super.save(); } void closeOpenFiles() { } } private class GribRewritePanel extends OpPanel { ucar.nc2.ui.grib.GribRewritePanel ftTable; final FileManager dirChooser; GribRewritePanel(PreferencesExt prefs) { super(prefs, "dir:", false, false); dirChooser = new FileManager(parentFrame, null, null, (PreferencesExt) prefs.node("FeatureScanFileManager")); ftTable = new ucar.nc2.ui.grib.GribRewritePanel(prefs, buttPanel); add(ftTable, BorderLayout.CENTER); ftTable.addPropertyChangeListener(new java.beans.PropertyChangeListener() { public void propertyChange(java.beans.PropertyChangeEvent e) { if (e.getPropertyName().equals("openNetcdfFile")) { String datasetName = (String) e.getNewValue(); openNetcdfFile(datasetName); } else if (e.getPropertyName().equals("openGridDataset")) { String datasetName = (String) e.getNewValue(); openGridDataset(datasetName); } else if (e.getPropertyName().equals("openGrib1Data")) { String datasetName = (String) e.getNewValue(); openGrib1Data(datasetName); } else if (e.getPropertyName().equals("openGrib2Data")) { String datasetName = (String) e.getNewValue(); openGrib2Data(datasetName); } } }); dirChooser.getFileChooser().setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); dirChooser.setCurrentDirectory(prefs.get("currDir", ".")); AbstractAction fileAction = new AbstractAction() { public void actionPerformed(ActionEvent e) { String filename = dirChooser.chooseFilename(); if (filename == null) return; cb.setSelectedItem(filename); } }; BAMutil.setActionProperties(fileAction, "FileChooser", "open Local dataset...", false, 'L', -1); BAMutil.addActionToContainer(buttPanel, fileAction); } boolean process(Object o) { String command = (String) o; return ftTable.setScanDirectory(command); } void closeOpenFiles() { ftTable.clear(); } void save() { dirChooser.save(); ftTable.save(); prefs.put("currDir", dirChooser.getCurrentDirectory()); super.save(); } } private class Hdf5ObjectPanel extends OpPanel { ucar.unidata.io.RandomAccessFile raf = null; Hdf5ObjectTable hdf5Table; void closeOpenFiles() throws IOException { hdf5Table.closeOpenFiles(); } Hdf5ObjectPanel(PreferencesExt p) { super(p, "file:", true, false); hdf5Table = new Hdf5ObjectTable(prefs); add(hdf5Table, BorderLayout.CENTER); AbstractButton infoButton = BAMutil.makeButtcon("Information", "Compact Representation", false); infoButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Formatter f = new Formatter(); try { hdf5Table.showInfo(f); } catch (IOException ioe) { StringWriter sw = new StringWriter(5000); ioe.printStackTrace(new PrintWriter(sw)); detailTA.setText(sw.toString()); detailWindow.show(); return; } detailTA.setText(f.toString()); detailTA.gotoTop(); detailWindow.show(); } }); buttPanel.add(infoButton); AbstractButton infoButton2 = BAMutil.makeButtcon("Information", "Detail Info", false); infoButton2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Formatter f = new Formatter(); try { hdf5Table.showInfo2(f); } catch (IOException ioe) { StringWriter sw = new StringWriter(5000); ioe.printStackTrace(new PrintWriter(sw)); detailTA.setText(sw.toString()); detailWindow.show(); return; } detailTA.setText(f.toString()); detailTA.gotoTop(); detailWindow.show(); } }); buttPanel.add(infoButton2); AbstractButton eosdump = BAMutil.makeButtcon("alien", "Show EOS processing", false); eosdump.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { Formatter f = new Formatter(); hdf5Table.getEosInfo(f); detailTA.setText(f.toString()); detailWindow.show(); } catch (IOException ioe) { StringWriter sw = new StringWriter(5000); ioe.printStackTrace(new PrintWriter(sw)); detailTA.setText(sw.toString()); detailWindow.show(); } } }); buttPanel.add(eosdump); } boolean process(Object o) { String command = (String) o; boolean err = false; try { if (raf != null) raf.close(); raf = new ucar.unidata.io.RandomAccessFile(command, "r"); hdf5Table.setHdf5File(raf); } catch (FileNotFoundException ioe) { JOptionPane.showMessageDialog(null, "Hdf5ObjectTable cant open " + command + "\n" + ioe.getMessage()); err = true; } catch (Exception e) { StringWriter sw = new StringWriter(5000); e.printStackTrace(new PrintWriter(sw)); detailTA.setText(sw.toString()); detailWindow.show(); err = true; } return !err; } void save() { hdf5Table.save(); super.save(); } } private class Hdf5DataPanel extends OpPanel { ucar.unidata.io.RandomAccessFile raf = null; Hdf5DataTable hdf5Table; void closeOpenFiles() throws IOException { hdf5Table.closeOpenFiles(); } Hdf5DataPanel(PreferencesExt p) { super(p, "file:", true, false); hdf5Table = new Hdf5DataTable(prefs, buttPanel); add(hdf5Table, BorderLayout.CENTER); AbstractButton infoButton = BAMutil.makeButtcon("Information", "Detail Info", false); infoButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Formatter f = new Formatter(); try { hdf5Table.showInfo(f); } catch (IOException ioe) { StringWriter sw = new StringWriter(5000); ioe.printStackTrace(new PrintWriter(sw)); detailTA.setText(sw.toString()); detailWindow.show(); return; } detailTA.setText(f.toString()); detailTA.gotoTop(); detailWindow.show(); } }); buttPanel.add(infoButton); } boolean process(Object o) { String command = (String) o; boolean err = false; try { if (raf != null) raf.close(); raf = new ucar.unidata.io.RandomAccessFile(command, "r"); hdf5Table.setHdf5File(raf); } catch (FileNotFoundException ioe) { JOptionPane.showMessageDialog(null, "Hdf5DataTable cant open " + command + "\n" + ioe.getMessage()); err = true; } catch (Exception e) { StringWriter sw = new StringWriter(5000); e.printStackTrace(new PrintWriter(sw)); detailTA.setText(sw.toString()); detailWindow.show(); err = true; } return !err; } void save() { hdf5Table.save(); super.save(); } } private class Hdf4Panel extends OpPanel { ucar.unidata.io.RandomAccessFile raf = null; Hdf4Table hdf4Table; void closeOpenFiles() throws IOException { hdf4Table.closeOpenFiles(); } Hdf4Panel(PreferencesExt p) { super(p, "file:", true, false); hdf4Table = new Hdf4Table(prefs); add(hdf4Table, BorderLayout.CENTER); AbstractButton eosdump = BAMutil.makeButtcon("alien", "Show EOS processing", false); eosdump.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { Formatter f = new Formatter(); hdf4Table.getEosInfo(f); detailTA.setText(f.toString()); detailWindow.show(); } catch (IOException ioe) { StringWriter sw = new StringWriter(5000); ioe.printStackTrace(new PrintWriter(sw)); detailTA.setText(sw.toString()); detailWindow.show(); } } }); buttPanel.add(eosdump); } boolean process(Object o) { String command = (String) o; boolean err = false; try { if (raf != null) raf.close(); raf = new ucar.unidata.io.RandomAccessFile(command, "r"); hdf4Table.setHdf4File(raf); } catch (FileNotFoundException ioe) { JOptionPane.showMessageDialog(null, "NetcdfDataset cant open " + command + "\n" + ioe.getMessage()); err = true; } catch (Exception e) { StringWriter sw = new StringWriter(5000); e.printStackTrace(new PrintWriter(sw)); detailTA.setText(sw.toString()); detailWindow.show(); err = true; } return !err; } void save() { hdf4Table.save(); super.save(); } } /* private class NcmlPanel extends OpPanel { NetcdfDataset ds = null; String ncmlLocation = null; AbstractButton gButt = null; boolean useG; void closeOpenFiles() throws IOException { if (ds != null) ds.close(); ds = null; } NcmlPanel(PreferencesExt p) { super(p, "dataset:"); AbstractAction gAction = new AbstractAction() { public void actionPerformed(ActionEvent e) { Boolean state = (Boolean) getValue(BAMutil.STATE); useG = state.booleanValue(); String tooltip = useG ? "use NcML-G" : "dont use NcML-G"; gButt.setToolTipText(tooltip); //doit( cb.getSelectedItem()); // called from cb action listener } }; useG = prefs.getBoolean("gState", false); String tooltip2 = useG ? "use NcML-G" : "dont use NcML-G"; BAMutil.setActionProperties(gAction, "G", tooltip2, true, 'G', -1); gAction.putValue(BAMutil.STATE, new Boolean(useG)); gButt = BAMutil.addActionToContainer(buttPanel, gAction); AbstractAction saveAction = new AbstractAction() { public void actionPerformed(ActionEvent e) { String location = (ds == null) ? ncmlLocation : ds.getLocation(); if (location == null) location = "test"; int pos = location.lastIndexOf("."); if (pos > 0) location = location.substring(0, pos); String filename = fileChooser.chooseFilenameToSave(location + ".ncml"); if (filename == null) return; doSave(ta.getText(), filename); } }; BAMutil.setActionProperties(saveAction, "Save", "Save NcML", false, 'S', -1); BAMutil.addActionToContainer(buttPanel, saveAction); AbstractAction netcdfAction = new AbstractAction() { public void actionPerformed(ActionEvent e) { String location = (ds == null) ? ncmlLocation : ds.getLocation(); if (location == null) location = "test"; int pos = location.lastIndexOf("."); if (pos > 0) location = location.substring(0, pos); String filename = fileChooser.chooseFilenameToSave(location + ".nc"); if (filename == null) return; doWriteNetCDF(ta.getText(), filename); } }; BAMutil.setActionProperties(netcdfAction, "netcdf", "Write netCDF", false, 'N', -1); BAMutil.addActionToContainer(buttPanel, netcdfAction); AbstractAction transAction = new AbstractAction() { public void actionPerformed(ActionEvent e) { doTransform(ta.getText()); } }; BAMutil.setActionProperties(transAction, "Import", "read textArea through NcMLReader\n write NcML back out via resulting dataset", false, 'T', -1); BAMutil.addActionToContainer(buttPanel, transAction); } boolean process(Object o) { ncmlLocation = (String) o; if (ncmlLocation.endsWith(".xml") || ncmlLocation.endsWith(".ncml")) { if (!ncmlLocation.startsWith("http:") && !ncmlLocation.startsWith("file:")) ncmlLocation = "file:" + ncmlLocation; String text = IO.readURLcontents(ncmlLocation); ta.setText(text); } else { writeNcml(ncmlLocation); } return true; } boolean writeNcml(String location) { boolean err = false; try { if (ds != null) ds.close(); } catch (IOException ioe) { } ByteArrayOutputStream bos = new ByteArrayOutputStream(10000); try { String result; ds = openDataset(location, addCoords, null); if (ds == null) { ta.setText("Failed to open <" + location + ">"); } else { if (useG) { boolean showCoords = Debug.isSet("NcML/ncmlG-showCoords"); ds.writeNcMLG(bos, showCoords, null); result = bos.toString(); } else { result = new NcMLWriter().writeXML(ds); } ta.setText(result); ta.gotoTop(); } } catch (FileNotFoundException ioe) { ta.setText("Failed to open <" + location + ">"); err = true; } catch (Exception e) { e.printStackTrace(); e.printStackTrace(new PrintStream(bos)); ta.setText(bos.toString()); err = true; } return !err; } void doWriteNetCDF(String text, String filename) { if (debugNcmlWrite) { System.out.println("filename=" + filename); System.out.println("text=" + text); } try { ByteArrayInputStream bis = new ByteArrayInputStream(text.getBytes()); NcMLReader.writeNcMLToFile(bis, filename); JOptionPane.showMessageDialog(this, "File successfully written"); } catch (Exception ioe) { JOptionPane.showMessageDialog(this, "ERROR: " + ioe.getMessage()); ioe.printStackTrace(); } } // read text from textArea through NcMLReader // then write it back out via resulting dataset void doTransform(String text) { try { StringReader reader = new StringReader(text); NetcdfDataset ncd = NcMLReader.readNcML(reader, null); ByteArrayOutputStream bos = new ByteArrayOutputStream(10000); ncd.writeNcML(bos, null); ta.setText(bos.toString()); ta.gotoTop(); JOptionPane.showMessageDialog(this, "File successfully transformed"); } catch (IOException ioe) { JOptionPane.showMessageDialog(this, "ERROR: " + ioe.getMessage()); ioe.printStackTrace(); } } void doSave(String text, String filename) { if (debugNcmlWrite) { System.out.println("filename=" + filename); System.out.println("text=" + text); } try { IO.writeToFile(text, new File(filename)); JOptionPane.showMessageDialog(this, "File successfully written"); } catch (IOException ioe) { JOptionPane.showMessageDialog(this, "ERROR: " + ioe.getMessage()); ioe.printStackTrace(); } // saveNcmlDialog.setVisible(false); } void save() { super.save(); } } */ private class NcmlEditorPanel extends OpPanel { NcmlEditor editor; void closeOpenFiles() throws IOException { editor.closeOpenFiles(); } NcmlEditorPanel(PreferencesExt p) { super(p, "dataset:", true, false); editor = new NcmlEditor(buttPanel, prefs); add(editor, BorderLayout.CENTER); } boolean process(Object o) { return editor.setNcml((String) o); } void save() { super.save(); editor.save(); } } private class CdmrFeature extends OpPanel { CdmrFeaturePanel panel; CdmrFeature(PreferencesExt p) { super(p, "file:", true, false); panel = new CdmrFeaturePanel(prefs); add(panel, BorderLayout.CENTER); AbstractAction infoAction = new AbstractAction() { public void actionPerformed(ActionEvent e) { Formatter f = new Formatter(); try { panel.showInfo(f); } catch (Exception ioe) { StringWriter sw = new StringWriter(5000); ioe.printStackTrace(new PrintWriter(sw)); detailTA.setText(sw.toString()); detailWindow.show(); return; } detailTA.setText(f.toString()); detailTA.gotoTop(); detailWindow.show(); } }; BAMutil.setActionProperties(infoAction, "Information", "show Info", false, 'I', -1); BAMutil.addActionToContainer(buttPanel, infoAction); } boolean process(Object o) { String command = (String) o; boolean err = false; try { panel.setNcStream(command); } catch (FileNotFoundException ioe) { JOptionPane.showMessageDialog(null, "CdmremotePanel cant open " + command + "\n" + ioe.getMessage()); err = true; } catch (Exception e) { StringWriter sw = new StringWriter(5000); e.printStackTrace(new PrintWriter(sw)); detailTA.setText(sw.toString()); detailWindow.show(); err = true; } return !err; } void save() { panel.save(); super.save(); } void closeOpenFiles() throws IOException { panel.closeOpenFiles(); } } private class NcStreamPanel extends OpPanel { ucar.nc2.ui.NcStreamPanel panel; NcStreamPanel(PreferencesExt p) { super(p, "file:", true, false); panel = new ucar.nc2.ui.NcStreamPanel(prefs); add(panel, BorderLayout.CENTER); AbstractAction infoAction = new AbstractAction() { public void actionPerformed(ActionEvent e) { Formatter f = new Formatter(); try { panel.showInfo(f); } catch (Exception ioe) { StringWriter sw = new StringWriter(5000); ioe.printStackTrace(new PrintWriter(sw)); detailTA.setText(sw.toString()); detailWindow.show(); return; } detailTA.setText(f.toString()); detailTA.gotoTop(); detailWindow.show(); } }; BAMutil.setActionProperties(infoAction, "Information", "show Info", false, 'I', -1); BAMutil.addActionToContainer(buttPanel, infoAction); } boolean process(Object o) { String command = (String) o; boolean err = false; try { panel.setNcStreamFile(command); } catch (FileNotFoundException ioe) { JOptionPane.showMessageDialog(null, "CdmremotePanel cant open " + command + "\n" + ioe.getMessage()); err = true; } catch (Exception e) { StringWriter sw = new StringWriter(5000); e.printStackTrace(new PrintWriter(sw)); detailTA.setText(sw.toString()); detailWindow.show(); err = true; } return !err; } void save() { panel.save(); super.save(); } void closeOpenFiles() throws IOException { panel.closeOpenFiles(); } } // new ucar.nc2.ft.fmrc stuff private class FmrcPanel extends OpPanel { Fmrc2Panel table; FmrcPanel(PreferencesExt dbPrefs) { super(dbPrefs, "collection:", true, false); table = new Fmrc2Panel(prefs); table.addPropertyChangeListener(new java.beans.PropertyChangeListener() { public void propertyChange(java.beans.PropertyChangeEvent e) { if (e.getPropertyName().equals("openNetcdfFile")) { if (e.getNewValue() instanceof String) openNetcdfFile((String) e.getNewValue()); else openNetcdfFile((NetcdfFile) e.getNewValue()); } else if (e.getPropertyName().equals("openCoordSys")) { if (e.getNewValue() instanceof String) openCoordSystems((String) e.getNewValue()); else openCoordSystems((NetcdfDataset) e.getNewValue()); } else if (e.getPropertyName().equals("openGridDataset")) { if (e.getNewValue() instanceof String) openGridDataset((String) e.getNewValue()); else openGridDataset((GridDataset) e.getNewValue()); } } }); add(table, BorderLayout.CENTER); AbstractButton infoButton = BAMutil.makeButtcon("Information", "Detail Info", false); infoButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Formatter f = new Formatter(); try { table.showInfo(f); } catch (IOException e1) { StringWriter sw = new StringWriter(5000); e1.printStackTrace(new PrintWriter(sw)); f.format("%s", sw.toString()); } detailTA.setText(f.toString()); detailTA.gotoTop(); detailWindow.show(); } }); buttPanel.add(infoButton); AbstractButton collectionButton = BAMutil.makeButtcon("Information", "Collection Parsing Info", false); collectionButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { table.showCollectionInfo(true); } }); buttPanel.add(collectionButton); AbstractButton viewButton = BAMutil.makeButtcon("Dump", "Show Dataset", false); viewButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { table.showDataset(); } catch (IOException e1) { StringWriter sw = new StringWriter(5000); e1.printStackTrace(new PrintWriter(sw)); detailTA.setText(sw.toString()); detailTA.gotoTop(); detailWindow.show(); } } }); buttPanel.add(viewButton); } boolean process(Object o) { String command = (String) o; if (command == null) return false; /* if (fmrc != null) { try { fmrc.close(); } catch (IOException ioe) { } } */ try { table.setFmrc(command); return true; } catch (Exception ioe) { StringWriter sw = new StringWriter(5000); ioe.printStackTrace(new PrintWriter(sw)); detailTA.setText(sw.toString()); detailTA.gotoTop(); detailWindow.show(); } return false; } void save() { table.save(); super.save(); } void closeOpenFiles() throws IOException { table.closeOpenFiles(); } } // new Fmrc Collection Metadata storage in bdb private class FmrcCollectionPanel extends OpPanel { FmrcCollectionTable table; FmrcCollectionPanel(PreferencesExt dbPrefs) { super(dbPrefs, "collection:", true, false); table = new FmrcCollectionTable(prefs); add(table, BorderLayout.CENTER); AbstractButton infoButton = BAMutil.makeButtcon("Information", "Detail Info", false); infoButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Formatter f = new Formatter(); try { table.showInfo(f); } catch (IOException e1) { StringWriter sw = new StringWriter(5000); e1.printStackTrace(new PrintWriter(sw)); f.format("%s", sw.toString()); } detailTA.setText(f.toString()); detailTA.gotoTop(); detailWindow.show(); } }); buttPanel.add(infoButton); AbstractButton refreshButton = BAMutil.makeButtcon("Undo", "Refresh", false); refreshButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { table.refresh(); } catch (Exception e1) { Formatter f = new Formatter(); StringWriter sw = new StringWriter(5000); e1.printStackTrace(new PrintWriter(sw)); f.format("%s", sw.toString()); detailTA.setText(f.toString()); detailTA.gotoTop(); detailWindow.show(); } } }); buttPanel.add(refreshButton); } boolean process(Object o) { String command = (String) o; if (command == null) return false; try { // table.setCacheRoot(command); return true; } catch (Exception ioe) { StringWriter sw = new StringWriter(5000); ioe.printStackTrace(new PrintWriter(sw)); detailTA.setText(sw.toString()); detailTA.gotoTop(); detailWindow.show(); } return false; } void closeOpenFiles() { } void save() { table.save(); super.save(); } } private class GeoGridPanel extends OpPanel { GeoGridTable dsTable; JSplitPane split; IndependentWindow viewerWindow, imageWindow; GridUI gridUI = null; ImageViewPanel imageViewer; NetcdfDataset ds = null; GeoGridPanel(PreferencesExt prefs) { super(prefs, "dataset:", true, false); dsTable = new GeoGridTable(prefs, true); add(dsTable, BorderLayout.CENTER); AbstractButton viewButton = BAMutil.makeButtcon("alien", "Grid Viewer", false); viewButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (ds != null) { GridDataset gridDataset = dsTable.getGridDataset(); if (gridUI == null) makeGridUI(); gridUI.setDataset(gridDataset); viewerWindow.show(); } } }); buttPanel.add(viewButton); AbstractButton imageButton = BAMutil.makeButtcon("VCRMovieLoop", "Image Viewer", false); imageButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (ds != null) { GridDatatype grid = dsTable.getGrid(); if (grid == null) return; if (imageWindow == null) makeImageWindow(); imageViewer.setImageFromGrid(grid); imageWindow.show(); } } }); buttPanel.add(imageButton); dsTable.addExtra(buttPanel, fileChooser); } private void makeGridUI() { // a little tricky to get the parent right for GridUI viewerWindow = new IndependentWindow("Grid Viewer", BAMutil.getImage("netcdfUI")); gridUI = new GridUI((PreferencesExt) prefs.node("GridUI"), viewerWindow, fileChooser, 800); gridUI.addMapBean(new WorldMapBean()); gridUI.addMapBean(new ShapeFileBean("WorldDetailMap", "Global Detailed Map", "WorldDetailMap", WorldDetailMap)); gridUI.addMapBean(new ShapeFileBean("USDetailMap", "US Detailed Map", "USMap", USMap)); viewerWindow.setComponent(gridUI); Rectangle bounds = (Rectangle) mainPrefs.getBean(GRIDVIEW_FRAME_SIZE, new Rectangle(77, 22, 700, 900)); if (bounds.x < 0) bounds.x = 0; if (bounds.y < 0) bounds.x = 0; viewerWindow.setBounds(bounds); } private void makeImageWindow() { imageWindow = new IndependentWindow("Grid Image Viewer", BAMutil.getImage("netcdfUI")); imageViewer = new ImageViewPanel(null); imageWindow.setComponent(imageViewer); imageWindow.setBounds((Rectangle) mainPrefs.getBean(GRIDIMAGE_FRAME_SIZE, new Rectangle(77, 22, 700, 900))); } boolean process(Object o) { String command = (String) o; boolean err = false; NetcdfDataset newds; try { newds = NetcdfDataset.openDataset(command, true, null); if (newds == null) { JOptionPane.showMessageDialog(null, "NetcdfDataset.open cant open " + command); return false; } setDataset(newds); } catch (FileNotFoundException ioe) { JOptionPane.showMessageDialog(null, "NetcdfDataset.open cant open " + command + "\n" + ioe.getMessage()); //ioe.printStackTrace(); err = true; } catch (Throwable ioe) { ioe.printStackTrace(); StringWriter sw = new StringWriter(5000); ioe.printStackTrace(new PrintWriter(sw)); detailTA.setText(sw.toString()); detailWindow.show(); err = true; } return !err; } void closeOpenFiles() throws IOException { if (ds != null) ds.close(); ds = null; dsTable.clear(); if (gridUI != null) gridUI.clear(); } void setDataset(NetcdfDataset newds) { if (newds == null) return; try { if (ds != null) ds.close(); } catch (IOException ioe) { System.out.printf("close failed %n"); } Formatter parseInfo = new Formatter(); this.ds = newds; try { dsTable.setDataset(newds, parseInfo); } catch (IOException e) { String info = parseInfo.toString(); if (info.length() > 0) { detailTA.setText(info); detailWindow.show(); } e.printStackTrace(); return; } setSelectedItem(newds.getLocation()); } void setDataset(GridDataset gds) { if (gds == null) return; try { if (ds != null) ds.close(); } catch (IOException ioe) { System.out.printf("close failed %n"); } this.ds = (NetcdfDataset) gds.getNetcdfFile(); try { dsTable.setDataset(gds); } catch (IOException e) { e.printStackTrace(); return; } setSelectedItem(gds.getLocationURI()); } void save() { super.save(); dsTable.save(); if (gridUI != null) gridUI.storePersistentData(); if (viewerWindow != null) mainPrefs.putBeanObject(GRIDVIEW_FRAME_SIZE, viewerWindow.getBounds()); if (imageWindow != null) mainPrefs.putBeanObject(GRIDIMAGE_FRAME_SIZE, imageWindow.getBounds()); } } private class CoveragePanel extends OpPanel { CoverageTable dsTable; CoverageDisplay display; JSplitPane split; IndependentWindow viewerWindow; NetcdfDataset ds = null; CoveragePanel(PreferencesExt prefs) { super(prefs, "dataset:", true, false); dsTable = new CoverageTable(prefs); add(dsTable, BorderLayout.CENTER); AbstractButton viewButton = BAMutil.makeButtcon("alien", "Grid Viewer", false); viewButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (ds != null) { CoverageDataset gridDataset = dsTable.getCoverageDataset(); if (gridDataset == null) return; if (display == null) makeDisplay(); display.setDataset(gridDataset); viewerWindow.show(); } } }); buttPanel.add(viewButton); dsTable.addExtra(buttPanel, fileChooser); } private void makeDisplay() { viewerWindow = new IndependentWindow("Coverage Viewer", BAMutil.getImage("netcdfUI")); display = new CoverageDisplay((PreferencesExt) prefs.node("CoverageDisplay"), viewerWindow, fileChooser, 800); display.addMapBean(new WorldMapBean()); display.addMapBean(new ShapeFileBean("WorldDetailMap", "Global Detailed Map", "WorldDetailMap", WorldDetailMap)); display.addMapBean(new ShapeFileBean("USDetailMap", "US Detailed Map", "USMap", USMap)); viewerWindow.setComponent(display); Rectangle bounds = (Rectangle) mainPrefs.getBean(GRIDVIEW_FRAME_SIZE, new Rectangle(77, 22, 700, 900)); if (bounds.x < 0) bounds.x = 0; if (bounds.y < 0) bounds.x = 0; viewerWindow.setBounds(bounds); } boolean process(Object o) { String command = (String) o; boolean err = false; NetcdfDataset newds; try { newds = NetcdfDataset.openDataset(command, true, null); if (newds == null) { JOptionPane.showMessageDialog(null, "NetcdfDataset.open cant open " + command); return false; } setDataset(newds); } catch (FileNotFoundException ioe) { JOptionPane.showMessageDialog(null, "NetcdfDataset.open cant open " + command + "\n" + ioe.getMessage()); //ioe.printStackTrace(); err = true; } catch (Throwable ioe) { ioe.printStackTrace(); StringWriter sw = new StringWriter(5000); ioe.printStackTrace(new PrintWriter(sw)); detailTA.setText(sw.toString()); detailWindow.show(); err = true; } return !err; } void closeOpenFiles() throws IOException { if (ds != null) ds.close(); ds = null; } void setDataset(NetcdfDataset newds) { if (newds == null) return; try { if (ds != null) ds.close(); } catch (IOException ioe) { System.out.printf("close failed %n"); } Formatter parseInfo = new Formatter(); this.ds = newds; try { dsTable.setDataset(newds, parseInfo); } catch (IOException e) { String info = parseInfo.toString(); if (info.length() > 0) { detailTA.setText(info); detailWindow.show(); } e.printStackTrace(); return; } setSelectedItem(newds.getLocation()); } void setDataset(CoverageDataset gds) { if (gds == null) return; try { if (ds != null) ds.close(); } catch (IOException ioe) { System.out.printf("close failed %n"); } try { dsTable.setDataset(gds); } catch (IOException e) { e.printStackTrace(); return; } setSelectedItem(gds.getLocation()); } void save() { super.save(); dsTable.save(); if (viewerWindow != null) mainPrefs.putBeanObject(GRIDVIEW_FRAME_SIZE, viewerWindow.getBounds()); } } private class RadialPanel extends OpPanel { RadialDatasetTable dsTable; JSplitPane split; RadialDatasetSweep ds = null; RadialPanel(PreferencesExt prefs) { super(prefs, "dataset:", true, false); dsTable = new RadialDatasetTable(prefs); add(dsTable, BorderLayout.CENTER); AbstractButton infoButton = BAMutil.makeButtcon("Information", "Parse Info", false); infoButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { RadialDatasetSweep radialDataset = dsTable.getRadialDataset(); String info; if ((radialDataset != null) && ((info = radialDataset.getDetailInfo()) != null)) { detailTA.setText(info); detailTA.gotoTop(); detailWindow.show(); } } }); buttPanel.add(infoButton); } boolean process(Object o) { String command = (String) o; boolean err = false; NetcdfDataset newds; try { newds = NetcdfDataset.openDataset(command, true, null); if (newds == null) { JOptionPane.showMessageDialog(null, "NetcdfDataset.open cant open " + command); return false; } Formatter errlog = new Formatter(); RadialDatasetSweep rds = (RadialDatasetSweep) FeatureDatasetFactoryManager.wrap(FeatureType.RADIAL, newds, null, errlog); if (rds == null) { JOptionPane.showMessageDialog(null, "FeatureDatasetFactoryManager cant open " + command + "as RADIAL dataset\n" + errlog.toString()); err = true; } else { setDataset(rds); } } catch (FileNotFoundException ioe) { JOptionPane.showMessageDialog(null, "NetcdfDataset.open cant open " + command + "\n" + ioe.getMessage()); ioe.printStackTrace(); err = true; } catch (IOException ioe) { StringWriter sw = new StringWriter(5000); ioe.printStackTrace(new PrintWriter(sw)); detailTA.setText(sw.toString()); detailWindow.show(); err = true; } return !err; } void setDataset(ucar.nc2.dt.RadialDatasetSweep newds) { if (newds == null) return; try { if (ds != null) ds.close(); } catch (IOException ioe) { System.out.printf("close failed %n"); } this.ds = newds; dsTable.setDataset(newds); setSelectedItem(newds.getLocationURI()); } void closeOpenFiles() throws IOException { if (ds != null) ds.close(); ds = null; } void save() { super.save(); dsTable.save(); } } private class DatasetViewerPanel extends OpPanel { DatasetViewer dsViewer; JSplitPane split; NetcdfFile ncfile = null; boolean jni; DatasetViewerPanel(PreferencesExt dbPrefs, boolean jni) { super(dbPrefs, "dataset:"); this.jni = jni; dsViewer = new DatasetViewer(dbPrefs, fileChooser); add(dsViewer, BorderLayout.CENTER); AbstractButton infoButton = BAMutil.makeButtcon("Information", "Detail Info", false); infoButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (ncfile != null) { detailTA.setText(ncfile.getDetailInfo()); detailTA.gotoTop(); detailWindow.show(); } } }); buttPanel.add(infoButton); AbstractAction dumpAction = new AbstractAction() { public void actionPerformed(ActionEvent e) { NetcdfFile ds = dsViewer.getDataset(); if (ds != null) { if (ncdumpPanel == null) { makeComponent(tabbedPane, "NCDump"); } ncdumpPanel.setNetcdfFile(ds); tabbedPane.setSelectedComponent(ncdumpPanel); } } }; BAMutil.setActionProperties(dumpAction, "Dump", "NCDump", false, 'D', -1); BAMutil.addActionToContainer(buttPanel, dumpAction); dsViewer.addActions(buttPanel); } boolean process(Object o) { String location = (String) o; boolean err = false; NetcdfFile ncnew; try { if (ncfile != null) ncfile.close(); } catch (IOException ioe) { System.out.printf("close failed %n"); } try { if (jni) { Nc4Iosp iosp = new Nc4Iosp(NetcdfFileWriter.Version.netcdf4); ncnew = new NetcdfFileSubclass(iosp, location); ucar.unidata.io.RandomAccessFile raf = new ucar.unidata.io.RandomAccessFile(location, "r"); iosp.open(raf, ncnew, null); } else { ncnew = openFile(location, addCoords, null); } if (ncnew != null) setDataset(ncnew); } catch (Exception ioe) { StringWriter sw = new StringWriter(5000); ioe.printStackTrace(new PrintWriter(sw)); detailTA.setText(sw.toString()); detailWindow.show(); err = true; } return !err; } void closeOpenFiles() throws IOException { if (ncfile != null) ncfile.close(); ncfile = null; dsViewer.clear(); } void setDataset(NetcdfFile nc) { try { if (ncfile != null) ncfile.close(); ncfile = null; } catch (IOException ioe) { System.out.printf("close failed %n"); } ncfile = nc; if (ncfile != null) { dsViewer.setDataset(nc); setSelectedItem(nc.getLocation()); } } void save() { super.save(); dsViewer.save(); } } private class DatasetWriterPanel extends OpPanel { DatasetWriter dsWriter; JSplitPane split; NetcdfFile ncfile = null; DatasetWriterPanel(PreferencesExt dbPrefs) { super(dbPrefs, "dataset:"); dsWriter = new DatasetWriter(dbPrefs, fileChooser); add(dsWriter, BorderLayout.CENTER); dsWriter.addActions(buttPanel); } boolean process(Object o) { String command = (String) o; boolean err = false; try { if (ncfile != null) ncfile.close(); } catch (IOException ioe) { System.out.printf("close failed %n"); } try { NetcdfFile ncnew = openFile(command, addCoords, null); if (ncnew != null) setDataset(ncnew); } catch (Exception ioe) { StringWriter sw = new StringWriter(5000); ioe.printStackTrace(new PrintWriter(sw)); detailTA.setText(sw.toString()); detailWindow.show(); err = true; } return !err; } void closeOpenFiles() throws IOException { if (ncfile != null) ncfile.close(); ncfile = null; } void setDataset(NetcdfFile nc) { try { if (ncfile != null) ncfile.close(); ncfile = null; } catch (IOException ioe) { System.out.printf("close failed %n"); } ncfile = nc; if (ncfile != null) { dsWriter.setDataset(nc); setSelectedItem(nc.getLocation()); } } void save() { super.save(); dsWriter.save(); } } private class FeatureScanPanel extends OpPanel { ucar.nc2.ui.FeatureScanPanel ftTable; final FileManager dirChooser; FeatureScanPanel(PreferencesExt prefs) { super(prefs, "dir:", false, false); dirChooser = new FileManager(parentFrame, null, null, (PreferencesExt) prefs.node("FeatureScanFileManager")); ftTable = new ucar.nc2.ui.FeatureScanPanel(prefs); add(ftTable, BorderLayout.CENTER); ftTable.addPropertyChangeListener(new java.beans.PropertyChangeListener() { public void propertyChange(java.beans.PropertyChangeEvent e) { if (e.getPropertyName().equals("openPointFeatureDataset")) { String datasetName = (String) e.getNewValue(); openPointFeatureDataset(datasetName); } else if (e.getPropertyName().equals("openNetcdfFile")) { String datasetName = (String) e.getNewValue(); openNetcdfFile(datasetName); } else if (e.getPropertyName().equals("openCoordSystems")) { String datasetName = (String) e.getNewValue(); openCoordSystems(datasetName); } else if (e.getPropertyName().equals("openNcML")) { String datasetName = (String) e.getNewValue(); openNcML(datasetName); } else if (e.getPropertyName().equals("openGridDataset")) { String datasetName = (String) e.getNewValue(); openGridDataset(datasetName); } else if (e.getPropertyName().equals("openCoverageDataset")) { String datasetName = (String) e.getNewValue(); openCoverageDataset(datasetName); } else if (e.getPropertyName().equals("openRadialDataset")) { String datasetName = (String) e.getNewValue(); openRadialDataset(datasetName); } } }); dirChooser.getFileChooser().setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); dirChooser.setCurrentDirectory(prefs.get("currDir", ".")); AbstractAction fileAction = new AbstractAction() { public void actionPerformed(ActionEvent e) { String filename = dirChooser.chooseFilename(); if (filename == null) return; cb.setSelectedItem(filename); } }; BAMutil.setActionProperties(fileAction, "FileChooser", "open Local dataset...", false, 'L', -1); BAMutil.addActionToContainer(buttPanel, fileAction); } boolean process(Object o) { String command = (String) o; return ftTable.setScanDirectory(command); } void closeOpenFiles() { ftTable.clear(); } void save() { dirChooser.save(); ftTable.save(); prefs.put("currDir", dirChooser.getCurrentDirectory()); super.save(); } } private class CollectionSpecPanel extends OpPanel { CollectionSpecTable table; CollectionSpecPanel(PreferencesExt dbPrefs) { super(dbPrefs, "collection spec:", true, false); table = new CollectionSpecTable(prefs); add(table, BorderLayout.CENTER); AbstractButton infoButton = BAMutil.makeButtcon("Information", "Detail Info", false); infoButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Formatter f = new Formatter(); try { table.showCollection(f); } catch (Exception e1) { StringWriter sw = new StringWriter(5000); e1.printStackTrace(new PrintWriter(sw)); f.format("%s", sw.toString()); } detailTA.setText(f.toString()); detailTA.gotoTop(); detailWindow.show(); } }); buttPanel.add(infoButton); } boolean process(Object o) { String command = (String) o; if (command == null) return false; try { table.setCollection(command); return true; } catch (Exception ioe) { StringWriter sw = new StringWriter(5000); ioe.printStackTrace(new PrintWriter(sw)); detailTA.setText(sw.toString()); detailTA.gotoTop(); detailWindow.show(); } return false; } void closeOpenFiles() { } void save() { table.save(); super.save(); } } private class DirectoryPartitionPanel extends OpPanel { DirectoryPartitionViewer table; DirectoryPartitionPanel(PreferencesExt dbPrefs) { super(dbPrefs, "collection:", false, false, false); table = new DirectoryPartitionViewer(prefs, topPanel, buttPanel); add(table, BorderLayout.CENTER); table.addPropertyChangeListener(new java.beans.PropertyChangeListener() { public void propertyChange(java.beans.PropertyChangeEvent e) { if (e.getPropertyName().equals("openGrib2Collection")) { String collectionName = (String) e.getNewValue(); openGrib2Collection(collectionName); } } }); } boolean process(Object o) { String command = (String) o; if (command == null) return false; try { //table.setCollectionFromConfig(command); return true; } catch (Exception ioe) { ioe.printStackTrace(); StringWriter sw = new StringWriter(5000); ioe.printStackTrace(new PrintWriter(sw)); detailTA.setText(sw.toString()); detailTA.gotoTop(); detailWindow.show(); } return false; } void closeOpenFiles() { } void save() { table.save(); super.save(); table.clear(); } } private class PointFeaturePanel extends OpPanel { PointFeatureDatasetViewer pfViewer; JSplitPane split; FeatureDatasetPoint pfDataset = null; JComboBox<FeatureType> types; PointFeaturePanel(PreferencesExt dbPrefs) { super(dbPrefs, "dataset:", true, false); pfViewer = new PointFeatureDatasetViewer(dbPrefs, buttPanel); add(pfViewer, BorderLayout.CENTER); types = new JComboBox<>(); for (FeatureType ft : FeatureType.values()) types.addItem(ft); types.getModel().setSelectedItem(FeatureType.ANY_POINT); buttPanel.add(types); AbstractButton infoButton = BAMutil.makeButtcon("Information", "Dataset Info", false); infoButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (pfDataset == null) return; Formatter f = new Formatter(); pfDataset.getDetailInfo(f); detailTA.setText(f.toString()); detailTA.appendLine(" detailTA.appendLine(getCapabilities(pfDataset)); detailTA.gotoTop(); detailWindow.show(); } }); buttPanel.add(infoButton); /* AbstractButton collectionButton = BAMutil.makeButtcon("Information", "Collection Parsing Info", false); collectionButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Formatter f = new Formatter(); pfViewer.showCollectionInfo(f); detailTA.setText(f.toString()); detailTA.gotoTop(); detailWindow.show(); } }); buttPanel.add(collectionButton); */ AbstractButton xmlButton = BAMutil.makeButtcon("XML", "pointConfig.xml", false); xmlButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (pfDataset == null) return; Formatter f = new Formatter(); ucar.nc2.ft.point.standard.PointConfigXML.writeConfigXML(pfDataset, f); detailTA.setText(f.toString()); detailTA.gotoTop(); detailWindow.show(); } }); buttPanel.add(xmlButton); AbstractButton calcButton = BAMutil.makeButtcon("V3", "CalcBounds", false); calcButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (pfDataset == null) return; Formatter f = new Formatter(); try { pfDataset.calcBounds(); pfDataset.getDetailInfo(f); detailTA.setText(f.toString()); } catch (IOException ioe) { StringWriter sw = new StringWriter(5000); ioe.printStackTrace(new PrintWriter(sw)); detailTA.setText(sw.toString()); } detailTA.gotoTop(); detailWindow.show(); } }); buttPanel.add(calcButton); } boolean process(Object o) { String location = (String) o; return setPointFeatureDataset((FeatureType) types.getSelectedItem(), location); } void closeOpenFiles() throws IOException { if (pfDataset != null) pfDataset.close(); pfDataset = null; pfViewer.clear(); } void save() { super.save(); pfViewer.save(); } private boolean setPointFeatureDataset(FeatureType type, String location) { if (location == null) return false; try { if (pfDataset != null) pfDataset.close(); } catch (IOException ioe) { System.out.printf("close failed %n"); } detailTA.clear(); Formatter log = new Formatter(); try { FeatureDataset featureDataset = FeatureDatasetFactoryManager.open(type, location, null, log); if (featureDataset == null) { JOptionPane.showMessageDialog(null, "Can't open " + location + ": " + log); return false; } if (!(featureDataset instanceof FeatureDatasetPoint)) { JOptionPane.showMessageDialog(null, location + " could not be opened as a PointFeatureDataset"); return false; } pfDataset = (FeatureDatasetPoint) featureDataset; pfViewer.setDataset(pfDataset); setSelectedItem(location); return true; } catch (IOException e) { String message = e.getClass().getName() + ": " + e.getMessage(); JOptionPane.showMessageDialog(this, message); return false; } catch (Throwable e) { StringWriter sw = new StringWriter(5000); e.printStackTrace(new PrintWriter(sw)); detailTA.setText(log.toString()); detailTA.setText(sw.toString()); detailWindow.show(); JOptionPane.showMessageDialog(this, e.getMessage()); return false; } } private boolean setPointFeatureDataset(FeatureDatasetPoint pfd) { try { if (pfDataset != null) pfDataset.close(); } catch (IOException ioe) { System.out.printf("close failed %n"); } detailTA.clear(); try { pfDataset = pfd; pfViewer.setDataset(pfDataset); setSelectedItem(pfDataset.getLocation()); return true; } catch (Throwable e) { StringWriter sw = new StringWriter(5000); e.printStackTrace(new PrintWriter(sw)); detailTA.setText(sw.toString()); detailWindow.show(); JOptionPane.showMessageDialog(this, e.getMessage()); return false; } } private String getCapabilities(FeatureDatasetPoint fdp) { ucar.nc2.ft.point.writer.FeatureDatasetPointXML xmlWriter = new ucar.nc2.ft.point.writer.FeatureDatasetPointXML(fdp, null); return xmlWriter.getCapabilities(); } } private class WmsPanel extends OpPanel { WmsViewer wmsViewer; JSplitPane split; JComboBox<String> types; WmsPanel(PreferencesExt dbPrefs) { super(dbPrefs, "dataset:", true, false); wmsViewer = new WmsViewer(dbPrefs, frame); add(wmsViewer, BorderLayout.CENTER); buttPanel.add(new JLabel("version:")); types = new JComboBox<>(); types.addItem("1.3.0"); types.addItem("1.1.1"); types.addItem("1.0.0"); buttPanel.add(types); AbstractButton infoButton = BAMutil.makeButtcon("Information", "Detail Info", false); infoButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { detailTA.setText(wmsViewer.getDetailInfo()); detailTA.gotoTop(); detailWindow.show(); } }); buttPanel.add(infoButton); } boolean process(Object o) { String location = (String) o; return wmsViewer.setDataset((String) types.getSelectedItem(), location); } void closeOpenFiles() { } void save() { super.save(); wmsViewer.save(); } } private class StationRadialPanel extends OpPanel { StationRadialViewer radialViewer; JSplitPane split; ucar.nc2.ft.FeatureDataset radarCollectionDataset = null; StationRadialPanel(PreferencesExt dbPrefs) { super(dbPrefs, "dataset:", true, false); radialViewer = new StationRadialViewer(dbPrefs); add(radialViewer, BorderLayout.CENTER); AbstractButton infoButton = BAMutil.makeButtcon("Information", "Dataset Info", false); infoButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (radarCollectionDataset != null) { Formatter info = new Formatter(); radarCollectionDataset.getDetailInfo(info); detailTA.setText(info.toString()); detailTA.gotoTop(); detailWindow.show(); } } }); buttPanel.add(infoButton); } boolean process(Object o) { String location = (String) o; return setStationRadialDataset(location); } void closeOpenFiles() throws IOException { if (radarCollectionDataset != null) radarCollectionDataset.close(); radarCollectionDataset = null; } void save() { super.save(); radialViewer.save(); } boolean setStationRadialDataset(String location) { if (location == null) return false; try { if (radarCollectionDataset != null) radarCollectionDataset.close(); } catch (IOException ioe) { System.out.printf("close failed %n"); } //StringBuilder log = new StringBuilder(); try { ThreddsDataFactory.Result result = threddsDataFactory.openFeatureDataset(FeatureType.STATION_RADIAL, location, null); if (result.fatalError) { JOptionPane.showMessageDialog(null, "Can't open " + location + ": " + result.errLog.toString()); return false; } setStationRadialDataset(result.featureDataset); return true; } catch (Exception e) { StringWriter sw = new StringWriter(5000); e.printStackTrace(new PrintWriter(sw)); detailTA.setText(log.toString()); detailTA.appendLine(sw.toString()); detailWindow.show(); JOptionPane.showMessageDialog(this, e.getMessage()); return false; } } boolean setStationRadialDataset(ucar.nc2.ft.FeatureDataset dataset) { if (dataset == null) return false; try { if (radarCollectionDataset != null) radarCollectionDataset.close(); } catch (IOException ioe) { System.out.printf("close failed %n"); } radarCollectionDataset = dataset; radialViewer.setDataset(radarCollectionDataset); setSelectedItem(radarCollectionDataset.getLocation()); return true; } } /* private class TrajectoryTablePanel extends OpPanel { TrajectoryObsViewer viewer; JSplitPane split; TrajectoryObsDataset ds = null; TrajectoryTablePanel(PreferencesExt dbPrefs) { super(dbPrefs, "dataset:", true, false); viewer = new TrajectoryObsViewer(dbPrefs); add(viewer, BorderLayout.CENTER); AbstractButton infoButton = BAMutil.makeButtcon("Information", "Dataset Info", false); infoButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String info; if ((ds != null) && ((info = ds.getDetailInfo()) != null)) { detailTA.setText(info); detailTA.gotoTop(); detailWindow.show(); } } }); buttPanel.add(infoButton); } boolean process(Object o) { String location = (String) o; return setStationObsDataset(location); } void save() { super.save(); viewer.save(); } void closeOpenFiles() throws IOException { if (ds != null) ds.close(); ds = null; } boolean setStationObsDataset(String location) { if (location == null) return false; try { if (ds != null) ds.close(); } catch (IOException ioe) { } ByteArrayOutputStream bos = new ByteArrayOutputStream(10000); try { StringBuilder errlog = new StringBuilder(); ds = (TrajectoryObsDataset) TypedDatasetFactory.open(FeatureType.TRAJECTORY, location, null, errlog); if (ds == null) { JOptionPane.showMessageDialog(null, "Can't open " + location + ": " + errlog); return false; } viewer.setDataset(ds); setSelectedItem(location); return true; } catch (IOException ioe) { ioe.printStackTrace(new PrintStream(bos)); detailTA.appendLine(bos.toString()); detailWindow.show(); return false; } } boolean setStationObsDataset(TrajectoryObsDataset sobsDataset) { if (sobsDataset == null) return false; try { if (ds != null) ds.close(); } catch (IOException ioe) { } viewer.setDataset(sobsDataset); ds = sobsDataset; setSelectedItem(ds.getLocationURI()); return true; } } */ private class ImagePanel extends OpPanel { ImageViewPanel imagePanel; JSplitPane split; ImagePanel(PreferencesExt dbPrefs) { super(dbPrefs, "dataset:", true, false); imagePanel = new ImageViewPanel(buttPanel); add(imagePanel, BorderLayout.CENTER); } boolean process(Object o) { String command = (String) o; try { if (null != command) imagePanel.setImageFromUrl(command); } catch (Exception ioe) { ioe.printStackTrace(); StringWriter sw = new StringWriter(5000); ioe.printStackTrace(new PrintWriter(sw)); detailTA.setText(sw.toString()); detailWindow.show(); return false; } return true; } void setImageLocation(String location) { imagePanel.setImageFromUrl(location); setSelectedItem(location); } void closeOpenFiles() throws IOException { } } private class GeotiffPanel extends OpPanel { TextHistoryPane ta; GeotiffPanel(PreferencesExt p) { super(p, "netcdf:", true, false); ta = new TextHistoryPane(true); add(ta, BorderLayout.CENTER); JButton readButton = new JButton("read geotiff"); readButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String item = cb.getSelectedItem().toString(); String fname = item.trim(); read(fname); } }); buttPanel.add(readButton); } boolean process(Object o) { String filename = (String) o; GridDataset gridDs = null; try { gridDs = ucar.nc2.dt.grid.GridDataset.open(filename); java.util.List grids = gridDs.getGrids(); if (grids.size() == 0) { System.out.println("No grids found."); return false; } GridDatatype grid = (GridDatatype) grids.get(0); ucar.ma2.Array data = grid.readDataSlice(0, 0, -1, -1); // first time, level String fileOut = fileChooser.chooseFilenameToSave(filename + ".tif"); if (fileOut == null) return false; ucar.nc2.geotiff.GeotiffWriter writer = new ucar.nc2.geotiff.GeotiffWriter(fileOut); writer.writeGrid(gridDs, grid, data, false); read(fileOut); JOptionPane.showMessageDialog(null, "File written to " + fileOut); } catch (IOException ioe) { ioe.printStackTrace(); return false; } finally { try { if (gridDs != null) gridDs.close(); } catch (IOException ioe) { System.out.printf("close failed %n"); } } return true; } void read(String filename) { GeoTiff geotiff = null; try { geotiff = new GeoTiff(filename); geotiff.read(); ta.setText(geotiff.showInfo()); } catch (IOException ioe) { ioe.printStackTrace(); } finally { try { if (geotiff != null) geotiff.close(); } catch (IOException ioe) { System.out.printf("close failed %n"); } } } void closeOpenFiles() throws IOException { } } private interface GetDataRunnable { public void run(Object o) throws IOException; } private static class GetDataTask extends ProgressMonitorTask implements ucar.nc2.util.CancelTask { GetDataRunnable getData; Object o; String name, errMsg = null; GetDataTask(GetDataRunnable getData, String name, Object o) { this.getData = getData; this.name = name; this.o = o; } public void run() { try { getData.run(o); } catch (FileNotFoundException ioe) { errMsg = ("Cant open " + name + " " + ioe.getMessage()); // ioe.printStackTrace(); success = false; done = true; return; } catch (Exception e) { StringWriter sw = new StringWriter(5000); e.printStackTrace(new PrintWriter(sw)); errMsg = sw.toString(); success = false; done = true; return; } success = true; done = true; } } // Dynamic proxy for Debug private static class DebugProxyHandler implements java.lang.reflect.InvocationHandler { @Override public Object invoke(Object proxy, java.lang.reflect.Method method, Object[] args) throws Throwable { if (method.getName().equals("toString")) return super.toString(); // System.out.println("proxy= "+proxy+" method = "+method+" args="+args); if (method.getName().equals("isSet")) { return Debug.isSet((String) args[0]); } if (method.getName().equals("set")) { ucar.util.prefs.ui.Debug.set((String) args[0], (Boolean) args[1]); return null; } return Boolean.FALSE; } } // About Window private class AboutWindow extends javax.swing.JWindow { public AboutWindow() { super(parentFrame); JLabel lab1 = new JLabel("<html> <body bgcolor=\"#FFECEC\"> <center>" + "<h1>Netcdf Tools User Interface (ToolsUI)</h1>" + "<b>" + getVersion() + "</b>" + "<br><i>http: "<br><b><i>Developers:</b>John Caron, Ethan Davis, Sean Arms, Dennis Heimbinger, Lansing Madry, Ryan May, Christian Ward-Garrison</i></b>" + "</center>" + "<br><br>With thanks to these <b>Open Source</b> contributors:" + "<ul>" + "<li><b>ADDE/VisAD</b>: Bill Hibbard, Don Murray, Tom Whittaker, et al (http: "<li><b>Apache HTTP Components</b> libraries: (http://hc.apache.org/)</li>" + "<li><b>Apache Jakarta Commons</b> libraries: (http: "<li><b>IDV:</b> Yuan Ho, Julien Chastang, Don Murray, Jeff McWhirter, Yuan H (http: "<li><b>Joda Time</b> library: Stephen Colebourne (http: "<li><b>JDOM</b> library: Jason Hunter, Brett McLaughlin et al (www.jdom.org)</li>" + "<li><b>JGoodies</b> library: Karsten Lentzsch (www.jgoodies.com)</li>" + "<li><b>JPEG-2000</b> Java library: (http: "<li><b>JUnit</b> library: Erich Gamma, Kent Beck, Erik Meade, et al (http://sourceforge.net/projects/junit/)</li>" + "<li><b>NetCDF C Library</b> library: Russ Rew, Ward Fisher, Dennis Heimbinger</li>" + "<li><b>OPeNDAP Java</b> library: Dennis Heimbinger, James Gallagher, Nathan Potter, Don Denbo, et. al.(http://opendap.org)</li>" + "<li><b>Protobuf serialization</b> library: Google (http://code.google.com/p/protobuf/)</li>" + "<li><b>Simple Logging Facade for Java</b> library: Ceki Gulcu (http: "<li><b>Spring lightweight framework</b> library: Rod Johnson, et. al.(http: "<li><b>Imaging utilities:</b>: Richard Eigenmann</li>" + "<li><b>Udunits:</b>: Steve Emmerson</li>" + "</ul><center>Special thanks to <b>Sun/Oracle</b> (java.oracle.com) for the platform on which we stand." + "</center></body></html> "); JPanel main = new JPanel(new BorderLayout()); main.setBorder(new javax.swing.border.LineBorder(Color.BLACK)); main.setBackground(new Color(0xFFECEC)); JLabel icon = new JLabel(new ImageIcon(BAMutil.getImage("netcdfUI"))); icon.setOpaque(true); icon.setBackground(new Color(0xFFECEC)); JLabel threddsLogo = new JLabel(Resource.getIcon(BAMutil.getResourcePath() + "threddsLogo.png", false)); threddsLogo.setBackground(new Color(0xFFECEC)); threddsLogo.setOpaque(true); main.add(icon, BorderLayout.NORTH); main.add(lab1, BorderLayout.CENTER); main.add(threddsLogo, BorderLayout.SOUTH); getContentPane().add(main); pack(); //show(); java.awt.Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); java.awt.Dimension labelSize = this.getPreferredSize(); setLocation(screenSize.width / 2 - (labelSize.width / 2), screenSize.height / 2 - (labelSize.height / 2)); addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { setVisible(false); } }); setVisible(true); //System.out.println("AW ok getPreferredSize="+getPreferredSize()+" screenSize="+screenSize); } } private String getVersion() { String version; try (InputStream is = ucar.nc2.ui.util.Resource.getFileResource("/README")) { if (is == null) return "4.5.0"; BufferedReader dataIS = new BufferedReader(new InputStreamReader(is, CDM.utf8Charset)); StringBuilder sbuff = new StringBuilder(); for (int i = 0; i < 3; i++) { sbuff.append(dataIS.readLine()); sbuff.append("<br>"); } version = sbuff.toString(); } catch (IOException ioe) { ioe.printStackTrace(); version = "version unknown"; } return version; } // Splash Window private static class MySplashScreen extends javax.swing.JWindow { public MySplashScreen() { Image image = Resource.getImage("/resources/nj22/ui/pix/ring2.jpg"); if (image != null) { ImageIcon icon = new ImageIcon(image); JLabel lab = new JLabel(icon); getContentPane().add(lab); pack(); //show(); java.awt.Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); int width = image.getWidth(null); int height = image.getHeight(null); setLocation(screenSize.width / 2 - (width / 2), screenSize.height / 2 - (height / 2)); addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { setVisible(false); } }); setVisible(true); } } } static private void exit() { ui.save(); Rectangle bounds = frame.getBounds(); prefs.putBeanObject(FRAME_SIZE, bounds); try { store.save(); } catch (IOException ioe) { ioe.printStackTrace(); } done = true; // on some systems, still get a window close event ucar.nc2.util.cache.FileCacheIF cache = NetcdfDataset.getNetcdfFileCache(); if (cache != null) cache.clearCache(true); FileCache.shutdown(); // shutdown threads MetadataManager.closeAll(); // shutdown bdb System.exit(0); } // handle messages private static ToolsUI ui; private static JFrame frame; private static PreferencesExt prefs; private static XMLStore store; private static boolean done = false; private static String wantDataset = null; private static void setDataset() { SwingUtilities.invokeLater(new Runnable() { // do it in the swing event thread public void run() { int pos = wantDataset.indexOf(' if (pos > 0) { String catName = wantDataset.substring(0, pos); // {catalog}#{dataset} if (catName.endsWith(".xml")) { ui.makeComponent(null, "THREDDS"); ui.threddsUI.setDataset(wantDataset); ui.tabbedPane.setSelectedComponent(ui.threddsUI); } return; } // default ui.openNetcdfFile(wantDataset); } }); } static boolean isCacheInit = false; public static void main(String args[]) { if (debugListen) { System.out.println("Arguments:"); for (String arg : args) { System.out.println(" " + arg); } HTTPSession.debugHeaders(true); } // handle multiple versions of ToolsUI, along with passing a dataset name SocketMessage sm; if (args.length > 0) { // munge arguments into a single string StringBuilder sbuff = new StringBuilder(); for (String arg : args) { sbuff.append(arg); sbuff.append(" "); } String arguments = sbuff.toString(); System.out.println("ToolsUI arguments=" + arguments); wantDataset = arguments; // see if another version is running, if so send it the message sm = new SocketMessage(14444, wantDataset); if (sm.isAlreadyRunning()) { System.out.println("ToolsUI already running - pass argument= '" + wantDataset + "' to it and exit"); System.exit(0); } } else { // no arguments were passed // look for messages from another ToolsUI sm = new SocketMessage(14444, null); if (sm.isAlreadyRunning()) { System.out.println("ToolsUI already running - start up another copy"); } else { sm.addEventListener(new SocketMessage.EventListener() { public void setMessage(SocketMessage.Event event) { wantDataset = event.getMessage(); if (debugListen) System.out.println(" got message= '" + wantDataset); setDataset(); } }); } } if (debugListen) { System.out.println("Arguments:"); for (String arg : args) { System.out.println(" " + arg); } HTTPSession.debugHeaders(true); } // spring initialization ApplicationContext springContext = new ClassPathXmlApplicationContext("classpath:resources/nj22/ui/spring/application-config.xml"); // look for run line arguments boolean configRead = false; for (int i = 0; i < args.length; i++) { if (args[i].equalsIgnoreCase("-nj22Config") && (i < args.length - 1)) { String runtimeConfig = args[i + 1]; i++; try { StringBuilder errlog = new StringBuilder(); FileInputStream fis = new FileInputStream(runtimeConfig); RuntimeConfigParser.read(fis, errlog); configRead = true; System.out.println(errlog); } catch (IOException ioe) { System.out.println("Error reading " + runtimeConfig + "=" + ioe.getMessage()); } } } if (!configRead) { String filename = XMLStore.makeStandardFilename(".unidata", "nj22Config.xml"); File f = new File(filename); if (f.exists()) { try { StringBuilder errlog = new StringBuilder(); FileInputStream fis = new FileInputStream(filename); RuntimeConfigParser.read(fis, errlog); configRead = true; System.out.println(errlog); } catch (IOException ioe) { System.out.println("Error reading " + filename + "=" + ioe.getMessage()); } } } // prefs storage try { String prefStore = XMLStore.makeStandardFilename(".unidata", "ToolsUI.xml"); File prefs44 = new File(prefStore); if (!prefs44.exists()) { // if 4.4 doesnt exist, see if 4.3 exists String prefStoreBack = XMLStore.makeStandardFilename(".unidata", "NetcdfUI22.xml"); File prefs43 = new File(prefStoreBack); if (prefs43.exists()) { // make a copy of it IO.copyFile(prefs43, prefs44); } } // open 4.4 version, create it if doesnt exist store = XMLStore.createFromFile(prefStore, null); prefs = store.getPreferences(); Debug.setStore(prefs.node("Debug")); } catch (IOException e) { System.out.println("XMLStore Creation failed " + e); } // LOOK needed? for efficiency, persist aggregations. Every hour, delete stuff older than 30 days Aggregation.setPersistenceCache(new DiskCache2("/.unidata/aggCache", true, 60 * 24 * 30, 60)); // filesystem caching // DiskCache2 cacheDir = new DiskCache2(".unidata/ehcache", true, -1, -1); //cacheManager = thredds.filesystem.ControllerCaching.makeTestController(cacheDir.getRootDirectory()); //DatasetCollectionMFiles.setController(cacheManager); // ehcache for files /* try { //thredds.inventory.bdb.MetadataManager.setCacheDirectory(fcCache, maxSizeBytes, jvmPercent); //thredds.inventory.CollectionManagerAbstract.setMetadataStore(thredds.inventory.bdb.MetadataManager.getFactory()); } catch (Exception e) { log.error("CdmInit: Failed to open CollectionManagerAbstract.setMetadataStore", e); } */ UrlAuthenticatorDialog provider = new UrlAuthenticatorDialog(frame); HTTPSession.setGlobalCredentialsProvider(provider); HTTPSession.setGlobalUserAgent("ToolsUI v4.5"); // set Authentication for accessing passsword protected services like TDS PUT java.net.Authenticator.setDefault(provider); // open dap initializations ucar.nc2.dods.DODSNetcdfFile.setAllowCompression(true); ucar.nc2.dods.DODSNetcdfFile.setAllowSessions(true); GribCollection.initDataRafCache(100, 200, -1); /* No longer needed HttpClient client = HttpClientManager.init(provider, "ToolsUI"); opendap.dap.DConnect2.setHttpClient(client); HTTPRandomAccessFile.setHttpClient(client); CdmRemote.setHttpClient(client); NetcdfDataset.setHttpClient(client); WmsViewer.setHttpClient(client); */ SwingUtilities.invokeLater(new Runnable() { @Override public void run() { createGui(); } }); } // run this on the event thread private static void createGui() { try { // Switch to Nimbus Look and Feel, if it's available. for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) { log.warn("Found Nimbus Look and Feel, but couldn't install it.", e); } // get a splash screen up right away final MySplashScreen splash = new MySplashScreen(); // misc initializations BAMutil.setResourcePath("/resources/nj22/ui/icons/"); // test // java.util.logging.Logger.getLogger("ucar.nc2").setLevel( java.util.logging.Level.SEVERE); // put UI in a JFrame frame = new JFrame("NetCDF (4.5) Tools"); ui = new ToolsUI(prefs, frame); frame.setIconImage(BAMutil.getImage("netcdfUI")); frame.addWindowListener(new WindowAdapter() { public void windowActivated(WindowEvent e) { splash.setVisible(false); splash.dispose(); } public void windowClosing(WindowEvent e) { if (!done) exit(); } }); frame.getContentPane().add(ui); Rectangle bounds = (Rectangle) prefs.getBean(FRAME_SIZE, new Rectangle(50, 50, 800, 450)); frame.setBounds(bounds); frame.pack(); frame.setBounds(bounds); frame.setVisible(true); // in case a dataset was on the command line if (wantDataset != null) setDataset(); } }