answer
stringlengths
17
10.2M
package com.hankcs.demo; import com.hankcs.hanlp.classification.classifiers.IClassifier; import com.hankcs.hanlp.classification.classifiers.NaiveBayesClassifier; import com.hankcs.hanlp.classification.models.NaiveBayesModel; import com.hankcs.hanlp.corpus.io.IOUtil; import java.io.File; import java.io.IOException; /** * demo, * * @author hankcs */ public class DemoTextClassification { /** * 510005000 */ public static final String CORPUS_FOLDER = "data/test/"; public static final String MODEL_PATH = "data/test/classification-model.ser"; public static void main(String[] args) throws IOException { IClassifier classifier = new NaiveBayesClassifier(trainOrLoadModel()); predict(classifier, "C 2017=C"); predict(classifier, "8 "); predict(classifier, ""); predict(classifier, ","); predict(classifier, ""); } private static void predict(IClassifier classifier, String text) { System.out.printf("%s %s\n", text, classifier.classify(text)); } private static NaiveBayesModel trainOrLoadModel() throws IOException { NaiveBayesModel model = (NaiveBayesModel) IOUtil.readObjectFrom(MODEL_PATH); if (model != null) return model; File corpusFolder = new File(CORPUS_FOLDER); if (!corpusFolder.exists() || !corpusFolder.isDirectory()) { System.err.println("IClassifier.train(java.lang.String)" + "https://github.com/hankcs/HanLP/wiki/%E6%96%87%E6%9C%AC%E5%88%86%E7%B1%BB%E4%B8%8E%E6%83%85%E6%84%9F%E5%88%86%E6%9E%90"); System.exit(1); } IClassifier classifier = new NaiveBayesClassifier(); // IClassifier classifier.train(CORPUS_FOLDER); model = (NaiveBayesModel) classifier.getModel(); IOUtil.saveObjectTo(model, MODEL_PATH); return model; } }
package fr.vidal.oss.jaxb.atom; import fr.vidal.oss.jaxb.atom.core.*; import org.junit.Before; import org.junit.Test; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import java.io.IOException; import java.io.StringWriter; import java.util.ArrayList; import java.util.Date; import java.util.TimeZone; import static fr.vidal.oss.jaxb.atom.core.DateAdapter.DATE_FORMAT; import static fr.vidal.oss.jaxb.atom.core.LinkRel.*; import static java.util.TimeZone.getTimeZone; import static org.assertj.core.api.Assertions.assertThat; public class MarshallingTest { private Marshaller marshaller; @Before public void prepare() throws JAXBException { TimeZone.setDefault(getTimeZone("Europe/Paris")); marshaller = JAXBContext.newInstance(Feed.class).createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8"); } @Test public void marshalls_standard_atom_feed() throws JAXBException, IOException { Feed feed = new Feed(); feed.setId("urn:uuid:60a76c80-d399-11d9-b91C-0003939e0af6"); feed.setTitle("My standard Atom 1.0 feed"); feed.setSubtitle("Or is it?"); feed.setUpdateDate(new Date(510278400000L)); Author author = new Author("VIDAL", null); feed.setAuthor(author); feed.addLink(new Link(self, null, "http://example.org/", null)); Entry entry = new Entry(); entry.addLink(new Link(null, null, "http://example.org/2003/12/13/atom03", null)); entry.setTitle("Atom is not what you think"); entry.setId("urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a"); entry.setUpdateDate(new Date(512697600000L)); entry.setSummary(new Summary("April's fool!", null)); feed.addEntry(entry); try (StringWriter writer = new StringWriter()) { marshaller.marshal(feed, writer); assertThat(writer.toString()) .isXmlEqualTo( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<feed xmlns=\"http: " <title>My standard Atom 1.0 feed</title>\n" + " <subtitle>Or is it?</subtitle>\n" + " <link href=\"http://example.org/\" rel=\"self\"/>\n" + " <id>urn:uuid:60a76c80-d399-11d9-b91C-0003939e0af6</id>\n" + " <author>\n" + " <name>VIDAL</name>\n" + " </author>\n" + " <updated>1986-03-04T01:00:00Z</updated>\n" + " <entry>\n" + " <title>Atom is not what you think</title>\n" + " <link href=\"http://example.org/2003/12/13/atom03\"/>\n" + " <id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id>\n" + " <updated>1986-04-01T02:00:00Z</updated>\n" + " <summary>April's fool!</summary>\n" + " <content/>\n" + " </entry>\n" + "</feed>"); } } @Test public void marshalls_feed_with_vendor_namespace_elements() throws JAXBException, IOException { Feed feed = new Feed(); feed.setTitle("Search Products - Query :sintrom"); feed.addLink(new Link(self, "application/atom+xml", "/rest/api/products?q=sintrom&amp;start-page=1&amp;page-size=25", null)); feed.setUpdateDate(new Date(1329350400000L)); feed.addAdditionalElement(new SimpleElement( new Namespace("http://purl.org/dc/elements/1.1/", "dc"), "date", DATE_FORMAT.format(new Date(1329350400000L)), new ArrayList<Attribute>() )); feed.addAdditionalElement(new SimpleElement( new Namespace("http://a9.com/-/spec/opensearch/1.1/", "opensearch"), "itemsPerPage", "25", new ArrayList<Attribute>() )); feed.addAdditionalElement(new SimpleElement( new Namespace("http://a9.com/-/spec/opensearch/1.1/", "opensearch"), "totalResults", "2", new ArrayList<Attribute>() )); feed.addAdditionalElement(new SimpleElement( new Namespace("http://a9.com/-/spec/opensearch/1.1/", "opensearch"), "startIndex", "1", new ArrayList<Attribute>() )); Entry firstEntry = new Entry(); firstEntry.setTitle("SINTROM 4 mg cp quadriséc"); firstEntry .addLink(new Link(alternate, "application/atom+xml", "/rest/api/product/15070", null)) .addLink(new Link(related, "application/atom+xml", "/rest/api/product/15070/packages", "PACKAGES")) .addLink(new Link(related, "application/atom+xml", "/rest/api/product/15070/documents", "DOCUMENTS")) .addLink(new Link(related, "application/atom+xml", "/rest/api/product/15070/documents/opt", "OPT_DOCUMENT")); firstEntry.setCategory(new Category("PRODUCT")); firstEntry.setAuthor(new Author("VIDAL", null)); firstEntry.setId("vidal://product/15070"); firstEntry.setUpdateDate(new Date(1329350400000L)); firstEntry.setSummary(new Summary("SINTROM 4 mg cp quadriséc", "text")); firstEntry.addAdditionalElement(new SimpleElement( new Namespace("http://api.vidal.net/-/spec/vidal-api/1.0/", "vidal"), "id", "15070", new ArrayList<Attribute>() )); feed.addEntry(firstEntry); Entry secondEntry = new Entry(); secondEntry.setTitle("SNAKE OIL 1 mg"); secondEntry .addLink(new Link(alternate, "application/atom+xml", "/rest/api/product/42", null)) .addLink(new Link(related, "application/atom+xml", "/rest/api/product/42/packages", "PACKAGES")) .addLink(new Link(related, "application/atom+xml", "/rest/api/product/42/documents", "DOCUMENTS")) .addLink(new Link(related, "application/atom+xml", "/rest/api/product/42/documents/opt", "OPT_DOCUMENT")); secondEntry.setCategory(new Category("PRODUCT")); secondEntry.setAuthor(new Author("VIDAL", null)); secondEntry.setId("vidal://product/42"); secondEntry.setUpdateDate(new Date(1329350400000L)); secondEntry.setSummary(new Summary("SNAKE OIL 1 mg", "text")); secondEntry.addAdditionalElement(new SimpleElement( new Namespace("http://api.vidal.net/-/spec/vidal-api/1.0/", "vidal"), "id", "42", new ArrayList<Attribute>() )); feed.addEntry(secondEntry); try (StringWriter writer = new StringWriter()) { marshaller.marshal(feed, writer); assertThat(writer.toString()) .isXmlEqualTo("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<feed xmlns=\"http: " <title>Search Products - Query :sintrom</title>\n" + " <link\n" + " href=\"/rest/api/products?q=sintrom&amp;amp;start-page=1&amp;amp;page-size=25\"\n" + " rel=\"self\" type=\"application/atom+xml\"/>\n" + " <updated>2012-02-16T01:00:00Z</updated>\n" + " <dc:date xmlns:dc=\"http://purl.org/dc/elements/1.1/\">2012-02-16T01:00:00Z</dc:date>\n" + " <opensearch:itemsPerPage xmlns:opensearch=\"http://a9.com/-/spec/opensearch/1.1/\">25</opensearch:itemsPerPage>\n" + " <opensearch:totalResults xmlns:opensearch=\"http://a9.com/-/spec/opensearch/1.1/\">2</opensearch:totalResults>\n" + " <opensearch:startIndex xmlns:opensearch=\"http://a9.com/-/spec/opensearch/1.1/\">1</opensearch:startIndex>\n" + " <entry>\n" + " <title>SINTROM 4 mg cp quadriséc</title>\n" + " <link href=\"/rest/api/product/15070\" rel=\"alternate\" type=\"application/atom+xml\"/>\n" + " <link href=\"/rest/api/product/15070/packages\" rel=\"related\"\n" + " title=\"PACKAGES\" type=\"application/atom+xml\"/>\n" + " <link href=\"/rest/api/product/15070/documents\" rel=\"related\"\n" + " title=\"DOCUMENTS\" type=\"application/atom+xml\"/>\n" + " <link href=\"/rest/api/product/15070/documents/opt\" rel=\"related\"\n" + " title=\"OPT_DOCUMENT\" type=\"application/atom+xml\"/>\n" + " <category term=\"PRODUCT\"/>\n" + " <author>\n" + " <name>VIDAL</name>\n" + " </author>\n" + " <id>vidal://product/15070</id>\n" + " <updated>2012-02-16T01:00:00Z</updated>\n" + " <summary type=\"text\">SINTROM 4 mg cp quadriséc</summary>\n" + " <content/>\n" + " <vidal:id xmlns:vidal=\"http://api.vidal.net/-/spec/vidal-api/1.0/\">15070</vidal:id>\n" + " </entry>\n" + " <entry>\n" + " <title>SNAKE OIL 1 mg</title>\n" + " <link href=\"/rest/api/product/42\" rel=\"alternate\" type=\"application/atom+xml\"/>\n" + " <link href=\"/rest/api/product/42/packages\" rel=\"related\"\n" + " title=\"PACKAGES\" type=\"application/atom+xml\"/>\n" + " <link href=\"/rest/api/product/42/documents\" rel=\"related\"\n" + " title=\"DOCUMENTS\" type=\"application/atom+xml\"/>\n" + " <link href=\"/rest/api/product/42/documents/opt\" rel=\"related\"\n" + " title=\"OPT_DOCUMENT\" type=\"application/atom+xml\"/>\n" + " <category term=\"PRODUCT\"/>\n" + " <author>\n" + " <name>VIDAL</name>\n" + " </author>\n" + " <id>vidal://product/42</id>\n" + " <updated>2012-02-16T01:00:00Z</updated>\n" + " <summary type=\"text\">SNAKE OIL 1 mg</summary>\n" + " <content/>\n" + " <vidal:id xmlns:vidal=\"http://api.vidal.net/-/spec/vidal-api/1.0/\">42</vidal:id>\n" + " </entry>\n" + "</feed>"); } } }
package com.ociweb.grove; import static com.ociweb.iot.grove.GroveTwig.*; import com.ociweb.iot.maker.Hardware; import com.ociweb.iot.grove.Grove_LCD_RGB; import com.ociweb.iot.maker.CommandChannel; import com.ociweb.iot.maker.DeviceRuntime; import com.ociweb.iot.maker.IoTSetup; import com.ociweb.iot.maker.Port; import static com.ociweb.iot.maker.Port.*; import static com.ociweb.iot.grove.GroveTwig.AngleSensor; import com.ociweb.gl.api.GreenCommandChannel; public class IoTApp implements IoTSetup { //Connection constants // // by using constants such as these you can easily use the right value to reference where the sensor was plugged in //private static final Port BUTTON_PORT = D3; //private static final Port LED_PORT = D2; //private static final Port RELAY_PORT = D7; private static final Port LIGHT_SENSOR_PORT= A2; public int brightness = 255; public static void main( String[] args ) { DeviceRuntime.run(new IoTApp()); } @Override public void declareConnections(Hardware c) { //Connection specifications // // specify each of the connections on the harware, eg which component is plugged into which connection. //c.connect(Button, BUTTON_PORT); //c.connect(Relay, RELAY_PORT); c.connect(LightSensor, LIGHT_SENSOR_PORT); //c.connect(LED, LED_PORT); c.useI2C(); } @Override public void declareBehavior(DeviceRuntime runtime) { //Specify the desired behavior // //Use lambdas or classes and add listeners to the runtime object // //CommandChannels are created to send outgoing events to the hardware // //CommandChannels must never be shared between two lambdas or classes. // //A single lambda or class can use mulitiple CommandChannels for cuoncurrent behavior final CommandChannel lcdScreenChannel = runtime.newCommandChannel(GreenCommandChannel.DYNAMIC_MESSAGING); runtime.addAnalogListener((port, time, durationMillis, average, value)->{ lcdScreenChannel.setValue(LIGHT_SENSOR_PORT, value); System.out.println(value); }); } }
package info.u_team.u_team_test.init; import java.util.List; import info.u_team.u_team_core.api.item.ExtendedTier; import info.u_team.u_team_core.item.tier.UExtendedTier; import info.u_team.u_team_test.TestMod; import net.minecraft.resources.ResourceLocation; import net.minecraft.tags.BlockTags; import net.minecraft.world.item.Tiers; import net.minecraft.world.item.crafting.Ingredient; import net.minecraftforge.common.TierSortingRegistry; import net.minecraftforge.eventbus.api.IEventBus; import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent; public class TestTiers { public static final ExtendedTier BASIC = new UExtendedTier(new float[] { 8, 0, 4, 2, 6 }, new float[] { -3.1F, -1, -2, -2, 0 }, BlockTags.createOptional(new ResourceLocation(TestMod.MODID, "needs_basic_tier")), 500, 10F, 8, 30, () -> Ingredient.of(TestItems.BASIC.get())); private static void setup(FMLCommonSetupEvent event) { TierSortingRegistry.registerTier(BASIC, new ResourceLocation(TestMod.MODID, "basic_tier"), List.of(Tiers.NETHERITE), List.of()); } public static void registerMod(IEventBus bus) { bus.addListener(TestTiers::setup); } }
package io.schinzel.basicutils.state; import io.schinzel.basicutils.collections.MapBuilder; import java.util.Arrays; import java.util.List; import java.util.Map; import org.hamcrest.CoreMatchers; import static org.hamcrest.Matchers.greaterThan; import org.junit.Assert; import org.junit.Test; /** * * @author schinzel */ public class StateTest { @Test public void testSomeMethod() { State state = State.getBuilder() .add("string", "a string") .add("the_int", 123456789) .add("the_long", 1234567890l) .add("the_double", 0.4444d, 2) .add("the_float", 12356.6666f, 3) .build(); List<Property> props = state.mProperties; //Check string Assert.assertEquals("string", props.get(0).mKey); Assert.assertEquals("a string", props.get(0).mValueAsString); Assert.assertEquals("string:a string", props.get(0).getString()); Assert.assertEquals("a string", props.get(0).getObject()); //Check int Assert.assertEquals("the_int", props.get(1).mKey); Assert.assertEquals("123 456 789", props.get(1).mValueAsString); Assert.assertEquals("the_int:123 456 789", props.get(1).getString()); Assert.assertEquals(new Long(123456789), props.get(1).getObject()); //Check long Assert.assertEquals("the_long", props.get(2).mKey); Assert.assertEquals("1 234 567 890", props.get(2).mValueAsString); Assert.assertEquals("the_long:1 234 567 890", props.get(2).getString()); Assert.assertEquals(new Long(1234567890), props.get(2).getObject()); //Check double Assert.assertEquals("the_double", props.get(3).mKey); Assert.assertEquals("0.44", props.get(3).mValueAsString); Assert.assertEquals("the_double:0.44", props.get(3).getString()); Assert.assertEquals(new Double(0.4444d), props.get(3).getObject()); //Check float Assert.assertEquals("the_float", props.get(4).mKey); Assert.assertEquals("12 356.667", props.get(4).mValueAsString); Assert.assertEquals("the_float:12 356.667", props.get(4).getString()); Assert.assertEquals(new Double(12356.6666f), props.get(4).getObject()); } @Test public void testOrder() { List<Property> props = State.getBuilder() .add("A", 1) .add("B", 2) .add("C", 3) .add("D", 4) .add("E", 5) .build().mProperties; Long prevValue = 0l; for (Property prop : props) { Assert.assertThat("value", (Long)prop.getObject(), greaterThan(prevValue)); prevValue = (Long)prop.getObject(); } } @Test public void testGetPropsAsString() { String result = State.create() .add("A", 1) .add("B", 2) .getPropsAsString(); String expected = "A:1 B:2"; Assert.assertEquals(expected, result); } @Test public void testAddChild() { TestClass a1 = new TestClass("A1"); TestClass b2 = new TestClass("B2"); State state = State.create() .add("A", 1) .add("B", 2) .addChild(a1) .addChild(b2); Assert.assertEquals(a1, state.mChildren.get(0)); Assert.assertEquals(b2, state.mChildren.get(1)); } @Test public void testToString() { TestClass a1 = new TestClass("A1"); a1.mChildren.add(new TestClass(("B1"))); TestClass b2 = new TestClass("B2"); b2.mChildren.add(new TestClass(("B2X"))); a1.mChildren.add(b2); String expected = " Name:A1\n" + "-- Name:B1\n" + "-- Name:B2\n" + "---- Name:B2X\n"; String result = a1.toString(); Assert.assertEquals(expected, result); } @Test public void testAddMap() { Map<String, Integer> map = MapBuilder.create() .add("A", 1) .add("B", 2) .add("C", 3) .getMap(); String result = State.create().add("akey", map).toString(); String expected = "{A:1,B:2,C:3}"; Assert.assertThat(result, CoreMatchers.containsString(expected)); } @Test public void testAddList() { List<String> list = Arrays.asList(new String[]{"A", "B", "C"}); String result = State.create().add("a_key", list).toString(); String expected = "{A,B,C}"; Assert.assertThat(result, CoreMatchers.containsString(expected)); } }
package net.engio.mbassy.common; import junit.framework.Assert; import net.engio.mbassy.IPublicationErrorHandler; import net.engio.mbassy.PublicationError; import net.engio.mbassy.bus.MessagePublication; import net.engio.mbassy.bus.config.BusConfiguration; import net.engio.mbassy.bus.MBassador; import net.engio.mbassy.messages.MessageTypes; import org.junit.Before; public abstract class MessageBusTest extends AssertSupport { // this value probably needs to be adjusted depending on the performance of the underlying plattform // otherwise the tests will fail since asynchronous processing might not have finished when // evaluation is run protected static final int processingTimeInMS = 6000; protected static final int InstancesPerListener = 5000; protected static final int ConcurrentUnits = 10; protected static final int IterationsPerThread = 100; protected static final IPublicationErrorHandler TestFailingHandler = new IPublicationErrorHandler() { @Override public void handleError(PublicationError error) { Assert.fail(); } }; private StrongConcurrentSet<MessagePublication> issuedPublications = new StrongConcurrentSet<MessagePublication>(); @Before public void setUp(){ for(MessageTypes mes : MessageTypes.values()) mes.reset(); } public MBassador getBus(BusConfiguration configuration) { MBassador bus = new MBassador(configuration); bus.addErrorHandler(TestFailingHandler); return bus; } public MBassador getBus(BusConfiguration configuration, ListenerFactory listeners) { MBassador bus = new MBassador(configuration); bus.addErrorHandler(TestFailingHandler); ConcurrentExecutor.runConcurrent(TestUtil.subscriber(bus, listeners), ConcurrentUnits); return bus; } public void waitForPublications(long timeOutInMs){ long start = System.currentTimeMillis(); while(issuedPublications.size() > 0 && System.currentTimeMillis() - start < timeOutInMs){ for(MessagePublication pub : issuedPublications){ if(pub.isFinished()) issuedPublications.remove(pub); } } if(issuedPublications.size() > 0) fail("Issued publications did not finish within specified timeout of " + timeOutInMs + " ms"); } public void addPublication(MessagePublication publication){ issuedPublications.add(publication); } }
package net.imagej.ops.create; import static org.junit.Assert.assertEquals; import net.imagej.ops.AbstractOpTest; import net.imglib2.img.Img; import net.imglib2.img.array.ArrayImgFactory; import net.imglib2.type.numeric.real.FloatType; import org.junit.Test; /** * Kernel generation test class. * * @author Brian Northan */ public class CreateKernelTest extends AbstractOpTest { @Test public void test() { double sigma = 5.0; int numDimensions = 2; double[] sigmas = new double[numDimensions]; for (int i = 0; i < numDimensions; i++) { sigmas[i] = sigma; } final Img<FloatType> gaussianKernel = ops.create().kernelGauss(new FloatType(), new ArrayImgFactory<FloatType>(), numDimensions, sigma); final Img<FloatType> gaussianKernel2 = ops.create().kernelGauss(new FloatType(), new ArrayImgFactory<FloatType>(), sigmas); final Img<FloatType> logKernel = ops.create().kernelLog(new FloatType(), new ArrayImgFactory<FloatType>(), numDimensions, sigma); final Img<FloatType> logKernel2 = ops.create().kernelLog(new FloatType(), new ArrayImgFactory<FloatType>(), sigmas); assertEquals(gaussianKernel.dimension(1), 31); assertEquals(gaussianKernel2.dimension(1), 31); assertEquals(logKernel.dimension(1), 27); assertEquals(logKernel2.dimension(1), 27); } @Test public void testDefaults() { double sigma = 5.0; int numDimensions = 2; double[] sigmas = new double[numDimensions]; for (int i = 0; i < numDimensions; i++) { sigmas[i] = sigma; } /*Img<FloatType> gaussianKernel = (Img<FloatType>) ops.create().kernelGauss(sigmas, null, new FloatType(), new ArrayImgFactory()); // no factory Img<FloatType> gaussianKernel2 = (Img<FloatType>) ops.create().kernelGauss(sigmas, null, new FloatType()); */ final Img<FloatType> gaussianKernel = ops.create().kernelGauss(new FloatType(), new ArrayImgFactory<FloatType>(), sigmas); // no factory final Img<FloatType> gaussianKernel2 = ops.create().kernelGauss(new FloatType(), null, sigmas); // no factory, no type final Img<FloatType> gaussianKernel3 = ops.create().<FloatType> kernelGauss(sigmas); assertEquals(gaussianKernel.dimension(1), 31); assertEquals(gaussianKernel2.dimension(1), 31); assertEquals(gaussianKernel3.dimension(1), 31); final Img<FloatType> logKernel = ops.create().kernelLog(new FloatType(), new ArrayImgFactory<FloatType>(), sigmas); // no factory final Img<FloatType> logKernel2 = ops.create().kernelLog(new FloatType(), null, sigmas); // no factory, no type final Img<FloatType> logKernel3 = ops.create().<FloatType> kernelLog(sigmas); assertEquals(logKernel.dimension(1), 27); assertEquals(logKernel2.dimension(1), 27); assertEquals(logKernel3.dimension(1), 27); } }
package net.ucanaccess.test; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.math.BigDecimal; import java.sql.Blob; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Date; import junit.framework.TestCase; import net.ucanaccess.console.Main; import net.ucanaccess.jdbc.UcanaccessDriver; import com.healthmarketscience.jackcess.Database; import com.healthmarketscience.jackcess.Database.FileFormat; public abstract class UcanaccessTestBase extends TestCase { private static FileFormat defaultFileFormat = FileFormat.V2003; private static File fileMdb; private static Class<?extends TestCase> testingClass; static { Main.setBatchMode(true); } public static void setDefaultFileFormat(FileFormat defaultFileFormat) { UcanaccessTestBase.defaultFileFormat = defaultFileFormat; } private FileFormat fileFormat; private String password = ""; protected Connection ucanaccess; private String user = "ucanaccess"; protected Connection verifyConnection; private Boolean ignoreCase; private int inactivityTimeout=-1; private static ArrayList<Class<? extends UcanaccessTestBase>> tableCreated=new ArrayList<Class<? extends UcanaccessTestBase>>(); public UcanaccessTestBase() { this(defaultFileFormat); } public UcanaccessTestBase(FileFormat accVer) { super(); this.fileFormat = accVer; } public void checkQuery(String expression, Object[][] resulMatrix) throws SQLException, IOException { Statement st = null; ResultSet myRs = null; try { st = ucanaccess.createStatement(); myRs = st.executeQuery(expression); diff(myRs, resulMatrix); } finally { if (myRs != null) myRs.close(); if (st != null) st.close(); } } public void checkQuery(String expression) throws SQLException, IOException { Statement st = null; ResultSet myRs = null; Statement st1 = null; ResultSet joRs = null; try { this.initVerifyConnection(); st = ucanaccess.createStatement(); myRs = st.executeQuery(expression); st1 = verifyConnection.createStatement(); joRs = st1.executeQuery(expression); diff(myRs, joRs); } finally { if (myRs != null) myRs.close(); if (st != null) st.close(); if (joRs != null) joRs.close(); if (st1 != null) st1.close(); if (verifyConnection != null) verifyConnection.close(); } } public void checkQuery(String expression, Object... rowResult) throws SQLException, IOException { checkQuery(expression,new Object[][] { rowResult }); } public void executeCreateTable(String createTableStatement) throws SQLException{ if (!tableCreated.contains(this.getClass())) { Statement st = null; try { st =this.ucanaccess.createStatement(); st.execute(createTableStatement); tableCreated.add(this.getClass()); } finally { if (st != null) st.close(); } } } private void diff(ResultSet myRs, Object[][] resulMatrix) throws SQLException, IOException { ResultSetMetaData mymeta = myRs.getMetaData(); int mycolmax = mymeta.getColumnCount(); if (resulMatrix.length > 0) assertEquals(mycolmax, resulMatrix[0].length); int j = 0; while (myRs.next()) { for (int i = 0; i < mycolmax; ++i) { Object ob1 = myRs.getObject(i + 1); assertTrue("matrix with different length was expected: " + resulMatrix.length + " not" + j, j < resulMatrix.length); Object ob2 = resulMatrix[j][i]; if (ob1 == null) { assertTrue((ob2 == null)); } else { if (ob1 instanceof Blob) { Blob blob = (Blob) ob1; InputStream bs = blob.getBinaryStream(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] bt = new byte[4096]; int len; while ((len = bs.read(bt)) != -1) { bos.write(bt, 0, len); } bt = bos.toByteArray(); byte[] btMtx = (byte[]) ob2; for (int y = 0; y < btMtx.length; y++) { assertEquals(btMtx[y], bt[y]); } } else { if (ob1 instanceof Number && ob2 instanceof Number) { BigDecimal ob1b = new BigDecimal(ob1.toString()); BigDecimal ob2b = new BigDecimal(ob2.toString()); ob1 = ob1b.doubleValue(); ob2 = ob2b.doubleValue(); } if (ob1 instanceof Date && ob2 instanceof Date) { ob1 = ((Date) ob1).getTime(); ob2 = ((Date) ob2).getTime(); } assertEquals(ob1, ob2); } } } j++; } assertEquals("matrix with different length was expected ", resulMatrix.length, j); } public void diff(ResultSet myRs, ResultSet joRs) throws SQLException, IOException { ResultSetMetaData mymeta = myRs.getMetaData(); int mycolmax = mymeta.getColumnCount(); ResultSetMetaData jometa = joRs.getMetaData(); int jocolmax = jometa.getColumnCount(); assertTrue(jocolmax == mycolmax); StringBuffer log = new StringBuffer("{"); while (next(joRs, myRs)) { if (log.length() > 1) log.append(","); log.append("{"); for (int i = 0; i < mycolmax; ++i) { if (i > 0) log.append(","); Object ob1 = myRs.getObject(i + 1); Object ob2 = joRs.getObject(i + 1); log.append(print(ob2)); if (ob1 == null) { assertTrue((ob2 == null)); } else { if (ob1 instanceof Blob) { Blob blob = (Blob) ob1; InputStream bs = blob.getBinaryStream(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] bt = new byte[4096]; int len; while ((len = bs.read(bt)) != -1) { bos.write(bt, 0, len); } bt = bos.toByteArray(); byte[] btodbc = (byte[]) ob2; for (int y = 0; y < btodbc.length; y++) { assertEquals(btodbc[y], bt[y]); } } else { if (ob1 instanceof Number && ob2 instanceof Number) { BigDecimal ob1b = new BigDecimal(ob1.toString()); BigDecimal ob2b = new BigDecimal(ob2.toString()); ob1 = ob1b.doubleValue(); ob2 = ob2b.doubleValue(); } if (ob1 instanceof Date && ob2 instanceof Date) { ob1 = ((Date) ob1).getTime(); ob2 = ((Date) ob2).getTime(); } assertEquals(ob1, ob2); } } } log.append("}"); } log.append("}"); } private String print(Object ob2) { if (ob2 == null) { return null; } if (ob2 instanceof String) { return "\"" + ob2 + "\""; } return ob2.toString(); } public void dump(ResultSet rs) throws SQLException { new Main(ucanaccess, null).dump(rs, System.out, true); } public void dump(String expression) throws SQLException, IOException { Statement st = null; ResultSet myRs = null; try { Connection conn = ucanaccess; st = conn.createStatement(); myRs = st.executeQuery(expression); dump(myRs); } finally { if (myRs != null) myRs.close(); if (st != null) st.close(); } } public void dumpVerify(String expression) throws SQLException, IOException { Statement st = null; ResultSet myRs = null; try { Connection conn = this.verifyConnection; st = conn.createStatement(); myRs = st.executeQuery(expression); dump(myRs); } finally { if (myRs != null) myRs.close(); if (st != null) st.close(); } } public String getAccessPath() { return null; } public String getAccessTempPath() throws IOException { if (fileMdb == null||!this.getClass().equals(testingClass)) { testingClass=this.getClass(); if (this.getAccessPath() == null) { fileMdb = File.createTempFile("test", ".mdb"); Database db = Database.create(this.fileFormat, fileMdb); db.flush(); db.close(); System.out.println("Access file version " + this.fileFormat + " created: " + fileMdb.getAbsolutePath()); } else { InputStream is = this.getClass().getClassLoader() .getResourceAsStream(this.getAccessPath()); byte[] buffer = new byte[4096]; File temp = File.createTempFile("tempJunit", "mdb"); System.out.println("Resource file: "+this.getAccessPath()+" copied in "+temp.getAbsolutePath()); FileOutputStream fos = new FileOutputStream(temp); int bread; while ((bread = is.read(buffer)) != -1) { fos.write(buffer, 0, bread); } fos.flush(); fos.close(); is.close(); fileMdb = temp; } } return fileMdb.getAbsolutePath(); } public int getCount(String sql) throws SQLException, IOException { return this.getCount(sql, true); } public int getCount(String sql, boolean equals) throws SQLException, IOException { //initJdbcOdbcConnection(); this.initVerifyConnection(); Statement st = this.verifyConnection.createStatement(); ResultSet joRs = st.executeQuery(sql); joRs.next(); int count = joRs.getInt(1); st = this.ucanaccess.createStatement(); ResultSet myRs = st.executeQuery(sql); myRs.next(); int myCount = myRs.getInt(1); if (equals) assertEquals(count, myCount); else assertFalse(count == myCount); return count; } @Override public String getName() { return super.getName() + " ver " + this.fileFormat; } String getPassword() { return password; } protected Connection getUcanaccessConnection() throws SQLException, IOException { String url=UcanaccessDriver.URL_PREFIX + getAccessTempPath(); if(this.ignoreCase!=null)url+=";ignoreCase="+this.ignoreCase; if(this.inactivityTimeout!=-1)url+=";inactivityTimeout="+this.inactivityTimeout; return DriverManager.getConnection(url, this.user, this.password); } protected void initVerifyConnection() throws SQLException, IOException { InputStream is = new FileInputStream(fileMdb); byte[] buffer = new byte[4096]; File tempVer = File.createTempFile("tempJunit", "mdb"); FileOutputStream fos = new FileOutputStream(tempVer); int bread; while ((bread = is.read(buffer)) != -1) { fos.write(buffer, 0, bread); } fos.flush(); fos.close(); is.close(); this.verifyConnection = DriverManager.getConnection( UcanaccessDriver.URL_PREFIX + tempVer.getAbsolutePath(), this.user, this.password); } private boolean next(ResultSet joRs, ResultSet myRs) throws SQLException { boolean b1 = joRs.next(); boolean b2 = myRs.next(); assertEquals(b1, b2); return b1; } public void setInactivityTimeout(int inactivityTimeout) { this.inactivityTimeout = inactivityTimeout; } void setPassword(String password) { this.password = password; } @Override protected void setUp() throws Exception { super.setUp(); Class.forName("net.ucanaccess.jdbc.UcanaccessDriver"); try { this.ucanaccess = this.getUcanaccessConnection(); } catch (Error e) { e.printStackTrace(); } } @Override protected void tearDown() throws Exception { if (this.ucanaccess != null) this.ucanaccess.close(); } public void setIgnoreCase(boolean ignoreCase) { this.ignoreCase=ignoreCase; } }
package nl.dvberkel.kata.base64; import org.junit.Before; import org.junit.experimental.theories.DataPoints; import org.junit.experimental.theories.Theories; import org.junit.experimental.theories.Theory; import org.junit.runner.RunWith; import java.io.ByteArrayOutputStream; import java.io.IOException; import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; import static org.junit.Assume.assumeThat; @RunWith(Theories.class) public class Base64Theories { private Kata kata; @Before public void createKata() { kata = new Kata(); } @DataPoints public static byte[][] dataPoints = new byte[][]{ new byte[]{0b0}, new byte[]{0b0, 0b0}, new byte[]{0b0, 0b0, 0b0}, new byte[]{0b0, 0b0, 0b0, 0b0}, new byte[]{0b0, 0b0, 0b0, 0b0, 0b0}, new byte[]{0b0, 0b0, 0b0, 0b0, 0b0, 0b0}, new byte[]{0b111111}, new byte[]{0b111111, 0b111111}, new byte[]{0b111111, 0b111111, 0b111111}, new byte[]{0b111111, 0b111111, 0b111111, 0b111111}, new byte[]{0b111111, 0b111111, 0b111111, 0b111111, 0b111111}, new byte[]{0b111111, 0b111111, 0b111111, 0b111111, 0b111111, 0b111111} }; @Theory public void decodeIsTheInverseOfEncode(byte[] input) { assumeThat(input.length, is(greaterThan(0))); assertThat(kata.decode(kata.encode(input)), is(input)); } @Theory public void encodeAndConcatenationAreCommutative(byte[] a, byte[] b) throws IOException { assumeThat(a.length % 3, is(0)); assumeThat(a.length, is(greaterThan(0))); assumeThat(b.length, is(greaterThan(0))); ByteArrayOutputStream s = new ByteArrayOutputStream(); s.write(a); s.write(b); byte[] concat = s.toByteArray(); assertThat(kata.encode(a).concat(kata.encode(b)), is(kata.encode(concat))); } }
package com.glezo.passwordDictionary; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; public class PasswordDictionary { private String description; private ArrayList<String> words; private String notes; public PasswordDictionary(String description,ArrayList<String> words,String notes) { this.description =description; this.words =words; this.notes =notes; } public String getDescription() { return this.description; } public ArrayList<String> getWords() { return this.words; } public String getNotes() { return this.notes; } public void saveDictionaryToFile(String output_file_path) { FileWriter fw; try { fw = new FileWriter(output_file_path); for(int i=0; i<this.words.size(); i++) { String current_word=this.words.get(i); fw.write(current_word+"\n"); } fw.close(); } catch (IOException e) { } } }
package dr.app.beauti.generator; import dr.app.beagle.evomodel.parsers.MarkovJumpsTreeLikelihoodParser; import dr.app.beauti.components.ComponentFactory; import dr.app.beauti.components.ancestralstates.AncestralStatesComponentOptions; import dr.app.beauti.options.*; import dr.app.beauti.types.MicroSatModelType; import dr.app.beauti.util.XMLWriter; import dr.evolution.datatype.Nucleotides; import dr.evomodel.branchratemodel.BranchRateModel; import dr.evomodel.sitemodel.GammaSiteModel; import dr.evomodel.sitemodel.SiteModel; import dr.evomodel.substmodel.AsymmetricQuadraticModel; import dr.evomodel.substmodel.LinearBiasModel; import dr.evomodel.substmodel.SubstitutionModel; import dr.evomodel.substmodel.TwoPhaseModel; import dr.evomodel.tree.TreeModel; import dr.evomodelxml.branchratemodel.DiscretizedBranchRatesParser; import dr.evomodelxml.branchratemodel.RandomLocalClockModelParser; import dr.evomodelxml.branchratemodel.StrictClockBranchRatesParser; import dr.evomodelxml.tree.MicrosatelliteSamplerTreeModelParser; import dr.evomodelxml.treelikelihood.MicrosatelliteSamplerTreeLikelihoodParser; import dr.evomodelxml.treelikelihood.TreeLikelihoodParser; import dr.evoxml.AlignmentParser; import dr.evoxml.SitePatternsParser; import dr.util.Attribute; import dr.xml.XMLParser; /** * @author Alexei Drummond * @author Andrew Rambaut * @author Walter Xie */ public class TreeLikelihoodGenerator extends Generator { public TreeLikelihoodGenerator(BeautiOptions options, ComponentFactory[] components) { super(options, components); } /** * Write the tree likelihood XML block. * * @param partition the partition to write likelihood block for * @param writer the writer */ public void writeTreeLikelihood(PartitionData partition, XMLWriter writer) { AncestralStatesComponentOptions ancestralStatesOptions = (AncestralStatesComponentOptions) options .getComponentOptions(AncestralStatesComponentOptions.class); PartitionSubstitutionModel model = partition.getPartitionSubstitutionModel(); if (model.isDolloModel()) { return; // DolloComponent will add tree likelihood } String treeLikelihoodTag = TreeLikelihoodParser.TREE_LIKELIHOOD; if (ancestralStatesOptions.usingAncestralStates(partition)) { treeLikelihoodTag = TreeLikelihoodParser.ANCESTRAL_TREE_LIKELIHOOD; } else if (ancestralStatesOptions.isCountingStates(partition)) { treeLikelihoodTag = MarkovJumpsTreeLikelihoodParser.MARKOV_JUMP_TREE_LIKELIHOOD; } if (model.getDataType() == Nucleotides.INSTANCE && model.getCodonHeteroPattern() != null) { for (int i = 1; i <= model.getCodonPartitionCount(); i++) { writeTreeLikelihood(treeLikelihoodTag, TreeLikelihoodParser.TREE_LIKELIHOOD, i, partition, writer); } } else { writeTreeLikelihood(treeLikelihoodTag, TreeLikelihoodParser.TREE_LIKELIHOOD, -1, partition, writer); } } /** * Write the tree likelihood XML block. * * @param id the id of the tree likelihood * @param num the likelihood number * @param partition the partition to write likelihood block for * @param writer the writer */ private void writeTreeLikelihood(String tag, String id, int num, PartitionData partition, XMLWriter writer) { PartitionSubstitutionModel substModel = partition.getPartitionSubstitutionModel(); PartitionTreeModel treeModel = partition.getPartitionTreeModel(); PartitionClockModel clockModel = partition.getPartitionClockModel(); writer.writeComment("Likelihood for tree given sequence data"); String idString; if (num > 0) { idString = substModel.getPrefix(num) + partition.getPrefix() + id; } else { idString = partition.getPrefix() + id; } Attribute[] attributes; if (tag.equals(MarkovJumpsTreeLikelihoodParser.MARKOV_JUMP_TREE_LIKELIHOOD)) { attributes = new Attribute[]{ new Attribute.Default<String>(XMLParser.ID, idString), new Attribute.Default<Boolean>(TreeLikelihoodParser.USE_AMBIGUITIES, substModel.isUseAmbiguitiesTreeLikelihood()), new Attribute.Default<Boolean>(MarkovJumpsTreeLikelihoodParser.USE_UNIFORMIZATION, true), new Attribute.Default<Integer>(MarkovJumpsTreeLikelihoodParser.NUMBER_OF_SIMULANTS, 1) }; } else { attributes = new Attribute[]{ new Attribute.Default<String>(XMLParser.ID, idString), new Attribute.Default<Boolean>(TreeLikelihoodParser.USE_AMBIGUITIES, substModel.isUseAmbiguitiesTreeLikelihood()) }; } writer.writeOpenTag(tag, attributes); if (!options.samplePriorOnly) { if (num > 0) { writeCodonPatternsRef(substModel.getPrefix(num) + partition.getPrefix(), num, substModel.getCodonPartitionCount(), writer); } else { writer.writeIDref(SitePatternsParser.PATTERNS, partition.getPrefix() + SitePatternsParser.PATTERNS); } } else { // We just need to use the dummy alignment writer.writeIDref(AlignmentParser.ALIGNMENT, partition.getAlignment().getId()); } writer.writeIDref(TreeModel.TREE_MODEL, treeModel.getPrefix() + TreeModel.TREE_MODEL); if (num > 0) { writer.writeIDref(GammaSiteModel.SITE_MODEL, substModel.getPrefix(num) + SiteModel.SITE_MODEL); } else { writer.writeIDref(GammaSiteModel.SITE_MODEL, substModel.getPrefix() + SiteModel.SITE_MODEL); } // TODO: search for other solution // Ancestral state likelihood doesn't need the substitution model - it gets // it from the siteModel. AncestralStatesComponentOptions ancestralStatesOptions = (AncestralStatesComponentOptions) options .getComponentOptions(AncestralStatesComponentOptions.class); if(ancestralStatesOptions.dNdSRobustCountingAvailable(partition) && ancestralStatesOptions.dNdSRobustCounting(partition) ) { writer.writeIDref(substModel.getNucSubstitutionModel().getXMLName(), substModel.getPrefix(num) + "hky"); // writer.writeComment(substModel.getNucSubstitutionModel().getXMLName()); } switch (clockModel.getClockType()) { case STRICT_CLOCK: writer.writeIDref(StrictClockBranchRatesParser.STRICT_CLOCK_BRANCH_RATES, clockModel.getPrefix() + BranchRateModel.BRANCH_RATES); break; case UNCORRELATED: writer.writeIDref(DiscretizedBranchRatesParser.DISCRETIZED_BRANCH_RATES, options.noDuplicatedPrefix(clockModel.getPrefix(), treeModel.getPrefix()) + BranchRateModel.BRANCH_RATES); break; case RANDOM_LOCAL_CLOCK: writer.writeIDref(RandomLocalClockModelParser.LOCAL_BRANCH_RATES, clockModel.getPrefix() + BranchRateModel.BRANCH_RATES); break; case AUTOCORRELATED: throw new UnsupportedOperationException("Autocorrelated relaxed clock model not implemented yet"); // writer.writeIDref(ACLikelihoodParser.AC_LIKELIHOOD, options.noDuplicatedPrefix(clockModel.getPrefix(), treeModel.getPrefix()) // + BranchRateModel.BRANCH_RATES); // break; default: throw new IllegalArgumentException("Unknown clock model"); } /*if (options.clockType == ClockType.STRICT_CLOCK) { writer.writeIDref(StrictClockBranchRates.STRICT_CLOCK_BRANCH_RATES, BranchRateModel.BRANCH_RATES); } else { writer.writeIDref(DiscretizedBranchRatesParser.DISCRETIZED_BRANCH_RATES, BranchRateModel.BRANCH_RATES); }*/ generateInsertionPoint(ComponentGenerator.InsertionPoint.IN_TREE_LIKELIHOOD, partition, writer); writer.writeCloseTag(tag); } public void writeTreeLikelihoodReferences(XMLWriter writer) { AncestralStatesComponentOptions ancestralStatesOptions = (AncestralStatesComponentOptions) options .getComponentOptions(AncestralStatesComponentOptions.class); for (AbstractPartitionData partition : options.dataPartitions) { // Each PD has one TreeLikelihood String treeLikelihoodTag = TreeLikelihoodParser.TREE_LIKELIHOOD; if (ancestralStatesOptions.usingAncestralStates(partition)) { treeLikelihoodTag = TreeLikelihoodParser.ANCESTRAL_TREE_LIKELIHOOD; if (ancestralStatesOptions.isCountingStates(partition)) { // State change counting uses the MarkovJumpsTreeLikelihood but treeLikelihoodTag = MarkovJumpsTreeLikelihoodParser.RECONSTRUCTING_TREE_LIKELIHOOD; } else if (ancestralStatesOptions.dNdSRobustCounting(partition)) { // dNdS robust counting doesn't as it has its own counting code... } } if (partition.getTaxonList() != null) { if (partition instanceof PartitionData && partition.getTraits() == null) { // is an alignment data partition PartitionSubstitutionModel substModel = partition.getPartitionSubstitutionModel(); if (substModel.getDataType() == Nucleotides.INSTANCE && substModel.getCodonHeteroPattern() != null) { for (int i = 1; i <= substModel.getCodonPartitionCount(); i++) { writer.writeIDref(treeLikelihoodTag, substModel.getPrefix(i) + partition.getPrefix() + TreeLikelihoodParser.TREE_LIKELIHOOD); } } else { writer.writeIDref(treeLikelihoodTag, partition.getPrefix() + TreeLikelihoodParser.TREE_LIKELIHOOD); } } else if (partition instanceof PartitionPattern) { // microsat writer.writeIDref(MicrosatelliteSamplerTreeLikelihoodParser.TREE_LIKELIHOOD, partition.getPrefix() + MicrosatelliteSamplerTreeLikelihoodParser.TREE_LIKELIHOOD); } } } } /** * Write Microsatellite Sampler tree likelihood XML block. * * @param partition the partition to write likelihood block for * @param writer the writer */ public void writeTreeLikelihood(PartitionPattern partition, XMLWriter writer) { PartitionSubstitutionModel substModel = partition.getPartitionSubstitutionModel(); PartitionTreeModel treeModel = partition.getPartitionTreeModel(); PartitionClockModel clockModel = partition.getPartitionClockModel(); writer.writeComment("Microsatellite Sampler Tree Likelihood"); writer.writeOpenTag(MicrosatelliteSamplerTreeLikelihoodParser.TREE_LIKELIHOOD, new Attribute[]{new Attribute.Default<String>(XMLParser.ID, partition.getPrefix() + MicrosatelliteSamplerTreeLikelihoodParser.TREE_LIKELIHOOD)}); writeMicrosatSubstModelRef(substModel, writer); writer.writeIDref(MicrosatelliteSamplerTreeModelParser.TREE_MICROSATELLITE_SAMPLER_MODEL, treeModel.getPrefix() + TreeModel.TREE_MODEL + ".microsatellite"); switch (clockModel.getClockType()) { case STRICT_CLOCK: writer.writeIDref(StrictClockBranchRatesParser.STRICT_CLOCK_BRANCH_RATES, clockModel.getPrefix() + BranchRateModel.BRANCH_RATES); break; case UNCORRELATED: case RANDOM_LOCAL_CLOCK: case AUTOCORRELATED: throw new UnsupportedOperationException("Microsatellite only supports strict clock model"); default: throw new IllegalArgumentException("Unknown clock model"); } writer.writeCloseTag(MicrosatelliteSamplerTreeLikelihoodParser.TREE_LIKELIHOOD); } public void writeMicrosatSubstModelRef(PartitionSubstitutionModel model, XMLWriter writer) { if (model.getPhase() != MicroSatModelType.Phase.ONE_PHASE) { writer.writeIDref(TwoPhaseModel.TWO_PHASE_MODEL, model.getPrefix() + TwoPhaseModel.TWO_PHASE_MODEL); } else if (model.getMutationBias() != MicroSatModelType.MutationalBias.UNBIASED) { writer.writeIDref(LinearBiasModel.LINEAR_BIAS_MODEL, model.getPrefix() + LinearBiasModel.LINEAR_BIAS_MODEL); } else { writer.writeIDref(AsymmetricQuadraticModel.ASYMQUAD_MODEL, model.getPrefix() + AsymmetricQuadraticModel.ASYMQUAD_MODEL); } } }
package biomodel.util; import java.awt.AWTError; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.IOException; import java.io.StringReader; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.prefs.Preferences; import java.util.regex.Pattern; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.tree.TreeNode; import javax.xml.stream.XMLStreamException; import main.Gui; import main.util.Utility; import odk.lang.FastMath; import org.sbml.jsbml.ASTNode; import org.sbml.jsbml.ext.comp.CompModelPlugin; import org.sbml.jsbml.ext.comp.CompSBMLDocumentPlugin; import org.sbml.jsbml.ext.comp.CompConstant; import org.sbml.jsbml.ext.comp.CompSBasePlugin; import org.sbml.jsbml.ext.fbc.FBCConstants; import org.sbml.jsbml.ext.fbc.FBCModelPlugin; import org.sbml.jsbml.ext.fbc.FluxBound; import org.sbml.jsbml.Compartment; //CompartmentType not supported in Level 3 //import org.sbml.jsbml.CompartmentType; import org.sbml.jsbml.Constraint; import org.sbml.jsbml.Delay; import org.sbml.jsbml.Event; import org.sbml.jsbml.EventAssignment; import org.sbml.jsbml.FunctionDefinition; import org.sbml.jsbml.InitialAssignment; import org.sbml.jsbml.KineticLaw; import org.sbml.jsbml.ext.layout.LayoutConstants; import org.sbml.jsbml.ext.layout.LayoutModelPlugin; import org.sbml.jsbml.text.parser.FormulaParserLL3; import org.sbml.jsbml.text.parser.IFormulaParser; import org.sbml.jsbml.text.parser.ParseException; import org.sbml.jsbml.validator.SBMLValidator; import org.sbml.jsbml.xml.XMLNode; import org.sbml.jsbml.AbstractNamedSBase; import org.sbml.jsbml.AbstractSBase; import org.sbml.jsbml.Annotation; import org.sbml.jsbml.ExplicitRule; import org.sbml.jsbml.ListOf; import org.sbml.jsbml.LocalParameter; import org.sbml.jsbml.Model; import org.sbml.jsbml.ModifierSpeciesReference; import org.sbml.jsbml.Parameter; import org.sbml.jsbml.QuantityWithUnit; import org.sbml.jsbml.Reaction; import org.sbml.jsbml.Rule; import org.sbml.jsbml.SBMLDocument; import org.sbml.jsbml.SBMLException; import org.sbml.jsbml.SBMLReader; import org.sbml.jsbml.SBMLWriter; import org.sbml.jsbml.SBase; import org.sbml.jsbml.Species; import org.sbml.jsbml.SpeciesReference; //SpeciesType not supported in Level 3 //import org.sbml.jsbml.SpeciesType; import org.sbml.jsbml.Unit; import org.sbml.jsbml.UnitDefinition; import org.sbml.jsbml.JSBML; import org.sbml.libsbml.libsbmlConstants; import flanagan.math.Fmath; import flanagan.math.PsRandom; import biomodel.parser.BioModel; public class SBMLutilities { /** * Check that ID is valid and unique */ public static boolean checkID(SBMLDocument document, String ID, String selectedID, boolean isReacParam) { Pattern IDpat = Pattern.compile("([a-zA-Z]|_)([a-zA-Z]|[0-9]|_)*"); if (ID.equals("")) { JOptionPane.showMessageDialog(Gui.frame, "An ID is required.", "Enter an ID", JOptionPane.ERROR_MESSAGE); return true; } if (!(IDpat.matcher(ID).matches())) { JOptionPane.showMessageDialog(Gui.frame, "An ID can only contain letters, numbers, and underscores.", "Invalid ID", JOptionPane.ERROR_MESSAGE); return true; } if (ID.equals("t") || ID.equals("time") || ID.equals("true") || ID.equals("false") || ID.equals("notanumber") || ID.equals("pi") || ID.equals("infinity") || ID.equals("exponentiale") || ID.equals("abs") || ID.equals("arccos") || ID.equals("arccosh") || ID.equals("arcsin") || ID.equals("arcsinh") || ID.equals("arctan") || ID.equals("arctanh") || ID.equals("arccot") || ID.equals("arccoth") || ID.equals("arccsc") || ID.equals("arccsch") || ID.equals("arcsec") || ID.equals("arcsech") || ID.equals("acos") || ID.equals("acosh") || ID.equals("asin") || ID.equals("asinh") || ID.equals("atan") || ID.equals("atanh") || ID.equals("acot") || ID.equals("acoth") || ID.equals("acsc") || ID.equals("acsch") || ID.equals("asec") || ID.equals("asech") || ID.equals("cos") || ID.equals("cosh") || ID.equals("cot") || ID.equals("coth") || ID.equals("csc") || ID.equals("csch") || ID.equals("ceil") || ID.equals("factorial") || ID.equals("exp") || ID.equals("floor") || ID.equals("ln") || ID.equals("log") || ID.equals("sqr") || ID.equals("log10") || ID.equals("pow") || ID.equals("sqrt") || ID.equals("root") || ID.equals("piecewise") || ID.equals("sec") || ID.equals("sech") || ID.equals("sin") || ID.equals("sinh") || ID.equals("tan") || ID.equals("tanh") || ID.equals("and") || ID.equals("or") || ID.equals("xor") || ID.equals("not") || ID.equals("eq") || ID.equals("geq") || ID.equals("leq") || ID.equals("gt") || ID.equals("neq") || ID.equals("lt") || ID.equals("delay") || ((document.getLevel() > 2) && (ID.equals("avogadro")))) { JOptionPane.showMessageDialog(Gui.frame, "ID cannot be a reserved word.", "Illegal ID", JOptionPane.ERROR_MESSAGE); return true; } if (!ID.equals(selectedID) && (getElementBySId(document, ID)!=null || getElementByMetaId(document, ID)!=null)) { if (isReacParam) { JOptionPane.showMessageDialog(Gui.frame, "ID shadows a global ID.", "Not a Unique ID", JOptionPane.WARNING_MESSAGE); } else { JOptionPane.showMessageDialog(Gui.frame, "ID is not unique.", "Enter a Unique ID", JOptionPane.ERROR_MESSAGE); return true; } } return false; } /** * Find invalid reaction variables in a formula */ public static ArrayList<String> getInvalidVariables(SBMLDocument document, String formula, String arguments, boolean isFunction) { ArrayList<String> validVars = new ArrayList<String>(); ArrayList<String> invalidVars = new ArrayList<String>(); Model model = document.getModel(); for (int i = 0; i < model.getFunctionDefinitionCount(); i++) { validVars.add(model.getFunctionDefinition(i).getId()); } if (!isFunction) { for (int i = 0; i < model.getSpeciesCount(); i++) { validVars.add(model.getSpecies(i).getId()); } } if (isFunction) { String[] args = arguments.split(" |\\,"); for (int i = 0; i < args.length; i++) { validVars.add(args[i]); } } else { for (int i = 0; i < model.getCompartmentCount(); i++) { if (document.getLevel() > 2 || model.getCompartment(i).getSpatialDimensions() != 0) { validVars.add(model.getCompartment(i).getId()); } } for (int i = 0; i < model.getParameterCount(); i++) { validVars.add(model.getParameter(i).getId()); } for (int i = 0; i < model.getReactionCount(); i++) { Reaction reaction = model.getReaction(i); validVars.add(reaction.getId()); for (int j = 0; j < reaction.getReactantCount(); j++) { SpeciesReference reactant = reaction.getReactant(j); if ((reactant.isSetId()) && (!reactant.getId().equals(""))) { validVars.add(reactant.getId()); } } for (int j = 0; j < reaction.getProductCount(); j++) { SpeciesReference product = reaction.getProduct(j); if ((product.isSetId()) && (!product.getId().equals(""))) { validVars.add(product.getId()); } } } String[] kindsL3V1 = { "ampere", "avogadro", "becquerel", "candela", "celsius", "coulomb", "dimensionless", "farad", "gram", "gray", "henry", "hertz", "item", "joule", "katal", "kelvin", "kilogram", "litre", "lumen", "lux", "metre", "mole", "newton", "ohm", "pascal", "radian", "second", "siemens", "sievert", "steradian", "tesla", "volt", "watt", "weber" }; for (int i = 0; i < kindsL3V1.length; i++) { validVars.add(kindsL3V1[i]); } for (int i = 0; i < model.getUnitDefinitionCount(); i++) { validVars.add(model.getListOfUnitDefinitions().get(i).getId()); } } String[] splitLaw = formula.split(" |\\(|\\)|\\,|\\*|\\+|\\/|\\-|>|=|<|\\^|%|&|\\||!"); for (int i = 0; i < splitLaw.length; i++) { if (splitLaw[i].equals("abs") || splitLaw[i].equals("arccos") || splitLaw[i].equals("arccosh") || splitLaw[i].equals("arcsin") || splitLaw[i].equals("arcsinh") || splitLaw[i].equals("arctan") || splitLaw[i].equals("arctanh") || splitLaw[i].equals("arccot") || splitLaw[i].equals("arccoth") || splitLaw[i].equals("arccsc") || splitLaw[i].equals("arccsch") || splitLaw[i].equals("arcsec") || splitLaw[i].equals("arcsech") || splitLaw[i].equals("acos") || splitLaw[i].equals("acosh") || splitLaw[i].equals("asin") || splitLaw[i].equals("asinh") || splitLaw[i].equals("atan") || splitLaw[i].equals("atanh") || splitLaw[i].equals("acot") || splitLaw[i].equals("acoth") || splitLaw[i].equals("acsc") || splitLaw[i].equals("acsch") || splitLaw[i].equals("asec") || splitLaw[i].equals("asech") || splitLaw[i].equals("cos") || splitLaw[i].equals("cosh") || splitLaw[i].equals("cot") || splitLaw[i].equals("coth") || splitLaw[i].equals("csc") || splitLaw[i].equals("csch") || splitLaw[i].equals("ceil") || splitLaw[i].equals("factorial") || splitLaw[i].equals("exp") || splitLaw[i].equals("floor") || splitLaw[i].equals("ln") || splitLaw[i].equals("log") || splitLaw[i].equals("sqr") || splitLaw[i].equals("log10") || splitLaw[i].equals("pow") || splitLaw[i].equals("sqrt") || splitLaw[i].equals("root") || splitLaw[i].equals("piecewise") || splitLaw[i].equals("sec") || splitLaw[i].equals("sech") || splitLaw[i].equals("sin") || splitLaw[i].equals("sinh") || splitLaw[i].equals("tan") || splitLaw[i].equals("tanh") || splitLaw[i].equals("") || splitLaw[i].equals("and") || splitLaw[i].equals("or") || splitLaw[i].equals("xor") || splitLaw[i].equals("not") || splitLaw[i].equals("eq") || splitLaw[i].equals("geq") || splitLaw[i].equals("leq") || splitLaw[i].equals("gt") || splitLaw[i].equals("neq") || splitLaw[i].equals("lt") || splitLaw[i].equals("delay") || splitLaw[i].equals("t") || splitLaw[i].equals("time") || splitLaw[i].equals("true") || splitLaw[i].equals("false") || splitLaw[i].equals("pi") || splitLaw[i].equals("exponentiale") || splitLaw[i].equals("infinity") || splitLaw[i].equals("notanumber") || ((document.getLevel() > 2) && (splitLaw[i].equals("avogadro")))) { } else { String temp = splitLaw[i]; if (splitLaw[i].substring(splitLaw[i].length() - 1, splitLaw[i].length()).equals("e")) { temp = splitLaw[i].substring(0, splitLaw[i].length() - 1); } try { Double.parseDouble(temp); } catch (Exception e1) { if (!validVars.contains(splitLaw[i])) { if (splitLaw[i].equals("uniform")) { createFunction(model, "uniform", "Uniform distribution", "lambda(a,b,(a+b)/2)"); } else if (splitLaw[i].equals("normal")) { createFunction(model, "normal", "Normal distribution", "lambda(m,s,m)"); } else if (splitLaw[i].equals("exponential")) { createFunction(model, "exponential", "Exponential distribution", "lambda(l,1/l)"); } else if (splitLaw[i].equals("gamma")) { createFunction(model, "gamma", "Gamma distribution", "lambda(a,b,a*b)"); } else if (splitLaw[i].equals("lognormal")) { createFunction(model, "lognormal", "Lognormal distribution", "lambda(z,s,exp(z+s^2/2))"); } else if (splitLaw[i].equals("chisq")) { createFunction(model, "chisq", "Chi-squared distribution", "lambda(nu,nu)"); } else if (splitLaw[i].equals("laplace")) { createFunction(model, "laplace", "Laplace distribution", "lambda(a,0)"); } else if (splitLaw[i].equals("cauchy")) { createFunction(model, "cauchy", "Cauchy distribution", "lambda(a,a)"); } else if (splitLaw[i].equals("rayleigh")) { createFunction(model, "rayleigh", "Rayleigh distribution","lambda(s,s*sqrt(pi/2))"); } else if (splitLaw[i].equals("poisson")) { createFunction(model, "poisson", "Poisson distribution", "lambda(mu,mu)"); } else if (splitLaw[i].equals("binomial")) { createFunction(model, "binomial", "Binomial distribution", "lambda(p,n,p*n)"); } else if (splitLaw[i].equals("bernoulli")) { createFunction(model, "bernoulli", "Bernoulli distribution", "lambda(p,p)"); } else if (splitLaw[i].equals("PSt")) { createFunction(model, "PSt", "Probabilistic Steady State Property", "lambda(x,uniform(0,1))"); } else if (splitLaw[i].equals("St")) { createFunction(model, "St", "Steady State Property", "lambda(x,not(not(x)))"); } else if (splitLaw[i].equals("PG")) { createFunction(model, "PG", "Probabilistic Globally Property", "lambda(t,x,uniform(0,1))"); } else if (splitLaw[i].equals("G")) { createFunction(model, "G", "Globally Property", "lambda(t,x,or(not(t),x))"); } else if (splitLaw[i].equals("PF")) { createFunction(model, "PF", "Probabilistic Eventually Property", "lambda(t,x,uniform(0,1))"); } else if (splitLaw[i].equals("F")) { createFunction(model, "F", "Eventually Property", "lambda(t,x,or(not(t),not(x)))"); } else if (splitLaw[i].equals("PU")) { createFunction(model, "PU", "Probabilistic Until Property", "lambda(t,x,y,uniform(0,1))"); } else if (splitLaw[i].equals("U")) { createFunction(model, "G", "Globally Property", "lambda(t,x,or(not(t),x))"); createFunction(model, "F", "Eventually Property", "lambda(t,x,or(not(t),not(x)))"); createFunction(model, "U", "Until Property", "lambda(t,x,y,and(G(t,x),F(t,y)))"); } else if (splitLaw[i].equals("rate")) { createFunction(model, "rate", "Rate", "lambda(a,a)"); } else if (splitLaw[i].equals("BIT")) { createFunction(model, "BIT", "bit selection", "lambda(a,b,a*b)"); } else if (splitLaw[i].equals("BITAND")) { createFunction(model, "BITAND", "Bitwise AND", "lambda(a,b,a*b)"); } else if (splitLaw[i].equals("BITOR")) { createFunction(model, "BITOR", "Bitwise OR", "lambda(a,b,a*b)"); } else if (splitLaw[i].equals("BITNOT")) { createFunction(model, "BITNOT", "Bitwise NOT", "lambda(a,b,a*b)"); } else if (splitLaw[i].equals("BITXOR")) { createFunction(model, "BITXOR", "Bitwise XOR", "lambda(a,b,a*b)"); } else if (splitLaw[i].equals("mod")) { createFunction(model, "mod", "Modular", "lambda(a,b,a-floor(a/b)*b)"); } else if (splitLaw[i].equals("neighborQuantityLeft")) { createFunction(model, "neighborQuantityLeft", "neighborQuantityLeft", "lambda(a,0)"); createFunction(model, "neighborQuantityLeftFull", "neighborQuantityLeftFull", "lambda(a,b,c,0)"); } else if (splitLaw[i].equals("neighborQuantityRight")) { createFunction(model, "neighborQuantityRight", "neighborQuantityRight", "lambda(a,0)"); createFunction(model, "neighborQuantityRightFull", "neighborQuantityRightFull", "lambda(a,b,c,0)"); } else if (splitLaw[i].equals("neighborQuantityAbove")) { createFunction(model, "neighborQuantityAbove", "neighborQuantityAbove", "lambda(a,0)"); createFunction(model, "neighborQuantityAboveFull", "neighborQuantityAboveFull", "lambda(a,b,c,0)"); } else if (splitLaw[i].equals("neighborQuantityBelow")) { createFunction(model, "neighborQuantityBelow", "neighborQuantityBelow", "lambda(a,0)"); createFunction(model, "neighborQuantityBelowFull", "neighborQuantityBelowFull", "lambda(a,b,c,0)"); } else { invalidVars.add(splitLaw[i]); } if (splitLaw[i].contains("neighborQuantity")) { createFunction(model, "getCompartmentLocationX", "getCompartmentLocationX", "lambda(a,0)"); createFunction(model, "getCompartmentLocationY", "getCompartmentLocationY", "lambda(a,0)"); } } } } } return invalidVars; } public static void pruneUnusedSpecialFunctions(SBMLDocument document) { if (document.getModel().getFunctionDefinition("uniform")!=null) { if (!variableInUse(document, "uniform", false, false, true)) { document.getModel().removeFunctionDefinition("uniform"); } } if (document.getModel().getFunctionDefinition("normal")!=null) { if (!variableInUse(document, "normal", false, false, true)) { document.getModel().removeFunctionDefinition("normal"); } } if (document.getModel().getFunctionDefinition("exponential")!=null) { if (!variableInUse(document, "exponential", false, false, true)) { document.getModel().removeFunctionDefinition("exponential"); } } if (document.getModel().getFunctionDefinition("gamma")!=null) { if (!variableInUse(document, "gamma", false, false, true)) { document.getModel().removeFunctionDefinition("gamma"); } } if (document.getModel().getFunctionDefinition("lognormal")!=null) { if (!variableInUse(document, "lognormal", false, false, true)) { document.getModel().removeFunctionDefinition("lognormal"); } } if (document.getModel().getFunctionDefinition("chisq")!=null) { if (!variableInUse(document, "chisq", false, false, true)) { document.getModel().removeFunctionDefinition("chisq"); } } if (document.getModel().getFunctionDefinition("laplace")!=null) { if (!variableInUse(document, "laplace", false, false, true)) { document.getModel().removeFunctionDefinition("laplace"); } } if (document.getModel().getFunctionDefinition("cauchy")!=null) { if (!variableInUse(document, "cauchy", false, false, true)) { document.getModel().removeFunctionDefinition("cauchy"); } } if (document.getModel().getFunctionDefinition("rayleigh")!=null) { if (!variableInUse(document, "rayleigh", false, false, true)) { document.getModel().removeFunctionDefinition("rayleigh"); } } if (document.getModel().getFunctionDefinition("poisson")!=null) { if (!variableInUse(document, "poisson", false, false, true)) { document.getModel().removeFunctionDefinition("poisson"); } } if (document.getModel().getFunctionDefinition("binomial")!=null) { if (!variableInUse(document, "binomial", false, false, true)) { document.getModel().removeFunctionDefinition("binomial"); } } if (document.getModel().getFunctionDefinition("bernoulli")!=null) { if (!variableInUse(document, "bernoulli", false, false, true)) { document.getModel().removeFunctionDefinition("bernoulli"); } } if (document.getModel().getFunctionDefinition("St")!=null) { if (!variableInUse(document, "St", false, false, true)) { document.getModel().removeFunctionDefinition("St"); } } if (document.getModel().getFunctionDefinition("PSt")!=null) { if (!variableInUse(document, "PSt", false, false, true)) { document.getModel().removeFunctionDefinition("PSt"); } } if (document.getModel().getFunctionDefinition("PG")!=null) { if (!variableInUse(document, "PG", false, false, true)) { document.getModel().removeFunctionDefinition("PG"); } } if (document.getModel().getFunctionDefinition("PF")!=null) { if (!variableInUse(document, "PF", false, false, true)) { document.getModel().removeFunctionDefinition("PF"); } } if (document.getModel().getFunctionDefinition("PU")!=null) { if (!variableInUse(document, "PU", false, false, true)) { document.getModel().removeFunctionDefinition("PU"); } } if (document.getModel().getFunctionDefinition("G")!=null) { if (!variableInUse(document, "G", false, false, true)) { document.getModel().removeFunctionDefinition("G"); } } if (document.getModel().getFunctionDefinition("F")!=null) { if (!variableInUse(document, "F", false, false, true)) { document.getModel().removeFunctionDefinition("F"); } } if (document.getModel().getFunctionDefinition("U")!=null) { if (!variableInUse(document, "U", false, false, true)) { document.getModel().removeFunctionDefinition("U"); } } if (document.getModel().getFunctionDefinition("rate")!=null) { if (!variableInUse(document, "rate", false, false, true)) { document.getModel().removeFunctionDefinition("rate"); } } if (document.getModel().getFunctionDefinition("mod")!=null) { if (!variableInUse(document, "mod", false, false, true)) { document.getModel().removeFunctionDefinition("mod"); } } if (document.getModel().getFunctionDefinition("BIT")!=null) { if (!variableInUse(document, "BIT", false, false, true)) { document.getModel().removeFunctionDefinition("BIT"); } } if (document.getModel().getFunctionDefinition("BITOR")!=null) { if (!variableInUse(document, "BITOR", false, false, true)) { document.getModel().removeFunctionDefinition("BITOR"); } } if (document.getModel().getFunctionDefinition("BITXOR")!=null) { if (!variableInUse(document, "BITXOR", false, false, true)) { document.getModel().removeFunctionDefinition("BITXOR"); } } if (document.getModel().getFunctionDefinition("BITNOT")!=null) { if (!variableInUse(document, "BITNOT", false, false, true)) { document.getModel().removeFunctionDefinition("BITNOT"); } } if (document.getModel().getFunctionDefinition("BITAND")!=null) { if (!variableInUse(document, "BITAND", false, false, true)) { document.getModel().removeFunctionDefinition("BITAND"); } } // if (document.getModel().getFunctionDefinition("neighborQuantityLeft") != null) { // if (!variableInUse(document, "neighborQuantityLeft", false, false, true)) { // document.getModel().removeFunctionDefinition("neighborQuantityLeft"); // if (document.getModel().getFunctionDefinition("neighborQuantityRight") != null) { // if (!variableInUse(document, "neighborQuantityRight", false, false, true)) { // document.getModel().removeFunctionDefinition("neighborQuantityRight"); // if (document.getModel().getFunctionDefinition("neighborQuantityAbove") != null) { // if (!variableInUse(document, "neighborQuantityAbove", false, false, true)) { // document.getModel().removeFunctionDefinition("neighborQuantityAbove"); // if (document.getModel().getFunctionDefinition("neighborQuantityBelow") != null) { // if (!variableInUse(document, "neighborQuantityBelow", false, false, true)) { // document.getModel().removeFunctionDefinition("neighborQuantityBelow"); // if (document.getModel().getFunctionDefinition("neighborQuantityLeftFull") != null) { // if (!variableInUse(document, "neighborQuantityLeftFull", false, false, true)) { // document.getModel().removeFunctionDefinition("neighborQuantityLeftFull"); // if (document.getModel().getFunctionDefinition("neighborQuantityRightFull") != null) { // if (!variableInUse(document, "neighborQuantityRightFull", false, false, true)) { // document.getModel().removeFunctionDefinition("neighborQuantityRightFull"); // if (document.getModel().getFunctionDefinition("neighborQuantityAboveFull") != null) { // if (!variableInUse(document, "neighborQuantityAboveFull", false, false, true)) { // document.getModel().removeFunctionDefinition("neighborQuantityAboveFull"); // if (document.getModel().getFunctionDefinition("neighborQuantityBelowFull") != null) { // if (!variableInUse(document, "neighborQuantityBelowFull", false, false, true)) { // document.getModel().removeFunctionDefinition("neighborQuantityBelowFull"); // if (document.getModel().getFunctionDefinition("getCompartmentLocationX") != null) { // if (!variableInUse(document, "getCompartmentLocationX", false, false, true)) { // document.getModel().removeFunctionDefinition("getCompartmentLocationX"); // if (document.getModel().getFunctionDefinition("getCompartmentLocationY") != null) { // if (!variableInUse(document, "getCompartmentLocationY", false, false, true)) { // document.getModel().removeFunctionDefinition("getCompartmentLocationY"); } /** * Convert ASTNodes into a string */ public static String myFormulaToString(ASTNode mathFormula) { if (mathFormula==null) return ""; setTimeToT(mathFormula); String formula; Preferences biosimrc = Preferences.userRoot(); if (biosimrc.get("biosim.general.infix", "").equals("prefix")) { formula = JSBML.formulaToString(mathFormula); } else { formula = myFormulaToStringInfix(mathFormula); } formula = formula.replaceAll("arccot", "acot"); formula = formula.replaceAll("arccoth", "acoth"); formula = formula.replaceAll("arccsc", "acsc"); formula = formula.replaceAll("arccsch", "acsch"); formula = formula.replaceAll("arcsec", "asec"); formula = formula.replaceAll("arcsech", "asech"); formula = formula.replaceAll("arccosh", "acosh"); formula = formula.replaceAll("arcsinh", "asinh"); formula = formula.replaceAll("arctanh", "atanh"); String newformula = formula.replaceFirst("00e", "0e"); while (!(newformula.equals(formula))) { formula = newformula; newformula = formula.replaceFirst("0e\\+", "e+"); newformula = newformula.replaceFirst("0e-", "e-"); } formula = formula.replaceFirst("\\.e\\+", ".0e+"); formula = formula.replaceFirst("\\.e-", ".0e-"); return formula; } /** * Recursive function to change time variable to t */ public static void setTimeToT(ASTNode node) { if (node==null) return; if (node.getType() == ASTNode.Type.NAME_TIME) { if (!node.getName().equals("t") || !node.getName().equals("time")) { node.setName("t"); } } else if (node.getType() == ASTNode.Type.NAME_AVOGADRO) { node.setName("avogadro"); } for (int c = 0; c < node.getChildCount(); c++) setTimeToT(node.getChild(c)); } /** * Convert String into ASTNodes */ public static ASTNode myParseFormula(String formula) { ASTNode mathFormula = null; Preferences biosimrc = Preferences.userRoot(); try { IFormulaParser parser = new FormulaParserLL3(new StringReader("")); if (biosimrc.get("biosim.general.infix", "").equals("prefix")) { mathFormula = ASTNode.parseFormula(formula, parser); } else { mathFormula = ASTNode.parseFormula(formula, parser); // mathFormula = libsbml.parseL3Formula(formula); } } catch (ParseException e) { return null; } catch (Exception e) { return null; } if (mathFormula == null) return null; setTimeAndTrigVar(mathFormula); return mathFormula; } /** * Recursive function to set time and trig functions */ public static void setTimeAndTrigVar(ASTNode node) { if (node.getType() == ASTNode.Type.NAME) { if (node.getName().equals("t")) { node.setType(ASTNode.Type.NAME_TIME); } else if (node.getName().equals("time")) { node.setType(ASTNode.Type.NAME_TIME); } else if (node.getName().equals("avogadro")) { node.setType(ASTNode.Type.NAME_AVOGADRO); } } if (node.getType() == ASTNode.Type.FUNCTION) { if (node.getName().equals("acot")) { node.setType(ASTNode.Type.FUNCTION_ARCCOT); } else if (node.getName().equals("acoth")) { node.setType(ASTNode.Type.FUNCTION_ARCCOTH); } else if (node.getName().equals("acsc")) { node.setType(ASTNode.Type.FUNCTION_ARCCSC); } else if (node.getName().equals("acsch")) { node.setType(ASTNode.Type.FUNCTION_ARCCSCH); } else if (node.getName().equals("asec")) { node.setType(ASTNode.Type.FUNCTION_ARCSEC); } else if (node.getName().equals("asech")) { node.setType(ASTNode.Type.FUNCTION_ARCSECH); } else if (node.getName().equals("acosh")) { node.setType(ASTNode.Type.FUNCTION_ARCCOSH); } else if (node.getName().equals("asinh")) { node.setType(ASTNode.Type.FUNCTION_ARCSINH); } else if (node.getName().equals("atanh")) { node.setType(ASTNode.Type.FUNCTION_ARCTANH); } } for (int c = 0; c < node.getChildCount(); c++) setTimeAndTrigVar(node.getChild(c)); } /** * Check the number of arguments to a function */ public static boolean checkNumFunctionArguments(SBMLDocument document, ASTNode node) { ListOf<FunctionDefinition> sbml = document.getModel().getListOfFunctionDefinitions(); switch (node.getType()) { case FUNCTION_ABS: case FUNCTION_ARCCOS: case FUNCTION_ARCCOSH: case FUNCTION_ARCSIN: case FUNCTION_ARCSINH: case FUNCTION_ARCTAN: case FUNCTION_ARCTANH: case FUNCTION_ARCCOT: case FUNCTION_ARCCOTH: case FUNCTION_ARCCSC: case FUNCTION_ARCCSCH: case FUNCTION_ARCSEC: case FUNCTION_ARCSECH: case FUNCTION_COS: case FUNCTION_COSH: case FUNCTION_SIN: case FUNCTION_SINH: case FUNCTION_TAN: case FUNCTION_TANH: case FUNCTION_COT: case FUNCTION_COTH: case FUNCTION_CSC: case FUNCTION_CSCH: case FUNCTION_SEC: case FUNCTION_SECH: case FUNCTION_CEILING: case FUNCTION_FACTORIAL: case FUNCTION_EXP: case FUNCTION_FLOOR: case FUNCTION_LN: if (node.getChildCount() != 1) { JOptionPane.showMessageDialog(Gui.frame, "Expected 1 argument for " + node.getName() + " but found " + node.getChildCount() + ".", "Number of Arguments Incorrect", JOptionPane.ERROR_MESSAGE); return true; } if (node.getChild(0).isBoolean()) { JOptionPane.showMessageDialog(Gui.frame, "Argument for " + node.getName() + " function must evaluate to a number.", "Number Expected", JOptionPane.ERROR_MESSAGE); return true; } break; case LOGICAL_NOT: if (node.getChildCount() != 1) { JOptionPane.showMessageDialog(Gui.frame, "Expected 1 argument for " + node.getName() + " but found " + node.getChildCount() + ".", "Number of Arguments Incorrect", JOptionPane.ERROR_MESSAGE); return true; } if (!node.getChild(0).isBoolean()) { JOptionPane.showMessageDialog(Gui.frame, "Argument for not function must be of type Boolean.", "Boolean Expected", JOptionPane.ERROR_MESSAGE); return true; } break; case LOGICAL_AND: case LOGICAL_OR: case LOGICAL_XOR: for (int i = 0; i < node.getChildCount(); i++) { if (!node.getChild(i).isBoolean()) { JOptionPane.showMessageDialog(Gui.frame, "Argument " + i + " for " + node.getName() + " function is not of type Boolean.", "Boolean Expected", JOptionPane.ERROR_MESSAGE); return true; } } break; case PLUS: if (node.getChild(0).isBoolean()) { JOptionPane.showMessageDialog(Gui.frame, "Argument 1 for + operator must evaluate to a number.", "Number Expected", JOptionPane.ERROR_MESSAGE); return true; } if (node.getChild(1).isBoolean()) { JOptionPane.showMessageDialog(Gui.frame, "Argument 2 for + operator must evaluate to a number.", "Number Expected", JOptionPane.ERROR_MESSAGE); return true; } break; case MINUS: if (node.getChild(0).isBoolean()) { JOptionPane.showMessageDialog(Gui.frame, "Argument 1 for - operator must evaluate to a number.", "Number Expected", JOptionPane.ERROR_MESSAGE); return true; } if ((node.getChildCount() > 1) && (node.getChild(1).isBoolean())) { JOptionPane.showMessageDialog(Gui.frame, "Argument 2 for - operator must evaluate to a number.", "Number Expected", JOptionPane.ERROR_MESSAGE); return true; } break; case TIMES: if (node.getChild(0).isBoolean()) { JOptionPane.showMessageDialog(Gui.frame, "Argument 1 for * operator must evaluate to a number.", "Number Expected", JOptionPane.ERROR_MESSAGE); return true; } if (node.getChild(1).isBoolean()) { JOptionPane.showMessageDialog(Gui.frame, "Argument 2 for * operator must evaluate to a number.", "Number Expected", JOptionPane.ERROR_MESSAGE); return true; } break; case DIVIDE: if (node.getChild(0).isBoolean()) { JOptionPane.showMessageDialog(Gui.frame, "Argument 1 for / operator must evaluate to a number.", "Number Expected", JOptionPane.ERROR_MESSAGE); return true; } if (node.getChild(1).isBoolean()) { JOptionPane.showMessageDialog(Gui.frame, "Argument 2 for / operator must evaluate to a number.", "Number Expected", JOptionPane.ERROR_MESSAGE); return true; } break; case POWER: if (node.getChild(0).isBoolean()) { JOptionPane.showMessageDialog(Gui.frame, "Argument 1 for ^ operator must evaluate to a number.", "Number Expected", JOptionPane.ERROR_MESSAGE); return true; } if (node.getChild(1).isBoolean()) { JOptionPane.showMessageDialog(Gui.frame, "Argument 2 for ^ operator must evaluate to a number.", "Number Expected", JOptionPane.ERROR_MESSAGE); return true; } break; case FUNCTION_DELAY: case FUNCTION_POWER: case FUNCTION_ROOT: case RELATIONAL_GEQ: case RELATIONAL_LEQ: case RELATIONAL_LT: case RELATIONAL_GT: case FUNCTION_LOG: if (node.getChildCount() != 2) { JOptionPane.showMessageDialog(Gui.frame, "Expected 2 arguments for " + node.getName() + " but found " + node.getChildCount() + ".", "Number of Arguments Incorrect", JOptionPane.ERROR_MESSAGE); return true; } if (node.getChild(0).isBoolean()) { JOptionPane.showMessageDialog(Gui.frame, "Argument 1 for " + node.getName() + " function must evaluate to a number.", "Number Expected", JOptionPane.ERROR_MESSAGE); return true; } if (node.getChild(1).isBoolean()) { JOptionPane.showMessageDialog(Gui.frame, "Argument 2 for " + node.getName() + " function must evaluate to a number.", "Number Expected", JOptionPane.ERROR_MESSAGE); return true; } break; case RELATIONAL_EQ: case RELATIONAL_NEQ: if (node.getChildCount() != 2) { JOptionPane.showMessageDialog(Gui.frame, "Expected 2 arguments for " + node.getName() + " but found " + node.getChildCount() + ".", "Number of Arguments Incorrect", JOptionPane.ERROR_MESSAGE); return true; } if ((node.getChild(0).isBoolean() && !node.getChild(1).isBoolean()) || (!node.getChild(0).isBoolean() && node.getChild(1).isBoolean())) { JOptionPane.showMessageDialog(Gui.frame, "Arguments for " + node.getName() + " function must either both be numbers or Booleans.", "Argument Mismatch", JOptionPane.ERROR_MESSAGE); return true; } break; case FUNCTION_PIECEWISE: if (node.getChildCount() < 1) { JOptionPane.showMessageDialog(Gui.frame, "Piecewise function requires at least 1 argument.", "Number of Arguments Incorrect", JOptionPane.ERROR_MESSAGE); return true; } for (int i = 1; i < node.getChildCount(); i += 2) { if (!node.getChild(i).isBoolean()) { JOptionPane.showMessageDialog(Gui.frame, "Even arguments of piecewise function must be of type Boolean.", "Boolean Expected", JOptionPane.ERROR_MESSAGE); return true; } } int pieceType = -1; for (int i = 0; i < node.getChildCount(); i += 2) { if (node.getChild(i).isBoolean()) { if (pieceType == 2) { JOptionPane.showMessageDialog(Gui.frame, "All odd arguments of a piecewise function must agree.", "Type Mismatch", JOptionPane.ERROR_MESSAGE); return true; } pieceType = 1; } else { if (pieceType == 1) { JOptionPane.showMessageDialog(Gui.frame, "All odd arguments of a piecewise function must agree.", "Type Mismatch", JOptionPane.ERROR_MESSAGE); return true; } pieceType = 2; } } break; case FUNCTION: for (int i = 0; i < document.getModel().getFunctionDefinitionCount(); i++) { if (sbml.get(i).getId().equals(node.getName())) { long numArgs = sbml.get(i).getArgumentCount(); if (numArgs != node.getChildCount()) { JOptionPane.showMessageDialog(Gui.frame, "Expected " + numArgs + " argument(s) for " + node.getName() + " but found " + node.getChildCount() + ".", "Number of Arguments Incorrect", JOptionPane.ERROR_MESSAGE); return true; } break; } } break; case NAME: if (node.getName().equals("abs") || node.getName().equals("arccos") || node.getName().equals("arccosh") || node.getName().equals("arcsin") || node.getName().equals("arcsinh") || node.getName().equals("arctan") || node.getName().equals("arctanh") || node.getName().equals("arccot") || node.getName().equals("arccoth") || node.getName().equals("arccsc") || node.getName().equals("arccsch") || node.getName().equals("arcsec") || node.getName().equals("arcsech") || node.getName().equals("acos") || node.getName().equals("acosh") || node.getName().equals("asin") || node.getName().equals("asinh") || node.getName().equals("atan") || node.getName().equals("atanh") || node.getName().equals("acot") || node.getName().equals("acoth") || node.getName().equals("acsc") || node.getName().equals("acsch") || node.getName().equals("asec") || node.getName().equals("asech") || node.getName().equals("cos") || node.getName().equals("cosh") || node.getName().equals("cot") || node.getName().equals("coth") || node.getName().equals("csc") || node.getName().equals("csch") || node.getName().equals("ceil") || node.getName().equals("factorial") || node.getName().equals("exp") || node.getName().equals("floor") || node.getName().equals("ln") || node.getName().equals("log") || node.getName().equals("sqr") || node.getName().equals("log10") || node.getName().equals("sqrt") || node.getName().equals("sec") || node.getName().equals("sech") || node.getName().equals("sin") || node.getName().equals("sinh") || node.getName().equals("tan") || node.getName().equals("tanh") || node.getName().equals("not")) { JOptionPane.showMessageDialog(Gui.frame, "Expected 1 argument for " + node.getName() + " but found 0.", "Number of Arguments Incorrect", JOptionPane.ERROR_MESSAGE); return true; } if (node.getName().equals("and") || node.getName().equals("or") || node.getName().equals("xor") || node.getName().equals("pow") || node.getName().equals("eq") || node.getName().equals("geq") || node.getName().equals("leq") || node.getName().equals("gt") || node.getName().equals("neq") || node.getName().equals("lt") || node.getName().equals("delay") || node.getName().equals("root")) { JOptionPane.showMessageDialog(Gui.frame, "Expected 2 arguments for " + node.getName() + " but found 0.", "Number of Arguments Incorrect", JOptionPane.ERROR_MESSAGE); return true; } if (node.getName().equals("piecewise")) { JOptionPane.showMessageDialog(Gui.frame, "Piecewise function requires at least 1 argument.", "Number of Arguments Incorrect", JOptionPane.ERROR_MESSAGE); return true; } for (int i = 0; i < document.getModel().getFunctionDefinitionCount(); i++) { if (sbml.get(i).getId().equals(node.getName())) { long numArgs = sbml.get(i).getArgumentCount(); JOptionPane.showMessageDialog(Gui.frame, "Expected " + numArgs + " argument(s) for " + node.getName() + " but found 0.", "Number of Arguments Incorrect", JOptionPane.ERROR_MESSAGE); return true; } } break; default: } for (int c = 0; c < node.getChildCount(); c++) { if (checkNumFunctionArguments(document, node.getChild(c))) { return true; } } return false; } public static Boolean isSpecialFunction(String functionId) { if (functionId.equals("uniform")) return true; else if (functionId.equals("normal")) return true; else if (functionId.equals("exponential")) return true; else if (functionId.equals("gamma")) return true; else if (functionId.equals("lognormal")) return true; else if (functionId.equals("chisq")) return true; else if (functionId.equals("laplace")) return true; else if (functionId.equals("cauchy")) return true; else if (functionId.equals("poisson")) return true; else if (functionId.equals("binomial")) return true; else if (functionId.equals("bernoulli")) return true; else if (functionId.equals("St")) return true; else if (functionId.equals("PSt")) return true; else if (functionId.equals("PG")) return true; else if (functionId.equals("PF")) return true; else if (functionId.equals("PU")) return true; else if (functionId.equals("G")) return true; else if (functionId.equals("F")) return true; else if (functionId.equals("U")) return true; return false; } public static void fillBlankMetaIDs (SBMLDocument document) { int metaIDIndex = 1; Model model = document.getModel(); setDefaultMetaID(document, model, metaIDIndex); for (int i = 0; i < model.getParameterCount(); i++) metaIDIndex = setDefaultMetaID(document, model.getParameter(i), metaIDIndex); for (int i = 0; i < model.getSpeciesCount(); i++) metaIDIndex = setDefaultMetaID(document, model.getSpecies(i), metaIDIndex); for (int i = 0; i < model.getReactionCount(); i++) metaIDIndex = setDefaultMetaID(document, model.getReaction(i), metaIDIndex); for (int i = 0; i < model.getRuleCount(); i++) metaIDIndex = setDefaultMetaID(document, model.getRule(i), metaIDIndex); for (int i = 0; i < model.getEventCount(); i++) metaIDIndex = setDefaultMetaID(document, model.getEvent(i), metaIDIndex); CompModelPlugin compModel = (CompModelPlugin) document.getModel().getExtension(CompConstant.namespaceURI); if (compModel != null && compModel.isSetListOfSubmodels()) { for (int i = 0; i < compModel.getListOfSubmodels().size(); i++) metaIDIndex = setDefaultMetaID(document, compModel.getListOfSubmodels().get(i), metaIDIndex); } } public static int setDefaultMetaID(SBMLDocument document, SBase sbmlObject, int metaIDIndex) { CompSBMLDocumentPlugin compDocument = (CompSBMLDocumentPlugin) document.getExtension(CompConstant.namespaceURI); String metaID = sbmlObject.getMetaId(); if (metaID == null || metaID.equals("")) { metaID = "iBioSim" + metaIDIndex; while (getElementByMetaId(document, metaID) != null || (compDocument != null && getElementByMetaId(compDocument, metaID) != null)) { metaIDIndex++; metaID = "iBioSim" + metaIDIndex; } setMetaId(sbmlObject, metaID); metaIDIndex++; } return metaIDIndex; } public static ArrayList<String> CreateListOfUsedIDs(SBMLDocument document) { ArrayList<String> usedIDs = new ArrayList<String>(); if (document==null) return usedIDs; Model model = document.getModel(); if (model.isSetId()) { usedIDs.add(model.getId()); } for (int i = 0; i < model.getFunctionDefinitionCount(); i++) { usedIDs.add(model.getFunctionDefinition(i).getId()); } usedIDs.add("uniform"); usedIDs.add("normal"); usedIDs.add("exponential"); usedIDs.add("gamma"); usedIDs.add("lognormal"); usedIDs.add("chisq"); usedIDs.add("laplace"); usedIDs.add("cauchy"); usedIDs.add("poisson"); usedIDs.add("binomial"); usedIDs.add("bernoulli"); usedIDs.add("St"); usedIDs.add("PSt"); usedIDs.add("PG"); usedIDs.add("PF"); usedIDs.add("PU"); usedIDs.add("G"); usedIDs.add("F"); usedIDs.add("U"); for (int i = 0; i < model.getUnitDefinitionCount(); i++) { usedIDs.add(model.getUnitDefinition(i).getId()); } // CompartmentType and SpeciesType not supported in Level 3 // ids = model.getListOfCompartmentTypes(); // for (int i = 0; i < model.getNumCompartmentTypes(); i++) { // usedIDs.add(((CompartmentType) ids.get(i)).getId()); // ids = model.getListOfSpeciesTypes(); // for (int i = 0; i < model.getSpeciesTypeCount(); i++) { // usedIDs.add(((SpeciesType) ids.get(i)).getId()); for (int i = 0; i < model.getCompartmentCount(); i++) { usedIDs.add(model.getCompartment(i).getId()); } for (int i = 0; i < model.getParameterCount(); i++) { usedIDs.add(model.getParameter(i).getId()); } for (int i = 0; i < model.getReactionCount(); i++) { Reaction reaction = model.getReaction(i); usedIDs.add(reaction.getId()); for (int j = 0; j < reaction.getReactantCount(); j++) { SpeciesReference reactant = reaction.getReactant(j); if ((reactant.isSetId()) && (!reactant.getId().equals(""))) { usedIDs.add(reactant.getId()); } } for (int j = 0; j < reaction.getProductCount(); j++) { SpeciesReference product = reaction.getProduct(j); if ((product.isSetId()) && (!product.getId().equals(""))) { usedIDs.add(product.getId()); } } } for (int i = 0; i < model.getSpeciesCount(); i++) { usedIDs.add(model.getSpecies(i).getId()); } for (int i = 0; i < model.getConstraintCount(); i++) { Constraint constraint = model.getConstraint(i); if (constraint.isSetMetaId()) { usedIDs.add(constraint.getMetaId()); } } for (int i = 0; i < model.getEventCount(); i++) { Event event = model.getEvent(i); if (event.isSetId()) { usedIDs.add(event.getId()); } } return usedIDs; } /** * Check for cycles in initialAssignments and assignmentRules */ public static boolean checkCycles(SBMLDocument document) { Model model = document.getModel(); String[] rateLaws = new String[model.getReactionCount()]; for (int i = 0; i < model.getReactionCount(); i++) { Reaction reaction = model.getReaction(i); if (reaction.getKineticLaw()==null || reaction.getKineticLaw().getMath()==null) { rateLaws[i] = reaction.getId() + " = 0.0"; } else { rateLaws[i] = reaction.getId() + " = " + myFormulaToString(reaction.getKineticLaw().getMath()); } } String[] initRules = new String[model.getInitialAssignmentCount()]; for (int i = 0; i < model.getInitialAssignmentCount(); i++) { InitialAssignment init = model.getInitialAssignment(i); initRules[i] = init.getVariable() + " = " + myFormulaToString(init.getMath()); } String[] rules = new String[model.getRuleCount()]; for (int i = 0; i < model.getRuleCount(); i++) { Rule rule = model.getRule(i); if (rule.isAlgebraic()) { rules[i] = "0 = " + SBMLutilities.myFormulaToString(rule.getMath()); } else if (rule.isAssignment()) { rules[i] = getVariable(rule) + " = " + SBMLutilities.myFormulaToString(rule.getMath()); } else { rules[i] = "d( " + getVariable(rule) + " )/dt = " + SBMLutilities.myFormulaToString(rule.getMath()); } } String[] result = new String[rules.length + initRules.length + rateLaws.length]; int j = 0; boolean[] used = new boolean[rules.length + initRules.length + rateLaws.length]; for (int i = 0; i < rules.length + initRules.length + rateLaws.length; i++) { used[i] = false; } for (int i = 0; i < rules.length; i++) { if (rules[i].split(" ")[0].equals("0")) { result[j] = rules[i]; used[i] = true; j++; } } boolean progress; do { progress = false; for (int i = 0; i < rules.length + initRules.length + rateLaws.length; i++) { String[] rule; if (i < rules.length) { if (used[i] || (rules[i].split(" ")[0].equals("0")) || (rules[i].split(" ")[0].equals("d("))) continue; rule = rules[i].split(" "); } else if (i < rules.length + initRules.length) { if (used[i]) continue; rule = initRules[i - rules.length].split(" "); } else { if (used[i]) continue; rule = rateLaws[i - (rules.length + initRules.length)].split(" "); } boolean insert = true; for (int k = 1; k < rule.length; k++) { for (int l = 0; l < rules.length + initRules.length + rateLaws.length; l++) { String rule2; if (l < rules.length) { if (used[l] || (rules[l].split(" ")[0].equals("0")) || (rules[l].split(" ")[0].equals("d("))) continue; rule2 = rules[l].split(" ")[0]; } else if (l < rules.length + initRules.length) { if (used[l]) continue; rule2 = initRules[l - rules.length].split(" ")[0]; } else { if (used[l]) continue; rule2 = rateLaws[l - (rules.length + initRules.length)].split(" ")[0]; } if (rule[k].equals(rule2)) { insert = false; break; } } if (!insert) break; } if (insert) { if (i < rules.length) { result[j] = rules[i]; } else if (i < rules.length + initRules.length) { result[j] = initRules[i - rules.length]; } else { result[j] = rateLaws[i - (rules.length + initRules.length)]; } j++; progress = true; used[i] = true; } } } while ((progress) && (j < rules.length + initRules.length + rateLaws.length)); for (int i = 0; i < rules.length; i++) { if (rules[i].split(" ")[0].equals("d(")) { result[j] = rules[i]; j++; } } if (j != rules.length + initRules.length + rateLaws.length) { return true; } return false; } /** * Checks consistency of the sbml file. */ public static void checkOverDetermined(SBMLDocument document) { if (Gui.isLibsbmlFound()) { try { org.sbml.libsbml.SBMLDocument doc = new org.sbml.libsbml.SBMLReader().readSBMLFromString(new SBMLWriter().writeSBMLToString(document)); doc.setConsistencyChecks(libsbmlConstants.LIBSBML_CAT_GENERAL_CONSISTENCY, false); doc.setConsistencyChecks(libsbmlConstants.LIBSBML_CAT_IDENTIFIER_CONSISTENCY, false); doc.setConsistencyChecks(libsbmlConstants.LIBSBML_CAT_UNITS_CONSISTENCY, false); doc.setConsistencyChecks(libsbmlConstants.LIBSBML_CAT_MATHML_CONSISTENCY, false); doc.setConsistencyChecks(libsbmlConstants.LIBSBML_CAT_SBO_CONSISTENCY, false); doc.setConsistencyChecks(libsbmlConstants.LIBSBML_CAT_MODELING_PRACTICE, false); doc.setConsistencyChecks(libsbmlConstants.LIBSBML_CAT_OVERDETERMINED_MODEL, true); long numErrors = doc.checkConsistency(); if (numErrors > 0) { JOptionPane.showMessageDialog(Gui.frame, "Algebraic rules make model overdetermined.", "Model is Overdetermined", JOptionPane.WARNING_MESSAGE); } } catch (SBMLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (XMLStreamException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { document.setConsistencyChecks(SBMLValidator.CHECK_CATEGORY.GENERAL_CONSISTENCY, false); document.setConsistencyChecks(SBMLValidator.CHECK_CATEGORY.IDENTIFIER_CONSISTENCY, false); document.setConsistencyChecks(SBMLValidator.CHECK_CATEGORY.UNITS_CONSISTENCY, false); document.setConsistencyChecks(SBMLValidator.CHECK_CATEGORY.MATHML_CONSISTENCY, false); document.setConsistencyChecks(SBMLValidator.CHECK_CATEGORY.SBO_CONSISTENCY, false); document.setConsistencyChecks(SBMLValidator.CHECK_CATEGORY.MODELING_PRACTICE, false); document.setConsistencyChecks(SBMLValidator.CHECK_CATEGORY.OVERDETERMINED_MODEL, true); long numErrors = document.checkConsistency(); if (numErrors > 0) { JOptionPane.showMessageDialog(Gui.frame, "Algebraic rules make model overdetermined.", "Model is Overdetermined", JOptionPane.WARNING_MESSAGE); } } } /** * Create check if species used in reaction */ public static boolean usedInReaction(SBMLDocument document, String id) { for (int i = 0; i < document.getModel().getReactionCount(); i++) { for (int j = 0; j < document.getModel().getReaction(i).getReactantCount(); j++) { if (document.getModel().getReaction(i).getReactant(j).getSpecies().equals(id)) { return true; } } for (int j = 0; j < document.getModel().getReaction(i).getProductCount(); j++) { if (document.getModel().getReaction(i).getProduct(j).getSpecies().equals(id)) { return true; } } } return false; } /** * Checks if species is a reactant in a non-degradation reaction */ public static boolean usedInNonDegradationReaction(SBMLDocument document, String id) { for (int i = 0; i < document.getModel().getReactionCount(); i++) { for (int j = 0; j < document.getModel().getReaction(i).getReactantCount(); j++) { if (document.getModel().getReaction(i).getReactant(j).getSpecies().equals(id) && (document.getModel().getReaction(i).getProductCount() > 0 || document.getModel().getReaction(i).getReactantCount() > 1)) { return true; } } } return false; } /** * Update variable in math formula using String */ public static String updateFormulaVar(String s, String origVar, String newVar) { s = " " + s + " "; s = s.replace(" " + origVar + " ", " " + newVar + " "); s = s.replace(" " + origVar + ",", " " + newVar + ","); s = s.replace(" " + origVar + "(", " " + newVar + "("); s = s.replace("(" + origVar + ")", "(" + newVar + ")"); s = s.replace("(" + origVar + " ", "(" + newVar + " "); s = s.replace("(" + origVar + ",", "(" + newVar + ","); s = s.replace(" " + origVar + ")", " " + newVar + ")"); s = s.replace(" " + origVar + "^", " " + newVar + "^"); return s.trim(); } /** * Update variable in math formula using ASTNode */ public static ASTNode updateMathVar(ASTNode math, String origVar, String newVar) { String s = updateFormulaVar(myFormulaToString(math), origVar, newVar); return myParseFormula(s); } /** * Check if compartment is in use. */ public static boolean compartmentInUse(SBMLDocument document, String compartmentId) { boolean remove = true; ArrayList<String> speciesUsing = new ArrayList<String>(); for (int i = 0; i < document.getModel().getSpeciesCount(); i++) { Species species = document.getModel().getListOfSpecies().get(i); if (species.isSetCompartment()) { if (species.getCompartment().equals(compartmentId)) { remove = false; speciesUsing.add(species.getId()); } } } ArrayList<String> reactionsUsing = new ArrayList<String>(); for (int i = 0; i < document.getModel().getReactionCount(); i++) { Reaction reaction = document.getModel().getReaction(i); if (reaction.isSetCompartment()) { if (reaction.getCompartment().equals(compartmentId)){ remove = false; reactionsUsing.add(reaction.getId()); } } } ArrayList<String> outsideUsing = new ArrayList<String>(); for (int i = 0; i < document.getModel().getCompartmentCount(); i++) { Compartment compartment = document.getModel().getCompartment(i); if (compartment.isSetOutside()) { if (compartment.getOutside().equals(compartmentId)) { remove = false; outsideUsing.add(compartment.getId()); } } } if (!remove) { String message = "Unable to remove the selected compartment."; if (speciesUsing.size() != 0) { message += "\n\nIt contains the following species:\n"; String[] vars = speciesUsing.toArray(new String[0]); Utility.sort(vars); for (int i = 0; i < vars.length; i++) { if (i == vars.length - 1) { message += vars[i]; } else { message += vars[i] + "\n"; } } } if (reactionsUsing.size() != 0) { message += "\n\nIt contains the following reactions:\n"; String[] vars = reactionsUsing.toArray(new String[0]); Utility.sort(vars); for (int i = 0; i < vars.length; i++) { if (i == vars.length - 1) { message += vars[i]; } else { message += vars[i] + "\n"; } } } if (outsideUsing.size() != 0) { message += "\n\nIt outside the following compartments:\n"; String[] vars = outsideUsing.toArray(new String[0]); Utility.sort(vars); for (int i = 0; i < vars.length; i++) { if (i == vars.length - 1) { message += vars[i]; } else { message += vars[i] + "\n"; } } } JTextArea messageArea = new JTextArea(message); messageArea.setEditable(false); JScrollPane scroll = new JScrollPane(); scroll.setMinimumSize(new Dimension(300, 300)); scroll.setPreferredSize(new Dimension(300, 300)); scroll.setViewportView(messageArea); JOptionPane.showMessageDialog(Gui.frame, scroll, "Unable To Remove Compartment", JOptionPane.ERROR_MESSAGE); } return !remove; } /** * Check if a variable is in use. */ public static boolean variableInUse(SBMLDocument document, String species, boolean zeroDim, boolean displayMessage, boolean checkReactions) { Model model = document.getModel(); boolean inUse = false; boolean isSpecies = (document.getModel().getSpecies(species) != null); if (species.equals("")) { return inUse; } boolean usedInModelConversionFactor = false; ArrayList<String> stoicMathUsing = new ArrayList<String>(); ArrayList<String> reactantsUsing = new ArrayList<String>(); ArrayList<String> productsUsing = new ArrayList<String>(); ArrayList<String> modifiersUsing = new ArrayList<String>(); ArrayList<String> kineticLawsUsing = new ArrayList<String>(); ArrayList<String> defaultParametersNeeded = new ArrayList<String>(); ArrayList<String> initsUsing = new ArrayList<String>(); ArrayList<String> rulesUsing = new ArrayList<String>(); ArrayList<String> constraintsUsing = new ArrayList<String>(); ArrayList<String> eventsUsing = new ArrayList<String>(); ArrayList<String> speciesUsing = new ArrayList<String>(); if (document.getLevel() > 2) { if (model.isSetConversionFactor() && model.getConversionFactor().equals(species)) { inUse = true; usedInModelConversionFactor = true; } for (int i = 0; i < model.getSpeciesCount(); i++) { Species speciesConv = model.getListOfSpecies().get(i); if (speciesConv.isSetConversionFactor()) { if (species.equals(speciesConv.getConversionFactor())) { inUse = true; speciesUsing.add(speciesConv.getId()); } } } } if (checkReactions) { for (int i = 0; i < model.getReactionCount(); i++) { Reaction reaction = model.getListOfReactions().get(i); if (isSpecies && (BioModel.isDegradationReaction(reaction) || BioModel.isDiffusionReaction(reaction) || BioModel.isConstitutiveReaction(reaction))) continue; if (BioModel.isProductionReaction(reaction) && BioModel.IsDefaultProductionParameter(species)) { defaultParametersNeeded.add(reaction.getId()); inUse = true; } for (int j = 0; j < reaction.getProductCount(); j++) { if (reaction.getProduct(j).isSetSpecies()) { String specRef = reaction.getProduct(j).getSpecies(); if (species.equals(specRef)) { inUse = true; productsUsing.add(reaction.getId()); } } } for (int j = 0; j < reaction.getReactantCount(); j++) { if (reaction.getReactant(j).isSetSpecies()) { String specRef = reaction.getReactant(j).getSpecies(); if (species.equals(specRef)) { inUse = true; reactantsUsing.add(reaction.getId()); } } } for (int j = 0; j < reaction.getModifierCount(); j++) { if (reaction.getModifier(j).isSetSpecies()) { String specRef = reaction.getModifier(j).getSpecies(); if (species.equals(specRef)) { inUse = true; modifiersUsing.add(reaction.getId()); } } } if (reaction.isSetKineticLaw()) { String[] vars = SBMLutilities.myFormulaToString(reaction.getKineticLaw().getMath()).split(" |\\(|\\)|\\,"); for (int j = 0; j < vars.length; j++) { if (vars[j].equals(species)) { kineticLawsUsing.add(reaction.getId()); inUse = true; break; } } } } } for (int i = 0; i < model.getInitialAssignmentCount(); i++) { InitialAssignment init = model.getInitialAssignment(i); String initStr = SBMLutilities.myFormulaToString(init.getMath()); String[] vars = initStr.split(" |\\(|\\)|\\,"); for (int j = 0; j < vars.length; j++) { if (vars[j].equals(species)) { initsUsing.add(init.getVariable() + " = " + SBMLutilities.myFormulaToString(init.getMath())); inUse = true; break; } } } for (int i = 0; i < model.getRuleCount(); i++) { Rule rule = model.getRule(i); String initStr = SBMLutilities.myFormulaToString(rule.getMath()); if (rule.isAssignment() || rule.isRate()) { initStr += " = " + getVariable(rule); } String[] vars = initStr.split(" |\\(|\\)|\\,"); for (int j = 0; j < vars.length; j++) { if (vars[j].equals(species)) { if (rule.isAssignment()) { rulesUsing.add(getVariable(rule) + " = " + SBMLutilities.myFormulaToString(rule.getMath())); } else if (rule.isRate()) { rulesUsing.add("d(" + getVariable(rule) + ")/dt = " + SBMLutilities.myFormulaToString(rule.getMath())); } else { rulesUsing.add("0 = " + SBMLutilities.myFormulaToString(rule.getMath())); } inUse = true; break; } } } for (int i = 0; i < model.getConstraintCount(); i++) { Constraint constraint = model.getConstraint(i); String consStr = SBMLutilities.myFormulaToString(constraint.getMath()); String[] vars = consStr.split(" |\\(|\\)|\\,"); for (int j = 0; j < vars.length; j++) { if (vars[j].equals(species)) { constraintsUsing.add(consStr); inUse = true; break; } } } for (int i = 0; i < model.getEventCount(); i++) { org.sbml.jsbml.Event event = model.getEvent(i); String trigger = SBMLutilities.myFormulaToString(event.getTrigger().getMath()); String eventStr = trigger; if (event.isSetDelay()) { eventStr += " " + SBMLutilities.myFormulaToString(event.getDelay().getMath()); } for (int j = 0; j < event.getEventAssignmentCount(); j++) { eventStr += " " + (event.getListOfEventAssignments().get(j).getVariable()) + " = " + SBMLutilities.myFormulaToString(event.getListOfEventAssignments().get(j).getMath()); } String[] vars = eventStr.split(" |\\(|\\)|\\,"); for (int j = 0; j < vars.length; j++) { if (vars[j].equals(species)) { eventsUsing.add(event.getId()); inUse = true; break; } } } if (inUse) { String reactants = ""; String products = ""; String modifiers = ""; String kineticLaws = ""; String defaults = ""; String stoicMath = ""; String initAssigns = ""; String rules = ""; String constraints = ""; String events = ""; String speciesConvFac = ""; String[] speciesConvFactors = speciesUsing.toArray(new String[0]); Utility.sort(speciesConvFactors); String[] reacts = reactantsUsing.toArray(new String[0]); Utility.sort(reacts); String[] prods = productsUsing.toArray(new String[0]); Utility.sort(prods); String[] mods = modifiersUsing.toArray(new String[0]); Utility.sort(mods); String[] kls = kineticLawsUsing.toArray(new String[0]); Utility.sort(kls); String[] dps = defaultParametersNeeded.toArray(new String[0]); Utility.sort(dps); String[] sm = stoicMathUsing.toArray(new String[0]); Utility.sort(sm); String[] inAs = initsUsing.toArray(new String[0]); Utility.sort(inAs); String[] ruls = rulesUsing.toArray(new String[0]); Utility.sort(ruls); String[] consts = constraintsUsing.toArray(new String[0]); Utility.sort(consts); String[] evs = eventsUsing.toArray(new String[0]); Utility.sort(evs); for (int i = 0; i < speciesConvFactors.length; i++) { if (i == speciesConvFactors.length - 1) { speciesConvFac += speciesConvFactors[i]; } else { speciesConvFac += speciesConvFactors[i] + "\n"; } } for (int i = 0; i < reacts.length; i++) { if (i == reacts.length - 1) { reactants += reacts[i]; } else { reactants += reacts[i] + "\n"; } } for (int i = 0; i < prods.length; i++) { if (i == prods.length - 1) { products += prods[i]; } else { products += prods[i] + "\n"; } } for (int i = 0; i < mods.length; i++) { if (i == mods.length - 1) { modifiers += mods[i]; } else { modifiers += mods[i] + "\n"; } } for (int i = 0; i < kls.length; i++) { if (i == kls.length - 1) { kineticLaws += kls[i]; } else { kineticLaws += kls[i] + "\n"; } } for (int i = 0; i < dps.length; i++) { if (i == dps.length - 1) { defaults += dps[i]; } else { defaults += dps[i] + "\n"; } } for (int i = 0; i < sm.length; i++) { if (i == sm.length - 1) { stoicMath += sm[i]; } else { stoicMath += sm[i] + "\n"; } } for (int i = 0; i < inAs.length; i++) { if (i == inAs.length - 1) { initAssigns += inAs[i]; } else { initAssigns += inAs[i] + "\n"; } } for (int i = 0; i < ruls.length; i++) { if (i == ruls.length - 1) { rules += ruls[i]; } else { rules += ruls[i] + "\n"; } } for (int i = 0; i < consts.length; i++) { if (i == consts.length - 1) { constraints += consts[i]; } else { constraints += consts[i] + "\n"; } } for (int i = 0; i < evs.length; i++) { if (i == evs.length - 1) { events += evs[i]; } else { events += evs[i] + "\n"; } } String message; if (zeroDim) { message = "Unable to change compartment to 0-dimensions."; } else { message = "Unable to remove the selected variable."; } if (usedInModelConversionFactor) { message += "\n\nIt is used as the model conversion factor.\n"; } if (speciesUsing.size() != 0) { message += "\n\nIt is used as a conversion factor in the following species:\n" + speciesConvFac; } if (reactantsUsing.size() != 0) { message += "\n\nIt is used as a reactant in the following reactions:\n" + reactants; } if (productsUsing.size() != 0) { message += "\n\nIt is used as a product in the following reactions:\n" + products; } if (modifiersUsing.size() != 0) { message += "\n\nIt is used as a modifier in the following reactions:\n" + modifiers; } if (kineticLawsUsing.size() != 0) { message += "\n\nIt is used in the kinetic law in the following reactions:\n" + kineticLaws; } if (defaultParametersNeeded.size() != 0) { message += "\n\nDefault parameter is needed by the following reactions:\n" + defaults; } if (stoicMathUsing.size() != 0) { message += "\n\nIt is used in the stoichiometry math for the following reaction/species:\n" + stoicMath; } if (initsUsing.size() != 0) { message += "\n\nIt is used in the following initial assignments:\n" + initAssigns; } if (rulesUsing.size() != 0) { message += "\n\nIt is used in the following rules:\n" + rules; } if (constraintsUsing.size() != 0) { message += "\n\nIt is used in the following constraints:\n" + constraints; } if (eventsUsing.size() != 0) { message += "\n\nIt is used in the following events:\n" + events; } if (displayMessage) { JTextArea messageArea = new JTextArea(message); messageArea.setEditable(false); JScrollPane scroll = new JScrollPane(); scroll.setMinimumSize(new Dimension(400, 400)); scroll.setPreferredSize(new Dimension(400, 400)); scroll.setViewportView(messageArea); JOptionPane.showMessageDialog(Gui.frame, scroll, "Unable To Remove Variable", JOptionPane.ERROR_MESSAGE); } } return inUse; } /** * Update variable Id */ public static void updateVarId(SBMLDocument document, boolean isSpecies, String origId, String newId) { if (origId.equals(newId)) return; Model model = document.getModel(); for (int i = 0; i < model.getReactionCount(); i++) { Reaction reaction = model.getListOfReactions().get(i); for (int j = 0; j < reaction.getProductCount(); j++) { if (reaction.getProduct(j).isSetSpecies()) { SpeciesReference specRef = reaction.getProduct(j); if (isSpecies && origId.equals(specRef.getSpecies())) { specRef.setSpecies(newId); } } } if (isSpecies) { for (int j = 0; j < reaction.getModifierCount(); j++) { if (reaction.getModifier(j).isSetSpecies()) { ModifierSpeciesReference specRef = reaction.getModifier(j); if (origId.equals(specRef.getSpecies())) { specRef.setSpecies(newId); } } } } for (int j = 0; j < reaction.getReactantCount(); j++) { if (reaction.getReactant(j).isSetSpecies()) { SpeciesReference specRef = reaction.getReactant(j); if (isSpecies && origId.equals(specRef.getSpecies())) { specRef.setSpecies(newId); } } } if (reaction.isSetKineticLaw()) { reaction.getKineticLaw().setMath(SBMLutilities.updateMathVar(reaction.getKineticLaw().getMath(), origId, newId)); } } if (document.getLevel() > 2) { if (model.isSetConversionFactor() && origId.equals(model.getConversionFactor())) { model.setConversionFactor(newId); } if (model.getSpeciesCount() > 0) { for (int i = 0; i < model.getSpeciesCount(); i++) { Species species = model.getListOfSpecies().get(i); if (species.isSetConversionFactor()) { if (origId.equals(species.getConversionFactor())) { species.setConversionFactor(newId); } } } } } if (model.getInitialAssignmentCount() > 0) { for (int i = 0; i < model.getInitialAssignmentCount(); i++) { InitialAssignment init = model.getListOfInitialAssignments().get(i); if (origId.equals(init.getVariable())) { init.setVariable(newId); } init.setMath(SBMLutilities.updateMathVar(init.getMath(), origId, newId)); } try { if (SBMLutilities.checkCycles(document)) { JOptionPane.showMessageDialog(Gui.frame, "Cycle detected within initial assignments, assignment rules, and rate laws.", "Cycle Detected", JOptionPane.ERROR_MESSAGE); } } catch (Exception e) { JOptionPane.showMessageDialog(Gui.frame, "Cycle detected in assignments.", "Cycle Detected", JOptionPane.ERROR_MESSAGE); } } if (model.getRuleCount() > 0) { for (int i = 0; i < model.getRuleCount(); i++) { Rule rule = model.getListOfRules().get(i); if (isSetVariable(rule) && origId.equals(getVariable(rule))) { setVariable(rule, newId); } rule.setMath(SBMLutilities.updateMathVar(rule.getMath(), origId, newId)); } try { if (SBMLutilities.checkCycles(document)) { JOptionPane.showMessageDialog(Gui.frame, "Cycle detected within initial assignments, assignment rules, and rate laws.", "Cycle Detected", JOptionPane.ERROR_MESSAGE); } } catch (Exception e) { JOptionPane.showMessageDialog(Gui.frame, "Cycle detected in assignments.", "Cycle Detected", JOptionPane.ERROR_MESSAGE); } } if (model.getConstraintCount() > 0) { for (int i = 0; i < model.getConstraintCount(); i++) { Constraint constraint = model.getListOfConstraints().get(i); constraint.setMath(SBMLutilities.updateMathVar(constraint.getMath(), origId, newId)); } } if (model.getEventCount() > 0) { for (int i = 0; i < model.getEventCount(); i++) { org.sbml.jsbml.Event event = model.getListOfEvents().get(i); if (event.isSetTrigger()) { event.getTrigger().setMath(SBMLutilities.updateMathVar(event.getTrigger().getMath(), origId, newId)); } if (event.isSetDelay()) { event.getDelay().setMath(SBMLutilities.updateMathVar(event.getDelay().getMath(), origId, newId)); } for (int j = 0; j < event.getEventAssignmentCount(); j++) { EventAssignment ea = event.getListOfEventAssignments().get(j); if (ea.getVariable().equals(origId)) { ea.setVariable(newId); } if (ea.isSetMath()) { ea.setMath(SBMLutilities.updateMathVar(ea.getMath(), origId, newId)); } } } } } /** * Variable that is updated by a rule or event cannot be constant */ public static boolean checkConstant(SBMLDocument document, String varType, String val) { for (int i = 0; i < document.getModel().getRuleCount(); i++) { Rule rule = document.getModel().getRule(i); if (getVariable(rule)!=null && getVariable(rule).equals(val)) { JOptionPane.showMessageDialog(Gui.frame, varType + " cannot be constant if updated by a rule.", varType + " Cannot Be Constant", JOptionPane.ERROR_MESSAGE); return true; } } for (int i = 0; i < document.getModel().getEventCount(); i++) { org.sbml.jsbml.Event event = document.getModel().getListOfEvents().get(i); for (int j = 0; j < event.getEventAssignmentCount(); j++) { EventAssignment ea = event.getListOfEventAssignments().get(j); if (ea.getVariable().equals(val)) { JOptionPane.showMessageDialog(Gui.frame, varType + " cannot be constant if updated by an event.", varType + " Cannot Be Constant", JOptionPane.ERROR_MESSAGE); return true; } } } return false; } /** * Checks consistency of the sbml file. */ public static boolean check(String file,SBMLDocument doc,boolean warnings,boolean overdetermined) { String message = ""; long numErrors = 0; if (Gui.isLibsbmlFound()) { org.sbml.libsbml.SBMLDocument document = null; if (doc == null) { document = new org.sbml.libsbml.SBMLReader().readSBML(file); } else { try { document = new org.sbml.libsbml.SBMLReader().readSBMLFromString(new SBMLWriter().writeSBMLToString(doc)); } catch (SBMLException e) { JOptionPane.showMessageDialog(Gui.frame, "Invalid SBML file","Error Checking File", JOptionPane.ERROR_MESSAGE); return false; } catch (XMLStreamException e) { JOptionPane.showMessageDialog(Gui.frame, "Invalid XML in SBML file","Error Checking File", JOptionPane.ERROR_MESSAGE); return false; } } if (document==null) return false; if (overdetermined) { document.setConsistencyChecks(libsbmlConstants.LIBSBML_CAT_GENERAL_CONSISTENCY, false); document.setConsistencyChecks(libsbmlConstants.LIBSBML_CAT_IDENTIFIER_CONSISTENCY, false); document.setConsistencyChecks(libsbmlConstants.LIBSBML_CAT_INTERNAL_CONSISTENCY, false); document.setConsistencyChecks(libsbmlConstants.LIBSBML_CAT_OVERDETERMINED_MODEL, true); } else { document.setConsistencyChecks(libsbmlConstants.LIBSBML_CAT_GENERAL_CONSISTENCY, true); document.setConsistencyChecks(libsbmlConstants.LIBSBML_CAT_IDENTIFIER_CONSISTENCY, true); document.setConsistencyChecks(libsbmlConstants.LIBSBML_CAT_INTERNAL_CONSISTENCY, true); document.setConsistencyChecks(libsbmlConstants.LIBSBML_CAT_OVERDETERMINED_MODEL, true); } if (warnings) { document.setConsistencyChecks(libsbmlConstants.LIBSBML_CAT_UNITS_CONSISTENCY, true); document.setConsistencyChecks(libsbmlConstants.LIBSBML_CAT_MATHML_CONSISTENCY, true); document.setConsistencyChecks(libsbmlConstants.LIBSBML_CAT_SBO_CONSISTENCY, true); document.setConsistencyChecks(libsbmlConstants.LIBSBML_CAT_MODELING_PRACTICE, true); } else { document.setConsistencyChecks(libsbmlConstants.LIBSBML_CAT_UNITS_CONSISTENCY, false); document.setConsistencyChecks(libsbmlConstants.LIBSBML_CAT_MATHML_CONSISTENCY, false); document.setConsistencyChecks(libsbmlConstants.LIBSBML_CAT_SBO_CONSISTENCY, false); document.setConsistencyChecks(libsbmlConstants.LIBSBML_CAT_MODELING_PRACTICE, false); } numErrors = document.checkConsistency(); for (int i = 0; i < numErrors; i++) { String error = document.getError(i).getMessage(); message += i + ":" + error + "\n"; } } else { SBMLDocument document = doc; if (document==null) { document = SBMLutilities.readSBML(file); } if (document==null) return false; if (overdetermined) { document.setConsistencyChecks(SBMLValidator.CHECK_CATEGORY.GENERAL_CONSISTENCY, false); document.setConsistencyChecks(SBMLValidator.CHECK_CATEGORY.IDENTIFIER_CONSISTENCY, false); document.setConsistencyChecks(SBMLValidator.CHECK_CATEGORY.OVERDETERMINED_MODEL, true); } else { document.setConsistencyChecks(SBMLValidator.CHECK_CATEGORY.GENERAL_CONSISTENCY, true); document.setConsistencyChecks(SBMLValidator.CHECK_CATEGORY.IDENTIFIER_CONSISTENCY, true); document.setConsistencyChecks(SBMLValidator.CHECK_CATEGORY.OVERDETERMINED_MODEL, true); } if (warnings) { document.setConsistencyChecks(SBMLValidator.CHECK_CATEGORY.UNITS_CONSISTENCY, true); document.setConsistencyChecks(SBMLValidator.CHECK_CATEGORY.MATHML_CONSISTENCY, true); document.setConsistencyChecks(SBMLValidator.CHECK_CATEGORY.SBO_CONSISTENCY, true); document.setConsistencyChecks(SBMLValidator.CHECK_CATEGORY.MODELING_PRACTICE, true); } else { document.setConsistencyChecks(SBMLValidator.CHECK_CATEGORY.UNITS_CONSISTENCY, false); document.setConsistencyChecks(SBMLValidator.CHECK_CATEGORY.MATHML_CONSISTENCY, false); document.setConsistencyChecks(SBMLValidator.CHECK_CATEGORY.SBO_CONSISTENCY, false); document.setConsistencyChecks(SBMLValidator.CHECK_CATEGORY.MODELING_PRACTICE, false); } numErrors = document.checkConsistency(); for (int i = 0; i < numErrors; i++) { String error = document.getError(i).getMessage(); message += i + ":" + error + "\n"; } } if (numErrors > 0) { JTextArea messageArea = new JTextArea(message); messageArea.setLineWrap(true); messageArea.setEditable(false); JScrollPane scroll = new JScrollPane(); scroll.setMinimumSize(new Dimension(600, 600)); scroll.setPreferredSize(new Dimension(600, 600)); scroll.setViewportView(messageArea); JOptionPane.showMessageDialog(Gui.frame, scroll, "SBML Errors and Warnings", JOptionPane.ERROR_MESSAGE); return false; } return true; } public static boolean checkUnitsInAssignmentRule(SBMLDocument document,Rule rule) { UnitDefinition unitDef = rule.getDerivedUnitDefinition(); UnitDefinition unitDefVar; Species species = document.getModel().getSpecies(getVariable(rule)); Compartment compartment = document.getModel().getCompartment(getVariable(rule)); Parameter parameter = document.getModel().getParameter(getVariable(rule)); if (species != null) { unitDefVar = species.getDerivedUnitDefinition(); } else if (compartment != null) { unitDefVar = compartment.getDerivedUnitDefinition(); } else { unitDefVar = parameter.getDerivedUnitDefinition(); } if (!UnitDefinition.areEquivalent(unitDef, unitDefVar)) { return true; } return false; } public static boolean checkUnitsInRateRule(SBMLDocument document,Rule rule) { UnitDefinition unitDef = rule.getDerivedUnitDefinition(); UnitDefinition unitDefVar; Species species = document.getModel().getSpecies(getVariable(rule)); Compartment compartment = document.getModel().getCompartment(getVariable(rule)); Parameter parameter = document.getModel().getParameter(getVariable(rule)); if (species != null) { unitDefVar = species.getDerivedUnitDefinition(); } else if (compartment != null) { unitDefVar = compartment.getDerivedUnitDefinition(); } else { unitDefVar = parameter.getDerivedUnitDefinition(); } if (document.getModel().getUnitDefinition("time") != null) { UnitDefinition timeUnitDef = document.getModel().getUnitDefinition("time"); for (int i = 0; i < timeUnitDef.getUnitCount(); i++) { Unit timeUnit = timeUnitDef.getUnit(i); Unit recTimeUnit = unitDefVar.createUnit(); recTimeUnit.setKind(timeUnit.getKind()); if (document.getLevel() < 3) { recTimeUnit.setExponent(timeUnit.getExponent() * (-1)); } else { recTimeUnit.setExponent(timeUnit.getExponent() * (-1)); } recTimeUnit.setScale(timeUnit.getScale()); recTimeUnit.setMultiplier(timeUnit.getMultiplier()); } } else { Unit unit = unitDefVar.createUnit(); unit.setKind(Unit.Kind.valueOf("second".toUpperCase())); unit.setExponent(-1.0); unit.setScale(0); unit.setMultiplier(1.0); } if (!UnitDefinition.areEquivalent(unitDef, unitDefVar)) { return true; } return false; } public static boolean checkUnitsInInitialAssignment(SBMLDocument document,InitialAssignment init) { UnitDefinition unitDef = init.getDerivedUnitDefinition(); UnitDefinition unitDefVar; Species species = document.getModel().getSpecies(init.getVariable()); Compartment compartment = document.getModel().getCompartment(init.getVariable()); Parameter parameter = document.getModel().getParameter(init.getVariable()); if (species != null) { unitDefVar = species.getDerivedUnitDefinition(); } else if (compartment != null) { unitDefVar = compartment.getDerivedUnitDefinition(); } else { unitDefVar = parameter.getDerivedUnitDefinition(); } if (!UnitDefinition.areEquivalent(unitDef, unitDefVar)) { return true; } return false; } public static boolean checkUnitsInKineticLaw(SBMLDocument document,KineticLaw law) { UnitDefinition unitDef = law.getDerivedUnitDefinition(); UnitDefinition unitDefLaw = new UnitDefinition(document.getLevel(), document.getVersion()); if (document.getModel().getUnitDefinition("substance") != null) { UnitDefinition subUnitDef = document.getModel().getUnitDefinition("substance"); for (int i = 0; i < subUnitDef.getUnitCount(); i++) { Unit subUnit = subUnitDef.getUnit(i); unitDefLaw.addUnit(subUnit); } } else { Unit unit = unitDefLaw.createUnit(); unit.setKind(Unit.Kind.valueOf("mole".toUpperCase())); unit.setExponent(1.0); unit.setScale(0); unit.setMultiplier(1.0); } if (document.getModel().getUnitDefinition("time") != null) { UnitDefinition timeUnitDef = document.getModel().getUnitDefinition("time"); for (int i = 0; i < timeUnitDef.getUnitCount(); i++) { Unit timeUnit = timeUnitDef.getUnit(i); Unit recTimeUnit = unitDefLaw.createUnit(); recTimeUnit.setKind(timeUnit.getKind()); if (document.getLevel() < 3) { recTimeUnit.setExponent(timeUnit.getExponent() * (-1)); } else { recTimeUnit.setExponent(timeUnit.getExponent() * (-1)); } recTimeUnit.setScale(timeUnit.getScale()); recTimeUnit.setMultiplier(timeUnit.getMultiplier()); } } else { Unit unit = unitDefLaw.createUnit(); unit.setKind(Unit.Kind.valueOf("second".toUpperCase())); unit.setExponent(-1.0); unit.setScale(0); unit.setMultiplier(1.0); } if (!UnitDefinition.areEquivalent(unitDef, unitDefLaw)) { return true; } return false; } public static boolean checkUnitsInEventDelay(Delay delay) { UnitDefinition unitDef = delay.getDerivedUnitDefinition(); if (unitDef != null && !(unitDef.isVariantOfTime())) { return true; } return false; } public static boolean checkUnitsInEventAssignment(SBMLDocument document,EventAssignment assign) { UnitDefinition unitDef = assign.getDerivedUnitDefinition(); UnitDefinition unitDefVar; Species species = document.getModel().getSpecies(assign.getVariable()); Compartment compartment = document.getModel().getCompartment(assign.getVariable()); Parameter parameter = document.getModel().getParameter(assign.getVariable()); if (species != null) { unitDefVar = species.getDerivedUnitDefinition(); } else if (compartment != null) { unitDefVar = compartment.getDerivedUnitDefinition(); } else { unitDefVar = parameter.getDerivedUnitDefinition(); } if (!UnitDefinition.areEquivalent(unitDef, unitDefVar)) { return true; } return false; } /** * Checks consistency of the sbml file. */ public static boolean checkUnits(SBMLDocument document) { long numErrors = 0; String message = "Change in unit definition causes unit errors in the following elements:\n"; for (int i = 0; i < document.getModel().getReactionCount(); i++) { Reaction reaction = document.getModel().getReaction(i); if (!reaction.isSetKineticLaw()) continue; KineticLaw law = reaction.getKineticLaw(); if (law != null) { if (checkUnitsInKineticLaw(document,law)) { message += "Reaction: " + reaction.getId() + "\n"; numErrors++; } } } for (int i = 0; i < document.getModel().getInitialAssignmentCount(); i++) { InitialAssignment init = document.getModel().getInitialAssignment(i); if (checkUnitsInInitialAssignment(document,init)) { message += "Initial assignment on variable: " + init.getVariable() + "\n"; numErrors++; } } for (int i = 0; i < document.getModel().getRuleCount(); i++) { Rule rule = document.getModel().getRule(i); if (rule.isAssignment()) { if (checkUnitsInAssignmentRule(document,rule)) { message += "Assignment rule on variable: " + getVariable(rule) + "\n"; numErrors++; } } else if (rule.isRate()) { if (checkUnitsInRateRule(document,rule)) { message += "Rate rule on variable: " + getVariable(rule) + "\n"; numErrors++; } } } for (int i = 0; i < document.getModel().getEventCount(); i++) { Event event = document.getModel().getEvent(i); Delay delay = event.getDelay(); if (delay != null) { if (checkUnitsInEventDelay(delay)) { message += "Delay on event: " + event.getId() + "\n"; numErrors++; } } for (int j = 0; j < event.getEventAssignmentCount(); j++) { EventAssignment assign = event.getListOfEventAssignments().get(j); if (checkUnitsInEventAssignment(document,assign)) { message += "Event assignment for event " + event.getId() + " on variable: " + assign.getVariable() + "\n"; numErrors++; } } } /* document.setConsistencyChecks(libsbml.LIBSBML_CAT_GENERAL_CONSISTENCY, false); document.setConsistencyChecks(libsbml.LIBSBML_CAT_IDENTIFIER_CONSISTENCY, false); document.setConsistencyChecks(libsbml.LIBSBML_CAT_UNITS_CONSISTENCY, true); document.setConsistencyChecks(libsbml.LIBSBML_CAT_MATHML_CONSISTENCY, false); document.setConsistencyChecks(libsbml.LIBSBML_CAT_SBO_CONSISTENCY, false); document.setConsistencyChecks(libsbml.LIBSBML_CAT_MODELING_PRACTICE, false); document.setConsistencyChecks(libsbml.LIBSBML_CAT_OVERDETERMINED_MODEL, false); long numErrorsWarnings = document.checkConsistency(); for (long i = 0; i < numErrorsWarnings; i++) { if (!document.getError(i).isWarning()) { String error = document.getError(i).getMessage(); message += i + ":" + error + "\n"; numErrors++; } } */ if (numErrors > 0) { JTextArea messageArea = new JTextArea(message); messageArea.setLineWrap(true); messageArea.setEditable(false); JScrollPane scroll = new JScrollPane(); scroll.setMinimumSize(new Dimension(600, 600)); scroll.setPreferredSize(new Dimension(600, 600)); scroll.setViewportView(messageArea); JOptionPane.showMessageDialog(Gui.frame, scroll, "Unit Errors in Model", JOptionPane.ERROR_MESSAGE); return true; } return false; } public static void addRandomFunctions(SBMLDocument document) { Model model = document.getModel(); createFunction(model, "uniform", "Uniform distribution", "lambda(a,b,(a+b)/2)"); createFunction(model, "normal", "Normal distribution", "lambda(m,s,m)"); createFunction(model, "exponential", "Exponential distribution", "lambda(l,1/l)"); createFunction(model, "gamma", "Gamma distribution", "lambda(a,b,a*b)"); createFunction(model, "lognormal", "Lognormal distribution", "lambda(z,s,exp(z+s^2/2))"); createFunction(model, "chisq", "Chi-squared distribution", "lambda(nu,nu)"); createFunction(model, "laplace", "Laplace distribution", "lambda(a,0)"); createFunction(model, "cauchy", "Cauchy distribution", "lambda(a,a)"); createFunction(model, "rayleigh", "Rayleigh distribution","lambda(s,s*sqrt(pi/2))"); createFunction(model, "poisson", "Poisson distribution", "lambda(mu,mu)"); createFunction(model, "binomial", "Binomial distribution", "lambda(p,n,p*n)"); createFunction(model, "bernoulli", "Bernoulli distribution", "lambda(p,p)"); } /** * Add a new function */ public static void createFunction(Model model, String id, String name, String formula) { if (model.getFunctionDefinition(id) == null) { FunctionDefinition f = model.createFunctionDefinition(); f.setId(id); f.setName(name); try { IFormulaParser parser = new FormulaParserLL3(new StringReader("")); f.setMath(ASTNode.parseFormula(formula, parser)); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public static boolean isBoolean(SBMLDocument document, ASTNode node) { if (node == null) { return false; } else if ( node.isBoolean() ) { return true; } else if (node.getType() == ASTNode.Type.FUNCTION) { FunctionDefinition fd = document.getModel().getFunctionDefinition( node.getName() ); if (fd != null && fd.isSetMath()) { return isBoolean( document, fd.getMath().getRightChild() ); } return false; } else if (node.getType() == ASTNode.Type.FUNCTION_PIECEWISE) { for (int c = 0; c < node.getChildCount(); c += 2) { if ( !isBoolean( document, node.getChild(c) ) ) return false; } return true; } return false; } public static boolean isBoolean(Parameter parameter) { if (parameter.isSetSBOTerm()) { if (parameter.getSBOTerm()==GlobalConstants.SBO_BOOLEAN) { parameter.setSBOTerm(GlobalConstants.SBO_LOGICAL); return true; } else if (parameter.getSBOTerm()==GlobalConstants.SBO_LOGICAL) { return true; } } return false; } public static boolean isPlace(Parameter parameter) { if (parameter.isSetSBOTerm()) { if (parameter.getSBOTerm()==GlobalConstants.SBO_PLACE) { parameter.setSBOTerm(GlobalConstants.SBO_PETRI_NET_PLACE); return true; } else if (parameter.getSBOTerm()==GlobalConstants.SBO_PETRI_NET_PLACE) { return true; } } return false; } public static boolean isTransition(Event event) { if (event.isSetSBOTerm()) { if (event.getSBOTerm()==GlobalConstants.SBO_TRANSITION) { event.setSBOTerm(GlobalConstants.SBO_PETRI_NET_TRANSITION); return true; } else if (event.getSBOTerm()==GlobalConstants.SBO_PETRI_NET_TRANSITION) { return true; } } return false; } public static ASTNode addPreset(ASTNode math,String place) { return myParseFormula("and("+myFormulaToString(math)+",eq("+place+","+"1))"); } public static ASTNode removePreset(ASTNode math,String place) { if (math.getType() == ASTNode.Type.LOGICAL_AND) { ASTNode rightChild = math.getRightChild(); if (rightChild.getType() == ASTNode.Type.RELATIONAL_EQ && rightChild.getLeftChild().getName().equals(place)) { return deepCopy(math.getLeftChild()); } } for (int i = 0; i < math.getChildCount(); i++) { ASTNode child = removePreset(math.getChild(i),place); math.replaceChild(i, child); } return deepCopy(math); } public static String addBoolean(String formula,String boolVar) { formula = formula.replace(" "+boolVar+" ", " eq("+boolVar+",1) "); formula = formula.replace(","+boolVar+",",",eq("+boolVar+",1),"); formula = formula.replace("("+boolVar+",", "(eq("+boolVar+",1),"); formula = formula.replace(","+boolVar+")", ",eq("+boolVar+",1))"); formula = formula.replace("("+boolVar+" ", "(eq("+boolVar+",1) "); formula = formula.replace(" "+boolVar+")", " eq("+boolVar+",1))"); formula = formula.replace("("+boolVar+")", " eq("+boolVar+",1)"); if (formula.startsWith(boolVar+" ")) { formula = formula.replaceFirst(boolVar+" ", "eq(" + boolVar + ",1)"); } if (formula.endsWith(" " + boolVar)) { formula = formula.replaceFirst(" " + boolVar, "eq(" + boolVar + ",1)"); } if (formula.equals(boolVar)) { formula = formula.replace(boolVar, "eq(" + boolVar + ",1)"); } return formula; } public static ASTNode removeBoolean(ASTNode math,String boolVar) { if (math.getType() == ASTNode.Type.RELATIONAL_EQ) { if (math.getLeftChild().getName()!=null && math.getLeftChild().getName().equals(boolVar)) { return deepCopy(math.getLeftChild()); } } for (int i = 0; i < math.getChildCount(); i++) { ASTNode child = removeBoolean(math.getChild(i),boolVar); math.replaceChild(i, child); } return deepCopy(math); } public static String myFormulaToStringInfix(ASTNode math) { if (math.getType() == ASTNode.Type.CONSTANT_E) { return "exponentiale"; } else if (math.getType() == ASTNode.Type.CONSTANT_FALSE) { return "false"; } else if (math.getType() == ASTNode.Type.CONSTANT_PI) { return "pi"; } else if (math.getType() == ASTNode.Type.CONSTANT_TRUE) { return "true"; } else if (math.getType() == ASTNode.Type.DIVIDE) { String leftStr = myFormulaToStringInfix(math.getLeftChild()); String rightStr = myFormulaToStringInfix(math.getRightChild()); return "(" + leftStr + " / " + rightStr + ")"; } else if (math.getType() == ASTNode.Type.FUNCTION) { String result = math.getName() + "("; for (int i = 0; i < math.getChildCount(); i++) { String child = myFormulaToStringInfix(math.getChild(i)); result += child; if (i+1 < math.getChildCount()) { result += ","; } } result += ")"; return result; } else if (math.getType() == ASTNode.Type.FUNCTION_ABS) { return "abs(" + myFormulaToStringInfix(math.getChild(0)) + ")"; } else if (math.getType() == ASTNode.Type.FUNCTION_ARCCOS) { return "acos(" + myFormulaToStringInfix(math.getChild(0)) + ")"; } else if (math.getType() == ASTNode.Type.FUNCTION_ARCCOSH) { return "acosh(" + myFormulaToStringInfix(math.getChild(0)) + ")"; } else if (math.getType() == ASTNode.Type.FUNCTION_ARCCOT) { return "acot(" + myFormulaToStringInfix(math.getChild(0)) + ")"; } else if (math.getType() == ASTNode.Type.FUNCTION_ARCCOTH) { return "acoth(" + myFormulaToStringInfix(math.getChild(0)) + ")"; } else if (math.getType() == ASTNode.Type.FUNCTION_ARCCSC) { return "acsc(" + myFormulaToStringInfix(math.getChild(0)) + ")"; } else if (math.getType() == ASTNode.Type.FUNCTION_ARCCSCH) { return "acsch(" + myFormulaToStringInfix(math.getChild(0)) + ")"; } else if (math.getType() == ASTNode.Type.FUNCTION_ARCSEC) { return "asec(" + myFormulaToStringInfix(math.getChild(0)) + ")"; } else if (math.getType() == ASTNode.Type.FUNCTION_ARCSECH) { return "asech(" + myFormulaToStringInfix(math.getChild(0)) + ")"; } else if (math.getType() == ASTNode.Type.FUNCTION_ARCSIN) { return "asin(" + myFormulaToStringInfix(math.getChild(0)) + ")"; } else if (math.getType() == ASTNode.Type.FUNCTION_ARCSINH) { return "asinh(" + myFormulaToStringInfix(math.getChild(0)) + ")"; } else if (math.getType() == ASTNode.Type.FUNCTION_ARCTAN) { return "atan(" + myFormulaToStringInfix(math.getChild(0)) + ")"; } else if (math.getType() == ASTNode.Type.FUNCTION_ARCTANH) { return "atanh(" + myFormulaToStringInfix(math.getChild(0)) + ")"; } else if (math.getType() == ASTNode.Type.FUNCTION_CEILING) { return "ceil(" + myFormulaToStringInfix(math.getChild(0)) + ")"; } else if (math.getType() == ASTNode.Type.FUNCTION_COS) { return "cos(" + myFormulaToStringInfix(math.getChild(0)) + ")"; } else if (math.getType() == ASTNode.Type.FUNCTION_COSH) { return "cosh(" + myFormulaToStringInfix(math.getChild(0)) + ")"; } else if (math.getType() == ASTNode.Type.FUNCTION_COT) { return "cot(" + myFormulaToStringInfix(math.getChild(0)) + ")"; } else if (math.getType() == ASTNode.Type.FUNCTION_COTH) { return "coth(" + myFormulaToStringInfix(math.getChild(0)) + ")"; } else if (math.getType() == ASTNode.Type.FUNCTION_CSC) { return "csc(" + myFormulaToStringInfix(math.getChild(0)) + ")"; } else if (math.getType() == ASTNode.Type.FUNCTION_CSCH) { return "csch(" + myFormulaToStringInfix(math.getChild(0)) + ")"; } else if (math.getType() == ASTNode.Type.FUNCTION_DELAY) { String leftStr = myFormulaToStringInfix(math.getLeftChild()); String rightStr = myFormulaToStringInfix(math.getRightChild()); return "delay(" + leftStr + " , " + rightStr + ")"; } else if (math.getType() == ASTNode.Type.FUNCTION_EXP) { return "exp(" + myFormulaToStringInfix(math.getChild(0)) + ")"; } else if (math.getType() == ASTNode.Type.FUNCTION_FACTORIAL) { return "factorial(" + myFormulaToStringInfix(math.getChild(0)) + ")"; } else if (math.getType() == ASTNode.Type.FUNCTION_FLOOR) { return "floor(" + myFormulaToStringInfix(math.getChild(0)) + ")"; } else if (math.getType() == ASTNode.Type.FUNCTION_LN) { return "ln(" + myFormulaToStringInfix(math.getChild(0)) + ")"; } else if (math.getType() == ASTNode.Type.FUNCTION_LOG) { String result = "log("; for (int i = 0; i < math.getChildCount(); i++) { String child = myFormulaToStringInfix(math.getChild(i)); result += child; if (i+1 < math.getChildCount()) { result += ","; } } result += ")"; return result; } else if (math.getType() == ASTNode.Type.FUNCTION_PIECEWISE) { String result = "piecewise("; for (int i = 0; i < math.getChildCount(); i++) { String child = myFormulaToStringInfix(math.getChild(i)); result += child; if (i+1 < math.getChildCount()) { result += ","; } } result += ")"; return result; } else if (math.getType() == ASTNode.Type.FUNCTION_POWER) { String leftStr = myFormulaToStringInfix(math.getLeftChild()); String rightStr = myFormulaToStringInfix(math.getRightChild()); return "pow(" + leftStr + " , " + rightStr + ")"; } else if (math.getType() == ASTNode.Type.FUNCTION_ROOT) { String leftStr = myFormulaToStringInfix(math.getLeftChild()); String rightStr = myFormulaToStringInfix(math.getRightChild()); return "root(" + leftStr + " , " + rightStr + ")"; } else if (math.getType() == ASTNode.Type.FUNCTION_SEC) { return "sec(" + myFormulaToStringInfix(math.getChild(0)) + ")"; } else if (math.getType() == ASTNode.Type.FUNCTION_SECH) { return "sech(" + myFormulaToStringInfix(math.getChild(0)) + ")"; } else if (math.getType() == ASTNode.Type.FUNCTION_SIN) { return "sin(" + myFormulaToStringInfix(math.getChild(0)) + ")"; } else if (math.getType() == ASTNode.Type.FUNCTION_SINH) { return "sinh(" + myFormulaToStringInfix(math.getChild(0)) + ")"; } else if (math.getType() == ASTNode.Type.FUNCTION_TAN) { return "tan(" + myFormulaToStringInfix(math.getChild(0)) + ")"; } else if (math.getType() == ASTNode.Type.FUNCTION_TANH) { return "tanh(" + myFormulaToStringInfix(math.getChild(0)) + ")"; } else if (math.getType() == ASTNode.Type.INTEGER) { if (math.hasUnits()) { return "" + math.getInteger() + " " + math.getUnits(); } return "" + math.getInteger(); } else if (math.getType() == ASTNode.Type.LOGICAL_AND) { if (math.getChildCount()==0) return ""; String result = "("; for (int i = 0; i < math.getChildCount(); i++) { String child = myFormulaToStringInfix(math.getChild(i)); result += child; if (i+1 < math.getChildCount()) { result += " && "; } } result += ")"; return result; } else if (math.getType() == ASTNode.Type.LOGICAL_NOT) { if (math.getChildCount()==0) return ""; String result = "!("; String child = myFormulaToStringInfix(math.getChild(0)); result += child; result += ")"; return result; } else if (math.getType() == ASTNode.Type.LOGICAL_OR) { if (math.getChildCount()==0) return ""; String result = "("; for (int i = 0; i < math.getChildCount(); i++) { String child = myFormulaToStringInfix(math.getChild(i)); result += child; if (i+1 < math.getChildCount()) { result += " || "; } } result += ")"; return result; } else if (math.getType() == ASTNode.Type.LOGICAL_XOR) { if (math.getChildCount()==0) return ""; String result = "xor("; for (int i = 0; i < math.getChildCount(); i++) { String child = myFormulaToStringInfix(math.getChild(i)); result += child; if (i+1 < math.getChildCount()) { result += ","; } } result += ")"; return result; } else if (math.getType() == ASTNode.Type.MINUS) { if (math.getChildCount()==1) { return "-" + myFormulaToStringInfix(math.getChild(0)); } String leftStr = myFormulaToStringInfix(math.getLeftChild()); String rightStr = myFormulaToStringInfix(math.getRightChild()); return "(" + leftStr + " - " + rightStr + ")"; } else if (math.getType() == ASTNode.Type.NAME) { return math.getName(); } else if (math.getType() == ASTNode.Type.NAME_AVOGADRO) { return "avogadro"; } else if (math.getType() == ASTNode.Type.NAME_TIME) { return "t"; } else if (math.getType() == ASTNode.Type.PLUS) { String returnVal = "("; boolean first = true; for (int i=0; i < math.getChildCount(); i++) { if (first) { first = false; } else { returnVal += " + "; } returnVal += myFormulaToStringInfix(math.getChild(i)); } returnVal += ")"; return returnVal; } else if (math.getType() == ASTNode.Type.POWER) { String leftStr = myFormulaToStringInfix(math.getLeftChild()); String rightStr = myFormulaToStringInfix(math.getRightChild()); return "(" + leftStr + " ^ " + rightStr + ")"; } else if (math.getType() == ASTNode.Type.RATIONAL) { if (math.hasUnits()) { return math.getNumerator() + "/" + math.getDenominator() + " " + math.getUnits(); } return math.getNumerator() + "/" + math.getDenominator(); } else if (math.getType() == ASTNode.Type.REAL) { if (math.hasUnits()) { return "" + math.getReal() + " " + math.getUnits(); } return "" + math.getReal(); } else if (math.getType() == ASTNode.Type.REAL_E) { if (math.hasUnits()) { return math.getMantissa() + "e" + math.getExponent() + " " + math.getUnits(); } return math.getMantissa() + "e" + math.getExponent(); } else if (math.getType() == ASTNode.Type.RELATIONAL_EQ) { String leftStr = myFormulaToStringInfix(math.getLeftChild()); String rightStr = myFormulaToStringInfix(math.getRightChild()); return "(" + leftStr + " == " + rightStr + ")"; } else if (math.getType() == ASTNode.Type.RELATIONAL_GEQ) { String leftStr = myFormulaToStringInfix(math.getLeftChild()); String rightStr = myFormulaToStringInfix(math.getRightChild()); return "(" + leftStr + " >= " + rightStr + ")"; } else if (math.getType() == ASTNode.Type.RELATIONAL_GT) { String leftStr = myFormulaToStringInfix(math.getLeftChild()); String rightStr = myFormulaToStringInfix(math.getRightChild()); return "(" + leftStr + " > " + rightStr + ")"; } else if (math.getType() == ASTNode.Type.RELATIONAL_LEQ) { String leftStr = myFormulaToStringInfix(math.getLeftChild()); String rightStr = myFormulaToStringInfix(math.getRightChild()); return "(" + leftStr + " <= " + rightStr + ")"; } else if (math.getType() == ASTNode.Type.RELATIONAL_LT) { String leftStr = myFormulaToStringInfix(math.getLeftChild()); String rightStr = myFormulaToStringInfix(math.getRightChild()); return "(" + leftStr + " < " + rightStr + ")"; } else if (math.getType() == ASTNode.Type.RELATIONAL_NEQ) { String leftStr = myFormulaToStringInfix(math.getLeftChild()); String rightStr = myFormulaToStringInfix(math.getRightChild()); return "(" + leftStr + " != " + rightStr + ")"; } else if (math.getType() == ASTNode.Type.TIMES) { String returnVal = "("; boolean first = true; for (int i=0; i < math.getChildCount(); i++) { if (first) { first = false; } else { returnVal += " * "; } returnVal += myFormulaToStringInfix(math.getChild(i)); } returnVal += ")"; return returnVal; } else { if (math.isOperator()) { System.out.println("Operator " + math.getName() + " is not currently supported."); } else { System.out.println(math.getName() + " is not currently supported."); } } return ""; } public static boolean returnsBoolean(ASTNode math, Model model) { if (math.isBoolean()) { return true; } else if (math.getType() == ASTNode.Type.CONSTANT_E) { return false; } else if (math.getType() == ASTNode.Type.CONSTANT_FALSE) { return true; } else if (math.getType() == ASTNode.Type.CONSTANT_PI) { return false; } else if (math.getType() == ASTNode.Type.CONSTANT_TRUE) { return true; } else if (math.getType() == ASTNode.Type.DIVIDE) { return false; } else if (math.getType() == ASTNode.Type.FUNCTION) { return returnsBoolean(math.getRightChild(), model); } else if (math.getType() == ASTNode.Type.FUNCTION_ABS) { return false; } else if (math.getType() == ASTNode.Type.FUNCTION_ARCCOS) { return false; } else if (math.getType() == ASTNode.Type.FUNCTION_ARCCOSH) { return false; } else if (math.getType() == ASTNode.Type.FUNCTION_ARCCOT) { return false; } else if (math.getType() == ASTNode.Type.FUNCTION_ARCCOTH) { return false; } else if (math.getType() == ASTNode.Type.FUNCTION_ARCCSC) { return false; } else if (math.getType() == ASTNode.Type.FUNCTION_ARCCSCH) { return false; } else if (math.getType() == ASTNode.Type.FUNCTION_ARCSEC) { return false; } else if (math.getType() == ASTNode.Type.FUNCTION_ARCSECH) { return false; } else if (math.getType() == ASTNode.Type.FUNCTION_ARCSIN) { return false; } else if (math.getType() == ASTNode.Type.FUNCTION_ARCSINH) { return false; } else if (math.getType() == ASTNode.Type.FUNCTION_ARCTAN) { return false; } else if (math.getType() == ASTNode.Type.FUNCTION_ARCTANH) { return false; } else if (math.getType() == ASTNode.Type.FUNCTION_CEILING) { return false; } else if (math.getType() == ASTNode.Type.FUNCTION_COS) { return false; } else if (math.getType() == ASTNode.Type.FUNCTION_COSH) { return false; } else if (math.getType() == ASTNode.Type.FUNCTION_COT) { return false; } else if (math.getType() == ASTNode.Type.FUNCTION_COTH) { return false; } else if (math.getType() == ASTNode.Type.FUNCTION_CSC) { return false; } else if (math.getType() == ASTNode.Type.FUNCTION_CSCH) { return false; } else if (math.getType() == ASTNode.Type.FUNCTION_DELAY) { return false; } else if (math.getType() == ASTNode.Type.FUNCTION_EXP) { return false; } else if (math.getType() == ASTNode.Type.FUNCTION_FACTORIAL) { return false; } else if (math.getType() == ASTNode.Type.FUNCTION_FLOOR) { return false; } else if (math.getType() == ASTNode.Type.FUNCTION_LN) { return false; } else if (math.getType() == ASTNode.Type.FUNCTION_LOG) { return false; } else if (math.getType() == ASTNode.Type.FUNCTION_PIECEWISE) { boolean result = true; for (int i = 0; i < math.getChildCount(); i++) { result = result && returnsBoolean(math.getChild(i), model); } return result; } else if (math.getType() == ASTNode.Type.FUNCTION_POWER) { return false; } else if (math.getType() == ASTNode.Type.FUNCTION_ROOT) { return false; } else if (math.getType() == ASTNode.Type.FUNCTION_SEC) { return false; } else if (math.getType() == ASTNode.Type.FUNCTION_SECH) { return false; } else if (math.getType() == ASTNode.Type.FUNCTION_SIN) { return false; } else if (math.getType() == ASTNode.Type.FUNCTION_SINH) { return false; } else if (math.getType() == ASTNode.Type.FUNCTION_TAN) { return false; } else if (math.getType() == ASTNode.Type.FUNCTION_TANH) { return false; } else if (math.getType() == ASTNode.Type.INTEGER) { return false; } else if (math.getType() == ASTNode.Type.LOGICAL_AND) { return true; } else if (math.getType() == ASTNode.Type.LOGICAL_NOT) { return true; } else if (math.getType() == ASTNode.Type.LOGICAL_OR) { return true; } else if (math.getType() == ASTNode.Type.LOGICAL_XOR) { return true; } else if (math.getType() == ASTNode.Type.MINUS) { return false; } else if (math.getType() == ASTNode.Type.NAME) { return false; } else if (math.getType() == ASTNode.Type.NAME_AVOGADRO) { return false; } else if (math.getType() == ASTNode.Type.NAME_TIME) { return false; } else if (math.getType() == ASTNode.Type.PLUS) { return false; } else if (math.getType() == ASTNode.Type.POWER) { return false; } else if (math.getType() == ASTNode.Type.RATIONAL) { return false; } else if (math.getType() == ASTNode.Type.REAL) { return false; } else if (math.getType() == ASTNode.Type.REAL_E) { return false; } else if (math.getType() == ASTNode.Type.RELATIONAL_EQ) { return true; } else if (math.getType() == ASTNode.Type.RELATIONAL_GEQ) { return true; } else if (math.getType() == ASTNode.Type.RELATIONAL_GT) { return true; } else if (math.getType() == ASTNode.Type.RELATIONAL_LEQ) { return true; } else if (math.getType() == ASTNode.Type.RELATIONAL_LT) { return true; } else if (math.getType() == ASTNode.Type.RELATIONAL_NEQ) { return true; } else if (math.getType() == ASTNode.Type.TIMES) { return false; } else { if (math.isOperator()) { System.out.println("Operator " + math.getName() + " is not currently supported."); } else { System.out.println(math.getName() + " is not currently supported."); } } return false; } public static String SBMLMathToBoolLPNString(ASTNode math,HashMap<String,Integer> constants,ArrayList<String> booleans) { if (math.getType() == ASTNode.Type.FUNCTION_PIECEWISE && math.getChildCount() > 1) { return SBMLMathToLPNString(math.getChild(1),constants,booleans); } return SBMLMathToLPNString(math,constants,booleans); } public static String SBMLMathToLPNString(ASTNode math,HashMap<String,Integer> constants,ArrayList<String> booleans) { if (math.getType() == ASTNode.Type.CONSTANT_FALSE) { return "false"; } else if (math.getType() == ASTNode.Type.CONSTANT_TRUE) { return "true"; } else if (math.getType() == ASTNode.Type.REAL) { return "" + math.getReal(); } else if (math.getType() == ASTNode.Type.INTEGER) { return "" + math.getInteger(); } else if (math.getType() == ASTNode.Type.NAME) { if (constants.containsKey(math.getName())) { return "" + constants.get(math.getName()); } return math.getName(); } else if (math.getType() == ASTNode.Type.FUNCTION) { String result = math.getName() + "("; for (int i = 0; i < math.getChildCount(); i++) { String child = SBMLMathToLPNString(math.getChild(i),constants,booleans); result += child; if (i+1 < math.getChildCount()) { result += ","; } } result += ")"; return result; } else if (math.getType() == ASTNode.Type.PLUS) { String leftStr = SBMLMathToLPNString(math.getLeftChild(),constants,booleans); String rightStr = SBMLMathToLPNString(math.getRightChild(),constants,booleans); return "(" + leftStr + "+" + rightStr + ")"; } else if (math.getType() == ASTNode.Type.MINUS) { if (math.getChildCount()==1) { return "-" + SBMLMathToLPNString(math.getChild(0),constants,booleans); } String leftStr = SBMLMathToLPNString(math.getLeftChild(),constants,booleans); String rightStr = SBMLMathToLPNString(math.getRightChild(),constants,booleans); return "(" + leftStr + "-" + rightStr + ")"; } else if (math.getType() == ASTNode.Type.TIMES) { String leftStr = SBMLMathToLPNString(math.getLeftChild(),constants,booleans); String rightStr = SBMLMathToLPNString(math.getRightChild(),constants,booleans); return "(" + leftStr + "*" + rightStr + ")"; } else if (math.getType() == ASTNode.Type.DIVIDE) { String leftStr = SBMLMathToLPNString(math.getLeftChild(),constants,booleans); String rightStr = SBMLMathToLPNString(math.getRightChild(),constants,booleans); return "(" + leftStr + "/" + rightStr + ")"; } else if (math.getType() == ASTNode.Type.POWER) { String leftStr = SBMLMathToLPNString(math.getLeftChild(),constants,booleans); String rightStr = SBMLMathToLPNString(math.getRightChild(),constants,booleans); return "(" + leftStr + "^" + rightStr + ")"; } else if (math.getType() == ASTNode.Type.RELATIONAL_EQ) { String leftStr = SBMLMathToLPNString(math.getLeftChild(),constants,booleans); String rightStr = SBMLMathToLPNString(math.getRightChild(),constants,booleans); if (booleans.contains(leftStr) && rightStr.equals("1")) { return leftStr; } return "(" + leftStr + "=" + rightStr + ")"; } else if (math.getType() == ASTNode.Type.RELATIONAL_GEQ) { String leftStr = SBMLMathToLPNString(math.getLeftChild(),constants,booleans); String rightStr = SBMLMathToLPNString(math.getRightChild(),constants,booleans); return "(" + leftStr + ">=" + rightStr + ")"; } else if (math.getType() == ASTNode.Type.RELATIONAL_GT) { String leftStr = SBMLMathToLPNString(math.getLeftChild(),constants,booleans); String rightStr = SBMLMathToLPNString(math.getRightChild(),constants,booleans); return "(" + leftStr + ">" + rightStr + ")"; } else if (math.getType() == ASTNode.Type.RELATIONAL_LEQ) { String leftStr = SBMLMathToLPNString(math.getLeftChild(),constants,booleans); String rightStr = SBMLMathToLPNString(math.getRightChild(),constants,booleans); return "(" + leftStr + "<=" + rightStr + ")"; } else if (math.getType() == ASTNode.Type.RELATIONAL_LT) { String leftStr = SBMLMathToLPNString(math.getLeftChild(),constants,booleans); String rightStr = SBMLMathToLPNString(math.getRightChild(),constants,booleans); return "(" + leftStr + "<" + rightStr + ")"; } else if (math.getType() == ASTNode.Type.RELATIONAL_NEQ) { String leftStr = SBMLMathToLPNString(math.getLeftChild(),constants,booleans); String rightStr = SBMLMathToLPNString(math.getRightChild(),constants,booleans); return "(" + leftStr + "!=" + rightStr + ")"; } else if (math.getType() == ASTNode.Type.LOGICAL_NOT) { if (math.getChildCount()==0) return ""; String result = "~("; String child = SBMLMathToLPNString(math.getChild(0),constants,booleans); result += child; result += ")"; return result; } else if (math.getType() == ASTNode.Type.LOGICAL_AND) { if (math.getChildCount()==0) return ""; String result = "("; for (int i = 0; i < math.getChildCount(); i++) { String child = SBMLMathToLPNString(math.getChild(i),constants,booleans); result += child; if (i+1 < math.getChildCount()) { result += "&"; } } result += ")"; return result; } else if (math.getType() == ASTNode.Type.LOGICAL_OR) { if (math.getChildCount()==0) return ""; String result = "("; for (int i = 0; i < math.getChildCount(); i++) { String child = SBMLMathToLPNString(math.getChild(i),constants,booleans); result += child; if (i+1 < math.getChildCount()) { result += "|"; } } result += ")"; return result; } else if (math.getType() == ASTNode.Type.LOGICAL_XOR) { if (math.getChildCount()==0) return ""; String result = "exor("; for (int i = 0; i < math.getChildCount(); i++) { String child = SBMLMathToLPNString(math.getChild(i),constants,booleans); result += child; if (i+1 < math.getChildCount()) { result += ","; } } result += ")"; return result; } else { if (math.isOperator()) { System.out.println("Operator " + math.getName() + " is not currently supported."); } else { System.out.println(math.getName() + " is not currently supported."); } } return ""; } public static ArrayList<String> getPreset(SBMLDocument doc,Event event) { ArrayList<String> preset = new ArrayList<String>(); for (int i = 0; i < event.getEventAssignmentCount(); i++) { EventAssignment ea = event.getListOfEventAssignments().get(i); Parameter p = doc.getModel().getParameter(ea.getVariable()); if (p != null && SBMLutilities.isPlace(p) && SBMLutilities.myFormulaToString(ea.getMath()).equals("0")) { preset.add(p.getId()); } } return preset; } public static ArrayList<String> getPostset(SBMLDocument doc,Event event) { ArrayList<String> postset = new ArrayList<String>(); for (int i = 0; i < event.getEventAssignmentCount(); i++) { EventAssignment ea = event.getListOfEventAssignments().get(i); Parameter p = doc.getModel().getParameter(ea.getVariable()); if (p != null && SBMLutilities.isPlace(p) && SBMLutilities.myFormulaToString(ea.getMath()).equals("1")) { postset.add(p.getId()); } } return postset; } public static void replaceArgument(ASTNode formula,String bvar, ASTNode arg) { int n = 0; for (int i = 0; i < formula.getChildCount(); i++) { ASTNode child = formula.getChild(i); if (child.getName() != null && child.getName().equals(bvar)) { formula.replaceChild(n, deepCopy(arg)); } else if (child.getChildCount() > 0) { replaceArgument(child, bvar, arg); } n++; } } /** * recursively puts every astnode child into the arraylist passed in * * @param node * @param nodeChildrenList */ protected static void getAllASTNodeChildren(ASTNode node, ArrayList<ASTNode> nodeChildrenList) { for (int i = 0; i < node.getChildCount(); i++) { ASTNode child = node.getChild(i); if (child.getChildCount() == 0) nodeChildrenList.add(child); else { nodeChildrenList.add(child); getAllASTNodeChildren(child, nodeChildrenList); } } } /** * inlines a formula with function definitions * * @param formula * @return */ public static ASTNode inlineFormula(Model model, ASTNode formula) { HashSet<String> ibiosimFunctionDefinitions = new HashSet<String>(); ibiosimFunctionDefinitions.add("uniform"); ibiosimFunctionDefinitions.add("exponential"); ibiosimFunctionDefinitions.add("gamma"); ibiosimFunctionDefinitions.add("chisq"); ibiosimFunctionDefinitions.add("lognormal"); ibiosimFunctionDefinitions.add("laplace"); ibiosimFunctionDefinitions.add("cauchy"); ibiosimFunctionDefinitions.add("poisson"); ibiosimFunctionDefinitions.add("binomial"); ibiosimFunctionDefinitions.add("bernoulli"); ibiosimFunctionDefinitions.add("normal"); ibiosimFunctionDefinitions.add("rate"); ibiosimFunctionDefinitions.add("BIT"); ibiosimFunctionDefinitions.add("BITNOT"); ibiosimFunctionDefinitions.add("BITAND"); ibiosimFunctionDefinitions.add("BITOR"); ibiosimFunctionDefinitions.add("BITXOR"); ibiosimFunctionDefinitions.add("G"); ibiosimFunctionDefinitions.add("PG"); ibiosimFunctionDefinitions.add("F"); ibiosimFunctionDefinitions.add("PF"); ibiosimFunctionDefinitions.add("U"); ibiosimFunctionDefinitions.add("PU"); if (formula.isFunction() == false /* || formula.isLeaf() == false*/) { for (int i = 0; i < formula.getChildCount(); ++i) formula.replaceChild(i, inlineFormula(model,formula.getChild(i)));//.clone())); } else if (formula.isFunction() && model.getFunctionDefinition(formula.getName()) != null) { if (ibiosimFunctionDefinitions.contains(formula.getName())) return formula; ASTNode inlinedFormula = deepCopy(model.getFunctionDefinition(formula.getName()).getBody()); ASTNode oldFormula = deepCopy(formula); ArrayList<ASTNode> inlinedChildren = new ArrayList<ASTNode>(); getAllASTNodeChildren(inlinedFormula, inlinedChildren); if (inlinedChildren.size() == 0) inlinedChildren.add(inlinedFormula); HashMap<String, Integer> inlinedChildToOldIndexMap = new HashMap<String, Integer>(); for (int i = 0; i < model.getFunctionDefinition(formula.getName()).getArgumentCount(); ++i) { inlinedChildToOldIndexMap.put(model.getFunctionDefinition(formula.getName()).getArgument(i).getName(), i); } for (int i = 0; i < inlinedChildren.size(); ++i) { ASTNode child = inlinedChildren.get(i); if (child.getChildCount()==0 && child.isName()) { int index = inlinedChildToOldIndexMap.get(child.getName()); replaceArgument(inlinedFormula,myFormulaToString(child), oldFormula.getChild(index)); if (inlinedFormula.getChildCount() == 0) inlinedFormula = oldFormula.getChild(index); } } return inlinedFormula; } return formula; } public static void expandFunctionDefinitions(SBMLDocument doc) { Model model = doc.getModel(); for (int i = 0; i < model.getInitialAssignmentCount(); i++) { InitialAssignment ia = model.getListOfInitialAssignments().get(i); if (ia.isSetMath()) { ia.setMath(inlineFormula(model,ia.getMath())); } } for (int i = 0; i < model.getRuleCount(); i++) { Rule r = model.getRule(i); if (r.isSetMath()) { r.setMath(inlineFormula(model,r.getMath())); } } for (int i = 0; i < model.getConstraintCount(); i++) { Constraint c = model.getConstraint(i); if (c.isSetMath()) { c.setMath(inlineFormula(model,c.getMath())); } } for (int i = 0; i < model.getEventCount(); i++) { Event e = model.getEvent(i); if (e.getDelay()!=null && e.getDelay().isSetMath()) { e.getDelay().setMath(inlineFormula(model,e.getDelay().getMath())); } if (e.getTrigger()!=null && e.getTrigger().isSetMath()) { e.getTrigger().setMath(inlineFormula(model,e.getTrigger().getMath())); } if (e.getPriority()!=null && e.getPriority().isSetMath()) { e.getPriority().setMath(inlineFormula(model,e.getPriority().getMath())); } for (int j = 0; j < e.getEventAssignmentCount(); j++) { EventAssignment ea = e.getListOfEventAssignments().get(j); if (ea.isSetMath()) { ea.setMath(inlineFormula(model,ea.getMath())); } } } } public static void expandInitialAssignments(SBMLDocument document) { for (InitialAssignment ia : document.getModel().getListOfInitialAssignments()) { SBase sb = getElementBySId(document, ia.getVariable()); if (sb instanceof QuantityWithUnit) { ((QuantityWithUnit) sb).setValue(evaluateExpression(document.getModel(), ia.getMath())); } } for (int i = 0; i < document.getModel().getListOfInitialAssignments().size(); i ++) { document.getModel().getListOfInitialAssignments().remove(i); } } public static String getVariable(Rule r) { if (r instanceof ExplicitRule) { return ((ExplicitRule) r).getVariable(); } return null; } public static void setVariable(Rule r, String variable) { if (r instanceof ExplicitRule) { ((ExplicitRule) r).setVariable(variable); } } public static boolean isSetVariable(Rule r) { if (r instanceof ExplicitRule) { return ((ExplicitRule) r).isSetVariable(); } return false; } public static ASTNode deepCopy(ASTNode original) { return new ASTNode(original); } public static void removeFromParentAndDelete(SBase element) { element.removeFromParent(); } public static SBase getElementByMetaId(SBMLDocument document, String metaId) { return document.findSBase(metaId); } public static SBase getElementBySId(SBMLDocument document, String id) { return getElementBySId(document.getModel(), id); } public static SBase getElementByMetaId(Model m, String metaId) { return getElementByMetaId(m.getSBMLDocument(), metaId); } public static SBase getElementBySId(Model m, String id) { return m.findNamedSBase(id); } private static SBase getElementByMetaId(CompSBMLDocumentPlugin compDocument, String metaId) { for (SBase sb : getListOfAllElements(compDocument)) { if (sb.getMetaId().equals(metaId)) { return sb; } } return null; } public static ArrayList<SBase> getListOfAllElements(TreeNode node) { ArrayList<SBase> elements = new ArrayList<SBase>(); if (node instanceof SBase) { elements.add((SBase) node); } for (int i = 0; i < node.getChildCount(); i++) { elements.addAll(getListOfAllElements(node.getChildAt(i))); } return elements; } // public static ListOf<SBase> getListOfAllElements(Model m) { // ListOf<SBase> elements = new ListOf<SBase>(); // for (Compartment c : m.getListOfCompartments()) { // for (Constraint c : m.getListOfConstraints()) { // for (Event e : m.getListOfEvents()) { // elements.add(e); // for (EventAssignment ea : e.getListOfEventAssignments()) { // elements.add(ea); // for (FunctionDefinition fd : m.getListOfFunctionDefinitions()) { // elements.add(fd); // for (InitialAssignment ia : m.getListOfInitialAssignments()) { // elements.add(ia); // for (Parameter p : m.getListOfParameters()) { // elements.add(p); // for (UnitDefinition ud : m.getListOfPredefinedUnitDefinitions()) { // elements.add(ud); // for (Reaction r : m.getListOfReactions()) { // elements.add(r); // for (ModifierSpeciesReference msr : r.getListOfModifiers()) { // elements.add(msr); // for (SpeciesReference sr : r.getListOfProducts()) { // elements.add(sr); // for (SpeciesReference sr : r.getListOfReactants()) { // elements.add(sr); // for (LocalParameter lp : r.getKineticLaw().getListOfLocalParameters()) { // elements.add(lp); // for (Rule r : m.getListOfRules()) { // elements.add(r); // for (Species s : m.getListOfSpecies()) { // elements.add(s); // for (UnitDefinition ud : m.getListOfUnitDefinitions()) { // elements.add(ud); // return elements; public static String getId(SBase sb) { if (sb instanceof AbstractNamedSBase) { return ((AbstractNamedSBase) sb).getId(); } return null; } public static int appendAnnotation(SBase sbmlObject, String annotation) { sbmlObject.getAnnotation().appendNoRDFAnnotation(annotation); //sbmlObject.setAnnotation(new Annotation(sbmlObject.getAnnotationString().replace("<annotation>", "").replace("</annotation>", "").trim() + annotation)); return JSBML.OPERATION_SUCCESS; } public static int appendAnnotation(SBase sbmlObject, XMLNode annotation) { sbmlObject.getAnnotation().appendNoRDFAnnotation(annotation.toXMLString()); //sbmlObject.setAnnotation(new Annotation(sbmlObject.getAnnotationString().replace("<annotation>", "").replace("</annotation>", "").trim() + annotation.toXMLString())); return JSBML.OPERATION_SUCCESS; } public static FBCModelPlugin getFBCModelPlugin(Model model) { if (model.getExtension(FBCConstants.namespaceURI) != null) { return (FBCModelPlugin)model.getExtension(FBCConstants.namespaceURI); } FBCModelPlugin fbc = new FBCModelPlugin(model); model.addExtension(FBCConstants.namespaceURI, fbc); return fbc; } public static LayoutModelPlugin getLayoutModelPlugin(Model model) { if (model.getExtension(LayoutConstants.namespaceURI) != null) { return (LayoutModelPlugin)model.getExtension(LayoutConstants.namespaceURI); } LayoutModelPlugin layout = new LayoutModelPlugin(model); model.addExtension(LayoutConstants.namespaceURI, layout); return layout; } public static CompSBMLDocumentPlugin getCompSBMLDocumentPlugin(SBMLDocument document) { if (document.getExtension(CompConstant.namespaceURI) != null) { return (CompSBMLDocumentPlugin)document.getExtension(CompConstant.namespaceURI); } CompSBMLDocumentPlugin comp = new CompSBMLDocumentPlugin(document); document.addExtension(CompConstant.namespaceURI, comp); return comp; } public static CompModelPlugin getCompModelPlugin(Model model) { if (model.getExtension(CompConstant.namespaceURI) != null) { return (CompModelPlugin)model.getExtension(CompConstant.namespaceURI); } CompModelPlugin comp = new CompModelPlugin(model); model.addExtension(CompConstant.namespaceURI, comp); return comp; } public static CompSBasePlugin getCompSBasePlugin(SBase sb) { if (sb.getExtension(CompConstant.namespaceURI) != null) { return (CompSBasePlugin)sb.getExtension(CompConstant.namespaceURI); } CompSBasePlugin comp = new CompSBasePlugin(sb); sb.addExtension(CompConstant.namespaceURI, comp); return comp; } public static void setNamespaces(SBMLDocument document, Map<String,String> namespaces) { document.getSBMLDocumentNamespaces().clear(); for (String key : namespaces.keySet()) { String prefix = ""; String shortName = key; if (key.contains(":")) { prefix = key.split(":")[0]; shortName = key.split(":")[1]; } document.addNamespace(shortName, prefix, namespaces.get(key)); } /* ArrayList<String> remove = new ArrayList<String>(); for (String namespace : document.getNamespaces()) { remove.add(namespace); } for (String namespace : remove) { document.removeNamespace(namespace); } for (String namespace : namespaces) { document.addNamespace(namespace); } */ } public static boolean getBooleanFromDouble(double value) { if (value == 0.0) return false; return true; } public static double getDoubleFromBoolean(boolean value) { if (value == true) return 1.0; return 0.0; } public static double evaluateExpression(Model model, ASTNode node) { PsRandom prng = new PsRandom(); if (node.isBoolean()) { switch (node.getType()) { case CONSTANT_TRUE: return 1.0; case CONSTANT_FALSE: return 0.0; case LOGICAL_NOT: return getDoubleFromBoolean(!(getBooleanFromDouble(evaluateExpression(model, node.getLeftChild())))); case LOGICAL_AND: { boolean andResult = true; for (int childIter = 0; childIter < node.getChildCount(); ++childIter) andResult = andResult && getBooleanFromDouble(evaluateExpression(model, node.getChild(childIter))); return getDoubleFromBoolean(andResult); } case LOGICAL_OR: { boolean orResult = false; for (int childIter = 0; childIter < node.getChildCount(); ++childIter) orResult = orResult || getBooleanFromDouble(evaluateExpression(model, node.getChild(childIter))); return getDoubleFromBoolean(orResult); } case LOGICAL_XOR: { boolean xorResult = getBooleanFromDouble(evaluateExpression(model, node.getChild(0))); for (int childIter = 1; childIter < node.getChildCount(); ++childIter) xorResult = xorResult ^ getBooleanFromDouble(evaluateExpression(model, node.getChild(childIter))); return getDoubleFromBoolean(xorResult); } case RELATIONAL_EQ: return getDoubleFromBoolean( evaluateExpression(model, node.getLeftChild()) == evaluateExpression(model, node.getRightChild())); case RELATIONAL_NEQ: return getDoubleFromBoolean( evaluateExpression(model, node.getLeftChild()) != evaluateExpression(model, node.getRightChild())); case RELATIONAL_GEQ: { //System.out.println("Node: " + libsbml.formulaToString(node.getRightChild()) + " " + evaluateExpressionRecursive(modelstate, node.getRightChild())); //System.out.println("Node: " + evaluateExpressionRecursive(modelstate, node.getLeftChild()) + " " + evaluateExpressionRecursive(modelstate, node.getRightChild())); return getDoubleFromBoolean( evaluateExpression(model, node.getLeftChild()) >= evaluateExpression(model, node.getRightChild())); } case RELATIONAL_LEQ: return getDoubleFromBoolean( evaluateExpression(model, node.getLeftChild()) <= evaluateExpression(model, node.getRightChild())); case RELATIONAL_GT: return getDoubleFromBoolean( evaluateExpression(model, node.getLeftChild()) > evaluateExpression(model, node.getRightChild())); case RELATIONAL_LT: { return getDoubleFromBoolean( evaluateExpression(model, node.getLeftChild()) < evaluateExpression(model, node.getRightChild())); } default: } } //if it's a mathematical constant else if (node.isConstant()) { switch (node.getType()) { case CONSTANT_E: return Math.E; case CONSTANT_PI: return Math.PI; default: } } else if (node.isInteger()) return node.getInteger(); //if it's a number else if (node.isReal()) return node.getReal(); //if it's a user-defined variable //eg, a species name or global/local parameter else if (node.isName()) { SBase sb = getElementBySId(model, node.getName()); if (sb instanceof QuantityWithUnit) { return ((QuantityWithUnit) sb).getValue(); } } //operators/functions with two children else { ASTNode leftChild = node.getLeftChild(); ASTNode rightChild = node.getRightChild(); switch (node.getType()) { case PLUS: { double sum = 0.0; for (int childIter = 0; childIter < node.getChildCount(); ++childIter) sum += evaluateExpression(model, node.getChild(childIter)); return sum; } case MINUS: { double sum = evaluateExpression(model, leftChild); for (int childIter = 1; childIter < node.getChildCount(); ++childIter) sum -= evaluateExpression(model, node.getChild(childIter)); return sum; } case TIMES: { double product = 1.0; for (int childIter = 0; childIter < node.getChildCount(); ++childIter) product *= evaluateExpression(model, node.getChild(childIter)); return product; } case DIVIDE: return (evaluateExpression(model, leftChild) / evaluateExpression(model, rightChild)); case FUNCTION_POWER: return (FastMath.pow(evaluateExpression(model, leftChild), evaluateExpression(model, rightChild))); case FUNCTION: { //use node name to determine function //i'm not sure what to do with completely user-defined functions, though String nodeName = node.getName(); //generates a uniform random number between the upper and lower bound if (nodeName.equals("uniform")) { double leftChildValue = evaluateExpression(model, node.getLeftChild()); double rightChildValue = evaluateExpression(model, node.getRightChild()); double lowerBound = FastMath.min(leftChildValue, rightChildValue); double upperBound = FastMath.max(leftChildValue, rightChildValue); return prng.nextDouble(lowerBound, upperBound); } else if (nodeName.equals("exponential")) { return prng.nextExponential(evaluateExpression(model, node.getLeftChild()), 1); } else if (nodeName.equals("gamma")) { return prng.nextGamma(1, evaluateExpression(model, node.getLeftChild()), evaluateExpression(model, node.getRightChild())); } else if (nodeName.equals("chisq")) { return prng.nextChiSquare((int) evaluateExpression(model, node.getLeftChild())); } else if (nodeName.equals("lognormal")) { return prng.nextLogNormal(evaluateExpression(model, node.getLeftChild()), evaluateExpression(model, node.getRightChild())); } else if (nodeName.equals("laplace")) { //function doesn't exist in current libraries return 0; } else if (nodeName.equals("cauchy")) { return prng.nextLorentzian(0, evaluateExpression(model, node.getLeftChild())); } else if (nodeName.equals("poisson")) { return prng.nextPoissonian(evaluateExpression(model, node.getLeftChild())); } else if (nodeName.equals("binomial")) { return prng.nextBinomial(evaluateExpression(model, node.getLeftChild()), (int) evaluateExpression(model, node.getRightChild())); } else if (nodeName.equals("bernoulli")) { return prng.nextBinomial(evaluateExpression(model, node.getLeftChild()), 1); } else if (nodeName.equals("normal")) { return prng.nextGaussian(evaluateExpression(model, node.getLeftChild()), evaluateExpression(model, node.getRightChild())); } break; } case FUNCTION_ABS: return FastMath.abs(evaluateExpression(model, node.getChild(0))); case FUNCTION_ARCCOS: return FastMath.acos(evaluateExpression(model, node.getChild(0))); case FUNCTION_ARCSIN: return FastMath.asin(evaluateExpression(model, node.getChild(0))); case FUNCTION_ARCTAN: return FastMath.atan(evaluateExpression(model, node.getChild(0))); case FUNCTION_CEILING: return FastMath.ceil(evaluateExpression(model, node.getChild(0))); case FUNCTION_COS: return FastMath.cos(evaluateExpression(model, node.getChild(0))); case FUNCTION_COSH: return FastMath.cosh(evaluateExpression(model, node.getChild(0))); case FUNCTION_EXP: return FastMath.exp(evaluateExpression(model, node.getChild(0))); case FUNCTION_FLOOR: return FastMath.floor(evaluateExpression(model, node.getChild(0))); case FUNCTION_LN: return FastMath.log(evaluateExpression(model, node.getChild(0))); case FUNCTION_LOG: return FastMath.log10(evaluateExpression(model, node.getChild(0))); case FUNCTION_SIN: return FastMath.sin(evaluateExpression(model, node.getChild(0))); case FUNCTION_SINH: return FastMath.sinh(evaluateExpression(model, node.getChild(0))); case FUNCTION_TAN: return FastMath.tan(evaluateExpression(model, node.getChild(0))); case FUNCTION_TANH: return FastMath.tanh(evaluateExpression(model, node.getChild(0))); case FUNCTION_PIECEWISE: { //loop through child triples //if child 1 is true, return child 0, else return child 2 for (int childIter = 0; childIter < node.getChildCount(); childIter += 3) { if ((childIter + 1) < node.getChildCount() && getBooleanFromDouble(evaluateExpression(model, node.getChild(childIter + 1)))) { return evaluateExpression(model, node.getChild(childIter)); } else if ((childIter + 2) < node.getChildCount()) { return evaluateExpression(model, node.getChild(childIter + 2)); } } return 0; } case FUNCTION_ROOT: return FastMath.pow(evaluateExpression(model, node.getRightChild()), 1 / evaluateExpression(model, node.getLeftChild())); case FUNCTION_SEC: return Fmath.sec(evaluateExpression(model, node.getChild(0))); case FUNCTION_SECH: return Fmath.sech(evaluateExpression(model, node.getChild(0))); case FUNCTION_FACTORIAL: return Fmath.factorial(evaluateExpression(model, node.getChild(0))); case FUNCTION_COT: return Fmath.cot(evaluateExpression(model, node.getChild(0))); case FUNCTION_COTH: return Fmath.coth(evaluateExpression(model, node.getChild(0))); case FUNCTION_CSC: return Fmath.csc(evaluateExpression(model, node.getChild(0))); case FUNCTION_CSCH: return Fmath.csch(evaluateExpression(model, node.getChild(0))); case FUNCTION_DELAY: //NOT PLANNING TO SUPPORT THIS return 0; case FUNCTION_ARCTANH: return Fmath.atanh(evaluateExpression(model, node.getChild(0))); case FUNCTION_ARCSINH: return Fmath.asinh(evaluateExpression(model, node.getChild(0))); case FUNCTION_ARCCOSH: return Fmath.acosh(evaluateExpression(model, node.getChild(0))); case FUNCTION_ARCCOT: return Fmath.acot(evaluateExpression(model, node.getChild(0))); case FUNCTION_ARCCOTH: return Fmath.acoth(evaluateExpression(model, node.getChild(0))); case FUNCTION_ARCCSC: return Fmath.acsc(evaluateExpression(model, node.getChild(0))); case FUNCTION_ARCCSCH: return Fmath.acsch(evaluateExpression(model, node.getChild(0))); case FUNCTION_ARCSEC: return Fmath.asec(evaluateExpression(model, node.getChild(0))); case FUNCTION_ARCSECH: return Fmath.asech(evaluateExpression(model, node.getChild(0))); default: } //end switch } return 0.0; } public static void setMetaId(AbstractSBase asb, String newId) { if (!asb.getMetaId().equals(newId)){ asb.setMetaId(newId); } } public static void setMetaId(SBase asb, String newId) { if (!asb.getMetaId().equals(newId)){ asb.setMetaId(newId); } } public static ModifierSpeciesReference removeModifier(Reaction r, String species) { if (r.getListOfModifiers() != null) { return r.removeModifier(species); } return null; } public static void checkModelCompleteness(SBMLDocument document) { FBCModelPlugin fbc = SBMLutilities.getFBCModelPlugin(document.getModel()); JTextArea messageArea = new JTextArea(); messageArea.append("Model is incomplete. Cannot be simulated until the following information is provided.\n"); boolean display = false; org.sbml.jsbml.Model model = document.getModel(); for (int i = 0; i < model.getCompartmentCount(); i++) { Compartment compartment = model.getCompartment(i); if (!compartment.isSetSize()) { messageArea.append(" messageArea.append("Compartment " + compartment.getId() + " needs a size.\n"); display = true; } } for (int i = 0; i < model.getSpeciesCount(); i++) { Species species = model.getSpecies(i); if (!(species.isSetInitialAmount()) && !(species.isSetInitialConcentration())) { messageArea.append(" messageArea.append("Species " + species.getId() + " needs an initial amount or concentration.\n"); display = true; } } for (int i = 0; i < model.getParameterCount(); i++) { Parameter parameter = model.getParameter(i); if (!(parameter.isSetValue())) { messageArea.append(" messageArea.append("Parameter " + parameter.getId() + " needs an initial value.\n"); display = true; } } for (int i = 0; i < model.getReactionCount(); i++) { Reaction reaction = model.getReaction(i); if (fbc!=null) { boolean foundIt = false; for (int j = 0; j < fbc.getListOfFluxBounds().size(); j++) { FluxBound fb = fbc.getFluxBound(j); if (fb.getReaction().equals(reaction.getId())) { foundIt = true; break; } } if (foundIt) continue; } if (!(reaction.isSetKineticLaw())) { messageArea.append(" messageArea.append("Reaction " + reaction.getId() + " needs a kinetic law.\n"); display = true; } else { for (int j = 0; j < reaction.getKineticLaw().getLocalParameterCount(); j++) { LocalParameter param = reaction.getKineticLaw().getLocalParameter(j); if (!(param.isSetValue())) { messageArea.append(" messageArea.append("Local parameter " + param.getId() + " for reaction " + reaction.getId() + " needs an initial value.\n"); display = true; } } } } if (display) { final JFrame f = new JFrame("SBML Model Completeness Errors"); messageArea.setLineWrap(true); messageArea.setEditable(false); messageArea.setSelectionStart(0); messageArea.setSelectionEnd(0); JScrollPane scroll = new JScrollPane(); scroll.setMinimumSize(new Dimension(600, 600)); scroll.setPreferredSize(new Dimension(600, 600)); scroll.setViewportView(messageArea); JButton close = new JButton("Dismiss"); close.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { f.dispose(); } }); JPanel consistencyPanel = new JPanel(new BorderLayout()); consistencyPanel.add(scroll, "Center"); consistencyPanel.add(close, "South"); f.setContentPane(consistencyPanel); f.pack(); Dimension screenSize; try { Toolkit tk = Toolkit.getDefaultToolkit(); screenSize = tk.getScreenSize(); } catch (AWTError awe) { screenSize = new Dimension(640, 480); } Dimension frameSize = f.getSize(); if (frameSize.height > screenSize.height) { frameSize.height = screenSize.height; } if (frameSize.width > screenSize.width) { frameSize.width = screenSize.width; } int x = screenSize.width / 2 - frameSize.width / 2; int y = screenSize.height / 2 - frameSize.height / 2; f.setLocation(x, y); f.setVisible(true); } } public static SBMLDocument readSBML(String filename) { //SBMLReader reader = new SBMLReader(); SBMLDocument document = null; try { document = SBMLReader.read(new File(filename)); // TODO: This is a hack to remove duplicate units int i = 0; while (i < document.getModel().getUnitDefinitionCount()) { UnitDefinition unitDef = document.getModel().getUnitDefinition(i); if (!unitDef.isSetId()) { document.getModel().removeUnitDefinition(i); } else { i++; } } } catch (XMLStreamException e1) { JOptionPane.showMessageDialog(Gui.frame, "Invalid XML in SBML file","Error Opening File", JOptionPane.ERROR_MESSAGE); return null; } catch (IOException e1) { JOptionPane.showMessageDialog(Gui.frame, "I/O error when opening SBML file","Error Opening File", JOptionPane.ERROR_MESSAGE); return null; } if (document.getModel().isSetId()) { document.getModel().setId(document.getModel().getId().replace(".","_")); } if (document.getLevel() < Gui.SBML_LEVEL || document.getVersion() < Gui.SBML_VERSION) { if (!Gui.libsbmlFound) { JOptionPane.showMessageDialog(Gui.frame, "Unable convert model to Level "+Gui.SBML_LEVEL+" Version " + Gui.SBML_VERSION, "Error Opening File", JOptionPane.ERROR_MESSAGE); return null; } long numErrors = 0; org.sbml.libsbml.SBMLReader reader = new org.sbml.libsbml.SBMLReader(); org.sbml.libsbml.SBMLDocument doc = reader.readSBML(filename); numErrors = doc.checkL3v1Compatibility(); if (numErrors > 0) { JTextArea messageArea = new JTextArea(); messageArea.append("Conversion to SBML level " + Gui.SBML_LEVEL + " version " + Gui.SBML_VERSION + " produced the errors listed below. "); messageArea.append("It is recommended that you fix them before using these models or you may get unexpected results.\n\n"); messageArea.append(" messageArea.append(filename); messageArea.append("\n for (int i = 0; i < numErrors; i++) { String error = doc.getError(i).getMessage(); messageArea.append(i + ":" + error + "\n"); } final JFrame f = new JFrame("SBML Conversion Errors and Warnings"); messageArea.setLineWrap(true); messageArea.setEditable(false); messageArea.setSelectionStart(0); messageArea.setSelectionEnd(0); JScrollPane scroll = new JScrollPane(); scroll.setMinimumSize(new Dimension(600, 600)); scroll.setPreferredSize(new Dimension(600, 600)); scroll.setViewportView(messageArea); JButton close = new JButton("Dismiss"); close.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { f.dispose(); } }); JPanel consistencyPanel = new JPanel(new BorderLayout()); consistencyPanel.add(scroll, "Center"); consistencyPanel.add(close, "South"); f.setContentPane(consistencyPanel); f.pack(); Dimension screenSize; try { Toolkit tk = Toolkit.getDefaultToolkit(); screenSize = tk.getScreenSize(); } catch (AWTError awe) { screenSize = new Dimension(640, 480); } Dimension frameSize = f.getSize(); if (frameSize.height > screenSize.height) { frameSize.height = screenSize.height; } if (frameSize.width > screenSize.width) { frameSize.width = screenSize.width; } int x = screenSize.width / 2 - frameSize.width / 2; int y = screenSize.height / 2 - frameSize.height / 2; f.setLocation(x, y); f.setVisible(true); Object[] options = { "Dismiss" }; JOptionPane.showOptionDialog(Gui.frame, scroll, "SBML Conversion Errors and Warnings", JOptionPane.YES_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); } doc.setLevelAndVersion(Gui.SBML_LEVEL, Gui.SBML_VERSION,false); org.sbml.libsbml.SBMLWriter writer = new org.sbml.libsbml.SBMLWriter(); try { writer.writeSBMLToFile(doc, filename); } catch (SBMLException e) { e.printStackTrace(); } try { document = SBMLReader.read(new File(filename)); } catch (XMLStreamException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } return document; } }
package org.mozilla.taskcluster.client; import java.io.BufferedReader; import java.io.InputStreamReader; import java.nio.ByteBuffer; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.TimeZone; import java.util.UUID; import java.util.logging.Logger; import org.junit.Assert; import org.junit.Assume; import org.junit.Test; import org.mozilla.taskcluster.client.APICallFailure; import org.mozilla.taskcluster.client.CallSummary; import org.mozilla.taskcluster.client.Certificate; import org.mozilla.taskcluster.client.Credentials; import org.mozilla.taskcluster.client.auth.Auth; import org.mozilla.taskcluster.client.auth.TestAuthenticateRequest; import org.mozilla.taskcluster.client.auth.TestAuthenticateResponse; import org.mozilla.taskcluster.client.InvalidOptionsException; import org.mozilla.taskcluster.client.index.Index; import org.mozilla.taskcluster.client.queue.Queue; import org.mozilla.taskcluster.client.queue.TaskDefinitionRequest; import org.mozilla.taskcluster.client.queue.TaskStatusResponse; import com.google.gson.Gson; import net.iharder.Base64; public class APITest { private static Logger log = Logger.getGlobal(); /** * Generates a 22 character random slugId that is url-safe ([0-9a-zA-Z_\-]*) */ public static String slug() { UUID uuid = UUID.randomUUID(); long hi = uuid.getMostSignificantBits(); long lo = uuid.getLeastSignificantBits(); ByteBuffer raw = ByteBuffer.allocate(16); raw.putLong(hi); raw.putLong(lo); byte[] rawBytes = raw.array(); return Base64.encodeBytes(rawBytes).replace('+', '-').replace('/', '_').substring(0, 22); } /** * This is a silly test that looks for the latest mozilla-inbound linux64 debug * build and asserts that it must have a created time between a year ago and an * hour in the future. * * Could easily break at a point in the future, e.g. if this index route * changes, at which point we can change to something else. * * Note, no credentials are needed, so this can be run even on travis-ci.org, * for example. */ @Test public void findLatestLinux64DebugBuild() { Index index = new Index(); Queue queue = new Queue(); try { String taskId = index .findTask("gecko.v2.mozilla-inbound.latest.firefox.linux64-debug").responsePayload.taskId; Date created = queue.task(taskId).responsePayload.created; // calculate time an hour in the future to allow for clock drift Date now = new Date(); Calendar c = Calendar.getInstance(); c.setTime(now); c.add(Calendar.HOUR, 1); Date inAnHour = c.getTime(); c.setTime(now); c.add(Calendar.YEAR, -1); Date aYearAgo = c.getTime(); SimpleDateFormat sdf = new SimpleDateFormat("EEE, d MMM yyyy 'at' HH:mm:ss Z"); System.out.println("=> Task " + taskId + " was created on " + sdf.format(created)); Assert.assertTrue(created.before(inAnHour)); Assert.assertTrue(created.after(aYearAgo)); } catch (APICallFailure e) { e.printStackTrace(); Assert.fail("Exception thrown"); } } /** * Tests whether it is possible to define a task against the production Queue. */ @Test public void testDefineTask() { String clientId = System.getenv("TASKCLUSTER_CLIENT_ID"); String accessToken = System.getenv("TASKCLUSTER_ACCESS_TOKEN"); String certificate = System.getenv("TASKCLUSTER_CERTIFICATE"); Assume.assumeFalse(clientId == null || clientId == "" || accessToken == null || accessToken == ""); Queue queue = new Queue(new Credentials(clientId, accessToken, certificate)); String taskId = slug(); TaskDefinitionRequest td = new TaskDefinitionRequest(); td.created = new Date(); Calendar c = Calendar.getInstance(); c.setTime(td.created); c.add(Calendar.DATE, 1); td.deadline = c.getTime(); td.expires = td.deadline; Map<String, Object> index = new HashMap<String, Object>(); index.put("rank", 12345); Map<String, Object> extra = new HashMap<String, Object>(); extra.put("index", index); td.extra = extra; td.metadata = td.new MetaData(); td.metadata.description = "Stuff"; td.metadata.name = "[TC] Pete"; td.metadata.owner = "pmoore@mozilla.com"; td.metadata.source = "http://somewhere.com/"; Map<String, Object> features = new HashMap<String, Object>(); features.put("relengAPIProxy", true); Map<String, Object> payload = new HashMap<String, Object>(); payload.put("features", features); td.payload = payload; td.provisionerId = "win-provisioner"; td.retries = 5; td.routes = new String[] { "tc-treeherder.mozilla-inbound.bcf29c305519d6e120b2e4d3b8aa33baaf5f0163", "tc-treeherder-stage.mozilla-inbound.bcf29c305519d6e120b2e4d3b8aa33baaf5f0163" }; td.schedulerId = "junit-test-scheduler"; td.scopes = new String[] {}; Map<String, Object> tags = new HashMap<String, Object>(); tags.put("createdForUser", "cbook@mozilla.com"); td.tags = tags; td.priority = "high"; td.taskGroupId = "dtwuF2n9S-i83G37V9eBuQ"; td.workerType = "win2008-worker"; try { CallSummary<TaskDefinitionRequest, TaskStatusResponse> cs = queue.defineTask(taskId, td); Assert.assertEquals(cs.requestPayload.provisionerId, "win-provisioner"); Assert.assertEquals(cs.responsePayload.status.schedulerId, "junit-test-scheduler"); Assert.assertEquals(cs.responsePayload.status.retriesLeft, 5); Assert.assertEquals(cs.responsePayload.status.state, "unscheduled"); } catch (APICallFailure e) { e.printStackTrace(); Assert.fail("Exception thrown"); } System.out.println("=> Task https://queue.taskcluster.net/v1/task/" + taskId + " created successfully"); } public static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); static { sdf.setTimeZone(TimeZone.getTimeZone("UTC")); } @Test public void createTemporaryCredentials() { BufferedReader br = null; try { Gson gson = new Gson(); br = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("/testcases.json"))); TempCredsTestCase[] testCases = gson.fromJson(br, TempCredsTestCase[].class); for (TempCredsTestCase tc : testCases) { log.info("Testing " + tc.description); Date start = sdf.parse(tc.start); Date expiry = sdf.parse(tc.expiry); Credentials permCreds = new Credentials(tc.permCreds.clientId, tc.permCreds.accessToken); Credentials tempCreds = permCreds.createTemporaryCredentials(tc.tempCredsName, tc.tempCredsScopes, start, expiry); Certificate cert = tempCreds.getCertificate(); cert.seed = tc.seed; // need to generate access token using fixed seed tempCreds.accessToken = Credentials.generateTemporaryAccessToken(permCreds.accessToken, cert.seed); // need to recalculate signature, as seed was updated cert.generateSignature(permCreds.accessToken, tempCreds.clientId); // update credentials with updated certificate tempCreds.certificate = cert.toString(); Assert.assertEquals(tc.expectedTempCreds.clientId, tempCreds.clientId); Assert.assertEquals(tc.expectedTempCreds.accessToken, tempCreds.accessToken); Assert.assertEquals(tc.expectedTempCreds.certificate, tempCreds.certificate); } } catch (Exception e) { e.printStackTrace(); Assert.fail("Exception thrown"); } finally { try { br.close(); } catch (Exception e) { e.printStackTrace(); } } } private static Credentials TEST_AUTH_CREDS = new Credentials("tester", "no-secret"); private static void checkAuthenticate(TestAuthenticateResponse response, String expectedClientID, String[] expectedScopes) { Assert.assertEquals(response.clientId, expectedClientID); Assert.assertEquals(response.scopes, expectedScopes); } @Test public void permaCred() { try { TestAuthenticateRequest request = new TestAuthenticateRequest(); request.clientScopes = new String[] { "scope:*" }; request.requiredScopes = new String[] { "scope:this" }; Auth auth = new Auth(TEST_AUTH_CREDS); CallSummary<TestAuthenticateRequest, TestAuthenticateResponse> cs = auth.testAuthenticate(request); checkAuthenticate(cs.responsePayload, "tester", new String[] { "scope:*" }); } catch (APICallFailure e) { e.printStackTrace(); Assert.fail("Exception thrown"); } } @Test public void tempCred() { Date fiveMinsAgo = new Date(new Date().getTime() - 1000 * 60 * 5); try { Credentials tempCreds = TEST_AUTH_CREDS.createTemporaryCredentials(new String[] { "scope:1", "scope:2" }, // valid 5 mins ago (account for clock skew) fiveMinsAgo, // expire in 55 mins new Date(fiveMinsAgo.getTime() + 1000 * 60 * 60)); TestAuthenticateRequest request = new TestAuthenticateRequest(); request.clientScopes = new String[] { "scope:*" }; request.requiredScopes = new String[] { "scope:1" }; Auth auth = new Auth(tempCreds); CallSummary<TestAuthenticateRequest, TestAuthenticateResponse> cs = auth.testAuthenticate(request); checkAuthenticate(cs.responsePayload, "tester", new String[] { "scope:1", "scope:2" }); } catch (APICallFailure e) { e.printStackTrace(); Assert.fail("Exception thrown"); } catch (InvalidOptionsException e) { e.printStackTrace(); Assert.fail("Exception thrown"); } } @Test public void namedTempCred() { Date fiveMinsAgo = new Date(new Date().getTime() - 1000 * 60 * 5); try { Credentials tempCreds = TEST_AUTH_CREDS.createTemporaryCredentials("jimmy", new String[] { "scope:1", "scope:2" }, // valid 5 mins ago (account for clock skew) fiveMinsAgo, // expire in 55 mins new Date(fiveMinsAgo.getTime() + 1000 * 60 * 60)); TestAuthenticateRequest request = new TestAuthenticateRequest(); request.clientScopes = new String[] { "scope:*", "auth:create-client:jimmy" }; request.requiredScopes = new String[] { "scope:1" }; Auth auth = new Auth(tempCreds); CallSummary<TestAuthenticateRequest, TestAuthenticateResponse> cs = auth.testAuthenticate(request); checkAuthenticate(cs.responsePayload, "jimmy", new String[] { "scope:1", "scope:2" }); } catch (APICallFailure e) { e.printStackTrace(); Assert.fail("Exception thrown"); } catch (InvalidOptionsException e) { e.printStackTrace(); Assert.fail("Exception thrown"); } } @Test public void authorizedScopes() { Date fiveMinsAgo = new Date(new Date().getTime() - 1000 * 60 * 5); try { Credentials permaCredsWithAuthorizedScopes = new Credentials(TEST_AUTH_CREDS.clientId, TEST_AUTH_CREDS.accessToken); permaCredsWithAuthorizedScopes.authorizedScopes = new String[] { "scope:1", "scope:3" }; TestAuthenticateRequest request = new TestAuthenticateRequest(); request.clientScopes = new String[] { "scope:*" }; request.requiredScopes = new String[] { "scope:1" }; Auth auth = new Auth(permaCredsWithAuthorizedScopes); CallSummary<TestAuthenticateRequest, TestAuthenticateResponse> cs = auth.testAuthenticate(request); checkAuthenticate(cs.responsePayload, "tester", new String[] { "scope:1", "scope:3" }); } catch (APICallFailure e) { e.printStackTrace(); Assert.fail("Exception thrown"); } } @Test public void tempCredsWithAuthorizedScopes() { Date fiveMinsAgo = new Date(new Date().getTime() - 1000 * 60 * 5); try { Credentials tempCreds = TEST_AUTH_CREDS.createTemporaryCredentials(new String[] { "scope:1", "scope:2" }, // valid 5 mins ago (account for clock skew) fiveMinsAgo, // expire in 55 mins new Date(fiveMinsAgo.getTime() + 1000 * 60 * 60)); tempCreds.authorizedScopes = new String[] { "scope:1" }; TestAuthenticateRequest request = new TestAuthenticateRequest(); request.clientScopes = new String[] { "scope:*" }; request.requiredScopes = new String[] { "scope:1" }; Auth auth = new Auth(tempCreds); CallSummary<TestAuthenticateRequest, TestAuthenticateResponse> cs = auth.testAuthenticate(request); checkAuthenticate(cs.responsePayload, "tester", new String[] { "scope:1" }); } catch (APICallFailure e) { e.printStackTrace(); Assert.fail("Exception thrown"); } catch (InvalidOptionsException e) { e.printStackTrace(); Assert.fail("Exception thrown"); } } @Test public void namedTempCredsWithAuthorizedScopes() { Date fiveMinsAgo = new Date(new Date().getTime() - 1000 * 60 * 5); try { Credentials tempCreds = TEST_AUTH_CREDS.createTemporaryCredentials("julie", new String[] { "scope:1", "scope:2" }, // valid 5 mins ago (account for clock skew) fiveMinsAgo, // expire in 55 mins new Date(fiveMinsAgo.getTime() + 1000 * 60 * 60)); tempCreds.authorizedScopes = new String[] { "scope:1" }; TestAuthenticateRequest request = new TestAuthenticateRequest(); request.clientScopes = new String[] { "scope:*", "auth:create-client:j*" }; request.requiredScopes = new String[] { "scope:1" }; Auth auth = new Auth(tempCreds); CallSummary<TestAuthenticateRequest, TestAuthenticateResponse> cs = auth.testAuthenticate(request); checkAuthenticate(cs.responsePayload, "julie", new String[] { "scope:1" }); } catch (APICallFailure e) { e.printStackTrace(); Assert.fail("Exception thrown"); } catch (InvalidOptionsException e) { e.printStackTrace(); Assert.fail("Exception thrown"); } } }
package dr.evomodelxml.operators; import dr.evomodel.operators.ExchangeOperator; import dr.evomodel.tree.TreeModel; import dr.inference.operators.MCMCOperator; import dr.xml.*; public class ExchangeOperatorParser { public static final String NARROW_EXCHANGE = "narrowExchange"; public static final String WIDE_EXCHANGE = "wideExchange"; public static final String INTERMEDIATE_EXCHANGE = "intermediateExchange"; public static XMLObjectParser NARROW_EXCHANGE_OPERATOR_PARSER = new AbstractXMLObjectParser() { public String getParserName() { return NARROW_EXCHANGE; } public Object parseXMLObject(XMLObject xo) throws XMLParseException { final TreeModel treeModel = (TreeModel) xo.getChild(TreeModel.class); final double weight = xo.getDoubleAttribute(MCMCOperator.WEIGHT); return new ExchangeOperator(ExchangeOperator.NARROW, treeModel, weight); } // AbstractXMLObjectParser implementation public String getParserDescription() { return "This element represents a narrow exchange operator. " + "This operator swaps a random subtree with its uncle."; } public Class getReturnType() { return ExchangeOperator.class; } public XMLSyntaxRule[] getSyntaxRules() { return rules; } private final XMLSyntaxRule[] rules = { AttributeRule.newDoubleRule(MCMCOperator.WEIGHT), new ElementRule(TreeModel.class) }; }; public static XMLObjectParser INTERMEDIATE_EXCHANGE_OPERATOR_PARSER = new AbstractXMLObjectParser() { public String getParserName() { return INTERMEDIATE_EXCHANGE; } public Object parseXMLObject(XMLObject xo) throws XMLParseException { final TreeModel treeModel = (TreeModel) xo.getChild(TreeModel.class); final double weight = xo.getDoubleAttribute(MCMCOperator.WEIGHT); return new ExchangeOperator(ExchangeOperator.INTERMEDIATE, treeModel, weight); } // AbstractXMLObjectParser implementation public String getParserDescription() { return "This element represents an intermediate exchange operator. " + "This operator swaps two subtree random subtrees with a bias towards nearby subtrees."; } public Class getReturnType() { return ExchangeOperator.class; } public XMLSyntaxRule[] getSyntaxRules() { return rules; } private final XMLSyntaxRule[] rules = { AttributeRule.newDoubleRule(MCMCOperator.WEIGHT), new ElementRule(TreeModel.class) }; }; public static XMLObjectParser WIDE_EXCHANGE_OPERATOR_PARSER = new AbstractXMLObjectParser() { public String getParserName() { return WIDE_EXCHANGE; } public Object parseXMLObject(XMLObject xo) throws XMLParseException { final TreeModel treeModel = (TreeModel) xo.getChild(TreeModel.class); if (treeModel.getExternalNodeCount() <= 2) { throw new XMLParseException("Tree with less than 3 taxa"); } final double weight = xo.getDoubleAttribute(MCMCOperator.WEIGHT); return new ExchangeOperator(ExchangeOperator.WIDE, treeModel, weight); } // AbstractXMLObjectParser implementation public String getParserDescription() { return "This element represents a wide exchange operator. " + "This operator swaps two random subtrees."; } public Class getReturnType() { return ExchangeOperator.class; } public XMLSyntaxRule[] getSyntaxRules() { return rules; } private final XMLSyntaxRule[] rules;{ rules = new XMLSyntaxRule[]{ AttributeRule.newDoubleRule(MCMCOperator.WEIGHT), new ElementRule(TreeModel.class) }; } }; }
package com.pacoapp.paco.sensors.android; import java.util.List; import org.joda.time.DateTime; import org.joda.time.format.DateTimeFormat; import android.app.Service; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.IBinder; import android.os.PowerManager; import android.util.Log; import com.pacoapp.paco.PacoConstants; import com.pacoapp.paco.UserPreferences; import com.pacoapp.paco.model.Event; import com.pacoapp.paco.model.EventUtil; import com.pacoapp.paco.model.Experiment; import com.pacoapp.paco.model.ExperimentProviderUtil; import com.pacoapp.paco.model.Output; import com.pacoapp.paco.net.SyncService; import com.pacoapp.paco.shared.model2.ExperimentGroup; import com.pacoapp.paco.shared.model2.InterruptCue; import com.pacoapp.paco.shared.model2.InterruptTrigger; import com.pacoapp.paco.shared.model2.PacoAction; import com.pacoapp.paco.shared.model2.PacoNotificationAction; import com.pacoapp.paco.shared.scheduling.ActionSpecification; import com.pacoapp.paco.shared.util.ExperimentHelper; import com.pacoapp.paco.shared.util.ExperimentHelper.Trio; import com.pacoapp.paco.shared.util.TimeUtil; import com.pacoapp.paco.triggering.AndroidActionExecutor; import com.pacoapp.paco.triggering.NotificationCreator; public class BroadcastTriggerService extends Service { @Override public IBinder onBind(Intent intent) { return null; } public void onStart(Intent intent, int startId) { super.onStart(intent, startId); if (intent == null) { Log.e(PacoConstants.TAG, "Null intent on broadcast trigger!"); return; } final Bundle extras = intent.getExtras(); PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); final PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Paco BroadcastTriggerService wakelock"); wl.acquire(); Runnable runnable = new Runnable() { public void run() { try { propagateToExperimentsThatCare(extras); } finally { wl.release(); stopSelf(); } } }; (new Thread(runnable)).start(); } protected synchronized void propagateToExperimentsThatCare(Bundle extras) { final int triggerEvent = extras.getInt(Experiment.TRIGGER_EVENT); final String sourceIdentifier = extras.getString(Experiment.TRIGGER_SOURCE_IDENTIFIER); final String timeStr = extras.getString(Experiment.TRIGGERED_TIME); // TODO pass the duration along to the experiment somehow (either log it at // the moment it happened, or, pass it in the notification (yuck)? final long duration = extras.getLong(Experiment.TRIGGER_PHONE_CALL_DURATION); DateTime time = null; if (timeStr != null) { time = DateTimeFormat.forPattern(TimeUtil.DATETIME_FORMAT).parseDateTime(timeStr); } ExperimentProviderUtil eu = new ExperimentProviderUtil(this); DateTime now = new DateTime(); NotificationCreator notificationCreator = NotificationCreator.create(this); List<Experiment> joined = eu.getJoinedExperiments(); for (Experiment experiment : joined) { if (!experiment.isRunning(now) && triggerEvent != InterruptCue.PACO_EXPERIMENT_ENDED_EVENT && triggerEvent != InterruptCue.PACO_EXPERIMENT_JOINED_EVENT) { // TODO This doesn't work if the experiment for experiment ended events // because the experiment is already over. Log.i(PacoConstants.TAG, "Skipping experiment: " + experiment.getExperimentDAO().getTitle()); continue; } Log.i(PacoConstants.TAG, "We have an experiment that is running"); List<ExperimentGroup> groupsListening = ExperimentHelper.isBackgroundListeningForSourceId(experiment.getExperimentDAO(), sourceIdentifier); persistBroadcastData(eu, experiment, groupsListening, extras); List<Trio<ExperimentGroup, InterruptTrigger, InterruptCue>> triggersThatMatch = ExperimentHelper.shouldTriggerBy(experiment.getExperimentDAO(), triggerEvent, sourceIdentifier); if (ExperimentHelper.declaresAccessibilityLogging(experiment.getExperimentDAO())) { List<ExperimentGroup> accessibilityGroupsListening = ExperimentHelper.isListeningForAccessibilityEvents(experiment.getExperimentDAO()); persistAccessibilityData(eu, experiment, accessibilityGroupsListening, extras.getBundle(RuntimePermissionMonitorService.PACO_ACTION_ACCESSIBILITY_PAYLOAD)); } Log.i(PacoConstants.TAG, "triggers that match count: " + triggersThatMatch.size()); for (Trio<ExperimentGroup, InterruptTrigger, InterruptCue> triggerInfo : triggersThatMatch) { final InterruptTrigger actionTrigger = triggerInfo.second; String uniqueStringForTrigger = createUniqueStringForTrigger(experiment, triggerInfo); if (!recentlyTriggered(experiment, uniqueStringForTrigger, actionTrigger.getMinimumBuffer())) { setRecentlyTriggered(now, uniqueStringForTrigger); List<PacoAction> actions = actionTrigger.getActions(); for (PacoAction pacoAction : actions) { final ExperimentGroup group = triggerInfo.first; final Long actionTriggerSpecId = triggerInfo.third != null ? triggerInfo.third.getId() : null; if (pacoAction.getActionCode() == pacoAction.NOTIFICATION_TO_PARTICIPATE_ACTION_CODE) { ActionSpecification timeExperiment = new ActionSpecification(time, experiment.getExperimentDAO(), group, actionTrigger, (PacoNotificationAction) pacoAction, actionTriggerSpecId); Log.i(PacoConstants.TAG, "creating a notification"); final long delay = ((PacoNotificationAction) pacoAction).getDelay(); notificationCreator.createNotificationsForTrigger(experiment, triggerInfo, delay, time, triggerEvent, sourceIdentifier, timeExperiment); Log.i(PacoConstants.TAG, "created a notification"); } else if (pacoAction.getActionCode() == PacoAction.EXECUTE_SCRIPT_ACTION_CODE) { AndroidActionExecutor.runAction(getApplicationContext(), pacoAction, experiment, experiment.getExperimentDAO(), group, actionTriggerSpecId, actionTrigger.getId()); } } } } } } private void setRecentlyTriggered(DateTime now, String uniqueStringForTrigger) { UserPreferences prefs = new UserPreferences(getApplicationContext()); prefs.setRecentlyTriggeredTime(uniqueStringForTrigger, now); } private boolean recentlyTriggered(Experiment experiment, String uniqueStringForTrigger, int minimumBuffer) { UserPreferences prefs = new UserPreferences(getApplicationContext()); DateTime recentlyTriggered = prefs.getRecentlyTriggeredTime(uniqueStringForTrigger); return recentlyTriggered != null && recentlyTriggered.plusMinutes(minimumBuffer).isAfterNow(); } public String createUniqueStringForTrigger(Experiment experiment, Trio<ExperimentGroup, InterruptTrigger, InterruptCue> triggerInfo) { // only create a key down to the trigger - return experiment.getId() + ":" + triggerInfo.first.getName() + ":" + triggerInfo.second.getId(); } /* * create and persist event containing any payload data sent along in original PACO_INTENT broadcast */ private void persistBroadcastData(ExperimentProviderUtil eu, Experiment experiment, List<ExperimentGroup> groupsListening, Bundle extras) { long nowMillis = new DateTime().getMillis(); for (ExperimentGroup experimentGroup : groupsListening) { Event event = EventUtil.createEvent(experiment, experimentGroup.getName(), nowMillis, null, null, null); Bundle payload = extras.getBundle(BroadcastTriggerReceiver.PACO_ACTION_PAYLOAD); persistEventBundle(eu, event, payload); } notifySyncService(); } /** * Persist data related to accessibility events, sent along as part of the * PACO_ACTION_ACCESSIBILITY_PAYLOAD bundle. * @param experimentProviderUtil an initialized ExperimentProviderUtil * @param experiment the experiment for which to save the events * @param payload the PACO_ACTION_ACCESSIBILITY_PAYLOAD bundle */ private void persistAccessibilityData(ExperimentProviderUtil experimentProviderUtil, Experiment experiment, List<ExperimentGroup> groupsListening, Bundle payload) { if (payload == null) { Log.v(PacoConstants.TAG, "No accessibility data for this trigger."); return; } Log.v(PacoConstants.TAG, "Persisting accessibility data for experiment " + experiment.getExperimentDAO().getTitle()); long nowMillis = new DateTime().getMillis(); for (ExperimentGroup experimentGroup : groupsListening) { Event event = EventUtil.createEvent(experiment, experimentGroup.getName(), nowMillis, null, null, null); persistEventBundle(experimentProviderUtil, event, payload); } notifySyncService(); } /** * Helper function for persistAccessibilityData() and persistBroadcastData(). * Stores all information in a Bundle in a given Event * @param experimentProviderUtil an initialized ExperimentProviderUtil * @param event Event for which the data should be stored * @param payload The data, as key-value pairs */ private void persistEventBundle(ExperimentProviderUtil experimentProviderUtil, Event event, Bundle payload) { for (String key : payload.keySet()) { if (payload.get(key) == null) { continue; } Output output = new Output(); output.setEventId(event.getId()); output.setName(key); output.setAnswer(payload.get(key).toString()); event.addResponse(output); } experimentProviderUtil.insertEvent(event); } private void notifySyncService() { startService(new Intent(this, SyncService.class)); } }
package lhpn2sbml.parser; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.swing.JOptionPane; //import org.apache.batik.svggen.font.table.Program; import org.sbml.libsbml.Compartment; import org.sbml.libsbml.Constraint; //import org.sbml.libsbml.Delay; import org.sbml.libsbml.AssignmentRule; import org.sbml.libsbml.Event; import org.sbml.libsbml.EventAssignment; import org.sbml.libsbml.FunctionDefinition; import org.sbml.libsbml.KineticLaw; import org.sbml.libsbml.Model; import org.sbml.libsbml.Parameter; import org.sbml.libsbml.RateRule; import org.sbml.libsbml.Reaction; import org.sbml.libsbml.SBMLDocument; import org.sbml.libsbml.SBMLWriter; import org.sbml.libsbml.Species; import org.sbml.libsbml.SpeciesReference; import org.sbml.libsbml.Trigger; import org.sbml.libsbml.libsbml; import sbmleditor.SBML_Editor; import lhpn2sbml.parser.ExprTree; import biomodelsim.BioSim; /** * This class converts a lph file to a sbml file * * @author Zhen Zhang * */ public class Translator { private String filename; private SBMLDocument document; public void BuildTemplate(String lhpnFilename, String property) { this.filename = lhpnFilename.replace(".lpn", ".xml"); // load lhpn file LhpnFile lhpn = new LhpnFile(); lhpn.load(lhpnFilename); // create sbml file //document = new SBMLDocument(BioSim.SBML_LEVEL, BioSim.SBML_VERSION); document = new SBMLDocument(3,1); Model m = document.createModel(); Compartment c = m.createCompartment(); m.setId(filename.replace(".xml", "")); c.setId("default"); c.setSize(1.0); c.setConstant(true); c.setSpatialDimensions(3); // Create bitwise operators for sbml createFunction(m, "rate", "Rate", "lambda(a,a)"); createFunction(m, "BITAND", "Bitwise AND", "lambda(a,b,a*b)"); createFunction(m, "BITOR", "Bitwise AND", "lambda(a,b,a*b)"); createFunction(m, "BITNOT", "Bitwise AND", "lambda(a,b,a*b)"); createFunction(m, "BITXOR", "Bitwise AND", "lambda(a,b,a*b)"); createFunction(m, "mod", "Modular", "lambda(a,b,a-floor(a/b)*b)"); createFunction(m, "and", "Logical AND", "lambda(a,b,a*b)"); createFunction(m, "uniform", "Uniform distribution", "lambda(a,b,(a+b)/2)"); createFunction(m, "normal", "Normal distribution", "lambda(m,s,m)"); createFunction(m, "exponential", "Exponential distribution", "lambda(l,1/l)"); createFunction(m, "gamma", "Gamma distribution", "lambda(a,b,a*b)"); createFunction(m, "lognormal", "Lognormal distribution", "lambda(z,s,exp(z+s^2/2))"); createFunction(m, "chisq", "Chi-squared distribution", "lambda(nu,nu)"); createFunction(m, "laplace", "Laplace distribution", "lambda(a,0)"); createFunction(m, "cauchy", "Cauchy distribution", "lambda(a,a)"); createFunction(m, "rayleigh", "Rayleigh distribution", "lambda(s,s*sqrt(pi/2))"); createFunction(m, "poisson", "Poisson distribution", "lambda(mu,mu)"); createFunction(m, "binomial", "Binomial distribution", "lambda(p,n,p*n)"); createFunction(m, "bernoulli", "Bernoulli distribution", "lambda(p,p)"); //createFunction(m, "priority", "Priority expressions", "lambda(d,p,d)"); // translate from lhpn to sbml for (String v: lhpn.getVariables()){ // System.out.println("Vars from lhpn.getVariables() " + v); if (v != null){ String initVal = lhpn.getInitialVal(v); // System.out.println("Begin:" + v + "= " + initVal); if (lhpn.isContinuous(v) || lhpn.isInteger(v)){ Parameter p = m.createParameter(); p.setConstant(false); p.setId(v); // For each continuous variable v, create rate rule dv/dt and set its initial value to lhpn.getInitialRate(v). if (lhpn.isContinuous(v)){ Parameter p_dot = m.createParameter(); p_dot.setConstant(false); p_dot.setId(v + "_dot"); // System.out.println("v_dot = " + v + "_dot"); RateRule rateRule = m.createRateRule(); rateRule.setVariable(v); rateRule.setMath(SBML_Editor.myParseFormula(v + "_dot")); String initValDot= lhpn.getInitialRate(v); double initValDot_dbl = Double.parseDouble(initValDot); p_dot.setValue(initValDot_dbl); } // Assign initial values to continuous, discrete and boolean variables // Short term fix: Extract the lower and upper bounds and set the initial value to the mean. // Anything that involves infinity, take either the lower or upper bound which is not infinity. // If both are infinity, set to 0. String initValue = lhpn.getInitialVal(v); String tmp_initValue = initValue; String[] subString = initValue.split(","); String lowerBound = null; String upperBound = null; // initial value is a range if (tmp_initValue.contains(",")){ // If the initial value is a range, check the range only contains one "," tmp_initValue = tmp_initValue.replaceFirst(",", ""); // // Test if tmp_initValue contains any more ",": if not, continue to extract upper and lower bounds // if (tmp_initValue.contains(",")){ // System.out.println("The inital range of variable " + v + " is incorrect."); // System.exit(0); // Extract the lower and upper bound of the initValue int i; for (i = 0; i<subString.length; i ++) { // System.out.println("splitted initValue range " + subString[i].toString()); if (subString[i].contains("[")){ lowerBound = subString[i].replace("[", ""); // System.out.println("remove [ " + subString[i].replace("[", "").toString()); } if (subString[i].contains("uniform(")){ lowerBound = subString[i].replace("uniform(", ""); // System.out.println("remove uniform( " + subString[i].replace("[", "").toString()); } else if(subString[i].contains("]")){ upperBound = subString[i].replace("]", ""); // System.out.println("remove ] " + subString[i].replace("]", "").toString()); } else if(subString[i].contains(")")){ upperBound = subString[i].replace(")", ""); // System.out.println("remove ) " + subString[i].replace("]", "").toString()); } } // initial value involves infinity if (lowerBound.contains("inf") || upperBound.contains("inf")){ if (lowerBound.contains("-inf") && upperBound.contains("inf")){ initValue = "0" ; // if [-inf,inf], initValue = 0 } else if (lowerBound.contains("-inf") && !upperBound.contains("inf")){ initValue = upperBound; // if [-inf,a], initValue = a } else if (!lowerBound.contains("-inf") && upperBound.contains("inf")){ initValue = lowerBound; // if [a,inf], initValue = a } double initVal_dbl = Double.parseDouble(initValue); p.setValue(initVal_dbl); } // initial value is a range, not involving infinity else { double lowerBound_dbl = Double.parseDouble(lowerBound); double upperBound_dbl = Double.parseDouble(upperBound); double initVal_dbl = (lowerBound_dbl + upperBound_dbl)/2; p.setValue(initVal_dbl); } } // initial value is a single number else { double initVal_dbl = Double.parseDouble(initValue); p.setValue(initVal_dbl); } } else // boolean variable { Parameter p = m.createParameter(); p.setConstant(false); p.setId(v); String initValue = lhpn.getInitialVal(v); // System.out.println(v + "=" + initValue); // check initValue type; if boolean, set parameter value as 0 or 1. if (initValue.equals("true")){ p.setValue(1); } else if (initValue.equals("false")){ p.setValue(0); } else if (initValue.equals("unknown")){ p.setValue(0); } else { // double initVal_dbl = Double.parseDouble(initValue); // p.setValue(initVal_dbl); System.out.println("It should be a boolean variable."); System.exit(0); } } } } for (String p: lhpn.getPlaceList()){ Boolean initMarking = lhpn.getPlace(p).isMarked(); // System.out.println(p + "=" + initMarking); Species sp = m.createSpecies(); sp.setId(p); sp.setCompartment("default"); sp.setBoundaryCondition(false); sp.setConstant(false); sp.setHasOnlySubstanceUnits(false); if (initMarking){ sp.setInitialAmount(1); } else { sp.setInitialAmount(0); } sp.setUnits(""); } // if transition rate is not null, use reaction and event; // else use event only int counter = lhpn.getTransitionList().length - 1; for (String t : lhpn.getTransitionList()) { if(lhpn.getTransition(t).getTransitionRate()!=null){ Species spT = m.createSpecies(); spT.setId(t); spT.setCompartment("default"); spT.setBoundaryCondition(false); spT.setConstant(false); spT.setHasOnlySubstanceUnits(false); spT.setInitialAmount(0); spT.setUnits(""); Reaction r = m.createReaction(); r.setReversible(false); r.setId("r" + counter); //test En(t) String EnablingTestNull = lhpn.getTransition(t).getEnabling(); String EnablingBool; String Enabling; if (EnablingTestNull == null){ Enabling = "1"; // Enabling is true (Boolean) } else { EnablingBool = lhpn.getEnablingTree(t).getElement("SBML"); Enabling = "piecewise(1," + EnablingBool + ",0)"; } // System.out.println("Enabling = " + Enabling); //test Preset(t) String CheckPreset = null; int indexPreset = 0; // Check if all the presets of transition t are marked // Transition t can fire only when all its preset are marked. for (String x:lhpn.getPreset(t)){ if (indexPreset == 0){ CheckPreset = "eq(" + x + ",1)"; } else { CheckPreset = "and(" + CheckPreset + "," + "eq(" + x + ",1)" + ")"; } indexPreset ++; } String reactantStr = ""; for (String x : lhpn.getPreset(t)){ // Is transition persistent? if (lhpn.getTransition(t).isPersistent()){ // transition is persistent // Create a rule for the persistent transition t. AssignmentRule rulePersis = m.createAssignmentRule(); String rulePersisSpeciesStr = "rPersis_" + t + x; // Create a parameter (id = rulePersisTriggName). Species rulePersisSpecies = m.createSpecies(); rulePersisSpecies.setId(rulePersisSpeciesStr); rulePersisSpecies.setCompartment("default"); rulePersisSpecies.setBoundaryCondition(false); rulePersisSpecies.setConstant(false); rulePersisSpecies.setHasOnlySubstanceUnits(false); rulePersisSpecies.setUnits(""); String ruleExpBool = "or(and(" + CheckPreset + "," + Enabling + "), and(" + CheckPreset + "," + "eq(" + rulePersisSpeciesStr + ", 1)" +"))"; String ruleExpReal = "piecewise(1, " + ruleExpBool + ", 0)"; rulePersis.setVariable(rulePersisSpeciesStr); double ruleVal = rulePersis.setMath(SBML_Editor.myParseFormula(ruleExpReal)); SpeciesReference reactant = r.createReactant(); reactant.setSpecies(rulePersisSpeciesStr); reactant.setStoichiometry(ruleVal); // create the part of Kinetic law expression involving reactants reactantStr = reactantStr + reactant.getSpecies().toString() + "*"; } else { // get preset(s) of a transition and set each as a reactant SpeciesReference reactant = r.createReactant(); reactant.setSpecies(x); reactant.setStoichiometry(1.0); reactantStr = reactantStr + reactant.getSpecies().toString() + "*"; } } SpeciesReference product = r.createProduct(); product.setSpecies(t); product.setStoichiometry(1.0); KineticLaw rateReaction = r.createKineticLaw(); // rate of reaction //Parameter p_local = rateReaction.createParameter(); //p_local.setConstant(false); //p_local.setId("rate" + counter); // get the transition rate from LHPN //System.out.println("transition rate = " + lhpn.getTransitionRate(t)); //double tRate = Double.parseDouble(lhpn.getTransitionRate(t)); //p_local.setValue(tRate); //lhpn.getTransitionRateTree(t) // create exp for KineticLaw rateReaction.setFormula("(" + reactantStr + lhpn.getTransitionRateTree(t).getElement("SBML") + ")"); //System.out.println("trans " + t + " enableCond " + lhpn.getEnabling(t)); Event e = m.createEvent(); e.setId("event" + counter); Trigger trigger = e.createTrigger(); trigger.setMath(SBML_Editor.myParseFormula("eq(" + product.getSpecies() + ",1)")); // For persistent transition, it does not matter whether the trigger is persistent or not, because the delay is set to 0. trigger.setPersistent(false); e.setUseValuesFromTriggerTime(false); trigger.setInitialValue(false); // t_postSet = 1 for (String x : lhpn.getPostset(t)){ EventAssignment assign0 = e.createEventAssignment(); assign0.setVariable(x); assign0.setMath(SBML_Editor.myParseFormula("1")); // System.out.println("transition: " + t + " postset: " + x); } // product = 0 EventAssignment assign1 = e.createEventAssignment(); assign1.setVariable(product.getSpecies()); assign1.setMath(SBML_Editor.myParseFormula("0")); // assignment <A> // continuous assignment if (lhpn.getContVars(t) != null){ for (String var : lhpn.getContVars(t)){ if (lhpn.getContAssign(t, var) != null) { ExprTree assignContTree = lhpn.getContAssignTree(t, var); String assignCont = assignContTree.toString("SBML"); // System.out.println("continuous assign: "+ assignCont); EventAssignment assign2 = e.createEventAssignment(); assign2.setVariable(var); assign2.setMath(SBML_Editor.myParseFormula(assignCont)); } } } // integer assignment if (lhpn.getIntVars()!= null){ for (String var : lhpn.getIntVars()){ if (lhpn.getIntAssign(t, var) != null) { ExprTree assignIntTree = lhpn.getIntAssignTree(t, var); String assignInt = assignIntTree.toString("SBML"); // System.out.println("integer assignment from LHPN: " + var + " := " + assignInt); EventAssignment assign3 = e.createEventAssignment(); assign3.setVariable(var); assign3.setMath(SBML_Editor.myParseFormula(assignInt)); } } } // boolean assignment if (lhpn.getBooleanVars(t)!= null){ for (String var :lhpn.getBooleanVars(t)){ if (lhpn.getBoolAssign(t, var) != null) { ExprTree assignBoolTree = lhpn.getBoolAssignTree(t, var); String assignBool_tmp = assignBoolTree.toString("SBML"); String assignBool = "piecewise(1," + assignBool_tmp + ",0)"; // System.out.println("boolean assignment from LHPN: " + var + " := " + assignBool); EventAssignment assign4 = e.createEventAssignment(); assign4.setVariable(var); assign4.setMath(SBML_Editor.myParseFormula(assignBool)); } } } // rate assignment if (lhpn.getRateVars(t)!= null){ for (String var : lhpn.getRateVars(t)){ // System.out.println("rate var: "+ var); if (lhpn.getRateAssign(t, var) != null) { ExprTree assignRateTree = lhpn.getRateAssignTree(t, var); String assignRate = assignRateTree.toString("SBML"); // System.out.println("rate assign: "+ assignRate); EventAssignment assign5 = e.createEventAssignment(); assign5.setVariable(var + "_dot"); assign5.setMath(SBML_Editor.myParseFormula(assignRate)); } } } } else { // Transition rate = null. Only use event. Transitions only have ranges // System.out.println("Event Only"); Event e = m.createEvent(); e.setId("event" + counter); Trigger trigger = e.createTrigger(); //trigger = CheckPreset(t) && En(t); //test En(t) String EnablingTestNull = lhpn.getTransition(t).getEnabling(); String Enabling; if (EnablingTestNull == null){ Enabling = "eq(1,1)"; // Enabling is true (Boolean) } else { Enabling = lhpn.getEnablingTree(t).getElement("SBML"); } // System.out.println("Enabling = " + Enabling); //test Preset(t) String CheckPreset = null; int indexPreset = 0; // Check if all the presets of transition t are marked // Transition t can fire only when all its preset are marked. for (String x:lhpn.getPreset(t)){ if (indexPreset == 0){ CheckPreset = "eq(" + x + ",1)"; } else { CheckPreset = "and(" + CheckPreset + "," + "eq(" + x + ",1)" + ")"; } indexPreset ++; } // Is transition persistent? if (!lhpn.getTransition(t).isPersistent() || (lhpn.getTransition(t).isPersistent() && !lhpn.getTransition(t).hasConflictSet())){ if (!lhpn.getTransition(t).isPersistent()) { trigger.setPersistent(false); } else { trigger.setPersistent(true); } trigger.setMath(SBML_Editor.myParseFormula("and(" + CheckPreset + "," + Enabling + ")")); } else { // transition is persistent // Create a rule for the persistent transition t. AssignmentRule rulePersisTrigg = m.createAssignmentRule(); String rulePersisTriggName = "trigg_" + t; // Create a parameter (id = rulePersisTriggName). Parameter rulePersisParam = m.createParameter(); rulePersisParam.setId(rulePersisTriggName); rulePersisParam.setValue(0); rulePersisParam.setConstant(false); rulePersisParam.setUnits(""); String ruleExpBool = "or(and(" + CheckPreset + "," + Enabling + "), and(" + CheckPreset + "," + "eq(" + rulePersisTriggName + ", 1)" +"))"; String ruleExpReal = "piecewise(1, " + ruleExpBool + ", 0)"; rulePersisTrigg.setVariable(rulePersisTriggName); rulePersisTrigg.setMath(SBML_Editor.myParseFormula(ruleExpReal)); trigger.setPersistent(false); trigger.setMath(SBML_Editor.myParseFormula("eq(" + rulePersisTriggName + ", 1)")); } // TriggerInitiallyFalse // trigger.setAnnotation("<TriggerInitiallyFalse/>"); trigger.setInitialValue(false); // use values at trigger time = false e.setUseValuesFromTriggerTime(false); // Priority and delay if (lhpn.getTransition(t).getDelay()!=null) { e.createDelay(); e.getDelay().setMath(SBML_Editor.myParseFormula(lhpn.getTransition(t).getDelay())); } if (lhpn.getTransition(t).getPriority()!=null) { e.createPriority(); e.getPriority().setMath(SBML_Editor.myParseFormula(lhpn.getTransition(t).getPriority())); } /* if (lhpn.getTransition(t).getPriority()==null) { if (lhpn.getTransition(t).getDelay()!=null) { e.createDelay(); e.getDelay().setMath(SBML_Editor.myParseFormula(lhpn.getTransition(t).getDelay())); } } else { if (lhpn.getTransition(t).getDelay()!=null) { e.createDelay(); e.getDelay().setMath(SBML_Editor.myParseFormula("priority(" + lhpn.getTransition(t).getDelay() + "," + lhpn.getTransition(t).getPriority() + ")")); } else { e.createDelay(); e.getDelay().setMath(SBML_Editor.myParseFormula("priority(0," + lhpn.getTransition(t).getPriority() + ")")); } } */ // Check if there is any self-loop. If the intersection between lhpn.getPreset(t) and lhpn.getPostset(t) // is not empty, self-loop exists. List<String> t_preset = Arrays.asList(lhpn.getPreset(t)); List<String> t_postset = Arrays.asList(lhpn.getPostset(t)); List<String> t_intersect = new ArrayList<String>(); // intersection of t_preset and t_postset List<String> t_NoIntersect = new ArrayList<String>(); // t_NoIntersect = t_postset - t_preset Boolean selfLoopFlag = false; // Check if there is intersection between the preset and postset. for (String x : lhpn.getPreset(t)){ if (t_postset.contains(x)){ selfLoopFlag = true; t_intersect.add(x); } } if (selfLoopFlag) { t_NoIntersect.removeAll(t_intersect); // t_preset = 0 for (String x : lhpn.getPreset(t)){ EventAssignment assign0 = e.createEventAssignment(); assign0.setVariable(x); assign0.setMath(SBML_Editor.myParseFormula("0")); // System.out.println("transition: " + t + " preset: " + x); } // t_NoIntersect = 1 for (String x : t_NoIntersect){ EventAssignment assign1 = e.createEventAssignment(); assign1.setVariable(x); assign1.setMath(SBML_Editor.myParseFormula("1")); // System.out.println("transition: " + t + " postset: " + x); } } else { // no self-loop // t_preSet = 0 for (String x : lhpn.getPreset(t)){ EventAssignment assign0 = e.createEventAssignment(); assign0.setVariable(x); assign0.setMath(SBML_Editor.myParseFormula("0")); // System.out.println("transition: " + t + " preset: " + x); } // t_postSet = 1 for (String x : lhpn.getPostset(t)){ EventAssignment assign1 = e.createEventAssignment(); assign1.setVariable(x); assign1.setMath(SBML_Editor.myParseFormula("1")); // System.out.println("transition: " + t + " postset: " + x); } } // assignment <A> // continuous assignment if (lhpn.getContVars(t) != null){ for (String var : lhpn.getContVars(t)){ if (lhpn.getContAssign(t, var) != null) { ExprTree assignContTree = lhpn.getContAssignTree(t, var); String assignCont = assignContTree.toString("SBML"); // System.out.println("continuous assign: "+ assignCont); EventAssignment assign2 = e.createEventAssignment(); assign2.setVariable(var); assign2.setMath(SBML_Editor.myParseFormula(assignCont)); } } } // integer assignment if (lhpn.getIntVars()!= null){ for (String var : lhpn.getIntVars()){ if (lhpn.getIntAssign(t, var) != null) { ExprTree assignIntTree = lhpn.getIntAssignTree(t, var); String assignInt = assignIntTree.toString("SBML"); // System.out.println("integer assignment from LHPN: " + var + " := " + assignInt); EventAssignment assign3 = e.createEventAssignment(); assign3.setVariable(var); assign3.setMath(SBML_Editor.myParseFormula(assignInt)); } } } // boolean assignment if (selfLoopFlag) { // if self-loop exists, create a new variable, extraVar, and a new event String extraVar = t.concat("_extraVar"); Parameter p = m.createParameter(); p.setConstant(false); p.setId(extraVar); p.setValue(0); EventAssignment assign4ex = e.createEventAssignment(); assign4ex.setVariable(extraVar); assign4ex.setMath(SBML_Editor.myParseFormula("1")); // Create other boolean assignments if (lhpn.getBooleanVars(t)!= null){ for (String var :lhpn.getBooleanVars(t)){ if (lhpn.getBoolAssign(t, var) != null) { ExprTree assignBoolTree = lhpn.getBoolAssignTree(t, var); String assignBool_tmp = assignBoolTree.toString("SBML"); String assignBool = "piecewise(1," + assignBool_tmp + ",0)"; //System.out.println("boolean assignment from LHPN: " + var + " := " + assignBool); EventAssignment assign4 = e.createEventAssignment(); assign4.setVariable(var); assign4.setMath(SBML_Editor.myParseFormula(assignBool)); } } } // create a new event Event extraEvent = m.createEvent(); extraEvent.setId("extraEvent" + counter); Trigger triggerExtra = extraEvent.createTrigger(); //triggerExtra.setMath(SBML_Editor.myParseFormula("and(gt(t,0),eq(" + extraVar + ",1))")); triggerExtra.setMath(SBML_Editor.myParseFormula("eq(" + extraVar + ",1)")); //triggerExtra.setAnnotation("<TriggerInitiallyFalse/>"); triggerExtra.setPersistent(true); triggerExtra.setInitialValue(false); extraEvent.setUseValuesFromTriggerTime(false); // assignments EventAssignment assign5ex2 = extraEvent.createEventAssignment(); for (String var : t_intersect){ EventAssignment assign5ex1 = extraEvent.createEventAssignment(); assign5ex1.setVariable(var); assign5ex1.setMath(SBML_Editor.myParseFormula("1")); } assign5ex2.setVariable(extraVar); assign5ex2.setMath(SBML_Editor.myParseFormula("0")); } else { if (lhpn.getBooleanVars(t)!= null){ for (String var :lhpn.getBooleanVars(t)){ if (lhpn.getBoolAssign(t, var) != null) { ExprTree assignBoolTree = lhpn.getBoolAssignTree(t, var); String assignBool_tmp = assignBoolTree.toString("SBML"); String assignBool = "piecewise(1," + assignBool_tmp + ",0)"; //System.out.println("boolean assignment from LHPN: " + var + " := " + assignBool); EventAssignment assign4 = e.createEventAssignment(); assign4.setVariable(var); assign4.setMath(SBML_Editor.myParseFormula(assignBool)); } } } } // rate assignment if (lhpn.getRateVars(t)!= null){ for (String var : lhpn.getRateVars(t)){ // System.out.println("rate var: "+ var); if (lhpn.getRateAssign(t, var) != null) { ExprTree assignRateTree = lhpn.getRateAssignTree(t, var); String assignRate = assignRateTree.toString("SBML"); // System.out.println("rate assign: "+ assignRate); EventAssignment assign5 = e.createEventAssignment(); assign5.setVariable(var + "_dot"); assign5.setMath(SBML_Editor.myParseFormula(assignRate)); } } } } counter } // Property parsing is dealt with in PropertyPanel.java // translate the LPN property to SBML constraints String probprop = ""; String[] probpropParts = new String[4]; if(!(property == null) && !property.equals("")){ probprop=getProbpropExpression(property); probpropParts=getProbpropParts(probprop); //System.out.println("probprop=" + probprop); //System.out.println("probpropParts[0]=" + probpropParts[0]); //System.out.println("probpropParts[1]=" + probpropParts[1]); //System.out.println("probpropParts[2]=" + probpropParts[2]); //System.out.println("probpropParts[3]=" + probpropParts[3]); // Convert extrated property parts into SBML constraints // probpropParts=[probpropLeft, probpropRight, lowerBound, upperBound] Constraint constraintFail = m.createConstraint(); Constraint constraintSucc = m.createConstraint(); ExprTree probpropLeftTree = String2ExprTree(lhpn, probpropParts[0]); String probpropLeftSBML = probpropLeftTree.toString("SBML"); ExprTree probpropRightTree = String2ExprTree(lhpn, probpropParts[1]); String probpropRightSBML = probpropRightTree.toString("SBML"); ExprTree lowerBoundTree = String2ExprTree(lhpn, probpropParts[2]); String lowerBoundSBML = lowerBoundTree.toString("SBML"); String lowerConstraint = "leq(t," + lowerBoundSBML + ")"; ExprTree upperBoundTree = String2ExprTree(lhpn, probpropParts[3]); String upperBoundSBML = upperBoundTree.toString("SBML"); String upperConstraint = "leq(t," + upperBoundSBML + ")"; if (property.contains("PU")){ // construct the SBML constraints constraintFail.setMetaId("Fail"); constraintFail.setMath(SBML_Editor.myParseFormula("and(" + probpropLeftSBML + "," + upperConstraint + ")")); constraintSucc.setMetaId("Success"); constraintSucc.setMath(SBML_Editor.myParseFormula("not(" + probpropRightSBML + ")")); } if (property.contains("PF")){ constraintFail.setMetaId("Fail"); constraintFail.setMath(SBML_Editor.myParseFormula(upperConstraint)); constraintSucc.setMetaId("Success"); constraintSucc.setMath(SBML_Editor.myParseFormula("not(" + probpropRightSBML + ")")); } if (property.contains("PG")){ constraintFail.setMetaId("Fail"); constraintFail.setMath(SBML_Editor.myParseFormula(probpropRightSBML)); constraintSucc.setMetaId("Success"); constraintSucc.setMath(SBML_Editor.myParseFormula(upperConstraint)); } } } private void createFunction(Model model, String id, String name, String formula) { if (document.getModel().getFunctionDefinition(id) == null) { FunctionDefinition f = model.createFunctionDefinition(); f.setId(id); f.setName(name); f.setMath(libsbml.parseFormula(formula)); } } public void outputSBML() { SBMLWriter writer = new SBMLWriter(); writer.writeSBML(document, filename); } public void setFilename(String filename) { this.filename = filename; } public String getFilename() { return filename; } // getProbpropExpression strips off the "Pr"("St"), relop and REAL parts of a property public static String getProbpropExpression(String property){ System.out.println("property (getProbpropExpression)= " + property); String probprop=""; // probproperty if (property.startsWith("Pr") | property.startsWith("St")){ // remove Pr/St from the property spec property=property.substring(2); boolean relopFlag = property.startsWith(">") | property.startsWith(">=") | property.startsWith("<") | property.startsWith("<=") | (property.startsWith("=") && !property.contains("?")); if (relopFlag){ if(property.startsWith(">=") | property.startsWith("<=")){ property=property.substring(2); } else{ property=property.substring(1); } // check the probability value after relop String probabilityValue = property.substring(0,property.indexOf("{")); Pattern ProbabilityValuePattern = Pattern.compile(probabilityValue); Matcher ProbabilityValueMatcher = ProbabilityValuePattern.matcher(probabilityValue); boolean correctProbabilityValue = ProbabilityValueMatcher.matches(); if(correctProbabilityValue) { property=property.replaceFirst(probabilityValue, ""); property=property.replace("{", ""); property=property.replace("}", ""); probprop=property; } else{ JOptionPane.showMessageDialog(BioSim.frame, "Invalid probability value", "Error in Property", JOptionPane.ERROR_MESSAGE); } } else if(property.startsWith("=") && property.contains("?")){ property=property.substring(3); property=property.replace("}", ""); probprop=property; } } else { // hsf return ""; } return probprop; } // getProbpropParts extracts the expressions before and after the PU (after PG and PF) // and time bound from the probprop // Currently, we assume no nested until property public static String[] getProbpropParts(String probprop){ String symbol = "@"; String[] probpropParts; probpropParts = new String[4]; boolean PUFlag = probprop.contains("PU"); boolean PFFlag = probprop.contains("PF"); boolean PGFlag = probprop.contains("PG"); String probpropRight=""; String probpropLeft=""; String timeBound=""; String upperBound=""; String lowerBound=""; if (!probprop.equals("")){ // property should be in this format at this stage: probprop // obtain the hsf AFTER bound probpropRight= probprop.substring(probprop.indexOf("]")+1, probprop.length()); // obtain the time bound timeBound= probprop.substring(probprop.indexOf("["), probprop.indexOf("]")+1); // bound: [<= upper] if(timeBound.contains("<=")){ // upper bound upperBound = timeBound.substring(timeBound.indexOf("<")+2, timeBound.indexOf("]")); if(PUFlag){ probprop = probprop.replace("PU",symbol); // obtain the logic BEFORE the temporal operator probpropLeft= probprop.substring(0, probprop.indexOf(symbol)); // if probpropLeft has a pair of outermost parentheses, remove them if (probpropLeft.startsWith("(") & probpropLeft.endsWith(")")){ probpropLeft=probprop.substring(1,probpropLeft.length()-1); } } if(PFFlag){ probprop = probprop.replace("PF",symbol); // Remove the outermost parentheses if (probprop.startsWith("(") & probpropLeft.endsWith(")")){ probprop=probprop.substring(1,probpropLeft.length()-1); } } if(PGFlag){ probprop = probprop.replace("PGs",symbol); // Remove the outermost parentheses if (probprop.startsWith("(") & probpropLeft.endsWith(")")){ probprop=probprop.substring(1,probpropLeft.length()-1); } } } // bound: [lower, upper] else if (timeBound.contains(",")){ // lower bound lowerBound = timeBound.substring(timeBound.indexOf("[")+1, timeBound.indexOf(",")); // upper bound upperBound = timeBound.substring(timeBound.indexOf(",")+1, timeBound.indexOf("]")); if(PUFlag){ probprop = probprop.replace("PU",symbol); // obtain the logic BEFORE the temporal operator probpropLeft= probprop.substring(0, probprop.indexOf(symbol)); // if probpropLeft has a pair of outermost parentheses, remove them if (probpropLeft.startsWith("(") & probpropLeft.endsWith(")")){ probpropLeft=probprop.substring(1,probpropLeft.length()-1); } } } } else { // hsfFlag = true JOptionPane.showMessageDialog(BioSim.frame, "Property does not contain the until operator", "Warning in Property", JOptionPane.WARNING_MESSAGE); } probpropParts[0]=probpropLeft; probpropParts[1]=probpropRight; probpropParts[2]=lowerBound; probpropParts[3]=upperBound; return probpropParts; } public ExprTree String2ExprTree(LhpnFile lhpn, String str) { boolean retVal; ExprTree result = new ExprTree(lhpn); ExprTree expr = new ExprTree(lhpn); expr.token = expr.intexpr_gettok(str); retVal = expr.intexpr_L(str); if (retVal) { result = expr; } return result; } private static final String probabilityValue = "(0\\.[0-9]+)"; }
package org.ls.asynchelper; import java.util.Map; import java.util.Optional; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.ForkJoinTask; import java.util.function.Supplier; import java.util.stream.Stream; public enum AsyncHelper { INSTANCE; private ForkJoinPool forkJoinPool = ForkJoinPool.commonPool(); private Map<ObjectsKey, Supplier<? extends Object>> futureSuppliers = new ConcurrentHashMap<>(); private Map<ObjectsKey, ObjectsKey> originalKeys = new ConcurrentHashMap<>(); private Map<ObjectsKey, ObjectsKey> multipleAccessedKeys = new ConcurrentHashMap<>(); private Map<ObjectsKey, Object> multipleAccessedValues = new ConcurrentHashMap<>(); public ForkJoinPool getForkJoinPool() { return forkJoinPool; } public void setForkJoinPool(ForkJoinPool forkJoinPool) { assert (forkJoinPool != null); this.forkJoinPool = forkJoinPool; } public <T> Optional<T> asyncGet(Supplier<T> supplier) { ForkJoinTask<T> task = forkJoinPool.submit(() -> supplier.get()); return safeGet(task); } private <T> Optional<T> safeGet(ForkJoinTask<T> task) { try { return Optional.ofNullable(task.get()); } catch (InterruptedException | ExecutionException e) { return Optional.empty(); } } private <T> Supplier<T> safeSupplier(ForkJoinTask<T> task) { return () -> { try { return task.get(); } catch (InterruptedException | ExecutionException e) { } return null; }; } public <T> Supplier<T> submitSupplier(Supplier<T> supplier) { return safeSupplier(forkJoinPool.submit(() -> supplier.get())); } public <T> Supplier<T> submitCallable(Callable<T> callable) { return safeSupplier(forkJoinPool.submit(callable)); } public synchronized <T> Optional<T> submitAndGet(Callable<T> callable) { ForkJoinTask<T> task = forkJoinPool.submit(callable); return safeGet(task); } public void submitTask(Runnable runnable) { forkJoinPool.execute(runnable); } public void submitTasks(Runnable... runnables) { Stream.of(runnables).forEach(forkJoinPool::execute); } public <T> boolean submitSupplierForMultipleAccess(Supplier<T> supplier, Object... keys) { return doSubmitSupplier(supplier, true, keys); } public <T> boolean submitSupplierForSingleAccess(Supplier<T> supplier, Object... keys) { return doSubmitSupplier(supplier, false, keys); } private <T> boolean doSubmitSupplier(Supplier<T> supplier, boolean multipleAccess, Object... keys) { ObjectsKey key = ObjectsKey.of(keys); if (!futureSuppliers.containsKey(key)) { Supplier<T> safeSupplier = safeSupplier(forkJoinPool.submit(() -> supplier.get())); storeSupplier(key, safeSupplier, multipleAccess); return true; } return false; } private <T> void storeSupplier(ObjectsKey key, Supplier<T> safeSupplier, boolean multipleAccess) { futureSuppliers.put(key, safeSupplier); originalKeys.put(key, key); if (multipleAccess) { multipleAccessedKeys.put(key, key); } else { multipleAccessedKeys.remove(key); } if(multipleAccessedValues.containsKey(key)) { multipleAccessedValues.remove(key); } } public boolean submitTask(Runnable runnable, Object... keys) { ObjectsKey key = ObjectsKey.of(keys); if (!futureSuppliers.containsKey(key)) { Supplier<Void> safeSupplier = safeSupplier(forkJoinPool.submit(() -> { runnable.run(); return null; })); storeSupplier(key, safeSupplier, false); return true; } return false; } public <T> Optional<T> waitAndGet(Class<T> clazz, Object... keys) { ObjectsKey objectsKey = ObjectsKey.of(keys); if (originalKeys.containsKey(objectsKey)) { synchronized (originalKeys.get(objectsKey)) { if (multipleAccessedValues.containsKey(objectsKey)) { return getCastedValue(clazz, () -> multipleAccessedValues.get(objectsKey)); } if (futureSuppliers.containsKey(objectsKey)) { Optional<T> value = getCastedValue(clazz, () -> futureSuppliers.get(objectsKey).get()); futureSuppliers.remove(objectsKey); if (multipleAccessedKeys.containsKey(objectsKey)) { multipleAccessedValues.put(objectsKey, value.orElse(null)); } else { originalKeys.remove(objectsKey); } return value; } } } return Optional.empty(); } public <T> Optional<T> getCastedValue(Class<T> clazz, Supplier<? extends Object> supplier) { Object object = supplier.get(); if (clazz.isInstance(object)) { return Optional.of(clazz.cast(object)); } return Optional.empty(); } public void waitForTask(Object... keys) { ObjectsKey objectsKey = ObjectsKey.of(keys); if (originalKeys.containsKey(objectsKey)) { synchronized (originalKeys.get(objectsKey)) { if (multipleAccessedValues.containsKey(objectsKey)) { return; } if (futureSuppliers.containsKey(objectsKey)) { futureSuppliers.get(objectsKey).get(); futureSuppliers.remove(objectsKey); if (multipleAccessedKeys.containsKey(objectsKey)) { multipleAccessedValues.put(objectsKey, objectsKey); } else { originalKeys.remove(objectsKey); } } } } } public void waitForFlag(String... flag) throws InterruptedException { ObjectsKey key = ObjectsKey.of((Object[])flag); ObjectsKey originalKey = originalKeys.get(key); if(originalKey == null) { originalKey = key; originalKeys.put(key, originalKey); } synchronized (originalKey) { originalKey.wait(); } } public void notifyFlag(String... flag) { ObjectsKey key = ObjectsKey.of((Object[])flag); ObjectsKey originalKey = originalKeys.get(key); if(originalKey != null) { originalKeys.remove(key); synchronized (originalKey) { originalKey.notify(); } } } public void notifyAllFlag(String... flag) { ObjectsKey key = ObjectsKey.of((Object[])flag); ObjectsKey originalKey = originalKeys.get(key); if(originalKey != null) { originalKeys.remove(key); synchronized (originalKey) { originalKey.notifyAll(); } } } }
package org.opencms.setup.xml.v8; import org.opencms.configuration.CmsConfigurationManager; import org.opencms.configuration.CmsSearchConfiguration; import org.opencms.configuration.I_CmsXmlConfiguration; import org.opencms.search.CmsVfsIndexer; import org.opencms.search.fields.CmsSearchField; import org.opencms.search.fields.CmsSearchFieldConfiguration; import org.opencms.search.fields.CmsSearchFieldMapping; import org.opencms.search.galleries.CmsGallerySearchAnalyzer; import org.opencms.search.galleries.CmsGallerySearchFieldConfiguration; import org.opencms.search.galleries.CmsGallerySearchFieldMapping; import org.opencms.search.galleries.CmsGallerySearchIndex; import org.opencms.setup.xml.A_CmsXmlSearch; import org.opencms.setup.xml.CmsSetupXmlHelper; import org.opencms.setup.xml.CmsXmlUpdateAction; import java.io.StringReader; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.Node; import org.dom4j.io.SAXReader; /** * Adds the gallery search nodes.<p> * * @since 8.0.0 */ public class CmsXmlAddADESearch extends A_CmsXmlSearch { /** * Action to add the gallery modules index source.<p> */ public static class CmsAddGalleryModuleIndexSourceAction extends CmsXmlUpdateAction { /** * @see org.opencms.setup.xml.CmsXmlUpdateAction#executeUpdate(org.dom4j.Document, java.lang.String, boolean) */ @Override public boolean executeUpdate(Document doc, String xpath, boolean forReal) { Element node = (Element)doc.selectSingleNode("/opencms/search/indexsources"); if (!node.selectNodes("indexsource[name='gallery_modules_source']").isEmpty()) { return false; } String galleryModulesSource = " <indexsource>\n" + " <name>gallery_modules_source</name>\n" + " <indexer class=\"org.opencms.search.CmsVfsIndexer\" />\n" + " <resources>\n" + " <resource>/system/modules/</resource>\n" + " </resources>\n" + " <documenttypes-indexed>\n" + " <name>xmlcontent-galleries</name>\n" + " </documenttypes-indexed> \n" + " </indexsource> \n"; try { Element sourceElem = createElementFromXml(galleryModulesSource); node.add(sourceElem); return true; } catch (DocumentException e) { System.err.println("Failed to add gallery_modules_source"); return false; } } } /** * Action for updating the office document types in the index sources.<p> */ public static final class CmsIndexSourceTypeUpdateAction extends CmsXmlUpdateAction { /** * @see org.opencms.setup.xml.CmsXmlUpdateAction#executeUpdate(org.dom4j.Document, java.lang.String, boolean) */ @SuppressWarnings("unchecked") @Override public boolean executeUpdate(Document doc, String xpath, boolean forReal) { List<Node> nodes = doc.selectNodes("/opencms/search/indexsources/indexsource"); boolean result = false; for (Node node : nodes) { if (containsOldType(node)) { result = true; removeTypes(node); addNewTypes(node); } } return result; } /** * Adds new office document types.<p> * * @param node the node to add the document types to */ protected void addNewTypes(Node node) { Element element = (Element)(node.selectSingleNode("documenttypes-indexed")); for (String type : new String[] {"openoffice", "msoffice-ole2", "msoffice-ooxml"}) { element.addElement("name").addText(type); } } /** * Checks whether a node contains the old office document types.<p> * * @param node the node which should be checked * * @return true if the node contains old office document types */ protected boolean containsOldType(Node node) { @SuppressWarnings("unchecked") List<Node> nodes = node.selectNodes("documenttypes-indexed/name[text()='msword' or text()='msexcel' or text()='mspowerpoint']"); return !nodes.isEmpty(); } /** * Removes the office document types from a node.<p> * * @param node the node from which to remove the document types */ protected void removeTypes(Node node) { @SuppressWarnings("unchecked") List<Node> nodes = node.selectNodes("documenttypes-indexed/name[text()='msword' or text()='msexcel' or text()='mspowerpoint' or text()='msoffice-ooxml' or text()='openoffice' or text()='msoffice-ole2']"); for (Node nodeToRemove : nodes) { nodeToRemove.detach(); } } } /** * An XML update action which replaces an element given by an XPath with some other XML element. */ class ElementReplaceAction extends CmsXmlUpdateAction { /** * The XML which should be used as a replacement (as a string). */ private String m_replacementXml; /** * The xpath of the element to replace. */ private String m_xpath; /** * Creates a new instance.<p> * * @param xpath the xpath of the element to replace * @param replacementXml the replacement xml */ public ElementReplaceAction(String xpath, String replacementXml) { m_xpath = xpath; m_replacementXml = replacementXml; } /** * @see org.opencms.setup.xml.CmsXmlUpdateAction#executeUpdate(org.dom4j.Document, java.lang.String, boolean) */ @Override public boolean executeUpdate(Document doc, String xpath, boolean forReal) { if (!forReal) { return true; } Node node = doc.selectSingleNode(m_xpath); if (node != null) { Element parent = node.getParent(); node.detach(); try { Element element = createElementFromXml(m_replacementXml); parent.add(element); return true; } catch (DocumentException e) { e.printStackTrace(System.out); return false; } } else { return false; } } } /** A map from xpaths to XML update actions.<p> */ private Map<String, CmsXmlUpdateAction> m_actions; /** * Creates a dom4j element from an XML string.<p> * * @param xml the xml string * @return the dom4j element * * @throws DocumentException if the XML parsing fails */ public static org.dom4j.Element createElementFromXml(String xml) throws DocumentException { SAXReader reader = new SAXReader(); Document newNodeDocument = reader.read(new StringReader(xml)); return newNodeDocument.getRootElement(); } /** * @see org.opencms.setup.xml.I_CmsSetupXmlUpdate#getName() */ public String getName() { return "Add the ADE containerpage and gallery search nodes"; } /** * @see org.opencms.setup.xml.A_CmsSetupXmlUpdate#executeUpdate(org.dom4j.Document, java.lang.String, boolean) */ @Override protected boolean executeUpdate(Document document, String xpath, boolean forReal) { CmsXmlUpdateAction action = m_actions.get(xpath); if (action == null) { return false; } return action.executeUpdate(document, xpath, forReal); } /** * @see org.opencms.setup.xml.A_CmsSetupXmlUpdate#getCommonPath() */ @Override protected String getCommonPath() { // /opencms/search return new StringBuffer("/").append(CmsConfigurationManager.N_ROOT).append("/").append( CmsSearchConfiguration.N_SEARCH).toString(); } /** * @see org.opencms.setup.xml.A_CmsSetupXmlUpdate#getXPathsToUpdate() */ @Override protected List<String> getXPathsToUpdate() { if (m_actions == null) { initActions(); } return new ArrayList<String>(m_actions.keySet()); } /** * Builds the xpath for the documenttypes node.<p> * * @return the xpath for the documenttypes node */ private String buildXpathForDoctypes() { return getCommonPath() + "/" + CmsSearchConfiguration.N_DOCUMENTTYPES; } /** * Builds an xpath for a document type node in an index source.<p> * * @param source the name of the index source * @param doctype the document type * * @return the xpath */ private String buildXpathForIndexedDocumentType(String source, String doctype) { StringBuffer xp = new StringBuffer(256); xp.append(getCommonPath()); xp.append("/"); xp.append(CmsSearchConfiguration.N_INDEXSOURCES); xp.append("/"); xp.append(CmsSearchConfiguration.N_INDEXSOURCE); xp.append("["); xp.append(I_CmsXmlConfiguration.N_NAME); xp.append("='" + source + "']"); xp.append("/"); xp.append(CmsSearchConfiguration.N_DOCUMENTTYPES_INDEXED); xp.append("/"); xp.append(I_CmsXmlConfiguration.N_NAME); xp.append("[text()='" + doctype + "']"); return xp.toString(); } /** * Creates an action which adds an indexed type to an index source.<p> * * @param type the type which should be indexed * * @return the update action */ private CmsXmlUpdateAction createIndexedTypeAction(final String type) { return new CmsXmlUpdateAction() { @Override public boolean executeUpdate(Document doc, String xpath, boolean forReal) { Node node = doc.selectSingleNode(xpath); if (node != null) { return false; } CmsSetupXmlHelper.setValue(doc, xpath + "/text()", type); return true; } }; } /** * Initializes the map of XML update actions.<p> */ private void initActions() { m_actions = new LinkedHashMap<String, CmsXmlUpdateAction>(); StringBuffer xp; CmsXmlUpdateAction action0 = new CmsXmlUpdateAction() { @SuppressWarnings("unchecked") @Override public boolean executeUpdate(Document doc, String xpath, boolean forReal) { Node node = doc.selectSingleNode(xpath); org.dom4j.Element parent = node.getParent(); int position = parent.indexOf(node); parent.remove(node); try { parent.elements().add( position, createElementFromXml(" <documenttypes> \n" + " <documenttype>\n" + " <name>generic</name>\n" + " <class>org.opencms.search.documents.CmsDocumentGeneric</class>\n" + " <mimetypes/>\n" + " <resourcetypes>\n" + " <resourcetype>*</resourcetype>\n" + " </resourcetypes>\n" + " </documenttype> \n" + " <documenttype>\n" + " <name>html</name>\n" + " <class>org.opencms.search.documents.CmsDocumentHtml</class>\n" + " <mimetypes>\n" + " <mimetype>text/html</mimetype>\n" + " </mimetypes>\n" + " <resourcetypes>\n" + " <resourcetype>plain</resourcetype>\n" + " </resourcetypes>\n" + " </documenttype>\n" + " <documenttype>\n" + " <name>image</name>\n" + " <class>org.opencms.search.documents.CmsDocumentGeneric</class>\n" + " <mimetypes/>\n" + " <resourcetypes>\n" + " <resourcetype>image</resourcetype>\n" + " </resourcetypes>\n" + " </documenttype> \n" + " <documenttype>\n" + " <name>jsp</name>\n" + " <class>org.opencms.search.documents.CmsDocumentPlainText</class>\n" + " <mimetypes/>\n" + " <resourcetypes>\n" + " <resourcetype>jsp</resourcetype>\n" + " </resourcetypes>\n" + " </documenttype> \n" + " <documenttype>\n" + " <name>pdf</name>\n" + " <class>org.opencms.search.documents.CmsDocumentPdf</class>\n" + " <mimetypes>\n" + " <mimetype>application/pdf</mimetype>\n" + " </mimetypes>\n" + " <resourcetypes>\n" + " <resourcetype>binary</resourcetype>\n" + " <resourcetype>plain</resourcetype>\n" + " </resourcetypes>\n" + " </documenttype>\n" + " <documenttype>\n" + " <name>rtf</name>\n" + " <class>org.opencms.search.documents.CmsDocumentRtf</class>\n" + " <mimetypes>\n" + " <mimetype>text/rtf</mimetype>\n" + " <mimetype>application/rtf</mimetype>\n" + " </mimetypes>\n" + " <resourcetypes>\n" + " <resourcetype>binary</resourcetype>\n" + " <resourcetype>plain</resourcetype>\n" + " </resourcetypes>\n" + " </documenttype> \n" + " <documenttype>\n" + " <name>text</name>\n" + " <class>org.opencms.search.documents.CmsDocumentPlainText</class>\n" + " <mimetypes>\n" + " <mimetype>text/html</mimetype>\n" + " <mimetype>text/plain</mimetype>\n" + " </mimetypes>\n" + " <resourcetypes>\n" + " <resourcetype>plain</resourcetype>\n" + " </resourcetypes>\n" + " </documenttype> \n" + " <documenttype>\n" + " <name>xmlcontent</name>\n" + " <class>org.opencms.search.documents.CmsDocumentXmlContent</class>\n" + " <mimetypes/>\n" + " <resourcetypes>\n" + " <resourcetype>*</resourcetype>\n" + " </resourcetypes>\n" + " </documenttype>\n" + " <documenttype>\n" + " <name>containerpage</name>\n" + " <class>org.opencms.search.documents.CmsDocumentContainerPage</class>\n" + " <mimetypes>\n" + " <mimetype>text/html</mimetype>\n" + " </mimetypes>\n" + " <resourcetypes>\n" + " <resourcetype>containerpage</resourcetype>\n" + " </resourcetypes>\n" + " </documenttype> \n" + " <documenttype>\n" + " <name>xmlpage</name>\n" + " <class>org.opencms.search.documents.CmsDocumentXmlPage</class>\n" + " <mimetypes>\n" + " <mimetype>text/html</mimetype>\n" + " </mimetypes>\n" + " <resourcetypes>\n" + " <resourcetype>xmlpage</resourcetype>\n" + " </resourcetypes>\n" + " </documenttype>\n" + " <documenttype>\n" + " <name>xmlcontent-galleries</name>\n" + " <class>org.opencms.search.galleries.CmsGalleryDocumentXmlContent</class>\n" + " <mimetypes/>\n" + " <resourcetypes>\n" + " <resourcetype>xmlcontent-galleries</resourcetype>\n" + " </resourcetypes>\n" + " </documenttype> \n" + " <documenttype>\n" + " <name>xmlpage-galleries</name>\n" + " <class>org.opencms.search.galleries.CmsGalleryDocumentXmlPage</class>\n" + " <mimetypes />\n" + " <resourcetypes>\n" + " <resourcetype>xmlpage-galleries</resourcetype>\n" + " </resourcetypes>\n" + " </documenttype> \n" + " <documenttype>\n" + " <name>msoffice-ole2</name>\n" + " <class>org.opencms.search.documents.CmsDocumentMsOfficeOLE2</class>\n" + " <mimetypes>\n" + " <mimetype>application/vnd.ms-powerpoint</mimetype>\n" + " <mimetype>application/msword</mimetype> \n" + " <mimetype>application/vnd.ms-excel</mimetype>\n" + " </mimetypes>\n" + " <resourcetypes>\n" + " <resourcetype>binary</resourcetype>\n" + " <resourcetype>plain</resourcetype>\n" + " </resourcetypes>\n" + " </documenttype> \n" + " <documenttype>\n" + " <name>msoffice-ooxml</name>\n" + " <class>org.opencms.search.documents.CmsDocumentMsOfficeOOXML</class>\n" + " <mimetypes> \n" + " <mimetype>application/vnd.openxmlformats-officedocument.wordprocessingml.document</mimetype>\n" + " <mimetype>application/vnd.openxmlformats-officedocument.spreadsheetml.sheet</mimetype>\n" + " <mimetype>application/vnd.openxmlformats-officedocument.presentationml.presentation</mimetype>\n" + " </mimetypes>\n" + " <resourcetypes>\n" + " <resourcetype>binary</resourcetype>\n" + " <resourcetype>plain</resourcetype>\n" + " </resourcetypes>\n" + " </documenttype> \n" + " <documenttype>\n" + " <name>openoffice</name>\n" + " <class>org.opencms.search.documents.CmsDocumentOpenOffice</class>\n" + " <mimetypes>\n" + " <mimetype>application/vnd.oasis.opendocument.text</mimetype>\n" + " <mimetype>application/vnd.oasis.opendocument.spreadsheet</mimetype>\n" + " </mimetypes>\n" + " <resourcetypes>\n" + " <resourcetype>binary</resourcetype>\n" + " <resourcetype>plain</resourcetype>\n" + " </resourcetypes>\n" + " </documenttype>\n" + " </documenttypes>\n")); } catch (DocumentException e) { System.out.println("failed to update document types."); } return true; } }; m_actions.put(buildXpathForDoctypes(), action0); CmsXmlUpdateAction action1 = new CmsXmlUpdateAction() { @SuppressWarnings("synthetic-access") @Override public boolean executeUpdate(Document doc, String xpath, boolean forReal) { Node node = doc.selectSingleNode(xpath); if (node == null) { createAnalyzer(doc, xpath, CmsGallerySearchAnalyzer.class, "all"); return true; } return false; } }; xp = new StringBuffer(256); xp.append(getCommonPath()); xp.append("/"); xp.append(CmsSearchConfiguration.N_ANALYZERS); xp.append("/"); xp.append(CmsSearchConfiguration.N_ANALYZER); xp.append("["); xp.append(CmsSearchConfiguration.N_CLASS); xp.append("='").append(CmsGallerySearchAnalyzer.class.getName()).append("']"); m_actions.put(xp.toString(), action1); CmsXmlUpdateAction action2 = new CmsXmlUpdateAction() { @SuppressWarnings("synthetic-access") @Override public boolean executeUpdate(Document doc, String xpath, boolean forReal) { Node node = doc.selectSingleNode(xpath); if (node != null) { node.detach(); } createIndex( doc, xpath, CmsGallerySearchIndex.class, CmsGallerySearchIndex.GALLERY_INDEX_NAME, "offline", "Offline", "all", "gallery_fields", new String[] {"gallery_source", "gallery_modules_source"}); return true; } }; xp = new StringBuffer(256); xp.append(getCommonPath()); xp.append("/"); xp.append(CmsSearchConfiguration.N_INDEXES); xp.append("/"); xp.append(CmsSearchConfiguration.N_INDEX); xp.append("["); xp.append(I_CmsXmlConfiguration.N_NAME); xp.append("='").append(CmsGallerySearchIndex.GALLERY_INDEX_NAME).append("']"); m_actions.put(xp.toString(), action2); CmsXmlUpdateAction action3 = new CmsXmlUpdateAction() { @SuppressWarnings("synthetic-access") @Override public boolean executeUpdate(Document doc, String xpath, boolean forReal) { Node node = doc.selectSingleNode(xpath); if (node != null) { return false; } // create doc type createIndexSource(doc, xpath, "gallery_source", CmsVfsIndexer.class, new String[] { "/sites/", "/shared/"}, new String[] { "xmlpage-galleries", "xmlcontent-galleries", "jsp", "page", "text", "pdf", "rtf", "html", "image", "generic", "openoffice", "msoffice-ole2", "msoffice-ooxml"}); return true; } }; xp = new StringBuffer(256); xp.append(getCommonPath()); xp.append("/"); xp.append(CmsSearchConfiguration.N_INDEXSOURCES); xp.append("/"); xp.append(CmsSearchConfiguration.N_INDEXSOURCE); xp.append("["); xp.append(I_CmsXmlConfiguration.N_NAME); xp.append("='gallery_source']"); m_actions.put(xp.toString(), action3); CmsXmlUpdateAction action4 = new CmsXmlUpdateAction() { @Override public boolean executeUpdate(Document document, String xpath, boolean forReal) { Node node = document.selectSingleNode(xpath); if (node != null) { node.detach(); } // create field config CmsSearchFieldConfiguration fieldConf = new CmsSearchFieldConfiguration(); fieldConf.setName("gallery_fields"); fieldConf.setDescription("The standard OpenCms search index field configuration."); CmsSearchField field = new CmsSearchField(); // <field name="content" store="compress" index="true" excerpt="true"> field.setName("content"); field.setStored("compress"); field.setIndexed("true"); field.setInExcerpt("true"); field.setDisplayNameForConfiguration("%(key.field.content)"); // <mapping type="content" /> CmsSearchFieldMapping mapping = new CmsSearchFieldMapping(); mapping.setType("content"); field.addMapping(mapping); fieldConf.addField(field); // <field name="title-key" store="true" index="untokenized" boost="0.0"> field = new CmsSearchField(); field.setName("title-key"); field.setStored("true"); field.setIndexed("untokenized"); field.setBoost("0.0"); // <mapping type="property">Title</mapping> mapping = new CmsSearchFieldMapping(); mapping.setType("property"); mapping.setParam("Title"); field.addMapping(mapping); fieldConf.addField(field); // <field name="title" store="false" index="true"> field = new CmsSearchField(); field.setName("title"); field.setStored("false"); field.setIndexed("true"); field.setDisplayNameForConfiguration("%(key.field.title)"); // <mapping type="property">Title</mapping> mapping = new CmsSearchFieldMapping(); mapping.setType("property"); mapping.setParam("Title"); field.addMapping(mapping); fieldConf.addField(field); // <field name="description" store="true" index="true"> field = new CmsSearchField(); field.setName("description"); field.setStored("true"); field.setIndexed("true"); field.setDisplayNameForConfiguration("%(key.field.description)"); // <mapping type="property">Description</mapping> mapping = new CmsSearchFieldMapping(); mapping.setType("property"); mapping.setParam("Description"); field.addMapping(mapping); fieldConf.addField(field); // <field name="meta" store="false" index="true"> field = new CmsSearchField(); field.setName("meta"); field.setStored("false"); field.setIndexed("true"); // <mapping type="property">Title</mapping> mapping = new CmsSearchFieldMapping(); mapping.setType("property"); mapping.setParam("Title"); field.addMapping(mapping); // <mapping type="property">Description</mapping> mapping = new CmsSearchFieldMapping(); mapping.setType("property"); mapping.setParam("Description"); field.addMapping(mapping); fieldConf.addField(field); // <field name="res_dateExpired" store="true" index="untokenized"> field = new CmsSearchField(); field.setName("res_dateExpired"); field.setStored("true"); field.setIndexed("untokenized"); // <mapping type="attribute">dateExpired</mapping> mapping = new CmsSearchFieldMapping(); mapping.setType("attribute"); mapping.setParam("dateExpired"); field.addMapping(mapping); fieldConf.addField(field); // <field name="res_dateReleased" store="true" index="untokenized"> field = new CmsSearchField(); field.setName("res_dateReleased"); field.setStored("true"); field.setIndexed("untokenized"); // <mapping type="attribute">dateReleased</mapping> mapping = new CmsSearchFieldMapping(); mapping.setType("attribute"); mapping.setParam("dateReleased"); field.addMapping(mapping); fieldConf.addField(field); // <field name="res_length" store="true" index="untokenized"> field = new CmsSearchField(); field.setName("res_length"); field.setStored("true"); field.setIndexed("untokenized"); // <mapping type="attribute">length</mapping> mapping = new CmsSearchFieldMapping(); mapping.setType("attribute"); mapping.setParam("length"); field.addMapping(mapping); fieldConf.addField(field); // <field name="res_state" store="true" index="untokenized"> field = new CmsSearchField(); field.setName("res_state"); field.setStored("true"); field.setIndexed("untokenized"); // <mapping type="attribute">state</mapping> mapping = new CmsSearchFieldMapping(); mapping.setType("attribute"); mapping.setParam("state"); field.addMapping(mapping); fieldConf.addField(field); // <field name="res_structureId" store="true" index="false"> field = new CmsSearchField(); field.setName("res_structureId"); field.setStored("true"); field.setIndexed("untokenized"); // <mapping type="attribute">structureId</mapping> mapping = new CmsSearchFieldMapping(); mapping.setType("attribute"); mapping.setParam("structureId"); field.addMapping(mapping); fieldConf.addField(field); // <field name="res_userCreated" store="true" index="untokenized"> field = new CmsSearchField(); field.setName("res_userCreated"); field.setStored("true"); field.setIndexed("untokenized"); // <mapping type="attribute">userCreated</mapping> mapping = new CmsSearchFieldMapping(); mapping.setType("attribute"); mapping.setParam("userCreated"); field.addMapping(mapping); fieldConf.addField(field); // <field name="res_userLastModified" store="true" index="untokenized"> field = new CmsSearchField(); field.setName("res_userLastModified"); field.setStored("true"); field.setIndexed("untokenized"); // <mapping type="attribute">userLastModified</mapping> mapping = new CmsSearchFieldMapping(); mapping.setType("attribute"); mapping.setParam("userLastModified"); field.addMapping(mapping); fieldConf.addField(field); // <field name="res_locales" store="true" index="true" analyzer="WhitespaceAnalyzer"> field = new CmsSearchField(); field.setName("res_locales"); field.setStored("true"); field.setIndexed("true"); try { field.setAnalyzer("WhitespaceAnalyzer"); } catch (Exception e) { // ignore e.printStackTrace(); } // <mapping type="dynamic" class="org.opencms.search.galleries.CmsGallerySearchFieldMapping">res_locales</mapping> mapping = new CmsGallerySearchFieldMapping(); mapping.setType("dynamic"); mapping.setParam("res_locales"); field.addMapping(mapping); fieldConf.addField(field); // <field name="additional_info" store="true" index="false"> field = new CmsSearchField(); field.setName("additional_info"); field.setStored("true"); field.setIndexed("false"); // <mapping type="dynamic" class="org.opencms.search.galleries.CmsGallerySearchFieldMapping">additional_info</mapping> mapping = new CmsGallerySearchFieldMapping(); mapping.setType("dynamic"); mapping.setParam("additional_info"); field.addMapping(mapping); fieldConf.addField(field); // <field name="container_types" store="true" index="true" analyzer="WhitespaceAnalyzer"> field = new CmsSearchField(); field.setName("container_types"); field.setStored("true"); field.setIndexed("true"); try { field.setAnalyzer("WhitespaceAnalyzer"); } catch (Exception e) { // ignore e.printStackTrace(); } // <mapping type="dynamic" class="org.opencms.search.galleries.CmsGallerySearchFieldMapping">container_types</mapping> mapping = new CmsGallerySearchFieldMapping(); mapping.setType("dynamic"); mapping.setParam("container_types"); field.addMapping(mapping); fieldConf.addField(field); createFieldConfig(document, xpath, fieldConf, CmsGallerySearchFieldConfiguration.class); return true; } }; xp = new StringBuffer(256); xp.append(getCommonPath()); xp.append("/"); xp.append(CmsSearchConfiguration.N_FIELDCONFIGURATIONS); xp.append("/"); xp.append(CmsSearchConfiguration.N_FIELDCONFIGURATION); xp.append("["); xp.append(I_CmsXmlConfiguration.N_NAME); xp.append("='gallery_fields']"); m_actions.put(xp.toString(), action4); m_actions.put("/opencms/search/indexsources", new CmsIndexSourceTypeUpdateAction()); // use dummy check [1=1] to make the xpaths unique m_actions.put("/opencms/search/indexsources[1=1]", new CmsAddGalleryModuleIndexSourceAction()); m_actions.put( buildXpathForIndexedDocumentType("source1", "containerpage"), createIndexedTypeAction("containerpage")); String analyzerEnPath = "/opencms/search/analyzers/analyzer[class='org.apache.lucene.analysis.standard.StandardAnalyzer'][locale='en']"; m_actions.put(analyzerEnPath, new ElementReplaceAction(analyzerEnPath, "<analyzer>\n" + " <class>org.apache.lucene.analysis.en.EnglishAnalyzer</class>\n" + " <locale>en</locale>\n" + " </analyzer>")); String analyzerItPath = "/opencms/search/analyzers/analyzer[class='org.apache.lucene.analysis.snowball.SnowballAnalyzer'][stemmer='Italian']"; m_actions.put(analyzerItPath, new ElementReplaceAction(analyzerItPath, "<analyzer>\n" + " <class>org.apache.lucene.analysis.it.ItalianAnalyzer</class>\n" + " <locale>it</locale>\n" + " </analyzer>")); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ae3.service.structuredquery; import java.util.*; import uk.ac.ebi.ae3.indexbuilder.Efo; /** * * @author pashky */ public class EfoTree<PayLoad extends Comparable<PayLoad>> { private Efo efo; private Map<String,PayLoad> efos = new HashMap<String,PayLoad>(); private Set<String> marked = new HashSet<String>(); private Set<String> explicitEfos = new HashSet<String>(); private Set<String> autoChildren = new HashSet<String>(); public EfoTree(Efo efo) { this.efo = efo; } public PayLoad get(String id) { return efos.get(id); } public void add(String id, EfoEfvPayloadCreator<PayLoad> plCreator, boolean withChildren) { if(efos.containsKey(id) && explicitEfos.contains(id)) return; Iterable<String> parents = efo.getTermParents(id, true); if(parents == null) // it's not in EFO, don't add it return; explicitEfos.add(id); if (!efos.containsKey(id)) efos.put(id, plCreator.make()); if(withChildren) for(String c : efo.getTermAndAllChildrenIds(id)) { if (!c.equals(id) && !efos.containsKey(c)) efos.put(c, plCreator.make()); autoChildren.add(c); } } public int getNumEfos() { return efos.size(); } public int getNumExplicitEfos() { return explicitEfos.size(); } public Set<String> getEfoIds() { return efos.keySet(); } public Set<String> getExplicitEfos() { return explicitEfos; } public static class EfoItem<PayLoad extends Comparable<PayLoad>> { private String id; private String term; private int depth; private PayLoad payload; private boolean explicit; private EfoItem(String id, String term, int depth, PayLoad payload, boolean explicit) { this.id = id; this.term = term; this.depth = depth; this.payload = payload; this.explicit = explicit; } public int getDepth() { return depth; } public String getId() { return id; } public PayLoad getPayload() { return payload; } public String getTerm() { return term; } public boolean isExplicit() { return explicit; } } public List<EfoItem<PayLoad>> getSubTreeList() { List<EfoItem<PayLoad>> result = new ArrayList<EfoItem<PayLoad>>(); for (Efo.Term t : efo.getSubTree(efos.keySet())) { result.add(new EfoItem<PayLoad>(t.getId(), t.getTerm(), t.getDepth(), efos.get(t.getId()), explicitEfos.contains(t.getId()))); } return result; } public List<EfoItem<PayLoad>> getMarkedSubTreeList() { List<EfoItem<PayLoad>> result = new ArrayList<EfoItem<PayLoad>>(); for (Efo.Term t : efo.getSubTree(marked)) { result.add(new EfoItem<PayLoad>(t.getId(), t.getTerm(), t.getDepth(), efos.get(t.getId()), explicitEfos.contains(t.getId()))); } return result; } public List<EfoItem<PayLoad>> getValueOrderedList() { List<EfoItem<PayLoad>> result = new ArrayList<EfoItem<PayLoad>>(); List<String> ids = new ArrayList<String>(efos.keySet()); Collections.sort(ids, new Comparator<String>() { public int compare(String o1, String o2) { return efos.get(o1).compareTo(efos.get(o2)); } }); for (String id : ids) { Efo.Term t = efo.getTermById(id); result.add(new EfoItem<PayLoad>(t.getId(), t.getTerm(), t.getDepth(), efos.get(t.getId()), explicitEfos.contains(t.getId()))); } return result; } public List<EfoItem<PayLoad>> getExplicitList() { List<EfoItem<PayLoad>> result = new ArrayList<EfoItem<PayLoad>>(); for (String id : explicitEfos) { Efo.Term t = efo.getTermById(id); result.add(new EfoItem<PayLoad>(t.getId(), t.getTerm(), t.getDepth(), efos.get(t.getId()), explicitEfos.contains(t.getId()))); } return result; } @Override public String toString() { StringBuilder sb = new StringBuilder(); for(EfoItem<PayLoad> i : getExplicitList()) { if(sb.length() > 0) sb.append(", "); sb.append(i.getId()).append("(").append(i.getTerm()).append(")=").append(i.getPayload()); } return sb.toString(); } public void mark(String id) { if(marked.contains(id)) return; if(explicitEfos.contains(id)) { marked.add(id); } else if(autoChildren.contains(id)) { marked.add(id); } } }
package org.mvel.tests.perftests; import ognl.Ognl; import org.mvel.MVEL; import org.mvel.tests.main.res.Base; import static java.lang.System.currentTimeMillis; import java.math.BigDecimal; import java.math.RoundingMode; /** * Performance Tests Comparing MVEL to OGNL with Same Expressions. */ public class ELComparisons { private Base baseClass = new Base(); private static int mvel = 1; private static int ognl = 1 << 1; private static int ALL = mvel + ognl; private static final int TESTNUM = 50000; private static final int TESTITER = 5; public ELComparisons() { } public static void main(String[] args) throws Exception { ELComparisons omc = new ELComparisons(); if (args.length > 0 && args[0].equals("-continuous")) { while (true) omc.runTests(); } omc.runTests(); } public void runTests() throws Exception { runTest("Simple String Pass-Through", "'Hello World'", TESTNUM, ALL); runTest("Shallow Property", "data", TESTNUM, ALL); runTest("Deep Property", "foo.bar.name", TESTNUM, ALL); runTest("Static Field Access (MVEL)", "Integer.MAX_VALUE", TESTNUM, mvel); runTest("Static Field Access (OGNL)", "@java.lang.Integer@MAX_VALUE", TESTNUM, ognl); runTest("Inline Array Creation (MVEL)", "{'foo', 'bar'}", TESTNUM, mvel); runTest("Inline Array Creation (OGNL)", "new String[] {'foo', 'bar'}", TESTNUM, ognl); runTest("Collection Access + Method Call", "funMap['foo'].happy()", TESTNUM, ALL); runTest("Boolean compare", "data == 'cat'", TESTNUM, ALL); runTest("Object instantiation", "new String('Hello')", TESTNUM, ALL); runTest("Method access", "readBack('this is a string')", TESTNUM, ALL); runTest("Arithmetic", "10 + 1 - 1", TESTNUM, ALL); } public void runTest(String name, String expression, int count, int totest) throws Exception { System.out.println("Test Name : " + name); System.out.println("Expression : " + expression); System.out.println("Iterations : " + count); System.out.println("Interpreted Results :"); long time; long mem; long total = 0; long[] res = new long[TESTITER]; if ((totest & ognl) != 0) { try { // unbenched warm-up for (int i = 0; i < count; i++) { Ognl.getValue(expression, baseClass); } System.gc(); time = currentTimeMillis(); mem = Runtime.getRuntime().freeMemory(); for (int reps = 0; reps < TESTITER; reps++) { for (int i = 0; i < count; i++) { Ognl.getValue(expression, baseClass); } if (reps == 0) res[0] = total += currentTimeMillis() - time; else res[reps] = (total * -1) + (total += currentTimeMillis() - time - total); } System.out.println("(OGNL) : " + new BigDecimal(((currentTimeMillis() - time))).divide(new BigDecimal(TESTITER), 2, RoundingMode.HALF_UP) + "ms avg. (mem delta: " + ((Runtime.getRuntime().freeMemory() - mem) / 1024) + "kb) " + resultsToString(res)); } catch (Exception e) { System.out.println("(OGNL) : <<COULD NOT EXECUTE>>"); } } total = 0; if ((totest & mvel) != 0) { try { for (int i = 0; i < count; i++) { MVEL.eval(expression, baseClass); } System.gc(); time = currentTimeMillis(); mem = Runtime.getRuntime().freeMemory(); for (int reps = 0; reps < TESTITER; reps++) { for (int i = 0; i < count; i++) { MVEL.eval(expression, baseClass); } if (reps == 0) res[0] = total += currentTimeMillis() - time; else res[reps] = (total * -1) + (total += currentTimeMillis() - time - total); } System.out.println("(MVEL) : " + new BigDecimal(((currentTimeMillis() - time))).divide(new BigDecimal(TESTITER), 2, RoundingMode.HALF_UP) + "ms avg. (mem delta: " + ((Runtime.getRuntime().freeMemory() - mem) / 1024) + "kb) " + resultsToString(res)); } catch (Exception e) { System.out.println("(MVEL) : <<COULD NOT EXECUTE>>"); } } // try { // for (int i = 0; i < count; i++) { // ReflectiveOptimizer.get(expression, baseClass); // System.gc(); // time = System.currentTimeMillis(); // mem = Runtime.getRuntime().freeMemory(); // for (int reps = 0; reps < 5; reps++) { // for (int i = 0; i < count; i++) { // ReflectiveOptimizer.get(expression, baseClass); // System.out.println("(MVELPropAcc) : " + new BigDecimal(((System.currentTimeMillis() - time))).divide(new BigDecimal(6), 2, RoundingMode.HALF_UP) // + "ms avg. (mem delta: " + ((Runtime.getRuntime().freeMemory() - mem) / 1024) + "kb)"); // catch (Exception e) { // System.out.println("(MVELPropAcc) : <<COULD NOT EXECUTE>>"); // try { // for (int i = 0; i < count; i++) { // PropertyResolver.getValue(expression, baseClass); // System.gc(); // time = System.currentTimeMillis(); // mem = Runtime.getRuntime().freeMemory(); // for (int reps = 0; reps < 5; reps++) { // for (int i = 0; i < count; i++) { // PropertyResolver.getValue(expression, baseClass); // System.out.println("(WicketPropRes) : " + new BigDecimal(((System.currentTimeMillis() - time))) // .divide(new BigDecimal(6), 2, RoundingMode.HALF_UP) // + "ms avg. (mem delta: " + ((Runtime.getRuntime().freeMemory() - mem) / 1024) + "kb)"); // catch (Exception e) { // System.out.println("(WicketPropRes) : <<COULD NOT EXECUTE>>"); runTestCompiled(name, expression, count, totest); System.out.println(" } public void runTestCompiled(String name, String expression, int count, int totest) throws Exception { Object compiled; long time; long mem; long total = 0; long[] res = new long[TESTITER]; System.out.println("Compiled Results :"); if ((totest & ognl) != 0) { try { compiled = Ognl.parseExpression(expression); for (int i = 0; i < count; i++) { Ognl.getValue(compiled, baseClass); } System.gc(); time = currentTimeMillis(); mem = Runtime.getRuntime().freeMemory(); for (int reps = 0; reps < TESTITER; reps++) { for (int i = 0; i < count; i++) { Ognl.getValue(compiled, baseClass); } if (reps == 0) res[0] = total += currentTimeMillis() - time; else res[reps] = (total * -1) + (total += currentTimeMillis() - time - total); } System.out.println("(OGNL Compiled) : " + new BigDecimal(currentTimeMillis() - time).divide(new BigDecimal(TESTITER), 2, RoundingMode.HALF_UP) + "ms avg. (mem delta: " + ((Runtime.getRuntime().freeMemory() - mem) / 1024) + "kb) " + resultsToString(res)); } catch (Exception e) { System.out.println("(OGNL) : <<COULD NOT EXECUTE>>"); } } total = 0; if ((totest & mvel) != 0) { try { compiled = MVEL.compileExpression(expression); for (int i = 0; i < count; i++) { MVEL.executeExpression(compiled, baseClass); } System.gc(); time = currentTimeMillis(); mem = Runtime.getRuntime().freeMemory(); for (int reps = 0; reps < TESTITER; reps++) { for (int i = 0; i < count; i++) { MVEL.executeExpression(compiled, baseClass); } if (reps == 0) res[0] = total += currentTimeMillis() - time; else res[reps] = (total * -1) + (total += currentTimeMillis() - time - total); } System.out.println("(MVEL Compiled) : " + new BigDecimal(currentTimeMillis() - time).divide(new BigDecimal(TESTITER), 2, RoundingMode.HALF_UP) + "ms avg. (mem delta: " + ((Runtime.getRuntime().freeMemory() - mem) / 1024) + "kb) " + resultsToString(res)); } catch (Exception e) { System.out.println("(MVEL) : <<COULD NOT EXECUTE>>"); } } } private static String resultsToString(long[] res) { StringBuffer sbuf = new StringBuffer("["); for (int i = 0; i < res.length; i++) { sbuf.append(res[i]); if ((i + 1) < res.length) sbuf.append(","); } sbuf.append("]"); return sbuf.toString(); } }
package edu.colorado.csdms.wmt.client.ui; import com.google.gwt.core.shared.GWT; import com.google.gwt.dom.client.Style.Unit; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.FlexTable; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.HasHorizontalAlignment; import edu.colorado.csdms.wmt.client.control.DataManager; import edu.colorado.csdms.wmt.client.data.ParameterJSO; import edu.colorado.csdms.wmt.client.ui.cell.DescriptionCell; import edu.colorado.csdms.wmt.client.ui.cell.ValueCell; import edu.colorado.csdms.wmt.client.ui.panel.ParameterActionPanel; /** * Builds a table of parameters for a single WMT model component. The value of * the parameter is editable. * * @author Mark Piper (mark.piper@colorado.edu) */ public class ParameterTable extends FlexTable { public DataManager data; private String componentId; // the id of the displayed component private ParameterActionPanel actionPanel; private Integer tableRowIndex; // where we are in table /** * Initializes a table of parameters for a single WMT model component. The * table is empty until {@link #loadTable()} is called. * * @param data the DataManager instance for the WMT session */ public ParameterTable(DataManager data) { this.data = data; this.tableRowIndex = 0; this.setWidth("100%"); } /** * A worker that displays an informational message in the ParameterTable. */ @Deprecated public void showInfoMessage() { HTML infoMessage = new HTML("Select a model component to view and edit its parameters"); infoMessage.setStyleName("wmt-ParameterTableMessage"); this.setWidget(0, 0, infoMessage); } /** * A worker that loads the ParameterTable with parameter values for the * selected model component. Displays a {@link ViewInputFilesPanel} at the * bottom of the table. * * @param the id of the component whose parameters are to be displayed */ public void loadTable(String componentId) { // The component whose parameters are to be displayed. this.setComponentId(componentId); // Return if the selected component doesn't have parameters. if (data.getModelComponent(componentId).getParameters() == null) { this.clearTable(); Window.alert("No parameters defined for this component."); return; } // Set the component name on the tab holding the ParameterTable. data.getPerspective().setParameterPanelTitle(componentId); // Add the ParameterActionPanel and align it with the ModelActionPanel. addActionPanel(); // Build the parameter table. Integer nParameters = data.getModelComponent(componentId).getParameters().length(); for (int i = 0; i < nParameters; i++) { ParameterJSO parameter = data.getModelComponent(componentId).getParameters().get(i); addTableEntry(parameter); } } /** * Adds the {@link ParameterActionPanel} to the top of the * {@link ParameterTable}. */ private void addActionPanel() { actionPanel = new ParameterActionPanel(data, componentId); actionPanel.getElement().getStyle().setMarginTop(-3.0, Unit.PX); this.setWidget(tableRowIndex, 0, actionPanel); tableRowIndex++; } /** * Adds an entry into the {@link ParameterTable}. * * @param parameter the ParameterJSO object for the parameter */ private void addTableEntry(ParameterJSO parameter) { if (!parameter.isVisible()) { return; } this.setWidget(tableRowIndex, 0, new DescriptionCell(parameter)); if (parameter.getKey().matches("separator")) { this.getFlexCellFormatter().setColSpan(tableRowIndex, 0, 2); this.getFlexCellFormatter().setStyleName(tableRowIndex, 0, "wmt-ParameterSeparator"); } else { this.setWidget(tableRowIndex, 1, new ValueCell(parameter)); this.getFlexCellFormatter().setStyleName(tableRowIndex, 0, "wmt-ParameterDescription"); this.getFlexCellFormatter().setHorizontalAlignment(tableRowIndex, 1, HasHorizontalAlignment.ALIGN_RIGHT); } tableRowIndex++; } /** * Stores the modified value of a parameter of a model component in the WMT * {@link DataManager}. * * @param parameter the ParameterJSO object for the parameter being modified * @param newValue the new parameter value, a String */ public void setValue(ParameterJSO parameter, String newValue) { String key = parameter.getKey(); String previousValue = data.getModelComponent(componentId).getParameter(key).getValue() .getDefault(); GWT.log(componentId + ": " + key + ": " + newValue); // Don't update state when tabbing between fields or moving within field. // XXX Would be better to handle this further upstream. if (!newValue.matches(previousValue)) { data.getModelComponent(componentId).getParameter(key).getValue() .setDefault(newValue); data.updateModelSaveState(false); } } /** * Deletes the contents of the ParameterTable and resets the tab title to * "Parameters". */ public void clearTable() { this.setComponentId(null); data.getPerspective().setParameterPanelTitle(null); this.tableRowIndex = 0; this.removeAllRows(); this.clear(true); } /** * Returns the id of the model component (a String) whose parameters are * displayed in the ParameterTable. */ public String getComponentId() { return componentId; } /** * Stores the id of the model component (a String) whose parameters are * displayed in the ParameterTable. * * @param componentId a component id, a String */ public void setComponentId(String componentId) { this.componentId = componentId; } }
package lhpn2sbml.parser; import org.sbml.libsbml.Compartment; import org.sbml.libsbml.Delay; import org.sbml.libsbml.Event; import org.sbml.libsbml.EventAssignment; import org.sbml.libsbml.FunctionDefinition; import org.sbml.libsbml.KineticLaw; import org.sbml.libsbml.Model; import org.sbml.libsbml.Parameter; import org.sbml.libsbml.RateRule; import org.sbml.libsbml.Reaction; import org.sbml.libsbml.SBMLDocument; import org.sbml.libsbml.SBMLWriter; import org.sbml.libsbml.Species; import org.sbml.libsbml.SpeciesReference; import org.sbml.libsbml.Trigger; import org.sbml.libsbml.libsbml; import sbmleditor.SBML_Editor; import lhpn2sbml.parser.ExprTree; import biomodelsim.BioSim; /** * This class converts a lph file to a sbml file * * @author Zhen Zhang * */ public class Translator { private String filename; private SBMLDocument document; public void BuildTemplate(String lhpnFilename) { this.filename = lhpnFilename.replace(".lpn", ".xml"); // load lhpn file LHPNFile lhpn = new LHPNFile(); lhpn.load(lhpnFilename); // create sbml file document = new SBMLDocument(BioSim.SBML_LEVEL, BioSim.SBML_VERSION); Model m = document.createModel(); Compartment c = m.createCompartment(); m.setId(filename.replace(".xml", "")); c.setId("default"); c.setSize(1.0); c.setConstant(true); c.setSpatialDimensions(3); // Create bitwise operators for sbml createFunction(m, "BITAND", "Bitwise AND", "lambda(a,b,a*b)"); createFunction(m, "BITOR", "Bitwise AND", "lambda(a,b,a*b)"); createFunction(m, "BITNOT", "Bitwise AND", "lambda(a,b,a*b)"); createFunction(m, "BITXOR", "Bitwise AND", "lambda(a,b,a*b)"); createFunction(m, "mod", "Modular", "lambda(a,b,a-floor(a/b)*b)"); createFunction(m, "and", "Logical AND", "lambda(a,b,a*b)"); createFunction(m, "uniform", "Uniform distribution", "lambda(a,b,(a+b)/2)"); createFunction(m, "normal", "Normal distribution", "lambda(m,s,m)"); createFunction(m, "exponential", "Exponential distribution", "lambda(mu,mu)"); createFunction(m, "gamma", "Gamma distribution", "lambda(a,b,a*b)"); createFunction(m, "lognormal", "Lognormal distribution", "lambda(z,s,exp(z+s^2/2))"); createFunction(m, "chisq", "Chi-squared distribution", "lambda(nu,nu)"); createFunction(m, "laplace", "Laplace distribution", "lambda(a,a)"); createFunction(m, "cauchy", "Cauchy distribution", "lambda(a,a)"); createFunction(m, "rayleigh", "Rayleigh distribution", "lambda(s,s*sqrt(pi/2))"); createFunction(m, "poisson", "Poisson distribution", "lambda(mu,mu)"); createFunction(m, "binomial", "Binomial distribution", "lambda(p,n,p*n)"); createFunction(m, "bernoulli", "Bernoulli distribution", "lambda(p,p)"); // translate from lhpn to sbml for (String v: lhpn.getAllVariables()){ if (v != null){ String initVal = lhpn.getInitialVal(v); System.out.println("Begin:" + v + "= " + initVal); if (lhpn.isContinuous(v)){ Parameter p = m.createParameter(); p.setConstant(false); p.setId(v); Parameter p_dot = m.createParameter(); p_dot.setConstant(false); p_dot.setId(v + "_dot"); // System.out.println("v_dot = " + v + "_dot"); RateRule rateRule = m.createRateRule(); rateRule.setVariable(v); rateRule.setMath(SBML_Editor.myParseFormula(v + "_dot")); // boolean error = checkRateRuleUnits(rateRule); String initValue = lhpn.getInitialVal(v); String initValDot= lhpn.getInitialRate(v); //System.out.println("initValue = " + initValue); //System.out.println("initValDot = " + initValDot); //System.out.println(v + "=" + initValue); double initVal_dbl = Double.parseDouble(initValue); p.setValue(initVal_dbl); double initValDot_dbl = Double.parseDouble(initValDot); p_dot.setValue(initValDot_dbl); } else { Parameter p = m.createParameter(); p.setConstant(false); p.setId(v); String initValue = lhpn.getInitialVal(v); System.out.println(v + "=" + initValue); // check initValue type; if boolean, set parameter value as 0 or 1. if (initValue.equals("true")){ p.setValue(1); } else if (initValue.equals("false")){ p.setValue(0); } else if(initValue.contains("inf")) { p.setValue(0); } else if (initValue.equals("unknown")){ p.setValue(0); } else { double initVal_dbl = Double.parseDouble(initValue); p.setValue(initVal_dbl); // System.out.println(Double.parseDouble("3")); } } } } for (String p: lhpn.getPlaceList()){ Boolean initMarking = lhpn.getPlaceInitial(p); // System.out.println(p + "=" + initMarking); Species sp = m.createSpecies(); sp.setId(p); sp.setCompartment("default"); sp.setBoundaryCondition(false); sp.setConstant(false); sp.setHasOnlySubstanceUnits(false); if (initMarking){ sp.setInitialAmount(1); } else { sp.setInitialAmount(0); } sp.setUnits(""); } // if transition rate is not null, use reaction and event; // else use event only int counter = lhpn.getTransitionList().length - 1; for (String t : lhpn.getTransitionList()) { if(lhpn.getTransitionRate(t)!=null){ Species spT = m.createSpecies(); spT.setId(t); spT.setCompartment("default"); spT.setBoundaryCondition(false); spT.setConstant(false); spT.setHasOnlySubstanceUnits(false); spT.setInitialAmount(0); spT.setUnits(""); Reaction r = m.createReaction(); r.setReversible(false); r.setId("r" + counter); SpeciesReference reactant = r.createReactant(); // get preset(s) of a transition and set each as a reactant for (String x : lhpn.getPreset(t)){ reactant.setId(x); reactant.setSpecies(x); //System.out.println("transition:" + t + "preset:" + x); } SpeciesReference product = r.createProduct(); product.setSpecies(t); KineticLaw rateReaction = r.createKineticLaw(); // rate of reaction //Parameter p_local = rateReaction.createParameter(); //p_local.setConstant(false); //p_local.setId("rate" + counter); // get the transition rate from LHPN //System.out.println("transition rate = " + lhpn.getTransitionRate(t)); //double tRate = Double.parseDouble(lhpn.getTransitionRate(t)); //p_local.setValue(tRate); //lhpn.getTransitionRateTree(t) // create exp for KineticLaw // expTestNull is used to test if the enabling condition exists for a transistion t String expTestNull = lhpn.getEnabling(t); String exp; if (expTestNull == null){ exp = "1"; } else { String tmp_exp = lhpn.getEnablingTree(t).getElement("SBML"); // System.out.println("tmp_exp = "+ tmp_exp); exp = "piecewise(1," + tmp_exp + ",0)"; } rateReaction.setFormula("(" + lhpn.getTransitionRate(t) + ")" + "*" + reactant.getSpecies() + "*" + exp); //System.out.println("trans " + t + " enableCond " + lhpn.getEnabling(t)); Event e = m.createEvent(); e.setId("event" + counter); Trigger trigger = e.createTrigger(); trigger.setMath(SBML_Editor.myParseFormula("eq(" + product.getSpecies() + ",1)")); // t_postSet = 1 EventAssignment assign0 = e.createEventAssignment(); for (String x : lhpn.getPostset(t)){ assign0.setVariable(x); assign0.setMath(SBML_Editor.myParseFormula("1")); // System.out.println("transition: " + t + " postset: " + x); } // t = 0 EventAssignment assign1 = e.createEventAssignment(); assign1.setVariable(product.getSpecies()); assign1.setMath(SBML_Editor.myParseFormula("0")); // assignment <A> // TODO need to test the continuous assignment if (lhpn.getContAssignVars(t) != null){ for (String var : lhpn.getContAssignVars(t)){ if (lhpn.getContAssign(t, var) != null) { ExprTree[] assignContTree = lhpn.getContAssignTree(t, var); String assignCont = assignContTree[0].toString("SBML"); System.out.println("continuous assign: "+ assignCont); EventAssignment assign2 = e.createEventAssignment(); assign2.setVariable(var); assign2.setMath(SBML_Editor.myParseFormula(assignCont)); } } } // TODO need to test the integer assignment if (lhpn.getIntVars()!= null){ for (String var : lhpn.getIntVars()){ if (lhpn.getIntAssign(t, var) != null) { ExprTree[] assignIntTree = lhpn.getIntAssignTree(t, var); String assignInt = assignIntTree[0].toString("SBML"); System.out.println("integer assignment from LHPN: " + var + " := " + assignInt); EventAssignment assign3 = e.createEventAssignment(); assign3.setVariable(var); assign3.setMath(SBML_Editor.myParseFormula(assignInt)); } } } // boolean assignment if (lhpn.getBooleanVars(t)!= null){ for (String var :lhpn.getBooleanVars(t)){ if (lhpn.getBoolAssign(t, var) != null) { ExprTree[] assignBoolTree = lhpn.getBoolAssignTree(t, var); String assignBool_tmp = assignBoolTree[0].toString("SBML"); String assignBool = "piecewise(1," + assignBool_tmp + ",0)"; System.out.println("boolean assignment from LHPN: " + var + " := " + assignBool); EventAssignment assign4 = e.createEventAssignment(); assign4.setVariable(var); assign4.setMath(SBML_Editor.myParseFormula(assignBool)); } } } // rate assignment if (lhpn.getRateVars(t)!= null){ for (String var : lhpn.getRateVars(t)){ System.out.println("rate var: "+ var); if (lhpn.getRateAssign(t, var) != null) { ExprTree[] assignRateTree = lhpn.getRateAssignTree(t, var); String assignRate = assignRateTree[0].toString("SBML"); // System.out.println("rate assign: "+ assignRate); EventAssignment assign5 = e.createEventAssignment(); assign5.setVariable(var + "_dot"); assign5.setMath(SBML_Editor.myParseFormula(assignRate)); } } } } //Only use event else { //lhpn.getContAssign(t, var) == null System.out.println("Event Only"); Event e = m.createEvent(); e.setId("event" + counter); Trigger trigger = e.createTrigger(); //trigger = CheckPreset(t) && En(t); //test En(t) String EnablingTestNull = lhpn.getEnabling(t); String Enabling; if (EnablingTestNull == null){ Enabling = "eq(1,1)"; // Enabling is true (Boolean) } else { Enabling = lhpn.getEnablingTree(t).getElement("SBML"); } System.out.println("Enabling = " + Enabling); //test Preset(t) // TODO how to get the marking for preset ? lhpn.getPlaceInitial(preset)? String CheckPreset = null; int indexPreset = 0; for (String x:lhpn.getPreset(t)){ if (indexPreset == 0){ CheckPreset = "eq(" + x + ",1)"; } else { CheckPreset = "and(" + CheckPreset + "," + "eq(" + x + ",1)" + ")"; } } trigger.setMath(SBML_Editor.myParseFormula("and(gt(t,0)," + CheckPreset + "," + Enabling + ")")); //trigger.setMath(SBML_Editor.myParseFormula("and(eq(" + lhpn.getPreset(t) + ",1)," + Enabling + ")")); // trigger.setMath(SBML_Editor.myParseFormula("eq(" + lhpn.getPreset(t) + ",1)")); // trigger.setMath(SBML_Editor.myParseFormula("eq(1,1)")); // triggerCanBeDisabled := true trigger.setAnnotation("<TriggerCanBeDisabled/>"); // Delay D(t) Delay delay = e.createDelay(); delay.setMath(SBML_Editor.myParseFormula(lhpn.getDelay(t))); // t_preSet = 0 EventAssignment assign0 = e.createEventAssignment(); for (String x : lhpn.getPreset(t)){ assign0.setVariable(x); assign0.setMath(SBML_Editor.myParseFormula("0")); // System.out.println("transition: " + t + " preset: " + x); } // t_postSet = 1 EventAssignment assign1 = e.createEventAssignment(); for (String x : lhpn.getPostset(t)){ assign1.setVariable(x); assign1.setMath(SBML_Editor.myParseFormula("1")); // System.out.println("transition: " + t + " postset: " + x); } // assignment <A> // continuous assignment if (lhpn.getContAssignVars(t) != null){ for (String var : lhpn.getContAssignVars(t)){ if (lhpn.getContAssign(t, var) != null) { ExprTree[] assignContTree = lhpn.getContAssignTree(t, var); String assignCont = assignContTree[0].toString("SBML"); // System.out.println("continuous assign: "+ assignCont); EventAssignment assign2 = e.createEventAssignment(); assign2.setVariable(var); assign2.setMath(SBML_Editor.myParseFormula(assignCont)); } } } // integer assignment if (lhpn.getIntVars()!= null){ for (String var : lhpn.getIntVars()){ if (lhpn.getIntAssign(t, var) != null) { ExprTree[] assignIntTree = lhpn.getIntAssignTree(t, var); String assignInt = assignIntTree[0].toString("SBML"); //System.out.println("integer assignment from LHPN: " + var + " := " + assignInt); EventAssignment assign3 = e.createEventAssignment(); assign3.setVariable(var); assign3.setMath(SBML_Editor.myParseFormula(assignInt)); } } } // boolean assignment if (lhpn.getBooleanVars(t)!= null){ for (String var :lhpn.getBooleanVars(t)){ if (lhpn.getBoolAssign(t, var) != null) { ExprTree[] assignBoolTree = lhpn.getBoolAssignTree(t, var); String assignBool_tmp = assignBoolTree[0].toString("SBML"); String assignBool = "piecewise(1," + assignBool_tmp + ",0)"; //System.out.println("boolean assignment from LHPN: " + var + " := " + assignBool); EventAssignment assign4 = e.createEventAssignment(); assign4.setVariable(var); assign4.setMath(SBML_Editor.myParseFormula(assignBool)); } } } // rate assignment if (lhpn.getRateVars(t)!= null){ for (String var : lhpn.getRateVars(t)){ System.out.println("rate var: "+ var); if (lhpn.getRateAssign(t, var) != null) { ExprTree[] assignRateTree = lhpn.getRateAssignTree(t, var); String assignRate = assignRateTree[0].toString("SBML"); // System.out.println("rate assign: "+ assignRate); EventAssignment assign5 = e.createEventAssignment(); assign5.setVariable(var + "_dot"); assign5.setMath(SBML_Editor.myParseFormula(assignRate)); } } } } counter } //filename.replace(".lpn", ".xml"); SBMLWriter writer = new SBMLWriter(); writer.writeSBML(document, filename); } private void createFunction(Model model, String id, String name, String formula) { if (document.getModel().getFunctionDefinition(id) == null) { FunctionDefinition f = model.createFunctionDefinition(); f.setId(id); f.setName(name); f.setMath(libsbml.parseFormula(formula)); } } public void setFilename(String filename) { this.filename = filename; } public String getFilename() { return filename; } }
package com.demo.util; import android.os.Handler; import android.os.HandlerThread; import android.os.Message; import android.util.Log; import android.util.LogPrinter; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class RecordManager2 { private static final String TAG = "RecordManager2"; private static final int SENDTASK_MSG = 1; private static final int TIMEOUT_MSG = 2; private static Handler handler; private static long last; private static List<String> caches = Collections.synchronizedList(new ArrayList<String>()); public static void init(){ final HandlerThread handlerThread = new HandlerThread(TAG); handlerThread.start(); handler = new Handler(handlerThread.getLooper()){ @Override public void handleMessage(Message msg) { int what = msg.what; switch (what){ case SENDTASK_MSG: long time = System.currentTimeMillis(); if (System.currentTimeMillis() - last > 500){ last = time; List<String> temp = new ArrayList<>(caches); caches.removeAll(temp); handleTask("normal", temp); handler.dump(new LogPrinter(Log.ERROR, "handler dump"), "dump"); } /*String s = (String) msg.obj; caches.add(s);*/ break; case TIMEOUT_MSG: if (!caches.isEmpty()){ Log.e(Thread.currentThread().getName()+"", "timeout"); List<String> temp = new ArrayList<>(caches); caches.removeAll(temp); handleTask("timeout", temp); } break; default: throw new IllegalStateException("Unexpected value: " + what); } } }; } public static void record(String r){ Log.e(Thread.currentThread().getName()+"-", r); Message msg = Message.obtain(); msg.what = SENDTASK_MSG; // msg.obj = r; if(!handler.hasMessages(SENDTASK_MSG)){ handler.sendMessage(msg); } caches.add(r); if(!handler.hasMessages(TIMEOUT_MSG)){ Log.e(Thread.currentThread().getName()+"-", r); handler.sendMessageDelayed(handler.obtainMessage(TIMEOUT_MSG), 2000); } } private static void handleTask(String msg, List<String> list){ if (list.isEmpty()) return; Log.e(Thread.currentThread().getName()+"", msg); StringBuilder sb = new StringBuilder(); for (String s : list) { sb.append(s).append(","); } try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } Log.e(Thread.currentThread().getName()+"::"+msg, sb.toString()); list.clear(); list = null; } }
package com.qulice.xml; import com.jcabi.log.Logger; import com.jcabi.xml.StrictXML; import com.jcabi.xml.XML; import com.jcabi.xml.XMLDocument; import com.jcabi.xml.XSDDocument; import com.qulice.spi.Environment; import com.qulice.spi.ValidationException; import com.qulice.spi.Validator; import java.io.File; import java.io.IOException; import java.net.URI; import java.util.List; import org.apache.commons.lang3.StringUtils; /** * Validates XML files for formatting. * * @author Yegor Bugayenko (yegor@tpc2.com) * @version $Id$ */ @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops") public final class XmlValidator implements Validator { @Override public void validate(final Environment env) throws ValidationException { try { for (final File file : env.files("*.xml")) { final String name = file.getAbsolutePath().substring( env.basedir().toString().length() ); if (env.exclude("xml", name)) { Logger.info(this, "%s: skipped", name); continue; } Logger.info(this, "%s: to be validated", name); final XML document = new XMLDocument(file); final List<String> schemas = document .xpath("/*/@xsi:schemaLocation"); if (schemas.isEmpty()) { throw new ValidationException( String.format( "XML validation exception: missing schema in %s", name ) ); } else { new StrictXML( document, new XSDDocument( URI.create( StringUtils.substringAfter( schemas.get(0), " " ) ).toURL() ) ); } } } catch (final IOException ex) { throw new IllegalStateException(ex); } } }
package edu.ucla.cens.awserver.jee.servlet; import java.io.IOException; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.springframework.context.ApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; import edu.ucla.cens.awserver.controller.Controller; import edu.ucla.cens.awserver.controller.ControllerException; import edu.ucla.cens.awserver.datatransfer.AwRequest; import edu.ucla.cens.awserver.jee.servlet.glue.AwRequestCreator; import edu.ucla.cens.awserver.jee.servlet.glue.HttpSessionModifier; import edu.ucla.cens.awserver.util.StringUtils; /** * Dispatch and handle requests which ultimately result in a final re-dispatch to a JSP for rendering. * * This Servlet has four init-params that need to be defined in web.xml. The parameters define objects used by the service() * method when handling user requests. * * <ol> * <li><code>controllerName</code> -- The Spring Bean id of the Controller to use. * <li><code>httpToAwRequestTransformerName</code> -- The Spring Bean id of the HttpToAwRequestTransformer to use. * <li><code>awToHttpRequestTransformerName</code> -- The Spring Bean id of the AwToHttpRequestTransformer to use. * <li><code>userSuccessForwardUrl</code> -- A relative (to WEB-INF) file URL to a JSP that will render the results of a successful * request. * <li><code>userErrorForwardUrl</code> -- A relative (to WEB-INF) file URL to a JSP that will render the results of a failed * request. * </ol> * * @see Controller * @see AwRequest * @see AwRequestCreator * @see HttpSessionModifier * * @author selsky */ @SuppressWarnings("serial") public class AwJspServlet extends HttpServlet { private static Logger _logger = Logger.getLogger(AwJspServlet.class); private Controller _controller; private String _successfulRequestRedirectUrl; private String _failedRequestRedirectUrl; private AwRequestCreator _awRequestCreator; private HttpSessionModifier _httpSessionModifier; /** * Default no-arg constructor. */ public AwJspServlet() { } /** * JavaEE-to-Spring glue code. When the web application starts up, the init method on all servlets is invoked by the Servlet * container (if load-on-startup for the Servlet > 0). In this method, names of Spring "beans" are pulled out of the * ServletConfig and the names are used to retrieve the beans out of the ApplicationContext. The basic design rule followed * is that only Servlet.init methods contain Spring Framework glue code. */ public void init(ServletConfig config) throws ServletException { super.init(config); String servletName = config.getServletName(); // Note that these names are actually Spring Bean ids, not FQCNs String controllerName = config.getInitParameter("controllerName"); String awRequestCreatorName = config.getInitParameter("awRequestCreatorName"); String httpSessionModifierName = config.getInitParameter("httpSessionModifierName"); String successfulRequestRedirectUrl = config.getInitParameter("successfulRequestRedirectUrl"); String failedRequestRedirectUrl = config.getInitParameter("failedRequestRedirectUrl"); if(StringUtils.isEmptyOrWhitespaceOnly(controllerName)) { throw new ServletException("Invalid web.xml. Missing controllerName init param. Servlet " + servletName + " cannot be initialized and put into service."); } if(StringUtils.isEmptyOrWhitespaceOnly(awRequestCreatorName)) { throw new ServletException("Invalid web.xml. Missing awRequestCreatorName init param. Servlet " + servletName + " cannot be initialized and put into service."); } // TODO -- // This guy needs to be optional, or should that be another class? -- refactor - use strategy for init-params // Implement the null check first and then refactor. // if(StringUtils.isEmptyOrWhitespaceOnly(awToHttpRequestTransformerName)) { // throw new ServletException("Invalid web.xml. Missing awRequestTransformerName init param. Servlet " + servletName + // " cannot be initialized and put into service."); if(StringUtils.isEmptyOrWhitespaceOnly(httpSessionModifierName)) { _logger.info("Servet " + servletName + " configured without an AW to HTTP Request copier"); } if(StringUtils.isEmptyOrWhitespaceOnly(successfulRequestRedirectUrl)) { throw new ServletException("Invalid web.xml. Missing redirectUrl init param. Servlet " + servletName + " cannot be initialized and put into service."); } _successfulRequestRedirectUrl = successfulRequestRedirectUrl; _failedRequestRedirectUrl = failedRequestRedirectUrl; // OK, now get the beans out of the Spring ApplicationContext // If the beans do not exist within the Spring configuration, Spring will throw a RuntimeException and initialization // of this Servlet will fail. (check catalina.out in addition to aw.log) ServletContext servletContext = config.getServletContext(); ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext); _controller = (Controller) applicationContext.getBean(controllerName); _awRequestCreator = (AwRequestCreator) applicationContext.getBean(awRequestCreatorName); if(null != httpSessionModifierName) { _httpSessionModifier = (HttpSessionModifier) applicationContext.getBean(httpSessionModifierName); } _logger.info("Servlet " + servletName + " successfully put into service"); } /** * Services the user requests to the URLs bound to this Servlet as configured in web.xml. * * Performs the following steps: * <ol> * <li>Maps HTTP request parameters into an AwRequest. * <li>Passes the AwRequest to a Controller. * <li>Places the results of the controller action into the HTTP request. * <li>Forwards to a JSP for rendering of the feature results. * </ol> */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // allow Tomcat to handle Servlet and IO Exceptions // Map data from the inbound request to our internal format AwRequest awRequest = _awRequestCreator.createFrom(request); try { // Execute feature-specific logic _controller.execute(awRequest); // Map data from the request into the HttpSession for later use or for rendering within a JSP if(null != _httpSessionModifier) { _httpSessionModifier.modifySession(awRequest, request.getSession()); } // Redirect to JSP if(awRequest.isFailedRequest()) { response.sendRedirect(_failedRequestRedirectUrl); } else { response.sendRedirect(_successfulRequestRedirectUrl); // getServletContext().getRequestDispatcher(_successfulRequestRedirectUrl).forward (request, response); } } catch(ControllerException ce) { _logger.error("", ce); // make sure the stack trace gets into our app log throw ce; // re-throw and allow Tomcat to redirect to the configured error page. the stack trace will also end up // in catalina.out } } /** * Dispatches to processRequest(). */ @Override protected final void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { processRequest(req, resp); } /** * Dispatches to processRequest(). */ @Override protected final void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { processRequest(req, resp); } }
package edu.wpi.first.wpilibj.usfirst.FRC4068; import edu.wpi.first.wpilibj.SimpleRobot; import edu.wpi.first.wpilibj.usfirst.FRC4068.subsystems.*; /** * The VM is configured to automatically run this class, and to call the * functions corresponding to each mode, as described in the SimpleRobot * documentation. If you change the name of this class or the package after * creating this project, you must also update the manifest file in the resource * directory. */ public class RobotMain extends SimpleRobot { References refs = new References(); public void robotInit(){ } /** * This function is called once each time the robot enters autonomous mode. */ public void autonomous() { } /** * This function is called once each time the robot enters operator control. */ public void operatorControl() { Launcher.startCompressor(); DriveTrain.setSafety(true); Claws.setSafety(true); double claws = 0; boolean holdClaws = false; while (isOperatorControl() && isEnabled()){ DriveTrain.drive(DStation.getAxisDriver(1), -(DStation.getAxisDriver(2))); boolean[] coDriverButtons = DStation.getButtonsCoDriver(); if(coDriverButtons[1]){ Launcher.launchLauncher(); }else if(coDriverButtons[3]){ Launcher.retractLauncher(); } boolean[] driverButtons = DStation.getButtonsDriver(); if(driverButtons[2]){ Claws.setOpenClose(1); }else if(driverButtons[3]){ Claws.setOpenClose(-1); } if(!holdClaws) claws = DStation.getAxisDriver(3); if(driverButtons[1]){ holdClaws = !holdClaws; } System.out.println(claws); Claws.setRaiseLower(claws); /** * Used for the drive train movement. Should be less jerky. Feel free to modify where necessary. */ if (driverjoystick[8]){ motor power = 100%; } else if (driverjoystick[7]){ motor power = 87.5%; } else if (driverjoystick[6]){ motor power = 75%; } else if (driverjoystick[5]){ motor power = 62.5%; } else if (driverjoystick[4]){ motor power = 50%; } else if (driverjoystick[3]){ motor power = 37.5%; } else if (driverjoystick[2]){ motor power = 25%; } else if (driverjoystick[1]){ motor power = 12.5%; } } } /** * This function is called once each time the robot enters test mode. */ public void test() { } public boolean isTeleop() { return (isOperatorControl() && isEnabled()); } }
package emergencylanding.k.library.internalstate; import emergencylanding.k.library.util.DrawableUtils; public class Victor { protected static int state = 0; public float x, y, z; public float lastX, lastY, lastZ; public Victor() { this(0, 0, 0); } public Victor(float x, float y, float z) { init(x, y, z); } public Victor interpolate(float del) { Victor inter = new Victor(); if (del > 1) { System.err.println("del > 1 (" + del + ")"); } inter.x = DrawableUtils.lerp(lastX, x, del); inter.y = DrawableUtils.lerp(lastY, y, del); inter.z = DrawableUtils.lerp(lastZ, z, del); return inter; } public void update(float xVal, float yVal, float zVal) { lastX = x; lastY = y; lastZ = z; x = xVal; y = yVal; z = zVal; } public void init(float xVal, float yVal, float zVal) { x = xVal; y = yVal; z = zVal; update(xVal, yVal, zVal); } @Override public boolean equals(Object o) { if (o == this) { return true; } if (o instanceof Victor) { Victor v = (Victor) o; /* * Note: possible want to consider comparing lastX/Y/Z, as that * makes calls to interpolate() different. */ return v.x == x && v.y == y && v.z == z; } return super.equals(o); } public synchronized static void flip() { Victor.state = 1 - Victor.state; } }
package ol; import com.google.gwt.core.client.js.JsProperty; import com.google.gwt.core.client.js.JsType; import com.google.gwt.dom.client.Element; import ol.control.Control; import ol.event.Event; import ol.gwt.TypedObject; import ol.interaction.Interaction; import ol.layer.Base; /** * The map is the core component of OpenLayers. For a map to render, a view, one * or more layers, and a target container are needed: * * var map = new ol.Map({ view: new ol.View({ center: [0, 0], zoom: 1 }), * layers: [ new ol.layer.Tile({ source: new ol.source.MapQuest({layer: 'osm'}) * }) ], target: 'map' }); * * The above snippet creates a map using a {@link ol.layer.Tile} to display * {@link ol.source.MapQuest} OSM data and render it to a DOM element with the * id `map`. * * The constructor places a viewport container (with CSS class name * `ol-viewport`) in the target element (see `getViewport()`), and then two * further elements within the viewport: one with CSS class name * `ol-overlaycontainer-stopevent` for controls and some overlays, and one with * CSS class name `ol-overlaycontainer` for other overlays (see the `stopEvent` * option of {@link ol.Overlay} for the difference). The map itself is placed in * a further element within the viewport, either DOM or Canvas, depending on the * renderer. * * Layers are stored as a `ol.Collection` in layerGroups. A top-level group is * provided by the library. This is what is accessed by `getLayerGroup` and * `setLayerGroup`. Layers entered in the options are added to this group, and * `addLayer` and `removeLayer` change the layer collection in the group. * `getLayers` is a convenience function for `getLayerGroup().getLayers()`. Note * that `ol.layer.Group` is a subclass of `ol.layer.Base`, so layers entered in * the options or added with `addLayer` can be groups, which can contain further * groups, and so on. * * @author Tino Desjardins */ @JsType(prototype = "ol.Map") public interface Map extends Object { /** * Add the given control to the map. * * @param control * Control. */ public void addControl(Control control); /** * Add the given interaction to the map. * * @param interaction * Interaction to add. */ public void addInteraction(Interaction interaction); /** * Adds the given layer to the top of this map. If you want to add a layer * elsewhere in the stack, use `getLayers()` and the methods available on * {@link ol.Collection}. * * @param layer * Layer. */ public void addLayer(Base layer); /** * Get the map controls. Modifying this collection changes the controls * associated with the map. * * @return {ol.Collection.<ol.control.Control>} Controls. */ public Collection<Control> getControls(); /** * Get the coordinate for a given pixel. This returns a coordinate in the * map view projection. * * @param pixel * Pixel position in the map viewport. * @return {ol.Coordinate} The coordinate for the pixel position. */ Coordinate getCoordinateFromPixel(Pixel pixel); /** * Returns the geographical coordinate for a browser event. * * @param event * Event. * @return {ol.Coordinate} Coordinate. */ Coordinate getEventCoordinate(Event event); /** * Returns the map pixel position for a browser event relative to the * viewport. * * @param event * Event. * @return {ol.Pixel} Pixel. */ Pixel getEventPixel(Event event); /** * Get the collection of layers associated with this map. * * @return {!ol.Collection.<ol.layer.Base>} Layers. */ public Collection<Base> getLayers(); /** * Get the pixel for a coordinate. This takes a coordinate in the map view * projection and returns the corresponding pixel. * * @param coordinate * A map coordinate. * @return {ol.Pixel} A pixel position in the map viewport. */ Pixel getPixelFromCoordinate(Coordinate coordinate); /** * The ratio between physical pixels and device-independent pixels (dips) on * the device. If undefined then it gets set by using * window.devicePixelRatio. * * @return pixel ratio */ @JsProperty public double getPixelRatio(); /** * Get the size of this map. * * @return {ol.Size|undefined} The size in pixels of the map in the DOM. */ Size getSize(); /** * Get the target in which this map is rendered. Note that this returns what * is entered as an option or in setTarget: if that was an element, it * returns an element; if a string, it returns that. * * @return {Element|string|undefined} The Element or id of the Element that * the map is rendered in. */ public String getTarget(); /** * Get the DOM element into which this map is rendered. In contrast to * `getTarget` this method always return an `Element`, or `null` if the map * has no target. * * @return {Element} The element that the map is rendered in. */ Element getTargetElement(); /** * Get the view associated with this map. A view manages properties such as * center and resolution. * * @return The view that controls this map. */ public View getView(); /** * Get the element that serves as the map viewport. * * @return {Element} Viewport. */ Element getViewport(); /** * Remove the given control from the map. * * @param control * Control. * @return {ol.control.Control|undefined} The removed control (or undefined * if the control was not found). */ public Control removeControl(Control control); /** * Remove the given interaction from the map. * * @param interaction * Interaction to remove. * @return {ol.interaction.Interaction|undefined} The removed interaction * (or undefined if the interaction was not found). */ public Interaction removeInteraction(Interaction interaction); /** * Removes the given layer from the map. * * @param layer * Layer. * @return {ol.layer.Base|undefined} The removed layer (or undefined if the * layer was not found). */ public Base removeLayer(Base layer); /** * Requests a render frame; rendering will effectively occur at the next * browser animation frame. */ public void render(); /** * Set the size of this map. * * @param size * The size in pixels of the map in the DOM. */ void setSize(Size size); /** * The container for the map, either the element itself or the id of the * element. If not specified at construction time, ol.Map#setTarget must be * called for the map to be rendered. * * @param o * id or element */ public void setTarget(TypedObject<Element, String> o); /** * Set the view for this map. * * @param view * The view that controls this map. */ public void setView(View view); /** * Force a recalculation of the map viewport size. This should be called * when third-party code changes the size of the map viewport. */ public void updateSize(); }
package org.objectweb.proactive.core.util; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.net.URI; import java.net.URISyntaxException; import java.net.UnknownHostException; import java.util.Enumeration; import org.apache.log4j.Logger; import org.objectweb.proactive.core.Constants; import org.objectweb.proactive.core.config.PAProperties; import org.objectweb.proactive.core.remoteobject.RemoteObjectHelper; import org.objectweb.proactive.core.remoteobject.exception.UnknownProtocolException; import org.objectweb.proactive.core.util.log.Loggers; import org.objectweb.proactive.core.util.log.ProActiveLogger; /** * This class is a utility class to perform modifications and operations on urls. */ public class URIBuilder { private static String[] LOCAL_URLS = { "", "localhost.localdomain", "localhost", "127.0.0.1" }; static Logger logger = ProActiveLogger.getLogger(Loggers.UTIL); /** * Checks if the given url is well-formed * @param url the url to check * @return The url if well-formed * @throws URISyntaxException if the url is not well-formed */ public static URI checkURI(String url) throws URISyntaxException { URI u = new URI(url); String hostname; try { hostname = fromLocalhostToHostname(u.getHost()); URI u2 = buildURI(hostname, u.getPath(), u.getScheme(), u.getPort()); return u2; } catch (UnknownHostException e) { throw new URISyntaxException(url, "host unknow"); } } /** * Returns an url compliant with RFC 2396 [protocol:][//host][[/]path] * loopback address is replaced by a non-loopback address localhost -> [DNS/IP] Address * @param host Url's hostname * @param name Url's Path * @param protocol Url's protocol * @throws UnknownProtocolException * @returnan url under the form [protocol:][//host][[/]name] */ public static URI buildURI(String host, String name, String protocol) { try { return buildURI(host, name, protocol, RemoteObjectHelper.getDefaultPortForProtocol(protocol)); } catch (UnknownProtocolException e) { e.printStackTrace(); } return null; } /** * Returns an url compliant with RFC 2396[//host][[/]path] * loopback address is replaced by a non-loopback address localhost -> [DNS/IP] Address * @param host Url's hostname * @param name Url's Path * @throws UnknownProtocolException * @returnan url under the form [//host][[/]name] */ public static URI buildURI(String host, String name) { return buildURI(host, name, null); } /** * Returns an url compliant with RFC 2396 [protocol:][//host[:port]][[/]path] * loopback address is replaced by a non-loopback address localhost -> [DNS/IP] Address * @param host Url's hostname * @param name Url's Path * @param protocol Url's protocol * @param port Url's port * @returnan url under the form [protocol:][//host[:port]][[/]name] */ public static URI buildURI(String host, String name, String protocol, int port) { return buildURI(host, name, protocol, port, true); } /** * Returns an url compliant with RFC 2396 [protocol:][//host[:port]][[/]name] * @param host Url's hostname * @param name Url's Path * @param protocol Url's protocol * @param port Url's port * @param replaceHost indicate if internal hooks regarding how to resolve the hostname have to be used * @see #fromLocalhostToHostname(String localName) * @see #getHostNameorIP(InetAddress address) * @returnan url under the form [protocol:][//host[:port]][[/]name] */ public static URI buildURI(String host, String name, String protocol, int port, boolean replaceHost) { // if (protocol == null) { // protocol = System.getProperty(Constants.PROPERTY_PA_COMMUNICATION_PROTOCOL); if (port == 0) { port = -1; } try { if (replaceHost) { host = fromLocalhostToHostname(host); } if ((name != null) && (!name.startsWith("/"))) { /* URI does not require a '/' at the beginning of the name like URLs. As we cannot use * URL directly (because we do not want to register a URL handler), we do this ugly hook. */ name = "/" + name; } return new URI(protocol, null, host, port, name, null, null); } catch (URISyntaxException e) { e.printStackTrace(); } catch (UnknownHostException e) { e.printStackTrace(); } return null; } public static URI setProtocol(URI uri, String protocol) { try { return new URI(protocol, uri.getUserInfo(), uri.getHost(), uri.getPort(), uri.getPath(), uri.getQuery(), uri.getFragment()); } catch (URISyntaxException e) { e.printStackTrace(); } return null; } /** * This method build an url in the form protocol://host:port/name where the port * and protocol are retrieved from system properties * @param host * @param name * @return an Url built from properties */ public static URI buildURIFromProperties(String host, String name) { int port = -1; String protocol = PAProperties.PA_COMMUNICATION_PROTOCOL.getValue(); try { // ok, awful hack but ensures that the factory for the given // protocol has effectively been loaded by the classloader // and that the initialization process has been performed port = RemoteObjectHelper.getDefaultPortForProtocol(protocol); } catch (UnknownProtocolException e) { logger.debug(e.getMessage()); } if (port == -1) { return buildURI(host, name, protocol); } else { return buildURI(host, name, protocol, new Integer(port).intValue()); } } /** * build a virtual node url from a given url * @param url * @return * @throws java.net.UnknownHostException if no network interface was found */ public static URI buildVirtualNodeUrl(URI uri) { String vnName = getNameFromURI(uri); vnName = vnName.concat("_VN"); String host = getHostNameFromUrl(uri); String protocol = uri.getScheme(); int port = uri.getPort(); return buildURI(host, vnName, protocol, port); } /** * build a virtual node url from a given url * @param url * @return * @throws java.net.UnknownHostException if no network interface was found */ public static URI buildVirtualNodeUrl(String url) { return buildVirtualNodeUrl(URI.create(url)); } public static String appendVnSuffix(String name) { return name.concat("_VN"); } public static String removeVnSuffix(String url) { int index = url.lastIndexOf("_VN"); if (index == -1) { return url; } return url.substring(0, index); } /** * Returns the name included in the url * @param url * @return the name included in the url */ public static String getNameFromURI(URI u) { String path = u.getPath(); if ((path != null) && (path.startsWith("/"))) { // remove the intial '/' return path.substring(1); } return path; } public static String getNameFromURI(String url) { URI uri = URI.create(url); return getNameFromURI(uri); } /** * Return the protocol specified in the string * The same convention as in URL is used */ public static String getProtocol(URI uri) { String protocol = uri.getScheme(); if (protocol == null) { return Constants.DEFAULT_PROTOCOL_IDENTIFIER; } return protocol; } public static String getProtocol(String url) { URI uri = URI.create(url); return getProtocol(uri); } /** * Returns the url without protocol */ public static URI removeProtocol(URI uri) { return buildURI(getHostNameFromUrl(uri), uri.getPath(), null, uri.getPort(), false); } public static URI removeProtocol(String url) { URI uri = URI.create(url); return removeProtocol(uri); } public static String getHostNameFromUrl(URI uri) { return uri.getHost(); } public static String getHostNameFromUrl(String url) { URI uri = URI.create(url); return getHostNameFromUrl(uri); } public static String removePortFromHost(String hostname) { try { URI uri = new URI(hostname); return uri.getHost(); } catch (URISyntaxException e) { e.printStackTrace(); return hostname; } } /** * this method returns the hostname or the IP address associated to the InetAddress address parameter. * It is possible to set * {@code "proactive.hostname"} property (evaluated in that order) to override the default java behaviour * of resolving InetAddress * @param address any InetAddress * @return a String matching the corresponding InetAddress */ public static String getHostNameorIP(InetAddress address) { // address = UrlBuilder.getNetworkInterfaces(); if (PAProperties.PA_HOSTNAME.getValue() != null) { return PAProperties.PA_HOSTNAME.getValue(); } String temp = ""; if (PAProperties.PA_USE_IP_ADDRESS.isTrue()) { temp = (address).getHostAddress(); } else { temp = address.getCanonicalHostName(); } return URIBuilder.ipv6withoutscope(temp); } /** * evaluate if localName is a loopback entry, if yes calls {@link getHostNameorIP(InetAddress address)} * @param localName * @return a remotely accessible host name if exists * @throws UnknownHostException if no network interface was found * @see getHostNameorIP(InetAddress address) */ public static String fromLocalhostToHostname(String localName) throws UnknownHostException { if (localName == null) { localName = "localhost"; } java.net.InetAddress hostInetAddress = getLocalAddress(); for (int i = 0; i < LOCAL_URLS.length; i++) { if (LOCAL_URLS[i].startsWith(localName.toLowerCase())) { return URIBuilder.getHostNameorIP(hostInetAddress); } } return localName; } /** * This method extract the port from a string in the form host:port or host * @param url * @return port number or 0 if there is no port */ public static int getPortNumber(String url) { URI uri = URI.create(url); return getPortNumber(uri); } public static int getPortNumber(URI uri) { if (uri.getPort() != -1) { return uri.getPort(); } return 0; } /** * change the port of a given url * @param url the url to change the port * @param port the new port number * @return the url with the new port */ public static URI setPort(URI u, int port) { URI u2; try { u2 = new URI(u.getScheme(), u.getUserInfo(), u.getHost(), port, u.getPath(), u.getQuery(), u.getFragment()); return u2; } catch (URISyntaxException e) { e.printStackTrace(); } return u; } public static String ipv6withoutscope(String address) { String name = address; int indexPercent = name.indexOf('%'); if (indexPercent != -1) { return "[" + name.substring(0, indexPercent) + "]"; } else { return address; } } public static String ipv6withoutscope(InetAddress address) { String name = address.getHostAddress(); int indexPercent = name.indexOf('%'); if (indexPercent != -1) { return "[" + name.substring(0, indexPercent) + "]"; } else { return name; } } public static String removeUsername(String url) { //this method is used to extract the username, that might be necessary for the callback //it updates the hostable. int index = url.indexOf("@"); if (index >= 0) { String username = url.substring(0, index); url = url.substring(index + 1, url.length()); HostsInfos.setUserName(getHostNameFromUrl(url), username); } return url; } /** * Return a suitable network address for localhost * * This function has to be used to determine the IP address of the localhost. * Two ProActive properties can be used to customize the returned address * <ul> * <li>PA_NOLOOPBACK will discards any loopback address (127.*)</li> * <li>PA_NOPRIVATE will discards any private IP address (10.*, 192.168.*, etc.)</li> * </ul> * * If no suitable address can be found then the result of InetAddress.getLocalhost is returned. * If no address at all can be found then null is returned. * * This function is IPv6 compliant since it relies on {@link Inet4Address} and {@link Inet6Address} * to determine if an address is loopback/private or not. * * @return A suitable IP Address for this host * @see -Djava.net.preferIPv4Stack=true * @see -Djava.net.preferIPv6Stack=true * * TODO cmathieu Write documentation ! */ public static InetAddress getLocalAddress() throws UnknownHostException { try { Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces(); while (nis.hasMoreElements()) { NetworkInterface ni = nis.nextElement(); Enumeration<InetAddress> ias = ni.getInetAddresses(); while (ias.hasMoreElements()) { InetAddress ia = ias.nextElement(); if (PAProperties.PA_NOLOOPBACK.isTrue()) { if (ia.isLoopbackAddress()) { continue; } } if (PAProperties.PA_NOPRIVATE.isTrue()) { if (ia.isSiteLocalAddress()) { continue; } } // Bug PROACTIVE-19 remove me when closed ! // Since IPv6 is broken skip all IPv6 addresses System.setProperty("java.net.preferIPv4Stack ", "true"); if (ia instanceof Inet6Address) { continue; } /* To automatically use the right protocol when using plain sockets if (ia instanceof Inet4Address) { System.setProperty("java.net.preferIPv6Stack ", "false"); System.setProperty("java.net.preferIPv6Stack ", "true"); } else if (ia instanceof Inet6Address) { System.setProperty("java.net.preferIPv4Stack ", "false"); System.setProperty("java.net.preferIPv6Stack ", "true"); } else { logger.warn("Unhandled type of InetAddress " + ia.getClass().getName()); } */ return ia; } } } catch (SocketException e1) { logger.warn("Unable to list all the network interface of this machine", e1); } logger.error("No suitable local address can be found"); return InetAddress.getLocalHost(); } }
package com.nlbhub.nlb.domain; import com.nlbhub.nlb.api.*; import com.nlbhub.nlb.exception.NLBConsistencyException; import com.nlbhub.nlb.exception.NLBFileManipulationException; import com.nlbhub.nlb.exception.NLBIOException; import com.nlbhub.nlb.exception.NLBVCSException; import com.nlbhub.nlb.util.FileManipulator; import com.nlbhub.nlb.util.MultiLangString; import com.nlbhub.nlb.util.StringHelper; import org.jetbrains.annotations.NotNull; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import java.io.File; import java.io.IOException; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.List; import java.util.Map; /** * The PageImpl class * * @author Anton P. Kolosov * @version 1.0 7/6/12 */ @XmlAccessorType(XmlAccessType.NONE) @XmlRootElement(name = "page") public class PageImpl extends AbstractNodeItem implements Page { private static final String TEXT_SUBDIR_NAME = "text"; private static final String IMAGE_FILE_NAME = "image"; private static final String IMAGEBG_FILE_NAME = "imagebg"; private static final String SOUND_FILE_NAME = "sound"; private static final String VARID_FILE_NAME = "varid"; private static final String CAPTION_SUBDIR_NAME = "caption"; private static final String USE_CAPT_FILE_NAME = "use_capt"; private static final String MODULE_SUBDIR_NAME = "module"; private static final String MODNAME_FILE_NAME = "modname"; private static final String TRAVTEXT_FILE_NAME = "travtext"; private static final String AUTOTRAV_FILE_NAME = "autotrav"; private static final String AUTORET_FILE_NAME = "autoret"; private static final String RETTEXT_SUBDIR_NAME = "rettext"; private static final String RETPAGE_FILE_NAME = "retpage"; private static final String MODCNSID_FILE_NAME = "modcnsid"; private static final String AUTO_IN_TEXT_SUBDIR_NAME = "aintext"; private static final String AUTO_OUT_TEXT_SUBDIR_NAME = "aouttext"; private static final String AUTO_IN_FILE_NAME = "auto_in"; private static final String AUTO_OUT_FILE_NAME = "auto_out"; private static final String AUTOWIRE_IN_CONSTRID_FILE_NAME = "autoid"; private static final String AUTOWIRE_OUT_CONSTRID_FILE_NAME = "autoutid"; private static final String DEFAULT_MODULE_NAME_FORMAT = "%s's submodule"; private String m_imageFileName = DEFAULT_IMAGE_FILE_NAME; private boolean m_imageBackground = DEFAULT_IMAGE_BACKGROUND; private String m_soundFileName = DEFAULT_SOUND_FILE_NAME; private String m_varId = DEFAULT_VARID; private MultiLangString m_caption = DEFAULT_CAPTION; private boolean m_useCaption = DEFAULT_USE_CAPTION; private MultiLangString m_text = DEFAULT_TEXT; private String m_moduleName; private String m_defaultModuleName; private MultiLangString m_traverseText; private boolean m_autoTraverse = DEFAULT_AUTO_TRAVERSE; private boolean m_autoReturn = DEFAULT_AUTO_RETURN; private MultiLangString m_returnText = DEFAULT_RETURN_TEXT; private String m_returnPageId = DEFAULT_RETURN_PAGE_ID; private String m_moduleConstrId = DEFAULT_MODULE_CONSTR_ID; private NonLinearBookImpl m_module; private MultiLangString m_autowireInText = DEFAULT_AUTOWIRE_IN_TEXT; private MultiLangString m_autowireOutText = DEFAULT_AUTOWIRE_OUT_TEXT; private boolean m_autoIn = DEFAULT_AUTO_IN; private boolean m_autoOut = DEFAULT_AUTO_OUT; private String m_autowireInConstrId = DEFAULT_AUTOWIRE_IN_CONSTR_ID; private String m_autowireOutConstrId = DEFAULT_AUTOWIRE_OUT_CONSTR_ID; /** * Default contructor. It is needed for JAXB conversion, do not remove! * Do not use it for any other purpose! */ public PageImpl() { super(); } public PageImpl(NonLinearBook currentNLB) { super(currentNLB); init(); } /** * NB: Please take into account that it will create full copy, including ids and such */ public PageImpl(PageImpl source) { super(source); m_imageFileName = source.getImageFileName(); m_imageBackground = source.isImageBackground(); m_soundFileName = source.getSoundFileName(); setVarId(source.getVarId()); setCaptions(source.getCaptions()); setUseCaption(source.isUseCaption()); setTexts(source.getTexts()); setModuleName(source.getModuleName()); resetDefaultModuleName(); setTraverseTexts(source.getTraverseTexts()); setAutoTraverse(source.isAutoTraverse()); setAutoReturn(source.isAutoReturn()); setReturnTexts(source.getReturnTexts()); setReturnPageId(source.getReturnPageId()); setModuleConstrId(source.getModuleConstrId()); m_module = new NonLinearBookImpl(getCurrentNLB(), this); m_module.append(source.getModuleImpl()); setAutowireInTexts(source.getAutowireInTexts()); setAutowireOutTexts(source.getAutowireOutTexts()); setAutoIn(source.isAutoIn()); setAutoOut(source.isAutoOut()); setAutowireInConstrId(source.getAutowireInConstrId()); setAutowireOutConstrId(source.getAutowireOutConstrId()); } private void init() { m_module = new NonLinearBookImpl(getCurrentNLB(), this); resetDefaultModuleName(); m_moduleName = m_defaultModuleName; m_traverseText = MultiLangString.createCopy(DEFAULT_TRAVERSE_TEXT); } private void resetDefaultModuleName() { m_defaultModuleName = String.format(DEFAULT_MODULE_NAME_FORMAT, getId()); } @Override public SearchResult searchText(SearchContract contract) { SearchResult result = super.searchText(contract); if (result != null) { return result; } else if ( textMatches(m_text, contract) || textMatches(m_caption, contract) || textMatches(m_returnText, contract) || textMatches(m_traverseText, contract) || textMatches(m_autowireInText, contract) || textMatches(m_autowireOutText, contract) || textMatches(m_imageFileName, contract) || textMatches(m_soundFileName, contract) || textMatches(m_moduleName, contract) ) { result = new SearchResult(); result.setId(getId()); result.setInformation(getCaption()); return result; } return null; } public PageImpl(NonLinearBook currentNLB, float left, float top) { super(currentNLB, left, top); init(); } public void setImageFileName(String imageFileName) { m_imageFileName = imageFileName; } @Override public String getImageFileName() { return m_imageFileName; } public void setImageBackground(final boolean imageBackground) { m_imageBackground = imageBackground; } @Override public boolean isImageBackground() { return m_imageBackground; } public void setSoundFileName(String soundFileName) { m_soundFileName = soundFileName; } @Override public String getSoundFileName() { return m_soundFileName; } public void setText(String text) { m_text.put(getCurrentNLB().getLanguage(), text); } @Override @XmlElement(name = "text") public String getText() { return m_text.get(getCurrentNLB().getLanguage()); } @Override public MultiLangString getTexts() { return MultiLangString.createCopy(m_text); } public void setTexts(final MultiLangString text) { m_text = text; } @Override @XmlElement(name = "varid") public String getVarId() { return m_varId; } public void setVarId(String varId) { m_varId = varId; } @Override @XmlElement(name = "moduleconstrid") public String getModuleConstrId() { return m_moduleConstrId; } public void setModuleConstrId(String moduleConstrId) { m_moduleConstrId = moduleConstrId; } @Override @XmlElement(name = "caption") public String getCaption() { return m_caption.get(getCurrentNLB().getLanguage()); } @Override public MultiLangString getCaptions() { return MultiLangString.createCopy(m_caption); } public void setCaptions(final MultiLangString caption) { m_caption = caption; } public void setCaption(String caption) { m_caption.put(getCurrentNLB().getLanguage(), caption); } @Override @XmlElement(name = "usecaption") public boolean isUseCaption() { return m_useCaption; } @Override public boolean isLeaf() { return getLinkCount() == 0; } @Override public String getTraverseText() { return m_traverseText.get(getCurrentNLB().getLanguage()); } @Override public MultiLangString getTraverseTexts() { return MultiLangString.createCopy(m_traverseText); } public void setTraverseTexts(final MultiLangString traverseText) { m_traverseText = traverseText; } @Override @XmlElement(name = "is-auto-traverse") public boolean isAutoTraverse() { return m_autoTraverse; } public void setAutoTraverse(boolean autoTraverse) { m_autoTraverse = autoTraverse; } @Override @XmlElement(name = "is-auto-return") public boolean isAutoReturn() { return m_autoReturn; } public void setAutoReturn(boolean autoReturn) { m_autoReturn = autoReturn; } @Override public String getReturnText() { return m_returnText.get(getCurrentNLB().getLanguage()); } @Override public MultiLangString getReturnTexts() { return MultiLangString.createCopy(m_returnText); } public void setReturnTexts(final MultiLangString returnText) { m_returnText = returnText; } @Override @XmlElement(name = "return-page-id") public String getReturnPageId() { return m_returnPageId; } public void setReturnPageId(String returnPageId) { m_returnPageId = returnPageId; } @Override public boolean shouldReturn() { return !StringHelper.isEmpty(m_returnText) || m_autoReturn; } @Override public String getModuleName() { return m_moduleName; } public void setModuleName(String moduleName) { m_moduleName = moduleName; } public void setTraverseText(String traverseText) { m_traverseText.put(getCurrentNLB().getLanguage(), traverseText); } public void setReturnText(String returnText) { m_returnText.put(getCurrentNLB().getLanguage(), returnText); } @Override public NonLinearBook getModule() { return m_module; } public void setAutoIn(boolean autoIn) { m_autoIn = autoIn; } public void setAutoOut(boolean autoOut) { m_autoOut = autoOut; } public void setAutowireInConstrId(String autowireInConstrId) { m_autowireInConstrId = autowireInConstrId; } public void setAutowireOutConstrId(String autowireOutConstrId) { m_autowireOutConstrId = autowireOutConstrId; } @Override public boolean isAutowire() { return getCurrentNLB().isAutowired(getId()); } @Override public String getAutowireInText() { return m_autowireInText.get(getCurrentNLB().getLanguage()); } @Override public MultiLangString getAutowireInTexts() { return MultiLangString.createCopy(m_autowireInText); } public void setAutowireInText(String autowireInText) { m_autowireInText.put(getCurrentNLB().getLanguage(), autowireInText); } public void setAutowireInTexts(MultiLangString autowireInText) { m_autowireInText = autowireInText; } @Override public String getAutowireOutText() { return m_autowireOutText.get(getCurrentNLB().getLanguage()); } @Override public MultiLangString getAutowireOutTexts() { return MultiLangString.createCopy(m_autowireOutText); } public void setAutowireOutText(String autowireOutText) { m_autowireOutText.put(getCurrentNLB().getLanguage(), autowireOutText); } public void setAutowireOutTexts(MultiLangString autowireOutText) { m_autowireOutText = autowireOutText; } @Override public boolean isAutoIn() { return m_autoIn; } @Override public boolean isAutoOut() { return m_autoOut; } @Override public String getAutowireInConstrId() { return m_autowireInConstrId; } @Override public String getAutowireOutConstrId() { return m_autowireOutConstrId; } /** * For internal use only! * * @return */ public NonLinearBookImpl getModuleImpl() { return m_module; } public void setUseCaption(boolean useCaption) { m_useCaption = useCaption; } public void writePage( final @NotNull FileManipulator fileManipulator, final @NotNull File pagesDir, final @NotNull NonLinearBookImpl nonLinearBook, final @NotNull PartialProgressData partialProgressData ) throws IOException, NLBIOException, NLBFileManipulationException, NLBVCSException, NLBConsistencyException { final File pageDir = new File(pagesDir, getId()); if (isDeleted()) { // Completely remove page directory fileManipulator.deleteFileOrDir(pageDir); } else { fileManipulator.createDir( pageDir, "Cannot create NLB page directory for page with Id = " + getId() ); final File moduleDir = new File(pageDir, MODULE_SUBDIR_NAME); if (m_module.isEmpty()) { if (moduleDir.exists()) { fileManipulator.deleteFileOrDir(moduleDir); } } else { m_module.setRootDir(moduleDir); m_module.save(fileManipulator, new DummyProgressData(), partialProgressData); } fileManipulator.writeOptionalString(pageDir, VARID_FILE_NAME, m_varId, DEFAULT_VARID); fileManipulator.writeOptionalMultiLangString( new File(pageDir, CAPTION_SUBDIR_NAME), m_caption, DEFAULT_CAPTION ); fileManipulator.writeOptionalString( pageDir, USE_CAPT_FILE_NAME, String.valueOf(m_useCaption), String.valueOf(DEFAULT_USE_CAPTION) ); fileManipulator.writeOptionalString( pageDir, IMAGE_FILE_NAME, m_imageFileName, DEFAULT_IMAGE_FILE_NAME ); fileManipulator.writeOptionalString( pageDir, IMAGEBG_FILE_NAME, String.valueOf(m_imageBackground), String.valueOf(DEFAULT_IMAGE_BACKGROUND) ); fileManipulator.writeOptionalString( pageDir, SOUND_FILE_NAME, m_soundFileName, DEFAULT_SOUND_FILE_NAME ); fileManipulator.writeOptionalMultiLangString( new File(pageDir, TEXT_SUBDIR_NAME), m_text, DEFAULT_TEXT ); fileManipulator.writeOptionalString( pageDir, MODNAME_FILE_NAME, m_moduleName, m_defaultModuleName ); fileManipulator.writeOptionalMultiLangString( new File(pageDir, TRAVTEXT_FILE_NAME), m_traverseText, DEFAULT_TRAVERSE_TEXT ); fileManipulator.writeOptionalString( pageDir, AUTOTRAV_FILE_NAME, String.valueOf(m_autoTraverse), String.valueOf(DEFAULT_AUTO_TRAVERSE) ); fileManipulator.writeOptionalString( pageDir, AUTORET_FILE_NAME, String.valueOf(m_autoReturn), String.valueOf(DEFAULT_AUTO_RETURN) ); fileManipulator.writeOptionalMultiLangString( new File(pageDir, RETTEXT_SUBDIR_NAME), m_returnText, DEFAULT_RETURN_TEXT ); fileManipulator.writeOptionalString( pageDir, RETPAGE_FILE_NAME, m_returnPageId, DEFAULT_RETURN_PAGE_ID ); fileManipulator.writeOptionalString( pageDir, MODCNSID_FILE_NAME, m_moduleConstrId, DEFAULT_MODULE_CONSTR_ID ); fileManipulator.writeOptionalMultiLangString( new File(pageDir, AUTO_IN_TEXT_SUBDIR_NAME), m_autowireInText, DEFAULT_AUTOWIRE_IN_TEXT ); fileManipulator.writeOptionalMultiLangString( new File(pageDir, AUTO_OUT_TEXT_SUBDIR_NAME), m_autowireOutText, DEFAULT_AUTOWIRE_OUT_TEXT ); fileManipulator.writeOptionalString( pageDir, AUTO_IN_FILE_NAME, String.valueOf(m_autoIn), String.valueOf(DEFAULT_AUTO_IN) ); fileManipulator.writeOptionalString( pageDir, AUTO_OUT_FILE_NAME, String.valueOf(m_autoOut), String.valueOf(DEFAULT_AUTO_OUT) ); fileManipulator.writeOptionalString( pageDir, AUTOWIRE_IN_CONSTRID_FILE_NAME, m_autowireInConstrId, DEFAULT_AUTOWIRE_IN_CONSTR_ID ); fileManipulator.writeOptionalString( pageDir, AUTOWIRE_OUT_CONSTRID_FILE_NAME, m_autowireOutConstrId, DEFAULT_AUTOWIRE_OUT_CONSTR_ID ); writeModOrderFile(fileManipulator, pageDir); writeModifications(fileManipulator, pageDir); writeNodeItemProperties(fileManipulator, pageDir, nonLinearBook); } } public void readPage( final File pageDir ) throws NLBIOException, NLBConsistencyException, NLBVCSException { try { setId(pageDir.getName()); resetDefaultModuleName(); final File moduleDir = new File(pageDir, MODULE_SUBDIR_NAME); m_module.loadAndSetParent(moduleDir.getCanonicalPath(), getCurrentNLB(), this); m_varId = ( FileManipulator.getOptionalFileAsString( pageDir, VARID_FILE_NAME, DEFAULT_VARID ) ); m_caption = ( FileManipulator.readOptionalMultiLangString( new File(pageDir, CAPTION_SUBDIR_NAME), DEFAULT_CAPTION ) ); m_useCaption = "true".equals( FileManipulator.getOptionalFileAsString( pageDir, USE_CAPT_FILE_NAME, String.valueOf(DEFAULT_USE_CAPTION) ) ); m_imageFileName = ( FileManipulator.getOptionalFileAsString( pageDir, IMAGE_FILE_NAME, DEFAULT_IMAGE_FILE_NAME ) ); m_imageBackground = "true".equals( FileManipulator.getOptionalFileAsString( pageDir, IMAGEBG_FILE_NAME, String.valueOf(DEFAULT_IMAGE_BACKGROUND) ) ); m_soundFileName = ( FileManipulator.getOptionalFileAsString( pageDir, SOUND_FILE_NAME, DEFAULT_SOUND_FILE_NAME ) ); m_text = ( FileManipulator.readOptionalMultiLangString( new File(pageDir, TEXT_SUBDIR_NAME), DEFAULT_TEXT ) ); m_moduleName = ( FileManipulator.getOptionalFileAsString( pageDir, MODNAME_FILE_NAME, m_defaultModuleName ) ); m_traverseText = ( FileManipulator.readOptionalMultiLangString( new File(pageDir, TRAVTEXT_FILE_NAME), DEFAULT_TRAVERSE_TEXT ) ); m_autoTraverse = "true".equals( FileManipulator.getOptionalFileAsString( pageDir, AUTOTRAV_FILE_NAME, String.valueOf(DEFAULT_AUTO_TRAVERSE) ) ); m_autoReturn = "true".equals( FileManipulator.getOptionalFileAsString( pageDir, AUTORET_FILE_NAME, String.valueOf(DEFAULT_AUTO_RETURN) ) ); m_returnText = ( FileManipulator.readOptionalMultiLangString( new File(pageDir, RETTEXT_SUBDIR_NAME), DEFAULT_RETURN_TEXT ) ); m_returnPageId = ( FileManipulator.getOptionalFileAsString( pageDir, RETPAGE_FILE_NAME, DEFAULT_RETURN_PAGE_ID ) ); m_moduleConstrId = ( FileManipulator.getOptionalFileAsString( pageDir, MODCNSID_FILE_NAME, DEFAULT_MODULE_CONSTR_ID ) ); m_autowireInText = ( FileManipulator.readOptionalMultiLangString( new File(pageDir, AUTO_IN_TEXT_SUBDIR_NAME), DEFAULT_AUTOWIRE_IN_TEXT ) ); m_autowireOutText = ( FileManipulator.readOptionalMultiLangString( new File(pageDir, AUTO_OUT_TEXT_SUBDIR_NAME), DEFAULT_AUTOWIRE_OUT_TEXT ) ); m_autoIn = "true".equals( FileManipulator.getOptionalFileAsString( pageDir, AUTO_IN_FILE_NAME, String.valueOf(DEFAULT_AUTO_IN) ) ); m_autoOut = "true".equals( FileManipulator.getOptionalFileAsString( pageDir, AUTO_OUT_FILE_NAME, String.valueOf(DEFAULT_AUTO_OUT) ) ); m_autowireInConstrId = ( FileManipulator.getOptionalFileAsString( pageDir, AUTOWIRE_IN_CONSTRID_FILE_NAME, DEFAULT_AUTOWIRE_IN_CONSTR_ID ) ); m_autowireOutConstrId = ( FileManipulator.getOptionalFileAsString( pageDir, AUTOWIRE_OUT_CONSTRID_FILE_NAME, DEFAULT_AUTOWIRE_OUT_CONSTR_ID ) ); readNodeItemProperties(pageDir); readModifications(pageDir); } catch (IOException e) { throw new NLBIOException( "Cannot get module dir canonical path for page with Id = " + getId(), e ); } } /** * Creates clone of the current page, with $varName$ expressions substituted with current variable values, some * links of which can be removed and some can be added * @param linkIdsToBeExcluded * @param linksToBeAdded * @param visitedVars * @return */ public PageImpl createFilteredCloneWithSubstitutions( final List<String> linkIdsToBeExcluded, final List<Link> linksToBeAdded, Map<String, Object> visitedVars ) { PageImpl result = new PageImpl(getCurrentNLB()); result.setId(getId()); result.setText(replaceVariables(getText(), visitedVars)); final Coords sourceCoords = getCoords(); final CoordsImpl resultCoords = result.getCoords(); resultCoords.setLeft(sourceCoords.getLeft()); resultCoords.setTop(sourceCoords.getTop()); resultCoords.setWidth(sourceCoords.getWidth()); resultCoords.setHeight(sourceCoords.getHeight()); result.setDeleted(isDeleted()); result.setReturnPageId(getReturnPageId()); result.setVarId(getVarId()); result.setCaption(getCaption()); result.setModuleConstrId(getModuleConstrId()); result.setModuleName(getModuleName()); result.setReturnText(getReturnText()); result.setTraverseText(getTraverseText()); result.setUseCaption(isUseCaption()); result.setAutoTraverse(isAutoTraverse()); result.setAutoReturn(isAutoReturn()); result.setAutowireInText(getAutowireInText()); result.setAutowireOutText(getAutowireOutText()); result.setAutoIn(isAutoIn()); result.setAutoOut(isAutoOut()); result.setAutowireInConstrId(getAutowireInConstrId()); result.setAutowireOutConstrId(getAutowireOutConstrId()); result.setFill(getFill()); result.setParent(getParent()); result.setStroke(getStroke()); result.setTextColor(getTextColor()); AbstractNodeItem.filterTargetLinkList(result, this, linkIdsToBeExcluded); for (Link link : linksToBeAdded) { result.addLink(new LinkImpl(this, link)); } return result; } private static String replaceVariables(String pageText, Map<String, Object> visitedVars) { StringBuilder result = new StringBuilder(); List<TextChunk> textChunks = StringHelper.getTextChunks(pageText); for (TextChunk textChunk : textChunks) { switch (textChunk.getType()) { case TEXT: result.append(textChunk.getText()); break; case VARIABLE: Object mappedItem = visitedVars.get(textChunk.getText()); if (mappedItem != null) { if (mappedItem instanceof Number) { result.append(new DecimalFormat(" } else { result.append(String.valueOf(mappedItem)); } } else { result.append("UNDEFINED"); } break; case NEWLINE: result.append(Constants.EOL_STRING); break; } } return result.toString(); } }
// Narya library - tools for developing networked games // This library is free software; you can redistribute it and/or modify it // (at your option) any later version. // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.presents.server; import java.net.InetAddress; import java.util.List; import java.util.Map; import java.util.TimeZone; import java.io.IOException; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.inject.Inject; import com.samskivert.util.IntMap; import com.samskivert.util.IntMaps; import com.samskivert.util.ResultListener; import com.samskivert.util.Throttle; import com.threerings.util.Name; import com.threerings.presents.annotation.AnyThread; import com.threerings.presents.annotation.EventThread; import com.threerings.presents.client.Client; import com.threerings.presents.data.ClientObject; import com.threerings.presents.dobj.DEvent; import com.threerings.presents.dobj.DObject; import com.threerings.presents.dobj.ObjectAccessException; import com.threerings.presents.dobj.ProxySubscriber; import com.threerings.presents.net.AuthRequest; import com.threerings.presents.net.BootstrapData; import com.threerings.presents.net.BootstrapNotification; import com.threerings.presents.net.Credentials; import com.threerings.presents.net.DownstreamMessage; import com.threerings.presents.net.EventNotification; import com.threerings.presents.net.FailureResponse; import com.threerings.presents.net.ForwardEventRequest; import com.threerings.presents.net.LogoffRequest; import com.threerings.presents.net.Message; import com.threerings.presents.net.ObjectResponse; import com.threerings.presents.net.PingRequest; import com.threerings.presents.net.PongResponse; import com.threerings.presents.net.SubscribeRequest; import com.threerings.presents.net.ThrottleUpdatedMessage; import com.threerings.presents.net.TransmitDatagramsRequest; import com.threerings.presents.net.UnsubscribeRequest; import com.threerings.presents.net.UnsubscribeResponse; import com.threerings.presents.net.UpdateThrottleMessage; import com.threerings.presents.server.net.Connection; import com.threerings.presents.server.net.ConnectionManager; import static com.threerings.presents.Log.log; /** * Represents a client session in the server. It is associated with a connection instance (while * the client is connected) and acts as the intermediary for the remote client in terms of passing * along events forwarded by the client, ensuring that subscriptions are maintained on behalf of * the client and that events are forwarded to the client. * * <p><em>A note on synchronization:</em> the client object is structured so that its * <code>Subscriber</code> implementation (which is called from the dobjmgr thread) can proceed * without synchronization. This does not overlap with its other client duties which are called * from the conmgr thread and therefore also need not be synchronized. */ public class PresentsSession implements Connection.MessageHandler, ClientResolutionListener { /** Used by {@link PresentsSession#setUsername} to report success or failure. */ public static interface UserChangeListener { /** Called when the new client object has been resolved and the new client object reported * to the client, but the old one has not yet been destroyed. Any events delivered on this * callback to the old client object will be delivered. * * @param rl when this method is finished with its business and the old client object can * be destroyed, the result listener should be called. */ void changeReported (ClientObject newObji, ResultListener<Void> rl); /** Called when the user change is completed, the old client object is destroyed and all * updates are committed. */ void changeCompleted (ClientObject newObj); /** Called if some failure occurs during the user change process. */ void changeFailed (Exception cause); } /** * Returns the credentials used to authenticate this session. */ public Credentials getCredentials () { return _areq.getCredentials(); } /** * Returns the time zone in which the client is operating. */ public TimeZone getTimeZone () { return _areq.getTimeZone(); } /** * Returns true if this session has been disconnected for sufficiently long that it should be * forcibly ended. */ public boolean checkExpired (long now) { return (getConnection() == null && (now - _networkStamp > getFlushTime())); } /** * Returns the time at which this client started their network session. */ public long getSessionStamp () { return _sessionStamp; } /** * Returns the time at which this client most recently connected or disconnected. */ public long getNetworkStamp () { return _networkStamp; } /** * Returns the username with which this client authenticated. Note: if {@link #setUsername} has * been called this may differ from {@link #getClientObject}.username. */ public Name getAuthName () { return _authname; } /** * Returns the address of the connected client or null if this client is not connected. */ public InetAddress getInetAddress () { Connection conn = getConnection(); return (conn == null) ? null : conn.getInetAddress(); } /** * Checks whether the client has requested that datagram transmission be enabled. */ public boolean getTransmitDatagrams () { Connection conn = getConnection(); return conn != null && conn.getTransmitDatagrams(); } /** * Configures this session with a custom class loader that will be used when unserializing * classes from the network. */ public void setClassLoader (ClassLoader loader) { _loader = loader; Connection conn = getConnection(); if (conn != null) { conn.setClassLoader(loader); } } /** * Configures the rate at which incoming messages are throttled for this client. This will * communicate the new limit to the client and begin enforcing the limit when the client has * acknowledged the new limit. * * <p><em>Note:</em> this means that a hacked client can refuse to ACK message rate reductions * and continue to use the most generous rate ever assigned to it. Don't increase the throttle * beyond the default for untrusted clients. This mechanism exists so that trusted clients can * have their throttle relaxed in a robust manner which will not result in disconnects if the * client happens to be at or near the throttle limit when the throttle is reduced. */ @EventThread public void setIncomingMessageThrottle (int messagesPerSec) { synchronized(_pendingThrottles) { _pendingThrottles.add(messagesPerSec); } postMessage(new UpdateThrottleMessage(messagesPerSec)); // when we get a ThrottleUpdatedMessage from the client, we'll apply the new throttle } /** * <em>Danger:</em> this method is not for general consumption. This changes the username of * the client, but should only be done very early in a user's session, when you know that no * one has mapped the user based on their username or has in any other way made use of their * username in a way that will break. However, it should not be done <em>too</em> early in the * session. The client must be fully resolved. * * <p> It exists to support systems wherein a user logs in with an account username and then * chooses a "screen name" by which they will play (often from a small set of available * "characters" available per account). This will take care of remapping the username to client * object mappings that were made by the Presents services when the user logs on, but anything * else that has had its grubby mits on the username will be left to its own devices, hence the * care that must be exercised when using this method. * * @param ucl an entity that will (optionally) be notified when the username conversion process * is complete. */ public void setUsername (Name username, final UserChangeListener ucl) { ClientResolutionListener clr = new ClientResolutionListener() { public void clientResolved (final Name username, final ClientObject clobj) { // if they old client object is gone by now, they ended their session while we were // switching, so freak out if (_clobj == null) { log.warning("Client disappeared before we could complete the switch to a " + "new client object", "ousername", clobj.username, "nusername", username); _clmgr.releaseClientObject(username); Exception error = new Exception("Early withdrawal"); resolutionFailed(username, error); return; } // call down to any derived classes clientObjectWillChange(_clobj, clobj); // let the caller know that we've got some new business if (ucl != null) { ucl.changeReported(clobj, new ResultListener<Void>() { public void requestCompleted (Void result) { finishResolved(username, clobj); } public void requestFailed (Exception cause) { finishResolved(username, clobj); } }); } else { finishResolved(username, clobj); } } /** * Finish the final phase of the switch. */ protected void finishResolved (Name username, ClientObject clobj) { // let the client know that the rug has been yanked out from under their ass Object[] args = new Object[] { clobj.getOid() }; _clobj.postMessage(ClientObject.CLOBJ_CHANGED, args); // release our old client object; this will destroy it _clmgr.releaseClientObject(_clobj.username); // update our internal fields _clobj = clobj; // call down to any derived classes clientObjectDidChange(_clobj); // let our listener know we're groovy if (ucl != null) { ucl.changeCompleted(_clobj); } } public void resolutionFailed (Name username, Exception reason) { log.warning("Unable to resolve new client object", "oldname", _clobj.username, "newname", username, "reason", reason, reason); // let our listener know we're hosed if (ucl != null) { ucl.changeFailed(reason); } } }; // resolve the new client object _clmgr.resolveClientObject(username, clr); } /** * <em>Double Danger:</em> this method is not for general consumption. Like * {@code #setUsername}, this changes the username of the client, but unlike setUsername, it * does it in the existing client object. Care must be taken to ensure that any client or * server code either doesn't map things based on username before this call, or that it's * updated to reflect the change. * * @return - true if the client was successfully renamed, false otherwise */ public boolean updateUsername (Name username) { return _clmgr.renameClientObject(_clobj.username, username); } /** * returns the client object that is associated with this client. */ public ClientObject getClientObject () { return _clobj; } /** * Forcibly terminates a client's session. This must be called from the dobjmgr thread. */ @EventThread public void endSession () { // queue up a request for our connection to be closed (if we have a connection, that is) Connection conn = getConnection(); if (conn != null) { // go ahead and clear out our connection now to prevent funniness setConnection(null); // have the connection manager close our connection when it is next convenient _conmgr.closeConnection(conn); } // if we don't have a client object, we failed to resolve in the first place, in which case // we have to cope as best we can if (_clobj != null) { // and clean up after ourselves try { sessionDidEnd(); } catch (Exception e) { log.warning("Choked in sessionDidEnd " + this + ".", e); } // release (and destroy) our client object _clmgr.releaseClientObject(_clobj.username); // we only report that our session started if we managed to resolve our client object, // so we only report that it ended in the same circumstance _clmgr.clientSessionDidEnd(this); } // we always want to clear ourselves out of the client manager _clmgr.clearSession(this); // clear out the client object so that we know the session is over _clobj = null; } /** * This is called when the server is shut down in the middle of a client session. In this * circumstance, {@link #endSession} will <em>not</em> be called and so any persistent data * that might normally be flushed at the end of a client's session should likely be flushed * here. */ public void shutdown () { // if the client is connected, we need to fake the computation of their final connect time // because we won't be closing their socket normally if (getConnection() != null) { long now = System.currentTimeMillis(); _connectTime += ((now - _networkStamp) / 1000); } } // from interface ClientResolutionListener public void clientResolved (Name username, ClientObject clobj) { // we'll be keeping this bad boy _clobj = clobj; // if our connection was closed while we were resolving our client object, then just // abandon ship if (getConnection() == null) { log.info("Session ended before client object could be resolved " + this + "."); endSession(); return; } // finish up our regular business sessionWillStart(); sendBootstrap(); // let the client manager know that we're operational _clmgr.clientSessionDidStart(this); } // from interface ClientResolutionListener public void resolutionFailed (Name username, Exception reason) { if (reason instanceof ClientResolver.ClientDisconnectedException) { log.info("Client disconnected during resolution", "who", who()); } else { // urk; nothing to do but complain and get the f**k out of dodge log.warning("Unable to resolve client", "who", who(), reason); } // end the session now to prevent danglage endSession(); } // from interface Connection.MessageHandler public void handleMessage (Message message) { _messagesIn++; // count 'em up! // if the client has been getting crazy with the cheeze whiz, stick a fork in them; the // first time through we end our session, subsequently _throttle is null and we just drop // any messages that come in until we've fully shutdown if (_throttle == null) { // log.info("Dropping message from force-quit client", "conn", getConnection(), // "msg", message); return; } else if (_throttle.throttleOp(message.received)) { handleThrottleExceeded(); } // we dispatch to a message dispatcher that is specialized for the particular class of // message that we received MessageDispatcher disp = _disps.get(message.getClass()); if (disp == null) { log.warning("No dispatcher for message", "msg", message); return; } // otherwise pass the message on to the dispatcher disp.dispatch(this, message); } /** * Called when {@link #setUsername} has been called and the new client object is about to be * applied to this client. The old client object will not yet have been destroyed, so any final * events can be sent along prior to the new object being put into effect. */ protected void clientObjectWillChange ( ClientObject oldClobj, ClientObject newClobj) { } /** * Called after the new client object has been committed to this client due to a call to {@link * #setUsername}. */ protected void clientObjectDidChange (ClientObject newClobj) { } /** * Initializes this client instance with the specified username, connection instance and client * object and begins a client session. */ protected void startSession (Name authname, AuthRequest req, Connection conn, Object authdata) { _authname = authname; _areq = req; _authdata = authdata; setConnection(conn); // resolve our client object before we get fully underway _clmgr.resolveClientObject(_authname, this); // make a note of our session start time _sessionStamp = System.currentTimeMillis(); } /** * Called by the client manager when a new connection arrives that authenticates as this * already established client. This must only be called from the congmr thread. */ protected void resumeSession (AuthRequest req, Connection conn) { // check to see if we've already got a connection object, in which case it's probably stale Connection oldconn = getConnection(); if (oldconn != null && !oldconn.isClosed()) { log.info("Closing stale connection", "old", oldconn, "new", conn); // close the old connection (which results in everything being properly unregistered) oldconn.close(); } // note our new auth request (so that we can deliver the proper bootstrap services) _areq = req; // start using the new connection setConnection(conn); // if a client connects, drops the connection and reconnects within the span of a very // short period of time, we'll find ourselves in resumeSession() before their client object // was resolved from the initial connection; in such a case, we can simply bail out here // and let the original session establishment code take care of initializing this resumed // session if (_clobj == null) { log.info("Rapid-fire reconnect caused us to arrive in resumeSession() before the " + "original session resolved its client object " + this + "."); return; } // we need to get onto the dobj thread so that we can finalize resumption of the session _omgr.postRunnable(new Runnable() { public void run () { // now that we're on the dobjmgr thread we can resume our session resumption finishResumeSession(); } }); } /** * This is called from the dobjmgr thread to complete the session resumption. We call some call * backs and send the bootstrap info to the client. */ @EventThread protected void finishResumeSession () { // if we have no client object for whatever reason; we're hosed, shut ourselves down if (_clobj == null) { log.info("Missing client object for resuming session " + this + "."); endSession(); return; } // let derived classes do any session resuming sessionWillResume(); // send off a bootstrap notification immediately as we've already got our client object sendBootstrap(); log.info("Session resumed " + this + "."); } /** * Queues up a runnable on the object manager thread where we can safely end the session. */ @AnyThread protected void safeEndSession () { if (!_omgr.isRunning()) { log.info("Dropping end session request as we're shutting down " + this + "."); } else { _omgr.postRunnable(new Runnable() { public void run () { endSession(); } }); } } /** * Creates our incoming message throttle. Use {@link #setIncomingMessageThrottle} to adjust the * throttle for running clients. */ protected Throttle createIncomingMessageThrottle () { // see throttleUpdated() for details on these numbers return new Throttle(10*(Client.DEFAULT_MSGS_PER_SECOND+1), 10*1000L); } /** * Called when a client exceeds their allotted incoming messages per second throttle. */ protected void handleThrottleExceeded () { log.warning("Client exceeded incoming message throttle, disconnecting", "client", this, "throttle", _throttle); safeEndSession(); _throttle = null; } /** * Makes a note that this client is no longer subscribed to this object. The subscription map * is used to clean up after the client when it goes away. */ protected synchronized void unmapSubscrip (int oid) { ClientProxy rec; synchronized (_subscrips) { rec = _subscrips.remove(oid); } if (rec != null) { rec.unsubscribe(); } else { log.warning("Missing subscription in unmap", "client", this, "oid", oid); } } /** * Clears out the tracked client subscriptions. Called when the client goes away and shouldn't * be called otherwise. */ protected void clearSubscrips (boolean verbose) { for (ClientProxy rec : _subscrips.values()) { if (verbose) { log.info("Clearing subscription", "client", this, "obj", rec.object.getOid()); } rec.unsubscribe(); } _subscrips.clear(); } /** * Called when the client session is first started. The client object has been created at this * point and after this method is executed, the bootstrap information will be sent to the * client which will trigger the start of the session. Derived classes that override this * method should be sure to call <code>super.sessionWillStart</code>. * * <p><em>Note:</em> This function will be called on the dobjmgr thread which means that object * manipulations are OK, but client instance manipulations must done carefully. */ @EventThread protected void sessionWillStart () { // configure a specific access controller for the client object _clobj.setAccessController(PresentsObjectAccess.CLIENT); } /** * Called when the client resumes a session (after having disconnected and reconnected). After * this method is executed, the bootstrap information will be sent to the client which will * trigger the resumption of the session. Derived classes that override this method should be * sure to call <code>super.sessionWillResume</code>. * * <p><em>Note:</em> This function will be called on the dobjmgr thread which means that object * manipulations are OK, but client instance manipulations must done carefully. */ @EventThread protected void sessionWillResume () { } /** * Called when the client session ends (either because the client logged off or because the * server forcibly terminated the session). Derived classes that override this method should * be sure to call <code>super.sessionDidEnd</code>. * * <p><em>Note:</em> This function will be called on the dobjmgr thread which means that object * manipulations are OK, but client instance manipulations must done carefully. */ @EventThread protected void sessionDidEnd () { // clear out our subscriptions so that we don't get a complaint about inability to forward // the object destroyed event we're about to generate clearSubscrips(false); } /** * Called to inform derived classes when the client has subscribed to a distributed object. */ @EventThread protected void subscribedToObject (DObject object) { } /** * Called to inform derived classes when the client has unsubscribed from a distributed object. */ @EventThread protected void unsubscribedFromObject (DObject object) { } /** * This is called once we have a handle on the client distributed object. It sends a bootstrap * notification to the client with all the information it will need to interact with the * server. */ protected void sendBootstrap () { // log.info("Sending bootstrap " + this + "."); // create and populate our bootstrap data BootstrapData data = createBootstrapData(); populateBootstrapData(data); // create a send bootstrap notification postMessage(new BootstrapNotification(data)); } /** * Derived client classes can override this member to create derived bootstrap data classes * that contain extra bootstrap information, if desired. */ protected BootstrapData createBootstrapData () { return new BootstrapData(); } /** * Derived client classes can override this member to populate the bootstrap data with * additional information. They should be sure to call <code>super.populateBootstrapData</code> * before doing their own populating, however. * * <p><em>Note:</em> This function will be called on the dobjmgr thread which means that object * manipulations are OK, but client instance manipulations must be done carefully. */ protected void populateBootstrapData (BootstrapData data) { // give them the connection id Connection conn = getConnection(); if (conn != null) { data.connectionId = conn.getConnectionId(); } else { log.warning("Connection disappeared before we could send bootstrap response.", "client", this); return; // stop here as we're just going to throw away this bootstrap } // and the client object id data.clientOid = _clobj.getOid(); // fill in the list of bootstrap services if (_areq.getBootGroups() == null) { log.warning("Client provided no invocation service boot groups? " + this); data.services = Lists.newArrayList(); } else { data.services = _invmgr.getBootstrapServices(_areq.getBootGroups()); } } /** * Called by the connection manager when this client's connection is unmapped. That may be * because of a connection failure (in which case this call will be followed up by a call to * <code>connectionFailed</code>) or it may be because of an orderly closing of the * connection. In either case, the client can deal with its lack of a connection in this * method. This is invoked by the conmgr thread and should behave accordingly. */ protected void wasUnmapped () { // clear out our connection reference setConnection(null); // if we are being closed after the omgr has shutdown, then just stop here; the whole world // is about to come to a screeching halt anyway if (_omgr.isRunning()) { // clear out our subscriptions: we need to do this on the dobjmgr thread. it is // important that we do this *after* we clear out our connection reference. once the // connection ref is null, no more subscriptions will be processed (even those that // were queued up before the connection went away) _omgr.postRunnable(new Runnable() { public void run () { sessionConnectionClosed(); } }); } } /** * Called on the dobjmgr thread when the connection associated with this session has been * closed and unmapped. If the user logged off before closing their connection, this will be * preceded by a call to {@link #sessionDidEnd}. */ @EventThread protected void sessionConnectionClosed () { // clear out our dobj subscriptions in case they weren't cleared by a call to sessionDidEnd clearSubscrips(false); } /** * Called by the connection manager when this client's connection fails. This is invoked on the * conmgr thread and should behave accordingly. */ protected void connectionFailed (IOException fault) { // nothing to do here, the client manager already complained about the failed connection } /** * Sets our connection reference in a thread safe way. Also establishes the back reference to * us as the connection's message handler. */ protected synchronized void setConnection (Connection conn) { // if our connection is being cleared out, record the amount of time we were connected to // our total connected time long now = System.currentTimeMillis(); if (_conn != null && conn == null) { _connectTime += ((now - _networkStamp) / 1000); } // keep a handle to the new connection _conn = conn; // tell the connection to pass messages on to us (if we're setting a connection rather than // clearing one out) if (_conn != null) { _conn.setMessageHandler(this); // configure any active custom class loader if (_loader != null) { _conn.setClassLoader(_loader); } } // make a note that our network status changed _networkStamp = now; } protected synchronized Connection getConnection () { return _conn; } /** * Callable from non-dobjmgr thread, this queues up a runnable on the dobjmgr thread to post * the supplied message to this client. */ protected final void safePostMessage (final DownstreamMessage msg) { _omgr.postRunnable(new Runnable() { public void run () { postMessage(msg); } }); } /** Queues a message for delivery to the client. */ protected boolean postMessage (DownstreamMessage msg) { Connection conn = getConnection(); if (conn != null) { conn.postMessage(msg); _messagesOut++; // count 'em up! return true; } // don't log dropped messages unless we're dropping a lot of them (meaning something is // still queueing messages up for this dead client even though it shouldn't be) if (++_messagesDropped % 50 == 0) { log.warning("Dropping many messages?", "client", this, "count", _messagesDropped); } // make darned sure we don't have any remaining subscriptions if (_subscrips.size() > 0) { // log.warning("Clearing stale subscriptions", "client", this, // "subscrips", _subscrips.size()); clearSubscrips(_messagesDropped > 10); } return false; } /** * Notifies this client that its throttle was updated. */ protected void throttleUpdated () { int messagesPerSec; synchronized(_pendingThrottles) { if (_pendingThrottles.size() == 0) { log.warning("Received throttleUpdated but have no pending throttles", "client", this); return; } messagesPerSec = _pendingThrottles.remove(0); } log.info("Applying updated throttle", "client", this, "msgsPerSec", messagesPerSec); // We set our hard throttle over a 10 second period instead of a 1 second period to // account for periods of network congestion that might cause otherwise properly // throttled messages to bunch up while they're "on the wire"; we also add a one // message buffer so that if the client is right up against the limit, we don't end // up quibbling over a couple of milliseconds _throttle.reinit(10*messagesPerSec+1, 10*1000L); } @Override public String toString () { StringBuilder buf = new StringBuilder("["); toString(buf); return buf.append("]").toString(); } protected String who () { return (_authname == null) ? "null" : (_authname.getClass().getSimpleName() + "(" + _authname + ")"); } /** * Returns the duration (in milliseconds) after which a disconnected session will be terminated * and flushed. */ protected long getFlushTime () { return DEFAULT_FLUSH_TIME; } /** * Derived classes override this to augment stringification. */ protected void toString (StringBuilder buf) { buf.append("who=").append(who()); buf.append(", conn=").append(getConnection()); buf.append(", in=").append(_messagesIn); buf.append(", out=").append(_messagesOut); } /** * Creates a properly initialized inner-class proxy subscriber. */ protected ClientProxy createProxySubscriber () { return new ClientProxy(); } /** Used to track information about an object subscription. */ protected class ClientProxy implements ProxySubscriber { public DObject object; public void unsubscribe () { object.removeSubscriber(this); unsubscribedFromObject(object); } // from interface ProxySubscriber public void objectAvailable (DObject dobj) { if (postMessage(new ObjectResponse<DObject>(dobj))) { _firstEventId = _omgr.getNextEventId(false); object = dobj; synchronized (_subscrips) { // make a note of this new subscription _subscrips.put(dobj.getOid(), this); } subscribedToObject(dobj); } else { // if we failed to send the object response, unsubscribe dobj.removeSubscriber(this); } } // from interface ProxySubscriber public void requestFailed (int oid, ObjectAccessException cause) { postMessage(new FailureResponse(oid, cause.getMessage())); } // from interface ProxySubscriber public void eventReceived (DEvent event) { if (event instanceof PresentsDObjectMgr.AccessObjectEvent) { log.warning("Ignoring event that shouldn't be forwarded " + event + ".", new Exception()); return; } // if this message was posted before we received this object and has already been // applied, then this event has already been applied to this object and we should not // forward it, it is equivalent to all the events applied to the object before we // became a subscriber if (event.eventId < _firstEventId) { return; } postMessage(new EventNotification(event)); } // from interface ProxySubscriber public ClientObject getClientObject () { return PresentsSession.this.getClientObject(); } protected long _firstEventId; } /** * Message dispatchers are used to dispatch each different type of message. We can look the * dispatcher up in a table and invoke it through an overloaded member which is faster (so we * think) than doing a bunch of instanceofs. */ protected static interface MessageDispatcher { /** * Dispatch the supplied message for the specified client. */ void dispatch (PresentsSession client, Message mge); } /** * Processes subscribe requests. */ protected static class SubscribeDispatcher implements MessageDispatcher { public void dispatch (PresentsSession client, Message msg) { SubscribeRequest req = (SubscribeRequest)msg; // log.info("Subscribing", "client", client, "oid", req.getOid()); // forward the subscribe request to the omgr for processing client._omgr.subscribeToObject(req.getOid(), client.createProxySubscriber()); } } /** * Processes unsubscribe requests. */ protected static class UnsubscribeDispatcher implements MessageDispatcher { public void dispatch (PresentsSession client, Message msg) { UnsubscribeRequest req = (UnsubscribeRequest)msg; int oid = req.getOid(); // log.info("Unsubscribing " + client + "", "oid", oid); // unsubscribe from the object and clear out our proxy client.unmapSubscrip(oid); // post a response to the client letting them know that we will no longer send them // events regarding this object client.safePostMessage(new UnsubscribeResponse(oid)); } } /** * Processes forward event requests. */ protected static class ForwardEventDispatcher implements MessageDispatcher { public void dispatch (PresentsSession client, Message msg) { ForwardEventRequest req = (ForwardEventRequest)msg; DEvent fevt = req.getEvent(); // freak not out if a message arrives from a client just after their session ended ClientObject clobj = client.getClientObject(); if (clobj == null) { log.info("Dropping event that arrived after client disconnected " + fevt + "."); return; } // fill in the proper source oid fevt.setSourceOid(clobj.getOid()); // log.info("Forwarding event", "client", client, "event", fevt); // forward the event to the omgr for processing client._omgr.postEvent(fevt); } } /** * Processes ping requests. */ protected static class PingDispatcher implements MessageDispatcher { public void dispatch (PresentsSession client, Message msg) { // send a pong response using the transport with which the message was received PingRequest req = (PingRequest)msg; if (PING_DEBUG) { log.info("Got ping, ponging", "client", client.getAuthName()); } client.safePostMessage(new PongResponse(req.getUnpackStamp(), req.getTransport())); } } /** * Processes datagram transmission requests. */ protected static class TransmitDatagramsDispatcher implements MessageDispatcher { public void dispatch (PresentsSession client, Message msg) { log.debug("Client requested datagram transmission", "client", client); client.getConnection().setTransmitDatagrams(true); } } /** * Processes throttle updated messages. */ protected static class ThrottleUpdatedDispatcher implements MessageDispatcher { public void dispatch (final PresentsSession client, Message msg) { log.debug("Client ACKed throttle update", "client", client); client.throttleUpdated(); } } /** * Processes logoff requests. */ protected static class LogoffDispatcher implements MessageDispatcher { public void dispatch (final PresentsSession client, Message msg) { log.debug("Client requested logoff", "client", client); client.safeEndSession(); } } @Inject protected ClientManager _clmgr; @Inject protected ConnectionManager _conmgr; @Inject protected PresentsDObjectMgr _omgr; @Inject protected InvocationManager _invmgr; protected AuthRequest _areq; protected Object _authdata; protected Name _authname; protected Connection _conn; protected ClientObject _clobj; protected IntMap<ClientProxy> _subscrips = IntMaps.newHashIntMap(); protected ClassLoader _loader; /** The time at which this client started their session. */ protected long _sessionStamp; /** The time at which this client most recently connected or disconnected. */ protected long _networkStamp; /** The total number of seconds for which the user was connected to the server in this * session. */ protected int _connectTime; /** Prevent the client from sending too many messages too frequently. */ protected Throttle _throttle = createIncomingMessageThrottle(); /** Used to keep throttles around until we know the client is ready for us to apply them. */ protected List<Integer> _pendingThrottles = Lists.newArrayList(); // keep these for kicks and giggles protected int _messagesIn; protected int _messagesOut; protected int _messagesDropped; /** A mapping of message dispatchers. */ protected static Map<Class<?>, MessageDispatcher> _disps = Maps.newHashMap(); /** Default period a user is allowed after disconn before their session is forcibly ended. */ protected static final long DEFAULT_FLUSH_TIME = 7 * 60 * 1000L; // TEMP protected static final boolean PING_DEBUG = Boolean.getBoolean("ping_debug"); // register our message dispatchers static { _disps.put(SubscribeRequest.class, new SubscribeDispatcher()); _disps.put(UnsubscribeRequest.class, new UnsubscribeDispatcher()); _disps.put(ForwardEventRequest.class, new ForwardEventDispatcher()); _disps.put(PingRequest.class, new PingDispatcher()); _disps.put(TransmitDatagramsRequest.class, new TransmitDatagramsDispatcher()); _disps.put(ThrottleUpdatedMessage.class, new ThrottleUpdatedDispatcher()); _disps.put(LogoffRequest.class, new LogoffDispatcher()); } }
package org.jaxen.function; import java.util.List; import org.jaxen.Context; import org.jaxen.Function; import org.jaxen.FunctionCallException; import org.jaxen.Navigator; public class NormalizeSpaceFunction implements Function { /** * Returns the string-value of the first item in <code>args</code> * after removing all leading and trailing white space, and * replacing each other sequence of whitespace by a single space. * Whitespace consists of the characters space (0x32), carriage return (0x0D), * linefeed (0x0A), and tab (0x09). * * @param context the context at the point in the * expression when the function is called * @param args a list that contains exactly one item * * @return a normalized <code>String</code> * * @throws FunctionCallException if <code>args</code> does not have length one */ public Object call(Context context, List args) throws FunctionCallException { if (args.size() == 0) { return evaluate( context.getNodeSet(), context.getNavigator() ); } else if (args.size() == 1) { return evaluate( args.get(0), context.getNavigator() ); } throw new FunctionCallException( "normalize-space() cannot have more than one argument" ); } /** * Returns the string-value of <code>strArg</code> after removing * all leading and trailing white space, and * replacing each other sequence of whitespace by a single space. * Whitespace consists of the characters space (0x32), carriage return (0x0D), * linefeed (0x0A), and tab (0x09). * * @param strArg the object whose string-value is normalized * @param nav the context at the point in the * expression when the function is called * * @return the normalized string-value */ public static String evaluate(Object strArg, Navigator nav) { String str = StringFunction.evaluate( strArg, nav ); char[] buffer = str.toCharArray(); int write = 0; int lastWrite = 0; boolean wroteOne = false; int read = 0; while (read < buffer.length) { if (isXMLSpace(buffer[read])) { if (wroteOne) { buffer[write++] = ' '; } do { read++; } while(read < buffer.length && isXMLSpace(buffer[read])); } else { buffer[write++] = buffer[read++]; wroteOne = true; lastWrite = write; } } return new String(buffer, 0, lastWrite); } private static boolean isXMLSpace(char c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t'; } }
package com.ejlchina.searcher; import com.ejlchina.searcher.util.MapUtils; import org.junit.Assert; import org.junit.Test; import java.util.HashMap; import java.util.List; import java.util.Map; public class TestCase1 { public static class Bean { private long id; private String name; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } @Test public void test1() { SqlExecutor sqlExecutor = new SqlExecutor() { @Override public <T> SqlResult<T> execute(SearchSql<T> searchSql) { Assert.assertEquals("select name c_1, id c_0 from bean limit ?, ?", searchSql.getListSqlString()); List<Object> listParams = searchSql.getListSqlParams(); Assert.assertEquals(2, listParams.size()); Assert.assertEquals(0L, listParams.get(0)); Assert.assertEquals(15, listParams.get(1)); Assert.assertEquals("select count(*) s_count from bean", searchSql.getClusterSqlString()); Assert.assertEquals(0, searchSql.getClusterSqlParams().size()); Assert.assertEquals("s_count", searchSql.getCountAlias()); Assert.assertEquals(0, searchSql.getSummaryAliases().size()); return new SqlResult<>(searchSql); } }; MapSearcher mapSearcher = SearcherBuilder.mapSearcher().sqlExecutor(sqlExecutor).build(); mapSearcher.search(Bean.class, new HashMap<>()); mapSearcher.search(Bean.class, null); BeanSearcher beanSearcher = SearcherBuilder.beanSearcher().sqlExecutor(sqlExecutor).build(); beanSearcher.search(Bean.class, new HashMap<>()); beanSearcher.search(Bean.class, null); } @Test public void test2() { SqlExecutor sqlExecutor = new SqlExecutor() { @Override public <T> SqlResult<T> execute(SearchSql<T> searchSql) { System.out.println(searchSql.getListSqlString()); System.out.println(searchSql.getListSqlParams()); Assert.assertEquals("select name c_1, id c_0 from bean where (id = ?) limit ?, ?", searchSql.getListSqlString()); List<Object> listParams = searchSql.getListSqlParams(); Assert.assertEquals(3, listParams.size()); Assert.assertEquals(1, listParams.get(0)); Assert.assertEquals(0L, listParams.get(1)); Assert.assertEquals(15, listParams.get(2)); System.out.println(searchSql.getClusterSqlString()); Assert.assertEquals("select count(*) s_count from bean where (id = ?)", searchSql.getClusterSqlString()); List<Object> clusterSqlParams = searchSql.getClusterSqlParams(); System.out.println(clusterSqlParams); Assert.assertEquals(1, clusterSqlParams.size()); Assert.assertEquals(1, clusterSqlParams.get(0)); System.out.println(searchSql.getCountAlias()); Assert.assertEquals("s_count", searchSql.getCountAlias()); System.out.println(searchSql.getSummaryAliases()); Assert.assertEquals(0, searchSql.getSummaryAliases().size()); return new SqlResult<>(searchSql); } }; MapSearcher mapSearcher = SearcherBuilder.mapSearcher().sqlExecutor(sqlExecutor).build(); BeanSearcher beanSearcher = SearcherBuilder.beanSearcher().sqlExecutor(sqlExecutor).build(); Map<String, Object> params1 = new HashMap<>(); params1.put("id", 1); Map<String, Object> params2 = MapUtils.builder().field(Bean::getId, 1).build(); mapSearcher.search(Bean.class, params1); mapSearcher.search(Bean.class, params2); beanSearcher.search(Bean.class, params1); beanSearcher.search(Bean.class, params2); } }
package org.dellroad.stuff.vaadin7; import com.vaadin.server.DeploymentConfiguration; import com.vaadin.server.ServiceException; import com.vaadin.server.VaadinRequest; import com.vaadin.server.VaadinServlet; import com.vaadin.server.VaadinServletService; import com.vaadin.server.VaadinSession; import java.util.ArrayList; import java.util.List; import java.util.Properties; import java.util.WeakHashMap; import javax.servlet.ServletConfig; import javax.servlet.ServletException; /** * A {@link VaadinServlet} that associates and manages a Spring * {@link org.springframework.web.context.ConfigurableWebApplicationContext} with each * {@link com.vaadin.server.VaadinSession} (aka, "Vaadin application" in the old terminology). * * <p> * The {@code vaadinContextConfigLocation} servlet parameter may be used to specify the Spring XML config * file location(s). For example: * * <blockquote><pre> * &lt;servlet&gt; * &lt;servlet-name&gt;My Vaadin App&lt;/servlet-name&gt; * &lt;servlet-class&gt;org.dellroad.stuff.vaadin7.SpringVaadinServlet&lt;/servlet-class&gt; * &lt;init-param&gt; * &lt;param-name&gt;UI&lt;/param-name&gt; * &lt;param-value&gt;com.example.MyApplicationUI&lt;/param-value&gt; * &lt;/init-param&gt; * &lt;init-param&gt; * &lt;param-name&gt;configLocation&lt;/param-name&gt; * &lt;param-value&gt;classpath:com/example/MyApplicationContext.xml&lt;/param-value&gt; * &lt;/init-param&gt; * &lt;/servlet&gt; * </pre></blockquote> * </p> * * <p> * The main function of this servlet is to create and register a {@link SpringVaadinSessionListener} as a listener on the * {@link com.vaadin.server.VaadinService} associated with this servlet. The {@link SpringVaadinSessionListener} in turn detects * the creation and destruction of Vaadin application instances (represented by {@link com.vaadin.server.VaadinSession} * instances) and does the work of managing the associated Spring application contexts. * </p> * * <p> * Use of this servlet in place of the standard Vaadin servlet is required for the {@link VaadinConfigurable @VaadinConfigurable} * annotation to work. * </p> * * <p> * Supported URL parameters: * <div style="margin-left: 20px;"> * <table border="1" cellpadding="3" cellspacing="0"> * <tr bgcolor="#ccffcc"> * <th align="left">Parameter Name</th> * <th align="left">Required?</th> * <th align="left">Description</th> * </tr> * <tr> * <td>{@code applicationName}</td> * <td align="center">No</td> * <td> * Vaadin application name. Used for logging purposes and as the name of the XML application context file * when {@code configLocation} is not specified. If this parameter is not specified, the * name of the servlet is used. * </td> * </tr> * <tr> * <td>{@code configLocation}</td> * <td align="center">No</td> * <td> * Location of Spring application context XML file(s). Multiple locations are separated by whitespace. * If omitted, {@code /WEB-INF/ServletName.xml} is used, where {@code ServletName} is the name of the Vaadin * application (see {@code applicationName}). * </td> * </tr> * <tr> * <td>{@code listenerClass}</td> * <td align="center">No</td> * <td> * Specify the name of a custom class extending {@link SpringVaadinSessionListener} and having the same constructor arguments. * If omitted, {@link SpringVaadinSessionListener} is used. * </td> * </tr> * <tr> * <td>{@code sessionTracking}</td> * <td align="center">No</td> * <td> * Boolean value that configures whether the {@link SpringVaadinSessionListener} should track Vaadin sessions; default * {@code false}. If set to {@code true}, then {@link #getSessions} can be used to access all active sessions. * Session tracking should not be used unless sessions are normally kept in memory; e.g., don't use session tracking * when sessions are being serialized and persisted. See also {@link VaadinSessionContainer}. * </td> * </tr> * <tr> * <td>{@code maxSessions}</td> * <td align="center">No</td> * <td> * Configures a limit on the number of simultaneous Vaadin sessions that may exist at one time. Going over this * limit will result in a {@link com.vaadin.server.ServiceException} being thrown. A zero or negative number * means there is no limit (this is the default). Ignored unless {@value #SESSION_TRACKING_PARAMETER} is set to {@code true}. * </td> * </tr> * </table> * </div> * </p> * * @see SpringVaadinSessionListener * @see VaadinConfigurable * @see VaadinApplication */ @SuppressWarnings("serial") public class SpringVaadinServlet extends VaadinServlet { /** * Servlet initialization parameter (<code>{@value #CONFIG_LOCATION_PARAMETER}</code>) used to specify * the location(s) of the Spring application context XML file(s). Multiple XML files may be separated by whitespace. * This parameter is optional. */ public static final String CONFIG_LOCATION_PARAMETER = "configLocation"; /** * Servlet initialization parameter (<code>{@value #LISTENER_CLASS_PARAMETER}</code>) used to specify * the name of an custom subclass of {@link SpringVaadinSessionListener}. * This parameter is optional. */ public static final String LISTENER_CLASS_PARAMETER = "listenerClass"; /** * Servlet initialization parameter (<code>{@value #APPLICATION_NAME_PARAMETER}</code>) used to specify * the name the application. * This parameter is optional. */ public static final String APPLICATION_NAME_PARAMETER = "applicationName"; /** * Servlet initialization parameter (<code>{@value #SESSION_TRACKING_PARAMETER}</code>) that enables * tracking of all Vaadin session. * This parameter is optional, and defaults to <code>false</code>. */ public static final String SESSION_TRACKING_PARAMETER = "sessionTracking"; /** * Servlet initialization parameter (<code>{@value #MAX_SESSIONS_PARAMETER}</code>) that configures the * maximum number of simultaneous Vaadin sessions. Requires {@link #SESSION_TRACKING_PARAMETER} to be set to {@code true}. * This parameter is optional, and defaults to zero, which means no limit. */ public static final String MAX_SESSIONS_PARAMETER = "maxSessions"; private final WeakHashMap<VaadinSession, Void> liveSessions = new WeakHashMap<VaadinSession, Void>(); private String servletName; @Override public void init(ServletConfig config) throws ServletException { this.servletName = config.getServletName(); if (this.servletName == null) throw new IllegalArgumentException("null servlet name"); super.init(config); } @Override protected void servletInitialized() throws ServletException { // Sanity check if (this.servletName == null) throw new IllegalArgumentException("servlet not initialized"); // Defer to superclass super.servletInitialized(); // Get params final VaadinServletService servletService = this.getService(); final Properties params = servletService.getDeploymentConfiguration().getInitParameters(); final String contextLocation = params.getProperty(CONFIG_LOCATION_PARAMETER); final String listenerClassName = params.getProperty(LISTENER_CLASS_PARAMETER); String applicationName = params.getProperty(APPLICATION_NAME_PARAMETER); if (applicationName == null) applicationName = this.servletName; // Detect listener class to use Class<? extends SpringVaadinSessionListener> listenerClass = SpringVaadinSessionListener.class; if (listenerClassName != null) { try { listenerClass = Class.forName(listenerClassName, false, Thread.currentThread().getContextClassLoader()) .asSubclass(SpringVaadinSessionListener.class); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new ServletException("error finding class " + listenerClassName, e); } } // Create session listener SpringVaadinSessionListener sessionListener; try { sessionListener = listenerClass.getConstructor(String.class, String.class) .newInstance(applicationName, contextLocation); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new ServletException("error instantiating " + listenerClass, e); } // Register session listener servletService.addSessionInitListener(sessionListener); servletService.addSessionDestroyListener(sessionListener); } @Override protected VaadinServletService createServletService(DeploymentConfiguration deploymentConfiguration) throws ServiceException { // Get session tracking parameters final Properties params = deploymentConfiguration.getInitParameters(); final boolean sessionTracking = Boolean.valueOf(params.getProperty(SESSION_TRACKING_PARAMETER)); int maxSessionsParam = 0; try { maxSessionsParam = Integer.parseInt(params.getProperty(MAX_SESSIONS_PARAMETER)); } catch (Exception e) { // ignore } final int maxSessions = maxSessionsParam; // If not tracking sessions, do the normal thing if (!sessionTracking) return super.createServletService(deploymentConfiguration); // Return a VaadinServletService that tracks sessions final VaadinServletService service = new VaadinServletService(this, deploymentConfiguration) { @Override protected VaadinSession createVaadinSession(VaadinRequest request) throws ServiceException { final VaadinSession session; synchronized (SpringVaadinServlet.this.liveSessions) { if (maxSessions > 0 && SpringVaadinServlet.this.liveSessions.size() >= maxSessions) throw new ServiceException("The maximum number of active sessions has been reached"); session = super.createVaadinSession(request); SpringVaadinServlet.this.liveSessions.put(session, null); } return session; } @Override public void fireSessionDestroy(VaadinSession session) { synchronized (SpringVaadinServlet.this.liveSessions) { SpringVaadinServlet.this.liveSessions.remove(session); } super.fireSessionDestroy(session); } }; service.init(); return service; } /** * Get all live {@link VaadinSession}s associated with this instance. * * @return live tracked sessions, or an empty collection if session tracking is not enabled * @see VaadinSessionContainer */ public List<VaadinSession> getSessions() { synchronized (this.liveSessions) { return new ArrayList<VaadinSession>(this.liveSessions.keySet()); } } public static SpringVaadinServlet getServlet(VaadinSession session) { if (session == null) throw new IllegalArgumentException("null session"); if (!(session.getService() instanceof VaadinServletService)) throw new IllegalStateException("the VaadinService associated with the session is not a VaadinServletService instance"); final VaadinServletService service = (VaadinServletService)session.getService(); if (!(service.getServlet() instanceof SpringVaadinServlet)) throw new IllegalStateException("the VaadinServlet associated with the session is not a SpringVaadinServlet instance"); return (SpringVaadinServlet)service.getServlet(); } }
package org.jdesktop.swingx.graphics; import java.awt.image.BufferedImage; import java.awt.image.ColorModel; import java.awt.image.Raster; import java.awt.image.WritableRaster; import java.awt.GraphicsConfiguration; import java.awt.Transparency; import java.awt.Graphics; import java.awt.GraphicsEnvironment; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.io.IOException; import java.net.URL; import javax.imageio.ImageIO; /** * <p><code>GraphicsUtilities</code> contains a set of tools to perform * common graphics operations easily. These operations are divided into * several themes, listed below.</p> * * <h2>Compatible Images</h2> * * <p>Compatible images can, and should, be used to increase drawing * performance. This class provides a number of methods to load compatible * images directly from files or to convert existing images to compatibles * images.</p> * * <h2>Creating Thumbnails</h2> * * <p>This class provides a number of methods to easily scale down images. * Some of these methods offer a trade-off between speed and result quality and * shouuld be used all the time. They also offer the advantage of producing * compatible images, thus automatically resulting into better runtime * performance.</p> * * <p>All these methodes are both faster than * {@link java.awt.Image#getScaledInstance(int, int, int)} and produce * better-looking results than the various <code>drawImage()</code> methods * in {@link java.awt.Graphics}, which can be used for image scaling.</p> * <h2>Image Manipulation</h2> * * <p>This class provides two methods to get and set pixels in a buffered image. * These methods try to avoid unmanaging the image in order to keep good * performance.</p> * * @author Romain Guy <romain.guy@mac.com> * @author rbair */ public class GraphicsUtilities { private GraphicsUtilities() { } // Returns the graphics configuration for the primary screen private static GraphicsConfiguration getGraphicsConfiguration() { return GraphicsEnvironment.getLocalGraphicsEnvironment(). getDefaultScreenDevice().getDefaultConfiguration(); } private static boolean isHeadless() { return GraphicsEnvironment.isHeadless(); } /** * <p>Returns a new <code>BufferedImage</code> using the same color model * as the image passed as a parameter. The returned image is only compatible * with the image passed as a parameter. This does not mean the returned * image is compatible with the hardware.</p> * * @param image the reference image from which the color model of the new * image is obtained * @return a new <code>BufferedImage</code>, compatible with the color model * of <code>image</code> */ public static BufferedImage createColorModelCompatibleImage(BufferedImage image) { ColorModel cm = image.getColorModel(); return new BufferedImage(cm, cm.createCompatibleWritableRaster(image.getWidth(), image.getHeight()), cm.isAlphaPremultiplied(), null); } /** * <p>Returns a new compatible image with the same width, height and * transparency as the image specified as a parameter. That is, the * returned BufferedImage will be compatible with the graphics hardware. * If this method is called in a headless environment, then * the returned BufferedImage will be compatible with the source * image.</p> * * @see java.awt.Transparency * @see #createCompatibleImage(int, int) * @see #createCompatibleImage(java.awt.image.BufferedImage, int, int) * @see #createCompatibleTranslucentImage(int, int) * @see #loadCompatibleImage(java.net.URL) * @see #toCompatibleImage(java.awt.image.BufferedImage) * @param image the reference image from which the dimension and the * transparency of the new image are obtained * @return a new compatible <code>BufferedImage</code> with the same * dimension and transparency as <code>image</code> */ public static BufferedImage createCompatibleImage(BufferedImage image) { return createCompatibleImage(image, image.getWidth(), image.getHeight()); } /** * <p>Returns a new compatible image of the specified width and height, and * the same transparency setting as the image specified as a parameter. * That is, the returned <code>BufferedImage</code> is compatible with * the graphics hardware. If the method is called in a headless * environment, then the returned BufferedImage will be compatible with * the source image.</p> * * @see java.awt.Transparency * @see #createCompatibleImage(java.awt.image.BufferedImage) * @see #createCompatibleImage(int, int) * @see #createCompatibleTranslucentImage(int, int) * @see #loadCompatibleImage(java.net.URL) * @see #toCompatibleImage(java.awt.image.BufferedImage) * @param width the width of the new image * @param height the height of the new image * @param image the reference image from which the transparency of the new * image is obtained * @return a new compatible <code>BufferedImage</code> with the same * transparency as <code>image</code> and the specified dimension */ public static BufferedImage createCompatibleImage(BufferedImage image, int width, int height) { return isHeadless() ? new BufferedImage(width, height, image.getType()) : getGraphicsConfiguration().createCompatibleImage(width, height, image.getTransparency()); } /** * <p>Returns a new opaque compatible image of the specified width and * height. That is, the returned <code>BufferedImage</code> is compatible with * the graphics hardware. If the method is called in a headless * environment, then the returned BufferedImage will be compatible with * the source image.</p> * * @see #createCompatibleImage(java.awt.image.BufferedImage) * @see #createCompatibleImage(java.awt.image.BufferedImage, int, int) * @see #createCompatibleTranslucentImage(int, int) * @see #loadCompatibleImage(java.net.URL) * @see #toCompatibleImage(java.awt.image.BufferedImage) * @param width the width of the new image * @param height the height of the new image * @return a new opaque compatible <code>BufferedImage</code> of the * specified width and height */ public static BufferedImage createCompatibleImage(int width, int height) { return isHeadless() ? new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB) : getGraphicsConfiguration().createCompatibleImage(width, height); } /** * <p>Returns a new translucent compatible image of the specified width and * height. That is, the returned <code>BufferedImage</code> is compatible with * the graphics hardware. If the method is called in a headless * environment, then the returned BufferedImage will be compatible with * the source image.</p> * * @see #createCompatibleImage(java.awt.image.BufferedImage) * @see #createCompatibleImage(java.awt.image.BufferedImage, int, int) * @see #createCompatibleImage(int, int) * @see #loadCompatibleImage(java.net.URL) * @see #toCompatibleImage(java.awt.image.BufferedImage) * @param width the width of the new image * @param height the height of the new image * @return a new translucent compatible <code>BufferedImage</code> of the * specified width and height */ public static BufferedImage createCompatibleTranslucentImage(int width, int height) { return isHeadless() ? new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB) : getGraphicsConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT); } /** * <p>Returns a new compatible image from a URL. The image is loaded from the * specified location and then turned, if necessary into a compatible * image.</p> * * @see #createCompatibleImage(java.awt.image.BufferedImage) * @see #createCompatibleImage(java.awt.image.BufferedImage, int, int) * @see #createCompatibleImage(int, int) * @see #createCompatibleTranslucentImage(int, int) * @see #toCompatibleImage(java.awt.image.BufferedImage) * @param resource the URL of the picture to load as a compatible image * @return a new translucent compatible <code>BufferedImage</code> of the * specified width and height * @throws java.io.IOException if the image cannot be read or loaded */ public static BufferedImage loadCompatibleImage(URL resource) throws IOException { BufferedImage image = ImageIO.read(resource); return toCompatibleImage(image); } /** * <p>Return a new compatible image that contains a copy of the specified * image. This method ensures an image is compatible with the hardware, * and therefore optimized for fast blitting operations.</p> * * <p>If the method is called in a headless environment, then the returned * <code>BufferedImage</code> will be the source image.</p> * * @see #createCompatibleImage(java.awt.image.BufferedImage) * @see #createCompatibleImage(java.awt.image.BufferedImage, int, int) * @see #createCompatibleImage(int, int) * @see #createCompatibleTranslucentImage(int, int) * @see #loadCompatibleImage(java.net.URL) * @param image the image to copy into a new compatible image * @return a new compatible copy, with the * same width and height and transparency and content, of <code>image</code> */ public static BufferedImage toCompatibleImage(BufferedImage image) { if (isHeadless()) { return image; } if (image.getColorModel().equals( getGraphicsConfiguration().getColorModel())) { return image; } BufferedImage compatibleImage = getGraphicsConfiguration().createCompatibleImage( image.getWidth(), image.getHeight(), image.getTransparency()); Graphics g = compatibleImage.getGraphics(); g.drawImage(image, 0, 0, null); g.dispose(); return compatibleImage; } public static BufferedImage createThumbnailFast(BufferedImage image, int newSize) { float ratio; int width = image.getWidth(); int height = image.getHeight(); if (width > height) { if (newSize >= width) { throw new IllegalArgumentException("newSize must be lower than" + " the image width"); } else if (newSize <= 0) { throw new IllegalArgumentException("newSize must" + " be greater than 0"); } ratio = (float) width / (float) height; width = newSize; height = (int) (newSize / ratio); } else { if (newSize >= height) { throw new IllegalArgumentException("newSize must be lower than" + " the image height"); } else if (newSize <= 0) { throw new IllegalArgumentException("newSize must" + " be greater than 0"); } ratio = (float) height / (float) width; height = newSize; width = (int) (newSize / ratio); } BufferedImage temp = createCompatibleImage(image, width, height); Graphics2D g2 = temp.createGraphics(); g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g2.drawImage(image, 0, 0, temp.getWidth(), temp.getHeight(), null); g2.dispose(); return temp; } public static BufferedImage createThumbnailFast(BufferedImage image, int newWidth, int newHeight) { if (newWidth >= image.getWidth() || newHeight >= image.getHeight()) { throw new IllegalArgumentException("newWidth and newHeight cannot" + " be greater than the image" + " dimensions"); } else if (newWidth <= 0 || newHeight <= 0) { throw new IllegalArgumentException("newWidth and newHeight must" + " be greater than 0"); } BufferedImage temp = createCompatibleImage(image, newWidth, newHeight); Graphics2D g2 = temp.createGraphics(); g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g2.drawImage(image, 0, 0, temp.getWidth(), temp.getHeight(), null); g2.dispose(); return temp; } public static BufferedImage createThumbnail(BufferedImage image, int newSize) { int width = image.getWidth(); int height = image.getHeight(); boolean isWidthGreater = width > height; if (isWidthGreater) { if (newSize >= width) { throw new IllegalArgumentException("newSize must be lower than" + " the image width"); } } else if (newSize >= height) { throw new IllegalArgumentException("newSize must be lower than" + " the image height"); } if (newSize <= 0) { throw new IllegalArgumentException("newSize must" + " be greater than 0"); } float ratioWH = (float) width / (float) height; float ratioHW = (float) height / (float) width; BufferedImage thumb = image; BufferedImage temp = null; Graphics2D g2 = null; int previousWidth = width; int previousHeight = height; do { if (isWidthGreater) { width /= 2; if (width < newSize) { width = newSize; } height = (int) (width / ratioWH); } else { height /= 2; if (height < newSize) { height = newSize; } width = (int) (height / ratioHW); } temp = createCompatibleImage(image, width, height); g2 = temp.createGraphics(); g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g2.drawImage(thumb, 0, 0, width, height, 0, 0, previousWidth, previousHeight, null); previousWidth = width; previousHeight = height; thumb = temp; } while (newSize != (isWidthGreater ? width : height)); g2.dispose(); if (width != thumb.getWidth() || height != thumb.getHeight()) { temp = createCompatibleImage(image, width, height); g2 = temp.createGraphics(); g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g2.drawImage(thumb, 0, 0, width, height, null); g2.dispose(); thumb = temp; } return thumb; } public static BufferedImage createThumbnail(BufferedImage image, int newWidth, int newHeight) { int width = image.getWidth(); int height = image.getHeight(); if (newWidth >= width || newHeight >= height) { throw new IllegalArgumentException("newWidth and newHeight cannot" + " be greater than the image" + " dimensions"); } else if (newWidth <= 0 || newHeight <= 0) { throw new IllegalArgumentException("newWidth and newHeight must" + " be greater than 0"); } BufferedImage thumb = image; BufferedImage temp = null; Graphics2D g2 = null; int previousWidth = width; int previousHeight = height; do { if (width > newWidth) { width /= 2; if (width < newWidth) { width = newWidth; } } if (height > newHeight) { height /= 2; if (height < newHeight) { height = newHeight; } } temp = createCompatibleImage(image, width, height); g2 = temp.createGraphics(); g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g2.drawImage(thumb, 0, 0, width, height, 0, 0, previousWidth, previousHeight, null); previousWidth = width; previousHeight = height; thumb = temp; } while (width != newWidth || height != newHeight); g2.dispose(); if (width != thumb.getWidth() || height != thumb.getHeight()) { temp = createCompatibleImage(image, width, height); g2 = temp.createGraphics(); g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g2.drawImage(thumb, 0, 0, width, height, null); g2.dispose(); thumb = temp; } return thumb; } public static int[] getPixels(BufferedImage img, int x, int y, int w, int h, int[] pixels) { if (w == 0 || h == 0) { return new int[0]; } if (pixels == null) { pixels = new int[w * h]; } else if (pixels.length < w * h) { throw new IllegalArgumentException("pixels array must have a length" + " >= w*h"); } int imageType = img.getType(); if (imageType == BufferedImage.TYPE_INT_ARGB || imageType == BufferedImage.TYPE_INT_RGB) { Raster raster = img.getRaster(); return (int[]) raster.getDataElements(x, y, w, h, pixels); } // Unmanages the image return img.getRGB(x, y, w, h, pixels, 0, w); } public static void setPixels(BufferedImage img, int x, int y, int w, int h, int[] pixels) { if (pixels == null || w == 0 || h == 0) { return; } else if (pixels.length < w * h) { throw new IllegalArgumentException("pixels array must have a length" + " >= w*h"); } int imageType = img.getType(); if (imageType == BufferedImage.TYPE_INT_ARGB || imageType == BufferedImage.TYPE_INT_RGB) { WritableRaster raster = img.getRaster(); raster.setDataElements(x, y, w, h, pixels); } else { // Unmanages the image img.setRGB(x, y, w, h, pixels, 0, w); } } }
package org.neo4j.impl.core; // Java imports import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.logging.Logger; import org.neo4j.api.core.Direction; import org.neo4j.api.core.Node; import org.neo4j.api.core.Relationship; import org.neo4j.api.core.RelationshipType; import org.neo4j.api.core.ReturnableEvaluator; import org.neo4j.api.core.StopEvaluator; import org.neo4j.api.core.Traverser; import org.neo4j.api.core.Traverser.Order; import org.neo4j.impl.command.CommandManager; import org.neo4j.impl.command.ExecuteFailedException; import org.neo4j.impl.event.Event; import org.neo4j.impl.event.EventData; import org.neo4j.impl.event.EventManager; import org.neo4j.impl.transaction.IllegalResourceException; import org.neo4j.impl.transaction.LockManager; import org.neo4j.impl.transaction.LockNotFoundException; import org.neo4j.impl.transaction.LockType; import org.neo4j.impl.transaction.NotInTransactionException; import org.neo4j.impl.transaction.TransactionFactory; import org.neo4j.impl.transaction.TransactionIsolationLevel; import org.neo4j.impl.traversal.TraverserFactory; /** * This is the implementation of {@link Node}. Class <CODE>NodeImpl</CODE> * has two different states/phases for relationships and properties. * First phase the full node isn't in memory, some or non of the properties and * relationships may be in memory. The second phase (full phase) all properties * or relationships are in memory. * <p> * All public methods must be invoked within a transaction context, * failure to do so will result in an exception. * Modifing methods will create a command that can execute and undo the desired * operation. The command will be associated with the transaction and * if the transaction fails all the commands participating in the transaction * will be undone. * <p> * Methods that uses commands will first create a command and verify that * we're in a transaction context. To persist operations a pro-active event * is generated and will cause the * {@link org.neo4j.impl.persistence.BusinessLayerMonitor} to persist the * then operation. * If the event fails (false is returned) the transaction is marked as * rollback only and if the command will be undone. * <p> * This implementaiton of node does not rely on persistence storage to * enforce contraints. This is done by {@link NeoConstraints} that evaluates * the events generated by modifying operations. */ class NodeImpl implements Node, Comparable { private enum NodePhase { EMPTY_PROPERTY, FULL_PROPERTY, EMPTY_REL, FULL_REL } private static Logger log = Logger.getLogger( NodeImpl.class.getName() ); private int id = -1; private boolean isDeleted = false; private NodePhase nodePropPhase; private NodePhase nodeRelPhase; private Map<String,Set<Integer>> relationshipMap = new HashMap<String,Set<Integer>>(); private Map<String,Property> propertyMap = new HashMap<String,Property>(); private static NodeManager nodeManager = NodeManager.getManager(); private static TraverserFactory travFactory = TraverserFactory.getFactory(); NodeImpl( int id ) { this.id = id; this.nodePropPhase = NodePhase.EMPTY_PROPERTY; this.nodeRelPhase = NodePhase.EMPTY_REL; } // newNode will only be true for NodeManager.createNode NodeImpl( int id, boolean newNode ) { this.id = id; if ( newNode ) { this.nodePropPhase = NodePhase.FULL_PROPERTY; this.nodeRelPhase = NodePhase.FULL_REL; } } public long getId() { return this.id; } public Iterable<Relationship> getRelationships() { acquireLock( this, LockType.READ ); try { ensureFullRelationships(); if ( relationshipMap == null ) { return Collections.emptyList(); } // Iterate through relationshipMap's values (which are sets // of relationships ids) and merge them all into one list. // Convert it to array and return it. // TODO: rewrite this with iterator wrapper List<Relationship> allRelationships = new LinkedList<Relationship>(); Iterator<Set<Integer>> values = relationshipMap.values().iterator(); while ( values.hasNext() ) { Set<Integer> relTypeSet = values.next(); for ( int relId : relTypeSet ) { allRelationships.add( nodeManager.getRelationshipById( relId) ); } } return allRelationships; } finally { releaseLock( this, LockType.READ ); } } public Iterable<Relationship> getRelationships( Direction dir ) { if ( dir == Direction.BOTH ) { return getRelationships(); } acquireLock( this, LockType.READ ); try { ensureFullRelationships(); if ( relationshipMap == null ) { return Collections.emptyList(); } // Iterate through relationshipMap's values (which are lists // of relationships) and merge them all into one list. Convert it // to array and return it. // TODO: rewrite this with iterator wrapper List<Relationship> allRelationships = new LinkedList<Relationship>(); Iterator<Set<Integer>> values = relationshipMap.values().iterator(); while ( values.hasNext() ) { Set<Integer> relTypeSet = values.next(); for ( int relId : relTypeSet ) { Relationship rel = nodeManager.getRelationshipById( relId ); if ( dir == Direction.OUTGOING && rel.getStartNode().equals( this ) ) { allRelationships.add( rel ); } else if ( dir == Direction.INCOMING && rel.getEndNode().equals( this ) ) { allRelationships.add( rel ); } } } return allRelationships; } finally { releaseLock( this, LockType.READ ); } } public Iterable<Relationship> getRelationships( RelationshipType type ) { acquireLock( this, LockType.READ ); try { ensureFullRelationships(); if ( relationshipMap == null ) { return Collections.emptyList(); } // TODO: rewrite with iterator wrapper Set<Integer> relationshipSet = relationshipMap.get( type.name() ); if ( relationshipSet == null ) { return Collections.emptyList(); } List<Relationship> rels = new LinkedList<Relationship>(); Iterator<Integer> values = relationshipSet.iterator(); while ( values.hasNext() ) { rels.add( nodeManager.getRelationshipById( values.next() ) ); } return rels; } finally { releaseLock( this, LockType.READ ); } } public Iterable<Relationship> getRelationships( RelationshipType... types ) { List<Relationship> rels = new LinkedList<Relationship>(); for ( RelationshipType type : types ) { for ( Relationship rel : getRelationships( type ) ) { rels.add( rel ); } } return rels; } public Relationship getSingleRelationship( RelationshipType type, Direction dir ) { Iterator<Relationship> rels = getRelationships( type, dir ).iterator(); if ( !rels.hasNext() ) { return null; } Relationship rel = rels.next(); if ( rels.hasNext() ) { throw new NotFoundException( "More then one relationship[" + type + "] found" ); } return rel; } public Iterable<Relationship> getRelationships( RelationshipType type, Direction dir ) { if ( dir == Direction.BOTH ) { return getRelationships( type ); } acquireLock( this, LockType.READ ); try { ensureFullRelationships(); if ( relationshipMap == null ) { return Collections.emptyList(); } // TODO: rewrite with iterator wrapper Set<Integer> relationshipSet = relationshipMap.get( type.name() ); if ( relationshipSet == null ) { return Collections.emptyList(); } List<Relationship> rels = new LinkedList<Relationship>(); Iterator<Integer> values = relationshipSet.iterator(); while ( values.hasNext() ) { Relationship rel = nodeManager.getRelationshipById( values.next() ); if ( dir == Direction.OUTGOING && rel.getStartNode().equals( this ) ) { rels.add( rel ); } else if ( dir == Direction.INCOMING && rel.getEndNode().equals( this ) ) { rels.add( rel ); } } return rels; } finally { releaseLock( this, LockType.READ ); } } /** * Deletes this node removing it from cache and persistent storage. If * unable to delete, a <CODE>DeleteException</CODE> is thrown. * <p> * If the node is in first phase it will be changed to full. This is done * because we don't rely on the underlying persistance storage to make sure * all relationships connected to this node has been deleted. Instead * {@link NeoConstraintsListener} will validate that all deleted nodes in * the transaction don't have any relationships connected to them before * the transaction completes. * <p> * Invoking any method on this node after delete is invalid, doing so might * result in a checked or runtime exception beeing thrown. * * @throws DeleteException if unable to delete */ public void delete() // throws DeleteException { acquireLock( this, LockType.WRITE ); NodeCommands nodeCommand = null; try { // neo constraints need to validate all rels deleted so we // must have full node ensureFullRelationships(); nodeCommand = new NodeCommands(); nodeCommand.setNode( this ); nodeCommand.initDelete(); EventManager em = EventManager.getManager(); EventData eventData = new EventData( nodeCommand ); if ( !em.generateProActiveEvent( Event.NODE_DELETE, eventData ) ) { setRollbackOnly(); throw new DeleteException( "Generate pro-active event failed, " + "unable to delete " + this ); } // normal node phase here isn't necessary, if something breaks we // still have the node as it was in memory and the transaction will // rollback so the full node will still be persistent nodeCommand.execute(); em.generateReActiveEvent( Event.NODE_DELETE, eventData ); } catch ( ExecuteFailedException e ) { setRollbackOnly(); if ( nodeCommand != null ) { nodeCommand.undo(); } throw new DeleteException( "Failed executing command deleting " + this, e ); } finally { releaseLock( this, LockType.WRITE ); } } // Property operations /** * Returns all properties on <CODE>this</CODE> node. The whole node will be * loaded (if not full phase already) to make sure that all properties are * present. * * @return an object array containing all properties. */ public Iterable<Object> getPropertyValues() { acquireLock( this, LockType.READ ); try { ensureFullProperties(); List<Object> properties = new ArrayList<Object>(); for ( Property property : propertyMap.values() ) { properties.add( property.getValue() ); } return properties; } finally { releaseLock( this, LockType.READ ); } } /** * Returns all property keys on <CODE>this</CODE> node. The whole node will * be loaded (if not full phase already) to make sure that all properties * are present. * * @return a string array containing all property keys. */ public Iterable<String> getPropertyKeys() { acquireLock( this, LockType.READ ); try { ensureFullProperties(); List<String> propertyKeys = new ArrayList<String>(); for ( String key : propertyMap.keySet() ) { propertyKeys.add( key ); } return propertyKeys; } finally { releaseLock( this, LockType.READ ); } } /** * Returns the property for <CODE>key</CODE>. If key is null or the * property <CODE>key</CODE> dosen't exist {@link NotFoundException} is * thrown. If node is in first phase the cache is first checked and if * the property isn't found the node enters full phase and the cache is * checked again. * * @param key the property key * @return the property object * @throws NotFoundException if this property doesn't exist */ public Object getProperty( String key ) throws NotFoundException { acquireLock( this, LockType.READ ); try { if ( propertyMap.containsKey( key ) ) { return propertyMap.get( key ).getValue(); } ensureFullProperties(); if ( propertyMap.containsKey( key ) ) { return propertyMap.get( key ).getValue(); } } finally { releaseLock( this, LockType.READ ); } throw new NotFoundException( "" + key + " property not found." ); } public Object getProperty( String key, Object defaultValue ) { if ( hasProperty( key ) ) { return getProperty( key ); } return defaultValue; } /** * Returns true if this node has the property <CODE>key</CODE>. If node is * in first phase the cache is first checked and if the property isn't * found the node enters full phase and the cache is checked again. * If <CODE>key</CODE> is null false is returned. * * @param key the property key * @return true if <CODE>key</CODE> property exists */ public boolean hasProperty( String key ) { acquireLock( this, LockType.READ ); try { if ( propertyMap.containsKey( key ) ) { return true; } ensureFullProperties(); return propertyMap.containsKey( key ); } finally { releaseLock( this, LockType.READ ); } } public void setProperty( String key, Object value ) throws IllegalValueException { if ( !hasProperty( key ) ) { addProperty( key, value ); } else { changeProperty( key, value ); } } void addProperty( String key, Object value ) throws IllegalValueException { if ( key == null || value == null ) { throw new IllegalValueException( "Null parameter, " + "key=" + key + ", " + "value=" + value ); } acquireLock( this, LockType.WRITE ); NodeCommands nodeCommand = null; try { // must make sure we don't add already existing property ensureFullProperties(); nodeCommand = new NodeCommands(); nodeCommand.setNode( this ); nodeCommand.initAddProperty( key, new Property( -1, value ) ); // have to execute command here since the full node is loaded // and then the property would already be in cache nodeCommand.execute(); EventManager em = EventManager.getManager(); EventData eventData = new EventData( nodeCommand ); if ( !em.generateProActiveEvent( Event.NODE_ADD_PROPERTY, eventData ) ) { setRollbackOnly(); nodeCommand.undo(); throw new IllegalValueException( "Generate pro-active event failed, " + " unable to add property[" + key + "," + value + "] on " + this ); } em.generateReActiveEvent( Event.NODE_ADD_PROPERTY, eventData ); } catch ( ExecuteFailedException e ) { if ( nodeCommand != null ) { nodeCommand.undo(); } throw new IllegalValueException( "Failed executing command when " + " adding property[" + key + "," + value + "] on " + this, e ); } finally { releaseLock( this, LockType.WRITE ); } } /** * Removes the property <CODE>key</CODE>. If null property <CODE>key</CODE> * a <CODE>NotFoundException</CODE> is thrown. If property doesn't exist * <CODE>null</CODE> is returned. * * @param key the property key * @return the removed property value */ public Object removeProperty( String key ) { if ( key == null ) { throw new IllegalArgumentException( "Null parameter." ); } acquireLock( this, LockType.WRITE ); NodeCommands nodeCommand = null; try { // if null or not found make sure full ensureFullProperties(); if ( !propertyMap.containsKey( key ) ) { return null; } nodeCommand = new NodeCommands(); nodeCommand.setNode( this ); nodeCommand.initRemoveProperty( doGetProperty( key ).getId(), key ); // have to execute here for NodeOperationEventData to be correct // nodeCommand also checks that the property really exist nodeCommand.execute(); EventManager em = EventManager.getManager(); EventData eventData = new EventData( nodeCommand ); if ( !em.generateProActiveEvent( Event.NODE_REMOVE_PROPERTY, eventData ) ) { setRollbackOnly(); nodeCommand.undo(); throw new NotFoundException( "Generate pro-active event failed, " + "unable to remove property[" + key + "] from " + this ); } em.generateReActiveEvent( Event.NODE_REMOVE_PROPERTY, eventData ); return nodeCommand.getOldProperty(); } catch ( ExecuteFailedException e ) { if ( nodeCommand != null ) { nodeCommand.undo(); } throw new NotFoundException( "Failed executing command " + "while removing property[" + key + "] on " + this, e ); } finally { releaseLock( this, LockType.WRITE ); } } Object changeProperty( String key, Object newValue ) throws IllegalValueException, NotFoundException { if ( key == null || newValue == null ) { throw new IllegalValueException( "Null parameter, " + "key=" + key + ", " + "value=" + newValue ); } acquireLock( this, LockType.WRITE ); NodeCommands nodeCommand = null; try { // if null or not found make sure full ensureFullProperties(); nodeCommand = new NodeCommands(); nodeCommand.setNode( this ); int propertyId = doGetProperty( key ).getId(); nodeCommand.initChangeProperty( propertyId, key, new Property( propertyId, newValue ) ); // have to execute here for NodeOperationEventData to be correct nodeCommand.execute(); EventManager em = EventManager.getManager(); EventData eventData = new EventData( nodeCommand ); if ( !em.generateProActiveEvent( Event.NODE_CHANGE_PROPERTY, eventData ) ) { setRollbackOnly(); nodeCommand.undo(); throw new IllegalValueException( "Generate pro-active event failed, " + " unable to change property[" + key + "," + newValue + "] on " + this ); } em.generateReActiveEvent( Event.NODE_CHANGE_PROPERTY, eventData ); return nodeCommand.getOldProperty(); } catch ( ExecuteFailedException e ) { if ( nodeCommand != null ) { nodeCommand.undo(); } throw new IllegalValueException( "Failed executing command when " + " changing property[" + key + "," + newValue + "] on " + this, e ); } finally { releaseLock( this, LockType.WRITE ); } } /** * If object <CODE>node</CODE> is a node, 0 is returned if <CODE>this</CODE> * node id equals <CODE>node's</CODE> node id, 1 if <CODE>this</CODE> * node id is greater and -1 else. * <p> * If <CODE>node</CODE> isn't a node a ClassCastException will be thrown. * * @param node the node to compare this node with * @return 0 if equal id, 1 if this id is greater else -1 */ // TODO: Verify this implementation public int compareTo( Object node ) { Node n = (Node) node; int ourId = (int) this.getId(), theirId = (int) n.getId(); if ( ourId < theirId ) { return -1; } else if ( ourId > theirId ) { return 1; } else { return 0; } } /** * Returns true if object <CODE>o</CODE> is a node with the same id * as <CODE>this</CODE>. * * @param o the object to compare * @return true if equal, else false */ public boolean equals( Object o ) { // verify type and not null, should use Node inteface if ( !(o instanceof Node) ) { return false; } // The equals contract: // o reflexive: x.equals(x) // o symmetric: x.equals(y) == y.equals(x) // o transitive: ( x.equals(y) && y.equals(z) ) == true // then x.equals(z) == true // o consistent: the nodeId never changes return this.getId() == ((Node) o).getId(); } private volatile int hashCode = 0; public int hashCode() { // hashcode contract: // 1. must return the same result for the same object consistenlty // 2. if two objects are equal they must produce the same hashcode // also two distinct object should (not required) produce different // hash values, ideally a hash function should distribute any // collection uniformly across all possible hash values // we have if ( hashCode == 0 ) { // this one is so leet, if you don't understand, that is ok... // you're just not on the same elitness level as some of us, // nothing to be ashamed of hashCode = 3217 * (int) this.getId(); } return hashCode; // or maybe this is enough when we have zillions of nodes? // return this.id; } /** * Returns this node's string representaiton. * * @return the string representaiton of this node */ public String toString() { return "Node #" + this.getId(); } /** * NOTE: caller is responsible for acquiring write lock on this node * before calling this method. */ void doAddProperty( String key, Property value ) throws IllegalValueException { if ( propertyMap.containsKey( key ) ) { throw new IllegalValueException( "Property[" + key + "] already added." ); } propertyMap.put( key, value ); } // caller is responsible for acquiring lock Property doRemoveProperty( String key ) throws NotFoundException { if ( propertyMap.containsKey( key ) ) { return propertyMap.remove( key ); } throw new NotFoundException( "Property not found: " + key ); } // caller is responsible for acquiring lock Property doChangeProperty( String key, Property newValue ) throws IllegalValueException, NotFoundException { if ( propertyMap.containsKey( key ) ) { Property oldValue = propertyMap.get( key ); propertyMap.put( key, newValue ); return oldValue; } throw new NotFoundException( "Property not found: " + key ); } // caller is responsible for acquiring lock Property doGetProperty( String key ) throws NotFoundException { if ( propertyMap.containsKey( key ) ) { return propertyMap.get( key ); } throw new NotFoundException( "Property not found: " + key ); } // caller is responsible for acquiring lock // this method is only called when a relationship is created or // a relationship delete is undone or when the full node is loaded void addRelationship( RelationshipType type, Integer relId ) { Set<Integer> relationshipSet = relationshipMap.get( type.name() ); if ( relationshipSet == null ) { relationshipSet = new LinkedHashSet<Integer>(); relationshipMap.put( type.name(), relationshipSet ); } relationshipSet.add( relId ); } // caller is responsible for acquiring lock // this method is only called when a undo create relationship or // a relationship delete is invoked. void removeRelationship( RelationshipType type, Integer relId ) { Set<Integer> relationshipSet = relationshipMap.get( type.name() ); if ( relationshipSet != null ) { relationshipSet.remove( relId ); if ( relationshipSet.size() == 0 ) { relationshipMap.remove( type.name() ); } } } boolean hasRelationships() { return ( relationshipMap.size() > 0 ); } private void setRollbackOnly() { try { TransactionFactory.getTransactionManager().setRollbackOnly(); } catch ( javax.transaction.SystemException se ) { se.printStackTrace(); log.severe( "Failed to set transaction rollback only" ); } } private void ensureFullProperties() { if ( nodePropPhase != NodePhase.FULL_PROPERTY ) { RawPropertyData[] rawProperties = NodeManager.getManager().loadProperties( this ); Set<Integer> addedProps = new LinkedHashSet<Integer>(); Map<String,Property> newPropertyMap = new HashMap<String,Property>(); for ( RawPropertyData propData : rawProperties ) { int propId = propData.getId(); assert !addedProps.contains( propId ); addedProps.add( propId ); Property property = new Property( propId, propData.getValue() ); newPropertyMap.put( propData.getKey(), property ); } for ( String key : this.propertyMap.keySet() ) { Property prop = propertyMap.get( key ); if ( !addedProps.contains( prop.getId() ) ) { newPropertyMap.put( key, prop ); } } this.propertyMap = newPropertyMap; nodePropPhase = NodePhase.FULL_PROPERTY; } } private void ensureFullRelationships() { if ( nodeRelPhase != NodePhase.FULL_REL ) { List<Relationship> fullRelationshipList = NodeManager.getManager().loadRelationships( this ); Set<Integer> addedRels = new HashSet<Integer>(); Map<String,Set<Integer>> newRelationshipMap = new HashMap<String,Set<Integer>>(); for ( Relationship rel : fullRelationshipList ) { int relId = (int) rel.getId(); assert !addedRels.contains( relId ); addedRels.add( relId ); RelationshipType type = rel.getType(); Set<Integer> relationshipSet = newRelationshipMap.get( type.name() ); if ( relationshipSet == null ) { relationshipSet = new LinkedHashSet<Integer>(); newRelationshipMap.put( type.name(), relationshipSet ); } relationshipSet.add( relId ); } for ( String typeName : this.relationshipMap.keySet() ) { Set<Integer> relationshipSet = this.relationshipMap.get( typeName ); for ( Integer relId : relationshipSet ) { if ( !addedRels.contains( relId ) ) { Set<Integer> newRelationshipSet = newRelationshipMap.get( typeName ); if ( newRelationshipSet == null ) { newRelationshipSet = new LinkedHashSet<Integer>(); newRelationshipMap.put( typeName, newRelationshipSet ); } newRelationshipSet.add( relId ); addedRels.add( relId ); } } } this.relationshipMap = newRelationshipMap; nodeRelPhase = NodePhase.FULL_REL; } } private void acquireLock( Object resource, LockType lockType ) { try { // make sure we're in transaction TransactionFactory.getTransactionIsolationLevel(); if ( lockType == LockType.READ ) { LockManager.getManager().getReadLock( resource ); } else if ( lockType == LockType.WRITE ) { LockManager.getManager().getWriteLock( resource ); } else { throw new RuntimeException( "Unkown lock type: " + lockType ); } } catch ( NotInTransactionException e ) { throw new RuntimeException( "Unable to get transaction isolation level.", e ); } catch ( IllegalResourceException e ) { throw new RuntimeException( e ); } } private void releaseLock( Object resource, LockType lockType ) { releaseLock( resource, lockType, false ); } private void releaseLock( Object resource, LockType lockType, boolean forceRelease ) { try { TransactionIsolationLevel level = TransactionFactory.getTransactionIsolationLevel(); if ( level == TransactionIsolationLevel.READ_COMMITTED ) { if ( lockType == LockType.READ ) { LockManager.getManager().releaseReadLock( resource ); } else if ( lockType == LockType.WRITE ) { if ( forceRelease ) { LockManager.getManager().releaseWriteLock( resource ); } else { CommandManager.getManager().addLockToTransaction( resource, lockType ); } } else { throw new RuntimeException( "Unkown lock type: " + lockType ); } } else if ( level == TransactionIsolationLevel.BAD ) { CommandManager.getManager().addLockToTransaction( resource, lockType ); } else { throw new RuntimeException( "Unkown transaction isolation level, " + level ); } } catch ( NotInTransactionException e ) { e.printStackTrace(); throw new RuntimeException( "Unable to get transaction isolation level.", e ); } catch ( LockNotFoundException e ) { throw new RuntimeException( "Unable to release locks.", e ); } catch ( IllegalResourceException e ) { throw new RuntimeException( "Unable to release locks.", e ); } } boolean isDeleted() { return isDeleted; } void setIsDeleted( boolean flag ) { isDeleted = flag; } public Relationship createRelationshipTo( Node otherNode, RelationshipType type ) { return nodeManager.createRelationship( this, otherNode, type ); } public Traverser traverse( Order traversalOrder, StopEvaluator stopEvaluator, ReturnableEvaluator returnableEvaluator, RelationshipType relationshipType, Direction direction ) { return travFactory.createTraverser( traversalOrder, this, relationshipType, direction, stopEvaluator, returnableEvaluator ); } public Traverser traverse( Order traversalOrder, StopEvaluator stopEvaluator, ReturnableEvaluator returnableEvaluator, RelationshipType firstRelationshipType, Direction firstDirection, RelationshipType secondRelationshipType, Direction secondDirection ) { RelationshipType[] types = new RelationshipType[2]; Direction[] dirs = new Direction[2]; types[0] = firstRelationshipType; types[1] = secondRelationshipType; dirs[0] = firstDirection; dirs[1] = secondDirection; return travFactory.createTraverser( traversalOrder, this, types, dirs, stopEvaluator, returnableEvaluator ); } public Traverser traverse( Order traversalOrder, StopEvaluator stopEvaluator, ReturnableEvaluator returnableEvaluator, Object... relationshipTypesAndDirections ) { int elements = relationshipTypesAndDirections.length / 2; RelationshipType[] types = new RelationshipType[ elements ]; Direction[] dirs = new Direction[ elements ]; int j = 0; for ( int i = 0; i < elements; i++ ) { types[i] = ( RelationshipType ) relationshipTypesAndDirections[j++]; dirs[i] = ( Direction ) relationshipTypesAndDirections[j++]; } return travFactory.createTraverser( traversalOrder, this, types, dirs, stopEvaluator, returnableEvaluator ); } }
package org.biojava3.ws.hmmer; import java.io.Serializable; import java.util.SortedSet; /** The results of a Hmmer search for a single sequence * * @author Andreas Prlic * @since 3.0.3 */ public class HmmerResult implements Comparable<HmmerResult>, Serializable{ private static final long serialVersionUID = -6016026193090737943L; String desc ; Float score; Float evalue; Double pvalue; String acc; Integer dcl; String name; Integer ndom; Integer nreported; SortedSet<HmmerDomain>domains; public SortedSet<HmmerDomain> getDomains() { return domains; } public void setDomains(SortedSet<HmmerDomain> domains) { this.domains = domains; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } public Float getScore() { return score; } public void setScore(Float score) { this.score = score; } public Float getEvalue() { return evalue; } public void setEvalue(Float evalue) { this.evalue = evalue; } public Double getPvalue() { return pvalue; } public void setPvalue(Double pvalue) { this.pvalue = pvalue; } public String getAcc() { return acc; } public void setAcc(String acc) { this.acc = acc; } public Integer getDcl() { return dcl; } public void setDcl(Integer dcl) { this.dcl = dcl; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getNdom() { return ndom; } public void setNdom(Integer ndom) { this.ndom = ndom; } public Integer getNreported() { return nreported; } public void setNreported(Integer nreported) { this.nreported = nreported; } @Override public String toString() { return "HmmerResult [acc=" + acc + ", desc=" + desc + ", score=" + score + ", evalue=" + evalue + ", pvalue=" + pvalue + ", dcl=" + dcl + ", name=" + name + ", ndom=" + ndom + ", nreported=" + nreported + ", domains=" + domains + "]"; } @Override public int compareTo(HmmerResult o) { // sort by the start position of the first domain if ( emptyDomains(this) && emptyDomains(o)){ return 0; } if ( ! emptyDomains(this) && emptyDomains(o)) return -1; if ( emptyDomains(this) && (! emptyDomains(o))) return 1; // ok when we are here, both domains are not empty HmmerDomain me = this.getDomains().first(); HmmerDomain other = o.getDomains().first(); //System.out.println(" domains: " + me.getHmmAcc() + " " + other.getHmmAcc()+ " " + me.getSqFrom().compareTo(other.getSqFrom())); return(me.getSqFrom().compareTo(other.getSqFrom())); } private boolean emptyDomains(HmmerResult o) { if ( o.getDomains() == null || o.getDomains().size() == 0) return true; return false; } public int getOverlapLength(HmmerResult other){ int overlap = 0; for ( HmmerDomain d1 : getDomains()){ for (HmmerDomain d2 : other.getDomains()){ overlap += getOverlap(d1, d2); } } return overlap; } private int getOverlap(HmmerDomain one, HmmerDomain other){ int xs = one.getSqFrom(); int ys = one.getSqTo(); int as = other.getSqFrom(); int bs = other.getSqTo(); int overlap = 0; if ((( xs< as) && ( as<ys)) || ((xs < bs) && ( bs <= ys)) || (as<xs && ys<bs)) { if ( xs < as) { if ( ys < bs) overlap = ys-as; else overlap = bs-as; } else { if ( ys < bs) overlap = ys -xs; else overlap = bs - xs; } } return overlap; } }
package org.jdesktop.swingx.graphics; import java.awt.image.BufferedImage; import java.awt.image.ColorModel; import java.awt.image.Raster; import java.awt.image.WritableRaster; import java.awt.GraphicsConfiguration; import java.awt.Transparency; import java.awt.Graphics; import java.awt.GraphicsEnvironment; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.io.IOException; import java.net.URL; import javax.imageio.ImageIO; /** * <p><code>GraphicsUtilities</code> contains a set of tools to perform * common graphics operations easily. These operations are divided into * several themes, listed below.</p> * * <h2>Compatible Images</h2> * * <p>Compatible images can, and should, be used to increase drawing * performance. This class provides a number of methods to load compatible * images directly from files or to convert existing images to compatibles * images.</p> * * <h2>Creating Thumbnails</h2> * * <p>This class provides a number of methods to easily scale down images. * Some of these methods offer a trade-off between speed and result quality and * shouuld be used all the time. They also offer the advantage of producing * compatible images, thus automatically resulting into better runtime * performance.</p> * * <p>All these methodes are both faster than * {@link java.awt.Image#getScaledInstance(int, int, int)} and produce * better-looking results than the various <code>drawImage()</code> methods * in {@link java.awt.Graphics}, which can be used for image scaling.</p> * <h2>Image Manipulation</h2> * * <p>This class provides two methods to get and set pixels in a buffered image. * These methods try to avoid unmanaging the image in order to keep good * performance.</p> * * @author Romain Guy <romain.guy@mac.com> * @author rbair */ public class GraphicsUtilities { private GraphicsUtilities() { } // Returns the graphics configuration for the primary screen private static GraphicsConfiguration getGraphicsConfiguration() { return GraphicsEnvironment.getLocalGraphicsEnvironment(). getDefaultScreenDevice().getDefaultConfiguration(); } private static boolean isHeadless() { return GraphicsEnvironment.isHeadless(); } /** * <p>Returns a new <code>BufferedImage</code> using the same color model * as the image passed as a parameter. The returned image is only compatible * with the image passed as a parameter. This does not mean the returned * image is compatible with the hardware.</p> * * @param image the reference image from which the color model of the new * image is obtained * @return a new <code>BufferedImage</code>, compatible with the color model * of <code>image</code> */ public static BufferedImage createColorModelCompatibleImage(BufferedImage image) { ColorModel cm = image.getColorModel(); return new BufferedImage(cm, cm.createCompatibleWritableRaster(image.getWidth(), image.getHeight()), cm.isAlphaPremultiplied(), null); } /** * <p>Returns a new compatible image with the same width, height and * transparency as the image specified as a parameter. That is, the * returned BufferedImage will be compatible with the graphics hardware. * If this method is called in a headless environment, then * the returned BufferedImage will be compatible with the source * image.</p> * * @see java.awt.Transparency * @see #createCompatibleImage(int, int) * @see #createCompatibleImage(java.awt.image.BufferedImage, int, int) * @see #createCompatibleTranslucentImage(int, int) * @see #loadCompatibleImage(java.net.URL) * @see #toCompatibleImage(java.awt.image.BufferedImage) * @param image the reference image from which the dimension and the * transparency of the new image are obtained * @return a new compatible <code>BufferedImage</code> with the same * dimension and transparency as <code>image</code> */ public static BufferedImage createCompatibleImage(BufferedImage image) { return createCompatibleImage(image, image.getWidth(), image.getHeight()); } /** * <p>Returns a new compatible image of the specified width and height, and * the same transparency setting as the image specified as a parameter. * That is, the returned <code>BufferedImage</code> is compatible with * the graphics hardware. If the method is called in a headless * environment, then the returned BufferedImage will be compatible with * the source image.</p> * * @see java.awt.Transparency * @see #createCompatibleImage(java.awt.image.BufferedImage) * @see #createCompatibleImage(int, int) * @see #createCompatibleTranslucentImage(int, int) * @see #loadCompatibleImage(java.net.URL) * @see #toCompatibleImage(java.awt.image.BufferedImage) * @param width the width of the new image * @param height the height of the new image * @param image the reference image from which the transparency of the new * image is obtained * @return a new compatible <code>BufferedImage</code> with the same * transparency as <code>image</code> and the specified dimension */ public static BufferedImage createCompatibleImage(BufferedImage image, int width, int height) { return isHeadless() ? new BufferedImage(width, height, image.getType()) : getGraphicsConfiguration().createCompatibleImage(width, height, image.getTransparency()); } /** * <p>Returns a new opaque compatible image of the specified width and * height. That is, the returned <code>BufferedImage</code> is compatible with * the graphics hardware. If the method is called in a headless * environment, then the returned BufferedImage will be compatible with * the source image.</p> * * @see #createCompatibleImage(java.awt.image.BufferedImage) * @see #createCompatibleImage(java.awt.image.BufferedImage, int, int) * @see #createCompatibleTranslucentImage(int, int) * @see #loadCompatibleImage(java.net.URL) * @see #toCompatibleImage(java.awt.image.BufferedImage) * @param width the width of the new image * @param height the height of the new image * @return a new opaque compatible <code>BufferedImage</code> of the * specified width and height */ public static BufferedImage createCompatibleImage(int width, int height) { return isHeadless() ? new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB) : getGraphicsConfiguration().createCompatibleImage(width, height); } /** * <p>Returns a new translucent compatible image of the specified width and * height. That is, the returned <code>BufferedImage</code> is compatible with * the graphics hardware. If the method is called in a headless * environment, then the returned BufferedImage will be compatible with * the source image.</p> * * @see #createCompatibleImage(java.awt.image.BufferedImage) * @see #createCompatibleImage(java.awt.image.BufferedImage, int, int) * @see #createCompatibleImage(int, int) * @see #loadCompatibleImage(java.net.URL) * @see #toCompatibleImage(java.awt.image.BufferedImage) * @param width the width of the new image * @param height the height of the new image * @return a new translucent compatible <code>BufferedImage</code> of the * specified width and height */ public static BufferedImage createCompatibleTranslucentImage(int width, int height) { return isHeadless() ? new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB) : getGraphicsConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT); } /** * <p>Returns a new compatible image from a URL. The image is loaded from the * specified location and then turned, if necessary into a compatible * image.</p> * * @see #createCompatibleImage(java.awt.image.BufferedImage) * @see #createCompatibleImage(java.awt.image.BufferedImage, int, int) * @see #createCompatibleImage(int, int) * @see #createCompatibleTranslucentImage(int, int) * @see #toCompatibleImage(java.awt.image.BufferedImage) * @param resource the URL of the picture to load as a compatible image * @return a new translucent compatible <code>BufferedImage</code> of the * specified width and height * @throws java.io.IOException if the image cannot be read or loaded */ public static BufferedImage loadCompatibleImage(URL resource) throws IOException { BufferedImage image = ImageIO.read(resource); return toCompatibleImage(image); } /** * <p>Return a new compatible image that contains a copy of the specified * image. This method ensures an image is compatible with the hardware, * and therefore optimized for fast blitting operations.</p> * * <p>If the method is called in a headless environment, then the returned * <code>BufferedImage</code> will be the source image.</p> * * @see #createCompatibleImage(java.awt.image.BufferedImage) * @see #createCompatibleImage(java.awt.image.BufferedImage, int, int) * @see #createCompatibleImage(int, int) * @see #createCompatibleTranslucentImage(int, int) * @see #loadCompatibleImage(java.net.URL) * @param image the image to copy into a new compatible image * @return a new compatible copy, with the * same width and height and transparency and content, of <code>image</code> */ public static BufferedImage toCompatibleImage(BufferedImage image) { if (isHeadless()) { return image; } if (image.getColorModel().equals( getGraphicsConfiguration().getColorModel())) { return image; } BufferedImage compatibleImage = getGraphicsConfiguration().createCompatibleImage( image.getWidth(), image.getHeight(), image.getTransparency()); Graphics g = compatibleImage.getGraphics(); g.drawImage(image, 0, 0, null); g.dispose(); return compatibleImage; } public static BufferedImage createThumbnailFast(BufferedImage image, int newSize) { float ratio; int width = image.getWidth(); int height = image.getHeight(); if (width > height) { if (newSize >= width) { throw new IllegalArgumentException("newSize must be lower than" + " the image width"); } else if (newSize <= 0) { throw new IllegalArgumentException("newSize must" + " be greater than 0"); } ratio = (float) width / (float) height; width = newSize; height = (int) (newSize / ratio); } else { if (newSize >= height) { throw new IllegalArgumentException("newSize must be lower than" + " the image height"); } else if (newSize <= 0) { throw new IllegalArgumentException("newSize must" + " be greater than 0"); } ratio = (float) height / (float) width; height = newSize; width = (int) (newSize / ratio); } BufferedImage temp = createCompatibleImage(image, width, height); Graphics2D g2 = temp.createGraphics(); g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g2.drawImage(image, 0, 0, temp.getWidth(), temp.getHeight(), null); g2.dispose(); return temp; } public static BufferedImage createThumbnailFast(BufferedImage image, int newWidth, int newHeight) { if (newWidth >= image.getWidth() || newHeight >= image.getHeight()) { throw new IllegalArgumentException("newWidth and newHeight cannot" + " be greater than the image" + " dimensions"); } else if (newWidth <= 0 || newHeight <= 0) { throw new IllegalArgumentException("newWidth and newHeight must" + " be greater than 0"); } BufferedImage temp = createCompatibleImage(image, newWidth, newHeight); Graphics2D g2 = temp.createGraphics(); g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g2.drawImage(image, 0, 0, temp.getWidth(), temp.getHeight(), null); g2.dispose(); return temp; } public static BufferedImage createThumbnail(BufferedImage image, int newSize) { int width = image.getWidth(); int height = image.getHeight(); boolean isTranslucent = image.getTransparency() != Transparency.OPAQUE; boolean isWidthGreater = width > height; if (isWidthGreater) { if (newSize >= width) { throw new IllegalArgumentException("newSize must be lower than" + " the image width"); } } else if (newSize >= height) { throw new IllegalArgumentException("newSize must be lower than" + " the image height"); } if (newSize <= 0) { throw new IllegalArgumentException("newSize must" + " be greater than 0"); } float ratioWH = (float) width / (float) height; float ratioHW = (float) height / (float) width; BufferedImage thumb = image; BufferedImage temp = null; Graphics2D g2 = null; int previousWidth = width; int previousHeight = height; do { if (isWidthGreater) { width /= 2; if (width < newSize) { width = newSize; } height = (int) (width / ratioWH); } else { height /= 2; if (height < newSize) { height = newSize; } width = (int) (height / ratioHW); } if (temp == null || isTranslucent) { if (g2 != null) { g2.dispose(); } temp = createCompatibleImage(image, width, height); g2 = temp.createGraphics(); g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); } g2.drawImage(thumb, 0, 0, width, height, 0, 0, previousWidth, previousHeight, null); previousWidth = width; previousHeight = height; thumb = temp; } while (newSize != (isWidthGreater ? width : height)); g2.dispose(); if (width != thumb.getWidth() || height != thumb.getHeight()) { temp = createCompatibleImage(image, width, height); g2 = temp.createGraphics(); g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g2.drawImage(thumb, 0, 0, width, height, 0, 0, width, height, null); g2.dispose(); thumb = temp; } return thumb; } public static BufferedImage createThumbnail(BufferedImage image, int newWidth, int newHeight) { int width = image.getWidth(); int height = image.getHeight(); boolean isTranslucent = image.getTransparency() != Transparency.OPAQUE; if (newWidth >= width || newHeight >= height) { throw new IllegalArgumentException("newWidth and newHeight cannot" + " be greater than the image" + " dimensions"); } else if (newWidth <= 0 || newHeight <= 0) { throw new IllegalArgumentException("newWidth and newHeight must" + " be greater than 0"); } BufferedImage thumb = image; BufferedImage temp = null; Graphics2D g2 = null; int previousWidth = width; int previousHeight = height; do { if (width > newWidth) { width /= 2; if (width < newWidth) { width = newWidth; } } if (height > newHeight) { height /= 2; if (height < newHeight) { height = newHeight; } } if (temp == null || isTranslucent) { if (g2 != null) { g2.dispose(); } temp = createCompatibleImage(image, width, height); g2 = temp.createGraphics(); g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); } g2.drawImage(thumb, 0, 0, width, height, 0, 0, previousWidth, previousHeight, null); previousWidth = width; previousHeight = height; thumb = temp; } while (width != newWidth || height != newHeight); g2.dispose(); if (width != thumb.getWidth() || height != thumb.getHeight()) { temp = createCompatibleImage(image, width, height); g2 = temp.createGraphics(); g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g2.drawImage(thumb, 0, 0, width, height, 0, 0, width, height, null); g2.dispose(); thumb = temp; } return thumb; } public static int[] getPixels(BufferedImage img, int x, int y, int w, int h, int[] pixels) { if (w == 0 || h == 0) { return new int[0]; } if (pixels == null) { pixels = new int[w * h]; } else if (pixels.length < w * h) { throw new IllegalArgumentException("pixels array must have a length" + " >= w*h"); } int imageType = img.getType(); if (imageType == BufferedImage.TYPE_INT_ARGB || imageType == BufferedImage.TYPE_INT_RGB) { Raster raster = img.getRaster(); return (int[]) raster.getDataElements(x, y, w, h, pixels); } // Unmanages the image return img.getRGB(x, y, w, h, pixels, 0, w); } public static void setPixels(BufferedImage img, int x, int y, int w, int h, int[] pixels) { if (pixels == null || w == 0 || h == 0) { return; } else if (pixels.length < w * h) { throw new IllegalArgumentException("pixels array must have a length" + " >= w*h"); } int imageType = img.getType(); if (imageType == BufferedImage.TYPE_INT_ARGB || imageType == BufferedImage.TYPE_INT_RGB) { WritableRaster raster = img.getRaster(); raster.setDataElements(x, y, w, h, pixels); } else { // Unmanages the image img.setRGB(x, y, w, h, pixels, 0, w); } } }
package org.orbeon.oxf.xforms; import org.apache.commons.pool.ObjectPool; import org.apache.log4j.Level; import org.dom4j.Document; import org.dom4j.Element; import org.orbeon.oxf.common.ValidationException; import org.orbeon.oxf.pipeline.api.ExternalContext; import org.orbeon.oxf.pipeline.api.PipelineContext; import org.orbeon.oxf.util.NetUtils; import org.orbeon.oxf.xforms.control.XFormsControl; import org.orbeon.oxf.xforms.control.XFormsValueControl; import org.orbeon.oxf.xforms.control.XFormsSingleNodeControl; import org.orbeon.oxf.xforms.control.controls.XFormsOutputControl; import org.orbeon.oxf.xforms.control.controls.XFormsUploadControl; import org.orbeon.oxf.xforms.control.controls.XXFormsDialogControl; import org.orbeon.oxf.xforms.event.*; import org.orbeon.oxf.xforms.event.events.*; import org.orbeon.oxf.xforms.processor.XFormsServer; import org.orbeon.oxf.xforms.state.XFormsState; import org.orbeon.oxf.xforms.processor.XFormsURIResolver; import org.orbeon.oxf.xml.dom4j.Dom4jUtils; import org.orbeon.oxf.xml.dom4j.LocationData; import org.orbeon.oxf.xml.dom4j.ExtendedLocationData; import org.orbeon.saxon.om.NodeInfo; import org.orbeon.saxon.om.FastStringBuffer; import java.io.IOException; import java.util.*; /** * Represents an XForms containing document. * * The containing document includes: * * o XForms models (including multiple instances) * o XForms controls * o Event handlers hierarchy */ public class XFormsContainingDocument implements XFormsEventTarget, XFormsEventHandlerContainer { public static final String CONTAINING_DOCUMENT_PSEUDO_ID = "$containing-document$"; // Global XForms function library private static XFormsFunctionLibrary functionLibrary = new XFormsFunctionLibrary(); // Object pool this object must be returned to, if any private ObjectPool sourceObjectPool; // URI resolver private XFormsURIResolver uriResolver; // Whether this document is currently being initialized private boolean isInitializing; // A document contains models and controls private XFormsStaticState xformsStaticState; private List models = new ArrayList(); private Map modelsMap = new HashMap(); private XFormsControls xformsControls; // Client state private boolean dirtySinceLastRequest; private XFormsModelSubmission activeSubmission; private boolean gotSubmission; private List messagesToRun; private List loadsToRun; private List scriptsToRun; private String focusEffectiveControlId; private String helpEffectiveControlId; // Global flag used during initialization only private boolean mustPerformInitializationFirstRefresh; // Legacy information private String legacyContainerType; private String legacyContainerNamespace; // Event information private static final Map ignoredXFormsOutputExternalEvents = new HashMap(); private static final Map allowedXFormsOutputExternalEvents = new HashMap(); private static final Map allowedXFormsUploadExternalEvents = new HashMap(); private static final Map allowedExternalEvents = new HashMap(); private static final Map allowedXFormsSubmissionExternalEvents = new HashMap(); private static final Map allowedXFormsContainingDocumentExternalEvents = new HashMap(); private static final Map allowedXXFormsDialogExternalEvents = new HashMap(); static { // External events ignored on xforms:output ignoredXFormsOutputExternalEvents.put(XFormsEvents.XFORMS_DOM_FOCUS_IN, ""); ignoredXFormsOutputExternalEvents.put(XFormsEvents.XFORMS_DOM_FOCUS_OUT, ""); // External events allowed on xforms:output allowedXFormsOutputExternalEvents.putAll(ignoredXFormsOutputExternalEvents); allowedXFormsOutputExternalEvents.put(XFormsEvents.XFORMS_HELP, ""); // External events allowed on xforms:upload allowedXFormsUploadExternalEvents.putAll(allowedXFormsOutputExternalEvents); allowedXFormsUploadExternalEvents.put(XFormsEvents.XFORMS_SELECT, ""); allowedXFormsUploadExternalEvents.put(XFormsEvents.XXFORMS_VALUE_CHANGE_WITH_FOCUS_CHANGE, ""); // External events allowed on other controls allowedExternalEvents.putAll(allowedXFormsOutputExternalEvents); allowedExternalEvents.put(XFormsEvents.XFORMS_DOM_ACTIVATE, ""); allowedExternalEvents.put(XFormsEvents.XXFORMS_VALUE_CHANGE_WITH_FOCUS_CHANGE, ""); // External events allowed on xforms:submission allowedXFormsSubmissionExternalEvents.put(XFormsEvents.XXFORMS_SUBMIT, ""); // External events allowed on containing document allowedXFormsContainingDocumentExternalEvents.put(XFormsEvents.XXFORMS_LOAD, ""); // External events allowed on xxforms:dialog allowedXXFormsDialogExternalEvents.put(XFormsEvents.XXFORMS_DIALOG_CLOSE, ""); } // For testing only private static int testAjaxToggleValue = 0; /** * Return the global function library. */ public static XFormsFunctionLibrary getFunctionLibrary() { return functionLibrary; } /** * Create an XFormsContainingDocument from an XFormsEngineStaticState object. * * @param pipelineContext current pipeline context * @param xformsStaticState XFormsEngineStaticState * @param uriResolver optional URIResolver for loading instances during initialization (and possibly more, such as schemas and "GET" submissions upon initialization) */ public XFormsContainingDocument(PipelineContext pipelineContext, XFormsStaticState xformsStaticState, XFormsURIResolver uriResolver) { logDebug("containing document", "creating new ContainingDocument (static state object provided)."); // Remember static state this.xformsStaticState = xformsStaticState; // Remember URI resolver for initialization this.uriResolver = uriResolver; this.isInitializing = true; // Initialize the containing document try { initialize(pipelineContext); } catch (Exception e) { throw ValidationException.wrapException(e, new ExtendedLocationData(getLocationData(), "initializing XForms containing document")); } // Clear URI resolver, since it is of no use after initialization, and it may keep dangerous references (PipelineContext) this.uriResolver = null; this.isInitializing = false; } /** * Create an XFormsContainingDocument from an XFormsState object. * * @param pipelineContext current pipeline context * @param xformsState XFormsState containing static and dynamic state */ public XFormsContainingDocument(PipelineContext pipelineContext, XFormsState xformsState) { logDebug("containing document", "creating new ContainingDocument (static state object not provided)."); // Create static state object // TODO: Handle caching of XFormsStaticState object xformsStaticState = new XFormsStaticState(pipelineContext, xformsState.getStaticState()); // Restore the containing document's dynamic state final String encodedDynamicState = xformsState.getDynamicState(); try { if (encodedDynamicState == null || encodedDynamicState.equals("")) { // Just for tests, we allow the dynamic state to be empty initialize(pipelineContext); xformsControls.evaluateAllControlsIfNeeded(pipelineContext); } else { // Regular case restoreDynamicState(pipelineContext, encodedDynamicState); } } catch (Exception e) { throw ValidationException.wrapException(e, new ExtendedLocationData(getLocationData(), "re-initializing XForms containing document")); } } /** * Legacy constructor for XForms Classic. */ public XFormsContainingDocument(PipelineContext pipelineContext, XFormsModel xformsModel) { this.models = Collections.singletonList(xformsModel); this.xformsControls = new XFormsControls(this, null, null); if (xformsModel.getEffectiveId() != null) modelsMap.put(xformsModel.getEffectiveId(), xformsModel); xformsModel.setContainingDocument(this); final ExternalContext externalContext = (ExternalContext) pipelineContext.getAttribute(PipelineContext.EXTERNAL_CONTEXT); this.legacyContainerType = externalContext.getRequest().getContainerType(); this.legacyContainerNamespace = externalContext.getRequest().getContainerNamespace(); initialize(pipelineContext); } public void setSourceObjectPool(ObjectPool sourceObjectPool) { this.sourceObjectPool = sourceObjectPool; } public ObjectPool getSourceObjectPool() { return sourceObjectPool; } public XFormsURIResolver getURIResolver() { return uriResolver; } public boolean isInitializing() { return isInitializing; } /** * Return model with the specified id, null if not found. If the id is the empty string, return * the default model, i.e. the first model. */ public XFormsModel getModel(String modelId) { return (XFormsModel) ("".equals(modelId) ? models.get(0) : modelsMap.get(modelId)); } /** * Get a list of all the models in this document. */ public List getModels() { return models; } /** * Return the XForms controls. */ public XFormsControls getXFormsControls() { return xformsControls; } /** * Whether the document is dirty since the last request. * * @return whether the document is dirty since the last request */ public boolean isDirtySinceLastRequest() { return dirtySinceLastRequest || xformsControls == null || xformsControls.isDirtySinceLastRequest(); } public void markCleanSinceLastRequest() { this.dirtySinceLastRequest = false; } public void markDirtySinceLastRequest() { this.dirtySinceLastRequest = true; } /** * Return the XFormsEngineStaticState. */ public XFormsStaticState getStaticState() { return xformsStaticState; } /** * Return a map of script id -> script text. */ public Map getScripts() { return (xformsStaticState == null) ? null : xformsStaticState.getScripts(); } /** * Return the document base URI. */ public String getBaseURI() { return (xformsStaticState == null) ? null : xformsStaticState.getBaseURI(); } /** * Return the container type that generate the XForms page, either "servlet" or "portlet". */ public String getContainerType() { return (xformsStaticState == null) ? legacyContainerType : xformsStaticState.getContainerType(); } /** * Return the container namespace that generate the XForms page. Always "" for servlets. */ public String getContainerNamespace() { return (xformsStaticState == null) ? legacyContainerNamespace : xformsStaticState.getContainerNamespace(); } public Map getNamespaceMappings(Element element) { if (xformsStaticState != null) return xformsStaticState.getNamespaceMappings(element); else // should happen only with the legacy XForms engine return Dom4jUtils.getNamespaceContextNoDefault(element); } /** * Return external-events configuration attribute. */ private Map getExternalEventsMap() { return (xformsStaticState == null) ? null : xformsStaticState.getExternalEventsMap(); } /** * Return whether an external event name is explicitly allowed by the configuration. * * @param eventName event name to check * @return true if allowed, false otherwise */ private boolean isExplicitlyAllowedExternalEvent(String eventName) { return !XFormsEventFactory.isBuiltInEvent(eventName) && getExternalEventsMap() != null && getExternalEventsMap().get(eventName) != null; } /** * Get object with the id specified. */ public Object getObjectById(String id) { // Search in models for (Iterator i = models.iterator(); i.hasNext();) { XFormsModel model = (XFormsModel) i.next(); final Object resultObject = model.getObjectByid(id); if (resultObject != null) return resultObject; } // Search in controls { final Object resultObject = xformsControls.getObjectById(id); if (resultObject != null) return resultObject; } // Check containing document if (id.equals(getEffectiveId())) return this; return null; } /** * Find the instance containing the specified node, in any model. * * @param nodeInfo node contained in an instance * @return instance containing the node */ public XFormsInstance getInstanceForNode(NodeInfo nodeInfo) { for (Iterator i = getModels().iterator(); i.hasNext();) { final XFormsModel currentModel = (XFormsModel) i.next(); final XFormsInstance currentInstance = currentModel.getInstanceForNode(nodeInfo); if (currentInstance != null) return currentInstance; } // This should not happen if the node is currently in an instance! return null; } /** * Find the instance with the specified id, searching in any model. * * @param instanceId id of the instance to find * @return instance containing the node */ public XFormsInstance findInstance(String instanceId) { for (Iterator i = getModels().iterator(); i.hasNext();) { final XFormsModel currentModel = (XFormsModel) i.next(); final XFormsInstance currentInstance = currentModel.getInstance(instanceId); if (currentInstance != null) return currentInstance; } return null; } /** * Return the active submission if any or null. */ public XFormsModelSubmission getClientActiveSubmission() { return activeSubmission; } /** * Clear current client state. */ private void clearClientState() { this.activeSubmission = null; this.gotSubmission = false; this.messagesToRun = null; this.loadsToRun = null; this.scriptsToRun = null; this.focusEffectiveControlId = null; this.helpEffectiveControlId = null; } /** * Set the active submission. * * This can be called with a non-null value at most once. */ public void setClientActiveSubmission(XFormsModelSubmission activeSubmission) { if (this.activeSubmission != null) throw new ValidationException("There is already an active submission.", activeSubmission.getLocationData()); if (loadsToRun != null) throw new ValidationException("Unable to run a two-pass submission and xforms:load within a same action sequence.", activeSubmission.getLocationData()); if (messagesToRun != null) throw new ValidationException("Unable to run a two-pass submission and xforms:message within a same action sequence.", activeSubmission.getLocationData()); if (scriptsToRun != null) throw new ValidationException("Unable to run a two-pass submission and xxforms:script within a same action sequence.", activeSubmission.getLocationData()); if (focusEffectiveControlId != null) throw new ValidationException("Unable to run a two-pass submission and xforms:setfocus within a same action sequence.", activeSubmission.getLocationData()); if (helpEffectiveControlId != null) throw new ValidationException("Unable to run a two-pass submission and xforms-help within a same action sequence.", activeSubmission.getLocationData()); this.activeSubmission = activeSubmission; } public boolean isGotSubmission() { return gotSubmission; } public void setGotSubmission(boolean gotSubmission) { this.gotSubmission = gotSubmission; } /** * Add an XForms message to send to the client. */ public void addMessageToRun(String message, String level) { if (activeSubmission != null) throw new ValidationException("Unable to run a two-pass submission and xforms:message within a same action sequence.", activeSubmission.getLocationData()); if (messagesToRun == null) messagesToRun = new ArrayList(); messagesToRun.add(new Message(message, level)); } /** * Return the list of messages to send to the client, null if none. */ public List getMessagesToRun() { return messagesToRun; } public static class Message { private String message; private String level; public Message(String message, String level) { this.message = message; this.level = level; } public String getMessage() { return message; } public String getLevel() { return level; } } public void addScriptToRun(String scriptId, String eventTargetId, String eventHandlerContainerId) { if (activeSubmission != null) throw new ValidationException("Unable to run a two-pass submission and xxforms:script within a same action sequence.", activeSubmission.getLocationData()); if (scriptsToRun == null) scriptsToRun = new ArrayList(); scriptsToRun.add(new Script(XFormsUtils.scriptIdToScriptName(scriptId), eventTargetId, eventHandlerContainerId)); } public static class Script { private String functionName; private String eventTargetId; private String eventHandlerContainerId; public Script(String functionName, String eventTargetId, String eventHandlerContainerId) { this.functionName = functionName; this.eventTargetId = eventTargetId; this.eventHandlerContainerId = eventHandlerContainerId; } public String getFunctionName() { return functionName; } public String getEventTargetId() { return eventTargetId; } public String getEventHandlerContainerId() { return eventHandlerContainerId; } } public List getScriptsToRun() { return scriptsToRun; } /** * Add an XForms load to send to the client. */ public void addLoadToRun(String resource, String target, String urlType, boolean isReplace, boolean isPortletLoad, boolean isShowProgress) { if (activeSubmission != null) throw new ValidationException("Unable to run a two-pass submission and xforms:load within a same action sequence.", activeSubmission.getLocationData()); if (loadsToRun == null) loadsToRun = new ArrayList(); loadsToRun.add(new Load(resource, target, urlType, isReplace, isPortletLoad, isShowProgress)); } /** * Return the list of messages to send to the client, null if none. */ public List getLoadsToRun() { return loadsToRun; } public static class Load { private String resource; private String target; private String urlType; private boolean isReplace; private boolean isPortletLoad; private boolean isShowProgress; public Load(String resource, String target, String urlType, boolean isReplace, boolean isPortletLoad, boolean isShowProgress) { this.resource = resource; this.target = target; this.urlType = urlType; this.isReplace = isReplace; this.isPortletLoad = isPortletLoad; this.isShowProgress = isShowProgress; } public String getResource() { return resource; } public String getTarget() { return target; } public String getUrlType() { return urlType; } public boolean isReplace() { return isReplace; } public boolean isPortletLoad() { return isPortletLoad; } public boolean isShowProgress() { return isShowProgress; } } /** * Tell the client that focus must be changed to the given effective control id. * * This can be called several times, but only the last controld id is remembered. * * @param effectiveControlId */ public void setClientFocusEffectiveControlId(String effectiveControlId) { if (activeSubmission != null) throw new ValidationException("Unable to run a two-pass submission and xforms:setfocus within a same action sequence.", activeSubmission.getLocationData()); this.focusEffectiveControlId = effectiveControlId; } /** * Return the effective control id of the control to set the focus to, or null. */ public String getClientFocusEffectiveControlId() { if (focusEffectiveControlId == null) return null; final XFormsControl xformsControl = (XFormsControl) getObjectById(focusEffectiveControlId); // It doesn't make sense to tell the client to set the focus to an element that is non-relevant or readonly if (xformsControl != null && xformsControl instanceof XFormsSingleNodeControl) { final XFormsSingleNodeControl xformsSingleNodeControl = (XFormsSingleNodeControl) xformsControl; if (xformsSingleNodeControl.isRelevant() && !xformsSingleNodeControl.isReadonly()) return focusEffectiveControlId; else return null; } else { return null; } } /** * Tell the client that help must be shown for the given effective control id. * * This can be called several times, but only the last controld id is remembered. * * @param effectiveControlId */ public void setClientHelpEffectiveControlId(String effectiveControlId) { if (activeSubmission != null) throw new ValidationException("Unable to run a two-pass submission and xforms-help within a same action sequence.", activeSubmission.getLocationData()); this.helpEffectiveControlId = effectiveControlId; } /** * Return the effective control id of the control to help for, or null. */ public String getClientHelpEffectiveControlId() { if (helpEffectiveControlId == null) return null; final XFormsControl xformsControl = (XFormsControl) getObjectById(helpEffectiveControlId); // It doesn't make sense to tell the client to show help for an element that is non-relevant, but we allow readonly if (xformsControl != null && xformsControl instanceof XFormsSingleNodeControl) { final XFormsSingleNodeControl xformsSingleNodeControl = (XFormsSingleNodeControl) xformsControl; if (xformsSingleNodeControl.isRelevant()) return helpEffectiveControlId; else return null; } else { return null; } } /** * Execute an external event on element with id targetElementId and event eventName. */ public void executeExternalEvent(PipelineContext pipelineContext, String eventName, String controlId, String otherControlId, String contextString, Element filesElement) { // Get event target object final XFormsEventTarget eventTarget; { final Object eventTargetObject = getObjectById(controlId); if (!(eventTargetObject instanceof XFormsEventTarget)) { if (XFormsProperties.isExceptionOnInvalidClientControlId(this)) { throw new ValidationException("Event target id '" + controlId + "' is not an XFormsEventTarget.", getLocationData()); } else { if (XFormsServer.logger.isDebugEnabled()) { logDebug("containing document", "ignoring client event with invalid control id", new String[] { "control id", controlId, "event name", eventName }); } return; } } eventTarget = (XFormsEventTarget) eventTargetObject; } // Don't allow for events on non-relevant, readonly or xforms:output controls (we accept focus events on // xforms:output though). // This is also a security measures that also ensures that somebody is not able to change values in an instance // by hacking external events. if (eventTarget instanceof XFormsControl) { // Target is a control if (eventTarget instanceof XXFormsDialogControl) { // Target is a dialog // Check for implicitly allowed events if (allowedXXFormsDialogExternalEvents.get(eventName) == null) { if (XFormsServer.logger.isDebugEnabled()) { logDebug("containing document", "ignoring invalid client event on xxforms:dialog", new String[] { "control id", controlId, "event name", eventName }); } return; } } else { // Target is a regular control // Only single-node controls accept events from the client if (!(eventTarget instanceof XFormsSingleNodeControl)) { if (XFormsServer.logger.isDebugEnabled()) { logDebug("containing document", "ignoring invalid client event on non-single-node control", new String[] { "control id", controlId, "event name", eventName }); } return; } final XFormsSingleNodeControl xformsControl = (XFormsSingleNodeControl) eventTarget; if (!xformsControl.isRelevant() || (xformsControl.isReadonly() && !(xformsControl instanceof XFormsOutputControl))) { // Controls accept event only if they are relevant and not readonly, except for xforms:output which may be readonly if (XFormsServer.logger.isDebugEnabled()) { logDebug("containing document", "ignoring invalid client event on non-relevant or read-only control", new String[] { "control id", controlId, "event name", eventName }); } return; } if (!isExplicitlyAllowedExternalEvent(eventName)) { // The event is not explicitly allowed: check for implicitly allowed events if (xformsControl instanceof XFormsOutputControl) { if (allowedXFormsOutputExternalEvents.get(eventName) == null) { if (XFormsServer.logger.isDebugEnabled()) { logDebug("containing document", "ignoring invalid client event on xforms:output", new String[] { "control id", controlId, "event name", eventName }); } return; } } else if (xformsControl instanceof XFormsUploadControl) { if (allowedXFormsUploadExternalEvents.get(eventName) == null) { if (XFormsServer.logger.isDebugEnabled()) { logDebug("containing document", "ignoring invalid client event on xforms:upload", new String[] { "control id", controlId, "event name", eventName }); } return; } } else { if (allowedExternalEvents.get(eventName) == null) { if (XFormsServer.logger.isDebugEnabled()) { logDebug("containing document", "ignoring invalid client event", new String[] { "control id", controlId, "event name", eventName }); } return; } } } } } else if (eventTarget instanceof XFormsModelSubmission) { // Target is a submission if (!isExplicitlyAllowedExternalEvent(eventName)) { // The event is not explicitly allowed: check for implicitly allowed events if (allowedXFormsSubmissionExternalEvents.get(eventName) == null) { if (XFormsServer.logger.isDebugEnabled()) { logDebug("containing document", "ignoring invalid client event on xforms:submission", new String[] { "control id", controlId, "event name", eventName }); } return; } } } else if (eventTarget instanceof XFormsContainingDocument) { // Target is the containing document // Check for implicitly allowed events if (allowedXFormsContainingDocumentExternalEvents.get(eventName) == null) { if (XFormsServer.logger.isDebugEnabled()) { logDebug("containing document", "ignoring invalid client event on containing document", new String[] { "control id", controlId, "event name", eventName }); } return; } } else { // Target is not a control if (!isExplicitlyAllowedExternalEvent(eventName)) { // The event is not explicitly allowed if (XFormsServer.logger.isDebugEnabled()) { logDebug("containing document", "ignoring invalid client event", new String[] { "control id", controlId, "event name", eventName }); } return; } } // Get other event target final XFormsEventTarget otherEventTarget; { final Object otherEventTargetObject = (otherControlId == null) ? null : getObjectById(otherControlId); if (otherEventTargetObject == null) { otherEventTarget = null; } else if (!(otherEventTargetObject instanceof XFormsEventTarget)) { if (XFormsProperties.isExceptionOnInvalidClientControlId(this)) { throw new ValidationException("Other event target id '" + otherControlId + "' is not an XFormsEventTarget.", getLocationData()); } else { if (XFormsServer.logger.isDebugEnabled()) { logDebug("containing document", "ignoring invalid client event with invalid second control id", new String[] { "control id", controlId, "event name", eventName, "second control id", otherControlId }); } return; } } else { otherEventTarget = (XFormsEventTarget) otherEventTargetObject; } } // Handle repeat focus. Don't dispatch event on DOMFocusOut however. if (controlId.indexOf(XFormsConstants.REPEAT_HIERARCHY_SEPARATOR_1) != -1 && !XFormsEvents.XFORMS_DOM_FOCUS_OUT.equals(eventName)) { // The event target is in a repeated structure, so make sure it gets repeat focus dispatchEvent(pipelineContext, new XXFormsRepeatFocusEvent(eventTarget)); } // Handle xforms:output if (eventTarget instanceof XFormsOutputControl) { // Note that repeat focus may have been dispatched already if (XFormsEvents.XFORMS_DOM_FOCUS_IN.equals(eventName)) { // We convert the focus event into a DOMActivate unless the control is read-only final XFormsOutputControl xformsOutputControl = (XFormsOutputControl) eventTarget; if (xformsOutputControl.isReadonly()) { return; } else { eventName = XFormsEvents.XFORMS_DOM_ACTIVATE; } } else if (ignoredXFormsOutputExternalEvents.equals(eventName)) { return; } } // Create event if (XFormsProperties.isAjaxTest()) { if (eventName.equals(XFormsEvents.XXFORMS_VALUE_CHANGE_WITH_FOCUS_CHANGE)) { if ("category-select1".equals(controlId)) { if (testAjaxToggleValue == 0) { testAjaxToggleValue = 1; contextString = "supplier"; } else { testAjaxToggleValue = 0; contextString = "customer"; } } else if (("xforms-element-287" + XFormsConstants.REPEAT_HIERARCHY_SEPARATOR_1 + "1").equals(controlId)) { contextString = "value" + System.currentTimeMillis(); } } } final XFormsEvent xformsEvent = XFormsEventFactory.createEvent(eventName, eventTarget, otherEventTarget, true, true, true, contextString, null, null, filesElement); // Interpret event if (xformsEvent instanceof XXFormsValueChangeWithFocusChangeEvent) { // 4.6.7 Sequence: Value Change // What we want to do here is set the value on the initial controls state, as the value // has already been changed on the client. This means that this event(s) must be the // first to come! final XXFormsValueChangeWithFocusChangeEvent concreteEvent = (XXFormsValueChangeWithFocusChangeEvent) xformsEvent; // 1. xforms-recalculate // 2. xforms-revalidate // 3. xforms-refresh performs reevaluation of UI binding expressions then dispatches // these events according to value changes, model item property changes and validity // changes // [n] xforms-value-changed, [n] xforms-valid or xforms-invalid, [n] xforms-enabled or // xforms-disabled, [n] xforms-optional or xforms-required, [n] xforms-readonly or // xforms-readwrite, [n] xforms-out-of-range or xforms-in-range final String targetControlEffectiveId; { // Set current context to control final XFormsValueControl valueXFormsControl = (XFormsValueControl) concreteEvent.getTargetObject(); targetControlEffectiveId = valueXFormsControl.getEffectiveId(); // Notify the control of the value change final String eventValue = concreteEvent.getNewValue(); valueXFormsControl.setExternalValue(pipelineContext, eventValue, null); } { // NOTE: Recalculate and revalidate are done with the automatic deferred updates // Handle focus change DOMFocusOut / DOMFocusIn if (concreteEvent.getOtherTargetObject() != null) { final XFormsControl sourceXFormsControl = (XFormsControl) getObjectById(targetControlEffectiveId); final XFormsControl otherTargetXFormsControl = (XFormsControl) getObjectById(((XFormsControl) concreteEvent.getOtherTargetObject()).getEffectiveId()); // We have a focus change (otherwise, the focus is assumed to remain the same) if (sourceXFormsControl != null) dispatchEvent(pipelineContext, new XFormsDOMFocusOutEvent(sourceXFormsControl)); if (otherTargetXFormsControl != null) dispatchEvent(pipelineContext, new XFormsDOMFocusInEvent(otherTargetXFormsControl)); } // NOTE: Refresh is done with the automatic deferred updates } } else { // Dispatch any other allowed event dispatchEvent(pipelineContext, xformsEvent); } } /** * Prepare the ContainingDocumentg for a sequence of external events. */ public void prepareForExternalEventsSequence(PipelineContext pipelineContext) { // Clear containing document state clearClientState(); // Initialize controls xformsControls.initialize(pipelineContext); } public void startOutermostActionHandler() { for (Iterator i = getModels().iterator(); i.hasNext();) { final XFormsModel currentModel = (XFormsModel) i.next(); currentModel.startOutermostActionHandler(); } } public void endOutermostActionHandler(PipelineContext pipelineContext) { for (Iterator i = getModels().iterator(); i.hasNext();) { final XFormsModel currentModel = (XFormsModel) i.next(); currentModel.endOutermostActionHandler(pipelineContext); } } public void synchronizeInstanceDataEventState() { for (Iterator i = getModels().iterator(); i.hasNext();) { final XFormsModel currentModel = (XFormsModel) i.next(); currentModel.synchronizeInstanceDataEventState(); } } public XFormsEventHandlerContainer getParentContainer(XFormsContainingDocument containingDocument) { return null; } public List getEventHandlers(XFormsContainingDocument containingDocument) { return null; } public String getId() { return CONTAINING_DOCUMENT_PSEUDO_ID; } public String getEffectiveId() { return getId(); } public LocationData getLocationData() { return (xformsStaticState != null) ? xformsStaticState.getLocationData() : null; } public void performDefaultAction(PipelineContext pipelineContext, XFormsEvent event) { final String eventName = event.getEventName(); if (XFormsEvents.XXFORMS_LOAD.equals(eventName)) { // Internal load event final XXFormsLoadEvent xxformsLoadEvent = (XXFormsLoadEvent) event; final ExternalContext externalContext = (ExternalContext) pipelineContext.getAttribute(PipelineContext.EXTERNAL_CONTEXT); try { final String resource = xxformsLoadEvent.getResource(); final String pathInfo; final Map parameters; final int qmIndex = resource.indexOf('?'); if (qmIndex != -1) { pathInfo = resource.substring(0, qmIndex); parameters = NetUtils.decodeQueryString(resource.substring(qmIndex + 1), false); } else { pathInfo = resource; parameters = null; } externalContext.getResponse().sendRedirect(pathInfo, parameters, false, false); } catch (IOException e) { throw new ValidationException(e, getLocationData()); } } } /** * Main event dispatching entry. */ public void dispatchEvent(PipelineContext pipelineContext, XFormsEvent event) { if (XFormsServer.logger.isDebugEnabled()) { logDebug("event", "dispatching", new String[] { "name", event.getEventName(), "id", event.getTargetObject().getEffectiveId(), "location", event.getLocationData().toString() }); } final XFormsEventTarget targetObject = event.getTargetObject(); try { if (targetObject == null) throw new ValidationException("Target object null for event: " + event.getEventName(), getLocationData()); // Find all event handler containers final List containers = new ArrayList(); { XFormsEventHandlerContainer container = (targetObject instanceof XFormsEventHandlerContainer) ? (XFormsEventHandlerContainer) targetObject : targetObject.getParentContainer(this); while (container != null) { containers.add(container); container = container.getParentContainer(this); } } boolean propagate = true; boolean performDefaultAction = true; // Go from root to leaf Collections.reverse(containers); // Capture phase for (Iterator i = containers.iterator(); i.hasNext();) { final XFormsEventHandlerContainer container = (XFormsEventHandlerContainer) i.next(); final List eventHandlers = container.getEventHandlers(this); if (eventHandlers != null) { if (container != targetObject) { // Event listeners on the target which are in capture mode are not called for (Iterator j = eventHandlers.iterator(); j.hasNext();) { final XFormsEventHandler eventHandler = (XFormsEventHandler) j.next(); if (!eventHandler.isPhase() && eventHandler.getEventName().equals(event.getEventName()) && (eventHandler.getTargetId() == null || eventHandler.getTargetId().equals(event.getTargetObject().getId()))) { // Capture phase match on event name and target is specified startHandleEvent(event); try { eventHandler.handleEvent(pipelineContext, XFormsContainingDocument.this, container, event); } finally { endHandleEvent(); } propagate &= eventHandler.isPropagate(); performDefaultAction &= eventHandler.isDefaultAction(); } } // Cancel propagation if requested and if authorized by event if (!propagate && event.isCancelable()) break; } } } // Go from leaf to root Collections.reverse(containers); // Bubbling phase if (propagate && event.isBubbles()) { for (Iterator i = containers.iterator(); i.hasNext();) { final XFormsEventHandlerContainer container = (XFormsEventHandlerContainer) i.next(); final List eventHandlers = container.getEventHandlers(this); if (eventHandlers != null) { for (Iterator j = eventHandlers.iterator(); j.hasNext();) { final XFormsEventHandler eventHandler = (XFormsEventHandler) j.next(); if (eventHandler.isPhase() && eventHandler.getEventName().equals(event.getEventName()) && (eventHandler.getTargetId() == null || eventHandler.getTargetId().equals(event.getTargetObject().getId()))) { // Bubbling phase match on event name and target is specified startHandleEvent(event); try { eventHandler.handleEvent(pipelineContext, XFormsContainingDocument.this, container, event); } finally { endHandleEvent(); } propagate &= eventHandler.isPropagate(); performDefaultAction &= eventHandler.isDefaultAction(); } } // Cancel propagation if requested and if authorized by event if (!propagate) break; } } } // Perform default action is allowed to if (performDefaultAction || !event.isCancelable()) { startHandleEvent(event); try { targetObject.performDefaultAction(pipelineContext, event); } finally { endHandleEvent(); } } } catch (Exception e) { // Add location information if possible final LocationData locationData = (targetObject != null) ? ((targetObject.getLocationData() != null) ? targetObject.getLocationData() : getLocationData()) : null; throw ValidationException.wrapException(e, new ExtendedLocationData(locationData, "dispatching XForms event", new String[] { "event", event.getEventName(), "target id", targetObject.getEffectiveId() })); } } private int logIndentLevel = 0; private Stack eventStack = new Stack(); private void startHandleEvent(XFormsEvent event) { eventStack.push(event); logIndentLevel++; } private void endHandleEvent() { eventStack.pop(); logIndentLevel } public void startHandleOperation() { logIndentLevel++; } public void endHandleOperation() { logIndentLevel } private static String getLogIndentSpaces(int level) { final StringBuffer sb = new StringBuffer(); for (int i = 0; i < level; i++) sb.append(" "); return sb.toString(); } public void logDebug(String type, String message) { log(Level.DEBUG, logIndentLevel, type, message, null); } public void logDebug(String type, String message, String[] parameters) { log(Level.DEBUG, logIndentLevel, type, message, parameters); } public static void logDebugStatic(String type, String message) { logDebugStatic(null, type, message); } public static void logDebugStatic(String type, String message, String[] parameters) { logDebugStatic(null, type, message, parameters); } public static void logDebugStatic(XFormsContainingDocument containingDocument, String type, String message) { log(Level.DEBUG, (containingDocument != null) ? containingDocument.logIndentLevel : 0, type, message, null); } public static void logDebugStatic(XFormsContainingDocument containingDocument, String type, String message, String[] parameters) { log(Level.DEBUG, (containingDocument != null) ? containingDocument.logIndentLevel : 0, type, message, parameters); } public void logWarning(String type, String message, String[] parameters) { log(Level.WARN, logIndentLevel, type, message, parameters); } private static void log(Level level, int indentLevel, String type, String message, String[] parameters) { final String parametersString; if (parameters != null) { final FastStringBuffer sb = new FastStringBuffer(" {"); if (parameters != null) { boolean first = true; for (int i = 0; i < parameters.length; i += 2) { final String paramName = parameters[i]; final String paramValue = parameters[i + 1]; if (paramValue != null) { if (!first) sb.append(", "); sb.append(paramName); sb.append(": \""); sb.append(paramValue); sb.append('\"'); first = false; } } } sb.append('}'); parametersString = sb.toString(); } else { parametersString = ""; } XFormsServer.logger.log(level, "XForms - " + getLogIndentSpaces(indentLevel) + type + " - " + message + parametersString); } /** * Return the event being processed by the current event handler, null if no event is being processed. */ public XFormsEvent getCurrentEvent() { return (eventStack.size() == 0) ? null : (XFormsEvent) eventStack.peek(); } /** * Create an encoded dynamic state that represents the dynamic state of this XFormsContainingDocument. * * @param pipelineContext current PipelineContext * @return encoded dynamic state */ public String createEncodedDynamicState(PipelineContext pipelineContext) { return XFormsUtils.encodeXML(pipelineContext, createDynamicStateDocument(), XFormsProperties.isClientStateHandling(this) ? XFormsProperties.getXFormsPassword() : null, false); } private Document createDynamicStateDocument() { final XFormsControls.ControlsState currentControlsState = getXFormsControls().getCurrentControlsState(); final Document dynamicStateDocument = Dom4jUtils.createDocument(); final Element dynamicStateElement = dynamicStateDocument.addElement("dynamic-state"); // Output instances { final Element instancesElement = dynamicStateElement.addElement("instances"); for (Iterator i = getModels().iterator(); i.hasNext();) { final XFormsModel currentModel = (XFormsModel) i.next(); if (currentModel.getInstances() != null) { for (Iterator j = currentModel.getInstances().iterator(); j.hasNext();) { final XFormsInstance currentInstance = (XFormsInstance) j.next(); // TODO: can we avoid storing the instance in the dynamic state if it has not changed from static state? if (currentInstance.isReplaced() || !(currentInstance instanceof SharedXFormsInstance)) { // Instance has been replaced, or it is not shared, so it has to go in the dynamic state instancesElement.add(currentInstance.createContainerElement(!currentInstance.isApplicationShared())); // Log instance if needed currentInstance.logIfNeeded(this, "storing instance to dynamic state"); } } } } } // Output divs information { final Element divsElement = Dom4jUtils.createElement("divs"); outputSwitchesDialogs(divsElement, getXFormsControls()); if (divsElement.hasContent()) dynamicStateElement.add(divsElement); } // Output repeat index information { final Map repeatIdToIndex = currentControlsState.getRepeatIdToIndex(); if (repeatIdToIndex.size() != 0) { final Element repeatIndexesElement = dynamicStateElement.addElement("repeat-indexes"); for (Iterator i = repeatIdToIndex.entrySet().iterator(); i.hasNext();) { final Map.Entry currentEntry = (Map.Entry) i.next(); final String repeatId = (String) currentEntry.getKey(); final Integer index = (Integer) currentEntry.getValue(); final Element newElement = repeatIndexesElement.addElement("repeat-index"); newElement.addAttribute("id", repeatId); newElement.addAttribute("index", index.toString()); } } } return dynamicStateDocument; } public static void outputSwitchesDialogs(Element divsElement, XFormsControls xformsControls) { { final Map switchIdToSelectedCaseIdMap = xformsControls.getCurrentSwitchState().getSwitchIdToSelectedCaseIdMap(); if (switchIdToSelectedCaseIdMap != null) { // There are some xforms:switch/xforms:case controls for (Iterator i = switchIdToSelectedCaseIdMap.entrySet().iterator(); i.hasNext();) { final Map.Entry currentEntry = (Map.Entry) i.next(); final String switchId = (String) currentEntry.getKey(); final String selectedCaseId = (String) currentEntry.getValue(); // Output selected ids { final Element divElement = divsElement.addElement("xxf:div", XFormsConstants.XXFORMS_NAMESPACE_URI); divElement.addAttribute("switch-id", switchId); divElement.addAttribute("case-id", selectedCaseId); divElement.addAttribute("visibility", "visible"); } // Output deselected ids final XFormsControl switchXFormsControl = (XFormsControl) xformsControls.getObjectById(switchId); final List children = switchXFormsControl.getChildren(); if (children != null && children.size() > 0) { for (Iterator j = children.iterator(); j.hasNext();) { final XFormsControl caseXFormsControl = (XFormsControl) j.next(); if (!caseXFormsControl.getEffectiveId().equals(selectedCaseId)) { final Element divElement = divsElement.addElement("xxf:div", XFormsConstants.XXFORMS_NAMESPACE_URI); divElement.addAttribute("switch-id", switchId); divElement.addAttribute("case-id", caseXFormsControl.getEffectiveId()); divElement.addAttribute("visibility", "hidden"); } } } } } } { final Map dialogIdToVisibleMap = xformsControls.getCurrentDialogState().getDialogIdToVisibleMap(); if (dialogIdToVisibleMap != null) { // There are some xxforms:dialog controls for (Iterator i = dialogIdToVisibleMap.entrySet().iterator(); i.hasNext();) { final Map.Entry currentEntry = (Map.Entry) i.next(); final String dialogId = (String) currentEntry.getKey(); final XFormsControls.DialogState.DialogInfo dialogInfo = (XFormsControls.DialogState.DialogInfo) currentEntry.getValue(); // Output element and attributes { final Element divElement = divsElement.addElement("xxf:div", XFormsConstants.XXFORMS_NAMESPACE_URI); divElement.addAttribute("dialog-id", dialogId); divElement.addAttribute("visibility", dialogInfo.isShow() ? "visible" : "hidden"); if (dialogInfo.isShow()) { if (dialogInfo.getNeighbor() != null) divElement.addAttribute("neighbor", dialogInfo.getNeighbor()); if (dialogInfo.isConstrainToViewport()) divElement.addAttribute("constrain", Boolean.toString(dialogInfo.isConstrainToViewport())); } } } } } } private void restoreDynamicState(PipelineContext pipelineContext, String encodedDynamicState) { // Get dynamic state document final Document dynamicStateDocument = XFormsUtils.decodeXML(pipelineContext, encodedDynamicState); // Get repeat indexes from dynamic state final Element repeatIndexesElement = dynamicStateDocument.getRootElement().element("repeat-indexes"); // Create XForms controls and models createControlAndModel(repeatIndexesElement); // Extract and restore instances { // Get instances from dynamic state first final Element instancesElement = dynamicStateDocument.getRootElement().element("instances"); if (instancesElement != null) { for (Iterator i = instancesElement.elements().iterator(); i.hasNext();) { final Element instanceElement = (Element) i.next(); // Create and set instance document on current model final XFormsInstance newInstance = new XFormsInstance(instanceElement); if (newInstance.getDocumentInfo() == null) { // Instance is not initialized yet // This means that the instance was application shared if (!newInstance.isApplicationShared()) throw new ValidationException("Non-initialized instance has to be application shared for id: " + newInstance.getEffectiveId(), getLocationData()); final SharedXFormsInstance sharedInstance = XFormsServerSharedInstancesCache.instance().find(pipelineContext, this, newInstance.getEffectiveId(), newInstance.getModelId(), newInstance.getSourceURI(), newInstance.getTimeToLive(), newInstance.getValidation()); getModel(sharedInstance.getModelId()).setInstance(sharedInstance, false); } else { // Instance is initialized, just use it getModel(newInstance.getModelId()).setInstance(newInstance, newInstance.isReplaced()); } // Log instance if needed newInstance.logIfNeeded(this, "restoring instance from dynamic state"); } } // Then get instances from static state if necessary final Map staticInstancesMap = xformsStaticState.getInstancesMap(); if (staticInstancesMap != null && staticInstancesMap.size() > 0) { for (Iterator instancesIterator = staticInstancesMap.values().iterator(); instancesIterator.hasNext();) { final XFormsInstance currentInstance = (XFormsInstance) instancesIterator.next(); if (findInstance(currentInstance.getEffectiveId()) == null) { // Instance was not set from dynamic state if (currentInstance.getDocumentInfo() == null) { // Instance is not initialized yet // This means that the instance was application shared if (!currentInstance.isApplicationShared()) throw new ValidationException("Non-initialized instance has to be application shared for id: " + currentInstance.getEffectiveId(), getLocationData()); final SharedXFormsInstance sharedInstance = XFormsServerSharedInstancesCache.instance().find(pipelineContext, this, currentInstance.getEffectiveId(), currentInstance.getModelId(), currentInstance.getSourceURI(), currentInstance.getTimeToLive(), currentInstance.getValidation()); getModel(sharedInstance.getModelId()).setInstance(sharedInstance, false); } else { // Instance is initialized, just use it getModel(currentInstance.getModelId()).setInstance(currentInstance, false); } } } } } // Restore models state for (Iterator j = getModels().iterator(); j.hasNext();) { final XFormsModel currentModel = (XFormsModel) j.next(); currentModel.initializeState(pipelineContext); } // Restore controls final Element divsElement = dynamicStateDocument.getRootElement().element("divs"); xformsControls.initializeState(pipelineContext, divsElement, repeatIndexesElement, true); xformsControls.evaluateAllControlsIfNeeded(pipelineContext); } /** * Whether, during initialization, this is the first refresh. The flag is automatically cleared during this call so * that only the first call returns true. * * @return true if this is the first refresh, false otherwise */ public boolean isInitializationFirstRefreshClear() { boolean result = mustPerformInitializationFirstRefresh; mustPerformInitializationFirstRefresh = false; return result; } private void initialize(PipelineContext pipelineContext) { // This is called upon the first creation of the XForms engine only // Create XForms controls and models createControlAndModel(null); // 4.2 Initialization Events // 1. Dispatch xforms-model-construct to all models // 2. Dispatch xforms-model-construct-done to all models // 3. Dispatch xforms-ready to all models // Before dispaching initialization events, remember that first refresh must be performed this.mustPerformInitializationFirstRefresh = true; final String[] eventsToDispatch = { XFormsEvents.XFORMS_MODEL_CONSTRUCT, XFormsEvents.XFORMS_MODEL_CONSTRUCT_DONE, XFormsEvents.XFORMS_READY, XFormsEvents.XXFORMS_READY }; for (int i = 0; i < eventsToDispatch.length; i++) { // Initialize controls right at the beginning final boolean isXFormsModelConstructDone = i == 1; if (isXFormsModelConstructDone) { // Initialize controls after all the xforms-model-construct events have been sent xformsControls.initialize(pipelineContext); } // Group all xforms-ready events within a single outermost action handler in order to optimize events final boolean isXFormsReady = i == 2; if (isXFormsReady) { // Performed deferred updates only for xforms-ready startOutermostActionHandler(); } // Iterate over all the models for (Iterator j = getModels().iterator(); j.hasNext();) { final XFormsModel currentModel = (XFormsModel) j.next(); // Make sure there is at least one refresh final XFormsModel.DeferredActionContext deferredActionContext = currentModel.getDeferredActionContext(); if (deferredActionContext != null) { deferredActionContext.refresh = true; } dispatchEvent(pipelineContext, XFormsEventFactory.createEvent(eventsToDispatch[i], currentModel)); } if (isXFormsReady) { // Performed deferred updates only for xforms-ready endOutermostActionHandler(pipelineContext); } } // In case there is no model or no controls, make sure the flag is cleared as it is only relevant during // initialization this.mustPerformInitializationFirstRefresh = false; } private void createControlAndModel(Element repeatIndexesElement) { if (xformsStaticState != null) { // Gather static analysis information final long startTime = XFormsServer.logger.isDebugEnabled() ? System.currentTimeMillis() : 0; final boolean analyzed = xformsStaticState.analyzeIfNecessary(); if (XFormsServer.logger.isDebugEnabled()) { if (analyzed) logDebug("containing document", "performed static analysis", new String[] { "time", Long.toString(System.currentTimeMillis() - startTime) }); else logDebug("containing document", "static analysis already available"); } // Create XForms controls xformsControls = new XFormsControls(this, xformsStaticState, repeatIndexesElement); // Create and index models for (Iterator i = xformsStaticState.getModelDocuments().iterator(); i.hasNext();) { final Document modelDocument = (Document) i.next(); final XFormsModel model = new XFormsModel(modelDocument); model.setContainingDocument(this); // NOTE: This requires the XFormsControls to be set on XFormsContainingDocument this.models.add(model); if (model.getEffectiveId() != null) this.modelsMap.put(model.getEffectiveId(), model); } } } }
package refdiff.core.io; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.function.BiConsumer; import org.eclipse.jgit.api.CheckoutCommand; import org.eclipse.jgit.api.Git; import org.eclipse.jgit.diff.DiffEntry; import org.eclipse.jgit.diff.DiffEntry.ChangeType; import org.eclipse.jgit.diff.RenameDetector; import org.eclipse.jgit.errors.MissingObjectException; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.ObjectReader; import org.eclipse.jgit.lib.Ref; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.lib.RepositoryBuilder; import org.eclipse.jgit.revwalk.RevCommit; import org.eclipse.jgit.revwalk.RevWalk; import org.eclipse.jgit.revwalk.RevWalkUtils; import org.eclipse.jgit.revwalk.filter.RevFilter; import org.eclipse.jgit.transport.FetchResult; import org.eclipse.jgit.transport.TrackingRefUpdate; import org.eclipse.jgit.treewalk.CanonicalTreeParser; import refdiff.core.util.PairBeforeAfter; public class GitHelper { private static final String REMOTE_REFS_PREFIX = "refs/remotes/origin/"; DefaultCommitsFilter commitsFilter = new DefaultCommitsFilter(); public Repository cloneIfNotExists(String projectPath, String cloneUrl/* , String branch */) throws Exception { File folder = new File(projectPath); Repository repository; if (folder.exists()) { RepositoryBuilder builder = new RepositoryBuilder(); repository = builder .setGitDir(new File(folder, ".git")) .readEnvironment() .findGitDir() .build(); // logger.info("Project {} is already cloned, current branch is {}", cloneUrl, repository.getBranch()); } else { Git git = Git.cloneRepository() .setDirectory(folder) .setURI(cloneUrl) .setCloneAllBranches(true) .call(); repository = git.getRepository(); // logger.info("Done cloning {}, current branch is {}", cloneUrl, repository.getBranch()); } // if (branch != null && !repository.getBranch().equals(branch)) { // Git git = new Git(repository); // String localBranch = "refs/heads/" + branch; // List<Ref> refs = git.branchList().call(); // boolean branchExists = false; // for (Ref ref : refs) { // if (ref.getName().equals(localBranch)) { // branchExists = true; // if (branchExists) { // git.checkout() // .setName(branch) // .call(); // } else { // git.checkout() // .setCreateBranch(true) // .setName(branch) // .setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK) // .setStartPoint("origin/" + branch) // .call(); // logger.info("Project {} switched to {}", cloneUrl, repository.getBranch()); return repository; } public Repository openRepository(String repositoryPath) throws Exception { return openRepository(new File(repositoryPath, ".git")); } public Repository openRepository(File repositoryPath) { try { if (repositoryPath.exists()) { RepositoryBuilder builder = new RepositoryBuilder(); Repository repository = builder .setGitDir(repositoryPath) .readEnvironment() .findGitDir() .build(); return repository; } else { throw new FileNotFoundException(repositoryPath.getPath()); } } catch (IOException e) { throw new RuntimeException(e); } } public void forEachNonMergeCommit(Repository repo, int maxDepth, BiConsumer<RevCommit, RevCommit> function) throws Exception { try (RevWalk revWalk = new RevWalk(repo)) { RevCommit head = revWalk.parseCommit(repo.resolve("HEAD")); revWalk.markStart(head); revWalk.setRevFilter(RevFilter.NO_MERGES); int count = 0; for (RevCommit commit : revWalk) { if (commit.getParentCount() == 1) { function.accept(commit.getParent(0), commit); } count++; if (count >= maxDepth) break; } } } public void checkout(Repository repository, String commitId) throws Exception { try (Git git = new Git(repository)) { CheckoutCommand checkout = git.checkout().setName(commitId); checkout.call(); } // File workingDir = repository.getDirectory().getParentFile(); // ExternalProcess.execute(workingDir, "git", "checkout", commitId); } public RevCommit resolveCommit(Repository repository, String commitId) throws Exception { ObjectId oid = repository.resolve(commitId); if (oid == null) { return null; } try (RevWalk rw = new RevWalk(repository)) { return rw.parseCommit(oid); } catch (MissingObjectException e) { return null; } } public PairBeforeAfter<SourceFileSet> getSourcesBeforeAndAfterCommit(Repository repository, RevCommit commitBefore, RevCommit commitAfter, List<String> fileExtensions) throws Exception { List<SourceFile> filesBefore = new ArrayList<>(); List<SourceFile> filesAfter = new ArrayList<>(); fileTreeDiff(repository, commitBefore, commitAfter, filesBefore, filesAfter, fileExtensions); return new PairBeforeAfter<>( new GitSourceTree(repository, commitBefore.getId(), filesBefore), new GitSourceTree(repository, commitAfter.getId(), filesAfter)); } public PairBeforeAfter<SourceFileSet> getSourcesBeforeAndAfterCommit(Repository repository, String commitId, List<String> fileExtensions) throws Exception { try (RevWalk rw = new RevWalk(repository)) { RevCommit commitAfter = rw.parseCommit(repository.resolve(commitId)); if (commitAfter.getParentCount() != 1) { throw new RuntimeException("Commit should have one parent"); } RevCommit commitBefore = rw.parseCommit(commitAfter.getParent(0)); return getSourcesBeforeAndAfterCommit(repository, commitBefore, commitAfter, fileExtensions); } } public PairBeforeAfter<SourceFileSet> getSourcesBeforeAndAfterCommit(Repository repository, String commitIdBefore, String commitIdAfter, List<String> fileExtensions) throws Exception { try (RevWalk rw = new RevWalk(repository)) { RevCommit commitBefore = rw.parseCommit(repository.resolve(commitIdBefore)); RevCommit commitAfter = rw.parseCommit(repository.resolve(commitIdAfter)); return getSourcesBeforeAndAfterCommit(repository, commitBefore, commitAfter, fileExtensions); } } public int countCommits(Repository repository, String branch) throws Exception { RevWalk walk = new RevWalk(repository); try { Ref ref = repository.findRef(REMOTE_REFS_PREFIX + branch); ObjectId objectId = ref.getObjectId(); RevCommit start = walk.parseCommit(objectId); walk.setRevFilter(RevFilter.NO_MERGES); return RevWalkUtils.count(walk, start, null); } finally { walk.dispose(); } } private List<TrackingRefUpdate> fetch(Repository repository) throws Exception { try (Git git = new Git(repository)) { FetchResult result = git.fetch().call(); Collection<TrackingRefUpdate> updates = result.getTrackingRefUpdates(); List<TrackingRefUpdate> remoteRefsChanges = new ArrayList<TrackingRefUpdate>(); for (TrackingRefUpdate update : updates) { String refName = update.getLocalName(); if (refName.startsWith(REMOTE_REFS_PREFIX)) { remoteRefsChanges.add(update); } } return remoteRefsChanges; } } public RevWalk fetchAndCreateNewRevsWalk(Repository repository) throws Exception { return this.fetchAndCreateNewRevsWalk(repository, null); } public RevWalk fetchAndCreateNewRevsWalk(Repository repository, String branch) throws Exception { List<ObjectId> currentRemoteRefs = new ArrayList<ObjectId>(); for (Ref ref : repository.getAllRefs().values()) { String refName = ref.getName(); if (refName.startsWith(REMOTE_REFS_PREFIX)) { currentRemoteRefs.add(ref.getObjectId()); } } List<TrackingRefUpdate> newRemoteRefs = this.fetch(repository); RevWalk walk = new RevWalk(repository); for (TrackingRefUpdate newRef : newRemoteRefs) { if (branch == null || newRef.getLocalName().endsWith("/" + branch)) { walk.markStart(walk.parseCommit(newRef.getNewObjectId())); } } for (ObjectId oldRef : currentRemoteRefs) { walk.markUninteresting(walk.parseCommit(oldRef)); } walk.setRevFilter(commitsFilter); return walk; } public RevWalk createAllRevsWalk(Repository repository) throws Exception { return this.createAllRevsWalk(repository, null); } public RevWalk createAllRevsWalk(Repository repository, String branch) throws Exception { List<ObjectId> currentRemoteRefs = new ArrayList<ObjectId>(); for (Ref ref : repository.getAllRefs().values()) { String refName = ref.getName(); if (refName.startsWith(REMOTE_REFS_PREFIX)) { if (branch == null || refName.endsWith("/" + branch)) { currentRemoteRefs.add(ref.getObjectId()); } } } RevWalk walk = new RevWalk(repository); for (ObjectId newRef : currentRemoteRefs) { walk.markStart(walk.parseCommit(newRef)); } walk.setRevFilter(commitsFilter); return walk; } public boolean isCommitAnalyzed(String sha1) { return false; } private class DefaultCommitsFilter extends RevFilter { @Override public final boolean include(final RevWalk walker, final RevCommit c) { return c.getParentCount() == 1 && !isCommitAnalyzed(c.getName()); } @Override public final RevFilter clone() { return this; } @Override public final boolean requiresCommitBody() { return false; } @Override public String toString() { return "RegularCommitsFilter"; } } public void fileTreeDiff(Repository repository, RevCommit current, List<String> javaFilesBefore, List<String> javaFilesCurrent, Map<String, String> renamedFilesHint, boolean detectRenames, List<String> fileExtensions) throws Exception { ObjectId oldHead = current.getParent(0).getTree(); ObjectId head = current.getTree(); // prepare the two iterators to compute the diff between ObjectReader reader = repository.newObjectReader(); CanonicalTreeParser oldTreeIter = new CanonicalTreeParser(); oldTreeIter.reset(reader, oldHead); CanonicalTreeParser newTreeIter = new CanonicalTreeParser(); newTreeIter.reset(reader, head); // finally get the list of changed files try (Git git = new Git(repository)) { List<DiffEntry> diffs = git.diff() .setNewTree(newTreeIter) .setOldTree(oldTreeIter) .setShowNameAndStatusOnly(true) .call(); if (detectRenames) { RenameDetector rd = new RenameDetector(repository); rd.addAll(diffs); diffs = rd.compute(); } for (DiffEntry entry : diffs) { ChangeType changeType = entry.getChangeType(); if (changeType != ChangeType.ADD) { String oldPath = entry.getOldPath(); if (isFileAllowed(oldPath, fileExtensions)) { javaFilesBefore.add(oldPath); } } if (changeType != ChangeType.DELETE) { String newPath = entry.getNewPath(); if (isFileAllowed(newPath, fileExtensions)) { javaFilesCurrent.add(newPath); if (changeType == ChangeType.RENAME) { String oldPath = entry.getOldPath(); renamedFilesHint.put(oldPath, newPath); } } } } } } public void fileTreeDiff(Repository repository, RevCommit commitBefore, RevCommit commitAfter, List<SourceFile> filesBefore, List<SourceFile> filesAfter, List<String> fileExtensions) throws Exception { ObjectId oldHead = commitBefore.getTree(); ObjectId head = commitAfter.getTree(); // prepare the two iterators to compute the diff between ObjectReader reader = repository.newObjectReader(); CanonicalTreeParser oldTreeIter = new CanonicalTreeParser(); oldTreeIter.reset(reader, oldHead); CanonicalTreeParser newTreeIter = new CanonicalTreeParser(); newTreeIter.reset(reader, head); // finally get the list of changed files try (Git git = new Git(repository)) { List<DiffEntry> diffs = git.diff() .setNewTree(newTreeIter) .setOldTree(oldTreeIter) .setShowNameAndStatusOnly(true) .call(); for (DiffEntry entry : diffs) { ChangeType changeType = entry.getChangeType(); if (changeType != ChangeType.ADD) { String oldPath = entry.getOldPath(); if (isFileAllowed(oldPath, fileExtensions)) { filesBefore.add(new SourceFile(Paths.get(oldPath))); } } if (changeType != ChangeType.DELETE) { String newPath = entry.getNewPath(); if (isFileAllowed(newPath, fileExtensions)) { filesAfter.add(new SourceFile(Paths.get(newPath))); } } } } } private boolean isFileAllowed(String path, List<String> fileExtensions) { for (String fileExtension : fileExtensions) { if (path.endsWith(fileExtension)) { return true; } } return false; } }
package joshua.decoder.ff.similarity; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; import java.net.UnknownHostException; import java.util.List; import joshua.corpus.Vocabulary; import joshua.decoder.chart_parser.SourcePath; import joshua.decoder.ff.DefaultStatefulFF; import joshua.decoder.ff.SourceDependentFF; import joshua.decoder.ff.state_maintenance.DPState; import joshua.decoder.ff.state_maintenance.NgramDPState; import joshua.decoder.ff.tm.BilingualRule; import joshua.decoder.ff.tm.Rule; import joshua.decoder.hypergraph.HGNode; import joshua.decoder.segment_file.Sentence; import joshua.util.Cache; public class EdgePhraseSimilarityFF extends DefaultStatefulFF implements SourceDependentFF { private static Cache<String, Double> cache = new Cache<String, Double>(1000000); private String host; private int port; private Socket socket; private PrintWriter serverAsk; private BufferedReader serverReply; private int[] source; private final int MAX_PHRASE_LENGTH = 3; public EdgePhraseSimilarityFF(int stateID, double weight, int featureID, String host, int port) throws NumberFormatException, UnknownHostException, IOException { super(stateID, weight, featureID); this.host = host; this.port = port; initializeConnection(); } private void initializeConnection() throws NumberFormatException, UnknownHostException, IOException { socket = new Socket(host, port); serverAsk = new PrintWriter(socket.getOutputStream(), true); serverReply = new BufferedReader(new InputStreamReader(socket.getInputStream())); } @Override public double estimateLogP(Rule rule, int sentID) { return 0; } @Override public double estimateFutureLogP(Rule rule, DPState curDPState, int sentID) { return 0; } @Override public double transitionLogP(Rule rule, List<HGNode> antNodes, int spanStart, int spanEnd, SourcePath srcPath, int sentID) { double similarity = 0; int count = 0; if (antNodes == null || antNodes.isEmpty()) return 0; // System.err.println("RULE [" + spanStart + ", " + spanEnd + "]: " + rule.toString()); int[] target = ((BilingualRule) rule).getEnglish(); // Find where the antecedent nodes plug into the target string. int[] gap_positions = new int[rule.getArity()]; for (int t = 0; t < target.length; t++) if (target[t] < 0) gap_positions[-target[t] - 1] = t; for (int n = 0; n < antNodes.size(); n++) { HGNode node = antNodes.get(n); NgramDPState state = (NgramDPState) node.getDPState(getStateID()); int anchor = gap_positions[n]; int left_bound = Math.max(0, anchor - MAX_PHRASE_LENGTH + 1); int right_bound = Math.min(target.length, anchor + MAX_PHRASE_LENGTH); if (rule.getArity() == 2) { int other_anchor = gap_positions[Math.abs(n - 1)]; if (other_anchor < anchor) left_bound = Math.max(left_bound, other_anchor + 1); else right_bound = Math.min(right_bound, other_anchor); } // System.err.println("CHILD: [" + node.i + ", " + node.j + "]"); if (node.i != spanStart) { // System.err.print("LEFT: "); // for (int w : state.getLeftLMStateWords()) System.err.print(Vocabulary.word(w) + " "); // System.err.println(); int[] i_target = getLeftTargetPhrase(target, state.getLeftLMStateWords(), anchor, left_bound); int[] i_source = getSourcePhrase(node.i); // System.err.println(n + " src_left: " + Vocabulary.getWords(i_source)); // System.err.println(n + " tgt_left: " + Vocabulary.getWords(i_target)); similarity += getSimilarity(i_source, i_target); count++; } if (node.j != spanEnd) { // System.err.print("RIGHT: "); // for (int w : state.getRightLMStateWords()) System.err.print(Vocabulary.word(w) + " "); // System.err.println(); int[] j_target = getRightTargetPhrase(target, state.getRightLMStateWords(), anchor, right_bound); int[] j_source = getSourcePhrase(node.j); // System.err.println(n + " src_rght: " + Vocabulary.getWords(j_source)); // System.err.println(n + " tgt_rght: " + Vocabulary.getWords(j_target)); similarity += getSimilarity(j_source, j_target); count++; } } if (count == 0) return 0; return this.getWeight() * similarity / count; } private final int[] getSourcePhrase(int anchor) { int idx; int[] phrase = new int[Math.min(anchor, MAX_PHRASE_LENGTH - 1) + Math.min(source.length - anchor, MAX_PHRASE_LENGTH - 1)]; idx = 0; for (int p = Math.max(0, anchor - MAX_PHRASE_LENGTH + 1); p < Math.min(source.length, anchor + MAX_PHRASE_LENGTH - 1); p++) phrase[idx++] = source[p]; return phrase; } private final int[] getLeftTargetPhrase(int[] target, List<Integer> state, int anchor, int bound) { int[] phrase = new int[anchor - bound + Math.min(state.size(), MAX_PHRASE_LENGTH)]; int idx = 0; for (int p = bound; p < anchor; p++) phrase[idx++] = target[p]; for (int p = 0; p < state.size(); p++) phrase[idx++] = state.get(p); return phrase; } private final int[] getRightTargetPhrase(int[] target, List<Integer> state, int anchor, int bound) { int[] phrase = new int[bound - anchor + Math.min(state.size(), MAX_PHRASE_LENGTH) - 1]; int idx = 0; for (int p = 0; p < state.size(); p++) phrase[idx++] = state.get(p); for (int p = anchor + 1; p < bound; p++) phrase[idx++] = target[p]; return phrase; } private double getSimilarity(int[] source, int[] target) { if (source.equals(target)) return 1.0; String source_string = Vocabulary.getWords(source); String target_string = Vocabulary.getWords(target); String both; if (source_string.compareTo(target_string) > 0) both = source_string + target_string; else both = target_string + " ||| " + source_string; Double cached = cache.get(both); if (cached != null) { // System.err.println("SIM: " + source_string + " X " + target_string + " = " + cached); return cached; } else { try { serverAsk.println("x\t" + source_string + "\t" + target_string); String response = serverReply.readLine(); double similarity = Double.parseDouble(response); cache.put(both, similarity); // System.err.println("SIM: " + source_string + " X " + target_string + " = " + similarity); return similarity; } catch (Exception e) { return 0; } } } @Override public double finalTransitionLogP(HGNode antNode, int spanStart, int spanEnd, SourcePath srcPath, int sentID) { return 0; } @Override public void setSource(Sentence source) { this.source = source.intSentence(); } public EdgePhraseSimilarityFF clone() { try { return new EdgePhraseSimilarityFF(this.getStateID(), this.getWeight(), this.getFeatureID(), host, port); } catch (Exception e) { e.printStackTrace(); return null; } } }
package fi.hu.cs.titokone; import fi.hu.cs.ttk91.TTK91CompileException; import java.util.HashMap; import java.util.Vector; /** This class knows everything about the relation between symbolic code and binary code. It can transform a full source to binary or one symbolic command to binary or vice versa. Empty out all compiler commands and empty lines at the start of round 2.*/ public class Compiler { /** This field contains the source code as a String array. */ private String[] source; /** This field holds the declared variables, labels and other symbols. It acts as a pointer to the symbolTable Vector where the actual data is stored. */ private HashMap symbols; /** This field holds the invalid values to be introduced (i.e. already used labels can't be re-used. */ private HashMap invalidLabels; /** This field tells the next line to be checked. */ private int nextLine; /** This field holds all the valid symbols on a label. */ private final String VALIDLABELCHARS = "0123456789abcdefghijklmnopqrstuvwxyz_"; private final int NOTVALID = -1; private final int EMPTY = -1; /** Maximum value of the address part. */ private final int MAXINT = 32767; /** Minimum value of the address part. */ private final int MININT = -32767; /** This field holds the value of Stdin if it was set with DEF command. */ private String defStdin; /** This field holds the value of Stdout if it was set with DEF command. */ private String defStdout; /** This field keeps track of whether we are in the first round of compilation or the second. It is set by compile() and updated by compileLine(). */ private boolean firstRound; /** This field counts the number of actual command lines found during the first round. */ private int commandLineCount; /** This array contains the code. During the first round this field holds the clean version of the code (stripped of compiler commands like def, ds, dc etc.) */ private Vector code; /** This field acts as a symboltable, it is a String array vector where 1:st position holds the name of the symbol and the second either it's value (label, equ) or the command (ds 10, dc 10) */ private Vector symbolTable; /** This array contains the data. */ private String[] data; // Second Round /** This field holds the Memoryline objects for the code. These are passed to the Application constructor at the end of the compile process, and are gathered during the second round from first round commands in code-array */ private MemoryLine[] codeMemoryLines; /** This field holds the Memoryline objects for the data area. Much like the code part, this is gathered during the second round and passed to the Application when getApplication() method is called. */ private MemoryLine[] dataMemoryLines; /** This value tells if all the lines are processed twice and getApplication can be run. */ private boolean compileFinished; /** This field contains the CompileDebugger instance to inform of any compilation happenings. */ private CompileDebugger compileDebugger; /** This field contains the SymbolicInterpreter instance to use as part of the compilation. */ private SymbolicInterpreter symbolicInterpreter; /** This constructor sets up the class. It also initializes an instance of CompileDebugger. */ public Compiler() { compileDebugger = new CompileDebugger(); symbolicInterpreter = new SymbolicInterpreter(); } /** This function initializes transforms a symbolic source code into an application class. After this, call compileLine() to actually compile the application one line at a time, and finally getApplication() to get the finished application. @param source The symbolic source code to be compiled. */ public void compile(String source) { firstRound = true; compileFinished = false; while (source.indexOf("\r\n") != -1) { source = source.substring(0, source.indexOf("\r\n")) + source.substring(source.indexOf("\r\n") + 1); } this.source = source.split("[\n\r\f\u0085\u2028\u2029]"); // antti: removed + from the split and added the while loop (21.04.2004) nextLine = 0; defStdin = ""; defStdout = ""; code = new Vector(); symbols = new HashMap(); symbolTable = new Vector(); invalidLabels = new HashMap(); invalidLabels.put("crt", new Integer(0)); invalidLabels.put("kbd", new Integer(1)); invalidLabels.put("stdin", new Integer(6)); invalidLabels.put("stdout", new Integer(7)); invalidLabels.put("halt", new Integer(11)); invalidLabels.put("read", new Integer(12)); invalidLabels.put("write", new Integer(13)); invalidLabels.put("time", new Integer(14)); invalidLabels.put("date", new Integer(15)); } /** This function goes through one line of the code. On the first round, it gathers the symbols and their definitions to a symbol table and conducts syntax-checking, on the second round it transforms each command to its binary format. For the transformations, the CompileConstants class is used. It calls the private methods firstRoundProcess() and secondRoundProcess() to do the actual work, if there is any to do. The transfer from first round of compilation to the second is done automatically; during it, initializeSecondRound() is called. @return A CompileInfo debug information object, describing what happened during the compilation of this line and whether this is the first or second round of compilation or null if there are no more lines left to process. @throws TTK91CompileException If a) there is a syntax error during the first round of checking (error code 101) or b) a symbol is still undefined after the first round of compilation is finished. */ public CompileInfo compileLine() throws TTK91CompileException { CompileInfo info; if (firstRound) { if (nextLine == source.length) { compileDebugger.firstPhase(); info = initializeSecondRound(); return info; } else { compileDebugger.firstPhase(nextLine, source[nextLine]); info = firstRoundProcess(source[nextLine]); ++nextLine; return info; } } else { if (nextLine == code.size()) { compileDebugger.finalPhase(); compileFinished = true; return null; } else { compileDebugger.secondPhase(nextLine, source[nextLine]); info = secondRoundProcess((String)code.get(nextLine)); ++nextLine; return info; } } } /** This method returns the readily-compiled application if the compilation is complete, or null otherwise. */ public Application getApplication() throws IllegalStateException { if (compileFinished) { dataMemoryLines = new MemoryLine[data.length]; for (int i = 0; i < data.length; ++i) { dataMemoryLines[i] = new MemoryLine(Integer.parseInt(data[i]), ""); } SymbolTable st = new SymbolTable(); String[] tempSTLine; for (int i = 0; i < symbolTable.size(); ++i) { tempSTLine = (String[])symbolTable.get(i); st.addSymbol(tempSTLine[0], Integer.parseInt(tempSTLine[1])); } if (!defStdin.equals("")) { st.addDefinition("stdin", defStdin); } if (!defStdout.equals("")) { st.addDefinition("stdout", defStdout); } return new Application(codeMemoryLines, dataMemoryLines, st); } else { throw new IllegalStateException(new Message("Compilation is not " + "finished " + "yet.").toString()); } } /** This function transforms a binary command number to a MemoryLine containing both the binary and the symbolic command corresponding to it. @param binary The command to be translated as binary. @return A MemoryLine instance containing both the information about the symbolic command and the binary version of it. */ public MemoryLine getSymbolicAndBinary(int binary) { BinaryInterpreter bi = new BinaryInterpreter(); return new MemoryLine(binary, bi.binaryToString(binary)); } /** This function transforms a MemoryLine containing only the binary command to a MemoryLine containing both the binary and the symbolic command corresponding to it. @param binaryOnly A MemoryLine containing the binary only of the command to be translated as binary. If the MemoryLine contains both, the pre-set symbolic value is ignored. @return A MemoryLine instance containing both the information about the symbolic command and the binary version of it. */ public MemoryLine getSymbolicAndBinary(MemoryLine binaryOnly) { BinaryInterpreter bi = new BinaryInterpreter(); return new MemoryLine(binaryOnly.getBinary(), bi.binaryToString(binaryOnly.getBinary())); } /** This function gathers new symbol information from the given line and checks its syntax. If a data reservation is detected, the dataAreaSize is incremented accordingly. If the line contains an actual command, commandLineCount is incremented. @param line The line of code to process. @return A CompileInfo object describing what was done, or null if the first round has been completed. This will be the sign for the compiler to prepare for the second round and start it. */ private CompileInfo firstRoundProcess(String line) throws TTK91CompileException { String[] lineTemp = parseCompilerCommandLine(line); boolean nothingFound = true; String comment = ""; String[] commentParameters; int intValue = 0; String[] symbolTableEntry = new String[2]; boolean labelFound = false; boolean variableUsed = false; if (lineTemp == null) { lineTemp = parseLine(line); if (lineTemp == null) { // not a valid command comment = new Message("Invalid command.").toString(); throw new TTK91CompileException(comment); } else { if (lineTemp[1].equals("")) { // line empty; } else { code.add(line); if (!lineTemp[0].equals("")) { nothingFound = false; labelFound = true; // label found if (invalidLabels.containsKey(lineTemp[0])) { // not a valid label comment = new Message("Invalid label.").toString(); throw new TTK91CompileException(comment); } else { invalidLabels.put(lineTemp[0], null); if (symbols.containsKey(lineTemp[0])) { symbolTableEntry[0] = lineTemp[0]; symbolTableEntry[1] = "" + (code.size() - 1); symbolTable.add(Integer.parseInt((String) symbols.get(lineTemp[0])), symbolTableEntry.clone()); } else { symbols.put(lineTemp[0], new Integer(code.size() - 1)); symbolTableEntry[0] = lineTemp[0]; symbolTableEntry[1] = "" + (code.size() - 1); symbolTable.add(symbolTableEntry.clone()); } compileDebugger.foundLabel(lineTemp[0], code.size() -1); } } try { if (!lineTemp[4].equals("")) Integer.parseInt(lineTemp[4]); } catch(NumberFormatException e) { // variable used if (symbolicInterpreter.getRegisterId(lineTemp[4])== -1) { nothingFound = false; variableUsed = true; compileDebugger.foundSymbol(lineTemp[4]); if (!symbols.containsKey(lineTemp[4])) { if (invalidLabels.get(lineTemp[4]) == null) { symbols.put(lineTemp[4], new Integer(symbolTable.size())); symbolTableEntry[0] = lineTemp[4]; symbolTableEntry[1] = ""; symbolTable.add(symbolTableEntry.clone()); } else { // predefined word (halt etc) was used symbols.put(lineTemp[4], new Integer(symbolTable.size())); symbolTableEntry[0] = lineTemp[4]; symbolTableEntry[1] = "" + (Integer) invalidLabels.get(lineTemp[4]); symbolTable.add(symbolTable.size(), symbolTableEntry.clone()); } } } } if (variableUsed && labelFound) { commentParameters = new String[2]; commentParameters[0] = lineTemp[0]; commentParameters[1] = lineTemp[4]; comment = new Message("Found label {0} and variable " + "{1}.", commentParameters).toString(); compileDebugger.setComment(comment); } else { if (variableUsed) { comment = new Message("Variable {0} used.", lineTemp[4]).toString(); compileDebugger.setComment(comment); } else { if (labelFound) { comment = new Message("Label {0} found.", lineTemp[0]).toString(); compileDebugger.setComment(comment); } } } } } } else { // compiler command boolean allCharsValid = true; boolean atLeastOneNonNumber = false; if (invalidLabels.containsKey(lineTemp[0])) { // not a valid label comment = new Message("Invalid label.").toString(); throw new TTK91CompileException(comment); } if(!validLabelName(lineTemp[0])) { // not a valid label; comment = new Message("Invalid label.").toString(); throw new TTK91CompileException(comment); } else { if (invalidLabels.containsKey(lineTemp[0])) { comment = new Message("Invalid label.").toString(); throw new TTK91CompileException(comment); } if (lineTemp[1].equalsIgnoreCase("ds")) { intValue = 0; try { intValue = Integer.parseInt(lineTemp[2]); } catch(NumberFormatException e) { comment = new Message("Invalid size for a " + "DS.").toString(); throw new TTK91CompileException(comment); } if (intValue < 0 || intValue > MAXINT) { comment = new Message("Invalid size for a " + "DS.").toString(); throw new TTK91CompileException(comment); } } if (lineTemp[1].equalsIgnoreCase("dc")) { intValue = 0; if (lineTemp[2].trim().length() > 0) { try { intValue = Integer.parseInt(lineTemp[2]); } catch(NumberFormatException e) { comment = new Message("Invalid value for a " + "DC.").toString(); throw new TTK91CompileException(comment); } if (intValue < MININT || intValue > MAXINT) { comment = new Message("Invalid value for a " + "DC.").toString(); throw new TTK91CompileException(comment); } } } if (lineTemp[1].equalsIgnoreCase("equ")) { if (symbols.containsKey(lineTemp[0])) { symbolTableEntry[0] = lineTemp[0]; symbolTableEntry[1] = lineTemp[2]; symbolTable.add(Integer.parseInt((String) symbols.get(lineTemp[0])), symbolTableEntry.clone()); } else { symbols.put(lineTemp[0], new Integer(symbolTable.size())); symbolTableEntry[0] = lineTemp[0]; symbolTableEntry[1] = lineTemp[2]; symbolTable.add(symbolTableEntry.clone()); } compileDebugger.foundEQU(lineTemp[0], intValue); commentParameters = new String[2]; commentParameters[0] = lineTemp[0]; commentParameters[1] = lineTemp[2]; comment = new Message("Variable {0} defined as {1}.", commentParameters).toString(); compileDebugger.setComment(comment); } if (lineTemp[1].equals("ds")) { if (symbols.containsKey(lineTemp[0])) { symbolTableEntry[0] = lineTemp[0]; symbolTableEntry[1] = lineTemp[1] + " " + lineTemp[2]; symbolTable.add(Integer.parseInt((String)symbols.get(lineTemp[0])), symbolTableEntry.clone()); } else { symbolTableEntry[0] = lineTemp[0]; symbolTableEntry[1] = lineTemp[1] + " " + lineTemp[2]; symbolTable.add(symbolTableEntry.clone()); } compileDebugger.foundDS(lineTemp[0]); comment = new Message("Found variable {0}.", lineTemp[0]).toString(); compileDebugger.setComment(comment); } if (lineTemp[1].equals("dc")) { compileDebugger.foundDC(lineTemp[0]); if (symbols.containsKey(lineTemp[0])) { symbolTableEntry[0] = lineTemp[0]; symbolTableEntry[1] = lineTemp[1] + " " + lineTemp[2]; symbolTable.add(Integer.parseInt((String)symbols.get(lineTemp[0])), symbolTableEntry.clone()); } else { symbolTableEntry[0] = lineTemp[0]; symbolTableEntry[1] = lineTemp[1] + " " + lineTemp[2]; symbolTable.add(symbolTableEntry.clone()); } compileDebugger.foundDC(lineTemp[0]); comment = new Message("Found variable {0}.", lineTemp[0]).toString(); compileDebugger.setComment(comment); } if (lineTemp[1].equals("def")) { if (lineTemp[0].equals("stdin") || lineTemp[0].equals("stdout")) { if (lineTemp[0].equals("stdin")) { defStdin = lineTemp[2]; } else { defStdout = lineTemp[2]; } compileDebugger.foundDEF(lineTemp[0], lineTemp[2]); commentParameters = new String[2]; commentParameters[0] = lineTemp[0].toUpperCase(); commentParameters[1] = lineTemp[2]; comment = new Message("{0} defined as {1}.", commentParameters).toString(); compileDebugger.setComment(comment); } else { comment = new Message("Invalid DEF " + "operation.").toString(); throw new TTK91CompileException(comment); } } } } return compileDebugger.lineCompiled(); } /** This method initializes the code and data area arrays for the second round processing according to the dataAreaSize and commandLineCount variables. It also resets the StringTokenizer by calling tokenize(). Before entering the second round we must clear all the empty lines like compiler-codes (pseudo-codes) and lines with nothing but comments. */ private CompileInfo initializeSecondRound() { nextLine = 0; firstRound = false; // copy the code. String[] newCode = new String[code.size()]; for (int i= 0; i < newCode.length; ++i) newCode[i] = (String)code.get(i); String[] lineTemp; int dataAreaSize = 0; // calculate the size of data-area for (int i = 0; i < symbolTable.size(); ++i) { lineTemp = (String[])symbolTable.get(i); if (lineTemp[1].trim().length() > 3) { if (lineTemp[1].substring(0,2).equalsIgnoreCase("ds")) { dataAreaSize += Integer.parseInt(lineTemp[1].substring(3)); } else { if (lineTemp[1].substring(0,2).equalsIgnoreCase("dc")) ++dataAreaSize; } } } if (!defStdin.equals("")) ++dataAreaSize; if (!defStdout.equals("")) ++dataAreaSize; data = new String[dataAreaSize]; String[] newSymbolTableLine = new String[2]; newSymbolTableLine[0] = ""; newSymbolTableLine[1] = ""; int nextPosition = 0; int nextMemorySlot = newCode.length; int dsValue = 0; // update variable values to symbolTable for (int i = 0; i < symbolTable.size(); ++i) { lineTemp = (String[])symbolTable.get(i); if (lineTemp[1].trim().length() > 2) { if (lineTemp[1].substring(0,2).equalsIgnoreCase("ds")) { dsValue = Integer.parseInt(lineTemp[1].substring(3)); newSymbolTableLine[0] = lineTemp[0]; newSymbolTableLine[1] = "" + nextMemorySlot; symbolTable.add(i, newSymbolTableLine); ++nextMemorySlot; for (int j = nextPosition; j < nextPosition + dsValue; ++nextPosition) { data[j] = "" + 0; } } else { if (lineTemp[1].substring(0,2).equalsIgnoreCase("dc")) { if (lineTemp[1].length() > 3) { data[nextPosition] = lineTemp[1].substring(3); } else { data[nextPosition] = "" + 0; } newSymbolTableLine[0] = lineTemp[0]; newSymbolTableLine[1] = "" + nextMemorySlot; symbolTable.add(i, newSymbolTableLine); ++nextMemorySlot; ++nextPosition; } } } } if (!defStdin.equals("")) { data[nextPosition] = "STDIN " + defStdin; ++nextPosition; } if (!defStdout.equals("")) { data[nextPosition] = "STDOUT " + defStdout; } // make new SymbolTable String[][] newSymbolTable = new String[symbolTable.size()][2]; for (int i = 0; i < newSymbolTable.length; ++i) { newSymbolTable[i] = (String[])symbolTable.get(i); } // prepare for the second round. codeMemoryLines = new MemoryLine[newCode.length]; compileDebugger.finalFirstPhase(newCode, data, newSymbolTable); return compileDebugger.lineCompiled(); } /** This function transforms any commands to binary and stores both forms in the code array, or sets any initial data values in the data array. It uses CompileConstants as its aid. @param line The line of code to process. @return A CompileInfo object describing what was done, or null if the second round and thus the compilation has been completed. */ private CompileInfo secondRoundProcess(String line) throws TTK91CompileException { /* Antti: 04.03.04 Do a pure binary translation first, then when all sections are complete, convert the binary to an integer. Needs variables for opcode(8bit), first operand(3 bit)(r0 to r7), m-part(memory format, direct, indirect or from code), possible index register (3 bit) and 16 bits for the address. Once STORE is converted to a 00000001 and the rest of the code processed we get 32bit binary that is the opcode from symbolic opcode. Antti 08.03.04 Teemu said that we should support the machine spec instead of Koksi with this one. No need to support opcodes like Muumuu LOAD R1, 100 kissa etc. Only tabs and extra spacing. So we need to support opcodes like LOAD R1, 100 but not codes like LOAD R1, =R2. Basic functionality: (Trim between each phase.) Check if there is a label (8 first are the meaningful ones also must have one non-number)) Convert opcode (8bit) check which register (0 to 7) =, Rj/addr or @ (00, 01 or 10) if addr(Ri) or Rj(Ri)(0 to 7) convert address (16bit) check if the rest is fine (empty or starts with ;) Store both formats to a data array (symbolic and binary). */ // check if variable is set! int addressAsInt = 0; int lineAsBinary; String comment; String[] symbolTableEntry; String[] lineTemp = parseLine(line); if (!lineTemp[4].equals("")) { try { addressAsInt = Integer.parseInt(lineTemp[4]); } catch (NumberFormatException e) { Object tempObject = symbolTable.get((((Integer)symbols.get(lineTemp[4]))).intValue()); symbolTableEntry = (String[])tempObject; if (symbolTableEntry[1].equals("")) { comment = new Message("").toString(); throw new TTK91CompileException(comment); } addressAsInt = Integer.parseInt((String)symbolTableEntry[1]); } } lineAsBinary = symbolicInterpreter.stringToBinary(lineTemp[1], lineTemp[2], lineTemp[3], addressAsInt + "", lineTemp[5]); compileDebugger.setBinary(lineAsBinary); codeMemoryLines[nextLine] = new MemoryLine(lineAsBinary, line); // comment String lineAsZerosAndOnes = symbolicInterpreter.intToBinary(lineAsBinary, 32); String binaryByPositions = symbolicInterpreter.binaryToInt(lineAsZerosAndOnes.substring(0, 8), true) + ":" + symbolicInterpreter.binaryToInt(lineAsZerosAndOnes.substring(8, 11), false) + ":" + symbolicInterpreter.binaryToInt(lineAsZerosAndOnes.substring(11, 13), false) + ":" + symbolicInterpreter.binaryToInt(lineAsZerosAndOnes.substring(13, 16), false) + ":" + symbolicInterpreter.binaryToInt(lineAsZerosAndOnes.substring(16), true); String[] commentParameters = {line, "" + lineAsBinary, binaryByPositions}; comment = new Message("{0} --> {1} ({2}) ", commentParameters).toString(); compileDebugger.setComment(comment); return compileDebugger.lineCompiled(); } /** This method parses a String and tries to find a label, opCode and all the other parts of a Command line. @param symbolicOpCode Symbolic form of an operation code. */ public String[] parseLine(String symbolicOpcode) { String label = ""; String opcode = ""; String firstRegister = ""; String addressingMode = ""; String secondRegister = ""; String address = ""; String[] parsedLine; String wordTemp = ""; int nextToCheck = 0; // for looping out the spacing int fieldEnd = 0; // searches the end of a field (' ', ',') boolean spaceBetweenMemorymodeAndAddress = false; fieldEnd = symbolicOpcode.indexOf(";"); if (fieldEnd != -1) { symbolicOpcode = symbolicOpcode.substring(0, fieldEnd); } symbolicOpcode = symbolicOpcode.replace('\t',' '); symbolicOpcode = symbolicOpcode.replace('', ' '); // Not stupid! symbolicOpcode = symbolicOpcode.toLowerCase(); symbolicOpcode = symbolicOpcode.trim(); if (symbolicOpcode.length() == 0) { parsedLine = new String[6]; for (int i = 0; i < parsedLine.length; ++i) parsedLine[i] = ""; return parsedLine; } String[] lineAsArray = symbolicOpcode.split("[ \t,]+"); int lineAsArrayIndex = 0; /* label */ wordTemp = lineAsArray[lineAsArrayIndex]; if (symbolicInterpreter.getOpcode(wordTemp) == -1) { if(!validLabelName(wordTemp)) return null; label = wordTemp; ++lineAsArrayIndex; } /* opcode */ if (lineAsArrayIndex < lineAsArray.length) { opcode = lineAsArray[lineAsArrayIndex]; ++lineAsArrayIndex; if (symbolicInterpreter.getOpcode(opcode) < 0) { return null; } } else { return null; } /*first register*/ if (lineAsArrayIndex < lineAsArray.length) { // first register might end with a ','. Not when push Sp etc. if (lineAsArray[lineAsArrayIndex].charAt( lineAsArray[lineAsArrayIndex].length() -1) == ',') { if (symbolicInterpreter.getRegisterId( lineAsArray[lineAsArrayIndex].substring(0, lineAsArray[lineAsArrayIndex].length() - 1) ) != -1) { firstRegister = lineAsArray[lineAsArrayIndex].substring(0, lineAsArray[lineAsArrayIndex].length() -1); ++lineAsArrayIndex; } } else { if (symbolicInterpreter.getRegisterId( lineAsArray[lineAsArrayIndex]) != -1) { firstRegister = lineAsArray[lineAsArrayIndex]; ++lineAsArrayIndex; } } } /* addressingMode */ if (lineAsArrayIndex < lineAsArray.length) { if (lineAsArray[lineAsArrayIndex].charAt(0) == '=' || lineAsArray[lineAsArrayIndex].charAt(0) == '@') { addressingMode = "" + lineAsArray[lineAsArrayIndex].charAt(0); if (lineAsArray[lineAsArrayIndex].length() == 1) { spaceBetweenMemorymodeAndAddress = true; ++lineAsArrayIndex; } } else { addressingMode = ""; } } /*address and second register*/ if (lineAsArrayIndex < lineAsArray.length) { if (lineAsArray[lineAsArrayIndex].indexOf("(") != -1) { if (lineAsArray[lineAsArrayIndex].indexOf(")") < lineAsArray[lineAsArrayIndex].indexOf("(")) { return null; } else { if (spaceBetweenMemorymodeAndAddress) { address = lineAsArray[lineAsArrayIndex].substring( 0, lineAsArray[lineAsArrayIndex].indexOf("(") ); } else { address = lineAsArray[lineAsArrayIndex].substring( addressingMode.length(), lineAsArray[lineAsArrayIndex].indexOf("(") ); } secondRegister = lineAsArray[lineAsArrayIndex].substring( lineAsArray[lineAsArrayIndex].indexOf("(") + 1, lineAsArray[lineAsArrayIndex].indexOf(")") ); if (symbolicInterpreter.getRegisterId(secondRegister) == -1) { return null; } } } else { if (spaceBetweenMemorymodeAndAddress) { address = lineAsArray[lineAsArrayIndex]; } else { address = lineAsArray[lineAsArrayIndex].substring(addressingMode.length()); } } ++lineAsArrayIndex; } if (symbolicInterpreter.getRegisterId(address) != -1) { secondRegister = address; address = ""; } if (lineAsArrayIndex < lineAsArray.length) { return null; } if (opcode.length() > 0) { if (opcode.charAt(0) == 'j' || opcode.charAt(0) == 'J') { // Opcode matches jneg/jzer/jpos or the negations // jnneg/jnzer/jnpos. if(opcode.toLowerCase().matches("j" + "n?" + "((neg)|(zer)|(pos))")) { if (firstRegister.equals("")) return null; } if (addressingMode.equals("=") || address.equals("")) return null; } else { if (opcode.equalsIgnoreCase("nop")) { // (do nothing) } else { if (opcode.equalsIgnoreCase("pop")) { if (addressingMode.equals("@") || addressingMode.equals("=") || !address.equals("")) return null; } else { if (firstRegister.equals("") || (address.equals("") && secondRegister.equals(""))) return null; } } } } if (addressingMode.equals("=") && address.equals("")) return null; if (opcode.equalsIgnoreCase("store") && address.equals("")) return null; if (opcode.equalsIgnoreCase("store") && addressingMode.equals("=")) return null; if (opcode.equals("") && (!label.equals("") || !firstRegister.equals("") || !addressingMode.equals("") || !address.equals("") || !secondRegister.equals(""))) { return null; } parsedLine = new String[6]; parsedLine[0] = label.trim(); parsedLine[1] = opcode.trim(); parsedLine[2] = firstRegister.trim(); parsedLine[3] = addressingMode.trim(); parsedLine[4] = address.trim(); parsedLine[5] = secondRegister.trim(); return parsedLine; } /** This function tries to find a compiler command from the line. Works much like parseLine but this time valid opcodes are DEF, EQU, DC and DS. @param line String representing one line from source code. @return String array with label in position 0, command in the position 1 and position 2 contains the parameter. */ public String[] parseCompilerCommandLine(String line) { int fieldEnd = 0; int nextToCheck = 0; String label = ""; String opcode = ""; String value = ""; int intValue; String[] parsedLine; /* preprosessing */ line = line.trim(); line = line.toLowerCase(); line = line.replace('\t',' '); fieldEnd = line.indexOf(";"); if (fieldEnd != -1) { line = line.substring(0, fieldEnd); } /* LABEL opcode value */ fieldEnd = line.indexOf(" "); if (fieldEnd == -1) { label = line.substring(nextToCheck); fieldEnd = line.length(); } else { label = line.substring(nextToCheck, fieldEnd); } nextToCheck = fieldEnd + 1; /* label OPCODE value */ if (nextToCheck < line.length()) { while (line.charAt(nextToCheck) == ' ') { ++nextToCheck; } fieldEnd = line.indexOf(' ', nextToCheck); if (fieldEnd == -1) { opcode = line.substring(nextToCheck); fieldEnd = line.length(); } else { opcode = line.substring(nextToCheck, fieldEnd); } if (!opcode.matches("((dc)|(ds)|(equ)|(def))")) { return null; } nextToCheck = fieldEnd; } /* label opcode VALUE */ if (nextToCheck < line.length()) { while (line.charAt(nextToCheck) == ' ') { ++nextToCheck; } value = line.substring(nextToCheck); if (value.length() > 0) { try { intValue = Integer.parseInt(value); if (opcode.equalsIgnoreCase("ds") && intValue < 1) { return null; } } catch (NumberFormatException e) { return null; } } } if (!opcode.equalsIgnoreCase("dc") && value.equals("")) return null; parsedLine = new String[3]; parsedLine[0] = label; parsedLine[1] = opcode; parsedLine[2] = value; return parsedLine; } /** This method tests whether a label name contains at least one non-number and consists of 0-9, A- and _. It does not check whether the label is in use already or if it is a reserved word. @param labelName The label name to test. @return True if the label consists of valid characters, false otherwise. */ private boolean validLabelName(String labelName) { // It must have one non-number. Valid characters are A-, 0-9 and _. // Test 1: the word contains one or more of the following: // a-z, A-Z, _, 0-9, , , in any order. // Test 2: the word also contains one non-number (class \D // means anything but 0-9) surrounded by any number of // any character. All these 'anything buts' and 'anys' are // also valid characters, since we check that in Test 1. if(labelName.matches("[\\w]+") && labelName.matches(".*\\D.*")) { return true; } return false; } }
package jsceneviewer.inventor.qt.viewers; import java.time.Instant; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.ToolBarManager; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.swt.SWT; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.TypedEvent; import org.eclipse.swt.graphics.Cursor; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import jscenegraph.database.inventor.SbMatrix; import jscenegraph.database.inventor.SbVec2s; import jscenegraph.database.inventor.SbVec3f; import jscenegraph.database.inventor.SoDB; import jscenegraph.database.inventor.SoDebug; import jscenegraph.database.inventor.SoFullPath; import jscenegraph.database.inventor.SoInput; import jscenegraph.database.inventor.actions.SoSearchAction; import jscenegraph.database.inventor.errors.SoDebugError; import jscenegraph.database.inventor.nodes.SoCamera; import jscenegraph.database.inventor.nodes.SoGroup; import jscenegraph.database.inventor.nodes.SoNode; import jscenegraph.database.inventor.nodes.SoOrthographicCamera; import jscenegraph.database.inventor.nodes.SoPerspectiveCamera; import jscenegraph.database.inventor.nodes.SoScale; import jscenegraph.database.inventor.nodes.SoSeparator; import jscenegraph.database.inventor.nodes.SoSwitch; import jscenegraph.database.inventor.nodes.SoTranslation; import jscenegraph.database.inventor.sensors.SoFieldSensor; import jscenegraph.database.inventor.sensors.SoSensor; import jscenegraph.database.inventor.sensors.SoSensorCB; import jsceneviewer.QDoubleSpinBox; import jsceneviewer.inventor.qt.SoQtCameraController.Type; import jsceneviewer.inventor.qt.SoQtIcons; import jsceneviewer.inventor.qt.SoQtThumbWheel; /** * @author Yves Boyadjian * */ //Class: SoXtExaminerViewer //Examiner viewer - allows the user to change the camera position //by spinning a sphere in front of the viewpoint. //Keys used by this viewer: //Left Mouse: Tumbles the virtual trackball. //Middle Mouse: //Ctrl + Left Mouse: Translate up, down, left and right. //Ctrl + Middle Mouse: //Left + Middle Mouse: Dolly in and out (gets closer to and further //away from the object). //<s> + click: Alternative to the Seek button. Press (but do not hold //down) the <s> key, then click on a target object. //Right Mouse: Open the popup menu. public class SoQtExaminerViewer extends SoQtFullViewer { // interaction modes offered by this viewer: enum ViewerModes { PICK_MODE, // interacts directly with the OpenInventor scene SPIN_MODE, // spin scene SPIN_MODE_ACTIVE, // ...when active PAN_MODE, // pan scene PAN_MODE_ACTIVE, // ...when active DOLLY_MODE, // zoom scene DOLLY_MODE_ACTIVE, // ...when active SEEK_MODE, // zoom/move to clicked point INTERACT_MODE_COUNT }; // viewer state variables final ViewerModes[] modeTable = new ViewerModes[64]; // contains viewing mode depending on // keyboard modifiers and mouse buttons int mode; Cursor[] modeCursors; int modeCursorCount; final SbVec2s locator = new SbVec2s(); // mouse position boolean firstBuild; // set false after buildWidget called once // point of rotation feedback vars boolean feedbackFlag; double feedbackSize; SoSeparator feedbackRoot; SoSwitch feedbackSwitch; SoTranslation feedbackTransNode; SoScale feedbackScaleNode; //static final String geometryBuffer; // variables used for doing spinning animation boolean animationEnabled, animatingFlag; SoFieldSensor animationSensor; Instant lastMotionTime; // point of rotation pref sheet stuff double feedbackSizeWheelValue; Composite feedbackSizeWidgets; Button enableSpinToggle; // SWT.CHECK Button showRotPointToggle; // SWT.CHECK QDoubleSpinBox feedbackInput; SoQtThumbWheel feedbackSizeWheel; boolean nestingFlag; boolean mouseInside; // set to true after mouse enter event // viewer toolbar actions protected Action perspAction; //! Constructor/Destructor public SoQtExaminerViewer (BuildFlag flag) { this(flag, Type.BROWSER); } public SoQtExaminerViewer (BuildFlag flag, Type type) { this(flag, type, null); } public SoQtExaminerViewer (BuildFlag flag, Type type, Composite parent) { this(flag, type, parent, 0); } public SoQtExaminerViewer (BuildFlag flag, Type type, Composite parent, int f) { super(flag, type, parent, f); commonConstructor(); } private void commonConstructor() { nestingFlag = false; mouseInside = false; // init local vars modeCursorCount = ViewerModes.INTERACT_MODE_COUNT.ordinal(); modeCursors = new Cursor [modeCursorCount]; setCursorShape (ViewerModes.PICK_MODE.ordinal(), new Cursor(getDisplay(),0)); setCursorShape (ViewerModes.SPIN_MODE.ordinal(), SoQtIcons.getCursor (SoQtIcons.CursorNum.CURSOR_CURVED_HAND.ordinal())); setCursorShape (ViewerModes.PAN_MODE.ordinal(), SoQtIcons.getCursor (SoQtIcons.CursorNum.CURSOR_FLAT_HAND.ordinal())); setCursorShape (ViewerModes.DOLLY_MODE.ordinal(), SoQtIcons.getCursor (SoQtIcons.CursorNum.CURSOR_POINTING_HAND.ordinal())); setCursorShape (ViewerModes.SEEK_MODE.ordinal(), SoQtIcons.getCursor (SoQtIcons.CursorNum.CURSOR_TARGET.ordinal())); setCursorShape (ViewerModes.SPIN_MODE_ACTIVE.ordinal(), getCursorShape (ViewerModes.SPIN_MODE.ordinal())); setCursorShape (ViewerModes.PAN_MODE_ACTIVE.ordinal(), getCursorShape (ViewerModes.PAN_MODE.ordinal())); setCursorShape (ViewerModes.DOLLY_MODE_ACTIVE.ordinal(), getCursorShape (ViewerModes.DOLLY_MODE.ordinal())); // axis of rotation feedback vars feedbackFlag = false; feedbackRoot = null; feedbackSwitch = null; feedbackSize = 20.0; feedbackInput = null; feedbackSizeWheel = null; feedbackSizeWheelValue = 0.0; feedbackSizeWidgets = null; // init animation variables animationEnabled = true; animatingFlag = false; animationSensor = new SoFieldSensor(new SoSensorCB() { @Override public void run(Object data, SoSensor sensor) { animationSensorCB(data,sensor); } } , this); //#ifdef DEBUG if (SoDebug.GetEnv("IV_DEBUG_SENSORS") != null) { SoDebug.NamePtr("examinerSpinSensor", animationSensor); } //#endif final String myTitle = "Examiner Viewer"; setPopupMenuTitle (myTitle); //setWindowTitle (myTitle); //setWindowIconText (myTitle); setBottomWheelTitle ("Roty"); setLeftWheelTitle ("Rotx"); lastMotionTime = Instant.now().plusSeconds(-1); // this is probably unnecessary here, because a camera probably // doesn't exist at this moment - too lazy to think about it... ImageDescriptor icon = SoQtIcons.getIcon ( getCameraController().isOrthographic() ? SoQtIcons.IconNum.ICON_ORTHO.ordinal() : SoQtIcons.IconNum.ICON_PERSP.ordinal()); perspAction = new Action ( "Perspective", icon) { public void run() { SoQtExaminerViewer.this.toggleCameraTypeSlot(); } }; restoreInteractions(); } public void destructor() { animationSensor.destructor(); if (feedbackRoot != null) { feedbackRoot.unref(); } super.destructor(); } private void resetInteractions() { for (int i=0;i<64;i++) { modeTable [i] = ViewerModes.PICK_MODE; } } private void restoreInteractions() { resetInteractions(); setInteraction ((SWT.BUTTON1 | SWT.BUTTON2), 0, ViewerModes.DOLLY_MODE_ACTIVE); setInteraction ((SWT.BUTTON1) | (SWT.SHIFT), 0, ViewerModes.PAN_MODE_ACTIVE); setInteraction ((SWT.BUTTON1) | (SWT.CTRL), 0, ViewerModes.PAN_MODE_ACTIVE); setInteraction ((SWT.BUTTON1) | (SWT.SHIFT | SWT.CTRL), 0, ViewerModes.DOLLY_MODE_ACTIVE); setInteraction ((SWT.BUTTON1), 0, ViewerModes.SPIN_MODE_ACTIVE); setInteraction ((SWT.BUTTON2) | (SWT.CTRL), 0, ViewerModes.DOLLY_MODE_ACTIVE); setInteraction ((SWT.BUTTON2), 0, ViewerModes.PAN_MODE_ACTIVE); setInteraction ((SWT.SHIFT | SWT.CTRL), 0, ViewerModes.DOLLY_MODE); setInteraction ((SWT.SHIFT), 0, ViewerModes.PAN_MODE); setInteraction ((SWT.CTRL), 0, ViewerModes.PAN_MODE); setInteraction (0, 0, ViewerModes.SPIN_MODE); mode = isViewing() ? modeTable[0].ordinal() : ViewerModes.PICK_MODE.ordinal(); } private void setInteraction (int inputState, int ignoreStateMask, ViewerModes mode) { if (ignoreStateMask == 0) { modeTable [getModeIndex (inputState)] = mode; } else { // this is kind of overkill, since values are set more than once, but it's simple: for (int i=0;i<64;i++) { int state = (inputState & (0xffff ^ ignoreStateMask)) | (i & ignoreStateMask); modeTable [getModeIndex (state)] = mode; } } } private SoQtExaminerViewer.ViewerModes getInteraction (int inputState) { return modeTable [getModeIndex (inputState)]; } private int getModeIndex (int inputState) { return ((inputState & SWT.BUTTON1)!= 0 ? 1 : 0) | ((inputState & SWT.BUTTON3)!= 0 ? 2 : 0) | ((inputState & SWT.BUTTON2)!= 0 ? 4 : 0) | ((inputState & SWT.SHIFT)!= 0 ? 8 : 0) | ((inputState & SWT.CONTROL)!= 0 ? 16 : 0) | ((inputState & SWT.ALT)!= 0 ? 32 : 0); } // Set/get the cursor shape for a given viewing mode public void setCursorShape (int viewingMode, final Cursor shape) { if (viewingMode >= ViewerModes.PICK_MODE.ordinal() && viewingMode < modeCursorCount && modeCursors != null) { // set new cursor shape for a_mode modeCursors [viewingMode] = shape; if (mouseInside && viewingMode == mode) { // update the currently shown cursor super.setGLCursor (shape); } } } // Set/get the cursor shape for a given viewing mode public Cursor getCursorShape (int viewingMode) { if (viewingMode >= ViewerModes.PICK_MODE.ordinal() && viewingMode < modeCursorCount && modeCursors != null) { return modeCursors [viewingMode]; } else { // return default cursor return new Cursor(getDisplay(),0); } } protected void createViewerButtons(ToolBarManager parent) { // create the default buttons super.createViewerButtons(parent); parent.add(perspAction); } //The point of interest geometry description private static final String geometryBuffer = "" +"#Inventor V2.0 ascii\n" +"" +"Separator { " +" PickStyle { style UNPICKABLE } " +" LightModel { model BASE_COLOR } " +" MaterialBinding { value PER_PART } " +" DrawStyle { lineWidth 2 } " +" Coordinate3 { point [0 0 0, 1 0 0, 0 1 0, 0 0 1] } " +" BaseColor { rgb [1 0 0, 0 1 0, 0 0 1] } " +" IndexedLineSet { coordIndex [1, 0, 2, -1, 0, 3] } " +" " +" LightModel { model PHONG } " +" MaterialBinding { value OVERALL } " +" Complexity { value .1 } " +" Separator { " +" Material { " +" diffuseColor [ 0.5 0 0 ] " +" emissiveColor [ 0.5 0 0 ] " +" } " +" Translation { translation 1 0 0 } " +" RotationXYZ { axis Z angle -1.570796327 } " +" Cone { bottomRadius .2 height .3 } " +" } " +" Separator { " +" Material { " +" diffuseColor [ 0 0.5 0 ] " +" emissiveColor [ 0 0.5 0 ] " +" } " +" Translation { translation 0 1 0 } " +" Cone { bottomRadius .2 height .3 } " +" } " +" Material { " +" diffuseColor [ 0 0 0.5 ] " +" emissiveColor [ 0 0 0.5 ] " +" } " +" Translation { translation 0 0 1 } " +" RotationXYZ { axis X angle 1.570796327 } " +" Cone { bottomRadius .2 height .3 } " +"} "; protected void createFeedbackNodes() { // make sure we havn't built this yet... if (feedbackRoot != null) { return; } feedbackRoot = new SoSeparator(1); feedbackSwitch = new SoSwitch(3); feedbackTransNode = new SoTranslation(); feedbackScaleNode = new SoScale(); feedbackRoot.ref(); feedbackRoot.addChild( feedbackSwitch ); feedbackSwitch.addChild( feedbackTransNode ); feedbackSwitch.addChild( feedbackScaleNode ); final SoInput in = new SoInput(); in.setBuffer(geometryBuffer, geometryBuffer.length()); final SoNode[] node = new SoNode[1]; boolean ok = SoDB.read(in, node); if (ok && node != null) { feedbackSwitch.addChild(node[0]); //#ifdef DEBUG } else { SoDebugError.post("SoQtExaminerViewer.createFeedbackNodes", "couldn't read feedback axis geometry"); //#endif } } //static callbacks stubs protected static void animationSensorCB (Object v, SoSensor sensor) { if (!((SoQtExaminerViewer)v).getCameraController().doSpinAnimation()) { ((SoQtExaminerViewer)v).stopAnimating(); } } protected void setFeedbackSizeWheelValue (double value) { // grow/shrink the feedback based on the wheel rotation setFeedbackSize ((double) (feedbackSize) * Math.pow (12.0, (value - feedbackSizeWheelValue) / 360.0)); feedbackSizeWheelValue = value; } //called when the viewer becomes visible/hidden - when hidden, make //sure to temporary stop any ongoing animation (and restart it as soon //as we become visible). protected void hideEvent () { super.hideEvent (); // only do this if we are/were spinning.... if (! animatingFlag) { return; } // if hidden, detach the field sensor, but don't change the // animatingFlag var to let us know we need to turn it back on // when we become visible.... animationSensor.detach(); animationSensor.unschedule(); } protected void showEvent () { super.showEvent (); // only do this if we are/were spinning.... if (! animatingFlag) { return; } // we now are visible again so attach the field sensor animationSensor.attach (viewerRealTime); } protected boolean isCurrentlyPicking() { return !isViewing() || (mode == ViewerModes.PICK_MODE.ordinal()); } // Show/hide the point of rotation feedback, which only appears while // in Viewing mode. (default OFF) public void setFeedbackVisibility(boolean insertFlag) { // check for trivial return if (getCameraController().getCamera() == null || feedbackFlag == insertFlag) { feedbackFlag = insertFlag; return; } if (feedbackSizeWidgets != null) { feedbackSizeWidgets.setEnabled (insertFlag); } // find the camera parent to insert/remove the feedback root final SoSearchAction sa = new SoSearchAction(); if (insertFlag) { sa.setNode(getCameraController().getCamera()); } else { sa.setNode(feedbackRoot); sa.setSearchingAll(true); // find under OFF switches for removal } sa.apply(sceneRoot); SoFullPath fullPath = SoFullPath.cast( sa.getPath()); if (fullPath == null) { //#if DEBUG SoDebugError.post("SoQtExaminerViewer.setFeedbackVisibility", insertFlag ? "ERROR: cannot find camera in graph" : "ERROR: cannot find axis feedback in graph"); //#endif return; } SoGroup parent = (SoGroup ) fullPath.getNodeFromTail(1); feedbackFlag = insertFlag; // make sure the feedback has been built if (feedbackRoot == null) { createFeedbackNodes(); } // inserts/remove the feedback axis group if (feedbackFlag) { int camIndex; // check to make sure that the camera parent is not a switch node // (VRML camera viewpoints are kept under a switch node). Otherwise // we will insert the feedback after the switch node. if (parent.isOfType(SoSwitch.getClassTypeId())) { SoNode switchNode = parent; parent = (SoGroup ) fullPath.getNodeFromTail(2); camIndex = parent.findChild(switchNode); } else { camIndex = parent.findChild(getCameraController().getCamera()); } // return if feedback is already there (this should be an error !) if (parent.findChild(feedbackRoot) >= 0) { return; } // insert the feedback right after the camera+headlight (index+2) if (camIndex >= 0) { if (getCameraController().isHeadlight()) { parent.insertChild(feedbackRoot, camIndex+2); } else { parent.insertChild(feedbackRoot, camIndex+1); } } // make sure the feedback switch is turned to the correct state now // that the feedback root has been inserted in the scene feedbackSwitch.whichChild.setValue(viewingFlag ? SoSwitch.SO_SWITCH_ALL : SoSwitch.SO_SWITCH_NONE); } else { if (parent.findChild(feedbackRoot) >= 0) { parent.removeChild(feedbackRoot); } } } public boolean isFeedbackVisible() { return feedbackFlag; } // Set/get the point of rotation feeedback size in pixels (default 20). public void setFeedbackSize(double newSize) { if (feedbackSize == newSize) { return; } if (nestingFlag) { return; } nestingFlag = true; // assign new value and redraw (since it is not a field in the scene) feedbackSize = newSize; if (feedbackInput != null) { feedbackInput.setValue (newSize); } if (isFeedbackVisible() && isViewing()) { getSceneHandler().scheduleRedraw(); } nestingFlag = false; } public int getFeedbackSize() { return (int) feedbackSize; } public void actualRedraw() { // place the feedback at the focal point // ??? we really only need to do this when the camera changes SoCamera camera = getCameraController().getCamera(); if (isViewing() && feedbackFlag && camera != null && feedbackRoot != null) { // adjust the position to be at the focal point final SbMatrix mx = new SbMatrix(); mx.copyFrom(camera.orientation.getValue()); final SbVec3f forward = new SbVec3f(-mx.getValue()[2][0], -mx.getValue()[2][1], -mx.getValue()[2][2]); feedbackTransNode.translation.setValue( camera.position.getValue().operator_add( forward.operator_mul(camera.focalDistance.getValue()))); // adjust the size to be constant on the screen float height = 1.0f; if (getCameraController().isPerspective()) { float angle = ((SoPerspectiveCamera )camera).heightAngle.getValue(); height = camera.focalDistance.getValue() * (float)Math.tan(angle/2); } else if (getCameraController().isOrthographic()) { height = ((SoOrthographicCamera )camera).height.getValue() / 2; } // ??? getGlxSize[1] == 0 the very first time, so return in that case // ??? else the redraws are 3 times slower from now on !! (alain) if (getGlxSize().getValue()[1] != 0) { float size = 2.0f * height * (float)feedbackSize / (float) (getGlxSize().getValue()[1]); feedbackScaleNode.scaleFactor.setValue(size, size, size); } } // have the base class draw the scene super.actualRedraw(); } // Stop animation, if it is occurring, and queuery if the viewer is // currently animating. public void stopAnimating() { if (animatingFlag) { animatingFlag = false; animationSensor.detach(); animationSensor.unschedule(); interactiveCountDec(); } } public boolean isAnimating() { return animatingFlag; } public void viewAll() { // stop spinning if ( isAnimating() ) { stopAnimating(); } // temporarily remove the feedback geometry if (feedbackFlag && isViewing() && feedbackSwitch != null) { feedbackSwitch.whichChild.setValue( SoSwitch.SO_SWITCH_NONE ); } // call the base class getCameraController().viewAll(); // now add the geometry back in if (feedbackFlag && isViewing() && feedbackSwitch != null) { feedbackSwitch.whichChild.setValue( SoSwitch.SO_SWITCH_ALL ); } } public void resetToHomePosition() { // stop spinning if ( isAnimating() ) { stopAnimating(); } // call the base class getCameraController().resetToHomePosition(); } public void setCamera(SoCamera newCamera, boolean createdCamera) { SoCamera camera = getCameraController().getCamera(); if (camera == newCamera) { return; } // set the right thumbwheel label and toggle button image based on // the camera type if (newCamera != null && (camera == null || newCamera.getTypeId() != camera.getTypeId())) { if (newCamera.isOfType(SoOrthographicCamera.getClassTypeId())) { perspAction.setImageDescriptor(SoQtIcons.getIcon (SoQtIcons.IconNum.ICON_ORTHO.ordinal())); setRightWheelTitle("Zoom"); } else { perspAction.setImageDescriptor (SoQtIcons.getIcon (SoQtIcons.IconNum.ICON_PERSP.ordinal())); setRightWheelTitle("Dolly"); } } perspAction.setEnabled(newCamera != null && createdCamera); // detach feedback which depends on camera if ( feedbackFlag ) { setFeedbackVisibility(false); feedbackFlag = true; // can later be turned on } // call parent class super.setCamera(newCamera, createdCamera); // attach feedback back on if ( feedbackFlag ) { feedbackFlag = false; // enables routine to be called setFeedbackVisibility(true); } } public void setViewing(boolean flag) { if (flag == viewingFlag) { return; } // call the parent class super.setViewing(flag); updateViewerMode(-1, -1); // show/hide the feedback geometry based on the viewing state if (feedbackFlag && feedbackSwitch != null) { feedbackSwitch.whichChild.setValue(viewingFlag ? SoSwitch.SO_SWITCH_ALL : SoSwitch.SO_SWITCH_NONE); } } protected void processEvent (TypedEvent anyEvent, EventType type, final boolean[] isAccepted) { SbVec2s raSize = getGlxSize(); double raViewScale = getGlxDevicePixelRatio(); if (type == EventType.MOUSE_EVENT_MOUSE_DOWN)//QEvent.MouseButtonPress) { MouseEvent me = (MouseEvent) anyEvent; // remember start position of mouse drag locator.copyFrom( new SbVec2s((short)(me.x * raViewScale), (short)(raSize.getValue()[1] - (me.y * raViewScale)))); if ((me.button == 1 || me.button == 2) && mode == ViewerModes.SEEK_MODE.ordinal()) { // handle temporary seek mode stopAnimating(); getCameraController().seekToPoint(locator); //me.accept(); } else { interactiveCountInc(); stopAnimating(); } updateViewerMode (me.stateMask & SWT.MODIFIER_MASK, (me.stateMask & SWT.BUTTON_MASK) | (me.button == 1 ? SWT.BUTTON1:0)| (me.button == 2 ? SWT.BUTTON2:0)| (me.button == 3 ? SWT.BUTTON3 :0) ); } else if (type == EventType.KEY_EVENT_KEY_PRESSED/*QEvent.KeyPress*/) { KeyEvent ke = (KeyEvent )anyEvent; updateViewerMode (ke.stateMask & SWT.MODIFIER_MASK, ke.stateMask & SWT.BUTTON_MASK); } else if (type == EventType.MOUSE_EVENT_MOUSE_MOVE/*QEvent.MouseMove*/) { MouseEvent me = (MouseEvent) anyEvent; final SbVec2s pos = new SbVec2s((short)(me.x * raViewScale), (short)(raSize.getValue()[1] - (me.y * raViewScale))); if ((me.stateMask & SWT.BUTTON_MASK) ==0) { // update viewer mode while we are not dragging - this allows us // to change the viewing mode depending on the cursor location updateViewerMode (me.stateMask & SWT.MODIFIER_MASK, me.stateMask & SWT.BUTTON_MASK); } switch (ViewerModes.values()[mode]) { case SPIN_MODE_ACTIVE: lastMotionTime = Instant.now(); getCameraController().spinCamera(pos); break; case PAN_MODE_ACTIVE: getCameraController().panCamera(pos); break; case DOLLY_MODE_ACTIVE: getCameraController().dollyCamera(pos); break; default: ; } } else if (type == EventType.MOUSE_EVENT_MOUSE_ENTER/*QEvent.Enter*/) { MouseEvent me = (MouseEvent)anyEvent; updateViewerMode(me.stateMask & SWT.MODIFIER_MASK, me.stateMask & SWT.BUTTON_MASK); updateCursor(); mouseInside = true; } else if (type == EventType.MOUSE_EVENT_MOUSE_EXIT/*QEvent.Leave*/) { super.unsetGLCursor(); mouseInside = false; } //if (!anyEvent.isAccepted()) { super.processEvent (anyEvent, type, isAccepted); // updates for button and key releases will be done _after_ the mouse event might // have been delivered to the inventor scene - otherwise we might swallow some needed // events if (type == EventType.KEY_EVENT_KEY_RELEASED/*QEvent.KeyRelease*/) { KeyEvent ke = (KeyEvent )anyEvent; updateViewerMode (ke.stateMask & SWT.MODIFIER_MASK, ke.stateMask & SWT.BUTTON_MASK); } else if (type == EventType.MOUSE_EVENT_MOUSE_UP/*QEvent.MouseButtonRelease*/) { MouseEvent me = (MouseEvent) anyEvent; if ((me.button == 1/*Qt.LeftButton*/ || me.button == 2/*Qt.MidButton*/) && mode == ViewerModes.SEEK_MODE.ordinal()) { //me.accept(); } else { //... ButtonRelease // check if we need to start spinning if (mode == ViewerModes.SPIN_MODE_ACTIVE.ordinal() && animationEnabled && // Qt is missing a mechanism to obtain the time when // an event was generated (in contrast to processing time) lastMotionTime.plusMillis(100).isAfter(Instant.now())) { animatingFlag = true; animationSensor.attach(viewerRealTime); interactiveCountInc(); // will be decreased again in stopAnimating } interactiveCountDec(); } updateViewerMode (me.stateMask & SWT.MODIFIER_MASK, me.stateMask & SWT.BUTTON_MASK & (me.button == 1 ? ~SWT.BUTTON1:SWT.BUTTON_MASK) & (me.button == 2 ? ~SWT.BUTTON2:SWT.BUTTON_MASK) & (me.button == 3 ? ~SWT.BUTTON3 :SWT.BUTTON_MASK)); } } private void updateViewerMode (int modifiers, int buttons) { // obtain modifiers and buttons if they weren't given: if (modifiers == -1) { modifiers = keyboardModifiers(); } if (buttons == -1) { buttons = mouseButtons(); } if (buttons == 0 && getCameraController().isSeekMode()) { // seek mode needs special handling because it's only temporary switchMode (ViewerModes.SEEK_MODE.ordinal(), buttons); } else if (!isViewing()) { switchMode (ViewerModes.PICK_MODE.ordinal(), buttons); } else { if (isAltSwitchingEnabled()) { // since 'alt' switches between viewing and picking, we remove // 'alt' from the modifiers, since we want to handle it as if // it wasn't pressed: modifiers = (modifiers | SWT.ALT) ^ SWT.ALT; } switchMode (getInteraction (modifiers | buttons).ordinal(), buttons); } } private int keyboardModifiers() { // TODO Auto-generated method stub return 0; } private int mouseButtons() { // TODO Auto-generated method stub return 0; } private void switchMode(int newMode, int buttons) { if (mode == newMode) { return; } //<- This wasn't there before - is this wrong? // assing new mode int prevMode = mode; mode = newMode; // update the cursor updateCursor(); // switch to new viewer mode switch (ViewerModes.values()[newMode]) { case PICK_MODE: if (mouseInside) { //int buttons = QApplication::mouseButtons(); if (prevMode != ViewerModes.SEEK_MODE.ordinal()) { // in SEEK_MODE the interactive count isn't increased // by a mouse press! if ((buttons & SWT.BUTTON1)!=0/*Qt::LeftButton*/) { interactiveCountDec(); } if ((buttons & SWT.BUTTON2)!=0/*Qt::MidButton*/) { interactiveCountDec(); } } if ((buttons & SWT.BUTTON3)!=0/*Qt::RightButton*/) { interactiveCountDec(); } } stopAnimating(); break; case DOLLY_MODE_ACTIVE: case SPIN_MODE_ACTIVE: case PAN_MODE_ACTIVE: getCameraController().startDrag(locator); break; case DOLLY_MODE: break; case INTERACT_MODE_COUNT: break; case PAN_MODE: break; case SEEK_MODE: break; case SPIN_MODE: break; default: break; } } private void updateCursor() { // the viewer cursor are not enabled, then we don't set a new cursor. // Instead erase the old viewer cursor. if (! cursorEnabledFlag) { super.unsetGLCursor(); return; } else { super.setGLCursor (getCursorShape (mode)); } } public void setGLCursor ( Cursor cursor) { setCursorShape (ViewerModes.PICK_MODE.ordinal(), cursor); } public void unsetGLCursor() { setCursorShape (ViewerModes.PICK_MODE.ordinal(), new Cursor(getDisplay(),0)); } protected void setSeekMode(boolean flag/*, int modifiers, int buttons*/) { if ( !isViewing() ) { return; } // stop spinning if (isAnimating()) { stopAnimating(); } // call the base class super.setSeekMode(flag/*, modifiers, buttons*/); updateViewerMode(-1, -1); updateCursor(); } }
package jsettlers.buildingcreator.editor.map; import jsettlers.common.buildings.EBuildingType; import jsettlers.common.buildings.IBuilding; import jsettlers.common.mapobject.EMapObjectType; import jsettlers.common.mapobject.IMapObject; import jsettlers.common.position.ISPosition2D; import jsettlers.common.selectable.ESelectionType; public class PseudoBuilding implements IBuilding { private final EBuildingType type; private final ISPosition2D pos; PseudoBuilding(EBuildingType type, ISPosition2D pos) { this.type = type; this.pos = pos; } @Override public EBuildingType getBuildingType() { return type; } @Override public float getStateProgress() { return 1; } @Override public ISPosition2D getPos() { return pos; } @Override public byte getPlayer() { return 0; } @Override public boolean isSelected() { return false; } @Override public void setSelected(boolean b) { } @Override public void stopOrStartWorking(boolean stop) { } @Override public EMapObjectType getObjectType() { return EMapObjectType.BUILDING; } @Override public IMapObject getNextObject() { return null; } @Override public boolean isWorking() { return false; } @Override public boolean isOccupied() { return true; } @Override public ESelectionType getSelectionType() { return ESelectionType.BUILDING; } }
package cn.momia.mapi.api.v1.product; import cn.momia.api.base.MetaUtil; import cn.momia.api.product.dto.PlaymateDto; import cn.momia.api.product.dto.ProductsOfDayDto; import cn.momia.api.product.dto.SkuPlaymatesDto; import cn.momia.api.user.dto.LeaderDto; import cn.momia.common.api.dto.PagedList; import cn.momia.common.api.http.MomiaHttpResponse; import cn.momia.api.product.dto.CommentDto; import cn.momia.common.webapp.config.Configuration; import cn.momia.image.api.ImageFile; import cn.momia.api.product.DealServiceApi; import cn.momia.api.product.ProductServiceApi; import cn.momia.api.product.dto.ProductDto; import cn.momia.api.product.dto.SkuDto; import cn.momia.api.user.UserServiceApi; import cn.momia.api.user.dto.UserDto; import cn.momia.mapi.api.v1.AbstractV1Api; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import org.apache.commons.lang3.StringUtils; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletRequest; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; @RestController @RequestMapping("/v1/product") public class ProductV1Api extends AbstractV1Api { private static final Logger LOGGER = LoggerFactory.getLogger(ProductV1Api.class); @RequestMapping(value = "/weekend", method = RequestMethod.GET) public MomiaHttpResponse listByWeekend(@RequestParam(value = "city") int cityId, @RequestParam int start) { if (cityId < 0 || start < 0) return MomiaHttpResponse.BAD_REQUEST; return MomiaHttpResponse.SUCCESS(processPagedProducts(ProductServiceApi.PRODUCT.listByWeekend(cityId, start, Configuration.getInt("PageSize.Product")))); } @RequestMapping(value = "/month", method = RequestMethod.GET) public MomiaHttpResponse listByMonth(@RequestParam(value = "city") int cityId, @RequestParam int month) { if (cityId < 0 || month <= 0 || month > 12) return MomiaHttpResponse.BAD_REQUEST; return MomiaHttpResponse.SUCCESS(processGroupedProducts(ProductServiceApi.PRODUCT.listByMonth(cityId, month))); } private List<ProductsOfDayDto> processGroupedProducts(List<ProductsOfDayDto> products) { for (ProductsOfDayDto productGroup : products) { processProducts(productGroup.getProducts(), ImageFile.Size.MIDDLE); } return products; } @RequestMapping(value = "/leader", method = RequestMethod.GET) public MomiaHttpResponse listNeedLeader(@RequestParam(value = "city") int cityId, @RequestParam int start) { if (cityId < 0 || start < 0) return MomiaHttpResponse.BAD_REQUEST; return MomiaHttpResponse.SUCCESS(processPagedProducts(ProductServiceApi.PRODUCT.listNeedLeader(cityId, start, Configuration.getInt("PageSize.Product")))); } @RequestMapping(value = "/sku/leader", method = RequestMethod.GET) public MomiaHttpResponse listSkusNeedLeader(@RequestParam(value = "pid") long id) { if (id <= 0) return MomiaHttpResponse.BAD_REQUEST; ProductDto product = ProductServiceApi.PRODUCT.get(id, ProductDto.Type.BASE); List<SkuDto> skus = ProductServiceApi.SKU.listWithLeader(id); Set<Long> leaderUserIds = new HashSet<Long>(); for (SkuDto sku : skus) { if (sku.getLeaderUserId() > 0) leaderUserIds.add(sku.getLeaderUserId()); } List<LeaderDto> leaders = UserServiceApi.LEADER.list(leaderUserIds); Map<Long, LeaderDto> leadersMap = new HashMap<Long, LeaderDto>(); for (LeaderDto leader : leaders) leadersMap.put(leader.getUserId(), leader); for (SkuDto sku : skus) { if (!sku.isNeedLeader()) { sku.setLeaderInfo(""); } else { LeaderDto leader = leadersMap.get(sku.getLeaderUserId()); if (leader == null || StringUtils.isBlank(leader.getName())) sku.setLeaderInfo(""); else sku.setLeaderInfo(leader.getName() + ""); } } JSONObject productSkusJson = new JSONObject(); productSkusJson.put("product", processProduct(product, ImageFile.Size.MIDDLE)); productSkusJson.put("skus", skus); return MomiaHttpResponse.SUCCESS(productSkusJson); } @RequestMapping(method = RequestMethod.GET) public MomiaHttpResponse get(@RequestParam(defaultValue = "") String utoken, @RequestParam long id, HttpServletRequest request) { if (id <= 0) return MomiaHttpResponse.BAD_REQUEST; ProductDto product = processProduct(ProductServiceApi.PRODUCT.get(id, ProductDto.Type.FULL), utoken, getClientType(request)); JSONObject productJson = JSON.parseObject(JSON.toJSONString(product)); try { List<String> avatars = DealServiceApi.ORDER.listCustomerAvatars(id, Configuration.getInt("PageSize.ProductCustomer")); productJson.put("customers", buildCustomers(avatars, product.getStock())); productJson.put("comments", processPagedComments(ProductServiceApi.COMMENT.list(id, 0, Configuration.getInt("PageSize.ProductDetailComment")))); long userId = StringUtils.isBlank(utoken) ? 0 : UserServiceApi.USER.get(utoken).getId(); if (ProductServiceApi.FAVORITE.favored(userId, id)) productJson.put("favored", true); } catch (Exception e) { LOGGER.error("exception!!", e); } return MomiaHttpResponse.SUCCESS(productJson); } private JSONObject buildCustomers(List<String> avatars, int stock) { JSONObject customersJson = new JSONObject(); customersJson.put("text", "" + ((stock > 0 && stock <= Configuration.getInt("Product.StockAlert")) ? "" + stock + "" : "")); customersJson.put("avatars", processAvatars(avatars)); return customersJson; } private List<String> processAvatars(List<String> avatars) { for (int i = 0; i < avatars.size(); i++) avatars.set(i, ImageFile.smallUrl(avatars.get(i))); return avatars; } private PagedList<CommentDto> processPagedComments(PagedList<CommentDto> pagedComments) { for (CommentDto comment : pagedComments.getList()) { comment.setAvatar(ImageFile.smallUrl(comment.getAvatar())); if (comment.getImgs() != null) { List<String> largeImgs = new ArrayList<String>(); comment.setLargeImgs(largeImgs); for (int i = 0; i < comment.getImgs().size(); i++) { String img = comment.getImgs().get(i); comment.getImgs().set(i, ImageFile.middleUrl(img)); largeImgs.add(ImageFile.largeUrl(img)); } } } return pagedComments; } @RequestMapping(value = "/detail", method = RequestMethod.GET) public MomiaHttpResponse getDetail(@RequestParam long id) { if (id <= 0) return MomiaHttpResponse.BAD_REQUEST; return MomiaHttpResponse.SUCCESS(processProductDetail(ProductServiceApi.PRODUCT.getDetail(id))); } private String processProductDetail(String detail) { Document detailDoc = Jsoup.parse(detail); Elements imgs = detailDoc.select("img[src]"); for (Element element : imgs) { String imgUrl = element.attr("src"); element.attr("src", ImageFile.largeUrl(imgUrl)); } return detailDoc.toString(); } @RequestMapping(value = "/order", method = RequestMethod.GET) public MomiaHttpResponse placeOrder(@RequestParam String utoken, @RequestParam long id) { if(StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED; if (id <= 0) return MomiaHttpResponse.BAD_REQUEST; JSONObject placeOrderJson = new JSONObject(); placeOrderJson.put("contacts", UserServiceApi.USER.getContacts(utoken)); List<SkuDto> skus = ProductServiceApi.SKU.list(id, SkuDto.Status.AVALIABLE); placeOrderJson.put("places", extractPlaces(skus)); placeOrderJson.put("skus", skus); return MomiaHttpResponse.SUCCESS(placeOrderJson); } private JSONArray extractPlaces(List<SkuDto> skus) { JSONArray placesJson = new JSONArray(); Set<Integer> placeIds = new HashSet<Integer>(); for (SkuDto sku : skus) { int placeId = sku.getPlaceId(); if (placeId <= 0 || placeIds.contains(placeId)) continue; placeIds.add(placeId); JSONObject placeJson = new JSONObject(); placeJson.put("id", placeId); placeJson.put("name", sku.getPlaceName()); placeJson.put("region", MetaUtil.getRegionName(sku.getRegionId())); placeJson.put("address", sku.getAddress()); placesJson.add(placeJson); } return placesJson; } @RequestMapping(value = "/playmate", method = RequestMethod.GET) public MomiaHttpResponse listPlaymates(@RequestParam long id) { if (id <= 0) return MomiaHttpResponse.BAD_REQUEST; return MomiaHttpResponse.SUCCESS(processPlaymates(DealServiceApi.ORDER.listPlaymates(id, Configuration.getInt("PageSize.PlaymateSku")))); } private List<SkuPlaymatesDto> processPlaymates(List<SkuPlaymatesDto> playmates) { for (SkuPlaymatesDto skuPlaymates : playmates) { for (PlaymateDto playmate : skuPlaymates.getPlaymates()) { playmate.setAvatar(ImageFile.smallUrl(playmate.getAvatar())); } } return playmates; } @RequestMapping(value = "/favor", method = RequestMethod.POST) public MomiaHttpResponse favor(@RequestParam String utoken, @RequestParam long id){ if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED; if (id <= 0) return MomiaHttpResponse.BAD_REQUEST; UserDto user = UserServiceApi.USER.get(utoken); ProductServiceApi.FAVORITE.favor(user.getId(), id); return MomiaHttpResponse.SUCCESS; } @RequestMapping(value = "/unfavor", method = RequestMethod.POST) public MomiaHttpResponse unfavor(@RequestParam String utoken, @RequestParam long id){ if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED; if (id <= 0) return MomiaHttpResponse.BAD_REQUEST; UserDto user = UserServiceApi.USER.get(utoken); ProductServiceApi.FAVORITE.unfavor(user.getId(), id); return MomiaHttpResponse.SUCCESS; } @RequestMapping(value = "/comment", method = RequestMethod.POST) public MomiaHttpResponse addComment(@RequestParam String utoken, @RequestParam String comment) { if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED; if (StringUtils.isBlank(comment)) return MomiaHttpResponse.BAD_REQUEST; UserDto user = UserServiceApi.USER.get(utoken); JSONObject commentJson = JSON.parseObject(comment); commentJson.put("userId", user.getId()); long orderId = commentJson.getLong("orderId"); long productId = commentJson.getLong("productId"); long skuId = commentJson.getLong("skuId"); if (!DealServiceApi.ORDER.check(utoken, orderId, productId, skuId)) return MomiaHttpResponse.FAILED(""); ProductServiceApi.COMMENT.add(commentJson); return MomiaHttpResponse.SUCCESS; } @RequestMapping(value = "/comment", method = RequestMethod.GET) public MomiaHttpResponse listComments(@RequestParam long id, @RequestParam int start) { if (id <= 0 || start < 0) return MomiaHttpResponse.BAD_REQUEST; return MomiaHttpResponse.SUCCESS(processPagedComments(ProductServiceApi.COMMENT.list(id, start, Configuration.getInt("PageSize.ProductComment")))); } }
package com.adyen.model.checkout; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import com.adyen.Util.DateUtil; import com.adyen.model.FraudResult; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import static com.adyen.constants.ApiConstants.AdditionalData.AUTH_CODE; import static com.adyen.constants.ApiConstants.AdditionalData.AVS_RESULT; import static com.adyen.constants.ApiConstants.AdditionalData.BOLETO_BARCODE_REFERENCE; import static com.adyen.constants.ApiConstants.AdditionalData.BOLETO_DATA; import static com.adyen.constants.ApiConstants.AdditionalData.BOLETO_DUE_DATE; import static com.adyen.constants.ApiConstants.AdditionalData.BOLETO_EXPIRATION_DATE; import static com.adyen.constants.ApiConstants.AdditionalData.BOLETO_URL; import static com.adyen.constants.ApiConstants.AdditionalData.CARD_BIN; import static com.adyen.constants.ApiConstants.AdditionalData.CARD_HOLDER_NAME; import static com.adyen.constants.ApiConstants.AdditionalData.CARD_SUMMARY; import static com.adyen.constants.ApiConstants.AdditionalData.EXPIRY_DATE; import static com.adyen.constants.ApiConstants.AdditionalData.PAYMENT_METHOD; import static com.adyen.constants.ApiConstants.AdditionalData.THREE_D_AUTHENTICATED; import static com.adyen.constants.ApiConstants.AdditionalData.THREE_D_OFFERERED; /** * PaymentsResponse */ public class PaymentsResponse { @SerializedName("additionalData") private Map<String, String> additionalData = null; @SerializedName("details") private List<InputDetail> details = null; @SerializedName("fraudResult") private FraudResult fraudResult = null; @SerializedName("paymentData") private String paymentData = null; @SerializedName("pspReference") private String pspReference = null; @SerializedName("redirect") private Redirect redirect = null; @SerializedName("refusalReason") private String refusalReason = null; @SerializedName("refusalReasonCode") private String refusalReasonCode = null; @SerializedName("resultCode") private ResultCodeEnum resultCode = null; @SerializedName("serviceError") private ServiceError serviceError; @SerializedName("authResponse") private ResultCodeEnum authResponse; @SerializedName("merchantReference") private String merchantReference; @SerializedName("outputDetails") private Map<String, String> outputDetails; @SerializedName("authentication") private Map<String, String> authentication; public PaymentsResponse additionalData(Map<String, String> additionalData) { this.additionalData = additionalData; return this; } public PaymentsResponse putAdditionalDataItem(String key, String additionalDataItem) { if (this.additionalData == null) { this.additionalData = new HashMap<>(); } this.additionalData.put(key, additionalDataItem); return this; } /** * This field contains additional data, which may be required to return in a particular payment response. To choose data fields to be returned, go to **Customer Area** &gt; **Settings** &gt; **API * and Response**. * * @return additionalData **/ public Map<String, String> getAdditionalData() { return additionalData; } public void setAdditionalData(Map<String, String> additionalData) { this.additionalData = additionalData; } public String getAdditionalDataByKey(String key) { if (additionalData == null) { return null; } return additionalData.get(key); } public PaymentsResponse details(List<InputDetail> details) { this.details = details; return this; } public PaymentsResponse addDetailsItem(InputDetail detailsItem) { if (this.details == null) { this.details = new ArrayList<InputDetail>(); } this.details.add(detailsItem); return this; } public String getOutputDetailDataByKey(String key) { if (outputDetails == null) { return null; } return outputDetails.get(key); } /** * When non-empty, contains all the fields that you must submit to the &#x60;/payments/details&#x60; endpoint. * * @return details **/ public List<InputDetail> getDetails() { return details; } public void setDetails(List<InputDetail> details) { this.details = details; } public PaymentsResponse fraudResult(FraudResult fraudResult) { this.fraudResult = fraudResult; return this; } /** * Get fraudResult * * @return fraudResult **/ public FraudResult getFraudResult() { return fraudResult; } public void setFraudResult(FraudResult fraudResult) { this.fraudResult = fraudResult; } public PaymentsResponse paymentData(String paymentData) { this.paymentData = paymentData; return this; } /** * When non-empty, contains a value that you must submit to the &#x60;/payments/details&#x60; endpoint. * * @return paymentData **/ public String getPaymentData() { return paymentData; } public void setPaymentData(String paymentData) { this.paymentData = paymentData; } public PaymentsResponse pspReference(String pspReference) { this.pspReference = pspReference; return this; } /** * Adyen&#x27;s 16-digit unique reference associated with the transaction/the request. This value is globally unique; quote it when communicating with us about this request. &gt; * &#x60;pspReference&#x60; is returned only for non-redirect payment methods. * * @return pspReference **/ public String getPspReference() { return pspReference; } public void setPspReference(String pspReference) { this.pspReference = pspReference; } public PaymentsResponse redirect(Redirect redirect) { this.redirect = redirect; return this; } /** * Get redirect * * @return redirect **/ public Redirect getRedirect() { return redirect; } public void setRedirect(Redirect redirect) { this.redirect = redirect; } public PaymentsResponse refusalReason(String refusalReason) { this.refusalReason = refusalReason; return this; } /** * If the payment&#x27;s authorisation is refused or an error occurs during authorisation, this field holds Adyen&#x27;s mapped reason for the refusal or a description of the error. When a * transaction fails, the authorisation response includes &#x60;resultCode&#x60; and &#x60;refusalReason&#x60; values. * * @return refusalReason **/ public String getRefusalReason() { return refusalReason; } public void setRefusalReason(String refusalReason) { this.refusalReason = refusalReason; } public PaymentsResponse resultCode(ResultCodeEnum resultCode) { this.resultCode = resultCode; return this; } public String getRefusalReasonCode() { return refusalReasonCode; } public void setRefusalReasonCode(String refusalReasonCode) { this.refusalReasonCode = refusalReasonCode; } public ResultCodeEnum getResultCode() { return resultCode; } public void setResultCode(ResultCodeEnum resultCode) { this.resultCode = resultCode; } public ServiceError getServiceError() { return serviceError; } public void setServiceError(ServiceError serviceError) { this.serviceError = serviceError; } public ResultCodeEnum getAuthResponse() { return authResponse; } public void setAuthResponse(ResultCodeEnum authResponse) { this.authResponse = authResponse; } public String getMerchantReference() { return merchantReference; } public void setMerchantReference(String merchantReference) { this.merchantReference = merchantReference; } public Map<String, String> getOutputDetails() { return outputDetails; } public void setOutputDetails(Map<String, String> outputDetails) { this.outputDetails = outputDetails; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PaymentsResponse paymentsResponse = (PaymentsResponse) o; return Objects.equals(this.additionalData, paymentsResponse.additionalData) && Objects.equals(this.details, paymentsResponse.details) && Objects.equals(this.fraudResult, paymentsResponse.fraudResult) && Objects.equals(this.paymentData, paymentsResponse.paymentData) && Objects.equals(this.pspReference, paymentsResponse.pspReference) && Objects.equals(this.redirect, paymentsResponse.redirect) && Objects.equals(this.refusalReason, paymentsResponse.refusalReason) && Objects.equals(this.refusalReasonCode, paymentsResponse.refusalReasonCode) && Objects.equals(this.resultCode, paymentsResponse.resultCode) && Objects.equals(this.serviceError, paymentsResponse.serviceError) && Objects.equals(this.authResponse, paymentsResponse.authResponse) && Objects.equals(this.merchantReference, paymentsResponse.merchantReference) && Objects.equals(this.outputDetails, paymentsResponse.outputDetails); } @Override public int hashCode() { return Objects.hash(additionalData, details, fraudResult, paymentData, pspReference, redirect, refusalReason, resultCode); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class PaymentsResponse {\n"); sb.append(" additionalData: ").append(toIndentedString(additionalData)).append("\n"); sb.append(" details: ").append(toIndentedString(details)).append("\n"); sb.append(" fraudResult: ").append(toIndentedString(fraudResult)).append("\n"); sb.append(" paymentData: ").append(toIndentedString(paymentData)).append("\n"); sb.append(" pspReference: ").append(toIndentedString(pspReference)).append("\n"); sb.append(" redirect: ").append(toIndentedString(redirect)).append("\n"); sb.append(" refusalReason: ").append(toIndentedString(refusalReason)).append("\n"); sb.append(" refusalReasonCode: ").append(toIndentedString(refusalReasonCode)).append("\n"); sb.append(" resultCode: ").append(toIndentedString(resultCode)).append("\n"); sb.append(" serviceError: ").append(toIndentedString(serviceError)).append("\n"); sb.append(" authResponse: ").append(toIndentedString(authResponse)).append("\n"); sb.append(" merchantReference: ").append(toIndentedString(merchantReference)).append("\n"); sb.append(" outputDetails: ").append(toIndentedString(outputDetails)).append("\n"); sb.append(" authentication: ").append(toIndentedString(authentication)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } @JsonAdapter(ResultCodeEnum.Adapter.class) public enum ResultCodeEnum { AUTHORISED("Authorised"), PARTIALLYAUTHORISED("PartiallyAuthorised"), REFUSED("Refused"), ERROR("Error"), CANCELLED("Cancelled"), RECEIVED("Received"), REDIRECTSHOPPER("RedirectShopper"), PRESENTTOSHOPPER("PresentToShopper"), IDENTIFYSHOPPER("IdentifyShopper"), CHALLENGESHOPPER("ChallengeShopper"), UNKNOWN("Unknown"); //applicable for payments/details private String value; ResultCodeEnum(String value) { this.value = value; } public static ResultCodeEnum fromValue(String text) { for (ResultCodeEnum b : ResultCodeEnum.values()) { if (String.valueOf(b.value).equals(text)) { return b; } } return null; } public String getValue() { return value; } @Override public String toString() { return String.valueOf(value); } public static class Adapter extends TypeAdapter<ResultCodeEnum> { @Override public void write(final JsonWriter jsonWriter, final ResultCodeEnum enumeration) throws IOException { jsonWriter.value(enumeration.getValue()); } @Override public ResultCodeEnum read(final JsonReader jsonReader) throws IOException { String value = jsonReader.nextString(); return ResultCodeEnum.fromValue(String.valueOf(value)); } }} public String getCardBin() { return getAdditionalDataByKey(CARD_BIN); } public String getCardHolderName() { return getAdditionalDataByKey(CARD_HOLDER_NAME); } public String getCardSummary() { return getAdditionalDataByKey(CARD_SUMMARY); } public String getPaymentMethod() { return getAdditionalDataByKey(PAYMENT_METHOD); } public String getAvsResult() { return getAdditionalDataByKey(AVS_RESULT); } public boolean get3DOffered() { return String.valueOf("true").equals(getAdditionalDataByKey(THREE_D_OFFERERED)); } public boolean get3DAuthenticated() { return String.valueOf("true").equals(getAdditionalDataByKey(THREE_D_AUTHENTICATED)); } public String getBoletoBarCodeReference() { return getOutputDetailDataByKey(BOLETO_BARCODE_REFERENCE); } public String getBoletoData() { return getOutputDetailDataByKey(BOLETO_DATA); } public String getAuthCode() { return getOutputDetailDataByKey(AUTH_CODE); } public Map<String, String> getAuthentication() { return authentication; } public void setAuthentication(Map<String, String> authentication) { this.authentication = authentication; } public Date getBoletoDueDate() { String date = getOutputDetailDataByKey(BOLETO_DUE_DATE); return DateUtil.parseYmdDate(date); } public Date getBoletoExpirationDate() { String date = getOutputDetailDataByKey(BOLETO_EXPIRATION_DATE); return DateUtil.parseYmdDate(date); } public String getBoletoUrl() { return getOutputDetailDataByKey(BOLETO_URL); } public Date getExpiryDate() { String expiryDate = getAdditionalDataByKey(EXPIRY_DATE); return DateUtil.parseMYDate(expiryDate); } }
package com.akiban.server.store; import com.akiban.ais.model.HKey; import com.akiban.ais.model.HKeySegment; import com.akiban.ais.model.TableName; import com.akiban.ais.model.UserTable; import com.akiban.server.rowdata.RowData; import com.akiban.server.rowdata.RowDef; import com.akiban.server.api.dml.scan.LegacyRowWrapper; import com.akiban.server.api.dml.scan.NewRow; import com.akiban.server.error.InvalidOperationException; import com.akiban.server.service.session.Session; import com.persistit.Exchange; import com.persistit.Key; import com.persistit.exception.PersistitException; import java.util.HashMap; import java.util.List; import java.util.Map; public abstract class TreeRecordVisitor { public final void visit() throws PersistitException, InvalidOperationException { NewRow row = row(); Object[] key = key(row.getRowDef()); visit(key, row); } public final void initialize(Session session, PersistitStore store, Exchange exchange) { this.session = session; this.store = store; this.exchange = exchange; for (UserTable table : store.getAIS(session).getUserTables().values()) { if (!table.getName().getSchemaName().equals(TableName.INFORMATION_SCHEMA) && !table.getName().getSchemaName().equals(TableName.SECURITY_SCHEMA)) { ordinalToTable.put(table.rowDef().getOrdinal(), table); } } } public abstract void visit(Object[] key, NewRow row); private NewRow row() throws PersistitException, InvalidOperationException { RowData rowData = new RowData(EMPTY_BYTE_ARRAY); store.expandRowData(exchange, rowData); return new LegacyRowWrapper(store.getRowDef(session, rowData.getRowDefId()), rowData); } private Object[] key(RowDef rowDef) { // Key traversal Key key = exchange.getKey(); int keySize = key.getDepth(); // HKey traversal HKey hKey = rowDef.userTable().hKey(); List<HKeySegment> hKeySegments = hKey.segments(); int k = 0; // Traverse key, guided by hKey, populating result Object[] keyArray = new Object[keySize]; int h = 0; while (k < hKeySegments.size()) { HKeySegment hKeySegment = hKeySegments.get(k++); UserTable table = hKeySegment.table(); int ordinal = (Integer) key.decode(); assert ordinalToTable.get(ordinal) == table : ordinalToTable.get(ordinal); keyArray[h++] = table; for (int i = 0; i < hKeySegment.columns().size(); i++) { keyArray[h++] = key.decode(); } } return keyArray; } private final static byte[] EMPTY_BYTE_ARRAY = new byte[0]; private Session session; private PersistitStore store; private Exchange exchange; private final Map<Integer, UserTable> ordinalToTable = new HashMap<Integer, UserTable>(); }
package com.akiban.sql.optimizer; import com.akiban.ais.model.TableIndex; import com.akiban.sql.optimizer.SimplifiedQuery.*; import com.akiban.sql.parser.*; import com.akiban.sql.compiler.*; import com.akiban.sql.StandardException; import com.akiban.sql.views.ViewDefinition; import com.akiban.ais.model.AkibanInformationSchema; import com.akiban.ais.model.Column; import com.akiban.ais.model.GroupTable; import com.akiban.ais.model.Index; import com.akiban.ais.model.IndexColumn; import com.akiban.ais.model.Join; import com.akiban.ais.model.UserTable; import com.akiban.server.api.dml.ColumnSelector; import com.akiban.qp.expression.Comparison; import com.akiban.qp.expression.Expression; import com.akiban.qp.expression.IndexBound; import com.akiban.qp.expression.IndexKeyRange; import static com.akiban.qp.expression.API.*; import com.akiban.qp.physicaloperator.PhysicalOperator; import static com.akiban.qp.physicaloperator.API.*; import com.akiban.qp.row.Row; import com.akiban.qp.rowtype.IndexRowType; import com.akiban.qp.rowtype.RowType; import com.akiban.qp.rowtype.Schema; import com.akiban.qp.rowtype.UserTableRowType; import java.util.*; /** * Compile SQL statements into operator trees. */ public class OperatorCompiler { protected SQLParserContext parserContext; protected NodeFactory nodeFactory; protected AISBinder binder; protected AISTypeComputer typeComputer; protected BooleanNormalizer booleanNormalizer; protected SubqueryFlattener subqueryFlattener; protected Grouper grouper; protected Schema schema; public OperatorCompiler(SQLParser parser, AkibanInformationSchema ais, String defaultSchemaName) { parserContext = parser; nodeFactory = parserContext.getNodeFactory(); binder = new AISBinder(ais, defaultSchemaName); parser.setNodeFactory(new BindingNodeFactory(nodeFactory)); typeComputer = new AISTypeComputer(); booleanNormalizer = new BooleanNormalizer(parser); subqueryFlattener = new SubqueryFlattener(parser); grouper = new Grouper(parser); schema = new Schema(ais); } public void addView(ViewDefinition view) throws StandardException { binder.addView(view); } public static class Result { private PhysicalOperator resultOperator; private RowType resultRowType; private List<Column> resultColumns; private int[] resultColumnOffsets; private int offset = 0; private int limit = -1; public Result(PhysicalOperator resultOperator, RowType resultRowType, List<Column> resultColumns, int[] resultColumnOffsets, int offset, int limit) { this.resultOperator = resultOperator; this.resultRowType = resultRowType; this.resultColumns = resultColumns; this.resultColumnOffsets = resultColumnOffsets; this.offset = offset; this.limit = limit; } public Result(PhysicalOperator resultOperator, RowType resultRowType) { this.resultOperator = resultOperator; this.resultRowType = resultRowType; } public PhysicalOperator getResultOperator() { return resultOperator; } public RowType getResultRowType() { return resultRowType; } public List<Column> getResultColumns() { return resultColumns; } public int[] getResultColumnOffsets() { return resultColumnOffsets; } public int getOffset() { return offset; } public int getLimit() { return limit; } public boolean isModify() { return (resultColumns == null); } @Override public String toString() { StringBuilder sb = new StringBuilder(); for (String operator : explainPlan()) { if (sb.length() > 0) sb.append("\n"); sb.append(operator); } return sb.toString(); } public List<String> explainPlan() { List<String> result = new ArrayList<String>(); explainPlan(resultOperator, result, 0); return result; } protected static void explainPlan(PhysicalOperator operator, List<String> into, int depth) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < depth; i++) sb.append(" "); sb.append(operator); into.add(sb.toString()); for (PhysicalOperator inputOperator : operator.getInputOperators()) { explainPlan(inputOperator, into, depth+1); } } } public Result compile(DMLStatementNode stmt) throws StandardException { switch (stmt.getNodeType()) { case NodeTypes.CURSOR_NODE: return compileSelect((CursorNode)stmt); case NodeTypes.UPDATE_NODE: return compileUpdate((UpdateNode)stmt); case NodeTypes.INSERT_NODE: return compileInsert((InsertNode)stmt); case NodeTypes.DELETE_NODE: return compileDelete((DeleteNode)stmt); default: throw new UnsupportedSQLException("Unsupported statement type: " + stmt.statementToString()); } } protected DMLStatementNode bindAndGroup(DMLStatementNode stmt) throws StandardException { binder.bind(stmt); stmt = (DMLStatementNode)booleanNormalizer.normalize(stmt); typeComputer.compute(stmt); stmt = subqueryFlattener.flatten(stmt); grouper.group(stmt); return stmt; } public Result compileSelect(CursorNode cursor) throws StandardException { // Get into standard form. cursor = (CursorNode)bindAndGroup(cursor); SimplifiedSelectQuery squery = new SimplifiedSelectQuery(cursor, grouper.getJoinConditions()); squery.reorderJoins(); GroupBinding group = squery.getGroup(); GroupTable groupTable = group.getGroup().getGroupTable(); // Try to use an index. IndexUsage index = pickBestIndex(squery); if ((squery.getSortColumns() != null) && !((index != null) && index.isSorting())) throw new UnsupportedSQLException("Unsupported ORDER BY"); PhysicalOperator resultOperator; if (index != null) { squery.removeConditions(index.getIndexConditions()); squery.recomputeUsed(); squery.removeUnusedJoins(); TableIndex iindex = index.getIndex(); TableNode indexTable = index.getTable(); squery.getTables().setLeftBranch(indexTable); UserTableRowType tableType = tableRowType(indexTable); IndexRowType indexType = tableType.indexRowType(iindex); resultOperator = indexScan_Default(indexType, index.isReverse(), index.getIndexKeyRange()); // Decide whether to use BranchLookup, which gets all // descendants, or AncestorLookup, which gets just the // given type with the same number of B-tree accesses and // so is more efficient, for the index's target table. boolean tableUsed = false, descendantUsed = false; for (TableNode table : indexTable.subtree()) { if (table == indexTable) { tableUsed = table.isUsed(); } else if (table.isUsed()) { descendantUsed = true; break; } } RowType ancestorType = indexType; if (descendantUsed) { resultOperator = lookup_Default(resultOperator, groupTable, indexType, tableType, false); checkForCrossProducts(indexTable); ancestorType = tableType; // Index no longer in stream. } // Tables above this that also need to be output. List<RowType> addAncestors = new ArrayList<RowType>(); // Any other branches need to be added beside the main one. List<TableNode> addBranches = new ArrayList<TableNode>(); for (TableNode left = indexTable; left != null; left = left.getParent()) { if ((left == indexTable) ? (!descendantUsed && tableUsed) : left.isUsed()) { addAncestors.add(tableRowType(left)); } { TableNode previous = null; TableNode sibling = left; while (true) { sibling = sibling.getNextSibling(); if (sibling == null) break; if (sibling.subtreeUsed()) { if (!descendantUsed && !tableUsed) { // TODO: Better would be to set a flag // for ancestorLookup below to keep // the index type in the output and // use it for the branch lookup. addAncestors.add(0, tableType); tableUsed = true; } addBranches.add(sibling); if (previous != null) needCrossProduct(previous, sibling); previous = sibling; } } } } if (!addAncestors.isEmpty()) { resultOperator = ancestorLookup_Default(resultOperator, groupTable, ancestorType, addAncestors, (descendantUsed && tableUsed)); } for (TableNode branchTable : addBranches) { resultOperator = lookup_Default(resultOperator, groupTable, tableType, tableRowType(branchTable), true); checkForCrossProducts(branchTable); } } else { resultOperator = groupScan_Default(groupTable); checkForCrossProducts(squery.getTables().getRoot()); } // TODO: Can apply most Select conditions before flattening. // In addition to conditions between fields of different // tables, a left join should not be satisfied if the right // table has a failing condition, since the WHERE is on the // whole (as opposed to the outer join with a subquery // containing the condition). Flattener fl = new Flattener(resultOperator); FlattenState fls = fl.flatten(squery.getJoins()); resultOperator = fl.getResultOperator(); RowType resultRowType = fls.getResultRowType(); Map<TableNode,Integer> fieldOffsets = fls.getFieldOffsets(); for (ColumnCondition condition : squery.getConditions()) { Expression predicate = condition.generateExpression(fieldOffsets); resultOperator = select_HKeyOrdered(resultOperator, resultRowType, predicate); } int ncols = squery.getSelectColumns().size(); List<Column> resultColumns = new ArrayList<Column>(ncols); int[] resultColumnOffsets = new int[ncols]; int i = 0; for (SimpleExpression selectExpr : squery.getSelectColumns()) { if (!selectExpr.isColumn()) throw new UnsupportedSQLException("Unsupported result column: " + selectExpr); ColumnExpression selectColumn = (ColumnExpression)selectExpr; TableNode table = selectColumn.getTable(); Column column = selectColumn.getColumn(); resultColumns.add(column); resultColumnOffsets[i++] = fieldOffsets.get(table) + column.getPosition(); } int offset = squery.getOffset(); int limit = squery.getLimit(); return new Result(resultOperator, resultRowType, resultColumns, resultColumnOffsets, offset, limit); } public Result compileUpdate(UpdateNode update) throws StandardException { update = (UpdateNode)bindAndGroup(update); SimplifiedUpdateStatement supdate = new SimplifiedUpdateStatement(update, grouper.getJoinConditions()); supdate.reorderJoins(); TableNode targetTable = supdate.getTargetTable(); GroupTable groupTable = targetTable.getGroupTable(); UserTableRowType targetRowType = tableRowType(targetTable); // TODO: If we flattened subqueries (e.g., IN or EXISTS) into // the main result set, then the index and conditions might be // on joined tables, which might need to be looked up and / or // flattened in before non-index conditions. IndexUsage index = pickBestIndex(supdate); PhysicalOperator resultOperator; if (index != null) { assert (targetTable == index.getTable()); supdate.removeConditions(index.getIndexConditions()); TableIndex iindex = index.getIndex(); IndexRowType indexType = targetRowType.indexRowType(iindex); resultOperator = indexScan_Default(indexType, index.isReverse(), index.getIndexKeyRange()); if (false) { List<RowType> ancestors = Collections.<RowType>singletonList(targetRowType); resultOperator = ancestorLookup_Default(resultOperator, groupTable, indexType, ancestors, false); } else { resultOperator = lookup_Default(resultOperator, groupTable, indexType, targetRowType, false); } } else { resultOperator = groupScan_Default(groupTable); } Map<TableNode,Integer> fieldOffsets = new HashMap<TableNode,Integer>(1); fieldOffsets.put(targetTable, 0); for (ColumnCondition condition : supdate.getConditions()) { Expression predicate = condition.generateExpression(fieldOffsets); resultOperator = select_HKeyOrdered(resultOperator, targetRowType, predicate); } Expression[] updates = new Expression[targetRowType.nFields()]; for (SimplifiedUpdateStatement.UpdateColumn updateColumn : supdate.getUpdateColumns()) { updates[updateColumn.getColumn().getPosition()] = updateColumn.getValue().generateExpression(fieldOffsets); } ExpressionRow updateRow = new ExpressionRow(targetRowType, updates); resultOperator = new com.akiban.qp.physicaloperator.Update_Default(resultOperator, new ExpressionRowUpdateFunction(updateRow)); return new Result(resultOperator, targetRowType); } public Result compileInsert(InsertNode insert) throws StandardException { insert = (InsertNode)bindAndGroup(insert); SimplifiedInsertStatement sstmt = new SimplifiedInsertStatement(insert, grouper.getJoinConditions()); throw new UnsupportedSQLException("No Insert operators yet"); } public Result compileDelete(DeleteNode delete) throws StandardException { delete = (DeleteNode)bindAndGroup(delete); SimplifiedDeleteStatement sstmt = new SimplifiedDeleteStatement(delete, grouper.getJoinConditions()); throw new UnsupportedSQLException("No Delete operators yet"); } // A possible index. class IndexUsage implements Comparable<IndexUsage> { private TableNode table; private TableIndex index; private List<ColumnCondition> equalityConditions; private ColumnCondition lowCondition, highCondition; private boolean sorting, reverse; public IndexUsage(TableNode table, TableIndex index) { this.table = table; this.index = index; } public TableNode getTable() { return table; } public TableIndex getIndex() { return index; } // The conditions that this index usage subsumes. public Set<ColumnCondition> getIndexConditions() { Set<ColumnCondition> result = new HashSet<ColumnCondition>(); if (equalityConditions != null) result.addAll(equalityConditions); if (lowCondition != null) result.add(lowCondition); if (highCondition != null) result.add(highCondition); return result; } // Does this index accomplish the query's sorting? public boolean isSorting() { return sorting; } // Should the index iteration be in reverse? public boolean isReverse() { return reverse; } // Is this a better index? // TODO: Best we can do without any idea of selectivity. public int compareTo(IndexUsage other) { if (sorting) { if (!other.sorting) return +1; } else if (other.sorting) return -1; if (equalityConditions != null) { if (other.equalityConditions == null) return +1; else if (equalityConditions.size() != other.equalityConditions.size()) return (equalityConditions.size() > other.equalityConditions.size()) ? +1 : -1; } else if (other.equalityConditions != null) return -1; int n = 0, on = 0; if (lowCondition != null) n++; if (highCondition != null) n++; if (other.lowCondition != null) on++; if (other.highCondition != null) on++; if (n != on) return (n > on) ? +1 : -1; return index.getTable().getTableId().compareTo(other.index.getTable().getTableId()); } // Can this index be used for part of the given query? public boolean usable(SimplifiedQuery squery) { List<IndexColumn> indexColumns = index.getColumns(); int ncols = indexColumns.size(); int nequals = 0; while (nequals < ncols) { IndexColumn indexColumn = indexColumns.get(nequals); Column column = indexColumn.getColumn(); ColumnCondition equalityCondition = squery.findColumnConstantCondition(column, Comparison.EQ); if (equalityCondition == null) break; if (nequals == 0) equalityConditions = new ArrayList<ColumnCondition>(1); equalityConditions.add(equalityCondition); nequals++; } if (nequals < ncols) { IndexColumn indexColumn = indexColumns.get(nequals); Column column = indexColumn.getColumn(); lowCondition = squery.findColumnConstantCondition(column, Comparison.GT); highCondition = squery.findColumnConstantCondition(column, Comparison.LT); } if (squery.getSortColumns() != null) { // Sort columns corresponding to equality constraints // were removed already as pointless. So the remaining // ones just need to be a subset of the remaining // index columns. int nsort = squery.getSortColumns().size(); if (nsort <= (ncols - nequals)) { found: { for (int i = 0; i < nsort; i++) { SortColumn sort = squery.getSortColumns().get(i); IndexColumn index = indexColumns.get(nequals + i); if (sort.getColumn() != index.getColumn()) break found; // Iterate in reverse if index goes wrong way. boolean dirMismatch = (sort.isAscending() != index.isAscending().booleanValue()); if (i == 0) reverse = dirMismatch; else if (reverse != dirMismatch) break found; } // This index will accomplish required sorting. sorting = true; } } } return ((equalityConditions != null) || (lowCondition != null) || (highCondition != null) || sorting); } // Generate key range bounds. public IndexKeyRange getIndexKeyRange() { if ((equalityConditions == null) && (lowCondition == null) && (highCondition == null)) return new IndexKeyRange(null, false, null, false); List<IndexColumn> indexColumns = index.getColumns(); int nkeys = indexColumns.size(); Expression[] keys = new Expression[nkeys]; int kidx = 0; if (equalityConditions != null) { for (ColumnCondition cond : equalityConditions) { keys[kidx++] = cond.getRight().generateExpression(null); } } if ((lowCondition == null) && (highCondition == null)) { IndexBound eq = getIndexBound(index, keys); return new IndexKeyRange(eq, true, eq, true); } else { Expression[] lowKeys = null, highKeys = null; boolean lowInc = false, highInc = false; if (lowCondition != null) { lowKeys = keys; if (highCondition != null) { highKeys = new Expression[nkeys]; System.arraycopy(keys, 0, highKeys, 0, kidx); } } else if (highCondition != null) { highKeys = keys; } if (lowCondition != null) { lowKeys[kidx] = lowCondition.getRight().generateExpression(null); lowInc = (lowCondition.getOperation() == Comparison.GE); } if (highCondition != null) { highKeys[kidx] = highCondition.getRight().generateExpression(null); highInc = (highCondition.getOperation() == Comparison.LE); } IndexBound lo = getIndexBound(index, lowKeys); IndexBound hi = getIndexBound(index, highKeys); return new IndexKeyRange(lo, lowInc, hi, highInc); } } } // Pick an index to use. protected IndexUsage pickBestIndex(SimplifiedQuery squery) { if (squery.getConditions().isEmpty() && (squery.getSortColumns() == null)) return null; IndexUsage bestIndex = null; for (TableNode table : squery.getTables()) { if (table.isUsed() && !table.isOuter()) { for (TableIndex index : table.getTable().getIndexes()) { // TODO: getIndexesIncludingInternal() IndexUsage candidate = new IndexUsage(table, index); if (candidate.usable(squery)) { if ((bestIndex == null) || (candidate.compareTo(bestIndex) > 0)) bestIndex = candidate; } } } } return bestIndex; } static class FlattenState { private RowType resultRowType; private Map<TableNode,Integer> fieldOffsets; int nfields; public FlattenState(RowType resultRowType, Map<TableNode,Integer> fieldOffsets, int nfields) { this.resultRowType = resultRowType; this.fieldOffsets = fieldOffsets; this.nfields = nfields; } public RowType getResultRowType() { return resultRowType; } public void setResultRowType(RowType resultRowType) { this.resultRowType = resultRowType; } public Map<TableNode,Integer> getFieldOffsets() { return fieldOffsets; } public int getNfields() { return nfields; } public void mergeFields(FlattenState other) { for (TableNode table : other.fieldOffsets.keySet()) { fieldOffsets.put(table, other.fieldOffsets.get(table) + nfields); } nfields += other.nfields; } } // Holds a partial operator tree while flattening, since need the // single return value for above per-branch result. class Flattener { private PhysicalOperator resultOperator; public Flattener(PhysicalOperator resultOperator) { this.resultOperator = resultOperator; } public PhysicalOperator getResultOperator() { return resultOperator; } public FlattenState flatten(BaseJoinNode join) { if (join.isTable()) { TableNode table = ((TableJoinNode)join).getTable(); Map<TableNode,Integer> fieldOffsets = new HashMap<TableNode,Integer>(); fieldOffsets.put(table, 0); return new FlattenState(tableRowType(table), fieldOffsets, table.getNFields()); } else { JoinJoinNode jjoin = (JoinJoinNode)join; BaseJoinNode left = jjoin.getLeft(); BaseJoinNode right = jjoin.getRight(); FlattenState fleft = flatten(left); FlattenState fright = flatten(right); int flags = DEFAULT; switch (jjoin.getJoinType()) { case LEFT: flags = LEFT_JOIN; break; case RIGHT: flags = RIGHT_JOIN; break; } resultOperator = flatten_HKeyOrdered(resultOperator, fleft.getResultRowType(), fright.getResultRowType(), flags); fleft.setResultRowType(resultOperator.rowType()); fleft.mergeFields(fright); return fleft; } } } protected UserTableRowType tableRowType(TableNode table) { return schema.userTableRowType(table.getTable()); } protected IndexBound getIndexBound(TableIndex index, Expression[] keys) { if (keys == null) return null; return new IndexBound((UserTable)index.getTable(), getIndexExpressionRow(index, keys), getIndexColumnSelector(index)); } protected ColumnSelector getIndexColumnSelector(final Index index) { return new ColumnSelector() { public boolean includesColumn(int columnPosition) { for (IndexColumn indexColumn : index.getColumns()) { Column column = indexColumn.getColumn(); if (column.getPosition() == columnPosition) { return true; } } return false; } }; } protected Row getIndexExpressionRow(TableIndex index, Expression[] keys) { return new ExpressionRow(schema.indexRowType(index), keys); } /** Check whether any list of children has a cross-product join, * since that does not come from the group structure. */ protected void checkForCrossProducts(TableNode node) throws StandardException { for (TableNode parent : node.subtree()) { TableNode previous = null; for (TableNode child = parent.getFirstChild(); child != null; child = child.getNextSibling()) { if (child.subtreeUsed()) { if (previous != null) needCrossProduct(previous, child); previous = child; } } } } // TODO: One slow way to do a cross product might be to filter out // any existing right rows and then lookup to get all of them for // the left's hkey. protected void needCrossProduct(TableNode left, TableNode right) throws StandardException { throw new UnsupportedSQLException("Need cross product between " + left + " and " + right); } }
package com.amee.base.validation; import com.amee.base.resource.ValidationResult; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.MutablePropertyValues; import org.springframework.beans.PropertyValues; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.MessageSource; import org.springframework.validation.DataBinder; import org.springframework.validation.Errors; import org.springframework.validation.ValidationUtils; import org.springframework.validation.Validator; import java.beans.PropertyEditor; import java.util.Map; /** * A base class providing a number of utility functions to validate objects. A {@link MessageSource} and * a {@link DataBinder} are used internally, integrating into the Spring validation framework. * <p/> * TODO: Merge this with {@link BaseValidator}. */ public abstract class ValidationHelper { private final Log log = LogFactory.getLog(getClass()); @Autowired private MessageSource messageSource; private DataBinder dataBinder; public ValidationHelper() { super(); } /** * Validates the supplied form. * <p/> * TODO: Binder.setValidator() & Binder.validate() instead. * * @param values to validate * @return true if form is valid, otherwise false */ public boolean isValid(Map<String, String> values) { log.debug("isValid()"); DataBinder dataBinder = getDataBinder(); prepareDataBinder(dataBinder); beforeBind(values); dataBinder.bind(createPropertyValues(values)); Errors errors = dataBinder.getBindingResult(); ValidationUtils.invokeValidator(getValidator(), dataBinder.getTarget(), errors); if (!errors.hasErrors()) { log.debug("isValid() - No validation errors."); return true; } else { log.debug("isValid() - Has validation errors."); return false; } } /** * Prepare the DataBinder before it is used for validation. Default implementation updates the DataBinder * allowedFields and calls registerCustomEditors with the DataBinder. * * @param dataBinder to be prepared */ protected void prepareDataBinder(DataBinder dataBinder) { dataBinder.setAllowedFields(getAllowedFields()); registerCustomEditors(dataBinder); } /** * Hook for registering custom PropertyEditors into the DataBinder. Default implementation does * nothing. Extending classes should override this method to supply required PropertyEditors to * the DataBinder. * * @param dataBinder to set editors on */ protected void registerCustomEditors(DataBinder dataBinder) { // do nothing } /** * Register a custom editor to the DataBinder. * * @param requiredType the type of the property * @param field the field name of the property * @param propertyEditor a {@link PropertyEditor} implementation */ protected void add(Class requiredType, String field, PropertyEditor propertyEditor) { getDataBinder().registerCustomEditor(requiredType, field, propertyEditor); } /** * Create a new {@link DataBinder}. * * @return the new {@link DataBinder} */ protected DataBinder createDataBinder() { return new DataBinder(getObject(), getName()); } /** * Hook for pre-processing the Form before binding happens. * * @param values to be validated */ protected void beforeBind(Map<String, String> values) { // do nothing } /** * Renames all parameters in the Form that match oldName to newName. Useful for re-implementations of beforeBind. * * @param values to consider for renaming * @param oldName old name for value * @param newName new name for value */ protected void renameValue(Map<String, String> values, String oldName, String newName) { String value = values.remove(oldName); if (value != null) { values.put(newName, value); } } protected PropertyValues createPropertyValues(Map<String, String> values) { return new MutablePropertyValues(values); } protected Validator getValidator() { throw new UnsupportedOperationException(); } /** * Get a DataBinder for the current validator. If a DataBinder has not already been created * a new one will be created and cached for subsequent calls. * * @return the DataBinder */ public DataBinder getDataBinder() { if (dataBinder == null) { dataBinder = createDataBinder(); } return dataBinder; } /** * Convenience method to get the BindingResult (errors) from the current DataBinder. * * @return Errors object */ public Errors getErrors() { return getDataBinder().getBindingResult(); } public Object getObject() { throw new UnsupportedOperationException(); } public String getName() { throw new UnsupportedOperationException(); } public String[] getAllowedFields() { return new String[]{}; } public ValidationResult getValidationResult() { // We always want a new ValidationResult. ValidationResult validationResult = new ValidationResult(messageSource); // Add the errors. validationResult.setErrors(getErrors()); // Add the values. // NOTE: This is not required and was commented out 2010/08/18 by DB. Left here for reference. // for (String field : getAllowedFields()) { // Object value = getErrors().getFieldValue(field); // if ((value != null) && (value instanceof String)) { // validationResult.addValue(field, (String) value); return validationResult; } }
package com.bupt.poirot.z3.parseAndDeduceOWL; import java.io.File; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.microsoft.z3.BoolExpr; import com.microsoft.z3.Context; import com.microsoft.z3.Expr; import com.microsoft.z3.FuncDecl; import com.microsoft.z3.Quantifier; import com.microsoft.z3.Solver; import com.microsoft.z3.Sort; import com.microsoft.z3.Status; import org.semanticweb.HermiT.model.DLClause; public class Main { public static Pattern pattern = Pattern.compile("(.+)\\((.+?)\\)"); public static Quantifier mkQuantifier(Context ctx, String boundString, String quantifierString, Set<String> sortSet) { Map<String, Sort> map = new HashMap<>(); String[] strings = quantifierString.split(","); for (String str : strings) { Matcher matcher = pattern.matcher(str); if (matcher.find()) { String string = matcher.group(2); System.out.println(string); String[] varibles = string.split(","); for (String var : varibles) { if (!map.containsKey(var)) { Sort sort = ctx.mkUninterpretedSort(var); map.put(var, sort); } } Sort[] domains = new Sort[varibles.length]; for (int i = 0; i < domains.length; i++) { domains[i] = map.get(varibles[i]); } String funcName = matcher.group(1); FuncDecl funcDecl = ctx.mkFuncDecl(funcName, domains, ctx.mkBoolSort()); Expr[] exprs = new Expr[varibles.length]; for (int i = 0; i < exprs.length; i++) { exprs[i] = ctx.mk } BoolExpr boolExpr = ctx.mkApp(funcdecl } } strings = boundString.split(","); for (String str : strings) { } Quantifier quantifier = null; return quantifier; } public static void main(String[] args) { System.out.println("begin"); // File file = new File("data/ontologies/warnSchemaTest0.xml"); File file = new File("data/schema.owl"); Set<DLClause> set = ParseOWL.parseOwl(file); System.out.println(set.size()); Set<String> quantifiersSet = new HashSet<>(); Set<String> boundStringSet = new HashSet<>(); Set<String> sortSet = new HashSet<>(); Context context = new Context(); Solver solver = context.mkSolver(); for (DLClause dlClause: set) { String dlClauseString = dlClause.toString(); String[] strings = dlClauseString.split(":-"); System.out.println(dlClauseString); String quantifier = strings[1]; quantifiersSet.add(quantifier); String boundString = strings[0]; boundStringSet.add(boundString); mkQuantifier(context, boundString, quantifier, sortSet); } if (solver.check() == Status.SATISFIABLE) { System.out.println(Status.SATISFIABLE); System.out.println(solver.getModel()); } else { System.out.println(Status.UNSATISFIABLE); } } }
package com.celements.web.service; import java.io.FileNotFoundException; import java.io.IOException; import java.math.BigDecimal; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.ResourceBundle; import org.apache.commons.lang.NotImplementedException; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xwiki.component.annotation.Component; import org.xwiki.component.annotation.Requirement; import org.xwiki.component.manager.ComponentLookupException; import org.xwiki.component.manager.ComponentManager; import org.xwiki.configuration.ConfigurationSource; import org.xwiki.context.Execution; import org.xwiki.model.EntityType; import org.xwiki.model.reference.AttachmentReference; import org.xwiki.model.reference.DocumentReference; import org.xwiki.model.reference.EntityReference; import org.xwiki.model.reference.EntityReferenceResolver; import org.xwiki.model.reference.EntityReferenceSerializer; import org.xwiki.model.reference.SpaceReference; import org.xwiki.model.reference.WikiReference; import com.celements.emptycheck.internal.IDefaultEmptyDocStrategyRole; import com.celements.inheritor.TemplatePathTransformationConfiguration; import com.celements.navigation.cmd.MultilingualMenuNameCommand; import com.celements.nextfreedoc.INextFreeDocRole; import com.celements.pagelayout.LayoutScriptService; import com.celements.pagetype.PageTypeReference; import com.celements.pagetype.service.IPageTypeResolverRole; import com.celements.parents.IDocumentParentsListerRole; import com.celements.rendering.RenderCommand; import com.celements.rendering.XHTMLtoHTML5cleanup; import com.celements.rights.AccessLevel; import com.celements.sajson.Builder; import com.celements.web.comparators.BaseObjectComparator; import com.celements.web.plugin.cmd.CelSendMail; import com.celements.web.plugin.cmd.EmptyCheckCommand; import com.celements.web.plugin.cmd.PageLayoutCommand; import com.celements.web.plugin.cmd.PlainTextCommand; import com.xpn.xwiki.XWikiContext; import com.xpn.xwiki.XWikiException; import com.xpn.xwiki.api.Attachment; import com.xpn.xwiki.api.Document; import com.xpn.xwiki.doc.XWikiAttachment; import com.xpn.xwiki.doc.XWikiDocument; import com.xpn.xwiki.objects.BaseObject; import com.xpn.xwiki.render.XWikiRenderingEngine; import com.xpn.xwiki.user.api.XWikiRightService; import com.xpn.xwiki.user.api.XWikiUser; import com.xpn.xwiki.web.Utils; import com.xpn.xwiki.web.XWikiMessageTool; import com.xpn.xwiki.web.XWikiRequest; @Component public class WebUtilsService implements IWebUtilsService { private static final WikiReference CENTRAL_WIKI_REF = new WikiReference("celements2web"); private static Logger _LOGGER = LoggerFactory.getLogger(WebUtilsService.class); @Requirement ComponentManager componentManager; @Requirement("default") EntityReferenceSerializer<String> serializer_default; @Requirement("local") EntityReferenceSerializer<String> serializer_local; @Requirement EntityReferenceResolver<String> referenceResolver; /** * Used to get the template path mapping information. */ @Requirement private TemplatePathTransformationConfiguration tempPathConfig; @Requirement IDefaultEmptyDocStrategyRole emptyChecker; @Requirement INextFreeDocRole nextFreeDocService; @Requirement ConfigurationSource defaultConfigSrc; /* * not loaded as requirement due to cyclic dependency */ IDocumentParentsListerRole docParentsLister; @Requirement Execution execution; XWikiRenderingEngine injectedRenderingEngine; private XWikiContext getContext() { return (XWikiContext)execution.getContext().getProperty("xwikicontext"); } @Override public DocumentReference getParentForLevel(int level) { _LOGGER.trace("getParentForLevel: start for level " + level); DocumentReference parent = null; List<DocumentReference> parentList = getDocumentParentsList( getContext().getDoc().getDocumentReference(), true); int startAtItem = (parentList.size() - level) + 1; if ((startAtItem > -1) && (startAtItem < parentList.size())) { parent = parentList.get(startAtItem); } _LOGGER.debug("getParentForLevel: level [" + level + "] returning [" + parent + "]"); return parent; } /** * @deprecated since 2.63.0 * @deprecated instead use IDocumentParentsListerRole.getDocumentParentsList( DocumentReference docRef, boolean includeDoc) */ @Override @Deprecated public List<DocumentReference> getDocumentParentsList(DocumentReference docRef, boolean includeDoc) { return getDocumentParentsLister().getDocumentParentsList(docRef, includeDoc); } @Override public String getDocSectionAsJSON(String regex, DocumentReference docRef, int section) throws XWikiException { Builder jsonBuilder = new Builder(); jsonBuilder.openArray(); jsonBuilder.openDictionary(); jsonBuilder.addStringProperty("content", getDocSection(regex, docRef, section)); int sectionNr = countSections(regex, docRef); jsonBuilder.openProperty("section"); jsonBuilder.addNumber(new BigDecimal(getSectionNr(section, sectionNr))); jsonBuilder.openProperty("sectionNr"); jsonBuilder.addNumber(new BigDecimal(sectionNr)); jsonBuilder.closeDictionary(); jsonBuilder.closeArray(); return jsonBuilder.getJSON(); } @Override public String getDocSection(String regex, DocumentReference docRef, int section ) throws XWikiException { _LOGGER.debug("use regex '" + regex + "' on '" + docRef + "' and get section " + section); XWikiDocument doc = getContext().getWiki().getDocument(docRef, getContext()); String content = doc.getTranslatedDocument(getContext()).getContent(); _LOGGER.debug("content of'" + docRef + "' is: '" + content + "'"); String section_str = null; if((content != null) && (!emptyChecker.isEmptyRTEString(content))){ section = getSectionNr(section, countSections(regex, docRef)); for (String partStr : content.split(regex)) { if(!emptyChecker.isEmptyRTEString(partStr)) { section if(section == 0) { section_str = partStr; break; } } } } else { _LOGGER.debug("content ist empty"); } if(section_str != null) { section_str = renderText(section_str); } return section_str; } @Override public int countSections(String regex, DocumentReference docRef) throws XWikiException { _LOGGER.debug("use regex '" + regex + "' on '" + docRef + "'"); XWikiDocument doc = getContext().getWiki().getDocument(docRef, getContext()); String content = doc.getTranslatedDocument(getContext()).getContent(); _LOGGER.debug("content of'" + docRef + "' is: '" + content + "'"); int parts = 0; if((content != null) && (!emptyChecker.isEmptyRTEString(content))){ for (String part : content.split(regex)) { if(!emptyChecker.isEmptyRTEString(part)) { parts++; } } } else { _LOGGER.debug("content ist empty"); } return parts; } int getSectionNr(int section, int sectionNr) { if(section <= 0){ section = 1; } if(section > sectionNr){ section = sectionNr; } return section; } private String renderText(String velocityText) { return getContext().getWiki().getRenderingEngine().renderText( "{pre}" + velocityText + "{/pre}", getContext().getDoc(), getContext()); } private boolean isEmptyRTEString(String rteContent) { return new EmptyCheckCommand().isEmptyRTEString(rteContent); } @Override public List<String> getAllowedLanguages() { if ((getContext() != null) && (getContext().getDoc() != null)) { return getAllowedLanguages(getContext().getDoc().getDocumentReference( ).getLastSpaceReference().getName()); } return Collections.emptyList(); } @Override public List<String> getAllowedLanguages(String spaceName) { List<String> languages = new ArrayList<String>(); String spaceLanguages = getContext().getWiki().getSpacePreference("languages", spaceName, "", getContext()); languages.addAll(Arrays.asList(spaceLanguages.split("[ ,]"))); languages.remove(""); if (languages.size() > 0) { _LOGGER.debug("getAllowedLanguages: returning [" + spaceLanguages + "] for space [" + spaceName + "]"); return languages; } _LOGGER.warn("Deprecated usage of Preferences field 'language'." + " Instead use 'languages'."); return Arrays.asList(getContext().getWiki( ).getSpacePreference("language", spaceName, "", getContext()).split("[ ,]")); } @Override public Date parseDate(String date, String format){ try{ return new SimpleDateFormat(format).parse(date); } catch(ParseException exp){ _LOGGER.error("parseDate failed.", exp); return null; } } @Override public XWikiMessageTool getMessageTool(String adminLanguage) { if(adminLanguage != null) { if((getContext().getLanguage() != null) && getContext().getLanguage().equals( adminLanguage)) { return getContext().getMessageTool(); } else { Locale locale = new Locale(adminLanguage); ResourceBundle bundle = ResourceBundle.getBundle("ApplicationResources", locale); if (bundle == null) { bundle = ResourceBundle.getBundle("ApplicationResources"); } XWikiContext adminContext = (XWikiContext) getContext().clone(); adminContext.putAll(getContext()); adminContext.setLanguage(adminLanguage); return new XWikiMessageTool(bundle, adminContext); } } else { return null; } } @Override public XWikiMessageTool getAdminMessageTool() { return getMessageTool(getAdminLanguage()); } @Override public String getAdminLanguage() { return getAdminLanguage(getContext().getUser()); } /** * @deprecated since 2.34.0 instead use getAdminLanguage(DocumentReference userRef) */ @Deprecated @Override public String getAdminLanguage(String userFullName) { return getAdminLanguage(resolveDocumentReference(userFullName)); } @Override public String getAdminLanguage(DocumentReference userRef) { String adminLanguage = null; try { DocumentReference xwikiUsersClassRef = new DocumentReference( userRef.getWikiReference().getName(), "XWiki", "XWikiUsers"); BaseObject userObj = getContext().getWiki().getDocument(userRef, getContext() ).getXObject(xwikiUsersClassRef); if (userObj != null) { adminLanguage = userObj.getStringValue("admin_language"); } } catch (XWikiException e) { _LOGGER.error("failed to get UserObject for " + getContext().getUser()); } if ((adminLanguage == null) || ("".equals(adminLanguage))) { adminLanguage = getDefaultAdminLanguage(); } return adminLanguage; } @Override public String getDefaultAdminLanguage() { String adminLanguage; adminLanguage = getContext().getWiki().getSpacePreference("admin_language", getContext().getLanguage(), getContext()); if ((adminLanguage == null) || ("".equals(adminLanguage))) { adminLanguage = getContext().getWiki().Param("celements.admin_language"); if ((adminLanguage == null) || ("".equals(adminLanguage))) { adminLanguage = "en"; } } return adminLanguage; } @Override public String getDefaultLanguage() { return getDefaultLanguage((SpaceReference) null); } @Deprecated @Override public String getDefaultLanguage(String spaceName) { SpaceReference spaceRef = null; if (StringUtils.isNotBlank(spaceName)) { spaceRef = resolveSpaceReference(spaceName); } return getDefaultLanguage(spaceRef); } @Override public String getDefaultLanguage(SpaceReference spaceRef) { String defaultLang = ""; String dbbackup = getContext().getDatabase(); XWikiDocument docBackup = getContext().getDoc(); try { if (spaceRef != null) { DocumentReference docRef = new DocumentReference("WebPreferences", spaceRef); if (getContext().getWiki().exists(docRef, getContext())) { getContext().setDatabase(spaceRef.getParent().getName()); getContext().setDoc(getContext().getWiki().getDocument(docRef, getContext())); } } defaultLang = defaultConfigSrc.getProperty("default_language", ""); } catch (XWikiException xwe) { _LOGGER.error("failed getting WebPreferences for space '{}'", spaceRef, xwe); } finally { getContext().setDatabase(dbbackup); getContext().setDoc(docBackup); } _LOGGER.trace("getDefaultLanguage: for spaceRef '{}' got lang '{}' ", spaceRef, defaultLang); return defaultLang; } @Override public boolean hasParentSpace() { return ((getParentSpace() != null) && !"".equals(getParentSpace())); } @Override public boolean hasParentSpace(String spaceName) { return ((getParentSpace(spaceName) != null) && !"".equals(getParentSpace(spaceName))); } @Override public String getParentSpace() { return getContext().getWiki().getSpacePreference("parent", getContext()); } @Override public String getParentSpace(String spaceName) { return getContext().getWiki().getSpacePreference("parent", spaceName, "", getContext()); } @Override public DocumentReference resolveDocumentReference(String fullName) { return resolveDocumentReference(fullName, null); } @Override public DocumentReference resolveDocumentReference(String fullName, WikiReference wikiRef) { return new DocumentReference(resolveEntityReference(fullName, EntityType.DOCUMENT, wikiRef)); } @Override public SpaceReference resolveSpaceReference(String spaceName) { return resolveSpaceReference(spaceName, null); } @Override public SpaceReference resolveSpaceReference(String spaceName, WikiReference wikiRef) { return new SpaceReference(resolveEntityReference(spaceName, EntityType.SPACE, wikiRef)); } @Override public AttachmentReference resolveAttachmentReference(String fullName) { return resolveAttachmentReference(fullName, null); } @Override public AttachmentReference resolveAttachmentReference(String fullName, WikiReference wikiRef) { return new AttachmentReference(resolveEntityReference(fullName, EntityType.ATTACHMENT, wikiRef)); } @Override public EntityReference resolveEntityReference(String name, EntityType type) { return resolveEntityReference(name, type, null); } @Override public EntityReference resolveEntityReference(String name, EntityType type, WikiReference wikiRef) { if (wikiRef == null) { wikiRef = new WikiReference(getContext().getDatabase()); } EntityReference ref = referenceResolver.resolve(name, type, wikiRef); _LOGGER.debug("resolveEntityReference: for [" + name + "] got reference [" + ref + "]"); return ref; } @Override public boolean isAdminUser() { try { if ((getContext().getXWikiUser() != null) && (getContext().getWiki().getRightService() != null) && (getContext().getDoc() != null)) { return (getContext().getWiki().getRightService().hasAdminRights(getContext()) || getContext().getXWikiUser().isUserInGroup("XWiki.XWikiAdminGroup", getContext())); } else { return false; } } catch (XWikiException e) { _LOGGER.error("Cannot determin if user has Admin Rights therefore guess" + " no (false).", e); return false; } } @Override public boolean isSuperAdminUser() { String user = getContext().getUser(); _LOGGER.trace("isSuperAdminUser: user [" + user + "] db [" + getContext().getDatabase() + "]."); return (isAdminUser() && (user.startsWith("xwiki:") || getContext().isMainWiki())); } @Override public boolean isLayoutEditor() { String user = getContext().getUser(); _LOGGER.trace("isLayoutEditor: user [" + user + "] db [" + getContext().getDatabase() + "]."); try { boolean isLayoutEditor = isAdvancedAdmin() || getContext().getXWikiUser( ).isUserInGroup("XWiki.LayoutEditorsGroup", getContext()); _LOGGER.debug("isLayoutEditor: admin [" + isAdminUser() + "] global user [" + user.startsWith("xwiki:") + "] returning [" + isLayoutEditor + "] db [" + getContext().getDatabase() + "]."); return isLayoutEditor; } catch (XWikiException exp) { _LOGGER.error("Failed to get user document for [" + user + "].", exp); } return false; } @Override public boolean isAdvancedAdmin() { String user = getContext().getUser(); _LOGGER.trace("isAdvancedAdmin: user [" + user + "] db [" + getContext().getDatabase() + "]."); try { XWikiDocument userDoc = getContext().getWiki().getDocument(resolveDocumentReference( user), getContext()); BaseObject userObj = userDoc.getXObject(resolveDocumentReference( "XWiki.XWikiUsers")); boolean isAdvancedAdmin = isAdminUser() && (user.startsWith("xwiki:") || ((userObj != null) && "Advanced".equals(userObj.getStringValue("usertype" )))); _LOGGER.debug("isAdvancedAdmin: admin [" + isAdminUser() + "] global user [" + user.startsWith("xwiki:") + "] usertype [" + ((userObj != null ) ? userObj.getStringValue("usertype") : "null") + "] returning [" + isAdvancedAdmin + "] db [" + getContext().getDatabase() + "]."); return isAdvancedAdmin; } catch (XWikiException exp) { _LOGGER.error("Failed to get user document for [" + user + "].", exp); } return false; } @Override public boolean hasAccessLevel(EntityReference ref, AccessLevel level ) throws XWikiException { return hasAccessLevel(ref, level, getContext().getXWikiUser()); } @Override public boolean hasAccessLevel(EntityReference ref, AccessLevel level, XWikiUser user ) throws XWikiException { boolean ret = false; DocumentReference docRef = null; if (ref instanceof SpaceReference) { docRef = nextFreeDocService.getNextUntitledPageDocRef((SpaceReference) ref); } else if (ref instanceof DocumentReference) { docRef = (DocumentReference) ref; } else if (ref instanceof AttachmentReference) { docRef = ((AttachmentReference) ref).getDocumentReference(); } if (docRef != null) { ret = getContext().getWiki().getRightService().hasAccessLevel(level.getIdentifier(), (user != null ? user.getUser() : XWikiRightService.GUEST_USER_FULLNAME), serializeRef(docRef), getContext()); } _LOGGER.debug("hasAccessLevel: for ref '{}', level '{}' and user '{}' returned '{}'", ref, level, user, ret); return ret; } @Override public XWikiAttachment getAttachment(AttachmentReference attRef) throws XWikiException { XWikiDocument attDoc = getContext().getWiki().getDocument( attRef.getDocumentReference(), getContext()); return attDoc.getAttachment(attRef.getName()); } @Override public Attachment getAttachmentApi(AttachmentReference attRef) throws XWikiException { XWikiAttachment att = getAttachment(attRef); if (att != null) { XWikiDocument attDoc = getContext().getWiki().getDocument( attRef.getDocumentReference(), getContext()); return new Attachment(attDoc.newDocument(getContext()), att, getContext()); } return null; } @Deprecated @SuppressWarnings("unchecked") @Override public List<Attachment> getAttachmentListSorted(Document doc, String comparator) throws ClassNotFoundException { List<Attachment> attachments = doc.getAttachmentList(); try { Comparator<Attachment> comparatorClass = (Comparator<Attachment>) Class.forName( "com.celements.web.comparators." + comparator).newInstance(); Collections.sort(attachments, comparatorClass); } catch (InstantiationException e) { _LOGGER.error("getAttachmentListSorted failed.", e); } catch (IllegalAccessException e) { _LOGGER.error("getAttachmentListSorted failed.", e); } catch (ClassNotFoundException e) { throw e; } return attachments; } @Override public List<XWikiAttachment> getAttachmentListSorted(XWikiDocument doc, Comparator<XWikiAttachment> comparator) { return getAttachmentListSorted(doc, comparator, false); } @Deprecated @Override public List<Attachment> getAttachmentListSorted(Document doc, String comparator, boolean imagesOnly) { return getAttachmentListSorted(doc, comparator, imagesOnly, 0, 0); } @Override public List<XWikiAttachment> getAttachmentListSorted(XWikiDocument doc, Comparator<XWikiAttachment> comparator, boolean imagesOnly) { return getAttachmentListSorted(doc, comparator, imagesOnly, 0, 0); } @Deprecated @Override public List<Attachment> getAttachmentListSorted(Document doc, String comparator, boolean imagesOnly, int start, int nb) { return getAttachmentListForTagSorted(doc, null, comparator, imagesOnly, start, nb); } @Override public List<XWikiAttachment> getAttachmentListSorted(XWikiDocument doc, Comparator<XWikiAttachment> comparator, boolean imagesOnly, int start, int nb) { List<XWikiAttachment> atts = new ArrayList<XWikiAttachment>(doc.getAttachmentList()); if (comparator != null) { Collections.sort(atts, comparator); } if (imagesOnly) { filterAttachmentsByImage(atts); } return Collections.unmodifiableList(reduceListToSize(atts, start, nb)); } private void filterAttachmentsByImage(List<XWikiAttachment> atts) { Iterator<XWikiAttachment> iter = atts.iterator(); while (iter.hasNext()) { if (!iter.next().isImage(getContext())) { iter.remove(); } } } @Override public List<Attachment> getAttachmentListSortedSpace(String spaceName, String comparator, boolean imagesOnly, int start, int nb ) throws ClassNotFoundException { return getAttachmentListForTagSortedSpace(spaceName, null, comparator, imagesOnly, start, nb); } @Override public List<Attachment> getAttachmentListForTagSorted(Document doc, String tagName, String comparator, boolean imagesOnly, int start, int nb) { try { List<Attachment> attachments = getAttachmentListSorted(doc, comparator); if (imagesOnly) { for (Attachment att : new ArrayList<Attachment>(attachments)) { if (!att.isImage()) { attachments.remove(att); } } } return reduceListToSize(filterAttachmentsByTag(attachments, tagName), start, nb); } catch (ClassNotFoundException exp) { _LOGGER.error("getAttachmentListSorted failed.", exp); } return Collections.emptyList(); } @Override public List<Attachment> getAttachmentListForTagSortedSpace(String spaceName, String tagName, String comparator, boolean imagesOnly, int start, int nb ) throws ClassNotFoundException { List<Attachment> attachments = new ArrayList<Attachment>(); try { for(String docName : getContext().getWiki().getSpaceDocsName(spaceName, getContext())) { DocumentReference docRef = new DocumentReference(getContext().getDatabase(), spaceName, docName); XWikiDocument doc = getContext().getWiki().getDocument(docRef, getContext()); attachments.addAll(new Document(doc, getContext()).getAttachmentList()); } } catch (XWikiException xwe) { _LOGGER.error("Could not get all documents in " + spaceName, xwe); } try { Comparator<Attachment> comparatorClass = (Comparator<Attachment>) Class.forName( "com.celements.web.comparators." + comparator).newInstance(); Collections.sort(attachments, comparatorClass); } catch (InstantiationException e) { _LOGGER.error("getAttachmentListSortedSpace failed.", e); } catch (IllegalAccessException e) { _LOGGER.error("getAttachmentListSortedSpace failed.", e); } catch (ClassNotFoundException e) { throw e; } if (imagesOnly) { for (Attachment att : new ArrayList<Attachment>(attachments)) { if (!att.isImage()) { attachments.remove(att); } } } return reduceListToSize(filterAttachmentsByTag(attachments, tagName), start, nb); } List<Attachment> filterAttachmentsByTag(List<Attachment> attachments, String tagName) { if((tagName != null) && getContext().getWiki().exists(resolveDocumentReference(tagName ), getContext())) { XWikiDocument filterDoc = null; try { filterDoc = getContext().getWiki().getDocument( resolveDocumentReference(tagName), getContext()); } catch(XWikiException xwe) { _LOGGER.error("Exception getting tag document '" + tagName + "'", xwe); } DocumentReference tagClassRef = new DocumentReference(getContext().getDatabase(), "Classes", "FilebaseTag"); if((filterDoc != null) && (filterDoc.getXObjectSize(tagClassRef) > 0)) { List<Attachment> filteredAttachments = new ArrayList<Attachment>(); for(Attachment attachment : attachments) { String attFN = attachment.getDocument().getFullName() + "/" + attachment.getFilename(); if(null != filterDoc.getXObject(tagClassRef, "attachment", attFN, false)) { filteredAttachments.add(attachment); } } return filteredAttachments; } } return attachments; } @Override public String getAttachmentListSortedAsJSON(Document doc, String comparator, boolean imagesOnly) { return getAttachmentListSortedAsJSON(doc, comparator, imagesOnly, 0, 0); } @Override public String getAttachmentListSortedAsJSON(Document doc, String comparator, boolean imagesOnly, int start, int nb) { SimpleDateFormat dateFormater = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss"); Builder jsonBuilder = new Builder(); jsonBuilder.openArray(); for (Attachment att : getAttachmentListSorted(doc, comparator, imagesOnly, start, nb) ) { jsonBuilder.openDictionary(); jsonBuilder.addStringProperty("filename", att.getFilename()); jsonBuilder.addStringProperty("version", att.getVersion()); jsonBuilder.addStringProperty("author", att.getAuthor()); jsonBuilder.addStringProperty("mimeType", att.getMimeType()); jsonBuilder.addStringProperty("lastChanged", dateFormater.format(att.getDate())); jsonBuilder.addStringProperty("url", doc.getAttachmentURL(att.getFilename())); jsonBuilder.closeDictionary(); } jsonBuilder.closeArray(); return jsonBuilder.getJSON(); } <T> List<T> reduceListToSize(List<T> list, int start, int nb) { List<T> countedAtts = new ArrayList<T>(); if ((start <= 0) && ((nb <= 0) || (nb >= list.size()))) { countedAtts = list; } else if (start < list.size()) { countedAtts = list.subList(Math.max(0, start), Math.min(Math.max(0, start) + Math.max(0, nb), list.size())); } return countedAtts; } Map<String, String> xwikiDoctoLinkedMap(XWikiDocument xwikiDoc, boolean bWithObjects, boolean bWithRendering, boolean bWithAttachmentContent, boolean bWithVersions) throws XWikiException { Map<String,String> docData = new LinkedHashMap<String, String>(); DocumentReference docRef = xwikiDoc.getDocumentReference(); docData.put("web", docRef.getLastSpaceReference().getName()); docData.put("name", docRef.getName()); docData.put("language", xwikiDoc.getLanguage()); docData.put("defaultLanguage", xwikiDoc.getDefaultLanguage()); docData.put("translation", "" + xwikiDoc.getTranslation()); docData.put("defaultLanguage", xwikiDoc.getDefaultLanguage()); List<DocumentReference> documentParentsList = getDocumentParentsList(docRef, false); String docParentStr = ""; if (!documentParentsList.isEmpty()) { DocumentReference docParentRef = documentParentsList.get(0); docParentStr = serializer_default.serialize(docParentRef); } docData.put("parent", docParentStr); String parentsListStr = ""; String parentsListMNStr = ""; MultilingualMenuNameCommand menuNameCmd = new MultilingualMenuNameCommand(); for(DocumentReference parentDocRef : documentParentsList) { String parentDocFN = serializer_default.serialize(parentDocRef); parentsListMNStr += menuNameCmd.getMultilingualMenuName(parentDocFN, getContext( ).getLanguage(), getContext()) + ","; parentsListStr += parentDocFN + ","; } docData.put("parentslist", parentsListStr.replaceAll(",*$", "")); docData.put("parentslistmenuname", parentsListMNStr.replaceAll(",*$", "")); PageTypeReference pageTypeRef = getPageTypeResolver().getPageTypeRefForDocWithDefault( xwikiDoc); if (pageTypeRef != null) { docData.put("pagetype", pageTypeRef.getConfigName()); } docData.put("author", xwikiDoc.getAuthor()); docData.put("creator", xwikiDoc.getCreator()); docData.put("customClass", xwikiDoc.getCustomClass()); docData.put("contentAuthor", xwikiDoc.getContentAuthor()); docData.put("creationDate", "" + xwikiDoc.getCreationDate().getTime()); docData.put("date", "" + xwikiDoc.getDate().getTime()); docData.put("contentUpdateDate", "" + xwikiDoc.getContentUpdateDate().getTime()); docData.put("version", xwikiDoc.getVersion()); docData.put("title", xwikiDoc.getTitle()); docData.put("template", serializer_local.serialize( xwikiDoc.getTemplateDocumentReference())); docData.put("getDefaultTemplate", xwikiDoc.getDefaultTemplate()); docData.put("getValidationScript", xwikiDoc.getValidationScript()); docData.put("comment", xwikiDoc.getComment()); docData.put("minorEdit", String.valueOf(xwikiDoc.isMinorEdit())); docData.put("syntaxId", xwikiDoc.getSyntax().toIdString()); docData.put("menuName", menuNameCmd.getMultilingualMenuName( serializer_default.serialize(xwikiDoc.getDocumentReference()), getContext( ).getLanguage(), getContext())); //docData.put("hidden", String.valueOf(xwikiDoc.isHidden())); /** TODO add Attachments for (XWikiAttachment attach : xwikiDoc.getAttachmentList()) { docel.add(attach.toXML(bWithAttachmentContent, bWithVersions, context)); }**/ if (bWithObjects) { // // Add Class // BaseClass bclass = xwikiDoc.getxWikiClass(); // if (bclass.getFieldList().size() > 0) { // // If the class has fields, add class definition and field information to XML // docel.add(bclass.toXML(null)); // // Add Objects (THEIR ORDER IS MOLDED IN STONE!) // for (Vector<BaseObject> objects : getxWikiObjects().values()) { // for (BaseObject obj : objects) { // if (obj != null) { // BaseClass objclass = null; // if (StringUtils.equals(getFullName(), obj.getClassName())) { // objclass = bclass; // } else { // objclass = obj.getxWikiClass(context); // docel.add(obj.toXML(objclass)); throw new NotImplementedException(); } String host = getContext().getRequest().getHeader("host"); // Add Content docData.put("content", replaceInternalWithExternalLinks(xwikiDoc.getContent(), host)); if (bWithRendering) { try { docData.put("renderedcontent", replaceInternalWithExternalLinks( xwikiDoc.getRenderedContent(getContext()), host)); } catch (XWikiException exp) { _LOGGER.error("Exception with rendering content: ", exp); } try { docData.put("celrenderedcontent", replaceInternalWithExternalLinks( getCelementsRenderCmd().renderCelementsDocument(xwikiDoc.getDocumentReference( ), getContext().getLanguage(), "view"), host)); } catch (XWikiException exp) { _LOGGER.error("Exception with rendering content: ", exp); } } if (bWithVersions) { try { docData.put("versions", xwikiDoc.getDocumentArchive(getContext() ).getArchive(getContext())); } catch (XWikiException exp) { _LOGGER.error("Document [" + docRef.getName() + "] has malformed history", exp); } } return docData; } private RenderCommand getCelementsRenderCmd() { RenderCommand renderCommand = new RenderCommand(); renderCommand.setDefaultPageType("RichText"); return renderCommand; } String replaceInternalWithExternalLinks(String content, String host) { String result = content.replaceAll("src=\\\"(\\.\\./)*/?download/", "src=\"http: + host + "/download/"); result = result.replaceAll("href=\\\"(\\.\\./)*/?download/", "href=\"http: + host + "/download/"); result = result.replaceAll("href=\\\"(\\.\\./)*/?skin/", "href=\"http: + host + "/skin/"); result = result.replaceAll("href=\\\"(\\.\\./)*/?view/", "href=\"http: + host + "/view/"); result = result.replaceAll("href=\\\"(\\.\\./)*/?edit/", "href=\"http: + host + "/edit/"); return result; } @Override public String getJSONContent(DocumentReference docRef) { try { return getJSONContent(getContext().getWiki().getDocument(docRef, getContext())); } catch (XWikiException exp) { _LOGGER.error("Failed to get document [" + docRef + "] for JSON.", exp); } return "{}"; } @Override public String getJSONContent(XWikiDocument cdoc) { Map<String, String> data; try { data = xwikiDoctoLinkedMap(cdoc.getTranslatedDocument(getContext()), false, true, false, false); } catch (XWikiException e) { _LOGGER.error("getJSONContent failed.", e); data = Collections.emptyMap(); } Builder jasonBuilder = new Builder(); jasonBuilder.openDictionary(); for (String key : data.keySet()) { String value = data.get(key); jasonBuilder.addStringProperty(key, value); } jasonBuilder.closeDictionary(); return jasonBuilder.getJSON(); } @Override public String getUserNameForDocRef(DocumentReference authDocRef) throws XWikiException { XWikiDocument authDoc = getContext().getWiki().getDocument(authDocRef, getContext()); BaseObject authObj = authDoc.getXObject(getRef("XWiki","XWikiUsers")); if(authObj!=null){ return authObj.getStringValue("last_name") + ", " + authObj.getStringValue("first_name"); } else{ return getAdminMessageTool().get("cel_ml_unknown_author"); } } @Override public String getMajorVersion(XWikiDocument doc) { String revision = "1"; if(doc!=null){ revision = doc.getVersion(); if((revision!=null) && (revision.trim().length()>0) && revision.contains(".")){ revision = revision.split("\\.")[0]; } } return revision; } private DocumentReference getRef(String spaceName, String pageName){ return new DocumentReference(getContext().getDatabase(), spaceName, pageName); } @Override public List<BaseObject> getObjectsOrdered(XWikiDocument doc, DocumentReference classRef, String orderField, boolean asc) { return getObjectsOrdered(doc, classRef, orderField, asc, null, false); } /** * Get a list of Objects for a Document sorted by one or two fields. * * @param doc The Document where the Objects are attached. * @param classRef The reference to the class of the Objects to return * @param orderField1 Field to order the objects by. First priority. * @param asc1 Order first priority ascending or descending. * @param orderField2 Field to order the objects by. Second priority. * @param asc2 Order second priority ascending or descending. * @return List of objects ordered as specified */ @Override public List<BaseObject> getObjectsOrdered(XWikiDocument doc, DocumentReference classRef, String orderField1, boolean asc1, String orderField2, boolean asc2) { List<BaseObject> resultList = new ArrayList<BaseObject>(); if(doc != null) { List<BaseObject> allObjects = doc.getXObjects(classRef); if(allObjects != null) { for (BaseObject obj : allObjects) { if(obj != null) { resultList.add(obj); } } } Collections.sort(resultList, new BaseObjectComparator(orderField1, asc1, orderField2, asc2)); } return resultList; } @Override public String[] splitStringByLength(String inStr, int maxLength) { int numFullStr = (inStr.length() - 1) / maxLength; String[] splitedStr = new String[1 + numFullStr]; for(int i = 0 ; i < numFullStr ; i ++) { int startIndex = i * maxLength; splitedStr[i] = inStr.substring(startIndex, startIndex + maxLength); } int lastPiece = splitedStr.length - 1; splitedStr[lastPiece] = inStr.substring(lastPiece * maxLength, inStr.length()); return splitedStr; } @Override public WikiReference getWikiRef() { return getWikiRef((EntityReference) null); } @Override public WikiReference getWikiRef(XWikiDocument doc) { EntityReference ref = ((doc != null) ? doc.getDocumentReference() : null); return getWikiRef(ref); } @Override public WikiReference getWikiRef(DocumentReference ref) { return getWikiRef((EntityReference) ref); } @Override public WikiReference getWikiRef(EntityReference ref) { WikiReference ret = null; if (ref != null) { ret = new WikiReference(ref.extractReference(EntityType.WIKI)); } else { ret = new WikiReference(getContext().getDatabase()); } return ret; } @Override public DocumentReference getWikiTemplateDocRef() { if (getContext().getRequest() != null) { String templateFN = getContext().getRequest().get("template"); if ((templateFN != null) && !"".equals(templateFN.trim())) { DocumentReference templateDocRef = resolveDocumentReference(templateFN); if (getContext().getWiki().exists(templateDocRef, getContext())) { return templateDocRef; } } } return null; } @Override public XWikiDocument getWikiTemplateDoc() { DocumentReference templateDocRef = getWikiTemplateDocRef(); if (templateDocRef != null) { try { return getContext().getWiki().getDocument(templateDocRef, getContext()); } catch (XWikiException exp) { _LOGGER.error("Exception while getting template doc '" + templateDocRef + "'", exp); } } return null; } @Override public EntityReferenceSerializer<String> getRefDefaultSerializer() { return serializer_default; } @Override public EntityReferenceSerializer<String> getRefLocalSerializer() { return serializer_local; } @Override public String serializeRef(EntityReference entityRef) { return getRefDefaultSerializer().serialize(entityRef); } @Override public String serializeRef(EntityReference entityRef, boolean local) { if (local) { return getRefLocalSerializer().serialize(entityRef); } else { return getRefDefaultSerializer().serialize(entityRef); } } @Override public Map<String, String[]> getRequestParameterMap() { XWikiRequest request = getContext().getRequest(); if (request != null) { Map<?, ?> requestMap = request.getParameterMap(); Map<String, String[]> convertedMap = new HashMap<String, String[]>(); for (Object keyObj : requestMap.keySet()) { String key = keyObj.toString(); String[] value = getValueAsStringArray(requestMap.get(keyObj)); convertedMap.put(key, value); } return convertedMap; } else { return null; } } private String[] getValueAsStringArray(Object value) { if (value instanceof String) { return new String[] { value.toString() }; } else if (value instanceof String[]) { return (String[]) value; } else { throw new IllegalArgumentException("Invalid requestMap value type"); } } @Override public String getInheritedTemplatedPath(DocumentReference localTemplateRef) { if (localTemplateRef != null) { String templatePath = getRefDefaultSerializer().serialize(localTemplateRef); if (!getContext().getWiki().exists(localTemplateRef, getContext())) { if (!"celements2web".equals(localTemplateRef.getLastSpaceReference().getParent( ).getName()) && getContext().getWiki().exists(getCentralTemplateRef(localTemplateRef), getContext())) { templatePath = "celements2web:" + templatePath; } else { templatePath = ":" + templatePath.replaceAll("celements2web:", ""); } } return templatePath.replaceAll(getContext().getDatabase() + ":", ""); } return null; } private DocumentReference getCentralTemplateRef(DocumentReference localTemplateRef) { DocumentReference centralTemplateRef = new DocumentReference("celements2web", localTemplateRef.getLastSpaceReference().getName(), localTemplateRef.getName()); return centralTemplateRef; } @Override public void deleteDocument(XWikiDocument doc, boolean totrash) throws XWikiException { /** deleteDocument in XWiki does NOT set context and store database to doc database * Thus deleting the doc fails if it is not in the current context database. Hence we * need to fix the context database before deleting. */ String dbBefore = getContext().getDatabase(); try { getContext().setDatabase(doc.getDocumentReference().getLastSpaceReference().getParent( ).getName()); _LOGGER.debug("deleteDocument: doc [" + getRefDefaultSerializer().serialize( doc.getDocumentReference()) + "," + doc.getLanguage() + "] totrash [" + totrash + "] dbBefore [" + dbBefore + "] db now [" + getContext().getDatabase() + "]."); getContext().getWiki().deleteDocument(doc, totrash, getContext()); } finally { getContext().setDatabase(dbBefore); } } @Override public void deleteAllDocuments(XWikiDocument doc, boolean totrash ) throws XWikiException { // Delete all documents for (String lang : doc.getTranslationList(getContext())) { XWikiDocument tdoc = doc.getTranslatedDocument(lang, getContext()); deleteDocument(tdoc, totrash); } deleteDocument(doc, totrash); } @Override public String getTemplatePathOnDisk(String renderTemplatePath) { return getTemplatePathOnDisk(renderTemplatePath, null); } @Override public String getTemplatePathOnDisk(String renderTemplatePath, String lang) { for (Map.Entry<Object, Object> entry : tempPathConfig.getMappings().entrySet()) { String pathName = (String) entry.getKey(); if (renderTemplatePath.startsWith(":" + pathName)) { String newRenderTemplatePath = renderTemplatePath.replaceAll("^:(" + pathName + "\\.)?", "/templates/" + ((String) entry.getValue()) + "/") + getTemplatePathLangSuffix(lang) + ".vm"; _LOGGER.debug("getTemplatePathOnDisk: for [" + renderTemplatePath + "] and lang [" + lang + "] returning [" + newRenderTemplatePath + "]."); return newRenderTemplatePath; } } return renderTemplatePath; } private String getTemplatePathLangSuffix(String lang) { if (lang != null) { return "_" + lang; } return ""; } @Override public String renderInheritableDocument(DocumentReference docRef, String lang ) throws XWikiException { return renderInheritableDocument(docRef, lang, null); } @Override public String renderInheritableDocument(DocumentReference docRef, String lang, String defLang) throws XWikiException { RenderCommand renderCommand = new RenderCommand(); if (this.injectedRenderingEngine != null) { renderCommand.setRenderingEngine(this.injectedRenderingEngine); } String templatePath = getInheritedTemplatedPath(docRef); _LOGGER.debug("renderInheritableDocument: call renderTemplatePath for [" + templatePath + "] and lang [" + lang + "] and defLang [" + defLang + "]."); return renderCommand.renderTemplatePath(templatePath, lang, defLang); } @Override public boolean existsInheritableDocument(DocumentReference docRef, String lang) { return existsInheritableDocument(docRef, lang, null); } @Override public boolean existsInheritableDocument(DocumentReference docRef, String lang, String defLang) { String templatePath = getInheritedTemplatedPath(docRef); _LOGGER.debug("existsInheritableDocument: check content for templatePath [" + templatePath + "] and lang [" + lang + "] and defLang [" + defLang + "]."); if (templatePath.startsWith(":")) { return !StringUtils.isEmpty(getTranslatedDiscTemplateContent(templatePath, lang, defLang)); } else { //Template must exist otherwise getInheritedTemplatedPath would have fallen back //on disk template path. return true; } } private PageLayoutCommand getPageLayoutCmd() { if (!getContext().containsKey(LayoutScriptService.CELEMENTS_PAGE_LAYOUT_COMMAND)) { getContext().put(LayoutScriptService.CELEMENTS_PAGE_LAYOUT_COMMAND, new PageLayoutCommand()); } return (PageLayoutCommand) getContext().get( LayoutScriptService.CELEMENTS_PAGE_LAYOUT_COMMAND); } @Deprecated @Override public String cleanupXHTMLtoHTML5(String xhtml) { return cleanupXHTMLtoHTML5(xhtml, getContext().getDoc().getDocumentReference()); } @Deprecated @Override public String cleanupXHTMLtoHTML5(String xhtml, DocumentReference docRef) { return cleanupXHTMLtoHTML5(xhtml, getPageLayoutCmd().getPageLayoutForDoc(docRef)); } @Deprecated @Override public String cleanupXHTMLtoHTML5(String xhtml, SpaceReference layoutRef) { BaseObject layoutObj = getPageLayoutCmd().getLayoutPropertyObj(layoutRef); if((layoutObj != null) && "HTML 5".equals(layoutObj.getStringValue("doctype"))) { XHTMLtoHTML5cleanup html5Cleaner = Utils.getComponent(XHTMLtoHTML5cleanup.class); return html5Cleaner.cleanAll(xhtml); } return xhtml; } @Override public List<Attachment> getAttachmentsForDocs(List<String> docsFN) { List<Attachment> attachments = new ArrayList<Attachment>(); for(String docFN : docsFN) { try { _LOGGER.info("getAttachmentsForDocs: processing doc " + docFN); for(XWikiAttachment xwikiAttachment : getContext().getWiki().getDocument( resolveDocumentReference(docFN), getContext()).getAttachmentList()) { _LOGGER.info("getAttachmentsForDocs: adding attachment " + xwikiAttachment.getFilename() + " to list."); attachments.add(new Attachment(getContext().getWiki().getDocument( resolveDocumentReference(docFN), getContext()).newDocument(getContext()), xwikiAttachment, getContext())); } } catch (XWikiException exp) { _LOGGER.error("", exp); } } return attachments; } @Override public String getTranslatedDiscTemplateContent(String renderTemplatePath, String lang, String defLang) { String templateContent; List<String> langList = new ArrayList<String>(); if (lang != null) { langList.add(lang); } if ((defLang != null) && !defLang.equals(lang)) { langList.add(defLang); } templateContent = ""; for(String theLang : langList) { String templatePath = getTemplatePathOnDisk(renderTemplatePath, theLang); try { templateContent = getContext().getWiki().getResourceContent(templatePath); } catch (FileNotFoundException fnfExp) { _LOGGER.trace("FileNotFound [" + templatePath + "]."); templateContent = ""; } catch (IOException exp) { _LOGGER.debug("Exception while parsing template [" + templatePath + "].", exp); templateContent = ""; } } if ("".equals(templateContent)) { String templatePathDef = getTemplatePathOnDisk(renderTemplatePath); try { templateContent = getContext().getWiki().getResourceContent(templatePathDef); } catch (FileNotFoundException fnfExp) { _LOGGER.trace("FileNotFound [" + templatePathDef + "]."); return ""; } catch (IOException exp) { _LOGGER.debug("Exception while parsing template [" + templatePathDef + "].", exp); return ""; } } return templateContent; } private IPageTypeResolverRole getPageTypeResolver() { return Utils.getComponent(IPageTypeResolverRole.class); } @Override public void sendCheckJobMail(String jobMailName, String fromAddr, String toAddr, List<String> params) { _LOGGER.info("sendCheckJobMail started for jobMailName [" + jobMailName + "] fromAdr [" + fromAddr + "], toAddr [" + toAddr + "]."); DocumentReference emailTemplateDocRef = new DocumentReference(getContext().getDatabase(), "Mails", jobMailName); String lang = "de"; //TODO add multilingual email addresslist try { String htmlContent = renderInheritableDocument(emailTemplateDocRef, lang); if (!emptyChecker.isEmptyRTEString(htmlContent)) { CelSendMail sender = new CelSendMail(); sender.setFrom(fromAddr); sender.setReplyTo(fromAddr); sender.setTo(toAddr); sender.setSubject(getMessageTool(lang).get("job_mail_subject_" + jobMailName, params)); sender.setHtmlContent(htmlContent, false); String textContent = new PlainTextCommand().convertToPlainText(htmlContent); sender.setTextContent(textContent); int successfulSend = sender.sendMail(); _LOGGER.debug("sendCheckJobMail ended for [" + toAddr + "] email send [" + successfulSend + "]."); } else { _LOGGER.warn("No Email content found for [" + jobMailName + "] [" + emailTemplateDocRef + "]."); } } catch (XWikiException exp) { _LOGGER.error("Failed to render email template document [" + emailTemplateDocRef + "].", exp); } } @Override public WikiReference getCentralWikiRef() { return CENTRAL_WIKI_REF; } @Override public EntityType resolveEntityTypeForFullName(String fullName) { return resolveEntityTypeForFullName(fullName, null); } @Override public EntityType resolveEntityTypeForFullName(String fullName, EntityType defaultNameType) { EntityType ret = null; if (StringUtils.isNotBlank(fullName)) { if (fullName.matches(REGEX_WORD)) { ret = defaultNameType != null ? defaultNameType : EntityType.WIKI; } else if (fullName.matches(REGEX_SPACE)) { ret = EntityType.SPACE; } else if (fullName.matches(REGEX_DOC)) { ret = EntityType.DOCUMENT; } else if (fullName.matches(REGEX_ATT)) { ret = EntityType.ATTACHMENT; } } _LOGGER.debug("resolveEntityTypeForFullName: got '" + ret + "' for fullName '" + fullName + "' and default '" + defaultNameType + "'"); return ret; } @Override public <T> T lookup(Class<T> role) throws ComponentLookupException { return componentManager.lookup(role); } @Override public <T> T lookup(Class<T> role, String roleHint) throws ComponentLookupException { return componentManager.lookup(role, roleHint); } @Override public <T> List<T> lookupList(Class<T> role) throws ComponentLookupException { return componentManager.lookupList(role); } @Override public <T> Map<String, T> lookupMap(Class<T> role) throws ComponentLookupException { return componentManager.lookupMap(role); } private IDocumentParentsListerRole getDocumentParentsLister() { if (docParentsLister == null) { docParentsLister = Utils.getComponent(IDocumentParentsListerRole.class); } return docParentsLister; } }
package <%= package.lower %>.<%= project.lower %>.dao; import java.util.logging.Logger; import static java.util.logging.Logger.getLogger; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import java.util.List; import <%= package.lower %>.<%= project.lower %>.entity.Fingerprint; import org.demoiselle.jee.crud.AbstractDAO; /** * * @author gladson */ public class FingerprintDAO extends AbstractDAO< Fingerprint, Long> { private static final Logger LOG = getLogger(FingerprintDAO.class.getName()); @PersistenceContext(unitName = "<%= project.lower %>PU") protected EntityManager em; /** * * @return */ @Override protected EntityManager getEntityManager() { return em; } /** * * @param id * @return */ public List<Fingerprint> findByUsuario(Long id) { return em.createQuery("SELECT f FROM Fingerprint f WHERE f.usuarioId = :id").setParameter("id", id).getResultList(); } /** * * @param cod * @return */ public List<Fingerprint> findByCodigo(String cod) { return em.createQuery("SELECT f FROM Fingerprint f WHERE f.codigo = :codigo").setParameter("codigo", cod).getResultList(); } }
package com.conveyal.r5.analyst.scenario; import com.conveyal.r5.transit.TransitLayer; import com.conveyal.r5.transit.TransportNetwork; import java.io.Serializable; import java.util.Set; /** * This represents either an existing or a new stop in Modifications when creating or inserting stops into routes. * If the id already exists, the existing stop is used. If not, a new stop is created. */ public class StopSpec implements Serializable { public static final long serialVersionUID = 1L; /** create a stop spec for a particular stop ID */ public StopSpec (String id) { this.id = id; } /** Create a stop spec at a particular location */ public StopSpec (double lon, double lat) { this.lat = lat; this.lon = lon; } /** default constructor for deserialization */ public StopSpec () { /* do nothing */ } public String id; public String name; public double lat; public double lon; /** * Given a specification for a transit stop, which can be a reference to an existing stop or the location and * name of a new stop, find or create the stop in the given network. This should in fact be a protective scenario * copy of the network to avoid trashing the original baseline network. * TODO maybe make protective copies a subclass of Networks to enforce this typing. * * @param network the transit network in which to find or create the specified transit stops. * @return the integer index of the new stop within the given network, or -1 if it could not be created. */ public int resolve (TransportNetwork network, Set<String> warnings) { if (id == null) { // No stop ID supplied, this is a new stop rather than a reference to an existing one. if (lat == 0 || lon == 0) { warnings.add("When no stop ID is supplied, nonzero coordinates must be supplied."); } int newStopId = materializeOne(network); return newStopId; } else { // Stop ID supplied, this is a reference to an existing stop rather than a new stop. if (lat != 0 || lon != 0 || name != null) { warnings.add("A reference to an existing id should not include coordinates or a name."); } int intStopId = network.transitLayer.indexForStopId.get(id); if (intStopId == -1) { warnings.add("Could not find existing stop with GTFS ID " + id); } return intStopId; } } /** * This follows the model of com.conveyal.r5.streets.StreetLayer.associateStops() * We reuse the method that is employed when the graph is first built, because we actually want to create * a new unique street vertex exactly at the supplied coordinate (which represents the stop itself) then * make edges that connect that stop to a splitter vertex on the street (which is potentially shared/reused). * @return the integer ID of the newly created stop */ private int materializeOne (TransportNetwork network) { int stopVertex = network.streetLayer.createAndLinkVertex(lat, lon); TransitLayer transitLayer = network.transitLayer; int newStopId = transitLayer.getStopCount(); transitLayer.stopIdForIndex.add(this.id); // indexForStopId will be derived from this transitLayer.stopNames.add(this.name); transitLayer.streetVertexForStop.add(stopVertex); // stopForStreetVertex will be derived from this return newStopId; } }
package com.ctry.clearcomposer.history; import com.ctry.clearcomposer.sequencer.GraphicNote; import java.util.List; public class NotesEntry extends AbstractEntry { private List<GraphicNote> notes; private boolean isPerma; /** * new notes entry instance * * @param notes all CHANGED notes * @param isPerma when changing notes, was isPerma on or off? */ public NotesEntry(List<GraphicNote> notes, boolean isPerma) { this.notes = notes; this.isPerma = isPerma; } /** * Tooltip when undo / redo button has mouse cursor on top * * @return tooltip (will be formatted as "undo tooltip" or "redo tooltip") */ @Override public String toString() { return "enter in notes"; } /** * Method called when undo button clicked * toggles all notes */ @Override public void undo() { toggle(); } /** * Method called when redo button clicked */ @Override public void redo() { toggle(); } private void toggle() { for (GraphicNote note : notes) { note.toggle(isPerma); } } }
package com.devexed.dbsource.jdbc; import com.devexed.dbsource.AbstractCloseable; import com.devexed.dbsource.Cursor; import com.devexed.dbsource.DatabaseException; import java.sql.ResultSet; import java.sql.SQLException; /** * A cursor over a JDBC result set. */ final class ResultSetCursor extends AbstractCloseable implements Cursor { /** Interface providing method of getting the accessor of a column with a specific name. */ public interface AccessorFunction { JdbcAccessor accessorOf(String column); } private final AccessorFunction typeOfFunction; private final ResultSet resultSet; ResultSetCursor(AccessorFunction typeOfFunction, ResultSet resultSet) { this.typeOfFunction = typeOfFunction; this.resultSet = resultSet; } @Override public boolean seek(int rows) { checkNotClosed(); try { if (resultSet.relative(rows)) { close(); return true; } } catch (SQLException e) { throw new DatabaseException(e); } return false; } @Override public boolean previous() { checkNotClosed(); try { if (resultSet.previous()) { close(); return true; } } catch (SQLException e) { throw new DatabaseException(e); } return false; } @Override public boolean next() { checkNotClosed(); try { if (resultSet.next()) return true; } catch (SQLException e) { throw new DatabaseException(e); } close(); return false; } @Override @SuppressWarnings("unchecked") public <T> T get(String column) { checkNotClosed(); try { // Should we cache the indexes or rely on the JDBC implementation to be swift enough? int index = resultSet.findColumn(column); JdbcAccessor accessor = typeOfFunction.accessorOf(column); if (accessor == null) throw new DatabaseException("No accessor is defined for column " + column); return (T) accessor.get(resultSet, index); } catch (SQLException e) { throw new DatabaseException(e); } } @Override protected boolean isClosed() { // Override to report correct status if this result set was closed by, for example, its parent JDBC statement. try { return resultSet.isClosed() || super.isClosed(); } catch (SQLException e) { throw new DatabaseException(e); } } }
/** * Created at Jul 20, 2010, 4:39:49 AM */ package com.dmurph.tracking; import java.util.Random; public class GoogleAnalyticsV4_7_2 implements IGoogleAnalyticsURLBuilder{ public static final String URL_PREFIX = "http: private AnalyticsConfigData config; private Random random = new Random((long)(Math.random()*Long.MAX_VALUE)); private int cookie1; private int cookie2; public GoogleAnalyticsV4_7_2(AnalyticsConfigData argConfig){ config = argConfig; resetSession(); } /** * @see com.dmurph.tracking.IGoogleAnalyticsURLBuilder#getGoogleAnalyticsVersion() */ public String getGoogleAnalyticsVersion() { return "4.7.2"; } /** * @see com.dmurph.tracking.IGoogleAnalyticsURLBuilder#buildURL(com.dmurph.tracking.AnalyticsRequestData) */ public String buildURL(AnalyticsRequestData argData) { StringBuilder sb = new StringBuilder(); sb.append(URL_PREFIX); long now = System.currentTimeMillis(); sb.append("?utmwv="+getGoogleAnalyticsVersion()); // version sb.append("&utmn=" + random.nextInt()); // random int so no caching if(argData.getHostName() != null){ sb.append("&utmhn=" + getURIString(argData.getHostName())); // hostname } if(argData.getEventAction() != null && argData.getEventCategory() != null){ sb.append("&utmt=event"); String category = getURIString(argData.getEventCategory()); String action = getURIString(argData.getEventAction()); sb.append("&utme=5("+category+"*"+action); if(argData.getEventLabel() != null){ sb.append("*"+getURIString(argData.getEventLabel())); } sb.append(")"); if(argData.getEventValue() != null){ sb.append("("+argData.getEventValue()+")"); } }else if(argData.getEventAction() != null || argData.getEventCategory() != null){ throw new IllegalArgumentException("Event tracking must have both a category and an action"); } if(config.getEncoding() != null){ sb.append("&utmcs="+ getURIString(config.getEncoding())); // encoding }else{ sb.append("&utmcs=-"); } if(config.getScreenResolution() != null){ sb.append("&utmsr=" + getURIString(config.getScreenResolution())); // screen resolution } if(config.getColorDepth() != null){ sb.append("&utmsc=" + getURIString(config.getColorDepth())); // color depth } if(config.getUserLanguage() != null){ sb.append("&utmul="+ getURIString(config.getUserLanguage())); // language } sb.append("&utmje=1"); // java enabled (probably) if(config.getFlashVersion() != null){ sb.append("&utmfl="+getURIString(config.getFlashVersion())); // flash version } if(argData.getPageTitle() != null){ sb.append("&utmdt=" + getURIString(argData.getPageTitle())); // page title } sb.append("&utmhid="+random.nextInt()); if(argData.getPageURL() != null){ sb.append("&utmp=" + getURIString(argData.getPageURL())); // page url } sb.append("&utmac=" + config.getTrackingCode()); // tracking code // cookie data // utmccn=(organic)|utmcsr=google|utmctr=snotwuh |utmcmd=organic String utmcsr = getURIString(argData.getUtmcsr()); String utmccn = getURIString(argData.getUtmccn()); String utmctr = getURIString(argData.getUtmctr()); String utmcmd = getURIString(argData.getUtmcmd()); String utmcct = getURIString(argData.getUtmcct()); // yes, this did take a while to figure out sb.append("&utmcc=__utma%3D"+cookie1+"."+cookie2+"."+now+"."+now+"."+now+"."+"13%3B%2B__utmz%3D"+cookie1+"."+now+".1.1.utmcsr%3D"+utmcsr+"%7Cutmccn%3D"+utmccn+"%7Cutmcmd%3D"+utmcmd+(utmctr != null?"%7Cutmctr%3D"+utmctr:"")+(utmcct != null?"%7Cutmcct%3D"+utmcct:"")+"%3B&gaq=1"); return sb.toString(); } // tracking url: private String getURIString(String argString){ if(argString == null){ return null; } return URIEncoder.encodeURI(argString); } /** * @see com.dmurph.tracking.IGoogleAnalyticsURLBuilder#resetSession() */ public void resetSession() { cookie1 = random.nextInt(); cookie2 = random.nextInt(); } }
package com.doctor.common.util; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.Map.Entry; import java.util.Properties; import java.util.concurrent.TimeUnit; import org.apache.commons.io.IOUtils; import clojure.main; import backtype.storm.Config; import backtype.storm.LocalCluster; import backtype.storm.StormSubmitter; import backtype.storm.generated.AlreadyAliveException; import backtype.storm.generated.InvalidTopologyException; import backtype.storm.generated.StormTopology; public final class StormSubmitterUtil { private static final String topologyDefaultConfig = "jstorm-config/conf.prop"; /** * jarjstorm-config/conf.prop * * @param topology * @throws IOException * @throws InvalidTopologyException * @throws AlreadyAliveException * @throws InterruptedException */ public static void submitTopology(final StormTopology topology) throws IOException, InterruptedException, AlreadyAliveException, InvalidTopologyException{ InputStream inputStream = StormSubmitterUtil.class.getClassLoader().getResourceAsStream(topologyDefaultConfig); Config config = LoadConfigFromInputStream(inputStream); submitTopology(topology, config); } /** * Topology Config * * @param topology * @param propFile * @throws InterruptedException * @throws AlreadyAliveException * @throws InvalidTopologyException */ public static void submitTopology(final StormTopology topology, final String propFile) throws InterruptedException, AlreadyAliveException, InvalidTopologyException { Config config = LoadConfigFromPropertyFile(propFile); String topologyName = (String) config.get(Config.TOPOLOGY_NAME); if (isLocalCluster(config)) { submitTopologyLocally(topology, topologyName, config, 20); } else { submitTopologyRemotely(topology, topologyName, config); } } public static void submitTopology(final StormTopology topology, final Config config) throws InterruptedException, AlreadyAliveException, InvalidTopologyException { String topologyName = (String) config.get(Config.TOPOLOGY_NAME); if (isLocalCluster(config)) { submitTopologyLocally(topology, topologyName, config, 20); } else { submitTopologyRemotely(topology, topologyName, config); } } public static void submitTopologyLocally(final StormTopology topology, final String topologyName, final Config conf, final int runtimeInMinutes) throws InterruptedException { LocalCluster localCluster = new LocalCluster(); localCluster.submitTopology(topologyName, conf, topology); TimeUnit.MINUTES.sleep(runtimeInMinutes); localCluster.killTopology(topologyName); localCluster.shutdown(); } public static void submitTopologyRemotely(final StormTopology topology, final String topologyName, final Config conf) throws AlreadyAliveException, InvalidTopologyException { StormSubmitter.submitTopology(topologyName, conf, topology); } /** * jstorm * * @param propFile * @return */ public static Config LoadConfigFromPropertyFile(final String propFile) { try (FileInputStream inputStream = new FileInputStream(propFile)) { return LoadConfigFromInputStream(inputStream); } catch (IOException e) { throw new RuntimeException("load file error:" + propFile, e); } } private static Config LoadConfigFromInputStream(final InputStream inputStream) throws IOException{ Properties properties = new Properties(); properties.load(inputStream); Config config = new Config(); for (Entry<Object, Object> entry : properties.entrySet()) { config.put(entry.getKey().toString(), entry.getValue()); } return config; } public static boolean isLocalCluster(final Config config) { String mode = (String) config.get(Config.STORM_CLUSTER_MODE); if ("local".equals(mode)) { return true; } return false; } }
package com.elmakers.mine.bukkit.blocks; import org.bukkit.block.Block; import com.elmakers.mine.bukkit.utilities.Messages; import com.elmakers.mine.bukkit.utilities.borrowed.ConfigurationNode; public class Automaton extends BlockData { private String message; private String name; private long createdAt; public Automaton(ConfigurationNode node) { super(node); name = node.getString("name"); message = node.getString("message"); createdAt = node.getLong("created", 0); } public Automaton(Block block, String name, String message) { super(block); this.name = name; this.message = message; this.createdAt = System.currentTimeMillis(); } @Override public void save(ConfigurationNode node) { super.save(node); node.setProperty("name", name); node.setProperty("message", message); node.setProperty("created", createdAt); } public String getMessage() { if (message == null || message.length() == 0 || name == null || name.length() == 0) return ""; String contents = Messages.get(message); if (contents == null || contents.length() == 0) return ""; return contents.replace("$name", name); } public String getName() { return name; } public long getCreatedTime() { return createdAt; } }
package com.faforever.client.game; import com.faforever.client.fa.ForgedAllianceService; import com.faforever.client.legacy.LobbyServerAccessor; import com.faforever.client.legacy.OnGameInfoListener; import com.faforever.client.legacy.OnGameTypeInfoListener; import com.faforever.client.legacy.domain.GameInfo; import com.faforever.client.legacy.domain.GameLaunchInfo; import com.faforever.client.legacy.domain.GameState; import com.faforever.client.legacy.domain.GameTypeInfo; import com.faforever.client.legacy.proxy.Proxy; import com.faforever.client.map.MapService; import com.faforever.client.user.UserService; import com.faforever.client.util.Callback; import com.faforever.client.util.ConcurrentUtil; import javafx.application.Platform; import javafx.collections.FXCollections; import javafx.collections.ListChangeListener; import javafx.collections.MapChangeListener; import javafx.collections.ObservableList; import javafx.collections.ObservableMap; import javafx.concurrent.Service; import javafx.concurrent.Task; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import javax.annotation.PostConstruct; import java.io.IOException; import java.lang.invoke.MethodHandles; import java.net.URL; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; public class GameServiceImpl implements GameService, OnGameTypeInfoListener, OnGameInfoListener { private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); @Autowired LobbyServerAccessor lobbyServerAccessor; @Autowired UserService userService; @Autowired ForgedAllianceService forgedAllianceService; @Autowired MapService mapService; @Autowired Proxy proxy; private Collection<OnGameStartedListener> onGameLaunchingListeners; private final ObservableMap<String, GameTypeBean> gameTypeBeans; // It is indeed ugly to keep references in both, a list and a map, however I don't see how I can populate the map // values as an observable list (in order to display it in the games table) private final ObservableList<GameInfoBean> gameInfoBeans; private final Map<Integer, GameInfoBean> uidToGameInfoBean; public GameServiceImpl() { gameTypeBeans = FXCollections.observableHashMap(); onGameLaunchingListeners = new HashSet<>(); gameInfoBeans = FXCollections.observableArrayList(); uidToGameInfoBean = new HashMap<>(); } @Override public void addOnGameInfoBeanListener(ListChangeListener<GameInfoBean> listener) { gameInfoBeans.addListener(listener); } @PostConstruct void postConstruct() { lobbyServerAccessor.addOnGameTypeInfoListener(this); lobbyServerAccessor.addOnGameInfoListener(this); } @Override public void publishPotentialPlayer() { String username = userService.getUsername(); // FIXME implement // serverAccessor.publishPotentialPlayer(username); } @Override public void hostGame(NewGameInfo newGameInfo, Callback<Void> callback) { cancelLadderSearch(); updateGameIfNecessary(newGameInfo.mod, new Callback<Void>() { @Override public void success(Void result) { lobbyServerAccessor.requestNewGame(newGameInfo, gameLaunchCallback(callback)); } @Override public void error(Throwable e) { callback.error(e); } }); } private void updateGameIfNecessary(String modName, Callback<Void> callback) { callback.success(null); } @Override public void cancelLadderSearch() { logger.warn("Cancelling ladder search has not yet been implemented"); } @Override public void joinGame(GameInfoBean gameInfoBean, String password, Callback<Void> callback) { logger.info("Joining game {} ({})", gameInfoBean.getTitle(), gameInfoBean.getUid()); cancelLadderSearch(); Callback<Void> mapDownloadCallback = new Callback<Void>() { @Override public void success(Void result) { lobbyServerAccessor.requestJoinGame(gameInfoBean, password, gameLaunchCallback(callback)); } @Override public void error(Throwable e) { callback.error(e); } }; updateGameIfNecessary(gameInfoBean.getFeaturedMod(), new Callback<Void>() { @Override public void success(Void result) { downloadMapIfNecessary(gameInfoBean.getMapName(), mapDownloadCallback); } @Override public void error(Throwable e) { callback.error(e); } }); } private void downloadMapIfNecessary(String mapName, Callback<Void> callback) { if (mapService.isAvailable(mapName)) { callback.success(null); return; } mapService.download(mapName, callback); } @Override public List<GameTypeBean> getGameTypes() { return new ArrayList<>(gameTypeBeans.values()); } @Override public void addOnGameTypeInfoListener(MapChangeListener<String, GameTypeBean> changeListener) { gameTypeBeans.addListener(changeListener); } private Callback<GameLaunchInfo> gameLaunchCallback(final Callback<Void> callback) { return new Callback<GameLaunchInfo>() { @Override public void success(GameLaunchInfo gameLaunchInfo) { List<String> args = fixMalformedArgs(gameLaunchInfo.args); try { Process process = forgedAllianceService.startGame(gameLaunchInfo.uid, gameLaunchInfo.mod, args); onGameLaunchingListeners.forEach(onGameStartedListener -> onGameStartedListener.onGameStarted(gameLaunchInfo.uid)); lobbyServerAccessor.notifyGameStarted(); waitForProcessTerminationInBackground(process); callback.success(null); } catch (Exception e) { callback.error(e); } } @Override public void error(Throwable e) { // FIXME implement logger.warn("Could not create game", e); } }; } Service<Void> waitForProcessTerminationInBackground(Process process) { return ConcurrentUtil.executeInBackground(new Task<Void>() { @Override protected Void call() throws Exception { int exitCode = process.waitFor(); logger.info("Forged Alliance terminated with exit code {}", exitCode); proxy.close(); lobbyServerAccessor.notifyGameTerminated(); return null; } }); } /** * A correct argument list looks like ["/ratingcolor", "d8d8d8d8", "/numgames", "236"]. However, the FAF server sends * it as ["/ratingcolor d8d8d8d8", "/numgames 236"]. This method fixes this. */ private List<String> fixMalformedArgs(List<String> gameLaunchMessage) { ArrayList<String> fixedArgs = new ArrayList<>(); for (String combinedArg : gameLaunchMessage) { String[] split = combinedArg.split(" "); Collections.addAll(fixedArgs, split); } return fixedArgs; } @Override public void onGameTypeInfo(GameTypeInfo gameTypeInfo) { if (!gameTypeInfo.host || !gameTypeInfo.live || gameTypeBeans.containsKey(gameTypeInfo.name)) { return; } gameTypeBeans.put(gameTypeInfo.name, new GameTypeBean(gameTypeInfo)); } @Override public void addOnGameStartedListener(OnGameStartedListener listener) { onGameLaunchingListeners.add(listener); } @Override public void runWithReplay(Path path, @Nullable Integer replayId) throws IOException { forgedAllianceService.startReplay(path, replayId); } @Override public void runWithReplay(URL replayUrl, Integer replayId) throws IOException { forgedAllianceService.startReplay(replayUrl, replayId); } @Override public ObservableList<GameInfoBean> getGameInfoBeans() { return FXCollections.unmodifiableObservableList(gameInfoBeans); } @Override public void onGameInfo(GameInfo gameInfo) { Platform.runLater(() -> { GameInfoBean gameInfoBean = new GameInfoBean(gameInfo); if (!GameState.OPEN.equals(gameInfo.state)) { gameInfoBeans.remove(gameInfoBean); return; } if (!uidToGameInfoBean.containsKey(gameInfo.uid)) { gameInfoBeans.add(gameInfoBean); uidToGameInfoBean.put(gameInfo.uid, gameInfoBean); } else { uidToGameInfoBean.get(gameInfo.uid).updateFromGameInfo(gameInfo); } }); } }
package com.github.hi_fi.dblibrary.keywords; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.robotframework.javalib.annotation.ArgumentNames; import org.robotframework.javalib.annotation.RobotKeyword; import org.robotframework.javalib.annotation.RobotKeywords; @RobotKeywords public class Query { @RobotKeyword("Deletes the entire content of the given database table. This keyword is" + "useful to start tests in a clean state. Use this keyword with care as" + "accidently execution of this keyword in a productive system will cause" + "heavy loss of data. There will be no rollback possible.\n\n" + "Example: \n" + "| Delete All Rows From Table | MySampleTable |") @ArgumentNames({ "Table name" }) public void deleteAllRowsFromTable(String tableName) throws SQLException { String sql = "delete from " + tableName; Statement stmt = DatabaseConnection.getConnection().createStatement(); try { stmt.execute(sql); } finally { stmt.close(); } } @RobotKeyword("Executes the given SQL without any further modifications. The given SQL " + "must be valid for the database that is used. Results are returned as a list of dictionaries" + "\n\n" + "*NOTE*: Use this method with care as you might cause damage to your " + "database, especially when using this in a productive environment. " + "\n\n" + "Example: \n" + "| Execute SQL | CREATE TABLE MyTable (Num INTEGER) | ") @ArgumentNames({ "SQL String to execute" }) public List<HashMap<String, Object>> executeSql(String sqlString) throws SQLException { ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>(); Statement stmt = DatabaseConnection.getConnection().createStatement(); try { stmt.execute(sqlString); ResultSet rs = (ResultSet) stmt.getResultSet(); if (rs != null) { ResultSetMetaData rsmd = rs.getMetaData(); int numberOfColumns = rsmd.getColumnCount(); while (rs.next()) { HashMap<String, Object> row = new HashMap<String, Object>(numberOfColumns); for (int i = 1; i <= numberOfColumns; ++i) { row.put(rsmd.getColumnName(i), rs.getObject(i)); } list.add(row); } } } finally { stmt.close(); } return list; } @RobotKeyword("Executes the SQL statements contained in the given file without any " + "further modifications. The given SQL must be valid for the database that " + "is used. Any lines prefixed with \"REM\" or \"#\" are ignored. This keyword " + "can for example be used to setup database tables from some SQL install " + "script. " + "\n\n" + "Single SQL statements in the file can be spread over multiple lines, but " + "must be terminated with a semicolon \";\". A new statement must always " + "start in a new line and not in the same line where the previous statement " + "was terminated by a \";\". " + "\n\n" + "In case there is a problem in executing any of the SQL statements from " + "the file the execution is terminated and the operation is rolled back. " + "\n\n" + "*NOTE*: Use this method with care as you might cause damage to your " + "database, especially when using this in a productive environment. \n\n" + "*NOTE2*: If using keyword remotely, file need to be trasfered to server some " + "other way; this library is not doing the transfer." + "\n\n" + "Example: \n" + "| Execute SQL from File | myFile.sql | ") @ArgumentNames({ "File containing SQL commands to execute" }) public void executeSqlFromFile(String fileName) throws SQLException, IOException, DatabaseLibraryException { DatabaseConnection.getConnection().setAutoCommit(false); FileReader fr = new FileReader(new File(fileName)); BufferedReader br = new BufferedReader(fr); String sql = ""; String line = ""; while ((line = br.readLine()) != null) { line = line.trim(); // Ignore lines commented out in the given file if (line.toLowerCase().startsWith("rem")) { continue; } if (line.startsWith(" continue; } // Add the line to the current SQL statement if (sql.length() > 0) { sql += " "; } sql += line; // Check if SQL statement is complete, if yes execute try { if (sql.endsWith(";")) { sql = sql.substring(0, sql.length() - 1); System.out.println("Executing: " + sql); executeSql(sql); sql = ""; } } catch (SQLException e) { sql = ""; br.close(); DatabaseConnection.getConnection().rollback(); DatabaseConnection.getConnection().setAutoCommit(true); throw new DatabaseLibraryException("Error executing: " + sql + " Execution from file rolled back!"); } } DatabaseConnection.getConnection().commit(); DatabaseConnection.getConnection().setAutoCommit(true); br.close(); } @RobotKeyword("Executes the SQL statements contained in the given file without any " + "further modifications. The given SQL must be valid for the database that " + "is used. Any lines prefixed with \"REM\" or \"#\" are ignored. This keyword " + "can for example be used to setup database tables from some SQL install " + "script. " + "\n\n" + "Single SQL statements in the file can be spread over multiple lines, but " + "must be terminated with a semicolon \";\". A new statement must always " + "start in a new line and not in the same line where the previous statement " + "was terminated by a \";\". " + "\n\n" + "Any errors that might happen during execution of SQL statements are " + "logged to the Robot Log-file, but otherwise ignored. " + "\n\n" + "*NOTE*: Use this method with care as you might cause damage to your " + "database, especially when using this in a productive environment. \n\n" + "*NOTE2*: If using keyword remotely, file need to be trasfered to server some " + "other way; this library is not doing the transfer." + "\n\n" + "Example: \n" + "| Execute SQL from File | myFile.sql | ") @ArgumentNames({ "File containing SQL commands to execute" }) public void executeSqlFromFileIgnoreErrors(String fileName) throws SQLException, IOException, DatabaseLibraryException { DatabaseConnection.getConnection().setAutoCommit(false); FileReader fr = new FileReader(new File(fileName)); BufferedReader br = new BufferedReader(fr); String sql = ""; String line = ""; while ((line = br.readLine()) != null) { line = line.trim(); // Ignore lines commented out in the given file if (line.toLowerCase().startsWith("rem")) { continue; } if (line.startsWith(" continue; } // Add the line to the current SQL statement if (sql.length() > 0) { sql += " "; } sql += line; // Check if SQL statement is complete, if yes execute try { if (sql.endsWith(";")) { sql = sql.substring(0, sql.length() - 1); System.out.println("Executing: " + sql + "\n"); executeSql(sql); sql = ""; System.out.println("\n"); } } catch (SQLException e) { System.out.println("Error executing: " + sql + "\n" + e.getMessage() + "\n\n"); sql = ""; } } DatabaseConnection.getConnection().commit(); DatabaseConnection.getConnection().setAutoCommit(true); br.close(); } @RobotKeyword("Reads a single value from the given table and column based on the " + "where-clause passed to the test. If the where-clause identifies more or " + "less than exactly one row in that table this will result in an error for " + "this teststep. Otherwise the selected value will be returned. " + "\n\n" + "Example: \n" + "| ${VALUE}= | Read single Value from Table | MySampleTable | EMail | Name='John Doe' | ") @ArgumentNames({ "Table name", "Column to get", "Where clause to identify the row" }) public String readSingleValueFromTable(String tableName, String columnName, String whereClause) throws SQLException, DatabaseLibraryException { String ret = ""; String sql = "select " + columnName + " from " + tableName + " where " + whereClause; Statement stmt = DatabaseConnection.getConnection().createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); try { stmt.executeQuery(sql); ResultSet rs = (ResultSet) stmt.getResultSet(); if (rs.first()) { ret = rs.getString(columnName); } if (rs.next()) { throw new DatabaseLibraryException("More than one value fetched for: " + sql); } } finally { // stmt.close() automatically takes care of its ResultSet, so no // rs.close() stmt.close(); } return ret; } }
package com.gmail.nossr50.listeners; import java.util.List; import org.bukkit.GameMode; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.Sound; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.block.BlockState; import org.bukkit.block.BrewingStand; import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.BlockDamageEvent; import org.bukkit.event.block.BlockPistonExtendEvent; import org.bukkit.event.block.BlockPistonRetractEvent; import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.inventory.ItemStack; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.config.Config; import com.gmail.nossr50.config.HiddenConfig; import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.skills.AbilityType; import com.gmail.nossr50.datatypes.skills.SkillType; import com.gmail.nossr50.datatypes.skills.ToolType; import com.gmail.nossr50.events.fake.FakeBlockBreakEvent; import com.gmail.nossr50.events.fake.FakeBlockDamageEvent; import com.gmail.nossr50.runnables.PistonTrackerTask; import com.gmail.nossr50.runnables.StickyPistonTrackerTask; import com.gmail.nossr50.skills.alchemy.Alchemy; import com.gmail.nossr50.skills.excavation.ExcavationManager; import com.gmail.nossr50.skills.herbalism.Herbalism; import com.gmail.nossr50.skills.herbalism.HerbalismManager; import com.gmail.nossr50.skills.mining.MiningManager; import com.gmail.nossr50.skills.repair.Repair; import com.gmail.nossr50.skills.salvage.Salvage; import com.gmail.nossr50.skills.smelting.SmeltingManager; import com.gmail.nossr50.skills.woodcutting.WoodcuttingManager; import com.gmail.nossr50.util.BlockUtils; import com.gmail.nossr50.util.EventUtils; import com.gmail.nossr50.util.ItemUtils; import com.gmail.nossr50.util.Misc; import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.skills.SkillUtils; public class BlockListener implements Listener { private final mcMMO plugin; public BlockListener(final mcMMO plugin) { this.plugin = plugin; } /** * Monitor BlockPistonExtend events. * * @param event The event to monitor */ @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onBlockPistonExtend(BlockPistonExtendEvent event) { if (!EventUtils.shouldProcessEvent(event.getBlock(), true)) { return; } BlockFace direction = event.getDirection(); Block futureEmptyBlock = event.getBlock().getRelative(direction); // Block that would be air after piston is finished if (futureEmptyBlock.getType() == Material.AIR) { return; } List<Block> blocks = event.getBlocks(); for (Block b : blocks) { if (BlockUtils.shouldBeWatched(b.getState()) && mcMMO.getPlaceStore().isTrue(b)) { b.getRelative(direction).setMetadata(mcMMO.blockMetadataKey, mcMMO.metadataValue); } } // Needed because blocks sometimes don't move when two pistons push towards each other new PistonTrackerTask(blocks, direction, futureEmptyBlock).runTaskLater(plugin, 2); } /** * Monitor BlockPistonRetract events. * * @param event The event to watch */ @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onBlockPistonRetract(BlockPistonRetractEvent event) { /*if (!EventUtils.shouldProcessEvent(event.getBlock(), false)) { return; }*/ if (!event.isSticky()) { return; } Block movedBlock = event.getRetractLocation().getBlock(); // Needed only because under some circumstances Minecraft doesn't move the block new StickyPistonTrackerTask(event.getDirection(), event.getBlock(), movedBlock).runTaskLater(plugin, 2); } /** * Monitor BlockPlace events. * * @param event The event to watch */ @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onBlockPlace(BlockPlaceEvent event) { Player player = event.getPlayer(); if (!UserManager.hasPlayerDataKey(player)) { return; } BlockState blockState = event.getBlock().getState(); /* Check if the blocks placed should be monitored so they do not give out XP in the future */ if (BlockUtils.shouldBeWatched(blockState)) { mcMMO.getPlaceStore().setTrue(blockState); } McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); if (blockState.getType() == Repair.anvilMaterial && SkillType.REPAIR.getPermissions(player)) { mcMMOPlayer.getRepairManager().placedAnvilCheck(); } else if (blockState.getType() == Salvage.anvilMaterial && SkillType.SALVAGE.getPermissions(player)) { mcMMOPlayer.getSalvageManager().placedAnvilCheck(); } } /** * Monitor BlockBreak events. * * @param event The event to monitor */ @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onBlockBreak(BlockBreakEvent event) { if (event instanceof FakeBlockBreakEvent) { return; } BlockState blockState = event.getBlock().getState(); Location location = blockState.getLocation(); if (!BlockUtils.shouldBeWatched(blockState)) { return; } /* ALCHEMY - Cancel any brew in progress for that BrewingStand */ if (blockState instanceof BrewingStand && Alchemy.brewingStandMap.containsKey(location)) { Alchemy.brewingStandMap.get(location).cancelBrew(); } Player player = event.getPlayer(); if (!UserManager.hasPlayerDataKey(player) || player.getGameMode() == GameMode.CREATIVE) { return; } McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); ItemStack heldItem = player.getItemInHand(); /* HERBALISM */ if (BlockUtils.affectedByGreenTerra(blockState)) { HerbalismManager herbalismManager = mcMMOPlayer.getHerbalismManager(); /* Green Terra */ if (herbalismManager.canActivateAbility()) { mcMMOPlayer.checkAbilityActivation(SkillType.HERBALISM); } /* * We don't check the block store here because herbalism has too many unusual edge cases. * Instead, we check it inside the drops handler. */ if (SkillType.HERBALISM.getPermissions(player)) { herbalismManager.herbalismBlockCheck(blockState); } } /* MINING */ else if (BlockUtils.affectedBySuperBreaker(blockState) && ItemUtils.isPickaxe(heldItem) && SkillType.MINING.getPermissions(player) && !mcMMO.getPlaceStore().isTrue(blockState)) { MiningManager miningManager = mcMMOPlayer.getMiningManager(); miningManager.miningBlockCheck(blockState); } /* WOOD CUTTING */ else if (BlockUtils.isLog(blockState) && ItemUtils.isAxe(heldItem) && SkillType.WOODCUTTING.getPermissions(player) && !mcMMO.getPlaceStore().isTrue(blockState)) { WoodcuttingManager woodcuttingManager = mcMMOPlayer.getWoodcuttingManager(); if (woodcuttingManager.canUseTreeFeller(heldItem)) { woodcuttingManager.processTreeFeller(blockState); } else { woodcuttingManager.woodcuttingBlockCheck(blockState); } } /* EXCAVATION */ else if (BlockUtils.affectedByGigaDrillBreaker(blockState) && ItemUtils.isShovel(heldItem) && SkillType.EXCAVATION.getPermissions(player) && !mcMMO.getPlaceStore().isTrue(blockState)) { ExcavationManager excavationManager = mcMMOPlayer.getExcavationManager(); excavationManager.excavationBlockCheck(blockState); if (mcMMOPlayer.getAbilityMode(AbilityType.GIGA_DRILL_BREAKER)) { excavationManager.gigaDrillBreaker(blockState); } } /* Remove metadata from placed watched blocks */ mcMMO.getPlaceStore().setFalse(blockState); } /** * Handle BlockBreak events where the event is modified. * * @param event The event to modify */ @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onBlockBreakHigher(BlockBreakEvent event) { if (event instanceof FakeBlockBreakEvent) { return; } Player player = event.getPlayer(); if (!UserManager.hasPlayerDataKey(player) || player.getGameMode() == GameMode.CREATIVE) { return; } BlockState blockState = event.getBlock().getState(); ItemStack heldItem = player.getItemInHand(); if (Herbalism.isRecentlyRegrown(blockState)) { event.setCancelled(true); return; } if (ItemUtils.isSword(heldItem)) { HerbalismManager herbalismManager = UserManager.getPlayer(player).getHerbalismManager(); if (herbalismManager.canUseHylianLuck()) { if (herbalismManager.processHylianLuck(blockState)) { blockState.update(true); event.setCancelled(true); } else if (blockState.getType() == Material.FLOWER_POT) { blockState.setType(Material.AIR); blockState.update(true); event.setCancelled(true); } } } else if (ItemUtils.isFluxPickaxe(heldItem) && !heldItem.containsEnchantment(Enchantment.SILK_TOUCH)) { SmeltingManager smeltingManager = UserManager.getPlayer(player).getSmeltingManager(); if (smeltingManager.canUseFluxMining(blockState)) { if (smeltingManager.processFluxMining(blockState)) { blockState.update(true); event.setCancelled(true); } } } } /** * Monitor BlockDamage events. * * @param event The event to watch */ @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onBlockDamage(BlockDamageEvent event) { if (event instanceof FakeBlockDamageEvent) { return; } Player player = event.getPlayer(); if (!UserManager.hasPlayerDataKey(player)) { return; } McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); BlockState blockState = event.getBlock().getState(); if (BlockUtils.canActivateAbilities(blockState)) { ItemStack heldItem = player.getItemInHand(); if (HiddenConfig.getInstance().useEnchantmentBuffs()) { if ((ItemUtils.isPickaxe(heldItem) && !mcMMOPlayer.getAbilityMode(AbilityType.SUPER_BREAKER)) || (ItemUtils.isShovel(heldItem) && !mcMMOPlayer.getAbilityMode(AbilityType.GIGA_DRILL_BREAKER))) { SkillUtils.removeAbilityBuff(heldItem); } } else { if ((mcMMOPlayer.getAbilityMode(AbilityType.SUPER_BREAKER) && !BlockUtils.affectedBySuperBreaker(blockState)) || (mcMMOPlayer.getAbilityMode(AbilityType.GIGA_DRILL_BREAKER) && !BlockUtils.affectedByGigaDrillBreaker(blockState))) { SkillUtils.handleAbilitySpeedDecrease(player); } } if (mcMMOPlayer.getToolPreparationMode(ToolType.HOE) && ItemUtils.isHoe(heldItem) && (BlockUtils.affectedByGreenTerra(blockState) || BlockUtils.canMakeMossy(blockState)) && Permissions.greenTerra(player)) { mcMMOPlayer.checkAbilityActivation(SkillType.HERBALISM); } else if (mcMMOPlayer.getToolPreparationMode(ToolType.AXE) && ItemUtils.isAxe(heldItem) && BlockUtils.isLog(blockState) && Permissions.treeFeller(player)) { mcMMOPlayer.checkAbilityActivation(SkillType.WOODCUTTING); } else if (mcMMOPlayer.getToolPreparationMode(ToolType.PICKAXE) && ItemUtils.isPickaxe(heldItem) && BlockUtils.affectedBySuperBreaker(blockState) && Permissions.superBreaker(player)) { mcMMOPlayer.checkAbilityActivation(SkillType.MINING); } else if (mcMMOPlayer.getToolPreparationMode(ToolType.SHOVEL) && ItemUtils.isShovel(heldItem) && BlockUtils.affectedByGigaDrillBreaker(blockState) && Permissions.gigaDrillBreaker(player)) { mcMMOPlayer.checkAbilityActivation(SkillType.EXCAVATION); } else if (mcMMOPlayer.getToolPreparationMode(ToolType.FISTS) && heldItem.getType() == Material.AIR && (BlockUtils.affectedByGigaDrillBreaker(blockState) || blockState.getType() == Material.SNOW || BlockUtils.affectedByBlockCracker(blockState) && Permissions.berserk(player))) { mcMMOPlayer.checkAbilityActivation(SkillType.UNARMED); } } if (mcMMOPlayer.getAbilityMode(AbilityType.TREE_FELLER) && BlockUtils.isLog(blockState) && Config.getInstance().getTreeFellerSoundsEnabled()) { player.playSound(blockState.getLocation(), Sound.FIZZ, Misc.FIZZ_VOLUME, Misc.getFizzPitch()); } } /** * Handle BlockDamage events where the event is modified. * * @param event The event to modify */ @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onBlockDamageHigher(BlockDamageEvent event) { if (event instanceof FakeBlockDamageEvent) { return; } Player player = event.getPlayer(); if (!UserManager.hasPlayerDataKey(player)) { return; } McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); ItemStack heldItem = player.getItemInHand(); Block block = event.getBlock(); BlockState blockState = block.getState(); if (mcMMOPlayer.getAbilityMode(AbilityType.GREEN_TERRA) && BlockUtils.canMakeMossy(blockState)) { if (mcMMOPlayer.getHerbalismManager().processGreenTerra(blockState)) { blockState.update(true); } } else if (mcMMOPlayer.getAbilityMode(AbilityType.BERSERK) && heldItem.getType() == Material.AIR) { if (AbilityType.BERSERK.blockCheck(block.getState()) && EventUtils.simulateBlockBreak(block, player, true)) { event.setInstaBreak(true); player.playSound(block.getLocation(), Sound.ITEM_PICKUP, Misc.POP_VOLUME, Misc.getPopPitch()); } else if (mcMMOPlayer.getUnarmedManager().canUseBlockCracker() && BlockUtils.affectedByBlockCracker(blockState) && EventUtils.simulateBlockBreak(block, player, true)) { if (mcMMOPlayer.getUnarmedManager().blockCrackerCheck(blockState)) { blockState.update(); } } } else if (mcMMOPlayer.getWoodcuttingManager().canUseLeafBlower(heldItem) && BlockUtils.isLeaves(blockState) && EventUtils.simulateBlockBreak(block, player, true)) { event.setInstaBreak(true); player.playSound(blockState.getLocation(), Sound.ITEM_PICKUP, Misc.POP_VOLUME, Misc.getPopPitch()); } } }
package com.gmail.nossr50.util.skills; import java.util.EnumMap; import java.util.HashMap; import java.util.Map; import java.util.Random; import org.bukkit.Material; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.AnimalTamer; import org.bukkit.entity.Animals; import org.bukkit.entity.Arrow; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.entity.IronGolem; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.entity.Skeleton; import org.bukkit.entity.Tameable; import org.bukkit.entity.Wolf; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityDamageEvent.DamageCause; import org.bukkit.event.entity.EntityDamageEvent.DamageModifier; import org.bukkit.inventory.ItemStack; import org.bukkit.projectiles.ProjectileSource; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.config.experience.ExperienceConfig; import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.skills.SkillType; import com.gmail.nossr50.datatypes.skills.XPGainReason; import com.gmail.nossr50.events.fake.FakeEntityDamageByEntityEvent; import com.gmail.nossr50.events.fake.FakeEntityDamageEvent; import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.party.PartyManager; import com.gmail.nossr50.runnables.skills.AwardCombatXpTask; import com.gmail.nossr50.runnables.skills.BleedTimerTask; import com.gmail.nossr50.skills.acrobatics.AcrobaticsManager; import com.gmail.nossr50.skills.archery.ArcheryManager; import com.gmail.nossr50.skills.axes.AxesManager; import com.gmail.nossr50.skills.swords.Swords; import com.gmail.nossr50.skills.swords.SwordsManager; import com.gmail.nossr50.skills.taming.TamingManager; import com.gmail.nossr50.skills.unarmed.UnarmedManager; import com.gmail.nossr50.util.EventUtils; import com.gmail.nossr50.util.ItemUtils; import com.gmail.nossr50.util.Misc; import com.gmail.nossr50.util.MobHealthbarUtils; import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.player.UserManager; import com.google.common.collect.ImmutableMap; public final class CombatUtils { private CombatUtils() { } private static boolean harmfulCreature; public final static double LIFE_STEAL_PCTG = 0.6; private static void processSwordCombat(LivingEntity target, Player player, EntityDamageByEntityEvent event) { McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); SwordsManager swordsManager = mcMMOPlayer.getSwordsManager(); double initialDamage = event.getDamage(); double finalDamage = event.getDamage(); Map<DamageModifier, Double> modifiers = getModifiers(event); if (swordsManager.canActivateAbility()) { mcMMOPlayer.checkAbilityActivation(SkillType.SWORDS); } if (swordsManager.canUseBleed()) { swordsManager.bleedCheck(target); } // 5th change of the 1st change request if (swordsManager.canCriticalHit(target)) { finalDamage += swordsManager.criticalHit(target, initialDamage); } if (swordsManager.canUseSerratedStrike()) { swordsManager.serratedStrikes(target, initialDamage, modifiers); } startGainXp(mcMMOPlayer, target, SkillType.SWORDS); } private static void processAxeCombat(LivingEntity target, Player player, EntityDamageByEntityEvent event) { double initialDamage = event.getDamage(); double finalDamage = initialDamage; Map<DamageModifier, Double> modifiers = getModifiers(event); McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); AxesManager axesManager = mcMMOPlayer.getAxesManager(); if (axesManager.canActivateAbility()) { mcMMOPlayer.checkAbilityActivation(SkillType.AXES); } if (axesManager.canUseAxeMastery()) { finalDamage += axesManager.axeMastery(); } if (axesManager.canCriticalHit(target)) { finalDamage += axesManager.criticalHit(target, initialDamage); } if (axesManager.canImpact(target)) { axesManager.impactCheck(target); } else if (axesManager.canGreaterImpact(target)) { finalDamage += axesManager.greaterImpact(target); } if (axesManager.canUseSkullSplitter(target)) { axesManager.skullSplitterCheck(target, initialDamage, modifiers); } applyScaledModifiers(initialDamage, finalDamage, event); startGainXp(mcMMOPlayer, target, SkillType.AXES); } private static void processUnarmedCombat(LivingEntity target, Player player, EntityDamageByEntityEvent event) { double initialDamage = event.getDamage(); double finalDamage = initialDamage; McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); UnarmedManager unarmedManager = mcMMOPlayer.getUnarmedManager(); if (unarmedManager.canActivateAbility()) { mcMMOPlayer.checkAbilityActivation(SkillType.UNARMED); } if (unarmedManager.canUseIronArm()) { finalDamage += unarmedManager.ironArm(); } if (unarmedManager.canUseBerserk()) { finalDamage += unarmedManager.berserkDamage(initialDamage); } if (unarmedManager.canDisarm(target)) { unarmedManager.disarmCheck((Player) target); } applyScaledModifiers(initialDamage, finalDamage, event); startGainXp(mcMMOPlayer, target, SkillType.UNARMED); } private static void processTamingCombat(LivingEntity target, Player master, Wolf wolf, EntityDamageByEntityEvent event) { double initialDamage = event.getDamage(); double finalDamage = initialDamage; McMMOPlayer mcMMOPlayer = UserManager.getPlayer(master); TamingManager tamingManager = mcMMOPlayer.getTamingManager(); if (tamingManager.canUseFastFoodService()) { tamingManager.fastFoodService(wolf, event.getDamage()); } if (tamingManager.canUseSharpenedClaws()) { finalDamage += tamingManager.sharpenedClaws(); } if (tamingManager.canUseGore()) { finalDamage += tamingManager.gore(target, initialDamage); } applyScaledModifiers(initialDamage, finalDamage, event); startGainXp(mcMMOPlayer, target, SkillType.TAMING); } public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) { if (commandLabel.equalsIgnoreCase("wolf")) { Player player = (Player) sender; org.bukkit.Location location = player.getLocation(); Wolf wolf = (Wolf) player.getWorld().spawnEntity(location, EntityType.WOLF); wolf.setAngry(true); wolf.setTarget(player); } return false; } private static void processArcheryCombat(LivingEntity target, Player player, EntityDamageByEntityEvent event, Arrow arrow) { double initialDamage = event.getDamage(); double finalDamage = initialDamage; McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); ArcheryManager archeryManager = mcMMOPlayer.getArcheryManager(); if (target instanceof Player && SkillType.UNARMED.getPVPEnabled()) { UnarmedManager unarmedManager = UserManager.getPlayer( (Player) target).getUnarmedManager(); if (unarmedManager.canDeflect()) { event.setCancelled(unarmedManager.deflectCheck()); if (event.isCancelled()) { return; } } } if (archeryManager.canSkillShot()) { finalDamage += archeryManager.skillShot(initialDamage); } if (archeryManager.canDaze(target)) { finalDamage += archeryManager.daze((Player) target); } if (!arrow.hasMetadata(mcMMO.infiniteArrowKey) && archeryManager.canRetrieveArrows()) { archeryManager.retrieveArrows(target); } archeryManager.distanceXpBonus(target, arrow); applyScaledModifiers(initialDamage, finalDamage, event); startGainXp(mcMMOPlayer, target, SkillType.ARCHERY, arrow.getMetadata(mcMMO.bowForceKey).get(0).asDouble()); } /** * Apply combat modifiers and process and XP gain. * * @param event * The event to run the combat checks on. */ public static void processCombatAttack(EntityDamageByEntityEvent event, Entity attacker, LivingEntity target) { Entity damager = event.getDamager(); EntityType entityType = damager.getType(); if (attacker instanceof Player && entityType == EntityType.PLAYER) { Player player = (Player) attacker; if (!UserManager.hasPlayerDataKey(player)) { return; } ItemStack heldItem = player.getItemInHand(); if (target instanceof Tameable) { if (heldItem.getType() == Material.BONE) { TamingManager tamingManager = UserManager.getPlayer(player) .getTamingManager(); if (tamingManager.canUseBeastLore()) { tamingManager.beastLore(target); event.setCancelled(true); return; } } if (isFriendlyPet(player, (Tameable) target)) { return; } } /* * Implementation of lifesteal * * PRE: the player is the attacker, the target is a harmful creature * and the player's health is not full * * POST: a percentage of the damage inflicted might be returned to * the player */ harmfulCreature = isHarmfulEntity(target); double currentHealth = player.getHealth(); double maxHealth = player.getMaxHealth(); if (harmfulCreature && currentHealth != maxHealth) { double dam = event.getDamage(); double pctg = Math.random(); // 60% chance of not getting health points back if (pctg >= LIFE_STEAL_PCTG) { pctg = Math.random(); Double addHealth = dam * pctg; double newHealth = currentHealth + addHealth; if (newHealth >= maxHealth) player.setHealth(maxHealth); else player.setHealth(newHealth); String message = "You have been given " + addHealth.toString() + " HP"; player.sendMessage(message); } } if (ItemUtils.isSword(heldItem)) { if (!SkillType.SWORDS.shouldProcess(target)) { return; } if (SkillType.SWORDS.getPermissions(player)) { processSwordCombat(target, player, event); } } else if (ItemUtils.isAxe(heldItem)) { if (!SkillType.AXES.shouldProcess(target)) { return; } if (SkillType.AXES.getPermissions(player)) { processAxeCombat(target, player, event); } } else if (heldItem.getType() == Material.AIR) { if (!SkillType.UNARMED.shouldProcess(target)) { return; } if (SkillType.UNARMED.getPermissions(player)) { processUnarmedCombat(target, player, event); } } } else if (entityType == EntityType.WOLF) { Wolf wolf = (Wolf) damager; AnimalTamer tamer = wolf.getOwner(); if (tamer != null && tamer instanceof Player && SkillType.TAMING.shouldProcess(target)) { Player master = (Player) tamer; if (!Misc.isNPCEntity(master) && SkillType.TAMING.getPermissions(master)) { processTamingCombat(target, master, wolf, event); } } } else if (entityType == EntityType.ARROW) { Arrow arrow = (Arrow) damager; ProjectileSource projectileSource = arrow.getShooter(); if (projectileSource != null && projectileSource instanceof Player && SkillType.ARCHERY.shouldProcess(target)) { Player player = (Player) projectileSource; if (!Misc.isNPCEntity(player) && SkillType.ARCHERY.getPermissions(player)) { processArcheryCombat(target, player, event, arrow); } } } if (target instanceof Player) { if (Misc.isNPCEntity(target)) { return; } Player player = (Player) target; if (!UserManager.hasPlayerDataKey(player)) { return; } McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); AcrobaticsManager acrobaticsManager = mcMMOPlayer .getAcrobaticsManager(); if (acrobaticsManager.canDodge(target)) { event.setDamage(acrobaticsManager.dodgeCheck(event.getDamage())); } if (ItemUtils.isSword(player.getItemInHand())) { if (!SkillType.SWORDS.shouldProcess(target)) { return; } SwordsManager swordsManager = mcMMOPlayer.getSwordsManager(); if (swordsManager.canUseCounterAttack(damager)) { swordsManager.counterAttackChecks((LivingEntity) damager, event.getDamage()); } } } } /** * Attempt to damage target for value dmg with reason CUSTOM * * @param target * LivingEntity which to attempt to damage * @param damage * Amount of damage to attempt to do */ @Deprecated public static void dealDamage(LivingEntity target, double damage) { dealDamage(target, damage, DamageCause.CUSTOM, null); } /** * Attempt to damage target for value dmg with reason ENTITY_ATTACK with * damager attacker * * @param target * LivingEntity which to attempt to damage * @param damage * Amount of damage to attempt to do * @param attacker * Player to pass to event as damager */ @Deprecated public static void dealDamage(LivingEntity target, double damage, LivingEntity attacker) { dealDamage(target, damage, DamageCause.ENTITY_ATTACK, attacker); } /** * Attempt to damage target for value dmg with reason ENTITY_ATTACK with * damager attacker * * @param target * LivingEntity which to attempt to damage * @param damage * Amount of damage to attempt to do * @param attacker * Player to pass to event as damager */ public static void dealDamage(LivingEntity target, double damage, Map<DamageModifier, Double> modifiers, LivingEntity attacker) { if (target.isDead()) { return; } // Aren't we applying the damage twice???? target.damage(callFakeDamageEvent(attacker, target, damage, modifiers)); } /** * Attempt to damage target for value dmg with reason ENTITY_ATTACK with * damager attacker * * @param target * LivingEntity which to attempt to damage * @param damage * Amount of damage to attempt to do * @param attacker * Player to pass to event as damager */ @Deprecated public static void dealDamage(LivingEntity target, double damage, DamageCause cause, Entity attacker) { if (target.isDead()) { return; } target.damage(callFakeDamageEvent(attacker, target, cause, damage)); } /** * Apply Area-of-Effect ability actions. * * @param attacker * The attacking player * @param target * The defending entity * @param damage * The initial damage amount * @param type * The type of skill being used */ public static void applyAbilityAoE(Player attacker, LivingEntity target, double damage, Map<DamageModifier, Double> modifiers, SkillType type) { int numberOfTargets = getTier(attacker.getItemInHand()); // The higher // the // weapon // tier, the // more // targets // you hit double damageAmount = Math.max(damage, 1); for (Entity entity : target.getNearbyEntities(2.5, 2.5, 2.5)) { if (numberOfTargets <= 0) { break; } if (Misc.isNPCEntity(entity) || !(entity instanceof LivingEntity) || !shouldBeAffected(attacker, entity)) { continue; } LivingEntity livingEntity = (LivingEntity) entity; EventUtils.callFakeArmSwingEvent(attacker); switch (type) { case SWORDS: if (entity instanceof Player) { ((Player) entity).sendMessage(LocaleLoader .getString("Swords.Combat.SS.Struck")); } BleedTimerTask.add(livingEntity, Swords.serratedStrikesBleedTicks); break; case AXES: if (entity instanceof Player) { ((Player) entity).sendMessage(LocaleLoader .getString("Axes.Combat.SS.Struck")); } break; default: break; } dealDamage(livingEntity, damageAmount, attacker); numberOfTargets } } public static void startGainXp(McMMOPlayer mcMMOPlayer, LivingEntity target, SkillType skillType) { startGainXp(mcMMOPlayer, target, skillType, 1.0); } /** * Start the task that gives combat XP. * * @param mcMMOPlayer * The attacking player * @param target * The defending entity * @param skillType * The skill being used */ private static void startGainXp(McMMOPlayer mcMMOPlayer, LivingEntity target, SkillType skillType, double multiplier) { double baseXP = 0; XPGainReason xpGainReason; if (target instanceof Player) { if (!ExperienceConfig.getInstance() .getExperienceGainsPlayerVersusPlayerEnabled()) { return; } xpGainReason = XPGainReason.PVP; Player defender = (Player) target; if (defender.isOnline() && SkillUtils.cooldownExpired(mcMMOPlayer.getRespawnATS(), Misc.PLAYER_RESPAWN_COOLDOWN_SECONDS)) { baseXP = 20 * ExperienceConfig.getInstance() .getPlayerVersusPlayerXP(); } } else { if (mcMMO.getModManager().isCustomEntity(target)) { baseXP = mcMMO.getModManager().getEntity(target) .getXpMultiplier(); } else if (target instanceof Animals) { baseXP = ExperienceConfig.getInstance().getAnimalsXP(); } else { EntityType type = target.getType(); switch (type) { case BAT: case SQUID: baseXP = ExperienceConfig.getInstance().getAnimalsXP(); break; case BLAZE: case CAVE_SPIDER: case CREEPER: case ENDER_DRAGON: case ENDERMAN: case GHAST: case GIANT: case MAGMA_CUBE: case PIG_ZOMBIE: case SILVERFISH: case SLIME: case SPIDER: case WITCH: case WITHER: case ZOMBIE: baseXP = ExperienceConfig.getInstance().getCombatXP(type); break; case SKELETON: switch (((Skeleton) target).getSkeletonType()) { case WITHER: baseXP = ExperienceConfig.getInstance() .getWitherSkeletonXP(); break; default: baseXP = ExperienceConfig.getInstance().getCombatXP( type); break; } break; case IRON_GOLEM: if (!((IronGolem) target).isPlayerCreated()) { baseXP = ExperienceConfig.getInstance().getCombatXP( type); } break; default: baseXP = 1.0; mcMMO.getModManager().addCustomEntity(target); break; } } if (target.hasMetadata(mcMMO.entityMetadataKey)) { baseXP *= ExperienceConfig.getInstance() .getSpawnedMobXpMultiplier(); } xpGainReason = XPGainReason.PVE; baseXP *= 10; } baseXP *= multiplier; if (baseXP != 0) { new AwardCombatXpTask(mcMMOPlayer, skillType, baseXP, target, xpGainReason).runTaskLater(mcMMO.p, 0); } } /** * Check to see if the given LivingEntity should be affected by a combat * ability. * * @param player * The attacking Player * @param entity * The defending Entity * @return true if the Entity should be damaged, false otherwise. */ private static boolean shouldBeAffected(Player player, Entity entity) { if (entity instanceof Player) { Player defender = (Player) entity; if (!defender.getWorld().getPVP() || defender == player || UserManager.getPlayer(defender).getGodMode()) { return false; } if ((PartyManager.inSameParty(player, defender) || PartyManager .areAllies(player, defender)) && !(Permissions.friendlyFire(player) && Permissions .friendlyFire(defender))) { return false; } // Vanished players should not be able to get hit by AoE effects if (!player.canSee(defender)) { return false; } // It may seem a bit redundant but we need a check here to prevent // bleed from being applied in applyAbilityAoE() if (callFakeDamageEvent(player, entity, 1.0) == 0) { return false; } } else if (entity instanceof Tameable) { if (isFriendlyPet(player, (Tameable) entity)) { // isFriendlyPet ensures that the Tameable is: Tamed, owned by a // player, and the owner is in the same party // So we can make some assumptions here, about our casting and // our check Player owner = (Player) ((Tameable) entity).getOwner(); if (!(Permissions.friendlyFire(player) && Permissions .friendlyFire(owner))) { return false; } } } return true; } /** * Checks to see if an entity is currently invincible. * * @param entity * The {@link LivingEntity} to check * @param eventDamage * The damage from the event the entity is involved in * @return true if the entity is invincible, false otherwise */ public static boolean isInvincible(LivingEntity entity, double eventDamage) { /* * So apparently if you do more damage to a LivingEntity than its last * damage int you bypass the invincibility. So yeah, this is for that. */ return (entity.getNoDamageTicks() > entity.getMaximumNoDamageTicks() / 2.0F) && (eventDamage <= entity.getLastDamage()); } /** * Checks to see if an entity is currently friendly toward a given player. * * @param attacker * The player to check. * @param pet * The entity to check. * @return true if the entity is friendly, false otherwise */ public static boolean isFriendlyPet(Player attacker, Tameable pet) { if (pet.isTamed()) { AnimalTamer tamer = pet.getOwner(); if (tamer instanceof Player) { Player owner = (Player) tamer; return (owner == attacker || PartyManager.inSameParty(attacker, owner) || PartyManager .areAllies(attacker, owner)); } } return false; } @Deprecated public static double callFakeDamageEvent(Entity attacker, Entity target, double damage) { return callFakeDamageEvent( attacker, target, DamageCause.ENTITY_ATTACK, new EnumMap<DamageModifier, Double>(ImmutableMap.of( DamageModifier.BASE, damage))); } @Deprecated public static double callFakeDamageEvent(Entity attacker, Entity target, DamageCause damageCause, double damage) { EntityDamageEvent damageEvent = attacker == null ? new FakeEntityDamageEvent( target, damageCause, damage) : new FakeEntityDamageByEntityEvent(attacker, target, damageCause, damage); mcMMO.p.getServer().getPluginManager().callEvent(damageEvent); if (damageEvent.isCancelled()) { return 0; } return damageEvent.getFinalDamage(); } public static double callFakeDamageEvent(Entity attacker, Entity target, Map<DamageModifier, Double> modifiers) { return callFakeDamageEvent(attacker, target, DamageCause.ENTITY_ATTACK, modifiers); } public static double callFakeDamageEvent(Entity attacker, Entity target, double damage, Map<DamageModifier, Double> modifiers) { return callFakeDamageEvent(attacker, target, DamageCause.ENTITY_ATTACK, getScaledModifiers(damage, modifiers)); } public static double callFakeDamageEvent(Entity attacker, Entity target, DamageCause cause, Map<DamageModifier, Double> modifiers) { EntityDamageEvent damageEvent = attacker == null ? new FakeEntityDamageEvent( target, cause, modifiers) : new FakeEntityDamageByEntityEvent( attacker, target, cause, modifiers); mcMMO.p.getServer().getPluginManager().callEvent(damageEvent); if (damageEvent.isCancelled()) { return 0; } return damageEvent.getFinalDamage(); } private static Map<DamageModifier, Double> getModifiers( EntityDamageEvent event) { Map<DamageModifier, Double> modifiers = new HashMap<DamageModifier, Double>(); for (DamageModifier modifier : DamageModifier.values()) { modifiers.put(modifier, event.getDamage(modifier)); } return modifiers; } private static Map<DamageModifier, Double> getScaledModifiers( double damage, Map<DamageModifier, Double> modifiers) { Map<DamageModifier, Double> scaledModifiers = new HashMap<DamageModifier, Double>(); for (DamageModifier modifier : modifiers.keySet()) { if (modifier == DamageModifier.BASE) { scaledModifiers.put(modifier, damage); continue; } scaledModifiers.put(modifier, damage * modifiers.get(modifier)); } return scaledModifiers; } public static EntityDamageByEntityEvent applyScaledModifiers( double initialDamage, double finalDamage, EntityDamageByEntityEvent event) { // No additional damage if (initialDamage == finalDamage) { return event; } for (DamageModifier modifier : DamageModifier.values()) { if (!event.isApplicable(modifier)) { continue; } if (modifier == DamageModifier.BASE) { event.setDamage(modifier, finalDamage); continue; } event.setDamage(modifier, finalDamage / initialDamage * event.getDamage(modifier)); } return event; } /** * Get the upgrade tier of the item in hand. * * @param inHand * The item to check the tier of * @return the tier of the item */ private static int getTier(ItemStack inHand) { int tier = 0; if (ItemUtils.isWoodTool(inHand)) { tier = 1; } else if (ItemUtils.isStoneTool(inHand)) { tier = 2; } else if (ItemUtils.isIronTool(inHand)) { tier = 3; } else if (ItemUtils.isGoldTool(inHand)) { tier = 1; } else if (ItemUtils.isDiamondTool(inHand)) { tier = 4; } else if (mcMMO.getModManager().isCustomTool(inHand)) { tier = mcMMO.getModManager().getTool(inHand).getTier(); } return tier; } public static void handleHealthbars(Entity attacker, LivingEntity target, double damage) { if (!(attacker instanceof Player)) { return; } Player player = (Player) attacker; if (Misc.isNPCEntity(player) || Misc.isNPCEntity(target)) { return; } if (!player.hasMetadata(mcMMO.playerDataKey)) { return; } MobHealthbarUtils.handleMobHealthbars(player, target, damage); } /* * PRE: target is not null * * POST: returns true if target can inflict damage to the player and false * otherwise */ public static boolean isHarmfulEntity(LivingEntity target) { EntityType type = target.getType(); if (type.equals(EntityType.BLAZE)) return true; else if (type.equals(EntityType.CAVE_SPIDER)) return true; else if (type.equals(EntityType.CREEPER)) return true; else if (type.equals(EntityType.ENDER_DRAGON)) return true; else if (type.equals(EntityType.ENDERMAN)) return true; else if (type.equals(EntityType.IRON_GOLEM)) return true; else if (type.equals(EntityType.SILVERFISH)) return true; else if (type.equals(EntityType.SKELETON)) return true; else if (type.equals(EntityType.SLIME)) return true; else if (type.equals(EntityType.SPIDER)) return true; else if (type.equals(EntityType.WITCH)) return true; else if (type.equals(EntityType.WITHER)) return true; else if (type.equals(EntityType.WITHER_SKULL)) return true; else if (type.equals(EntityType.WOLF)) return true; else if (type.equals(EntityType.ZOMBIE)) return true; else return false; } }
package info.xiaomo.admin.controller; import info.xiaomo.core.controller.BaseController; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.HashMap; import java.util.Map; import java.util.Properties; @RestController @RequestMapping("/admin/system") public class SystemController extends BaseController { @RequestMapping("getSystem") public HashMap<String, Object> getSystem() { Map<String, Object> map = new HashMap<>(); Properties properties = System.getProperties(); map.put("javaVersion", properties.getProperty("java.version")); map.put("javaVendor", properties.getProperty("java.vendor"));//Java map.put("javaVendorUrl", properties.getProperty("java.vendor.url"));// Java URL map.put("javaHome", properties.getProperty("java.home"));//Java map.put("javaClassVersion", properties.getProperty("java.class.version"));// Java map.put("osName", properties.getProperty("os.name")); map.put("osVersion", properties.getProperty("os.version")); map.put("userName", properties.getProperty("user.name")); map.put("useRHome", properties.getProperty("user.home")); map.put("userDir", properties.getProperty("user.dir")); result.put(systems, map); result.put(code, success); return result; } }
package ti.modules.titanium.ui; import java.util.ArrayList; import java.util.HashMap; import org.appcelerator.kroll.KrollDict; import org.appcelerator.kroll.KrollProxy; import org.appcelerator.kroll.annotations.Kroll; import org.appcelerator.kroll.common.AsyncResult; import org.appcelerator.kroll.common.Log; import org.appcelerator.kroll.common.TiMessenger; import org.appcelerator.titanium.TiApplication; import org.appcelerator.titanium.TiC; import org.appcelerator.titanium.TiContext; import org.appcelerator.titanium.proxy.TiViewProxy; import org.appcelerator.titanium.util.TiConvert; import org.appcelerator.titanium.view.TiUIView; import ti.modules.titanium.ui.widget.TiUITableView; import ti.modules.titanium.ui.widget.tableview.TableViewModel.Item; import android.app.Activity; import android.os.Message; @Kroll.proxy(creatableInModule = UIModule.class, propertyAccessors = { TiC.PROPERTY_FILTER_ATTRIBUTE, TiC.PROPERTY_FILTER_CASE_INSENSITIVE, TiC.PROPERTY_HEADER_TITLE, TiC.PROPERTY_HEADER_VIEW, TiC.PROPERTY_FOOTER_TITLE, TiC.PROPERTY_FOOTER_VIEW, TiC.PROPERTY_SEARCH, TiC.PROPERTY_SEPARATOR_COLOR }) public class TableViewProxy extends TiViewProxy { private static final String TAG = "TableViewProxy"; private static final int INSERT_ROW_BEFORE = 0; private static final int INSERT_ROW_AFTER = 1; private static final int MSG_UPDATE_VIEW = TiViewProxy.MSG_LAST_ID + 5001; private static final int MSG_SCROLL_TO_INDEX = TiViewProxy.MSG_LAST_ID + 5002; private static final int MSG_SET_DATA = TiViewProxy.MSG_LAST_ID + 5003; private static final int MSG_DELETE_ROW = TiViewProxy.MSG_LAST_ID + 5004; private static final int MSG_INSERT_ROW = TiViewProxy.MSG_LAST_ID + 5005; private static final int MSG_APPEND_ROW = TiViewProxy.MSG_LAST_ID + 5006; private static final int MSG_SCROLL_TO_TOP = TiViewProxy.MSG_LAST_ID + 5007; private static final int MSG_SELECT_ROW = TiViewProxy.MSG_LAST_ID + 5008; public static final String CLASSNAME_DEFAULT = "__default__"; public static final String CLASSNAME_HEADER = "__header__"; public static final String CLASSNAME_HEADERVIEW = "__headerView__"; public static final String CLASSNAME_NORMAL = "__normal__"; class RowResult { int sectionIndex; TableViewSectionProxy section; TableViewRowProxy row; int rowIndexInSection; } private ArrayList<TableViewSectionProxy> localSections; public TableViewProxy() { super(); // eventManager.addOnEventChangeListener(this); } public TableViewProxy(TiContext tiContext) { this(); } @Override public void handleCreationDict(KrollDict dict) { Object data[] = null; if (dict.containsKey(TiC.PROPERTY_DATA)) { Object o = dict.get(TiC.PROPERTY_DATA); if (o != null && o instanceof Object[]) { data = (Object[]) o; dict.remove(TiC.PROPERTY_DATA); // don't override our data accessor } } super.handleCreationDict(dict); if (data != null) { processData(data); } } @Override public void setActivity(Activity activity) { super.setActivity(activity); if (localSections != null) { for (TableViewSectionProxy section : localSections) { section.setActivity(activity); } } } @Override public void releaseViews() { super.releaseViews(); if (localSections != null) { for (TableViewSectionProxy section : localSections) { section.releaseViews(); } } } @Override public TiUIView createView(Activity activity) { return new TiUITableView(this); } public TiUITableView getTableView() { return (TiUITableView) getOrCreateView(); } @Kroll.method public void updateRow(Object row, Object data, @Kroll.argument(optional = true) KrollDict options) { TableViewSectionProxy sectionProxy = null; int rowIndex = -1; if (row instanceof Number) { RowResult rr = new RowResult(); rowIndex = ((Number) row).intValue(); locateIndex(rowIndex, rr); sectionProxy = rr.section; rowIndex = rr.rowIndexInSection; } else if (row instanceof TableViewRowProxy) { ArrayList<TableViewSectionProxy> sections = getSectionsArray(); sectionLoop: for (int i = 0; i < sections.size(); i++) { ArrayList<TableViewRowProxy> rows = sections.get(i).rows; for (int j = 0; j < rows.size(); j++) { if (rows.get(j) == row) { sectionProxy = sections.get(i); rowIndex = j; break sectionLoop; } } } } if (sectionProxy != null) { sectionProxy.updateRowAt(rowIndex, rowProxyFor(data)); getTableView().setModelDirty(); updateView(); } } // options argument exists in order to maintain parity with iOS, do not remove @Kroll.method public void appendRow(Object rows, @Kroll.argument(optional = true) KrollDict options) { if (TiApplication.isUIThread()) { handleAppendRow(rows); return; } TiMessenger.sendBlockingMainMessage(getMainHandler().obtainMessage(MSG_APPEND_ROW), rows); } @Override public boolean fireEvent(String eventName, Object data) { if (eventName.equals(TiC.EVENT_LONGPRESS)) { double x = ((KrollDict)data).getDouble(TiC.PROPERTY_X); double y = ((KrollDict)data).getDouble(TiC.PROPERTY_Y); int index = getTableView().getTableView().getIndexFromXY(x, y); if (index != -1) { Item item = getTableView().getTableView().getItemAtPosition(index); TableViewRowProxy.fillClickEvent((KrollDict) data, getTableView().getModel(), item); } } //create copy to be thread safe. KrollDict dataCopy = new KrollDict((KrollDict)data); return super.fireEvent(eventName, dataCopy); } private void handleAppendRow(Object rows) { Object[] rowList = null; if (rows instanceof Object[]) { rowList = (Object[]) rows; } else { rowList = new Object[] { rows }; } ArrayList<TableViewSectionProxy> sections = getSectionsArray(); if (sections.size() == 0) { processData(rowList); } else { for (int i = 0; i < rowList.length; i++) { TableViewRowProxy rowProxy = rowProxyFor(rowList[i]); TableViewSectionProxy lastSection = sections.get(sections.size() - 1); TableViewSectionProxy addedToSection = addRowToSection(rowProxy, lastSection); if (lastSection == null || !lastSection.equals(addedToSection)) { sections.add(addedToSection); } rowProxy.setProperty(TiC.PROPERTY_SECTION, addedToSection); rowProxy.setProperty(TiC.PROPERTY_PARENT, addedToSection); } } getTableView().setModelDirty(); updateView(); } @Kroll.method public void deleteRow(int index, @Kroll.argument(optional = true) KrollDict options) { if (TiApplication.isUIThread()) { handleDeleteRow(index); return; } Object asyncResult = TiMessenger.sendBlockingMainMessage(getMainHandler().obtainMessage(MSG_DELETE_ROW), index); if (asyncResult instanceof IllegalStateException) { throw (IllegalStateException) asyncResult; } } private void handleDeleteRow(int index) throws IllegalStateException { RowResult rr = new RowResult(); if (locateIndex(index, rr)) { rr.section.removeRowAt(rr.rowIndexInSection); getTableView().setModelDirty(); updateView(); } else { throw new IllegalStateException("Index out of range. Non-existent row at " + index); } } @Kroll.method public int getIndexByName(String name) { int index = -1; int idx = 0; if (name != null) { for (TableViewSectionProxy section : getSections()) { for (TableViewRowProxy row : section.getRows()) { String rname = TiConvert.toString(row.getProperty(TiC.PROPERTY_NAME)); if (rname != null && name.equals(rname)) { index = idx; break; } idx++; } if (index > -1) { break; } } } return index; } @Kroll.method public void insertRowBefore(int index, Object data, @Kroll.argument(optional = true) KrollDict options) { if (TiApplication.isUIThread()) { handleInsertRowBefore(index, data); return; } Object asyncResult = TiMessenger.sendBlockingMainMessage( getMainHandler().obtainMessage(MSG_INSERT_ROW, INSERT_ROW_BEFORE, index), data); if (asyncResult instanceof IllegalStateException) { throw (IllegalStateException) asyncResult; } } private void handleInsertRowBefore(int index, Object data) throws IllegalStateException { if (getSectionsArray().size() > 0) { if (index < 0) { index = 0; } RowResult rr = new RowResult(); if (locateIndex(index, rr)) { TableViewRowProxy rowProxy = rowProxyFor(data); rr.section.insertRowAt(rr.rowIndexInSection, rowProxy); } else { throw new IllegalStateException("Index out of range. Non-existent row at " + index); } } else { // Add first row. Object[] args = { rowProxyFor(data) }; processData(args); } getTableView().setModelDirty(); updateView(); } @Kroll.method public void insertRowAfter(int index, Object data, @Kroll.argument(optional = true) KrollDict options) { if (TiApplication.isUIThread()) { handleInsertRowAfter(index, data); return; } Object asyncResult = TiMessenger.sendBlockingMainMessage( getMainHandler().obtainMessage(MSG_INSERT_ROW, INSERT_ROW_AFTER, index), data); if (asyncResult instanceof IllegalStateException) { throw (IllegalStateException) asyncResult; } } private void handleInsertRowAfter(int index, Object data) throws IllegalStateException { RowResult rr = new RowResult(); if (locateIndex(index, rr)) { // TODO check for section TableViewRowProxy rowProxy = rowProxyFor(data); rr.section.insertRowAt(rr.rowIndexInSection + 1, rowProxy); getTableView().setModelDirty(); updateView(); } else { throw new IllegalStateException("Index out of range. Non-existent row at " + index); } } @Kroll.getProperty @Kroll.method public TableViewSectionProxy[] getSections() { ArrayList<TableViewSectionProxy> sections = getSectionsArray(); return sections.toArray(new TableViewSectionProxy[sections.size()]); } public ArrayList<TableViewSectionProxy> getSectionsArray() { ArrayList<TableViewSectionProxy> sections = localSections; if (sections == null) { sections = new ArrayList<TableViewSectionProxy>(); localSections = sections; } return sections; } /** * If the row does not carry section information, it will be added * to the currentSection. If it does carry section information (i.e., a header), * that section will be created and the row added to it. Either way, * whichever section the row gets added to will be returned. */ private TableViewSectionProxy addRowToSection(TableViewRowProxy row, TableViewSectionProxy currentSection) { TableViewSectionProxy addedToSection = null; if (currentSection == null || row.hasProperty(TiC.PROPERTY_HEADER)) { addedToSection = new TableViewSectionProxy(); } else { addedToSection = currentSection; } if (row.hasProperty(TiC.PROPERTY_HEADER)) { addedToSection.setProperty(TiC.PROPERTY_HEADER_TITLE, row.getProperty(TiC.PROPERTY_HEADER)); } if (row.hasProperty(TiC.PROPERTY_FOOTER)) { addedToSection.setProperty(TiC.PROPERTY_FOOTER_TITLE, row.getProperty(TiC.PROPERTY_FOOTER)); } addedToSection.add(row); return addedToSection; } public void processData(Object[] data) { ArrayList<TableViewSectionProxy> sections = getSectionsArray(); sections.clear(); TableViewSectionProxy currentSection = null; if (hasProperty(TiC.PROPERTY_HEADER_TITLE)) { currentSection = new TableViewSectionProxy(); currentSection.setActivity(getActivity()); sections.add(currentSection); currentSection.setProperty(TiC.PROPERTY_HEADER_TITLE, getProperty(TiC.PROPERTY_HEADER_TITLE)); } if (hasProperty(TiC.PROPERTY_FOOTER_TITLE)) { if (currentSection == null) { currentSection = new TableViewSectionProxy(); currentSection.setActivity(getActivity()); sections.add(currentSection); } currentSection.setProperty(TiC.PROPERTY_FOOTER_TITLE, getProperty(TiC.PROPERTY_FOOTER_TITLE)); } for (int i = 0; i < data.length; i++) { Object o = data[i]; if (o instanceof HashMap || o instanceof TableViewRowProxy) { TableViewRowProxy rowProxy = rowProxyFor(o); TableViewSectionProxy addedToSection = addRowToSection(rowProxy, currentSection); if (currentSection == null || !currentSection.equals(addedToSection)) { currentSection = addedToSection; sections.add(currentSection); } } else if (o instanceof TableViewSectionProxy) { currentSection = (TableViewSectionProxy) o; sections.add(currentSection); currentSection.setParent(this); } } } @Kroll.setProperty @Kroll.method public void setData(Object[] args) { Object[] data = args; if (args != null && args.length > 0 && args[0] instanceof Object[]) { data = (Object[]) args[0]; } if (TiApplication.isUIThread()) { handleSetData(data); } else { TiMessenger.sendBlockingMainMessage(getMainHandler().obtainMessage(MSG_SET_DATA), data); } } private void handleSetData(Object[] data) { if (data != null) { processData(data); getTableView().setModelDirty(); updateView(); } } @Kroll.getProperty @Kroll.method public Object[] getData() { ArrayList<TableViewSectionProxy> sections = getSectionsArray(); if (sections != null) { return sections.toArray(); } return new Object[0]; } private TableViewRowProxy rowProxyFor(Object row) { TableViewRowProxy rowProxy = null; if (row instanceof TableViewRowProxy) { rowProxy = (TableViewRowProxy) row; rowProxy.setProperty(TiC.PROPERTY_ROW_DATA, new KrollDict(rowProxy.getProperties())); } else { KrollDict rowDict = null; if (row instanceof KrollDict) { rowDict = (KrollDict) row; } else if (row instanceof HashMap) { rowDict = new KrollDict((HashMap) row); } if (rowDict != null) { rowProxy = new TableViewRowProxy(); rowProxy.setCreationUrl(creationUrl.getNormalizedUrl()); rowProxy.handleCreationDict(rowDict); rowProxy.setProperty(TiC.PROPERTY_CLASS_NAME, CLASSNAME_NORMAL); rowProxy.setCreationProperties(rowDict); rowProxy.setProperty(TiC.PROPERTY_ROW_DATA, row); rowProxy.setActivity(getActivity()); } } if (rowProxy == null) { Log.e(TAG, "Unable to create table view row proxy for object, likely an error in the type of the object passed in..."); return null; } rowProxy.setParent(this); return rowProxy; } private boolean locateIndex(int index, RowResult rowResult) { boolean found = false; int rowCount = 0; int sectionIndex = 0; for (TableViewSectionProxy section : getSections()) { int sectionRowCount = (int) section.getRowCount(); if (sectionRowCount + rowCount > index) { rowResult.section = section; rowResult.sectionIndex = sectionIndex; rowResult.row = section.getRows()[index - rowCount]; rowResult.rowIndexInSection = index - rowCount; found = true; break; } else { rowCount += sectionRowCount; } sectionIndex += 1; } return found; } public void updateView() { if (TiApplication.isUIThread()) { getTableView().updateView(); return; } TiMessenger.sendBlockingMainMessage(getMainHandler().obtainMessage(MSG_UPDATE_VIEW)); } @Kroll.method public void scrollToIndex(int index) { Message message = getMainHandler().obtainMessage(MSG_SCROLL_TO_INDEX); // Message msg = getUIHandler().obtainMessage(MSG_SCROLL_TO_INDEX); message.arg1 = index; message.sendToTarget(); } @Kroll.method public void selectRow(int row_id) { Message message = getMainHandler().obtainMessage(MSG_SELECT_ROW); message.arg1 = row_id; message.sendToTarget(); } @Kroll.method public void scrollToTop(int index) { Message message = getMainHandler().obtainMessage(MSG_SCROLL_TO_TOP); // Message msg = getUIHandler().obtainMessage(MSG_SCROLL_TO_TOP); message.arg1 = index; message.sendToTarget(); } @Override public boolean handleMessage(Message msg) { if (msg.what == MSG_UPDATE_VIEW) { getTableView().updateView(); ((AsyncResult) msg.obj).setResult(null); return true; } else if (msg.what == MSG_SCROLL_TO_INDEX) { getTableView().scrollToIndex(msg.arg1); return true; } else if (msg.what == MSG_SET_DATA) { AsyncResult result = (AsyncResult) msg.obj; Object[] data = (Object[]) result.getArg(); handleSetData(data); result.setResult(null); return true; } else if (msg.what == MSG_INSERT_ROW) { AsyncResult result = (AsyncResult) msg.obj; try { if (msg.arg1 == INSERT_ROW_AFTER) { handleInsertRowAfter(msg.arg2, result.getArg()); } else { handleInsertRowBefore(msg.arg2, result.getArg()); } result.setResult(null); } catch (IllegalStateException e) { result.setResult(e); } return true; } else if (msg.what == MSG_APPEND_ROW) { AsyncResult result = (AsyncResult) msg.obj; handleAppendRow(result.getArg()); result.setResult(null); return true; } else if (msg.what == MSG_DELETE_ROW) { AsyncResult result = (AsyncResult) msg.obj; try { handleDeleteRow((Integer) result.getArg()); result.setResult(null); } catch (IllegalStateException e) { result.setResult(e); } return true; } else if (msg.what == MSG_SCROLL_TO_TOP) { getTableView().scrollToTop(msg.arg1); return true; } else if (msg.what == MSG_SELECT_ROW){ getTableView().selectRow(msg.arg1); return true; } return super.handleMessage(msg); } // labels only send out click events when they are explicitly told to do so. // we need to tell each label child to enable clicks when a click listener is added @Override public void eventListenerAdded(String eventName, int count, KrollProxy proxy) { super.eventListenerAdded(eventName, count, proxy); if (eventName.equals(TiC.EVENT_CLICK) && proxy == this) { for (TableViewSectionProxy section : getSections()) { for (TableViewRowProxy row : section.getRows()) { row.setLabelsClickable(true); } } } } @Override public void eventListenerRemoved(String eventName, int count, KrollProxy proxy) { super.eventListenerRemoved(eventName, count, proxy); if (eventName.equals(TiC.EVENT_CLICK) && count == 0 && proxy == this) { for (TableViewSectionProxy section : getSections()) { for (TableViewRowProxy row : section.getRows()) { row.setLabelsClickable(false); } } } } }
package annotator.find; import com.sun.source.tree.*; import com.sun.source.util.TreePath; /** * Represents the criterion that a program element is not enclosed by any * method (i.e. it's a field, class type parameter, etc.). */ final class NotInMethodCriterion implements Criterion { /** * {@inheritDoc} */ @Override public Kind getKind() { return Kind.NOT_IN_METHOD; } /** {@inheritDoc} */ @Override public boolean isSatisfiedBy(TreePath path, Tree leaf) { assert path == null || path.getLeaf() == leaf; return isSatisfiedBy(path); } /** {@inheritDoc} */ @Override public boolean isSatisfiedBy(TreePath path) { do { Tree tree = path.getLeaf(); if (tree.getKind() == Tree.Kind.METHOD) return false; if (Criteria.isClassEquiv(tree)) { return true; } path = path.getParentPath(); } while (path != null && path.getLeaf() != null); return true; } /** * {@inheritDoc} */ @Override public String toString() { return "not in method"; } }
package com.j256.simplecsv.processor; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.Reader; import java.io.Writer; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.text.ParseException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.Callable; import com.j256.simplecsv.common.CsvColumn; import com.j256.simplecsv.common.CsvField; import com.j256.simplecsv.converter.Converter; import com.j256.simplecsv.converter.ConverterUtils; import com.j256.simplecsv.converter.EnumConverter; import com.j256.simplecsv.processor.ParseError.ErrorType; @SuppressWarnings("deprecation") public class CsvProcessor<T> { /** * Default separator character for columns. This can be changed with {@link #setColumnSeparator(char)}. */ public static final char DEFAULT_COLUMN_SEPARATOR = ','; /** * Default quote character for columns to wrap them if they have special characters. This can be changed with * {@link #setColumnQuote(char)}. */ public static final char DEFAULT_COLUMN_QUOTE = '"'; /** * Default line termination string to be written at the end of CSV lines. This can be changed with * {@link #setLineTermination(String)}. */ public static final String DEFAULT_LINE_TERMINATION = System.getProperty("line.separator"); private static ColumnNameMatcher stringEqualsColumnNameMatcher = new ColumnNameMatcher() { @Override public boolean matchesColumnName(String definitionName, String csvName) { return definitionName.equals(csvName); } }; private char columnSeparator = DEFAULT_COLUMN_SEPARATOR; private char columnQuote = DEFAULT_COLUMN_QUOTE; private String lineTermination = DEFAULT_LINE_TERMINATION; private boolean allowPartialLines; private boolean alwaysTrimInput; private boolean headerValidation = true; private boolean firstLineHeader = true; private boolean flexibleOrder; private boolean ignoreUnknownColumns; private RowValidator<T> rowValidator; private ColumnNameMatcher columnNameMatcher = stringEqualsColumnNameMatcher; private Class<T> entityClass; private Constructor<T> constructor; private Callable<T> constructorCallable; private final Map<Class<?>, Converter<?, ?>> converterMap = new HashMap<Class<?>, Converter<?, ?>>(); private List<ColumnInfo<Object>> allColumnInfos; private Map<Integer, ColumnInfo<Object>> columnPositionInfoMap; { ConverterUtils.addInternalConverters(converterMap); } public CsvProcessor() { // for spring } /** * Constructs a processor with an entity class whose fields should be marked with {@link CsvColumn} annotations. The * entity-class must also define a public no-arg contructor so the processor can instantiate them using reflection. */ public CsvProcessor(Class<T> entityClass) { this.entityClass = entityClass; } /** * Register a converter class for all instances of the class argument. The converter can also be specified with the * {@link CsvColumn#converterClass()} annotation field. */ public <FT> void registerConverter(Class<FT> clazz, Converter<FT, ?> converter) { converterMap.put(clazz, converter); } /** * Register a converter class for all instances of the class argument. The converter can also be specified with the * {@link CsvColumn#converterClass()} annotation field. Alternative way to do * {@link #registerConverter(Class, Converter)}. */ public <FT> CsvProcessor<T> withConverter(Class<FT> clazz, Converter<FT, ?> converter) { converterMap.put(clazz, converter); return this; } /** * This initializing the internal configuration information. It will self initialize if you start calling read/write * methods but this is here if you are using the class concurrently and need to force the initialization. */ public CsvProcessor<T> initialize() { configureEntityClass(); return this; } /** * Read in all of the entities in the file passed in. * * @param file * Where to read the header and entities from. It will be closed when the method returns. * @param parseErrors * If not null, any errors will be added to the collection and null will be returned. If validateHeader * is true and the header does not match then no additional lines will be returned. If this is null then * a ParseException will be thrown on parsing problems. * @return A list of entities read in or null if validateHeader is true and the first-line header was not valid. * @throws ParseException * Thrown on any parsing problems. If parseErrors is not null then parse errors will be added there and * an exception should not be thrown. * @throws IOException * If there are any IO exceptions thrown when reading. */ public List<T> readAll(File file, Collection<ParseError> parseErrors) throws IOException, ParseException { checkEntityConfig(); return readAll(new FileReader(file), parseErrors); } /** * Read in all of the entities in the reader passed in. It will use an internal buffered reader. * * @param reader * Where to read the header and entities from. It will be closed when the method returns. * @param parseErrors * If not null, any errors will be added to the collection and null will be returned. If validateHeader * is true and the header does not match then no additional lines will be returned. If this is null then * a ParseException will be thrown on parsing problems. * @return A list of entities read in or null if parseErrors is not null. * @throws ParseException * Thrown on any parsing problems. If parseErrors is not null then parse errors will be added there and * an exception should not be thrown. * @throws IOException * If there are any IO exceptions thrown when reading. */ public List<T> readAll(Reader reader, Collection<ParseError> parseErrors) throws IOException, ParseException { checkEntityConfig(); BufferedReader bufferedReader = new BufferedReaderLineCounter(reader); try { ParseError parseError = null; // we do this to reuse the parse error objects if we can if (parseErrors != null) { parseError = new ParseError(); } if (firstLineHeader) { if (readHeader(bufferedReader, parseError) == null) { if (parseError != null && parseError.isError()) { parseErrors.add(parseError); } return null; } } return readRows(bufferedReader, parseErrors); } finally { bufferedReader.close(); } } /** * Read in a line and process it as a CSV header. * * @param bufferedReader * Where to read the header from. It needs to be closed by the caller. Consider using * {@link BufferedReaderLineCounter} to populate the line-number for parse errors. * @param parseError * If not null, this will be set with the first parse error and it will return null. If this is null then * a ParseException will be thrown instead. * @return Array of header column names or null on error. * @throws ParseException * Thrown on any parsing problems. If parseError is not null then the error will be added there and an * exception should not be thrown. * @throws IOException * If there are any IO exceptions thrown when reading. */ public String[] readHeader(BufferedReader bufferedReader, ParseError parseError) throws ParseException, IOException { checkEntityConfig(); String header = bufferedReader.readLine(); if (header == null) { if (parseError == null) { throw new ParseException("no header line read", 0); } else { parseError.setErrorType(ErrorType.NO_HEADER); parseError.setLineNumber(getLineNumber(bufferedReader)); return null; } } String[] columns = processHeader(header, parseError, getLineNumber(bufferedReader)); if (columns == null) { return null; } else if (headerValidation && !validateHeaderColumns(columns, parseError, getLineNumber(bufferedReader))) { if (parseError == null) { throw new ParseException("header line is not valid: " + header, 0); } else { return null; } } return columns; } /** * Read in all of the entities in the reader passed in but without the header. * * @param bufferedReader * Where to read the entries from. It needs to be closed by the caller. Consider using * {@link BufferedReaderLineCounter} to populate the line-number for parse errors. * @param parseErrors * If not null, any errors will be added to the collection and null will be returned. If validateHeader * is true and the header does not match then no additional lines will be returned. If this is null then * a ParseException will be thrown on parsing problems. * @return A list of entities read in or null if parseErrors is not null. * @throws ParseException * Thrown on any parsing problems. If parseErrors is not null then parse errors will be added there and * an exception should not be thrown. * @throws IOException * If there are any IO exceptions thrown when reading. */ public List<T> readRows(BufferedReader bufferedReader, Collection<ParseError> parseErrors) throws IOException, ParseException { checkEntityConfig(); ParseError parseError = null; // we do this to reuse the parse error objects if we can if (parseErrors != null) { parseError = new ParseError(); } List<T> results = new ArrayList<T>(); while (true) { if (parseError != null) { parseError.reset(); } T result = readRow(bufferedReader, parseError); if (result != null) { results.add(result); } else if (parseError != null && parseError.isError()) { // if there was an error then add it to the list parseErrors.add(parseError); // once we use it, we need to create another one parseError = new ParseError(); } else { // if no result and no error then EOF return results; } } } /** * Read an entity line from the reader. * * @param bufferedReader * Where to read the row from. It needs to be closed by the caller. Consider using * {@link BufferedReaderLineCounter} to populate the line-number for parse errors. * @param parseError * If not null, this will be set with the first parse error and it will return null. If this is null then * a ParseException will be thrown instead. * @return Entity read in or null on EOF or error. Check {@link ParseError#isError()} to see if it was an error or * EOF. * @throws ParseException * Thrown on any parsing problems. If parseError is not null then the error will be added there and an * exception should not be thrown. * @throws IOException * If there are any IO exceptions thrown when reading. */ public T readRow(BufferedReader bufferedReader, ParseError parseError) throws ParseException, IOException { checkEntityConfig(); String line = bufferedReader.readLine(); if (line == null) { return null; } else { return processRow(line, parseError, getLineNumber(bufferedReader)); } } /** * Validate the header row against the configured header columns. * * @param line * Line to process to get our validate our header. * @param parseError * If not null, this will be set with the first parse error and it will return null. If this is null then * a ParseException will be thrown instead. * @return true if the header matched the column names configured here otherwise false. * @throws ParseException * Thrown on any parsing problems. If parseError is not null then the error will be added there and an * exception should not be thrown. */ public boolean validateHeader(String line, ParseError parseError) throws ParseException { checkEntityConfig(); String[] columns = processHeader(line, parseError); return validateHeaderColumns(columns, parseError, 1); } /** * Validate header columns returned by {@link #processHeader(String, ParseError)}. * * @param columns * Array of columns to validate. * @param parseError * If not null, this will be set with the first parse error and it will return null. If this is null then * a ParseException will be thrown instead. * @return true if the header matched the column names configured here otherwise false. * @throws ParseException * Thrown on any parsing problems. If parseError is not null then the error will be added there and an * exception should not be thrown. */ public boolean validateHeaderColumns(String[] columns, ParseError parseError) { checkEntityConfig(); return validateHeaderColumns(columns, parseError, 1); } /** * Process a header line and divide it up into a series of quoted columns. * * @param line * Line to process looking for header. * @param parseError * If not null, this will be set with the first parse error and it will return null. If this is null then * a ParseException will be thrown instead. * @return Returns an array of processed header names entity or null if an error and parseError has been set. The * array will be the same length as the number of configured columns so some elements may be null. * @throws ParseException * Thrown on any parsing problems. If parseError is not null then the error will be added there and an * exception should not be thrown. */ public String[] processHeader(String line, ParseError parseError) throws ParseException { checkEntityConfig(); return processHeader(line, parseError, 1); } /** * Read and process a line and return the associated entity. * * @param line * to process to build our entity. * @param parseError * If not null, this will be set with the first parse error and it will return null. If this is null then * a ParseException will be thrown instead. * @return Returns a processed entity or null if an error and parseError has been set. * @throws ParseException * Thrown on any parsing problems. If parseError is not null then the error will be added there and an * exception should not be thrown. */ public T processRow(String line, ParseError parseError) throws ParseException { checkEntityConfig(); return processRow(line, parseError, 1); } /** * Write a collection of entities to the writer. * * @param file * Where to write the header and entities. * @param entities * Collection of entities to write to the writer. * @param writeHeader * Set to true to write header at the start of the output file. * @throws IOException * If there are any IO exceptions thrown when writing. */ public void writeAll(File file, Collection<T> entities, boolean writeHeader) throws IOException { writeAll(new FileWriter(file), entities, writeHeader); } /** * Write a header and then the collection of entities to the writer. * * @param writer * Where to write the header and entities. It will be closed before this method returns. * @param entities * Collection of entities to write to the writer. * @param writeHeader * Set to true to write header at the start of the writer. * @throws IOException * If there are any IO exceptions thrown when writing. */ public void writeAll(Writer writer, Collection<T> entities, boolean writeHeader) throws IOException { checkEntityConfig(); BufferedWriter bufferedWriter = new BufferedWriter(writer); try { if (writeHeader) { writeHeader(bufferedWriter, true); } for (T entity : entities) { writeRow(bufferedWriter, entity, true); } } finally { bufferedWriter.close(); } } /** * Write the header line to the writer. * * @param bufferedWriter * Where to write our header information. * @param appendLineTermination * Set to true to add the newline to the end of the line. * @throws IOException * If there are any IO exceptions thrown when writing. */ public void writeHeader(BufferedWriter bufferedWriter, boolean appendLineTermination) throws IOException { checkEntityConfig(); bufferedWriter.write(buildHeaderLine(appendLineTermination)); } /** * Write an entity row to the writer. * * @param bufferedWriter * Where to write our header information. * @param entity * The entity we are writing to the buffered writer. * @param appendLineTermination * Set to true to add the newline to the end of the line. * @throws IOException * If there are any IO exceptions thrown when writing. */ public void writeRow(BufferedWriter bufferedWriter, T entity, boolean appendLineTermination) throws IOException { checkEntityConfig(); String line = buildLine(entity, appendLineTermination); bufferedWriter.write(line); } /** * Build and return a header string made up of quoted column names. * * @param appendLineTermination * Set to true to add the newline to the end of the line. */ public String buildHeaderLine(boolean appendLineTermination) { checkEntityConfig(); StringBuilder sb = new StringBuilder(); boolean first = true; for (ColumnInfo<?> columnInfo : allColumnInfos) { if (first) { first = false; } else { sb.append(columnSeparator); } String header = columnInfo.getColumnName(); // need to protect the column if it contains a quote if (header.indexOf(columnQuote) >= 0) { writeQuoted(sb, header); continue; } sb.append(columnQuote); sb.append(header); sb.append(columnQuote); } if (appendLineTermination) { sb.append(lineTermination); } return sb.toString(); } /** * Convert the entity into a string of column values. * * @param appendLineTermination * Set to true to add the newline to the end of the line. */ public String buildLine(T entity, boolean appendLineTermination) { checkEntityConfig(); StringBuilder sb = new StringBuilder(); boolean first = true; for (ColumnInfo<Object> columnInfo : allColumnInfos) { if (first) { first = false; } else { sb.append(columnSeparator); } Object value; try { value = columnInfo.getValue(entity); } catch (Exception e) { throw new IllegalStateException("Could not get value from entity field: " + columnInfo); } @SuppressWarnings("unchecked") Converter<Object, Object> castConverter = (Converter<Object, Object>) columnInfo.getConverter(); String str = castConverter.javaToString(columnInfo, value); boolean needsQuotes = columnInfo.isNeedsQuotes(); if (str == null) { if (needsQuotes) { sb.append(columnQuote).append(columnQuote); } continue; } // need to protect the column if it contains a quote if (str.indexOf(columnQuote) >= 0) { writeQuoted(sb, str); continue; } if (!needsQuotes) { for (int i = 0; i < str.length(); i++) { char ch = str.charAt(i); if (ch == columnSeparator || ch == '\r' || ch == '\n' || ch == '\t' || ch == '\b') { needsQuotes = true; break; } } } if (needsQuotes) { sb.append(columnQuote); } sb.append(str); if (needsQuotes) { sb.append(columnQuote); } } if (appendLineTermination) { sb.append(lineTermination); } return sb.toString(); } /** * Class that we are processing. */ public void setEntityClass(Class<T> entityClass) { this.entityClass = entityClass; } /** * Class that we are processing. Alternative way to do {@link #setEntityClass(Class)}. */ public CsvProcessor<T> withEntityClass(Class<T> entityClass) { this.entityClass = entityClass; return this; } /** * Set the a method that will construct the entity we are loading. This is used in case there are is not a no-arg * constructor for the entity. */ public void setConstructorCallable(Callable<T> constructorCallable) { this.constructorCallable = constructorCallable; } /** * Set the a method that will construct the entity we are loading. This is used in case there are is not a no-arg * constructor for the entity. Alternative way to do {@link #setConstructorCallable(Callable)}. */ public CsvProcessor<T> withConstructorCallable(Callable<T> constructorCallable) { this.constructorCallable = constructorCallable; return this; } /** * String that separates columns in out CSV input and output. */ public void setColumnSeparator(char columnSeparator) { this.columnSeparator = columnSeparator; } /** * String that separates columns in out CSV input and output. Alternative way to do * {@link #setColumnSeparator(char)}. */ public CsvProcessor<T> withColumnSeparator(char columnSeparator) { this.columnSeparator = columnSeparator; return this; } /** * Quote character that is used to wrap each column. */ public void setColumnQuote(char columnQuote) { this.columnQuote = columnQuote; } /** * Quote character that is used to wrap each column. Alternative way to do {@link #setColumnQuote(char)}. */ public CsvProcessor<T> withColumnQuote(char columnQuote) { this.columnQuote = columnQuote; return this; } /** * Sets the character which is written at the end of the row. Default is to use * System.getProperty("line.separator");. */ public void setLineTermination(String lineTermination) { this.lineTermination = lineTermination; } /** * Sets the character which is written at the end of the row. Default is to use * System.getProperty("line.separator");. Alternative way to do {@link #setLineTermination(String)}. */ public CsvProcessor<T> withLineTermination(String lineTermination) { this.lineTermination = lineTermination; return this; } public void setAllowPartialLines(boolean allowPartialLines) { this.allowPartialLines = allowPartialLines; } public CsvProcessor<T> withAllowPartialLines(boolean allowPartialLines) { this.allowPartialLines = allowPartialLines; return this; } /** * Set to true to always call {@link String#trim()} on data input columns to remove any spaces from the start or * end. */ public void setAlwaysTrimInput(boolean alwaysTrimInput) { this.alwaysTrimInput = alwaysTrimInput; } /** * Set to true to always call {@link String#trim()} on data input columns to remove any spaces from the start or * end. Alternative way to do {@link #setAlwaysTrimInput(boolean)}. */ public CsvProcessor<T> withAlwaysTrimInput(boolean alwaysTrimInput) { this.alwaysTrimInput = alwaysTrimInput; return this; } /** * Set to false to not validate the header when it is read in. Default is true. */ public void setHeaderValidation(boolean headerValidation) { this.headerValidation = headerValidation; } /** * Set to false to not validate the header when it is read in. Default is true. */ public CsvProcessor<T> withHeaderValidation(boolean headerValidation) { this.headerValidation = headerValidation; return this; } /** * Set to false if the first line is a header line to be processed. Default is true. */ public void setFirstLineHeader(boolean firstLineHeader) { this.firstLineHeader = firstLineHeader; } /** * Set to false if the first line is a header line to be processed. Default is true. */ public CsvProcessor<T> withFirstLineHeader(boolean firstLineHeader) { this.firstLineHeader = firstLineHeader; return this; } /** * Set the column name matcher class which will be used to see if the column from the CSV file matches the * definition name. This can be used if you have optional suffix characters such as "*" or something. Default is * {@link String#equals(Object)}. */ public void setColumnNameMatcher(ColumnNameMatcher columnNameMatcher) { this.columnNameMatcher = columnNameMatcher; } /** * Set the column name matcher class which will be used to see if the column from the CSV file matches the * definition name. This can be used if you have optional suffix characters such as "*" or something. Default is * {@link String#equals(Object)}. */ public CsvProcessor<T> withColumnNameMatcher(ColumnNameMatcher columnNameMatcher) { this.columnNameMatcher = columnNameMatcher; return this; } /** * Set to true if the order of the input columns is flexible and does not have to match the order of the definition * fields in the entity. The order is determined by the header columns so their must be a header. Default is false. * * <b>WARNING:</b> If you are using flexible ordering, this CsvProcessor cannot be used with multiple files at the * same time since the column orders are dynamic depending on the input file being read. */ public void setFlexibleOrder(boolean flexibleOrder) { this.flexibleOrder = flexibleOrder; } /** * Set to true if the order of the input columns is flexible and does not have to match the order of the definition * fields in the entity. The order is determined by the header columns so their must be a header. Default is false. * * <b>WARNING:</b> If you are using flexible ordering, this CsvProcessor cannot be used with multiple files at the * same time since the column orders are dynamic depending on the input file being read. */ public CsvProcessor<T> withFlexibleOrder(boolean flexibleOrder) { this.flexibleOrder = flexibleOrder; return this; } /** * Set to true to ignore columns that are not know to the configuration. Default is to raise an error. * * <b>WARNING:</b> If you are using unknown columns, this CsvProcessor cannot be used with multiple files at the * same time since the column position is dynamic depending on the input file being read. */ public void setIgnoreUnknownColumns(boolean ignoreUnknownColumns) { this.ignoreUnknownColumns = ignoreUnknownColumns; } /** * Set to true to ignore columns that are not know to the configuration. Default is to raise an error. * * <b>WARNING:</b> If you are using unknown columns, this CsvProcessor cannot be used with multiple files at the * same time since the column position is dynamic depending on the input file being read. */ public CsvProcessor<T> withIgnoreUnknownColumns(boolean ignoreUnknownColumns) { this.ignoreUnknownColumns = ignoreUnknownColumns; return this; } /** * Set the validator which will validate each entity after it has been parsed. */ public void setRowValidator(RowValidator<T> rowValidator) { this.rowValidator = rowValidator; } /** * Set the validator which will validate each entity after it has been parsed. */ public CsvProcessor<T> withRowValidator(RowValidator<T> rowValidator) { this.rowValidator = rowValidator; return this; } private boolean validateHeaderColumns(String[] columns, ParseError parseError, int lineNumber) { boolean result = true; Map<String, ColumnInfo<Object>> columnNameToInfoMap = new HashMap<String, ColumnInfo<Object>>(); for (ColumnInfo<Object> columnInfo : allColumnInfos) { columnNameToInfoMap.put(columnInfo.getColumnName(), columnInfo); } Map<Integer, ColumnInfo<Object>> columnPositionInfoMap = new HashMap<Integer, ColumnInfo<Object>>(); int lastColumnInfoPosition = -1; for (int i = 0; i < columns.length; i++) { String headerColumn = columns[i]; ColumnInfo<Object> matchedColumnInfo = null; if (columnNameMatcher == null) { matchedColumnInfo = columnNameToInfoMap.get(headerColumn); } else { // have to do a N^2 search because we are using a matcher not just string equals for (ColumnInfo<Object> columnInfo : allColumnInfos) { if (columnNameMatcher.matchesColumnName(columnInfo.getColumnName(), headerColumn)) { matchedColumnInfo = columnInfo; break; } } } if (matchedColumnInfo == null) { if (!ignoreUnknownColumns) { if (parseError != null) { parseError.setErrorType(ErrorType.INVALID_HEADER); parseError.setMessage("column name '" + headerColumn + "' is unknown"); parseError.setLineNumber(lineNumber); } result = false; } } else { if (!flexibleOrder && matchedColumnInfo.getPosition() <= lastColumnInfoPosition) { if (parseError != null) { parseError.setErrorType(ErrorType.INVALID_HEADER); parseError.setMessage("column name '" + headerColumn + "' is not in the proper order"); assignParseErrorFields(parseError, matchedColumnInfo, null); parseError.setLineNumber(lineNumber); } result = false; } else { lastColumnInfoPosition = matchedColumnInfo.getPosition(); } // remove it from the map once we've matched with it columnNameToInfoMap.remove(matchedColumnInfo.getColumnName()); columnPositionInfoMap.put(i, matchedColumnInfo); } } // did the column position information change if (!columnPositionInfoMap.equals(this.columnPositionInfoMap)) { this.columnPositionInfoMap = columnPositionInfoMap; } // now look for must-be-supplied columns for (ColumnInfo<Object> columnInfo : columnNameToInfoMap.values()) { if (columnInfo.isMustBeSupplied()) { if (parseError != null) { parseError.setErrorType(ErrorType.INVALID_HEADER); parseError.setMessage( "column '" + columnInfo.getColumnName() + "' must be supplied and was not specified"); assignParseErrorFields(parseError, columnInfo, null); parseError.setLineNumber(lineNumber); } result = false; } } // if we have an error then reset the columnCount if (!result) { resetColumnPositionInfoMap(); } return result; } private String[] processHeader(String line, ParseError parseError, int lineNumber) throws ParseException { StringBuilder sb = new StringBuilder(32); int linePos = 0; ParseError localParseError = parseError; if (localParseError == null) { localParseError = new ParseError(); } List<String> headerColumns = new ArrayList<String>(); while (true) { boolean atEnd = (linePos == line.length()); localParseError.reset(); sb.setLength(0); if (linePos < line.length() && line.charAt(linePos) == columnQuote) { linePos = processQuotedColumn(line, lineNumber, linePos, null, null, sb, localParseError); } else { linePos = processUnquotedColumn(line, lineNumber, linePos, null, null, sb, localParseError); } if (localParseError.isError()) { if (localParseError == parseError) { // if we pass in an error then it gets set and we return null return null; } else { // if no error passed in then we throw throw new ParseException("Problems parsing header line at position " + linePos + " (" + localParseError + "): " + line, linePos); } } if (sb.length() > 0) { headerColumns.add(sb.toString()); } if (atEnd) { break; } } return headerColumns.toArray(new String[headerColumns.size()]); } private T processRow(String line, ParseError parseError, int lineNumber) throws ParseException { T entity = processRowInner(line, parseError, lineNumber); if (entity != null && rowValidator != null) { ParseError localParseError = parseError; if (localParseError == null) { localParseError = new ParseError(); } try { rowValidator.validateRow(line, lineNumber, entity, localParseError); } catch (ParseException pe) { if (localParseError != parseError) { throw pe; } localParseError.setErrorType(ErrorType.INVALID_ENTITY); localParseError.setMessage(pe.getMessage()); } } if (parseError != null && parseError.isError()) { if (parseError.getLine() == null) { parseError.setLine(line); } if (parseError.getLineNumber() == 0) { parseError.setLineNumber(lineNumber); } if (parseError.getMessage() == null) { parseError.setMessage(parseError.getErrorType().getTypeMessage()); } // force the entity to be null entity = null; } return entity; } private T processRowInner(String line, ParseError parseError, int lineNumber) throws ParseException { T target = constructEntity(); int linePos = 0; ParseError localParseError = parseError; if (localParseError == null) { localParseError = new ParseError(); } int columnCount = 0; while (true) { ColumnInfo<Object> columnInfo = columnPositionInfoMap.get(columnCount); if (columnInfo == null && !ignoreUnknownColumns) { break; } // we have to do this because a blank column may be ok boolean atEnd = (linePos == line.length()); localParseError.reset(); if (linePos < line.length() && line.charAt(linePos) == columnQuote) { linePos = processQuotedColumn(line, lineNumber, linePos, columnInfo, target, null, localParseError); } else { linePos = processUnquotedColumn(line, lineNumber, linePos, columnInfo, target, null, localParseError); } if (localParseError.isError()) { if (localParseError == parseError) { // parseError has the error information return null; } else { throw new ParseException( "Problems parsing line at position " + linePos + " for type " + columnInfo.getType().getSimpleName() + " (" + localParseError + "): " + line, linePos); } } columnCount++; if (atEnd) { break; } // NOTE: we can't break here if we are at the end of line because might be blank column } if (columnCount < columnPositionInfoMap.size() && !allowPartialLines) { if (parseError == null) { throw new ParseException("Line does not have " + columnPositionInfoMap.size() + " columns: " + line, linePos); } else { parseError.setErrorType(ErrorType.TRUNCATED_LINE); parseError.setMessage("Line does not have " + columnPositionInfoMap.size() + " columns"); parseError.setLinePos(linePos); return null; } } if (linePos < line.length() && !ignoreUnknownColumns) { if (parseError == null) { throw new ParseException( "Line has extra information past last column at position " + linePos + ": " + line, linePos); } else { parseError.setErrorType(ErrorType.TOO_MANY_COLUMNS); parseError.setMessage("Line has extra information past last column at position " + linePos); parseError.setLinePos(linePos); return null; } } return target; } private T constructEntity() throws ParseException { try { if (constructorCallable == null) { return constructor.newInstance(); } else { return constructorCallable.call(); } } catch (Exception e) { ParseException parseException = new ParseException("Could not construct instance of " + entityClass, 0); parseException.initCause(e); throw parseException; } } private void checkEntityConfig() { if (allColumnInfos == null) { configureEntityClass(); } } private void configureEntityClass() { if (entityClass == null) { throw new IllegalStateException("Entity class not configured for CSV processor"); } Map<String, ColumnInfo<Object>> fieldNameMap = new LinkedHashMap<String, ColumnInfo<Object>>(); for (Class<?> clazz = entityClass; clazz != Object.class; clazz = clazz.getSuperclass()) { for (Field field : clazz.getDeclaredFields()) { if (fieldNameMap.containsKey(field.getName())) { continue; } CsvField csvField = field.getAnnotation(CsvField.class); CsvColumn csvColumn = field.getAnnotation(CsvColumn.class); if (csvField == null && csvColumn == null) { continue; } addColumnInfo(fieldNameMap, csvColumn, csvField, field.getName(), field.getType(), field, null, null); field.setAccessible(true); } } // now process the get/set methods Map<String, Method> otherMethodMap = new HashMap<String, Method>(); for (Class<?> clazz = entityClass; clazz != Object.class; clazz = clazz.getSuperclass()) { for (Method method : clazz.getMethods()) { CsvColumn csvColumn = method.getAnnotation(CsvColumn.class); if (csvColumn == null) { continue; } Method getMethod = null; Method setMethod = null; String fieldName = method.getName(); if (fieldName.length() > 3 && fieldName.startsWith("get")) { fieldName = Character.toLowerCase(fieldName.charAt(3)) + fieldName.substring(4); getMethod = method; } else if (fieldName.length() > 2 && fieldName.startsWith("is")) { fieldName = Character.toLowerCase(fieldName.charAt(2)) + fieldName.substring(3); getMethod = method; } else if (fieldName.length() > 3 && fieldName.startsWith("set")) { fieldName = Character.toLowerCase(fieldName.charAt(3)) + fieldName.substring(4); setMethod = method; } if (fieldNameMap.containsKey(fieldName)) { continue; } Method otherMethod = otherMethodMap.remove(fieldName); if (otherMethod == null) { otherMethodMap.put(fieldName, method); continue; } // figure out which method is the right one if (getMethod == null) { getMethod = otherMethod; } else { setMethod = otherMethod; } // test the types if (getMethod.getReturnType() == null || getMethod.getReturnType() == void.class) { throw new IllegalStateException("Get method must return a type, not void: " + getMethod); } Class<?>[] setParamTypes = setMethod.getParameterTypes(); if (setParamTypes.length != 1) { throw new IllegalStateException("Get method must have exactly 1 argument: " + setMethod); } if (setParamTypes[0] != getMethod.getReturnType()) { throw new IllegalStateException("Get method return type " + getMethod.getReturnType() + " should match set method parameter type " + setParamTypes[0] + " for field " + fieldName); } // NOTE: it is the CsvColumn on the 2nd method that is really the one that is used addColumnInfo(fieldNameMap, csvColumn, null, fieldName, getMethod.getReturnType(), null, getMethod, setMethod); } } if (!otherMethodMap.isEmpty()) { Method firstMethod = otherMethodMap.values().iterator().next(); throw new IllegalStateException( "Must mark both the get/is and set methods with CsvColumn annotation, not just: " + firstMethod); } if (fieldNameMap.isEmpty()) { throw new IllegalArgumentException("Could not find any exposed CSV fields in: " + entityClass); } this.allColumnInfos = assignColumnPositions(fieldNameMap); resetColumnPositionInfoMap(); if (constructorCallable == null) { try { this.constructor = entityClass.getConstructor(); } catch (Exception e) { throw new IllegalStateException( "No callable configured or could not find public no-arg constructor for: " + entityClass); } } } private List<ColumnInfo<Object>> assignColumnPositions(Map<String, ColumnInfo<Object>> fieldNameMap) { // run through the columns and track the columns that come after others Map<ColumnInfo<Object>, ColumnInfo<Object>> afterMap = new HashMap<ColumnInfo<Object>, ColumnInfo<Object>>(); Set<ColumnInfo<Object>> afterDestSet = new HashSet<ColumnInfo<Object>>(); for (ColumnInfo<Object> columnInfo : fieldNameMap.values()) { if (columnInfo.getAfterColumn() == null) { continue; } // lookup the column by name ColumnInfo<Object> previousColumnInfo = fieldNameMap.get(columnInfo.getAfterColumn()); if (previousColumnInfo == null) { throw new IllegalArgumentException( "Could not find an after column with the name: " + columnInfo.getAfterColumn()); } /* * Add this to the end of the fields already in the after list for this field (first one wins). We track the * field number so we don't get into some sort of infinite loop. */ int fieldCount = 0; while (true) { ColumnInfo<Object> previousNext = afterMap.get(previousColumnInfo); if (previousNext == null) { break; } previousColumnInfo = previousNext; if (++fieldCount > fieldNameMap.size()) { throw new IllegalStateException( "Some sort of after-column loop has been detected, check all after-column settings"); } } afterMap.put(previousColumnInfo, columnInfo); afterDestSet.add(columnInfo); } // go back and build our list of column infos List<ColumnInfo<Object>> columnInfos = new ArrayList<ColumnInfo<Object>>(fieldNameMap.size()); for (ColumnInfo<Object> columnInfo : fieldNameMap.values()) { // if the column does not come after any other column then spit it out in order if (afterDestSet.contains(columnInfo)) { continue; } // also spit out any of the columns that come after it according to after-column for (; columnInfo != null; columnInfo = afterMap.get(columnInfo)) { columnInfos.add(columnInfo); if (columnInfos.size() > fieldNameMap.size()) { throw new IllegalStateException( "Some sort of after-column loop has been detected, check all after-column settings"); } } } /* * Now we need to make sure that we don't have a gap in the after-column points. This could happen because of: * value1, value2 comes after value3, value3 comes after value2. */ if (columnInfos.size() < fieldNameMap.size()) { throw new IllegalStateException("Some sort of after-column gap has been detected because only configured " + columnInfos.size() + " fields but expected " + fieldNameMap.size()); } int fieldCount = 0; for (ColumnInfo<Object> columnInfo : columnInfos) { columnInfo.setPosition(fieldCount++); } return columnInfos; } private void addColumnInfo(Map<String, ColumnInfo<Object>> fieldNameMap, CsvColumn csvColumn, CsvField csvField, String fieldName, Class<?> type, Field field, Method getMethod, Method setMethod) { Converter<?, ?> converter = converterMap.get(type); // test for the enum converter specifically if (converter == null && type.isEnum()) { converter = EnumConverter.getSingleton(); } // NOTE: converter could be null in which case the CsvColumn.converterClass must be set @SuppressWarnings("unchecked") Converter<Object, Object> castConverter = (Converter<Object, Object>) converter; ColumnInfo<Object> columnInfo; @SuppressWarnings("unchecked") Class<Object> castType = (Class<Object>) type; if (csvField == null) { columnInfo = ColumnInfo.fromAnnotation(csvColumn, fieldName, castType, field, getMethod, setMethod, castConverter); } else { columnInfo = ColumnInfo.fromAnnotation(csvField, fieldName, castType, field, getMethod, setMethod, castConverter); } fieldNameMap.put(columnInfo.getColumnName(), columnInfo); } private void resetColumnPositionInfoMap() { Map<Integer, ColumnInfo<Object>> columnPositionInfoMap = new HashMap<Integer, ColumnInfo<Object>>(); int columnCount = 0; for (ColumnInfo<Object> columnInfo : allColumnInfos) { columnPositionInfoMap.put(columnCount, columnInfo); columnCount++; } this.columnPositionInfoMap = columnPositionInfoMap; } private int processQuotedColumn(String line, int lineNumber, int linePos, ColumnInfo<Object> columnInfo, Object target, StringBuilder headerSb, ParseError parseError) { // linePos is pointing at the first quote, move past it linePos++; int columnStart = linePos; int sectionStart = linePos; int sectionEnd = linePos; StringBuilder sb = null; while (linePos < line.length()) { // look for the next quote sectionEnd = line.indexOf(columnQuote, linePos); if (sectionEnd < 0) { parseError.setErrorType(ErrorType.TRUNCATED_COLUMN); parseError.setMessage("Column not terminated with quote '" + columnQuote + "'"); assignParseErrorFields(parseError, columnInfo, null); parseError.setLinePos(linePos); return line.length(); } linePos = sectionEnd + 1; if (linePos == line.length()) { break; } else if (line.charAt(linePos) == columnSeparator) { linePos++; break; } // must have a quote following a quote if there wasn't a columnSeparator if (line.charAt(linePos) != columnQuote) { parseError.setErrorType(ErrorType.INVALID_FORMAT); parseError.setMessage( "quote '" + columnQuote + "' is not followed up separator '" + columnSeparator + "'"); assignParseErrorFields(parseError, columnInfo, null); parseError.setLinePos(linePos); return linePos; } sectionEnd = linePos; // move past possibly end quote linePos++; if (linePos == line.length()) { break; } if (line.charAt(linePos) == columnSeparator) { // move past the comma linePos++; break; } // need to build the string dynamically now if (sb == null) { sb = new StringBuilder(32); } // add to the string-builder the column + 1 quote sb.append(line, sectionStart, sectionEnd); // line-pos is pointing past 2nd (maybe 3rd) quote sectionStart = linePos; } if (sb == null) { if (headerSb == null) { String columnStr = line.substring(sectionStart, sectionEnd); if (columnInfo != null) { extractAndAssignValue(line, lineNumber, columnInfo, columnStr, columnStart, target, parseError); } } else { headerSb.append(line, sectionStart, sectionEnd); } } else { sb.append(line, sectionStart, sectionEnd); String str = sb.toString(); if (headerSb == null) { if (columnInfo != null) { extractAndAssignValue(str, lineNumber, columnInfo, str, columnStart, target, parseError); } } else { headerSb.append(str); } } return linePos; } private int processUnquotedColumn(String line, int lineNumber, int linePos, ColumnInfo<Object> columnInfo, Object target, StringBuilder headerSb, ParseError parseError) { int columnStart = linePos; linePos = line.indexOf(columnSeparator, columnStart); if (linePos < 0) { linePos = line.length(); } if (headerSb == null) { String columnStr = line.substring(columnStart, linePos); if (columnInfo != null) { extractAndAssignValue(line, lineNumber, columnInfo, columnStr, columnStart, target, parseError); } } else { headerSb.append(line, columnStart, linePos); } if (linePos < line.length()) { // skip over the separator linePos++; } return linePos; } private void writeQuoted(StringBuilder sb, String str) { sb.append(columnQuote); int start = 0; while (true) { int linePos = str.indexOf(columnQuote, start); if (linePos < 0) { sb.append(str, start, str.length()); break; } // move past the quote so we can output it linePos++; sb.append(str, start, linePos); // output another quote sb.append(columnQuote); start = linePos; } sb.append(columnQuote); } /** * Extract a value from the line, convert it into its java equivalent, and assign it to our target object. */ private void extractAndAssignValue(String line, int lineNumber, ColumnInfo<Object> columnInfo, String columnStr, int linePos, Object target, ParseError parseError) { Object value = extractValue(line, lineNumber, columnInfo, columnStr, linePos, target, parseError); if (value == null) { assignParseErrorFields(parseError, columnInfo, columnStr); // either error or no value return; } try { columnInfo.setValue(target, value); } catch (Exception e) { parseError.setErrorType(ErrorType.INTERNAL_ERROR); parseError .setMessage("setting value for field '" + columnInfo.getFieldName() + "' error: " + e.getMessage()); assignParseErrorFields(parseError, columnInfo, columnStr); parseError.setLinePos(linePos); } } /** * Extract a value from the line and convert it into its java equivalent. */ private Object extractValue(String line, int lineNumber, ColumnInfo<Object> columnInfo, String columnStr, int linePos, Object target, ParseError parseError) { Converter<Object, ?> converter = columnInfo.getConverter(); if (alwaysTrimInput || columnInfo.isTrimInput() || converter.isAlwaysTrimInput()) { columnStr = columnStr.trim(); } if (columnStr.isEmpty() && columnInfo.getDefaultValue() != null) { columnStr = columnInfo.getDefaultValue(); } if (columnStr.isEmpty() && columnInfo.isMustNotBeBlank()) { parseError.setErrorType(ErrorType.MUST_NOT_BE_BLANK); parseError.setMessage("field '" + columnInfo.getFieldName() + "' must not be blank"); assignParseErrorFields(parseError, columnInfo, columnStr); parseError.setLinePos(linePos); return null; } try { return converter.stringToJava(line, lineNumber, linePos, columnInfo, columnStr, parseError); } catch (ParseException e) { parseError.setErrorType(ErrorType.INVALID_FORMAT); parseError.setMessage("field '" + columnInfo.getFieldName() + "' parse-error: " + e.getMessage()); parseError.setLinePos(linePos); return null; } catch (Exception e) { parseError.setErrorType(ErrorType.INTERNAL_ERROR); parseError.setMessage("field '" + columnInfo.getFieldName() + "' error: " + e.getMessage()); parseError.setLinePos(linePos); return null; } } private void assignParseErrorFields(ParseError parseError, ColumnInfo<Object> columnInfo, String columnStr) { if (parseError != null && parseError.isError() && columnInfo != null) { parseError.setColumnName(columnInfo.getColumnName()); if (columnStr != null) { parseError.setColumnValue(columnStr); } parseError.setColumnType(columnInfo.getType()); } } private int getLineNumber(BufferedReader bufferedReader) { if (bufferedReader instanceof BufferedReaderLineCounter) { return ((BufferedReaderLineCounter) bufferedReader).getLineCount(); } else { return 1; } } }
package com.jomofisher.cmakeify; import com.jomofisher.cmakeify.CMakeify.OSType; import com.jomofisher.cmakeify.model.ArchiveUrl; import com.jomofisher.cmakeify.model.HardNameDependency; import com.jomofisher.cmakeify.model.OS; import com.jomofisher.cmakeify.model.RemoteArchive; import com.jomofisher.cmakeify.model.Toolset; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.util.Collection; import java.util.HashMap; import java.util.Map; public class BashScriptBuilder extends ScriptBuilder { final private static String ABORT_LAST_FAILED = "rc=$?; if [[ $rc != 0 ]]; then exit $rc; fi"; final private static String TOOLS_FOLDER = ".cmakeify/tools"; final private static String DOWNLOADS_FOLDER = ".cmakeify/downloads"; final private StringBuilder body = new StringBuilder(); final private Map<String, String> zips = new HashMap<>(); final private OSType hostOS; final private File workingFolder; final private File rootBuildFolder; final private File zipsFolder; final private File cdepFile; final private File androidFolder; final private String targetGroupId; final private String targetArtifactId; final private String targetVersion; BashScriptBuilder( OSType hostOS, File workingFolder, String targetGroupId, String targetArtifactId, String targetVersion) { this.hostOS = hostOS; this.workingFolder = workingFolder; this.rootBuildFolder = new File(workingFolder, "build"); this.zipsFolder = new File(rootBuildFolder, "zips"); this.cdepFile = new File(zipsFolder, "cdep-manifest.yml"); this.androidFolder = new File(rootBuildFolder, "Android"); this.targetGroupId = targetGroupId; this.targetArtifactId = targetArtifactId; this.targetVersion = targetVersion; } private BashScriptBuilder body(String format, Object... args) { body.append(String.format(format + "\n", args)); return this; } private BashScriptBuilder cdep(String format, Object... args) { String embed = String.format(format, args); body.append(String.format("printf \"%%s\\r\\n\" \"%s\" >> %s \n", embed, cdepFile)); return this; } @Override ScriptBuilder createEmptyBuildFolder(HardNameDependency dependencies[]) { body("rm -rf %s", rootBuildFolder); body("mkdir -p %s", zipsFolder); body("mkdir -p %s/", TOOLS_FOLDER); body("mkdir -p %s/", DOWNLOADS_FOLDER); cdep("# Generated by CMakeify"); cdep("coordinate:"); cdep(" groupId: %s", targetGroupId); cdep(" artifactId: %s", targetArtifactId); cdep(" version: %s", targetVersion); if (dependencies != null && dependencies.length > 0) { cdep("dependencies:"); for (HardNameDependency dependency : dependencies) { cdep(" - compile: %s", dependency.compile); cdep(" sha256: %s", dependency.sha256); } } return this; } private ArchiveUrl getHostArchive(RemoteArchive remote) { switch (hostOS) { case Linux: return remote.linux; case MacOS: return remote.darwin; } throw new RuntimeException(hostOS.toString()); } @Override ScriptBuilder download(RemoteArchive remote) { ArchiveInfo archive = new ArchiveInfo(getHostArchive(remote)); return body(archive.downloadToFolder(DOWNLOADS_FOLDER)) .body(archive.uncompressToFolder(DOWNLOADS_FOLDER, TOOLS_FOLDER)); } @Override File writeToShellScript() { BufferedWriter writer = null; File file = new File(".cmakeify/build.sh"); file.getAbsoluteFile().mkdirs(); file.delete(); try { writer = new BufferedWriter(new FileWriter(file)); writer.write(body.toString()); } catch (Exception e) { e.printStackTrace(); } finally { try { // Close the writer regardless of what happens... writer.close(); } catch (Exception e) { } } return file; } @Override ScriptBuilder checkForCompilers(Collection<String> compilers) { for (String compiler : compilers) { body("if [[ -z \"$(which %s)\" ]]; then", compiler); body(" echo CMAKEIFY ERROR: Missing %s. Please install.", compiler); body(" exit 100"); body("fi"); } return this; } @Override ScriptBuilder cmakeAndroid(String cmakeVersion, RemoteArchive cmakeRemote, String androidCppFlags, String flavor, String flavorFlags, String ndkVersion, RemoteArchive ndkRemote, String includes[], String lib, String compiler, String runtime, String platform, String abis[], boolean multipleFlavors, boolean multipleCMake, boolean multipleNDK, boolean multipleCompiler, boolean multipleRuntime, boolean multiplePlatforms) { body("echo Executing script for %s %s %s %s %s", flavor, ndkVersion, platform, compiler, runtime); String cmakeExe = String.format("%s/%s/bin/cmake", TOOLS_FOLDER, getHostArchive(cmakeRemote).unpackroot); File outputFolder = androidFolder; String zipName = targetArtifactId + "-android"; if (multipleCMake) { outputFolder = new File(outputFolder, "cmake-" + cmakeVersion); zipName += "-cmake-" + cmakeVersion; } if (multipleNDK) { outputFolder = new File(outputFolder, ndkVersion); zipName += "-" + ndkVersion; } if (multipleCompiler) { outputFolder = new File(outputFolder, compiler); zipName += "-" + compiler; } if (multipleRuntime) { String fixedRuntime = runtime.replace('+', 'x'); outputFolder = new File(outputFolder, fixedRuntime); zipName += "-" + fixedRuntime; } if (multiplePlatforms) { outputFolder = new File(outputFolder, "android-" + platform); zipName += "-platform-" + platform; } if (multipleFlavors) { outputFolder = new File(outputFolder, "flavor-" + flavor); zipName += "-" + flavor; } zipName += ".zip"; File zip = new File(zipsFolder, zipName).getAbsoluteFile(); File buildFolder = new File(outputFolder, "cmake-generated-files"); String ndkFolder = String .format("%s/%s", TOOLS_FOLDER, getHostArchive(ndkRemote).unpackroot); File redistFolder = new File(outputFolder, "redist").getAbsoluteFile(); File stagingFolder = new File(outputFolder, "staging").getAbsoluteFile(); body("ABIS="); for (String abi : abis) { File abiBuildFolder = new File(buildFolder, abi); File archFolder = new File(String.format("%s/platforms/android-%s/arch-%s", new File(ndkFolder).getAbsolutePath(), platform, Abi.getByName(abi).getArchitecture())); body("if [ -d '%s' ]; then", archFolder); body(" echo Creating make project in %s", abiBuildFolder); body(" if [[ \"$ABIS\" == \"\" ]]; then"); body(" ABIS=%s", abi); body(" else"); body(" ABIS=\"${ABIS}, %s\"", abi); body(" fi"); String stagingAbiFolder = String.format("%s/lib/%s", stagingFolder, abi); String command = String.format( "%s \\\n" + " -H%s \\\n" + " -B%s \\\n" + " -DCMAKE_ANDROID_NDK_TOOLCHAIN_VERSION=%s \\\n" + " -DCMAKE_ANDROID_NDK_TOOLCHAIN_DEBUG=1 \\\n" + " -DCMAKE_SYSTEM_NAME=Android \\\n" + " -DCMAKE_SYSTEM_VERSION=%s \\\n" + " -DCMAKEIFY_REDIST_INCLUDE_DIRECTORY=%s/include \\\n" + " -DCMAKE_LIBRARY_OUTPUT_DIRECTORY=%s \\\n" + " -DCMAKE_ARCHIVE_OUTPUT_DIRECTORY=%s \\\n" + " -DCMAKE_ANDROID_STL_TYPE=%s_static \\\n" + " -DCMAKE_ANDROID_NDK=%s \\\n" + " -DCMAKE_ANDROID_ARCH_ABI=%s %s %s\n", cmakeExe, workingFolder, abiBuildFolder, compiler, platform, redistFolder, stagingAbiFolder, stagingAbiFolder, runtime, new File(ndkFolder).getAbsolutePath(), abi, flavorFlags, androidCppFlags); body(" echo Executing %s", command); body(" " + command); body(" " + ABORT_LAST_FAILED); body(String.format(" %s --build %s -- -j8", cmakeExe, abiBuildFolder)); body(" " + ABORT_LAST_FAILED); String stagingLib = String.format("%s/%s", stagingAbiFolder, lib); String redistAbiFolder = String.format("%s/lib/%s", redistFolder, abi); if (lib != null && lib.length() > 0) { body(" if [ -f '%s' ]; then", stagingLib); body(" mkdir -p %s", redistAbiFolder); body(" cp %s %s/%s", stagingLib, redistAbiFolder, lib); body(" " + ABORT_LAST_FAILED); body(" else"); body(" echo CMAKEIFY ERROR: CMake build did not produce %s", lib); body(" exit 100"); body(" fi"); } body("else"); body(" echo Build skipped ABI %s because arch folder didnt exist: %s", abi, archFolder); body("fi"); zips.put(zip.getAbsolutePath(), redistFolder.getPath()); } body("if [ -d '%s' ]; then", stagingFolder); // Create a folder with something in it so there'e always something to zip body(" mkdir -p %s", redistFolder); body(" echo %s %s %s %s %s %s > %s/cmakeify.txt", cmakeVersion, flavor, ndkVersion, platform, compiler, runtime, redistFolder); if (includes != null) { for (String include : includes) { body(" if [ ! -d '%s/%s' ]; then", workingFolder, include); body(" echo CMAKEIFY ERROR: Extra include folder '%s/%s' does not exist", workingFolder, include); body(" exit 600"); body(" fi"); body(" pushd %s", workingFolder); body(" find %s -name '*.h' | cpio -pdm %s", include, redistFolder); body(" find %s -name '*.hpp' | cpio -pdm %s", include, redistFolder); body(" popd"); body(" " + ABORT_LAST_FAILED); } } body(" if [ -f '%s' ]; then", zip); body(" echo CMAKEIFY ERROR: Android zip %s would be overwritten", zip); body(" exit 400"); body(" fi"); body(" pushd %s", redistFolder); body(" " + ABORT_LAST_FAILED); body(" zip %s . -r", zip); body(" " + ABORT_LAST_FAILED); body(" if [ -f '%s' ]; then", zip); body(" echo Zip %s was created", zip); body(" else"); body(" echo CMAKEIFY ERROR: Zip %s was not created", zip); body(" exit 402"); body(" fi"); body(" popd"); body(" " + ABORT_LAST_FAILED); body(" SHASUM256=$(shasum -a 256 %s | awk '{print $1}')", zip); body(" ARCHIVESIZE=$(du %s | awk '{print $1}'", zip); body(" " + ABORT_LAST_FAILED); cdep(" - lib: %s", lib); cdep(" file: %s", zip.getName()); cdep(" sha256: $SHASUM256"); cdep(" size: $ARCHIVESIZE"); if (multipleFlavors) { cdep(" flavor: %s", flavor); } cdep(" runtime: %s", runtime); cdep(" platform: %s", platform); cdep(" ndk: %s", ndkVersion); cdep(" abis: [ ${ABIS} ]"); if (multipleCompiler) { cdep(" compiler: %s", compiler); } if (multipleCMake) { cdep(" builder: cmake-%s", cmakeVersion); } if (lib == null || lib.length() > 0) { body("else"); body(" echo CMAKEIFY ERROR: Build did not produce an output in %s", stagingFolder); body(" exit 200"); } body("fi"); return this; } @Override ScriptBuilder cmakeLinux( String cmakeVersion, RemoteArchive cmakeRemote, Toolset toolset, boolean multipleCMake, boolean multipleCompiler) { String cmakeExe = String.format("%s/%s/bin/cmake", TOOLS_FOLDER, getHostArchive(cmakeRemote).unpackroot); File outputFolder = new File(rootBuildFolder, "Linux"); String zipName = targetArtifactId + "-linux"; if (multipleCMake) { outputFolder = new File(outputFolder, "cmake-" + cmakeVersion); zipName += "-cmake-" + cmakeVersion; } if (multipleCompiler) { outputFolder = new File(outputFolder, toolset.c); zipName += "-" + toolset.c; } zipName += ".zip"; File zip = new File(zipsFolder, zipName).getAbsoluteFile(); File buildFolder = new File(outputFolder, "cmake-generated-files"); File redistFolder = new File(outputFolder, "redist").getAbsoluteFile(); body("echo Building to %s", outputFolder); body("mkdir --parents %s/include", redistFolder); body(String.format( "%s \\\n" + " -H%s \\\n" + " -B%s \\\n" + " -DCMAKEIFY_REDIST_INCLUDE_DIRECTORY=%s/include \\\n" + " -DCMAKE_LIBRARY_OUTPUT_DIRECTORY=%s/lib \\\n" + " -DCMAKE_ARCHIVE_OUTPUT_DIRECTORY=%s/lib \\\n" + " -DCMAKE_SYSTEM_NAME=Linux \\\n" + " -DCMAKE_C_COMPILER=%s \\\n" + " -DCMAKE_CXX_COMPILER=%s", cmakeExe, workingFolder, buildFolder, redistFolder, redistFolder, redistFolder, toolset.c, toolset.cxx)); body(String.format("%s --build %s -- -j8", cmakeExe, buildFolder)); body(ABORT_LAST_FAILED); zips.put(zip.getAbsolutePath(), redistFolder.getPath()); body("# Zip Linux redist if folder was created in %s", redistFolder); body("if [ -d '%s' ]; then", redistFolder); body(" if [ -f '%s' ]; then", zip); body(" echo CMAKEIFY ERROR: Linux zip %s would be overwritten", zip); body(" exit 500"); body(" fi"); body(" pushd %s", redistFolder); body(" " + ABORT_LAST_FAILED); body(" zip %s . -r", zip); body(" " + ABORT_LAST_FAILED); body(" if [ -f '%s' ]; then", zip); body(" echo Zip %s was created", zip); body(" else"); body(" echo CMAKEIFY ERROR: Zip %s was not created", zip); body(" exit 402"); body(" fi"); body(" popd"); body(" " + ABORT_LAST_FAILED); body(" SHASUM256=$(shasum -a 256 %s | awk '{print $1}')", zip); body(" " + ABORT_LAST_FAILED); body("fi"); return this; } @Override ScriptBuilder startBuilding(OS target) { switch(target) { case android: cdep("android:"); cdep(" archives:"); return this; case linux: cdep("linux:"); return this; case windows: cdep("windows:"); return this; } throw new RuntimeException(target.toString()); } @Override ScriptBuilder buildRedistFiles(File workingFolder, String[] includes, String example) { if (example != null && example.length() > 0) { cdep("example: |"); String lines[] = example.split("\\r?\\n"); for (String line : lines) { cdep(" %s", line); } } body("cat %s", cdepFile); body("echo - %s", cdepFile); for(String zip : zips.keySet()) { String relativeZip = new File(".").toURI().relativize(new File(zip).toURI()).getPath(); body("if [ -f '%s' ]; then", relativeZip); body(" echo - %s", relativeZip); body("fi"); } return this; } @Override ScriptBuilder uploadBadges() { // Record build information String badgeUrl = String.format("%s:%s:%s", targetGroupId, targetArtifactId, targetVersion); badgeUrl = badgeUrl.replace(":", "%3A"); badgeUrl = badgeUrl.replace("-", " badgeUrl = String.format("https://img.shields.io/badge/cdep-%s-brightgreen.svg", badgeUrl); String badgeFolder = String.format("%s/%s", targetGroupId, targetArtifactId); body("if [ -n \"$TRAVIS_TAG\" ]; then"); body(" if [ -n \"$CDEP_BADGES_API_KEY\" ]; then"); body(" git clone https://github.com/cdep-io/cdep-io.github.io.git"); body(" pushd cdep-io.github.io"); body(" mkdir -p %s/latest", badgeFolder); body(" echo curl %s > %s/latest/latest.svg ", badgeUrl, badgeFolder); body(" curl %s > %s/latest/latest.svg ", badgeUrl, badgeFolder); body(" " + ABORT_LAST_FAILED); body(" git add %s/latest/latest.svg", badgeFolder); body(" git -c user.name='cmakeify' -c user.email='cmakeify' commit -m init"); body(" git push -f -q https://cdep-io:$CDEP_BADGES_API_KEY@github.com/cdep-io/cdep-io.github.io &2>/dev/null"); body(" popd"); body(" else"); body(" echo Add CDEP_BADGES_API_KEY to Travis settings to get badges!"); body(" fi"); body("fi"); return this; } @Override public String toString() { return body.toString(); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.laytonsmith.core.functions; import com.laytonsmith.abstraction.StaticLayer; import com.laytonsmith.core.*; import com.laytonsmith.core.constructs.*; import com.laytonsmith.core.exceptions.CancelCommandException; import com.laytonsmith.core.exceptions.ConfigRuntimeException; import com.laytonsmith.core.exceptions.ProgramFlowManipulationException; import com.laytonsmith.core.functions.Exceptions.ExceptionType; import java.text.SimpleDateFormat; import java.util.Date; import java.util.concurrent.atomic.AtomicInteger; /** * * @author Layton */ public class Scheduling { public static void ClearScheduledRunners(){ StaticLayer.ClearAllRunnables(); } public static String docs(){ return "This class contains methods for dealing with time and server scheduling."; } @api public static class time extends AbstractFunction{ public String getName() { return "time"; } public Integer[] numArgs() { return new Integer[]{0}; } public String docs() { return "int {} Returns the current unix time stamp, in milliseconds. The resolution of this is not guaranteed to be extremely accurate. If " + "you need extreme accuracy, use nano_time()"; } public ExceptionType[] thrown() { return new ExceptionType[]{}; } public boolean isRestricted() { return false; } public void varList(IVariableList varList) {} public boolean preResolveVariables() { return true; } public CHVersion since() { return CHVersion.V3_1_0; } public Boolean runAsync() { return null; } public Construct exec(Target t, Env env, Construct... args) throws CancelCommandException, ConfigRuntimeException { return new CInt(System.currentTimeMillis(), t); } } @api public static class nano_time extends AbstractFunction{ public String getName() { return "nano_time"; } public Integer[] numArgs() { return new Integer[]{0}; } public String docs() { return "int {} Returns an arbitrary number based on the most accurate clock available on this system. Only useful when compared to other calls" + " to nano_time(). The return is in nano seconds. See the Java API on System.nanoTime() for more information on the usage of this function."; } public ExceptionType[] thrown() { return new ExceptionType[]{}; } public boolean isRestricted() { return false; } public void varList(IVariableList varList) {} public boolean preResolveVariables() { return true; } public CHVersion since() { return CHVersion.V3_1_0; } public Boolean runAsync() { return null; } public Construct exec(Target t, Env env, Construct... args) throws CancelCommandException, ConfigRuntimeException { return new CInt(System.nanoTime(), t); } } public static class sleep extends AbstractFunction { public String getName() { return "sleep"; } public Integer[] numArgs() { return new Integer[]{1}; } public String docs() { return "void {seconds} Sleeps the script for the specified number of seconds, up to the maximum time limit defined in the preferences file." + " Seconds may be a double value, so 0.5 would be half a second." + " PLEASE NOTE: Sleep times are NOT very accurate, and should not be relied on for preciseness."; } public ExceptionType[] thrown() { return new ExceptionType[]{ExceptionType.CastException}; } public boolean isRestricted() { return true; } public void varList(IVariableList varList) { } public boolean preResolveVariables() { return true; } public CHVersion since() { return CHVersion.V3_1_0; } public Construct exec(Target t, Env env, Construct... args) throws CancelCommandException, ConfigRuntimeException { // if (Thread.currentThread().getName().equals("Server thread")) { // throw new ConfigRuntimeException("sleep() cannot be run in the main server thread", // null, t); // Construct x = args[0]; // double time = Static.getNumber(x); // Integer i = (Integer) (Prefs.); // if (i > time || i <= 0) { // try { // Thread.sleep((int)(time * 1000)); // } catch (InterruptedException ex) { // } else { // throw new ConfigRuntimeException("The value passed to sleep must be less than the server defined value of " + i + " seconds or less.", // ExceptionType.RangeException, t); return new CVoid(t); } public Boolean runAsync() { //Because we stop the thread return true; } } @api public static class set_interval extends AbstractFunction{ public String getName() { return "set_interval"; } public Integer[] numArgs() { return new Integer[]{2, 3}; } public String docs() { return "int {timeInMS, [initialDelayInMS,] closure} Sets a task to run every so often. This works similarly to set_timeout," + " except the task will automatically re-register itself to run again. Note that the resolution" + " of the time is in ms, however, the server will only have a resolution of up to 50 ms, meaning" + " that a time of 1-50ms is essentially the same as 50ms. The inital delay defaults to the same" + " thing as timeInMS, that is, there will be a pause between registration and initial firing. However," + " this can be set to 0 (or some other number) to adjust how long of a delay there is before it begins."; } public ExceptionType[] thrown() { return new ExceptionType[]{ExceptionType.CastException}; } public boolean isRestricted() { return true; } public boolean preResolveVariables() { return true; } public Boolean runAsync() { return false; } public Construct exec(Target t, Env environment, Construct... args) throws ConfigRuntimeException { long time = Static.getInt(args[0]); int offset = 0; long delay = time; if(args.length == 3){ offset = 1; delay = Static.getInt(args[1]); } if(!(args[1 + offset] instanceof CClosure)){ throw new ConfigRuntimeException(getName() + " expects a closure to be sent as the second argument", ExceptionType.CastException, t); } final CClosure c = (CClosure) args[1 + offset]; final AtomicInteger ret = new AtomicInteger(-1); ret.set(StaticLayer.SetFutureRepeater(time, delay, new Runnable(){ public void run(){ c.getEnv().SetCustom("timeout-id", ret.get()); try{ c.execute(null); } catch(ConfigRuntimeException e){ ConfigRuntimeException.React(e); } catch(CancelCommandException e){ } catch(ProgramFlowManipulationException e){ ConfigRuntimeException.DoWarning("Using a program flow manipulation construct improperly! " + e.getClass().getSimpleName()); } } })); return new CInt(ret.get(), t); } public CHVersion since() { return CHVersion.V3_3_1; } } @api public static class set_timeout extends AbstractFunction{ public String getName() { return "set_timeout"; } public Integer[] numArgs() { return new Integer[]{2}; } public String docs() { return "int {timeInMS, closure} Sets a task to run in the specified number of ms in the future." + " The task will only run once. Note that the resolution" + " of the time is in ms, however, the server will only have a resolution of up to 50 ms, meaning" + " that a time of 1-50ms is essentially the same as 50ms."; } public ExceptionType[] thrown() { return new ExceptionType[]{ExceptionType.CastException}; } public boolean isRestricted() { return true; } public boolean preResolveVariables() { return true; } public Boolean runAsync() { return false; } public Construct exec(Target t, Env environment, Construct... args) throws ConfigRuntimeException { long time = Static.getInt(args[0]); if(!(args[1] instanceof CClosure)){ throw new ConfigRuntimeException(getName() + " expects a closure to be sent as the second argument", ExceptionType.CastException, t); } final CClosure c = (CClosure) args[1]; final AtomicInteger ret = new AtomicInteger(-1); ret.set(StaticLayer.SetFutureRunnable(time, new Runnable(){ public void run(){ c.getEnv().SetCustom("timeout-id", ret.get()); try{ c.execute(null); } catch(ConfigRuntimeException e){ ConfigRuntimeException.React(e); } catch(CancelCommandException e){ } catch(ProgramFlowManipulationException e){ ConfigRuntimeException.DoWarning("Using a program flow manipulation construct improperly! " + e.getClass().getSimpleName()); } } })); return new CInt(ret.get(), t); } public CHVersion since() { return CHVersion.V3_3_1; } } @api public static class clear_task extends AbstractFunction{ public String getName() { return "clear_task"; } public Integer[] numArgs() { return new Integer[]{0, 1}; } public String docs() { return "void {[id]} Stops the interval or timeout that is specified. The id can be gotten by" + " storing the integer returned from either set_timeout or set_interval." + " An invalid id is simply ignored. Also note that you can cancel an interval" + " (and technically a timeout, though this is pointless) from within the interval" + " by using the cancel function. This clear_task function is more useful for set_timeout, where" + " you may queue up some task to happen in the far future, yet have some trigger to" + " prevent it from happening. ID is optional, but only if called from within a set_interval or set_timeout" + " closure, in which case it defaults to the id of that particular task."; } public ExceptionType[] thrown() { return new ExceptionType[]{ExceptionType.CastException, ExceptionType.InsufficientArgumentsException}; } public boolean isRestricted() { return true; } public boolean preResolveVariables() { return true; } public Boolean runAsync() { return null; } public Construct exec(Target t, Env environment, Construct... args) throws ConfigRuntimeException { if(args.length == 0 && environment.GetCustom("timeout-id") != null){ StaticLayer.ClearFutureRunnable((Integer)environment.GetCustom("timeout-id")); } else if(args.length == 1){ StaticLayer.ClearFutureRunnable((int)Static.getInt(args[0])); } else { throw new ConfigRuntimeException("No id was passed to clear_task, and it's not running inside a task either.", ExceptionType.InsufficientArgumentsException, t); } return new CVoid(t); } public CHVersion since() { return CHVersion.V3_3_1; } } @api public static class date extends AbstractFunction{ public String getName() { return "date"; } public Integer[] numArgs() { return new Integer[]{1, 2}; } public String docs() { return "mixed {format} Returns a date of the current time in the format you give."; } public ExceptionType[] thrown() { return new ExceptionType[]{}; } public boolean isRestricted() { return false; } public void varList(IVariableList varList) {} public boolean preResolveVariables() { return true; } public CHVersion since() { return CHVersion.V3_3_1; } public Boolean runAsync() { return null; } public Construct exec(Target t, Env env, Construct... args) throws CancelCommandException, ConfigRuntimeException { Date now = new Date(); SimpleDateFormat dateFormat = new SimpleDateFormat(args[0].toString()); return new CString(dateFormat.format(now), t); } } }
package com.maddyhome.idea.vim.group; import com.intellij.execution.ExecutionException; import com.intellij.execution.configurations.GeneralCommandLine; import com.intellij.execution.process.CapturingProcessHandler; import com.intellij.execution.process.ProcessAdapter; import com.intellij.execution.process.ProcessEvent; import com.intellij.execution.process.ProcessOutput; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressIndicatorProvider; import com.intellij.openapi.progress.ProgressManager; import com.intellij.util.execution.ParametersListUtil; import com.intellij.util.text.CharSequenceReader; import com.maddyhome.idea.vim.KeyHandler; import com.maddyhome.idea.vim.VimPlugin; import com.maddyhome.idea.vim.command.Command; import com.maddyhome.idea.vim.command.CommandState; import com.maddyhome.idea.vim.ex.ExException; import com.maddyhome.idea.vim.ex.InvalidCommandException; import com.maddyhome.idea.vim.helper.UiHelper; import com.maddyhome.idea.vim.ui.ex.ExEntryPanel; import com.maddyhome.idea.vim.vimscript.Executor; import com.maddyhome.idea.vim.vimscript.model.datatypes.VimString; import com.maddyhome.idea.vim.vimscript.services.OptionService; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.io.*; import java.util.ArrayList; public class ProcessGroup { public String getLastCommand() { return lastCommand; } public void startSearchCommand(@NotNull Editor editor, DataContext context, int count, char leader) { if (editor.isOneLineMode()) // Don't allow searching in one line editors { return; } String initText = ""; String label = String.valueOf(leader); ExEntryPanel panel = ExEntryPanel.getInstance(); panel.activate(editor, context, label, initText, count); } public @NotNull String endSearchCommand(final @NotNull Editor editor) { ExEntryPanel panel = ExEntryPanel.getInstance(); panel.deactivate(true); return panel.getText(); } public void startExCommand(@NotNull Editor editor, DataContext context, @NotNull Command cmd) { // Don't allow ex commands in one line editors if (editor.isOneLineMode()) return; String initText = getRange(editor, cmd); CommandState.getInstance(editor).pushModes(CommandState.Mode.CMD_LINE, CommandState.SubMode.NONE); ExEntryPanel panel = ExEntryPanel.getInstance(); panel.activate(editor, context, ":", initText, 1); } public boolean processExKey(Editor editor, @NotNull KeyStroke stroke) { // This will only get called if somehow the key focus ended up in the editor while the ex entry window // is open. So I'll put focus back in the editor and process the key. ExEntryPanel panel = ExEntryPanel.getInstance(); if (panel.isActive()) { UiHelper.requestFocus(panel.getEntry()); panel.handleKey(stroke); return true; } else { CommandState.getInstance(editor).popModes(); KeyHandler.getInstance().reset(editor); return false; } } public boolean processExEntry(final @NotNull Editor editor, final @NotNull DataContext context) { ExEntryPanel panel = ExEntryPanel.getInstance(); panel.deactivate(true); boolean res = true; try { CommandState.getInstance(editor).popModes(); logger.debug("processing command"); final String text = panel.getText(); if (!panel.getLabel().equals(":")) { // Search is handled via Argument.Type.EX_STRING. Although ProcessExEntryAction is registered as the handler for // <CR> in both command and search modes, it's only invoked for command mode (see KeyHandler.handleCommandNode). // We should never be invoked for anything other than an actual ex command. throw new InvalidCommandException("Expected ':' command. Got '" + panel.getLabel() + "'", text); } if (logger.isDebugEnabled()) logger.debug("swing=" + SwingUtilities.isEventDispatchThread()); Executor.INSTANCE.execute(text, editor, context, false, true, null); } catch (ExException e) { VimPlugin.showMessage(e.getMessage()); VimPlugin.indicateError(); res = false; } catch (Exception bad) { ProcessGroup.logger.error(bad); VimPlugin.indicateError(); res = false; } return res; } public void cancelExEntry(final @NotNull Editor editor, boolean resetCaret) { CommandState.getInstance(editor).popModes(); KeyHandler.getInstance().reset(editor); ExEntryPanel panel = ExEntryPanel.getInstance(); panel.deactivate(true, resetCaret); } public void startFilterCommand(@NotNull Editor editor, DataContext context, @NotNull Command cmd) { String initText = getRange(editor, cmd) + "!"; CommandState.getInstance(editor).pushModes(CommandState.Mode.CMD_LINE, CommandState.SubMode.NONE); ExEntryPanel panel = ExEntryPanel.getInstance(); panel.activate(editor, context, ":", initText, 1); } private @NotNull String getRange(Editor editor, @NotNull Command cmd) { String initText = ""; if (CommandState.getInstance(editor).getMode() == CommandState.Mode.VISUAL) { initText = "'<,'>"; } else if (cmd.getRawCount() > 0) { if (cmd.getCount() == 1) { initText = "."; } else { initText = ".,.+" + (cmd.getCount() - 1); } } return initText; } public @Nullable String executeCommand(@NotNull Editor editor, @NotNull String command, @Nullable CharSequence input, @Nullable String currentDirectoryPath) throws ExecutionException, ProcessCanceledException { // This is a much simplified version of how Vim does this. We're using stdin/stdout directly, while Vim will // redirect to temp files ('shellredir' and 'shelltemp') or use pipes. We don't support 'shellquote', because we're // not handling redirection, but we do use 'shellxquote' and 'shellxescape', because these have defaults that work // better with Windows. We also don't bother using ShellExecute for Windows commands beginning with `start`. // Finally, we're also not bothering with the crazy space and backslash handling of the 'shell' options content. return ProgressManager.getInstance().runProcessWithProgressSynchronously(() -> { final String shell = ((VimString) VimPlugin.getOptionService().getOptionValue(OptionService.Scope.GLOBAL.INSTANCE, "shell", "shell")).getValue(); final String shellcmdflag = ((VimString) VimPlugin.getOptionService().getOptionValue(OptionService.Scope.GLOBAL.INSTANCE, "shellcmdflag", "shellcmdflag")).getValue(); final String shellxescape = ((VimString) VimPlugin.getOptionService().getOptionValue(OptionService.Scope.GLOBAL.INSTANCE, "shellxescape", "shellxescape")).getValue(); final String shellxquote = ((VimString) VimPlugin.getOptionService().getOptionValue(OptionService.Scope.GLOBAL.INSTANCE, "shellxquote", "shellxquote")).getValue(); // For Win32. See :help 'shellxescape' final String escapedCommand = shellxquote.equals("(") ? doEscape(command, shellxescape, "^") : command; // Required for Win32+cmd.exe, defaults to "(". See :help 'shellxquote' final String quotedCommand = shellxquote.equals("(") ? "(" + escapedCommand + ")" : (shellxquote.equals("\"(") ? "\"(" + escapedCommand + ")\"" : shellxquote + escapedCommand + shellxquote); final ArrayList<String> commands = new ArrayList<>(); commands.add(shell); if (!shellcmdflag.isEmpty()) { // Note that Vim also does a simple whitespace split for multiple parameters commands.addAll(ParametersListUtil.parse(shellcmdflag)); } commands.add(quotedCommand); if (logger.isDebugEnabled()) { logger.debug(String.format("shell=%s shellcmdflag=%s command=%s", shell, shellcmdflag, quotedCommand)); } final GeneralCommandLine commandLine = new GeneralCommandLine(commands); if (currentDirectoryPath != null) { commandLine.setWorkDirectory(currentDirectoryPath); } final CapturingProcessHandler handler = new CapturingProcessHandler(commandLine); if (input != null) { handler.addProcessListener(new ProcessAdapter() { @Override public void startNotified(@NotNull ProcessEvent event) { try { final CharSequenceReader charSequenceReader = new CharSequenceReader(input); final BufferedWriter outputStreamWriter = new BufferedWriter(new OutputStreamWriter(handler.getProcessInput())); copy(charSequenceReader, outputStreamWriter); outputStreamWriter.close(); } catch (IOException e) { logger.error(e); } } }); } final ProgressIndicator progressIndicator = ProgressIndicatorProvider.getInstance().getProgressIndicator(); final ProcessOutput output = handler.runProcessWithProgressIndicator(progressIndicator); lastCommand = command; if (output.isCancelled()) { // TODO: Vim will use whatever text has already been written to stdout // For whatever reason, we're not getting any here, so just throw an exception throw new ProcessCanceledException(); } final Integer exitCode = handler.getExitCode(); if (exitCode != null && exitCode != 0) { VimPlugin.showMessage("shell returned " + exitCode); VimPlugin.indicateError(); } return output.getStderr() + output.getStdout(); }, "IdeaVim - !" + command, true, editor.getProject()); } private String doEscape(String original, String charsToEscape, String escapeChar) { String result = original; for (char c : charsToEscape.toCharArray()) { result = result.replace("" + c, escapeChar + c); } return result; } // TODO: Java 10 has a transferTo method we could use instead private void copy(@NotNull Reader from, @NotNull Writer to) throws IOException { char[] buf = new char[2048]; int cnt; while ((cnt = from.read(buf)) != -1) { to.write(buf, 0, cnt); } } private String lastCommand; private static final Logger logger = Logger.getInstance(ProcessGroup.class.getName()); }
package ualberta.g12.adventurecreator; import java.util.List; /** * Controller that dictates all fragment methods. Is responsible for all modification within a fragment. * Contains code that allows the user to add, edit or delete, the illustrations, text or choices within * a fragment. * */ public class FragmentController implements FController { @Override /** * Edit the current title in place of the fragment * * @param frag fragment reference corresponding to the current fragment * @param newTitle title that has been previously stated */ public void editTitle(Fragment frag, String newTitle){ frag.setTitle(newTitle); } @Override /** * Allows the user to add a text segment to the current fragment. * * @param frag fragment reference corresponding to the current fragment * @param textSegment reference to the text of the current segment * @param dispNum refers to the position of the text segment */ public boolean addTextSegment(Fragment frag, String textSegment, int dispNum){ List<String> textSegments = frag.getTextSegments(); List<String> displayOrder = frag.getDisplayOrder(); //check for invalid dispNum if (displayOrder.size()<dispNum) return false; //Insert the text segment int textSegNum=0; for (int i=0; i<dispNum;i++){ if (displayOrder.get(i).equals("t")) textSegNum++; } if (textSegments.size()==textSegNum){ textSegments.add(textSegment); } else { textSegments.add(textSegNum, textSegment); } //insert t into corresponding spot in display order displayOrder.add(dispNum, "t"); frag.setDisplayOrder(displayOrder); frag.setTextSegments(textSegments); return true; } /** * Removes the text segment at the given dispNum * returns true if successful * * @param frag fragment reference corresponding to the current fragment * @param dispNum refers to the position of the text segment */ private boolean deleteTextSegment(Fragment frag, int dispNum){ List<String> textSegments = frag.getTextSegments(); List<String> displayOrder = frag.getDisplayOrder(); //not a text segment at dispNum if (!displayOrder.get(dispNum).equals("t")) return false; int textSegNum=0; for (int i=0; i<dispNum;i++){ if (displayOrder.get(i).equals("t")) textSegNum++; } textSegments.remove(textSegNum); frag.setTextSegments(textSegments); displayOrder.remove(dispNum); frag.setDisplayOrder(displayOrder); return true; } @Override /** * allows the author to add an illustration into a fragment * * @param frag fragment reference corresponding to the current fragment * @param illustration refers to the illustration that has been previously saved * @param dispNum refers to the position of the text segment * */ public boolean addIllustration(Fragment frag, String illustration, int dispNum){ List<String> illustrations = frag.getIllustrations(); List<String> displayOrder = frag.getDisplayOrder(); System.out.println("add ill start2"); //check for invalid dispNum if (displayOrder.size()<dispNum) return false; System.out.println("ill 3"); //Insert the text segment int illNum=0; for (int i=0; i<dispNum;i++){ if (displayOrder.get(i).equals("i")) illNum++; } System.out.println("illNum "+illNum); if (illustrations.size()==illNum){ illustrations.add(illustration); } else { illustrations.add(illNum, illustration); } //insert t into corresponding spot in display order displayOrder.add(dispNum, "i"); frag.setDisplayOrder(displayOrder); frag.setIllustrations(illustrations); System.out.println("ill disord "+displayOrder.toString()); System.out.println("ill size "+illustrations.size()); return true; } /** * Removes the illustration at the given dispNum * returns true if successful * * @param frag fragment reference corresponding to the current fragment * @param dispNum refers to the position of the text segment */ private boolean deleteIllustration(Fragment frag, int dispNum){ List<String> illustrations = frag.getIllustrations(); List<String> displayOrder = frag.getDisplayOrder(); //not an illustration at dispNum if (!displayOrder.get(dispNum).equals("i")) return false; int illustrationNum=0; for (int i=0; i<dispNum;i++){ if (displayOrder.get(i).equals("i")) illustrationNum++; } illustrations.remove(illustrationNum); frag.setIllustrations(illustrations); displayOrder.remove(dispNum); frag.setDisplayOrder(displayOrder); return true; } // @Override // public void addSound(Fragment frag, Sound sound){ // LinkedList<Sound> sounds = frag.getSounds(); // sounds.add(sound); // frag.setSounds(sounds); // LinkedList<String> displayOrder = frag.getDisplayOrder(); // displayOrder.add("s"); // frag.setDisplayOrder(displayOrder); // @Override // public void addVideo(Fragment frag, Video video){ // LinkedList<Video> videos = frag.getVideos(); // videos.add(video); // frag.setVideos(videos); // LinkedList<String> displayOrder = frag.getDisplayOrder(); // displayOrder.add("v"); // frag.setDisplayOrder(displayOrder); @Override /** * Allows the user to add a choice to the fragment. This will allow the user to link two * fragments together. * * @param frag fragment reference corresponding to the current fragment * @param cho reference to the old choice within that position (null if new) */ public void addChoice(Fragment frag, Choice cho){ List<Choice> choices = frag.getChoices(); choices.add(cho); frag.setChoices(choices); List<String> displayOrder = frag.getDisplayOrder(); displayOrder.add("c"); frag.setDisplayOrder(displayOrder); } /** * Removes the Choice at the given dispNum * returns true if successful * * @param frag fragment reference corresponding to the current fragment * @param dispNum refers to the position of the text segment */ private boolean deleteChoice(Fragment frag, int dispNum){ List<String> textSegments = frag.getTextSegments(); List<String> displayOrder = frag.getDisplayOrder(); //not a text segment at dispNum if (!displayOrder.get(dispNum).equals("c")) return false; int choiceNum=0; for (int i=0; i<dispNum;i++){ if (displayOrder.get(i).equals("c")) choiceNum++; } textSegments.remove(choiceNum); frag.setTextSegments(textSegments); displayOrder.remove(dispNum); frag.setDisplayOrder(displayOrder); return true; } @Override /** * adds a new element into the listview so that a segment can be added. * * @param frag fragment reference corresponding to the current fragment */ public void addEmptyPart(Fragment frag){ List<String> displayOrder = frag.getDisplayOrder(); displayOrder.add("e"); frag.setDisplayOrder(displayOrder); } @Override /** * deletes the selected segment when the user desires to delete a segment. * * @param frag fragment reference corresponding to the current fragment */ public void removeEmptyPart(Fragment frag){ List<String> displayOrder = frag.getDisplayOrder(); displayOrder.remove("e"); frag.setDisplayOrder(displayOrder); } // @Override // public void addAnnotation(Fragment frag, Annotation annotation){ // Annotation annotations = frag.getAnnotations(); // annotations.addAnnotation(annotation); // frag.setAnnotations(annotations); @Override public void deleteFragmentPart(Fragment frag, int partNum){ List<String> displayOrder = frag.getDisplayOrder(); //check for invalid partNum if (partNum >= displayOrder.size()) return; String type = displayOrder.get(partNum); if (type.equals("t")) deleteTextSegment(frag, partNum); else if (type.equals("i")) deleteIllustration(frag, partNum); else if (type.equals("c")) deleteChoice(frag, partNum); else if (type.equals("e")) removeEmptyPart(frag); } }
package com.minelittlepony.render.layer; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.entity.RenderLivingBase; import net.minecraft.entity.EntityLivingBase; import net.minecraft.util.ResourceLocation; import org.lwjgl.opengl.GL11; import com.google.common.collect.Lists; import com.minelittlepony.model.AbstractPonyModel; import com.minelittlepony.model.BodyPart; import com.minelittlepony.model.gear.IGear; import com.minelittlepony.model.gear.IStackable; import com.minelittlepony.model.gear.Muffin; import com.minelittlepony.model.gear.SaddleBags; import com.minelittlepony.model.gear.Stetson; import com.minelittlepony.model.gear.WitchHat; import java.util.HashMap; import java.util.List; import java.util.Map; public class LayerGear<T extends EntityLivingBase> extends AbstractPonyLayer<T> { private static List<IGear> gears = Lists.newArrayList( new SaddleBags(), new WitchHat(), new Muffin(), new Stetson() ); public LayerGear(RenderLivingBase<T> renderer) { super(renderer); } @Override protected void doPonyRender(T entity, float move, float swing, float partialTicks, float ticks, float headYaw, float headPitch, float scale) { if (entity.isInvisible()) { return; } AbstractPonyModel model = getPlayerModel(); Map<BodyPart, Float> renderStackingOffsets = new HashMap<>(); for (IGear gear : gears) { if (gear.canRender(model, entity)) { GlStateManager.pushMatrix(); model.transform(gear.getGearLocation()); gear.getOriginBodyPart(model).postRender(scale); if (gear instanceof IStackable) { BodyPart part = gear.getGearLocation(); renderStackingOffsets.compute(part, (k, v) -> { float offset = ((IStackable)gear).getStackingOffset(); if (v != null) { GlStateManager.translate(0, -v, 0); offset += v; } return offset; }); } renderGear(model, entity, gear, move, swing, scale, ticks); GlStateManager.popMatrix(); } } } private void renderGear(AbstractPonyModel model, T entity, IGear gear, float move, float swing, float scale, float ticks) { GL11.glPushAttrib(GL11.GL_ALL_ATTRIB_BITS); ResourceLocation texture = gear.getTexture(entity); if (texture != null) { getRenderer().bindTexture(texture); } gear.setLivingAnimations(model, entity); gear.setRotationAndAngles(model.isGoingFast(), move, swing, model.getWobbleAmount(), ticks); gear.renderPart(scale); GlStateManager.popAttrib(); } }
package com.ociweb.gl.impl.stage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.ociweb.gl.impl.schema.IngressMessages; import com.ociweb.gl.impl.schema.MessageSubscription; import com.ociweb.pronghorn.network.schema.MQTTClientRequestSchema; import com.ociweb.pronghorn.network.schema.MQTTClientResponseSchema; import com.ociweb.pronghorn.pipe.DataInputBlobReader; import com.ociweb.pronghorn.pipe.DataOutputBlobWriter; import com.ociweb.pronghorn.pipe.Pipe; import com.ociweb.pronghorn.pipe.PipeReader; import com.ociweb.pronghorn.pipe.PipeWriter; import com.ociweb.pronghorn.stage.PronghornStage; import com.ociweb.pronghorn.stage.scheduling.GraphManager; public class IngressMQTTStage extends PronghornStage { private final Pipe<MQTTClientResponseSchema> input; private final Pipe<IngressMessages> output; private final CharSequence[] externalTopic; private final CharSequence[] internalTopic; private final IngressConverter[] converter; private boolean allTopicsMatch; private static final Logger logger = LoggerFactory.getLogger(IngressMQTTStage.class); public static final IngressConverter copyConverter = new IngressConverter() { @Override public void convertData(DataInputBlobReader<?> inputStream, DataOutputBlobWriter<IngressMessages> outputStream) { inputStream.readInto(outputStream, inputStream.available()); } }; public IngressMQTTStage(GraphManager graphManager, Pipe<MQTTClientResponseSchema> input, Pipe<IngressMessages> output, CharSequence[] externalTopic, CharSequence[] internalTopic) { this(graphManager, input, output, externalTopic, internalTopic, asArray(copyConverter, internalTopic.length )); } public IngressMQTTStage(GraphManager graphManager, Pipe<MQTTClientResponseSchema> input, Pipe<IngressMessages> output, CharSequence[] externalTopic, CharSequence[] internalTopic, IngressConverter[] converter) { super(graphManager, input, output); this.input = input; this.output = output; this.externalTopic = externalTopic; this.internalTopic = internalTopic; this.allTopicsMatch = isMatching(internalTopic,externalTopic,converter); this.converter = converter; } private static IngressConverter[] asArray(IngressConverter copyconverter, int length) { IngressConverter[] array = new IngressConverter[length]; while (--length>=0) { array[length] = copyconverter; } return array; } private boolean isMatching(CharSequence[] internalTopic, CharSequence[] externalTopic, IngressConverter[] converter) { assert(internalTopic.length == externalTopic.length); int i = internalTopic.length; while (--i>=0) { CharSequence a = internalTopic[i]; CharSequence b = externalTopic[i]; if (a.length()!=b.length()) { return false; } int j = a.length(); while (--j>=0) { if (a.charAt(j)!=b.charAt(j)) { return false; } } } IngressConverter prototype = converter[0]; int k = converter.length; while(--k>=0) { if (prototype!=converter[k]) { return false; } } return true; } @Override public void run() { while (PipeWriter.hasRoomForWrite(output) && PipeReader.tryReadFragment(input)) { int msgIdx = PipeReader.getMsgIdx(input); switch(msgIdx) { case MQTTClientResponseSchema.MSG_MESSAGE_3: int i = internalTopic.length; if (allTopicsMatch) { i = 0;//to select the common converter for all. PipeWriter.presumeWriteFragment(output, IngressMessages.MSG_PUBLISH_103); //direct copy of topic DataOutputBlobWriter<IngressMessages> stream = PipeWriter.outputStream(output); DataOutputBlobWriter.openField(stream); PipeReader.readUTF8(input, MQTTClientResponseSchema.MSG_MESSAGE_3_FIELD_TOPIC_23, stream); DataOutputBlobWriter.closeHighLevelField(stream, IngressMessages.MSG_PUBLISH_103_FIELD_TOPIC_1); } else { boolean topicMatches = false; while (--i >= 0) { //TODO: this is very bad, swap out with trie parser instead of linear search if (PipeReader.isEqual(input, MQTTClientResponseSchema.MSG_MESSAGE_3_FIELD_TOPIC_23, externalTopic[i])) { topicMatches = true; break; } } assert(topicMatches) : "ERROR, this topic was not known "+PipeReader.readUTF8(input, MQTTClientResponseSchema.MSG_MESSAGE_3_FIELD_TOPIC_23, new StringBuilder()); if (!topicMatches) { logger.warn("Unknown topic from external broker {}",PipeReader.readUTF8(input, MQTTClientResponseSchema.MSG_MESSAGE_3_FIELD_TOPIC_23, new StringBuilder())); break; } PipeWriter.presumeWriteFragment(output, IngressMessages.MSG_PUBLISH_103); //direct copy of topic DataOutputBlobWriter<IngressMessages> stream = PipeWriter.outputStream(output); DataOutputBlobWriter.openField(stream); PipeReader.readUTF8(input, MQTTClientResponseSchema.MSG_MESSAGE_3_FIELD_TOPIC_23, stream); DataOutputBlobWriter.closeHighLevelField(stream, IngressMessages.MSG_PUBLISH_103_FIELD_TOPIC_1); } //copy and convert the data //debug //StringBuilder b = new StringBuilder("IngressMQTTStage "); //System.err.println(PipeReader.readUTF8(input, MQTTClientResponseSchema.MSG_MESSAGE_3_FIELD_PAYLOAD_25 , b)); DataInputBlobReader<MQTTClientResponseSchema> inputStream = PipeReader.inputStream(input, MQTTClientResponseSchema.MSG_MESSAGE_3_FIELD_PAYLOAD_25); DataOutputBlobWriter<IngressMessages> outputStream = PipeWriter.outputStream(output); DataOutputBlobWriter.openField(outputStream); converter[i].convertData(inputStream, outputStream); int length = DataOutputBlobWriter.closeHighLevelField(outputStream, IngressMessages.MSG_PUBLISH_103_FIELD_PAYLOAD_3); PipeWriter.publishWrites(output); break; case MQTTClientResponseSchema.MSG_ERROR_4: int fieldErrorCode = PipeReader.readInt(input,MQTTClientResponseSchema.MSG_ERROR_4_FIELD_ERRORCODE_41); StringBuilder fieldErrorText = PipeReader.readUTF8(input,MQTTClientResponseSchema.MSG_ERROR_4_FIELD_ERRORTEXT_42,new StringBuilder(PipeReader.readBytesLength(input,MQTTClientResponseSchema.MSG_ERROR_4_FIELD_ERRORTEXT_42))); //TODO: what should we do with these errors? break; case -1: requestShutdown(); break; } PipeReader.releaseReadLock(input); } } }
package com.philmander.jstest; /** * @author Michael Meyer */ public class DefaultJsTestLogger implements JsTestLogger { public void log(String message) { System.out.println(message); } public void error(String message) { System.err.println(message); } }
package com.sandwell.JavaSimulation3D; import static com.sandwell.JavaSimulation.Util.formatNumber; import java.util.ArrayList; import java.util.HashMap; import com.jaamsim.input.InputAgent; import com.jaamsim.math.Color4d; import com.sandwell.JavaSimulation.BooleanInput; import com.sandwell.JavaSimulation.BooleanListInput; import com.sandwell.JavaSimulation.BooleanVector; import com.sandwell.JavaSimulation.ColourInput; import com.sandwell.JavaSimulation.DoubleInput; import com.sandwell.JavaSimulation.DoubleListInput; import com.sandwell.JavaSimulation.DoubleVector; import com.sandwell.JavaSimulation.EntityInput; import com.sandwell.JavaSimulation.EntityListInput; import com.sandwell.JavaSimulation.ErrorException; import com.sandwell.JavaSimulation.FileEntity; import com.sandwell.JavaSimulation.Input; import com.sandwell.JavaSimulation.InputErrorException; import com.sandwell.JavaSimulation.IntegerVector; import com.sandwell.JavaSimulation.Keyword; import com.sandwell.JavaSimulation.ProbabilityDistribution; import com.sandwell.JavaSimulation.Process; import com.sandwell.JavaSimulation.Tester; import com.sandwell.JavaSimulation.Vector; /** * Class ModelEntity - JavaSimulation3D */ public class ModelEntity extends DisplayEntity { // Breakdowns @Keyword(desc = "Reliability is defined as:\n" + " 100% - (plant breakdown time / total operation time)\n " + "or\n " + "(Operational Time)/(Breakdown + Operational Time)", example = "Object1 Reliability { 0.95 }") private final DoubleInput availability; protected double hoursForNextFailure; // The number of working hours required before the next breakdown protected double iATFailure; // inter arrival time between failures protected boolean breakdownPending; // true when a breakdown is to occur protected boolean brokendown; // true => entity is presently broken down protected boolean maintenance; // true => entity is presently in maintenance protected boolean associatedBreakdown; // true => entity is presently in Associated Breakdown protected boolean associatedMaintenance; // true => entity is presently in Associated Maintenance protected double breakdownStartTime; // Start time of the most recent breakdown protected double breakdownEndTime; // End time of the most recent breakdown // Breakdown Probability Distributions @Keyword(desc = "A ProbabilityDistribution object that governs the duration of breakdowns (in hours).", example = "Object1 DowntimeDurationDistribution { BreakdownProbDist1 }") private final EntityInput<ProbabilityDistribution> downtimeDurationDistribution; @Keyword(desc = "A ProbabilityDistribution object that governs when breakdowns occur (in hours).", example = "Object1 DowntimeIATDistribution { BreakdownProbDist1 }") private final EntityInput<ProbabilityDistribution> downtimeIATDistribution; // Maintenance @Keyword(desc = "The simulation time for the start of the first maintenance for each maintenance cycle.", example = "Object1 FirstMaintenanceTime { 24 h }") protected DoubleListInput firstMaintenanceTimes; @Keyword(desc = "The time between maintenance activities for each maintenance cycle", example = "Object1 MaintenanceInterval { 168 h }") protected DoubleListInput maintenanceIntervals; @Keyword(desc = "The durations of a single maintenance event for each maintenance cycle.", example = "Object1 MaintenanceDuration { 336 h }") protected DoubleListInput maintenanceDurations; protected IntegerVector maintenancePendings; // Number of maintenance periods that are due @Keyword(desc = "A Boolean value. Allows scheduled maintenances to be skipped if it overlaps " + "with another planned maintenance event.", example = "Object1 SkipMaintenanceIfOverlap { TRUE }") protected BooleanListInput skipMaintenanceIfOverlap; @Keyword(desc = "A list of objects that share the maintenance schedule with this object. " + "In order for the maintenance to start, all objects on this list must be available." + "This keyword is for Handlers and Signal Blocks only.", example = "Block1 SharedMaintenance { Block2 Block2 }") private final EntityListInput<ModelEntity> sharedMaintenanceList; protected ModelEntity masterMaintenanceEntity; // The entity that has maintenance information protected boolean performMaintenanceAfterShipDelayPending; // maintenance needs to be done after shipDelay // Maintenance based on hours of operations @Keyword(desc = "Working time for the start of the first maintenance for each maintenance cycle", example = "Object1 FirstMaintenanceOperatingHours { 1000 2500 h }") private final DoubleListInput firstMaintenanceOperatingHours; @Keyword(desc = "Working time between one maintenance event and the next for each maintenance cycle", example = "Object1 MaintenanceOperatingHoursIntervals { 2000 5000 h }") private final DoubleListInput maintenanceOperatingHoursIntervals; @Keyword(desc = "Duration of maintenance events based on working hours for each maintenance cycle", example = "Ship1 MaintenanceOperatingHoursDurations { 24 48 h }") private final DoubleListInput maintenanceOperatingHoursDurations; protected IntegerVector maintenanceOperatingHoursPendings; // Number of maintenance periods that are due protected DoubleVector hoursForNextMaintenanceOperatingHours; protected double maintenanceStartTime; // Start time of the most recent maintenance protected double maintenanceEndTime; // End time of the most recent maintenance protected DoubleVector nextMaintenanceTimes; // next start time for each maintenance protected double nextMaintenanceDuration; // duration for next maintenance protected DoubleVector lastScheduledMaintenanceTimes; @Keyword(desc = "If maintenance has been deferred by the DeferMaintenanceLookAhead keyword " + "for longer than this time, the maintenance will start even if " + "there is an object within the lookahead. There must be one entry for each " + "defined maintenance schedule if DeferMaintenanceLookAhead is used. This" + "keyword is only used for signal blocks.", example = "Object1 DeferMaintenanceLimit { 50 50 h }") private final DoubleListInput deferMaintenanceLimit; @Keyword(desc = "If the duration of the downtime is longer than this time, equipment will be released", example = "Object1 DowntimeToReleaseEquipment { 1.0 h }") protected final DoubleInput downtimeToReleaseEquipment; @Keyword(desc = "A list of Boolean values corresponding to the maintenance cycles. If a value is TRUE, " + "then routes/tasks are released before performing the maintenance in the cycle.", example = "Object1 ReleaseEquipment { TRUE FALSE FALSE }") protected final BooleanListInput releaseEquipment; @Keyword(desc = "A list of Boolean values corresponding to the maintenance cycles. If a value is " + "TRUE, then maintenance in the cycle can start even if the equipment is presently " + "working.", example = "Object1 ForceMaintenance { TRUE FALSE FALSE }") protected final BooleanListInput forceMaintenance; // Statistics @Keyword(desc = "If TRUE, then statistics for this object are " + "included in the main output report.", example = "Object1 PrintToReport { TRUE }") private final BooleanInput printToReport; // States private static Vector stateList = new Vector( 11, 1 ); // List of valid states private final HashMap<String, StateRecord> stateMap; protected double workingHours; // Accumulated working time spent in working states private double timeOfLastStateChange; private int numberOfCompletedCycles; protected double lastHistogramUpdateTime; // Last time at which a histogram was updated for this entity protected double secondToLastHistogramUpdateTime; // Second to last time at which a histogram was updated for this entity private StateRecord presentState; // The present state of the entity protected FileEntity stateReportFile; // The file to store the state information private String finalLastState = ""; // The final state of the entity (in a sequence of transitional states) private double timeOfLastPrintedState = 0; // The time that the last state printed in the trace state file // Graphics protected final static Color4d breakdownColor = ColourInput.DARK_RED; // Color of the entity in breaking down protected final static Color4d maintenanceColor = ColourInput.RED; // Color of the entity in maintenance static { stateList.addElement( "Idle" ); stateList.addElement( "Working" ); stateList.addElement( "Breakdown" ); stateList.addElement( "Maintenance" ); } { maintenanceDurations = new DoubleListInput("MaintenanceDurations", "Maintenance", new DoubleVector()); maintenanceDurations.setValidRange(0.0d, Double.POSITIVE_INFINITY); maintenanceDurations.setUnits("h"); this.addInput(maintenanceDurations, true, "MaintenanceDuration"); maintenanceIntervals = new DoubleListInput("MaintenanceIntervals", "Maintenance", new DoubleVector()); maintenanceIntervals.setValidRange(0.0d, Double.POSITIVE_INFINITY); maintenanceIntervals.setUnits("h"); this.addInput(maintenanceIntervals, true, "MaintenanceInterval"); firstMaintenanceTimes = new DoubleListInput("FirstMaintenanceTimes", "Maintenance", new DoubleVector()); firstMaintenanceTimes.setValidRange(0.0d, Double.POSITIVE_INFINITY); firstMaintenanceTimes.setUnits("h"); this.addInput(firstMaintenanceTimes, true, "FirstMaintenanceTime"); forceMaintenance = new BooleanListInput("ForceMaintenance", "Maintenance", null); this.addInput(forceMaintenance, true); releaseEquipment = new BooleanListInput("ReleaseEquipment", "Maintenance", null); this.addInput(releaseEquipment, true); availability = new DoubleInput("Reliability", "Breakdowns", 1.0d, 0.0d, 1.0d); this.addInput(availability, true); downtimeIATDistribution = new EntityInput<ProbabilityDistribution>(ProbabilityDistribution.class, "DowntimeIATDistribution", "Breakdowns", null); this.addInput(downtimeIATDistribution, true); downtimeDurationDistribution = new EntityInput<ProbabilityDistribution>(ProbabilityDistribution.class, "DowntimeDurationDistribution", "Breakdowns", null); this.addInput(downtimeDurationDistribution, true); downtimeToReleaseEquipment = new DoubleInput("DowntimeToReleaseEquipment", "Breakdowns", 0.0d, 0.0d, Double.POSITIVE_INFINITY); this.addInput(downtimeToReleaseEquipment, true); skipMaintenanceIfOverlap = new BooleanListInput("SkipMaintenanceIfOverlap", "Maintenance", new BooleanVector()); this.addInput(skipMaintenanceIfOverlap, true); deferMaintenanceLimit = new DoubleListInput("DeferMaintenanceLimit", "Maintenance", null); deferMaintenanceLimit.setValidRange(0.0d, Double.POSITIVE_INFINITY); deferMaintenanceLimit.setUnits("h"); this.addInput(deferMaintenanceLimit, true); sharedMaintenanceList = new EntityListInput<ModelEntity>(ModelEntity.class, "SharedMaintenance", "Maintenance", new ArrayList<ModelEntity>(0)); this.addInput(sharedMaintenanceList, true); firstMaintenanceOperatingHours = new DoubleListInput("FirstMaintenanceOperatingHours", "Maintenance", new DoubleVector()); firstMaintenanceOperatingHours.setValidRange(0.0d, Double.POSITIVE_INFINITY); firstMaintenanceOperatingHours.setUnits("h"); this.addInput(firstMaintenanceOperatingHours, true); maintenanceOperatingHoursDurations = new DoubleListInput("MaintenanceOperatingHoursDurations", "Maintenance", new DoubleVector()); maintenanceOperatingHoursDurations.setValidRange(1e-15, Double.POSITIVE_INFINITY); maintenanceOperatingHoursDurations.setUnits("h"); this.addInput(maintenanceOperatingHoursDurations, true); maintenanceOperatingHoursIntervals = new DoubleListInput("MaintenanceOperatingHoursIntervals", "Maintenance", new DoubleVector()); maintenanceOperatingHoursIntervals.setValidRange(1e-15, Double.POSITIVE_INFINITY); maintenanceOperatingHoursIntervals.setUnits("h"); this.addInput(maintenanceOperatingHoursIntervals, true); printToReport = new BooleanInput("PrintToReport", "Report", true); this.addInput(printToReport, true); } public ModelEntity() { lastHistogramUpdateTime = 0.0; secondToLastHistogramUpdateTime = 0.0; hoursForNextFailure = 0.0; iATFailure = 0.0; maintenancePendings = new IntegerVector( 1, 1 ); maintenanceOperatingHoursPendings = new IntegerVector( 1, 1 ); hoursForNextMaintenanceOperatingHours = new DoubleVector( 1, 1 ); performMaintenanceAfterShipDelayPending = false; lastScheduledMaintenanceTimes = new DoubleVector(); breakdownStartTime = 0.0; breakdownEndTime = Double.POSITIVE_INFINITY; breakdownPending = false; brokendown = false; associatedBreakdown = false; maintenanceStartTime = 0.0; maintenanceEndTime = Double.POSITIVE_INFINITY; maintenance = false; associatedMaintenance = false; workingHours = 0.0; stateMap = new HashMap<String, StateRecord>(); StateRecord idle = new StateRecord("Idle", 0); stateMap.put("idle" , idle); presentState = idle; timeOfLastStateChange = getCurrentTime(); idle.lastStartTimeInState = getCurrentTime(); idle.secondLastStartTimeInState = getCurrentTime(); initStateMap(); } /** * Clear internal properties */ public void clearInternalProperties() { hoursForNextFailure = 0.0; performMaintenanceAfterShipDelayPending = false; breakdownPending = false; brokendown = false; associatedBreakdown = false; maintenance = false; associatedMaintenance = false; workingHours = 0.0; } @Override public void validate() throws InputErrorException { super.validate(); this.validateMaintenance(); Input.validateIndexedLists(firstMaintenanceOperatingHours.getValue(), maintenanceOperatingHoursIntervals.getValue(), "FirstMaintenanceOperatingHours", "MaintenanceOperatingHoursIntervals"); Input.validateIndexedLists(firstMaintenanceOperatingHours.getValue(), maintenanceOperatingHoursDurations.getValue(), "FirstMaintenanceOperatingHours", "MaintenanceOperatingHoursDurations"); if( getAvailability() < 1.0 ) { if( getDowntimeDurationDistribution() == null ) { throw new InputErrorException("When availability is less than one you must define downtimeDurationDistribution in your input file!"); } } if( downtimeIATDistribution.getValue() != null ) { if( getDowntimeDurationDistribution() == null ) { throw new InputErrorException("When DowntimeIATDistribution is set, DowntimeDurationDistribution must also be set."); } } if( skipMaintenanceIfOverlap.getValue().size() > 0 ) Input.validateIndexedLists(firstMaintenanceTimes.getValue(), skipMaintenanceIfOverlap.getValue(), "FirstMaintenanceTimes", "SkipMaintenanceIfOverlap"); if( releaseEquipment.getValue() != null ) Input.validateIndexedLists(firstMaintenanceTimes.getValue(), releaseEquipment.getValue(), "FirstMaintenanceTimes", "ReleaseEquipment"); if( forceMaintenance.getValue() != null ) { Input.validateIndexedLists(firstMaintenanceTimes.getValue(), forceMaintenance.getValue(), "FirstMaintenanceTimes", "ForceMaintenance"); } if(downtimeDurationDistribution.getValue() != null && downtimeDurationDistribution.getValue().getMinimumValue() < 0) throw new InputErrorException("DowntimeDurationDistribution cannot allow negative values"); if(downtimeIATDistribution.getValue() != null && downtimeIATDistribution.getValue().getMinimumValue() < 0) throw new InputErrorException("DowntimeIATDistribution cannot allow negative values"); } @Override public void earlyInit() { super.earlyInit(); if( downtimeDurationDistribution.getValue() != null ) { downtimeDurationDistribution.getValue().initialize(); } if( downtimeIATDistribution.getValue() != null ) { downtimeIATDistribution.getValue().initialize(); } } public int getNumberOfCompletedCycles() { return numberOfCompletedCycles; } // INPUT public void validateMaintenance() { Input.validateIndexedLists(firstMaintenanceTimes.getValue(), maintenanceIntervals.getValue(), "FirstMaintenanceTimes", "MaintenanceIntervals"); Input.validateIndexedLists(firstMaintenanceTimes.getValue(), maintenanceDurations.getValue(), "FirstMaintenanceTimes", "MaintenanceDurations"); for( int i = 0; i < maintenanceIntervals.getValue().size(); i++ ) { if( maintenanceIntervals.getValue().get( i ) < maintenanceDurations.getValue().get( i ) ) { throw new InputErrorException("MaintenanceInterval should be greater than MaintenanceDuration (%f) <= (%f)", maintenanceIntervals.getValue().get(i), maintenanceDurations.getValue().get(i)); } } } // INITIALIZATION METHODS public void clearStatistics() { for( int i = 0; i < getMaintenanceOperatingHoursIntervals().size(); i++ ) { hoursForNextMaintenanceOperatingHours.set( i, hoursForNextMaintenanceOperatingHours.get( i ) - this.getWorkingHours() ); } // Determine the time for the first breakdown event /*if ( downtimeIATDistribution == null ) { if( breakdownSeed != 0 ) { breakdownRandGen.initialiseWith( breakdownSeed ); hoursForNextFailure = breakdownRandGen.getUniformFrom_To( 0.5*iATFailure, 1.5*iATFailure ); } else { hoursForNextFailure = getNextBreakdownIAT(); } } else { hoursForNextFailure = getNextBreakdownIAT(); }*/ } /** * *!*!*!*! OVERLOAD !*!*!*!* * Initialize statistics */ public void initialize() { brokendown = false; maintenance = false; associatedBreakdown = false; associatedMaintenance = false; // Create state trace file if required if (testFlag(FLAG_TRACESTATE)) { String fileName = InputAgent.getReportDirectory() + InputAgent.getRunName() + "-" + this.getName() + ".trc"; stateReportFile = new FileEntity( fileName, FileEntity.FILE_WRITE, false ); } workingHours = 0.0; // Calculate the average downtime duration if distributions are used double average = 0.0; if(getDowntimeDurationDistribution() != null) average = getDowntimeDurationDistribution().getExpectedValue(); // Calculate the average downtime inter-arrival time if( (getAvailability() == 1.0 || average == 0.0) ) { iATFailure = 10.0E10; } else { if( getDowntimeIATDistribution() != null ) { iATFailure = getDowntimeIATDistribution().getExpectedValue(); // Adjust the downtime inter-arrival time to get the specified availability if( ! Tester.equalCheckTolerance( iATFailure, ( (average / (1.0 - getAvailability())) - average ) ) ) { getDowntimeIATDistribution().setValueFactor_For( ( (average / (1.0 - getAvailability())) - average) / iATFailure, this ); iATFailure = getDowntimeIATDistribution().getExpectedValue(); } } else { iATFailure = ( (average / (1.0 - getAvailability())) - average ); } } // Determine the time for the first breakdown event hoursForNextFailure = getNextBreakdownIAT(); this.setPresentState( "Idle" ); brokendown = false; // Start the maintenance network if( firstMaintenanceTimes.getValue().size() != 0 ) { maintenancePendings.fillWithEntriesOf( firstMaintenanceTimes.getValue().size(), 0 ); lastScheduledMaintenanceTimes.fillWithEntriesOf( firstMaintenanceTimes.getValue().size(), Double.POSITIVE_INFINITY ); this.doMaintenanceNetwork(); } // calculate hours for first operating hours breakdown for ( int i = 0; i < getMaintenanceOperatingHoursIntervals().size(); i++ ) { hoursForNextMaintenanceOperatingHours.add( firstMaintenanceOperatingHours.getValue().get( i ) ); maintenanceOperatingHoursPendings.add( 0 ); } } // ACCESSOR METHODS /** * Return the time at which the most recent maintenance is scheduled to end */ public double getMaintenanceEndTime() { return maintenanceEndTime; } /** * Return the time at which a the most recent breakdown is scheduled to end */ public double getBreakdownEndTime() { return breakdownEndTime; } public double getTimeOfLastStateChange() { return timeOfLastStateChange; } /** * Returns the availability proportion. */ public double getAvailability() { return availability.getValue(); } public DoubleListInput getFirstMaintenanceTimes() { return firstMaintenanceTimes; } public boolean getPrintToReport() { return printToReport.getValue(); } /** * Return true if the entity is working */ public boolean isWorking() { return false; } public boolean isBrokendown() { return brokendown; } public boolean isBreakdownPending() { return breakdownPending; } public boolean isInAssociatedBreakdown() { return associatedBreakdown; } public boolean isInMaintenance() { return maintenance; } public boolean isInAssociatedMaintenance() { return associatedMaintenance; } public boolean isInService() { return ( brokendown || maintenance || associatedBreakdown || associatedMaintenance ); } public void setBrokendown( boolean bool ) { brokendown = bool; this.setPresentState(); } public void setMaintenance( boolean bool ) { maintenance = bool; this.setPresentState(); } public void setAssociatedBreakdown( boolean bool ) { associatedBreakdown = bool; } public void setAssociatedMaintenance( boolean bool ) { associatedMaintenance = bool; } public ProbabilityDistribution getDowntimeDurationDistribution() { return downtimeDurationDistribution.getValue(); } public double getDowntimeToReleaseEquipment() { return downtimeToReleaseEquipment.getValue(); } public boolean hasServiceDefined() { return( maintenanceDurations.getValue().size() > 0 || getDowntimeDurationDistribution() != null ); } // HOURS AND STATES public static class StateRecord { String stateName; int index; double initializationHours; double totalHours; double completedCycleHours; double currentCycleHours; double lastStartTimeInState; double secondLastStartTimeInState; public StateRecord(String state, int i) { stateName = state; index = i; } public int getIndex() { return index; } public String getStateName() { return stateName; } public double getTotalHours() { return totalHours; } public double getCompletedCycleHours() { return completedCycleHours; } public double getCurrentCycleHours() { return currentCycleHours; } public double getLastStartTimeInState() { return lastStartTimeInState; } public double getSecondLastStartTimeInState() { return secondLastStartTimeInState; } @Override public String toString() { return getStateName(); } } public void initStateMap() { // Populate the hash map for the states and StateRecord StateRecord idle = getStateRecordFor("Idle"); stateMap.clear(); for (int i = 0; i < getStateList().size(); i++) { String state = (String)getStateList().get(i); if ( state.equals("Idle") ) { idle.index = i; continue; } StateRecord stateRecord = new StateRecord(state, i); stateMap.put(state.toLowerCase() , stateRecord); } stateMap.put("idle", idle); timeOfLastStateChange = getCurrentTime(); } /** * Runs after initialization period */ public void collectInitializationStats() { collectPresentHours(); for ( StateRecord each : stateMap.values() ) { each.initializationHours = each.getTotalHours(); each.totalHours = 0.0d; each.completedCycleHours = 0.0d; } numberOfCompletedCycles = 0; } /** * Runs when cycle is finished */ public void collectCycleStats() { collectPresentHours(); // finalize cycle for each state record for ( StateRecord each : stateMap.values() ) { each.completedCycleHours += each.getCurrentCycleHours(); each.currentCycleHours = 0.0d; } numberOfCompletedCycles++; } /** * Clear the current cycle hours */ protected void clearCurrentCycleHours() { collectPresentHours(); // clear current cycle hours for each state record for ( StateRecord each : stateMap.values() ) each.currentCycleHours = 0.0d; } /** * Runs after each report interval */ public void clearReportStats() { collectPresentHours(); // clear totalHours for each state record for ( StateRecord each : stateMap.values() ) { each.totalHours = 0.0d; each.completedCycleHours = 0.0d; } numberOfCompletedCycles = 0; } /** * Update the hours for the present state and set new timeofLastStateChange */ private void collectPresentHours() { double curTime = getCurrentTime(); if (curTime == timeOfLastStateChange) return; double duration = curTime - timeOfLastStateChange; timeOfLastStateChange = curTime; presentState.totalHours += duration; presentState.currentCycleHours += duration; if (this.isWorking()) workingHours += duration; } /** * Updates the statistics, then sets the present status to be the specified value. */ public void setPresentState( String state ) { if (traceFlag) { this.trace("setState( " + state + " )"); this.traceLine(" Old State = " + getPresentState()); } if (presentStateEquals(state)) return; if (testFlag(FLAG_TRACESTATE)) this.printStateTrace(state); StateRecord nextState = this.getStateRecordFor(state); if (nextState == null) throw new ErrorException(this + " Specified state: " + state + " was not found in the StateList: " + this.getStateList()); collectPresentHours(); nextState.secondLastStartTimeInState = nextState.getLastStartTimeInState(); nextState.lastStartTimeInState = timeOfLastStateChange; presentState = nextState; } public StateRecord getStateRecordFor(String state) { return stateMap.get(state.toLowerCase()); } private StateRecord getStateRecordFor(int index) { String state = (String)getStateList().get(index); return getStateRecordFor(state); } public double getTotalHoursFor(StateRecord state) { double hours = state.getTotalHours(); if (presentState == state) hours += getCurrentTime() - timeOfLastStateChange; return hours; } public double getTotalHoursFor(String state) { StateRecord rec = getStateRecordFor(state); return getTotalHoursFor(rec); } public double getTotalHoursFor(int index) { return getTotalHoursFor( (String) getStateList().get(index) ); } public double getTotalHours() { double total = getCurrentTime() - timeOfLastStateChange; for (int i = 0; i < getNumberOfStates(); i++) total += getStateRecordFor(i).getTotalHours(); return total; } public double getCompletedCycleHoursFor(String state) { return getStateRecordFor(state).getCompletedCycleHours(); } public double getCompletedCycleHoursFor(int index) { return getStateRecordFor(index).getCompletedCycleHours(); } public double getCompletedCycleHours() { double total = 0.0d; for (int i = 0; i < getStateList().size(); i ++) total += getStateRecordFor(i).getCompletedCycleHours(); return total; } public double getCurrentCycleHoursFor(StateRecord state) { double hours = state.getCurrentCycleHours(); if (presentState == state) hours += getCurrentTime() - timeOfLastStateChange; return hours; } /** * Returns the amount of time spent in the specified state in current cycle */ public double getCurrentCycleHoursFor( String state ) { StateRecord rec = getStateRecordFor(state); return getCurrentCycleHoursFor(rec); } /** * Return spent hours for a given state at the index in stateList for current cycle */ public double getCurrentCycleHoursFor(int index) { StateRecord rec = getStateRecordFor(index); return getCurrentCycleHoursFor(rec); } /** * Return the total hours in current cycle for all the states */ public double getCurrentCycleHours() { double total = getCurrentTime() - timeOfLastStateChange; for (int i = 0; i < getNumberOfStates(); i++) { total += getStateRecordFor(i).getCurrentCycleHours(); } return total; } /** * Returns the present state name */ public String getPresentState() { return presentState.getStateName(); } public boolean presentStateEquals(String state) { return getPresentState().equals(state); } public boolean presentStateMatches(String state) { return getPresentState().equalsIgnoreCase(state); } public boolean presentStateStartsWith(String prefix) { return getPresentState().startsWith(prefix); } public boolean presentStateEndsWith(String suffix) { return getPresentState().endsWith(suffix); } protected int getPresentStateIndex() { return presentState.getIndex(); } public void setPresentState() {} /** * Print that state information on the trace state log file */ public void printStateTrace( String state ) { // First state ever if( finalLastState.equals("") ) { finalLastState = state; stateReportFile.putString(String.format("%.5f %s.setState( \"%s\" ) dt = %s\n", 0.0d, this.getName(), getPresentState(), formatNumber(getCurrentTime()))); stateReportFile.flush(); timeOfLastPrintedState = getCurrentTime(); } else { // The final state in a sequence from the previous state change (one step behind) if ( ! Tester.equalCheckTimeStep( timeOfLastPrintedState, getCurrentTime() ) ) { stateReportFile.putString(String.format("%.5f %s.setState( \"%s\" ) dt = %s\n", timeOfLastPrintedState, this.getName(), finalLastState, formatNumber(getCurrentTime() - timeOfLastPrintedState))); // for( int i = 0; i < stateTraceRelatedModelEntities.size(); i++ ) { // ModelEntitiy each = (ModelEntitiy) stateTraceRelatedModelEntities.get( i ); // putString( ) stateReportFile.flush(); timeOfLastPrintedState = getCurrentTime(); } finalLastState = state; } } /** * Set the last time a histogram was updated for this entity */ public void setLastHistogramUpdateTime( double time ) { secondToLastHistogramUpdateTime = lastHistogramUpdateTime; lastHistogramUpdateTime = time; } /** * Returns the time from the start of the start state to the start of the end state */ public double getTimeFromStartState_ToEndState( String startState, String endState) { // Determine the index of the start state StateRecord startStateRec = this.getStateRecordFor(startState); if (startStateRec == null) { throw new ErrorException("Specified state: %s was not found in the StateList.", startState); } // Determine the index of the end state StateRecord endStateRec = this.getStateRecordFor(endState); if (endStateRec == null) { throw new ErrorException("Specified state: %s was not found in the StateList.", endState); } // Is the start time of the end state greater or equal to the start time of the start state? if (endStateRec.getLastStartTimeInState() >= startStateRec.getLastStartTimeInState()) { // If either time was not in the present cycle, return NaN if (endStateRec.getLastStartTimeInState() <= lastHistogramUpdateTime || startStateRec.getLastStartTimeInState() <= lastHistogramUpdateTime ) { return Double.NaN; } // Return the time from the last start time of the start state to the last start time of the end state return endStateRec.getLastStartTimeInState() - startStateRec.getLastStartTimeInState(); } else { // If either time was not in the present cycle, return NaN if (endStateRec.getLastStartTimeInState() <= lastHistogramUpdateTime || startStateRec.getSecondLastStartTimeInState() <= secondToLastHistogramUpdateTime ) { return Double.NaN; } // Return the time from the second to last start time of the start date to the last start time of the end state return endStateRec.getLastStartTimeInState() - startStateRec.getSecondLastStartTimeInState(); } } /** * Return the commitment */ public double getCommitment() { return 1.0 - this.getFractionOfTimeForState( "Idle" ); } /** * Return the fraction of time for the given status */ public double getFractionOfTimeForState( String aState ) { if( getTotalHours() > 0.0 ) { return ((this.getTotalHoursFor( aState ) / getTotalHours()) ); } else { return 0.0; } } /** * Return the percentage of time for the given status */ public double getPercentageOfTimeForState( String aState ) { if( getTotalHours() > 0.0 ) { return ((this.getTotalHoursFor( aState ) / getTotalHours()) * 100.0); } else { return 0.0; } } /** * Returns the number of hours the entity is in use. * *!*!*!*! OVERLOAD !*!*!*!* */ public double getWorkingHours() { double hours = 0.0d; if ( this.isWorking() ) hours = getCurrentTime() - timeOfLastStateChange; return workingHours + hours; } public Vector getStateList() { return stateList; } /** * Return total number of states */ public int getNumberOfStates() { return stateMap.size(); } // MAINTENANCE METHODS /** * Perform tasks required before a maintenance period */ public void doPreMaintenance() { //@debug@ cr 'Entity should be overloaded' print } /** * Start working again following a breakdown or maintenance period */ public void restart() { //@debug@ cr 'Entity should be overloaded' print } /** * Disconnect routes, release truck assignments, etc. when performing maintenance or breakdown */ public void releaseEquipment() {} public boolean releaseEquipmentForMaintenanceSchedule( int index ) { if( releaseEquipment.getValue() == null ) return true; return releaseEquipment.getValue().get( index ); } public boolean forceMaintenanceSchedule( int index ) { if( forceMaintenance.getValue() == null ) return false; return forceMaintenance.getValue().get( index ); } /** * Perform all maintenance schedules that are due */ public void doMaintenance() { // scheduled maintenance for( int index = 0; index < maintenancePendings.size(); index++ ) { if( this.getMaintenancePendings().get( index ) > 0 ) { if( traceFlag ) this.trace( "Starting Maintenance Schedule: " + index ); this.doMaintenance(index); } } // Operating hours maintenance for( int index = 0; index < maintenanceOperatingHoursPendings.size(); index++ ) { if( this.getWorkingHours() > hoursForNextMaintenanceOperatingHours.get( index ) ) { hoursForNextMaintenanceOperatingHours.set(index, this.getWorkingHours() + getMaintenanceOperatingHoursIntervals().get( index )); maintenanceOperatingHoursPendings.addAt( 1, index ); this.doMaintenanceOperatingHours(index); } } } /** * Perform all the planned maintenance that is due for the given schedule */ public void doMaintenance( int index ) { double wait; if( masterMaintenanceEntity != null ) { wait = masterMaintenanceEntity.getMaintenanceDurations().getValue().get( index ); } else { wait = this.getMaintenanceDurations().getValue().get( index ); } if( wait > 0.0 && maintenancePendings.get( index ) != 0 ) { if( traceFlag ) this.trace( "ModelEntity.doMaintenance_Wait() -- start of maintenance" ); // Keep track of the start and end of maintenance times maintenanceStartTime = getCurrentTime(); if( masterMaintenanceEntity != null ) { maintenanceEndTime = maintenanceStartTime + ( maintenancePendings.get( index ) * masterMaintenanceEntity.getMaintenanceDurations().getValue().get( index ) ); } else { maintenanceEndTime = maintenanceStartTime + ( maintenancePendings.get( index ) * maintenanceDurations.getValue().get( index ) ); } this.setPresentState( "Maintenance" ); maintenance = true; this.doPreMaintenance(); // Release equipment if necessary if( this.releaseEquipmentForMaintenanceSchedule( index ) ) { this.releaseEquipment(); } while( maintenancePendings.get( index ) != 0 ) { maintenancePendings.subAt( 1, index ); scheduleWait( wait ); // If maintenance pending goes negative, something is wrong if( maintenancePendings.get( index ) < 0 ) { this.error( "ModelEntity.doMaintenance_Wait()", "Maintenace pending should not be negative", "maintenacePending = "+maintenancePendings.get( index ) ); } } if( traceFlag ) this.trace( "ModelEntity.doMaintenance_Wait() -- end of maintenance" ); // The maintenance is over this.setPresentState( "Idle" ); maintenance = false; this.restart(); } } /** * Perform all the planned maintenance that is due */ public void doMaintenanceOperatingHours( int index ) { if(maintenanceOperatingHoursPendings.get( index ) == 0 ) return; if( traceFlag ) this.trace( "ModelEntity.doMaintenance_Wait() -- start of maintenance" ); // Keep track of the start and end of maintenance times maintenanceStartTime = getCurrentTime(); maintenanceEndTime = maintenanceStartTime + (maintenanceOperatingHoursPendings.get( index ) * getMaintenanceOperatingHoursDurationFor(index)); this.setPresentState( "Maintenance" ); maintenance = true; this.doPreMaintenance(); while( maintenanceOperatingHoursPendings.get( index ) != 0 ) { //scheduleWait( maintenanceDurations.get( index ) ); scheduleWait( maintenanceEndTime - maintenanceStartTime ); maintenanceOperatingHoursPendings.subAt( 1, index ); // If maintenance pending goes negative, something is wrong if( maintenanceOperatingHoursPendings.get( index ) < 0 ) { this.error( "ModelEntity.doMaintenance_Wait()", "Maintenace pending should not be negative", "maintenacePending = "+maintenanceOperatingHoursPendings.get( index ) ); } } if( traceFlag ) this.trace( "ModelEntity.doMaintenance_Wait() -- end of maintenance" ); // The maintenance is over maintenance = false; this.setPresentState( "Idle" ); this.restart(); } /** * Check if a maintenance is due. if so, try to perform the maintenance */ public boolean checkMaintenance() { if( traceFlag ) this.trace( "checkMaintenance()" ); if( checkOperatingHoursMaintenance() ) { return true; } // List of all entities going to maintenance ArrayList<ModelEntity> sharedMaintenanceEntities; // This is not a master maintenance entity if( masterMaintenanceEntity != null ) { sharedMaintenanceEntities = masterMaintenanceEntity.getSharedMaintenanceList(); } // This is a master maintenance entity else { sharedMaintenanceEntities = getSharedMaintenanceList(); } // If this entity is in shared maintenance relation with a group of entities if( sharedMaintenanceEntities.size() > 0 || masterMaintenanceEntity != null ) { // Are all entities in the group ready for maintenance if( this.areAllEntitiesAvailable() ) { // For every entity in the shared maintenance list plus the master maintenance entity for( int i=0; i <= sharedMaintenanceEntities.size(); i++ ) { ModelEntity aModel; // Locate master maintenance entity( after all entity in shared maintenance list have been taken care of ) if( i == sharedMaintenanceEntities.size() ) { // This entity is manster maintenance entity if( masterMaintenanceEntity == null ) { aModel = this; } // This entity is on the shared maintenannce list of the master maintenance entity else { aModel = masterMaintenanceEntity; } } // Next entity in the shared maintenance list else { aModel = sharedMaintenanceEntities.get( i ); } // Check for aModel maintenances for( int index = 0; index < maintenancePendings.size(); index++ ) { if( aModel.getMaintenancePendings().get( index ) > 0 ) { if( traceFlag ) this.trace( "Starting Maintenance Schedule: " + index ); aModel.startProcess("doMaintenance", index); } } } return true; } else { return false; } } // This block is maintained indipendently else { // Check for maintenances for( int i = 0; i < maintenancePendings.size(); i++ ) { if( maintenancePendings.get( i ) > 0 ) { if( this.canStartMaintenance( i ) ) { if( traceFlag ) this.trace( "Starting Maintenance Schedule: " + i ); this.startProcess("doMaintenance", i); return true; } } } } return false; } /** * Determine how many hours of maintenance is scheduled between startTime and endTime */ public double getScheduledMaintenanceHoursForPeriod( double startTime, double endTime ) { if( traceFlag ) this.trace("Handler.getScheduledMaintenanceHoursForPeriod( "+startTime+", "+endTime+" )" ); double totalHours = 0.0; double firstTime = 0.0; // Add on hours for all pending maintenance for( int i=0; i < maintenancePendings.size(); i++ ) { totalHours += maintenancePendings.get( i ) * maintenanceDurations.getValue().get( i ); } if( traceFlag ) this.traceLine( "Hours of pending maintenances="+totalHours ); // Add on hours for all maintenance scheduled to occur in the given period from startTime to endTime for( int i=0; i < maintenancePendings.size(); i++ ) { // Find the first time that maintenance is scheduled after startTime firstTime = firstMaintenanceTimes.getValue().get( i ); while( firstTime < startTime ) { firstTime += maintenanceIntervals.getValue().get( i ); } if( traceFlag ) this.traceLine(" first time maintenance "+i+" is scheduled after startTime= "+firstTime ); // Now have the first maintenance start time after startTime // Add all maintenances that lie in the given interval while( firstTime < endTime ) { if( traceFlag ) this.traceLine(" Checking for maintenances for period:"+firstTime+" to "+endTime ); // Add the maintenance totalHours += maintenanceDurations.getValue().get( i ); // Update the search period endTime += maintenanceDurations.getValue().get( i ); // Look for next maintenance in new interval firstTime += maintenanceIntervals.getValue().get( i ); if( traceFlag ) this.traceLine(" Adding Maintenance duration = "+maintenanceDurations.getValue().get( i ) ); } } // Return the total hours of maintenance scheduled from startTime to endTime if( traceFlag ) this.traceLine( "Maintenance hours to add= "+totalHours ); return totalHours; } public boolean checkOperatingHoursMaintenance() { if( traceFlag ) this.trace("checkOperatingHoursMaintenance()"); // Check for maintenances for( int i = 0; i < getMaintenanceOperatingHoursIntervals().size(); i++ ) { // If the entity is not available, maintenance cannot start if( ! this.canStartMaintenance( i ) ) continue; if( this.getWorkingHours() > hoursForNextMaintenanceOperatingHours.get( i ) ) { hoursForNextMaintenanceOperatingHours.set(i, (this.getWorkingHours() + getMaintenanceOperatingHoursIntervals().get( i ))); maintenanceOperatingHoursPendings.addAt( 1, i ); if( traceFlag ) this.trace( "Starting Maintenance Operating Hours Schedule : " + i ); this.startProcess("doMaintenanceOperatingHours", i); return true; } } return false; } /** * Wrapper method for doMaintenance_Wait. */ public void doMaintenanceNetwork() { this.startProcess("doMaintenanceNetwork_Wait"); } /** * Network for planned maintenance. * This method should be called in the initialize method of the specific entity. */ public void doMaintenanceNetwork_Wait() { // Initialize schedules for( int i=0; i < maintenancePendings.size(); i++ ) { maintenancePendings.set( i, 0 ); } nextMaintenanceTimes = new DoubleVector(firstMaintenanceTimes.getValue()); nextMaintenanceDuration = 0; // Find the next maintenance event int index = 0; double earliestTime = Double.POSITIVE_INFINITY; for( int i=0; i < nextMaintenanceTimes.size(); i++ ) { double time = nextMaintenanceTimes.get( i ); if( Tester.lessCheckTolerance( time, earliestTime ) ) { earliestTime = time; index = i; nextMaintenanceDuration = maintenanceDurations.getValue().get( i ); } } // Make sure that maintenance for entities on the shared list are being called after those entities have been initialize (AT TIME ZERO) scheduleLastLIFO(); while( true ) { double dt = earliestTime - getCurrentTime(); // Wait for the maintenance check time if( dt > Process.getEventTolerance() ) { scheduleWait( dt ); } // Increment the number of maintenances due for the entity maintenancePendings.addAt( 1, index ); // If this is a master maintenance entity if (getSharedMaintenanceList().size() > 0) { // If all the entities on the shared list are ready for maintenance if( this.areAllEntitiesAvailable() ) { // Put this entity to maintenance if( traceFlag ) this.trace( "Starting Maintenance Schedule: " + index ); this.startProcess("doMaintenance", index); } } // If this entity is maintained independently else { // Do maintenance if possible if( ! this.isInService() && this.canStartMaintenance( index ) ) { // if( traceFlag ) this.trace( "doMaintenanceNetwork_Wait: Starting Maintenance. PresentState = "+presentState+" IsAvailable? = "+this.isAvailable() ); if( traceFlag ) this.trace( "Starting Maintenance Schedule: " + index ); this.startProcess("doMaintenance", index); } // Keep track of the time the maintenance was attempted else { lastScheduledMaintenanceTimes.set( index, getCurrentTime() ); // If skipMaintenance was defined, cancel the maintenance if( this.shouldSkipMaintenance( index ) ) { // if a different maintenance is due, cancel this maintenance boolean cancelMaintenance = false; for( int i=0; i < maintenancePendings.size(); i++ ) { if( i != index ) { if( maintenancePendings.get( i ) > 0 ) { cancelMaintenance = true; break; } } } if( cancelMaintenance || this.isInMaintenance() ) { maintenancePendings.subAt( 1, index ); } } // Do a check after the limit has expired if( this.getDeferMaintenanceLimit( index ) > 0.0 ) { this.startProcess( "scheduleCheckMaintenance", this.getDeferMaintenanceLimit( index ) ); } } } // Determine the next maintenance time nextMaintenanceTimes.addAt( maintenanceIntervals.getValue().get( index ), index ); // Find the next maintenance event index = 0; earliestTime = Double.POSITIVE_INFINITY; for( int i=0; i < nextMaintenanceTimes.size(); i++ ) { double time = nextMaintenanceTimes.get( i ); if( Tester.lessCheckTolerance( time, earliestTime ) ) { earliestTime = time; index = i; nextMaintenanceDuration = maintenanceDurations.getValue().get( i ); } } } } public double getDeferMaintenanceLimit( int index ) { if( deferMaintenanceLimit.getValue() == null ) return 0.0d; return deferMaintenanceLimit.getValue().get( index ); } public void scheduleCheckMaintenance( double wait ) { scheduleWait( wait ); this.checkMaintenance(); } public boolean shouldSkipMaintenance( int index ) { if( skipMaintenanceIfOverlap.getValue().size() == 0 ) return false; return skipMaintenanceIfOverlap.getValue().get( index ); } /** * Return TRUE if there is a pending maintenance for any schedule */ public boolean isMaintenancePending() { for( int i = 0; i < maintenancePendings.size(); i++ ) { if( maintenancePendings.get( i ) > 0 ) { return true; } } for( int i = 0; i < hoursForNextMaintenanceOperatingHours.size(); i++ ) { if( this.getWorkingHours() > hoursForNextMaintenanceOperatingHours.get( i ) ) { return true; } } return false; } public boolean isForcedMaintenancePending() { if( forceMaintenance.getValue() == null ) return false; for( int i = 0; i < maintenancePendings.size(); i++ ) { if( maintenancePendings.get( i ) > 0 && forceMaintenance.getValue().get(i) ) { return true; } } return false; } public ArrayList<ModelEntity> getSharedMaintenanceList () { return sharedMaintenanceList.getValue(); } public IntegerVector getMaintenancePendings () { return maintenancePendings; } public DoubleListInput getMaintenanceDurations() { return maintenanceDurations; } /** * Return the start of the next scheduled maintenance time if not in maintenance, * or the start of the current scheduled maintenance time if in maintenance */ public double getNextMaintenanceStartTime() { if( nextMaintenanceTimes == null ) return Double.POSITIVE_INFINITY; else return nextMaintenanceTimes.getMin(); } /** * Return the duration of the next maintenance event (assuming only one pending) */ public double getNextMaintenanceDuration() { return nextMaintenanceDuration; } // Shows if an Entity would ever go on service public boolean hasServiceScheduled() { if( firstMaintenanceTimes.getValue().size() != 0 || masterMaintenanceEntity != null ) { return true; } return false; } public void setMasterMaintenanceBlock( ModelEntity aModel ) { masterMaintenanceEntity = aModel; } // BREAKDOWN METHODS /** * No Comments Given. */ public void calculateTimeOfNextFailure() { hoursForNextFailure = (this.getWorkingHours() + this.getNextBreakdownIAT()); } /** * Activity Network for Breakdowns. */ public void doBreakdown() { } /** * Prints the header for the entity's state list. * @return bottomLine contains format for each column of the bottom line of the group report */ public IntegerVector printUtilizationHeaderOn( FileEntity anOut ) { IntegerVector bottomLine = new IntegerVector(); if( getStateList().size() != 0 ) { anOut.putStringTabs( "Name", 1 ); bottomLine.add( ReportAgent.BLANK ); int doLoop = getStateList().size(); for( int x = 0; x < doLoop; x++ ) { String state = (String)getStateList().get( x ); anOut.putStringTabs( state, 1 ); bottomLine.add( ReportAgent.AVERAGE_PCT_ONE_DEC ); } anOut.newLine(); } return bottomLine; } /** * Print the entity's name and percentage of hours spent in each state. * @return columnValues are the values for each column in the group report (0 if the value is a String) */ public DoubleVector printUtilizationOn( FileEntity anOut ) { double total; DoubleVector columnValues = new DoubleVector(); if( getNumberOfStates() != 0 ) { total = getTotalHours(); if( !(total == 0.0) ) { anOut.putStringTabs( getName(), 1 ); columnValues.add( 0.0 ); for( int i = 0; i < getNumberOfStates(); i++ ) { double value = getTotalHoursFor( i ) / total; anOut.putDoublePercentWithDecimals( value, 1 ); anOut.putTabs( 1 ); columnValues.add( value ); } anOut.newLine(); } } return columnValues; } /** * This method must be overridden in any subclass of ModelEntity. */ public boolean isAvailable() { throw new ErrorException( "Must override isAvailable in any subclass of ModelEntity." ); } /** * This method must be overridden in any subclass of ModelEntity. */ public boolean canStartMaintenance( int index ) { return isAvailable(); } /** * This method must be overridden in any subclass of ModelEntity. */ public boolean canStartForcedMaintenance() { return isAvailable(); } /** * This method must be overridden in any subclass of ModelEntity. */ public boolean areAllEntitiesAvailable() { throw new ErrorException( "Must override areAllEntitiesAvailable in any subclass of ModelEntity." ); } /** * Return the time of the next breakdown duration */ public double getBreakdownDuration() { // if( traceFlag ) this.trace( "getBreakdownDuration()" ); // If a distribution was specified, then select a duration randomly from the distribution if ( getDowntimeDurationDistribution() != null ) { return getDowntimeDurationDistribution().nextValue(); } else { return 0.0; } } /** * Return the time of the next breakdown IAT */ public double getNextBreakdownIAT() { if( getDowntimeIATDistribution() != null ) { return getDowntimeIATDistribution().nextValue(); } else { return iATFailure; } } public double getHoursForNextFailure() { return hoursForNextFailure; } public void setHoursForNextFailure( double hours ) { hoursForNextFailure = hours; } /** Returns a vector of strings describing the ModelEntity. Override to add details @return Vector - tab delimited strings describing the DisplayEntity **/ @Override public Vector getInfo() { Vector info = super.getInfo(); info.add( String.format("Present State\t%s", getPresentState()) ); return info; } protected DoubleVector getMaintenanceOperatingHoursIntervals() { return maintenanceOperatingHoursIntervals.getValue(); } protected double getMaintenanceOperatingHoursDurationFor(int index) { return maintenanceOperatingHoursDurations.getValue().get(index); } protected ProbabilityDistribution getDowntimeIATDistribution() { return downtimeIATDistribution.getValue(); } }
package com.sandwell.JavaSimulation3D; import static com.sandwell.JavaSimulation.Util.formatNumber; import java.util.ArrayList; import java.util.HashMap; import com.jaamsim.input.InputAgent; import com.jaamsim.math.Color4d; import com.sandwell.JavaSimulation.BooleanInput; import com.sandwell.JavaSimulation.BooleanListInput; import com.sandwell.JavaSimulation.BooleanVector; import com.sandwell.JavaSimulation.ColourInput; import com.sandwell.JavaSimulation.DoubleInput; import com.sandwell.JavaSimulation.DoubleListInput; import com.sandwell.JavaSimulation.DoubleVector; import com.sandwell.JavaSimulation.EntityInput; import com.sandwell.JavaSimulation.EntityListInput; import com.sandwell.JavaSimulation.ErrorException; import com.sandwell.JavaSimulation.FileEntity; import com.sandwell.JavaSimulation.Input; import com.sandwell.JavaSimulation.InputErrorException; import com.sandwell.JavaSimulation.IntegerVector; import com.sandwell.JavaSimulation.Keyword; import com.sandwell.JavaSimulation.ProbabilityDistribution; import com.sandwell.JavaSimulation.Process; import com.sandwell.JavaSimulation.Tester; import com.sandwell.JavaSimulation.Vector; /** * Class ModelEntity - JavaSimulation3D */ public class ModelEntity extends DisplayEntity { // Breakdowns @Keyword(desc = "Reliability is defined as:\n" + " 100% - (plant breakdown time / total operation time)\n " + "or\n " + "(Operational Time)/(Breakdown + Operational Time)", example = "Object1 Reliability { 0.95 }") private final DoubleInput availability; protected double hoursForNextFailure; // The number of working hours required before the next breakdown protected double iATFailure; // inter arrival time between failures protected boolean breakdownPending; // true when a breakdown is to occur protected boolean brokendown; // true => entity is presently broken down protected boolean maintenance; // true => entity is presently in maintenance protected boolean associatedBreakdown; // true => entity is presently in Associated Breakdown protected boolean associatedMaintenance; // true => entity is presently in Associated Maintenance protected double breakdownStartTime; // Start time of the most recent breakdown protected double breakdownEndTime; // End time of the most recent breakdown // Breakdown Probability Distributions @Keyword(desc = "A ProbabilityDistribution object that governs the duration of breakdowns (in hours).", example = "Object1 DowntimeDurationDistribution { BreakdownProbDist1 }") private final EntityInput<ProbabilityDistribution> downtimeDurationDistribution; @Keyword(desc = "A ProbabilityDistribution object that governs when breakdowns occur (in hours).", example = "Object1 DowntimeIATDistribution { BreakdownProbDist1 }") private final EntityInput<ProbabilityDistribution> downtimeIATDistribution; // Maintenance @Keyword(desc = "The simulation time for the start of the first maintenance for each maintenance cycle.", example = "Object1 FirstMaintenanceTime { 24 h }") protected DoubleListInput firstMaintenanceTimes; @Keyword(desc = "The time between maintenance activities for each maintenance cycle", example = "Object1 MaintenanceInterval { 168 h }") protected DoubleListInput maintenanceIntervals; @Keyword(desc = "The durations of a single maintenance event for each maintenance cycle.", example = "Object1 MaintenanceDuration { 336 h }") protected DoubleListInput maintenanceDurations; protected IntegerVector maintenancePendings; // Number of maintenance periods that are due @Keyword(desc = "A Boolean value. Allows scheduled maintenances to be skipped if it overlaps " + "with another planned maintenance event.", example = "Object1 SkipMaintenanceIfOverlap { TRUE }") protected BooleanListInput skipMaintenanceIfOverlap; @Keyword(desc = "A list of objects that share the maintenance schedule with this object. " + "In order for the maintenance to start, all objects on this list must be available." + "This keyword is for Handlers and Signal Blocks only.", example = "Block1 SharedMaintenance { Block2 Block2 }") private final EntityListInput<ModelEntity> sharedMaintenanceList; protected ModelEntity masterMaintenanceEntity; // The entity that has maintenance information protected boolean performMaintenanceAfterShipDelayPending; // maintenance needs to be done after shipDelay // Maintenance based on hours of operations @Keyword(desc = "Working time for the start of the first maintenance for each maintenance cycle", example = "Object1 FirstMaintenanceOperatingHours { 1000 2500 h }") private final DoubleListInput firstMaintenanceOperatingHours; @Keyword(desc = "Working time between one maintenance event and the next for each maintenance cycle", example = "Object1 MaintenanceOperatingHoursIntervals { 2000 5000 h }") private final DoubleListInput maintenanceOperatingHoursIntervals; @Keyword(desc = "Duration of maintenance events based on working hours for each maintenance cycle", example = "Ship1 MaintenanceOperatingHoursDurations { 24 48 h }") private final DoubleListInput maintenanceOperatingHoursDurations; protected IntegerVector maintenanceOperatingHoursPendings; // Number of maintenance periods that are due protected DoubleVector hoursForNextMaintenanceOperatingHours; protected double maintenanceStartTime; // Start time of the most recent maintenance protected double maintenanceEndTime; // End time of the most recent maintenance protected DoubleVector nextMaintenanceTimes; // next start time for each maintenance protected double nextMaintenanceDuration; // duration for next maintenance protected DoubleVector lastScheduledMaintenanceTimes; @Keyword(desc = "If maintenance has been deferred by the DeferMaintenanceLookAhead keyword " + "for longer than this time, the maintenance will start even if " + "there is an object within the lookahead. There must be one entry for each " + "defined maintenance schedule if DeferMaintenanceLookAhead is used. This" + "keyword is only used for signal blocks.", example = "Object1 DeferMaintenanceLimit { 50 50 h }") private final DoubleListInput deferMaintenanceLimit; @Keyword(desc = "If the duration of the downtime is longer than this time, equipment will be released", example = "Object1 DowntimeToReleaseEquipment { 1.0 h }") protected final DoubleInput downtimeToReleaseEquipment; @Keyword(desc = "A list of Boolean values corresponding to the maintenance cycles. If a value is TRUE, " + "then routes/tasks are released before performing the maintenance in the cycle.", example = "Object1 ReleaseEquipment { TRUE FALSE FALSE }") protected final BooleanListInput releaseEquipment; @Keyword(desc = "A list of Boolean values corresponding to the maintenance cycles. If a value is " + "TRUE, then maintenance in the cycle can start even if the equipment is presently " + "working.", example = "Object1 ForceMaintenance { TRUE FALSE FALSE }") protected final BooleanListInput forceMaintenance; // Statistics @Keyword(desc = "If TRUE, then statistics for this object are " + "included in the main output report.", example = "Object1 PrintToReport { TRUE }") private final BooleanInput printToReport; // States private static Vector stateList = new Vector( 11, 1 ); // List of valid states private final HashMap<String, StateRecord> stateMap; protected double workingHours; // Accumulated working time spent in working states private static class StateRecord { String stateName; int index; double initializationHours; double totalHours; double completedCycleHours; double currentCycleHours; public StateRecord(String state, int i) { stateName = state; index = i; } public int getIndex() { return index; } public String getStateName() { return stateName; } public double getTotalHours() { return totalHours; } public double getCompletedCycleHours() { return completedCycleHours; } public double getCurrentCycleHours() { return currentCycleHours; } public void setInitializationHours(double init) { initializationHours = init; } public void setTotalHours(double total) { totalHours = total; } public void setCompletedCycleHours(double hours) { completedCycleHours = hours; } public void setCurrentCycleHours(double hours) { currentCycleHours = hours; } @Override public String toString() { return getStateName(); } public void addHours(double dur) { totalHours += dur; currentCycleHours += dur; } public void clearReportStats() { totalHours = 0.0d; completedCycleHours = 0.0d; } public void clearCurrentCycleHours() { currentCycleHours = 0.0d; } } private double timeOfLastStateUpdate; private int numberOfCompletedCycles; protected double lastHistogramUpdateTime; // Last time at which a histogram was updated for this entity protected double secondToLastHistogramUpdateTime; // Second to last time at which a histogram was updated for this entity protected DoubleVector lastStartTimePerState; // Last time at which the state changed from some other state to each state protected DoubleVector secondToLastStartTimePerState; // The second to last time at which the state changed from some other state to each state private StateRecord presentState; // The present state of the entity protected double timeOfLastStateChange; // Time at which the state was last changed protected FileEntity stateReportFile; // The file to store the state information private String finalLastState = ""; // The final state of the entity (in a sequence of transitional states) private double timeOfLastPrintedState = 0; // The time that the last state printed in the trace state file // Graphics protected final static Color4d breakdownColor = ColourInput.DARK_RED; // Color of the entity in breaking down protected final static Color4d maintenanceColor = ColourInput.RED; // Color of the entity in maintenance static { stateList.addElement( "Idle" ); stateList.addElement( "Working" ); stateList.addElement( "Breakdown" ); stateList.addElement( "Maintenance" ); } { maintenanceDurations = new DoubleListInput("MaintenanceDurations", "Maintenance", new DoubleVector()); maintenanceDurations.setValidRange(0.0d, Double.POSITIVE_INFINITY); maintenanceDurations.setUnits("h"); this.addInput(maintenanceDurations, true, "MaintenanceDuration"); maintenanceIntervals = new DoubleListInput("MaintenanceIntervals", "Maintenance", new DoubleVector()); maintenanceIntervals.setValidRange(0.0d, Double.POSITIVE_INFINITY); maintenanceIntervals.setUnits("h"); this.addInput(maintenanceIntervals, true, "MaintenanceInterval"); firstMaintenanceTimes = new DoubleListInput("FirstMaintenanceTimes", "Maintenance", new DoubleVector()); firstMaintenanceTimes.setValidRange(0.0d, Double.POSITIVE_INFINITY); firstMaintenanceTimes.setUnits("h"); this.addInput(firstMaintenanceTimes, true, "FirstMaintenanceTime"); forceMaintenance = new BooleanListInput("ForceMaintenance", "Maintenance", null); this.addInput(forceMaintenance, true); releaseEquipment = new BooleanListInput("ReleaseEquipment", "Maintenance", null); this.addInput(releaseEquipment, true); availability = new DoubleInput("Reliability", "Breakdowns", 1.0d, 0.0d, 1.0d); this.addInput(availability, true); downtimeIATDistribution = new EntityInput<ProbabilityDistribution>(ProbabilityDistribution.class, "DowntimeIATDistribution", "Breakdowns", null); this.addInput(downtimeIATDistribution, true); downtimeDurationDistribution = new EntityInput<ProbabilityDistribution>(ProbabilityDistribution.class, "DowntimeDurationDistribution", "Breakdowns", null); this.addInput(downtimeDurationDistribution, true); downtimeToReleaseEquipment = new DoubleInput("DowntimeToReleaseEquipment", "Breakdowns", 0.0d, 0.0d, Double.POSITIVE_INFINITY); this.addInput(downtimeToReleaseEquipment, true); skipMaintenanceIfOverlap = new BooleanListInput("SkipMaintenanceIfOverlap", "Maintenance", new BooleanVector()); this.addInput(skipMaintenanceIfOverlap, true); deferMaintenanceLimit = new DoubleListInput("DeferMaintenanceLimit", "Maintenance", null); deferMaintenanceLimit.setValidRange(0.0d, Double.POSITIVE_INFINITY); deferMaintenanceLimit.setUnits("h"); this.addInput(deferMaintenanceLimit, true); sharedMaintenanceList = new EntityListInput<ModelEntity>(ModelEntity.class, "SharedMaintenance", "Maintenance", new ArrayList<ModelEntity>(0)); this.addInput(sharedMaintenanceList, true); firstMaintenanceOperatingHours = new DoubleListInput("FirstMaintenanceOperatingHours", "Maintenance", new DoubleVector()); firstMaintenanceOperatingHours.setValidRange(0.0d, Double.POSITIVE_INFINITY); firstMaintenanceOperatingHours.setUnits("h"); this.addInput(firstMaintenanceOperatingHours, true); maintenanceOperatingHoursDurations = new DoubleListInput("MaintenanceOperatingHoursDurations", "Maintenance", new DoubleVector()); maintenanceOperatingHoursDurations.setValidRange(1e-15, Double.POSITIVE_INFINITY); maintenanceOperatingHoursDurations.setUnits("h"); this.addInput(maintenanceOperatingHoursDurations, true); maintenanceOperatingHoursIntervals = new DoubleListInput("MaintenanceOperatingHoursIntervals", "Maintenance", new DoubleVector()); maintenanceOperatingHoursIntervals.setValidRange(1e-15, Double.POSITIVE_INFINITY); maintenanceOperatingHoursIntervals.setUnits("h"); this.addInput(maintenanceOperatingHoursIntervals, true); printToReport = new BooleanInput("PrintToReport", "Report", true); this.addInput(printToReport, true); } public ModelEntity() { lastHistogramUpdateTime = 0.0; secondToLastHistogramUpdateTime = 0.0; lastStartTimePerState = new DoubleVector(); secondToLastStartTimePerState = new DoubleVector(); hoursForNextFailure = 0.0; iATFailure = 0.0; maintenancePendings = new IntegerVector( 1, 1 ); maintenanceOperatingHoursPendings = new IntegerVector( 1, 1 ); hoursForNextMaintenanceOperatingHours = new DoubleVector( 1, 1 ); performMaintenanceAfterShipDelayPending = false; lastScheduledMaintenanceTimes = new DoubleVector(); breakdownStartTime = 0.0; breakdownEndTime = Double.POSITIVE_INFINITY; breakdownPending = false; brokendown = false; associatedBreakdown = false; maintenanceStartTime = 0.0; maintenanceEndTime = Double.POSITIVE_INFINITY; maintenance = false; associatedMaintenance = false; workingHours = 0.0; stateMap = new HashMap<String, StateRecord>(); initStateMap(); } /** * Clear internal properties */ public void clearInternalProperties() { hoursForNextFailure = 0.0; performMaintenanceAfterShipDelayPending = false; breakdownPending = false; brokendown = false; associatedBreakdown = false; maintenance = false; associatedMaintenance = false; workingHours = 0.0; } @Override public void validate() throws InputErrorException { super.validate(); this.validateMaintenance(); Input.validateIndexedLists(firstMaintenanceOperatingHours.getValue(), maintenanceOperatingHoursIntervals.getValue(), "FirstMaintenanceOperatingHours", "MaintenanceOperatingHoursIntervals"); Input.validateIndexedLists(firstMaintenanceOperatingHours.getValue(), maintenanceOperatingHoursDurations.getValue(), "FirstMaintenanceOperatingHours", "MaintenanceOperatingHoursDurations"); if( getAvailability() < 1.0 ) { if( getDowntimeDurationDistribution() == null ) { throw new InputErrorException("When availability is less than one you must define downtimeDurationDistribution in your input file!"); } } if( downtimeIATDistribution.getValue() != null ) { if( getDowntimeDurationDistribution() == null ) { throw new InputErrorException("When DowntimeIATDistribution is set, DowntimeDurationDistribution must also be set."); } } if( skipMaintenanceIfOverlap.getValue().size() > 0 ) Input.validateIndexedLists(firstMaintenanceTimes.getValue(), skipMaintenanceIfOverlap.getValue(), "FirstMaintenanceTimes", "SkipMaintenanceIfOverlap"); if( releaseEquipment.getValue() != null ) Input.validateIndexedLists(firstMaintenanceTimes.getValue(), releaseEquipment.getValue(), "FirstMaintenanceTimes", "ReleaseEquipment"); if( forceMaintenance.getValue() != null ) { Input.validateIndexedLists(firstMaintenanceTimes.getValue(), forceMaintenance.getValue(), "FirstMaintenanceTimes", "ForceMaintenance"); } if(downtimeDurationDistribution.getValue() != null && downtimeDurationDistribution.getValue().getMinimumValue() < 0) throw new InputErrorException("DowntimeDurationDistribution cannot allow negative values"); if(downtimeIATDistribution.getValue() != null && downtimeIATDistribution.getValue().getMinimumValue() < 0) throw new InputErrorException("DowntimeIATDistribution cannot allow negative values"); } @Override public void earlyInit() { super.earlyInit(); if( downtimeDurationDistribution.getValue() != null ) { downtimeDurationDistribution.getValue().initialize(); } if( downtimeIATDistribution.getValue() != null ) { downtimeIATDistribution.getValue().initialize(); } } /** * Runs after initialization period */ public void collectInitializationStats() { for ( StateRecord each : stateMap.values() ) { each.setInitializationHours( getTotalHoursFor(each) ); each.clearReportStats(); if (each == presentState) each.setCurrentCycleHours( getCurrentCycleHoursFor(each) ); } if ( this.isWorking() ) workingHours += getCurrentTime() - timeOfLastStateUpdate; timeOfLastStateUpdate = getCurrentTime(); numberOfCompletedCycles = 0; } /** * Runs when cycle is finished */ public void collectCycleStats() { // finalize cycle for each state record for ( StateRecord each : stateMap.values() ) { double hour = each.getCompletedCycleHours(); hour += getCurrentCycleHoursFor(each); each.setCompletedCycleHours(hour); each.clearCurrentCycleHours(); if (each == presentState) each.setTotalHours( getTotalHoursFor(each) ); } if ( this.isWorking() ) workingHours += getCurrentTime() - timeOfLastStateUpdate; timeOfLastStateUpdate = getCurrentTime(); numberOfCompletedCycles++; } /** * Runs after each report interval */ public void clearReportStats() { // clear totalHours for each state record for ( StateRecord each : stateMap.values() ) { each.clearReportStats(); } numberOfCompletedCycles = 0; } public int getNumberOfCompletedCycles() { return numberOfCompletedCycles; } /** * Clear the current cycle hours */ protected void clearCurrentCycleHours() { this.updateStateRecordHours(); // clear current cycle hours for each state record for ( StateRecord each : stateMap.values() ) { each.clearCurrentCycleHours(); } } public void initStateMap() { // Populate the hash map for the states and StateRecord stateMap.clear(); for (int i = 0; i < getStateList().size(); i++) { String state = (String)getStateList().get(i); StateRecord stateRecord = new StateRecord(state, i); stateMap.put(state.toLowerCase() , stateRecord); } timeOfLastStateUpdate = getCurrentTime(); timeOfLastStateChange = getCurrentTime(); } private StateRecord getStateRecordFor(String state) { return stateMap.get(state.toLowerCase()); } private StateRecord getStateRecordFor(int index) { String state = (String)getStateList().get(index); return getStateRecordFor(state); } public double getCompletedCycleHoursFor(String state) { return getStateRecordFor(state).getCompletedCycleHours(); } public double getCompletedCycleHoursFor(int index) { return getStateRecordFor(index).getCompletedCycleHours(); } public double getCompletedCycleHours() { double total = 0.0d; for (int i = 0; i < getStateList().size(); i ++) total += getStateRecordFor(i).getCompletedCycleHours(); return total; } public double getTotalHoursFor(int index) { return getTotalHoursFor( (String) getStateList().get(index) ); } public double getTotalHoursFor(String state) { StateRecord rec = getStateRecordFor(state); return getTotalHoursFor(rec); } public double getTotalHoursFor(StateRecord state) { double hours = state.getTotalHours(); if (presentState == state) hours += getCurrentTime() - timeOfLastStateUpdate; return hours; } public double getTotalHours() { double total = getCurrentTime() - timeOfLastStateUpdate; for (int i = 0; i < getNumberOfStates(); i++) total += getStateRecordFor(i).getTotalHours(); return total; } // INPUT public void validateMaintenance() { Input.validateIndexedLists(firstMaintenanceTimes.getValue(), maintenanceIntervals.getValue(), "FirstMaintenanceTimes", "MaintenanceIntervals"); Input.validateIndexedLists(firstMaintenanceTimes.getValue(), maintenanceDurations.getValue(), "FirstMaintenanceTimes", "MaintenanceDurations"); for( int i = 0; i < maintenanceIntervals.getValue().size(); i++ ) { if( maintenanceIntervals.getValue().get( i ) < maintenanceDurations.getValue().get( i ) ) { throw new InputErrorException("MaintenanceInterval should be greater than MaintenanceDuration (%f) <= (%f)", maintenanceIntervals.getValue().get(i), maintenanceDurations.getValue().get(i)); } } } // INITIALIZATION METHODS public void clearStatistics() { for( int i = 0; i < getMaintenanceOperatingHoursIntervals().size(); i++ ) { hoursForNextMaintenanceOperatingHours.set( i, hoursForNextMaintenanceOperatingHours.get( i ) - this.getWorkingHours() ); } // Determine the time for the first breakdown event /*if ( downtimeIATDistribution == null ) { if( breakdownSeed != 0 ) { breakdownRandGen.initialiseWith( breakdownSeed ); hoursForNextFailure = breakdownRandGen.getUniformFrom_To( 0.5*iATFailure, 1.5*iATFailure ); } else { hoursForNextFailure = getNextBreakdownIAT(); } } else { hoursForNextFailure = getNextBreakdownIAT(); }*/ } /** * *!*!*!*! OVERLOAD !*!*!*!* * Initialize statistics */ public void initialize() { brokendown = false; maintenance = false; associatedBreakdown = false; associatedMaintenance = false; // Create state trace file if required if (testFlag(FLAG_TRACESTATE)) { String fileName = InputAgent.getReportDirectory() + InputAgent.getRunName() + "-" + this.getName() + ".trc"; stateReportFile = new FileEntity( fileName, FileEntity.FILE_WRITE, false ); } lastStartTimePerState.fillWithEntriesOf( getStateList().size(), 0.0 ); secondToLastStartTimePerState.fillWithEntriesOf( getStateList().size(), 0.0 ); workingHours = 0.0; // Calculate the average downtime duration if distributions are used double average = 0.0; if(getDowntimeDurationDistribution() != null) average = getDowntimeDurationDistribution().getExpectedValue(); // Calculate the average downtime inter-arrival time if( (getAvailability() == 1.0 || average == 0.0) ) { iATFailure = 10.0E10; } else { if( getDowntimeIATDistribution() != null ) { iATFailure = getDowntimeIATDistribution().getExpectedValue(); // Adjust the downtime inter-arrival time to get the specified availability if( ! Tester.equalCheckTolerance( iATFailure, ( (average / (1.0 - getAvailability())) - average ) ) ) { getDowntimeIATDistribution().setValueFactor_For( ( (average / (1.0 - getAvailability())) - average) / iATFailure, this ); iATFailure = getDowntimeIATDistribution().getExpectedValue(); } } else { iATFailure = ( (average / (1.0 - getAvailability())) - average ); } } // Determine the time for the first breakdown event hoursForNextFailure = getNextBreakdownIAT(); int ind = this.indexOfState( "Idle" ); if( ind != -1 ) { this.setPresentState( "Idle" ); } brokendown = false; // Start the maintenance network if( firstMaintenanceTimes.getValue().size() != 0 ) { maintenancePendings.fillWithEntriesOf( firstMaintenanceTimes.getValue().size(), 0 ); lastScheduledMaintenanceTimes.fillWithEntriesOf( firstMaintenanceTimes.getValue().size(), Double.POSITIVE_INFINITY ); this.doMaintenanceNetwork(); } // calculate hours for first operating hours breakdown for ( int i = 0; i < getMaintenanceOperatingHoursIntervals().size(); i++ ) { hoursForNextMaintenanceOperatingHours.add( firstMaintenanceOperatingHours.getValue().get( i ) ); maintenanceOperatingHoursPendings.add( 0 ); } } // ACCESSOR METHODS /** * Return the time at which the most recent maintenance is scheduled to end */ public double getMaintenanceEndTime() { return maintenanceEndTime; } /** * Return the time at which a the most recent breakdown is scheduled to end */ public double getBreakdownEndTime() { return breakdownEndTime; } public double getTimeOfLastStateChange() { return timeOfLastStateChange; } /** * Returns the availability proportion. */ public double getAvailability() { return availability.getValue(); } public DoubleListInput getFirstMaintenanceTimes() { return firstMaintenanceTimes; } public boolean getPrintToReport() { return printToReport.getValue(); } public boolean isBrokendown() { return brokendown; } public boolean isBreakdownPending() { return breakdownPending; } public boolean isInAssociatedBreakdown() { return associatedBreakdown; } public boolean isInMaintenance() { return maintenance; } public boolean isInAssociatedMaintenance() { return associatedMaintenance; } public boolean isInService() { return ( brokendown || maintenance || associatedBreakdown || associatedMaintenance ); } public void setBrokendown( boolean bool ) { brokendown = bool; this.setPresentState(); } public void setMaintenance( boolean bool ) { maintenance = bool; this.setPresentState(); } public void setAssociatedBreakdown( boolean bool ) { associatedBreakdown = bool; } public void setAssociatedMaintenance( boolean bool ) { associatedMaintenance = bool; } public ProbabilityDistribution getDowntimeDurationDistribution() { return downtimeDurationDistribution.getValue(); } public double getDowntimeToReleaseEquipment() { return downtimeToReleaseEquipment.getValue(); } public boolean hasServiceDefined() { return( maintenanceDurations.getValue().size() > 0 || getDowntimeDurationDistribution() != null ); } // HOURS AND STATES public void updateStateRecordHours() { if (presentState == null) { timeOfLastStateUpdate = getCurrentTime(); return; } double time = getCurrentTime(); if (time != timeOfLastStateUpdate) { double dur = time - timeOfLastStateUpdate; presentState.addHours(dur); if ( this.isWorking() ) workingHours += dur; timeOfLastStateUpdate = getCurrentTime(); } } /** * Return true if the entity is working */ public boolean isWorking() { return false; } /** * Returns the present status. */ public String getPresentState() { if (presentState == null) return ""; return presentState.getStateName(); } public boolean presentStateEquals(String state) { return getPresentState().equals(state); } public boolean presentStateMatches(String state) { return getPresentState().equalsIgnoreCase(state); } public boolean presentStateStartsWith(String prefix) { return getPresentState().startsWith(prefix); } public boolean presentStateEndsWith(String suffix) { return getPresentState().endsWith(suffix); } protected int getPresentStateIndex() { if (presentState == null) return -1; return presentState.getIndex(); } public void setPresentState() {} /** * Updates the statistics, then sets the present status to be the specified value. */ public void setPresentState( String state ) { if( traceFlag ) this.trace("setState( "+state+" )"); if( traceFlag ) this.traceLine(" Old State = "+getPresentState() ); if( ! presentStateEquals( state ) ) { if (testFlag(FLAG_TRACESTATE)) this.printStateTrace(state); int ind = this.indexOfState( state ); if( ind != -1 ) { this.updateStateRecordHours(); presentState = getStateRecordFor(state); timeOfLastStateChange = getCurrentTime(); if( lastStartTimePerState.size() > 0 ) { if( secondToLastStartTimePerState.size() > 0 ) { secondToLastStartTimePerState.set( ind, lastStartTimePerState.get( ind ) ); } lastStartTimePerState.set( ind, getCurrentTime() ); } } else { throw new ErrorException( this + " Specified state: " + state + " was not found in the StateList: " + this.getStateList() ); } } } /** * Print that state information on the trace state log file */ public void printStateTrace( String state ) { // First state ever if( finalLastState.equals("") ) { finalLastState = state; stateReportFile.putString(String.format("%.5f %s.setState( \"%s\" ) dt = %s\n", 0.0d, this.getName(), getPresentState(), formatNumber(getCurrentTime()))); stateReportFile.flush(); timeOfLastPrintedState = getCurrentTime(); } else { // The final state in a sequence from the previous state change (one step behind) if ( ! Tester.equalCheckTimeStep( timeOfLastPrintedState, getCurrentTime() ) ) { stateReportFile.putString(String.format("%.5f %s.setState( \"%s\" ) dt = %s\n", timeOfLastPrintedState, this.getName(), finalLastState, formatNumber(getCurrentTime() - timeOfLastPrintedState))); // for( int i = 0; i < stateTraceRelatedModelEntities.size(); i++ ) { // ModelEntitiy each = (ModelEntitiy) stateTraceRelatedModelEntities.get( i ); // putString( ) stateReportFile.flush(); timeOfLastPrintedState = getCurrentTime(); } finalLastState = state; } } /** * Returns the amount of time spent in the specified status. */ public double getCurrentCycleHoursFor( String state ) { StateRecord rec = getStateRecordFor(state); return getCurrentCycleHoursFor(rec); } /** * Return spent hours for a given state at the index in stateList */ public double getCurrentCycleHoursFor(int index) { StateRecord rec = getStateRecordFor(index); return getCurrentCycleHoursFor(rec); } public double getCurrentCycleHoursFor(StateRecord state) { double hours = state.getCurrentCycleHours(); if (presentState == state) hours += getCurrentTime() - timeOfLastStateUpdate; return hours; } /** * Set the last time a histogram was updated for this entity */ public void setLastHistogramUpdateTime( double time ) { secondToLastHistogramUpdateTime = lastHistogramUpdateTime; lastHistogramUpdateTime = time; } /** * Returns the time from the start of the start state to the start of the end state */ public double getTimeFromStartState_ToEndState( String startState, String endState) { // Determine the index of the start state int startIndex = this.indexOfState( startState ); if( startIndex == -1 ) { throw new ErrorException( "Specified state: " + startState + " was not found in the StateList." ); } // Determine the index of the end state int endIndex = this.indexOfState( endState ); if( endIndex == -1 ) { throw new ErrorException( "Specified state: " + endState + " was not found in the StateList." ); } // Is the start time of the end state greater or equal to the start time of the start state? if( lastStartTimePerState.get( endIndex ) >= lastStartTimePerState.get( startIndex ) ) { // If either time was not in the present cycle, return NaN if( lastStartTimePerState.get( endIndex ) <= lastHistogramUpdateTime || lastStartTimePerState.get( startIndex ) <= lastHistogramUpdateTime ) { return Double.NaN; } // Return the time from the last start time of the start state to the last start time of the end state return lastStartTimePerState.get( endIndex ) - lastStartTimePerState.get( startIndex ); } else { // If either time was not in the present cycle, return NaN if( lastStartTimePerState.get( endIndex ) <= lastHistogramUpdateTime || secondToLastStartTimePerState.get( startIndex ) <= secondToLastHistogramUpdateTime ) { return Double.NaN; } // Return the time from the second to last start time of the start date to the last start time of the end state return lastStartTimePerState.get( endIndex ) - secondToLastStartTimePerState.get( startIndex ); } } /** * Return the commitment */ public double getCommitment() { return 1.0 - this.getFractionOfTimeForState( "Idle" ); } /** * Return the fraction of time for the given status */ public double getFractionOfTimeForState( String aState ) { if( getTotalHours() > 0.0 ) { return ((this.getTotalHoursFor( aState ) / getTotalHours()) ); } else { return 0.0; } } /** * Return the percentage of time for the given status */ public double getPercentageOfTimeForState( String aState ) { if( getTotalHours() > 0.0 ) { return ((this.getTotalHoursFor( aState ) / getTotalHours()) * 100.0); } else { return 0.0; } } /** * Returns the number of hours the entity is in use. * *!*!*!*! OVERLOAD !*!*!*!* */ public double getWorkingHours() { double hours = 0.0d; if ( this.isWorking() ) hours = getCurrentTime() - timeOfLastStateUpdate; return workingHours + hours; } public Vector getStateList() { return stateList; } public int indexOfState( String state ) { StateRecord stateRecord = stateMap.get( state.toLowerCase() ); if (stateRecord != null) return stateRecord.getIndex(); return -1; } /** * Return total number of states */ public int getNumberOfStates() { return stateMap.size(); } /** * Return the total hours in current cycle for all the states */ public double getCurrentCycleHours() { double total = getCurrentTime() - timeOfLastStateUpdate; for (int i = 0; i < getNumberOfStates(); i++) { total += getStateRecordFor(i).getCurrentCycleHours(); } return total; } // MAINTENANCE METHODS /** * Perform tasks required before a maintenance period */ public void doPreMaintenance() { //@debug@ cr 'Entity should be overloaded' print } /** * Start working again following a breakdown or maintenance period */ public void restart() { //@debug@ cr 'Entity should be overloaded' print } /** * Disconnect routes, release truck assignments, etc. when performing maintenance or breakdown */ public void releaseEquipment() {} public boolean releaseEquipmentForMaintenanceSchedule( int index ) { if( releaseEquipment.getValue() == null ) return true; return releaseEquipment.getValue().get( index ); } public boolean forceMaintenanceSchedule( int index ) { if( forceMaintenance.getValue() == null ) return false; return forceMaintenance.getValue().get( index ); } /** * Perform all maintenance schedules that are due */ public void doMaintenance() { // scheduled maintenance for( int index = 0; index < maintenancePendings.size(); index++ ) { if( this.getMaintenancePendings().get( index ) > 0 ) { if( traceFlag ) this.trace( "Starting Maintenance Schedule: " + index ); this.doMaintenance(index); } } // Operating hours maintenance for( int index = 0; index < maintenanceOperatingHoursPendings.size(); index++ ) { if( this.getWorkingHours() > hoursForNextMaintenanceOperatingHours.get( index ) ) { hoursForNextMaintenanceOperatingHours.set(index, this.getWorkingHours() + getMaintenanceOperatingHoursIntervals().get( index )); maintenanceOperatingHoursPendings.addAt( 1, index ); this.doMaintenanceOperatingHours(index); } } } /** * Perform all the planned maintenance that is due for the given schedule */ public void doMaintenance( int index ) { double wait; if( masterMaintenanceEntity != null ) { wait = masterMaintenanceEntity.getMaintenanceDurations().getValue().get( index ); } else { wait = this.getMaintenanceDurations().getValue().get( index ); } if( wait > 0.0 && maintenancePendings.get( index ) != 0 ) { if( traceFlag ) this.trace( "ModelEntity.doMaintenance_Wait() -- start of maintenance" ); // Keep track of the start and end of maintenance times maintenanceStartTime = getCurrentTime(); if( masterMaintenanceEntity != null ) { maintenanceEndTime = maintenanceStartTime + ( maintenancePendings.get( index ) * masterMaintenanceEntity.getMaintenanceDurations().getValue().get( index ) ); } else { maintenanceEndTime = maintenanceStartTime + ( maintenancePendings.get( index ) * maintenanceDurations.getValue().get( index ) ); } this.setPresentState( "Maintenance" ); maintenance = true; this.doPreMaintenance(); // Release equipment if necessary if( this.releaseEquipmentForMaintenanceSchedule( index ) ) { this.releaseEquipment(); } while( maintenancePendings.get( index ) != 0 ) { maintenancePendings.subAt( 1, index ); scheduleWait( wait ); // If maintenance pending goes negative, something is wrong if( maintenancePendings.get( index ) < 0 ) { this.error( "ModelEntity.doMaintenance_Wait()", "Maintenace pending should not be negative", "maintenacePending = "+maintenancePendings.get( index ) ); } } if( traceFlag ) this.trace( "ModelEntity.doMaintenance_Wait() -- end of maintenance" ); // The maintenance is over this.setPresentState( "Idle" ); maintenance = false; this.restart(); } } /** * Perform all the planned maintenance that is due */ public void doMaintenanceOperatingHours( int index ) { if(maintenanceOperatingHoursPendings.get( index ) == 0 ) return; if( traceFlag ) this.trace( "ModelEntity.doMaintenance_Wait() -- start of maintenance" ); // Keep track of the start and end of maintenance times maintenanceStartTime = getCurrentTime(); maintenanceEndTime = maintenanceStartTime + (maintenanceOperatingHoursPendings.get( index ) * getMaintenanceOperatingHoursDurationFor(index)); this.setPresentState( "Maintenance" ); maintenance = true; this.doPreMaintenance(); while( maintenanceOperatingHoursPendings.get( index ) != 0 ) { //scheduleWait( maintenanceDurations.get( index ) ); scheduleWait( maintenanceEndTime - maintenanceStartTime ); maintenanceOperatingHoursPendings.subAt( 1, index ); // If maintenance pending goes negative, something is wrong if( maintenanceOperatingHoursPendings.get( index ) < 0 ) { this.error( "ModelEntity.doMaintenance_Wait()", "Maintenace pending should not be negative", "maintenacePending = "+maintenanceOperatingHoursPendings.get( index ) ); } } if( traceFlag ) this.trace( "ModelEntity.doMaintenance_Wait() -- end of maintenance" ); // The maintenance is over maintenance = false; this.setPresentState( "Idle" ); this.restart(); } /** * Check if a maintenance is due. if so, try to perform the maintenance */ public boolean checkMaintenance() { if( traceFlag ) this.trace( "checkMaintenance()" ); if( checkOperatingHoursMaintenance() ) { return true; } // List of all entities going to maintenance ArrayList<ModelEntity> sharedMaintenanceEntities; // This is not a master maintenance entity if( masterMaintenanceEntity != null ) { sharedMaintenanceEntities = masterMaintenanceEntity.getSharedMaintenanceList(); } // This is a master maintenance entity else { sharedMaintenanceEntities = getSharedMaintenanceList(); } // If this entity is in shared maintenance relation with a group of entities if( sharedMaintenanceEntities.size() > 0 || masterMaintenanceEntity != null ) { // Are all entities in the group ready for maintenance if( this.areAllEntitiesAvailable() ) { // For every entity in the shared maintenance list plus the master maintenance entity for( int i=0; i <= sharedMaintenanceEntities.size(); i++ ) { ModelEntity aModel; // Locate master maintenance entity( after all entity in shared maintenance list have been taken care of ) if( i == sharedMaintenanceEntities.size() ) { // This entity is manster maintenance entity if( masterMaintenanceEntity == null ) { aModel = this; } // This entity is on the shared maintenannce list of the master maintenance entity else { aModel = masterMaintenanceEntity; } } // Next entity in the shared maintenance list else { aModel = sharedMaintenanceEntities.get( i ); } // Check for aModel maintenances for( int index = 0; index < maintenancePendings.size(); index++ ) { if( aModel.getMaintenancePendings().get( index ) > 0 ) { if( traceFlag ) this.trace( "Starting Maintenance Schedule: " + index ); aModel.startProcess("doMaintenance", index); } } } return true; } else { return false; } } // This block is maintained indipendently else { // Check for maintenances for( int i = 0; i < maintenancePendings.size(); i++ ) { if( maintenancePendings.get( i ) > 0 ) { if( this.canStartMaintenance( i ) ) { if( traceFlag ) this.trace( "Starting Maintenance Schedule: " + i ); this.startProcess("doMaintenance", i); return true; } } } } return false; } /** * Determine how many hours of maintenance is scheduled between startTime and endTime */ public double getScheduledMaintenanceHoursForPeriod( double startTime, double endTime ) { if( traceFlag ) this.trace("Handler.getScheduledMaintenanceHoursForPeriod( "+startTime+", "+endTime+" )" ); double totalHours = 0.0; double firstTime = 0.0; // Add on hours for all pending maintenance for( int i=0; i < maintenancePendings.size(); i++ ) { totalHours += maintenancePendings.get( i ) * maintenanceDurations.getValue().get( i ); } if( traceFlag ) this.traceLine( "Hours of pending maintenances="+totalHours ); // Add on hours for all maintenance scheduled to occur in the given period from startTime to endTime for( int i=0; i < maintenancePendings.size(); i++ ) { // Find the first time that maintenance is scheduled after startTime firstTime = firstMaintenanceTimes.getValue().get( i ); while( firstTime < startTime ) { firstTime += maintenanceIntervals.getValue().get( i ); } if( traceFlag ) this.traceLine(" first time maintenance "+i+" is scheduled after startTime= "+firstTime ); // Now have the first maintenance start time after startTime // Add all maintenances that lie in the given interval while( firstTime < endTime ) { if( traceFlag ) this.traceLine(" Checking for maintenances for period:"+firstTime+" to "+endTime ); // Add the maintenance totalHours += maintenanceDurations.getValue().get( i ); // Update the search period endTime += maintenanceDurations.getValue().get( i ); // Look for next maintenance in new interval firstTime += maintenanceIntervals.getValue().get( i ); if( traceFlag ) this.traceLine(" Adding Maintenance duration = "+maintenanceDurations.getValue().get( i ) ); } } // Return the total hours of maintenance scheduled from startTime to endTime if( traceFlag ) this.traceLine( "Maintenance hours to add= "+totalHours ); return totalHours; } public boolean checkOperatingHoursMaintenance() { if( traceFlag ) this.trace("checkOperatingHoursMaintenance()"); // Check for maintenances for( int i = 0; i < getMaintenanceOperatingHoursIntervals().size(); i++ ) { // If the entity is not available, maintenance cannot start if( ! this.canStartMaintenance( i ) ) continue; if( this.getWorkingHours() > hoursForNextMaintenanceOperatingHours.get( i ) ) { hoursForNextMaintenanceOperatingHours.set(i, (this.getWorkingHours() + getMaintenanceOperatingHoursIntervals().get( i ))); maintenanceOperatingHoursPendings.addAt( 1, i ); if( traceFlag ) this.trace( "Starting Maintenance Operating Hours Schedule : " + i ); this.startProcess("doMaintenanceOperatingHours", i); return true; } } return false; } /** * Wrapper method for doMaintenance_Wait. */ public void doMaintenanceNetwork() { this.startProcess("doMaintenanceNetwork_Wait"); } /** * Network for planned maintenance. * This method should be called in the initialize method of the specific entity. */ public void doMaintenanceNetwork_Wait() { // Initialize schedules for( int i=0; i < maintenancePendings.size(); i++ ) { maintenancePendings.set( i, 0 ); } nextMaintenanceTimes = new DoubleVector(firstMaintenanceTimes.getValue()); nextMaintenanceDuration = 0; // Find the next maintenance event int index = 0; double earliestTime = Double.POSITIVE_INFINITY; for( int i=0; i < nextMaintenanceTimes.size(); i++ ) { double time = nextMaintenanceTimes.get( i ); if( Tester.lessCheckTolerance( time, earliestTime ) ) { earliestTime = time; index = i; nextMaintenanceDuration = maintenanceDurations.getValue().get( i ); } } // Make sure that maintenance for entities on the shared list are being called after those entities have been initialize (AT TIME ZERO) scheduleLastLIFO(); while( true ) { double dt = earliestTime - getCurrentTime(); // Wait for the maintenance check time if( dt > Process.getEventTolerance() ) { scheduleWait( dt ); } // Increment the number of maintenances due for the entity maintenancePendings.addAt( 1, index ); // If this is a master maintenance entity if (getSharedMaintenanceList().size() > 0) { // If all the entities on the shared list are ready for maintenance if( this.areAllEntitiesAvailable() ) { // Put this entity to maintenance if( traceFlag ) this.trace( "Starting Maintenance Schedule: " + index ); this.startProcess("doMaintenance", index); } } // If this entity is maintained independently else { // Do maintenance if possible if( ! this.isInService() && this.canStartMaintenance( index ) ) { // if( traceFlag ) this.trace( "doMaintenanceNetwork_Wait: Starting Maintenance. PresentState = "+presentState+" IsAvailable? = "+this.isAvailable() ); if( traceFlag ) this.trace( "Starting Maintenance Schedule: " + index ); this.startProcess("doMaintenance", index); } // Keep track of the time the maintenance was attempted else { lastScheduledMaintenanceTimes.set( index, getCurrentTime() ); // If skipMaintenance was defined, cancel the maintenance if( this.shouldSkipMaintenance( index ) ) { // if a different maintenance is due, cancel this maintenance boolean cancelMaintenance = false; for( int i=0; i < maintenancePendings.size(); i++ ) { if( i != index ) { if( maintenancePendings.get( i ) > 0 ) { cancelMaintenance = true; break; } } } if( cancelMaintenance || this.isInMaintenance() ) { maintenancePendings.subAt( 1, index ); } } // Do a check after the limit has expired if( this.getDeferMaintenanceLimit( index ) > 0.0 ) { this.startProcess( "scheduleCheckMaintenance", this.getDeferMaintenanceLimit( index ) ); } } } // Determine the next maintenance time nextMaintenanceTimes.addAt( maintenanceIntervals.getValue().get( index ), index ); // Find the next maintenance event index = 0; earliestTime = Double.POSITIVE_INFINITY; for( int i=0; i < nextMaintenanceTimes.size(); i++ ) { double time = nextMaintenanceTimes.get( i ); if( Tester.lessCheckTolerance( time, earliestTime ) ) { earliestTime = time; index = i; nextMaintenanceDuration = maintenanceDurations.getValue().get( i ); } } } } public double getDeferMaintenanceLimit( int index ) { if( deferMaintenanceLimit.getValue() == null ) return 0.0d; return deferMaintenanceLimit.getValue().get( index ); } public void scheduleCheckMaintenance( double wait ) { scheduleWait( wait ); this.checkMaintenance(); } public boolean shouldSkipMaintenance( int index ) { if( skipMaintenanceIfOverlap.getValue().size() == 0 ) return false; return skipMaintenanceIfOverlap.getValue().get( index ); } /** * Return TRUE if there is a pending maintenance for any schedule */ public boolean isMaintenancePending() { for( int i = 0; i < maintenancePendings.size(); i++ ) { if( maintenancePendings.get( i ) > 0 ) { return true; } } for( int i = 0; i < hoursForNextMaintenanceOperatingHours.size(); i++ ) { if( this.getWorkingHours() > hoursForNextMaintenanceOperatingHours.get( i ) ) { return true; } } return false; } public boolean isForcedMaintenancePending() { if( forceMaintenance.getValue() == null ) return false; for( int i = 0; i < maintenancePendings.size(); i++ ) { if( maintenancePendings.get( i ) > 0 && forceMaintenance.getValue().get(i) ) { return true; } } return false; } public ArrayList<ModelEntity> getSharedMaintenanceList () { return sharedMaintenanceList.getValue(); } public IntegerVector getMaintenancePendings () { return maintenancePendings; } public DoubleListInput getMaintenanceDurations() { return maintenanceDurations; } /** * Return the start of the next scheduled maintenance time if not in maintenance, * or the start of the current scheduled maintenance time if in maintenance */ public double getNextMaintenanceStartTime() { if( nextMaintenanceTimes == null ) return Double.POSITIVE_INFINITY; else return nextMaintenanceTimes.getMin(); } /** * Return the duration of the next maintenance event (assuming only one pending) */ public double getNextMaintenanceDuration() { return nextMaintenanceDuration; } // Shows if an Entity would ever go on service public boolean hasServiceScheduled() { if( firstMaintenanceTimes.getValue().size() != 0 || masterMaintenanceEntity != null ) { return true; } return false; } public void setMasterMaintenanceBlock( ModelEntity aModel ) { masterMaintenanceEntity = aModel; } // BREAKDOWN METHODS /** * No Comments Given. */ public void calculateTimeOfNextFailure() { hoursForNextFailure = (this.getWorkingHours() + this.getNextBreakdownIAT()); } /** * Activity Network for Breakdowns. */ public void doBreakdown() { } /** * Prints the header for the entity's state list. * @return bottomLine contains format for each column of the bottom line of the group report */ public IntegerVector printUtilizationHeaderOn( FileEntity anOut ) { IntegerVector bottomLine = new IntegerVector(); if( getStateList().size() != 0 ) { anOut.putStringTabs( "Name", 1 ); bottomLine.add( ReportAgent.BLANK ); int doLoop = getStateList().size(); for( int x = 0; x < doLoop; x++ ) { String state = (String)getStateList().get( x ); anOut.putStringTabs( state, 1 ); bottomLine.add( ReportAgent.AVERAGE_PCT_ONE_DEC ); } anOut.newLine(); } return bottomLine; } /** * Print the entity's name and percentage of hours spent in each state. * @return columnValues are the values for each column in the group report (0 if the value is a String) */ public DoubleVector printUtilizationOn( FileEntity anOut ) { double total; DoubleVector columnValues = new DoubleVector(); if( getNumberOfStates() != 0 ) { total = getTotalHours(); if( !(total == 0.0) ) { anOut.putStringTabs( getName(), 1 ); columnValues.add( 0.0 ); for( int i = 0; i < getNumberOfStates(); i++ ) { double value = getTotalHoursFor( i ) / total; anOut.putDoublePercentWithDecimals( value, 1 ); anOut.putTabs( 1 ); columnValues.add( value ); } anOut.newLine(); } } return columnValues; } /** * This method must be overridden in any subclass of ModelEntity. */ public boolean isAvailable() { throw new ErrorException( "Must override isAvailable in any subclass of ModelEntity." ); } /** * This method must be overridden in any subclass of ModelEntity. */ public boolean canStartMaintenance( int index ) { return isAvailable(); } /** * This method must be overridden in any subclass of ModelEntity. */ public boolean canStartForcedMaintenance() { return isAvailable(); } /** * This method must be overridden in any subclass of ModelEntity. */ public boolean areAllEntitiesAvailable() { throw new ErrorException( "Must override areAllEntitiesAvailable in any subclass of ModelEntity." ); } /** * Return the time of the next breakdown duration */ public double getBreakdownDuration() { // if( traceFlag ) this.trace( "getBreakdownDuration()" ); // If a distribution was specified, then select a duration randomly from the distribution if ( getDowntimeDurationDistribution() != null ) { return getDowntimeDurationDistribution().nextValue(); } else { return 0.0; } } /** * Return the time of the next breakdown IAT */ public double getNextBreakdownIAT() { if( getDowntimeIATDistribution() != null ) { return getDowntimeIATDistribution().nextValue(); } else { return iATFailure; } } public double getHoursForNextFailure() { return hoursForNextFailure; } public void setHoursForNextFailure( double hours ) { hoursForNextFailure = hours; } /** Returns a vector of strings describing the ModelEntity. Override to add details @return Vector - tab delimited strings describing the DisplayEntity **/ @Override public Vector getInfo() { Vector info = super.getInfo(); if ( presentStateEquals("") ) info.addElement( "Present State\t<no state>" ); else info.addElement( "Present State" + "\t" + getPresentState() ); return info; } protected DoubleVector getMaintenanceOperatingHoursIntervals() { return maintenanceOperatingHoursIntervals.getValue(); } protected double getMaintenanceOperatingHoursDurationFor(int index) { return maintenanceOperatingHoursDurations.getValue().get(index); } protected ProbabilityDistribution getDowntimeIATDistribution() { return downtimeIATDistribution.getValue(); } }
package com.solace.kafka.connect; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.kafka.common.config.ConfigDef; import org.apache.kafka.common.config.ConfigDef.Type; import org.apache.kafka.common.utils.AppInfoParser; import org.apache.kafka.connect.errors.ConnectException; import org.apache.kafka.connect.source.SourceRecord; import org.apache.kafka.connect.source.SourceTask; import org.apache.kafka.common.config.types.Password; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.solacesystems.jcsmp.JCSMPException; import com.solacesystems.jcsmp.JCSMPFactory; import com.solacesystems.jcsmp.JCSMPProperties; import com.solacesystems.jcsmp.JCSMPReconnectEventHandler; import com.solacesystems.jcsmp.JCSMPSession; import com.solacesystems.jcsmp.Queue; import com.solacesystems.jcsmp.SessionEventArgs; import com.solacesystems.jcsmp.SessionEventHandler; import com.solacesystems.jcsmp.Topic; import com.solacesystems.jcsmp.XMLMessageConsumer; import com.solacesystems.jcsmp.XMLMessageListener; import com.solacesystems.jcsmp.BytesXMLMessage; import com.solacesystems.jcsmp.EndpointProperties; import com.solacesystems.jcsmp.JCSMPChannelProperties; public class SolaceSourceTask extends SourceTask implements SessionEventHandler { private static final Logger log = LoggerFactory.getLogger(SolaceSourceTask.class); protected JCSMPSession session; public JCSMPSession getSession() { return session; } protected Topic topic; protected XMLMessageConsumer consumer; protected String instanceName; protected String smfHost; protected String msgVpnName; protected String clientUsername; protected Password clientPassword; protected String solaceTopicName; protected String kafkaTopicName; protected int longPollInterval = SolaceConnectorConstants.DEFAULT_LONG_POLL_INTERVAL; protected int shortPollInterval = SolaceConnectorConstants.DEFAULT_SHORT_POLL_INTERVAL; protected int kafkaBufferSize = SolaceConnectorConstants.DEFAULT_POLL_BATCH_SIZE; protected SolaceConverter converter; protected int reconnectRetries; protected int connectTimeoutInMillis; protected int connectRetriesPerHost; protected int keepAliveIntervalInMillis; protected int reconnectRetryWaitInMillis; protected int compressionLevel; protected String haSentinelQueueName = null; public String getHASentinelQueueName() { return haSentinelQueueName; } protected HASentinel haSentinel = null; @Override public String version() { return AppInfoParser.getVersion(); } /** * This is where the main work is done. Grab a bunch of messages from the Solace topic and put in * a list which will be consumed by Kafka. * * Uses the Solace JCSMP API in synchronous mode with a combination of short and long polling. * - When no messages are available this method blocks for the longPollInterval. * - When messages are available we try to assemble kafkaBufferSize records together to pass to Kafka, * allowing max shortPollInterval between consecutive messages. */ @Override public List<SourceRecord> poll() throws InterruptedException { log.debug(instanceName+" in poll()"); ArrayList<SourceRecord> records = new ArrayList<SourceRecord>(); if(haSentinel != null && haSentinel.isActiveMember() || haSentinel == null) { try { BytesXMLMessage msg = consumer.receive(longPollInterval); if (msg == null) return records; records.add(converter.convertMessage(msg)); //Now fast poll as long as we keep getting messages int i=0; while(i < kafkaBufferSize-1) { i++; msg = consumer.receive(shortPollInterval); if (msg == null) break; records.add(converter.convertMessage(msg)); } } catch (JCSMPException e) { e.printStackTrace(); } log.info("{} poll() found {} records",instanceName,records.size()); return records; } else { log.debug("{} poll() not active ",instanceName); Thread.sleep(longPollInterval); return records; } } @Override public void start(Map<String, String> propMap) { setParameters(propMap); log.info("Solace Kafka Source connector started. Will connect to router at url:" +smfHost+" vpn:"+msgVpnName+" user:"+clientUsername+" pass:"+clientPassword +" Solace topic:"+solaceTopicName+" Kafka topic:"+kafkaTopicName); // Now start the subscribers try { connect(); } catch (JCSMPException e) { // TODO Auto-generated catch block e.printStackTrace(); throw new ConnectException("SolaceSourceTask failed to connect.", e); } // Consume messages synchronously converter = new SolaceConverter(this); try { if (consumer == null) { consumer = session.getMessageConsumer((XMLMessageListener)null); session.addSubscription(topic); } consumer.start(); } catch (JCSMPException e) { // TODO Auto-generated catch block e.printStackTrace(); throw new ConnectException("SolaceSourceTask failed to start listener.", e); } } protected void setParameters(Map<String, String> propMap) { // Pull the parameters needed to connect to the Message Router SolaceConfigDef conf = new SolaceConfigDef(SolaceConfigDef.defaultConfig(), propMap); instanceName = conf.getString(SolaceConnectorConstants.CONNECTOR_INSTANCE); smfHost = conf.getString(SolaceConnectorConstants.SOLACE_URL); msgVpnName = conf.getString(SolaceConnectorConstants.SOLACE_VPN); clientUsername = conf.getString(SolaceConnectorConstants.SOLACE_USERNAME); clientPassword = conf.getPassword(SolaceConnectorConstants.SOLACE_PASSWORD); kafkaTopicName = conf.getString(SolaceConnectorConstants.KAFKA_TOPIC); solaceTopicName = conf.getString(SolaceConnectorConstants.SOLACE_TOPIC); longPollInterval = conf.getInt(SolaceConnectorConstants.LONG_POLL_INTERVAL); shortPollInterval = conf.getInt(SolaceConnectorConstants.SHORT_POLL_INTERVAL); kafkaBufferSize = conf.getInt(SolaceConnectorConstants.POLL_BATCH_SIZE); reconnectRetries = conf.getInt(SolaceConnectorConstants.SOLACE_RECONNECT_RETRIES); reconnectRetryWaitInMillis = conf.getInt(SolaceConnectorConstants.SOLACE_RECONNECT_RETRY_WAIT); haSentinelQueueName = conf.getString(SolaceConnectorConstants.SOLACE_HA_QUEUE); } @Override public void stop() { if (consumer != null) { consumer.close(); } if (session != null) { session.closeSession(); } } public void connect() throws JCSMPException { final JCSMPProperties properties = new JCSMPProperties(); properties.setProperty(JCSMPProperties.HOST, smfHost); properties.setProperty(JCSMPProperties.VPN_NAME, msgVpnName); properties.setProperty(JCSMPProperties.USERNAME, clientUsername); if (clientPassword != null) { properties.setProperty(JCSMPProperties.PASSWORD, clientPassword.value()); } properties.setProperty(JCSMPProperties.APPLICATION_DESCRIPTION, SolaceConnectorConstants.CONNECTOR_NAME+" Version "+SolaceConnectorConstants.CONNECTOR_VERSION); // Settings for automatic reconnection to Solace Router JCSMPChannelProperties channelProps = (JCSMPChannelProperties) properties.getProperty(JCSMPProperties.CLIENT_CHANNEL_PROPERTIES); channelProps.setReconnectRetries(reconnectRetries); channelProps.setReconnectRetryWaitInMillis(reconnectRetryWaitInMillis); channelProps.setConnectTimeoutInMillis(connectTimeoutInMillis); channelProps.setConnectRetriesPerHost(connectRetriesPerHost); channelProps.setKeepAliveIntervalInMillis(keepAliveIntervalInMillis); properties.setProperty(JCSMPProperties.CLIENT_CHANNEL_PROPERTIES, channelProps); log.info("Connecting to Solace Message Router..."); topic = JCSMPFactory.onlyInstance().createTopic(solaceTopicName); session = JCSMPFactory.onlyInstance().createSession(properties, null, this); session.connect(); log.info("Connection succeeded!"); if (haSentinelQueueName != null) { haSentinel = new HASentinel(instanceName, session, haSentinelQueueName); haSentinel.start(); } } @Override public void handleEvent(SessionEventArgs arg0) { log.info("Received event on Session:"+arg0.getResponseCode()+" "+arg0.getInfo()); } }
package com.teamwizardry.refraction.api.beam; import com.teamwizardry.librarianlib.common.network.PacketHandler; import com.teamwizardry.librarianlib.common.util.bitsaving.IllegalValueSetException; import com.teamwizardry.refraction.api.Constants; import com.teamwizardry.refraction.api.beam.Effect.EffectType; import com.teamwizardry.refraction.api.internal.PacketLaserFX; import com.teamwizardry.refraction.api.raytrace.EntityTrace; import net.minecraft.block.state.IBlockState; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.RayTraceResult; import net.minecraft.util.math.Vec3d; import net.minecraft.world.World; import net.minecraftforge.common.util.INBTSerializable; import net.minecraftforge.fml.common.FMLCommonHandler; import net.minecraftforge.fml.common.network.NetworkRegistry; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.awt.*; import java.util.UUID; import java.util.concurrent.ThreadLocalRandom; public class Beam implements INBTSerializable<NBTTagCompound> { /** * The initial position the beams comes from. */ public Vec3d initLoc; /** * The vector that specifies the inclination of the beam. * Set it to your final location and it'll work. */ public Vec3d slope; /** * The destination of the beam. Don't touch this, just set the slope to the final loc * and let this class handle it unless you know what you're doing. */ public Vec3d finalLoc; /** * The color of the beam including it's alpha. */ @NotNull public Color color = Color.WHITE; /** * The world the beam will spawn in. */ @NotNull public World world; /** * The effect the beam will produce across itself or at it's destination */ @Nullable public Effect effect; /** * Specify whether this beam will be aesthetic only or not. * If not, it will run the effect dictated by the color unless the effect is changed. */ public boolean enableEffect = true; /** * If true, the beam will phase through entities. */ public boolean ignoreEntities = false; /** * The raytrace produced from the beam after it spawns. * Contains some neat methods you can use. */ public RayTraceResult trace; /** * The range of the raytrace. Will default to Beam_RANGE unless otherwise specified. */ public double range = Constants.BEAM_RANGE; /** * A unique identifier for a beam. Used for uniqueness checks. */ @NotNull public UUID uuid = UUID.randomUUID(); /** * The number of times this beam has bounced or been reflected. */ public int bouncedTimes = 0; /** * The amount of times this beam is allowed to bounce or reflect. */ public int allowedBounceTimes = Constants.BEAM_BOUNCE_LIMIT; public Beam(@NotNull World world, @NotNull Vec3d initLoc, @NotNull Vec3d slope, @NotNull Color color) { this.world = world; this.initLoc = initLoc; this.slope = slope; this.finalLoc = slope.normalize().scale(128).add(initLoc); this.color = color; } public Beam(World world, double initX, double initY, double initZ, double slopeX, double slopeY, double slopeZ, Color color) { this(world, new Vec3d(initX, initY, initZ), new Vec3d(slopeX, slopeY, slopeZ), color); } public Beam(World world, double initX, double initY, double initZ, double slopeX, double slopeY, double slopeZ, float red, float green, float blue, float alpha) { this(world, initX, initY, initZ, slopeX, slopeY, slopeZ, new Color(red, green, blue, alpha)); } public Beam(NBTTagCompound compound) { deserializeNBT(compound); } /** * Will create a beam that's exactly like the one passed. * * @return The new beam created. Can be modified as needed. */ public Beam createSimilarBeam() { return createSimilarBeam(initLoc, finalLoc); } /** * Will create a beam that's exactly like the one passed except in color. * * @return The new beam created. Can be modified as needed. */ public Beam createSimilarBeam(Color color) { return createSimilarBeam(initLoc, finalLoc, color); } /** * Will create a similar beam that starts from the position this beam ended at * and will set it's slope to the one specified. So it's a new beam from the position * you last hit to the new one you specify. * * @param slope The slope or destination or final location the beam will point to. * @return The new beam created. Can be modified as needed. */ public Beam createSimilarBeam(Vec3d slope) { return createSimilarBeam(finalLoc, slope); } /** * Will create a similar beam that starts and ends in the positions you specify * * @param init The initial location or origin to spawn the beam from. * @param dir The direction or slope or final destination or location the beam will point to. * @return The new beam created. Can be modified as needed. */ public Beam createSimilarBeam(Vec3d init, Vec3d dir) { return createSimilarBeam(init, dir, color); } /** * Will create a similar beam that starts and ends in the positions you specify, with a custom color. * * @param init The initial location or origin to spawn the beam from. * @param dir The direction or slope or final destination or location the beam will point to. * @return The new beam created. Can be modified as needed. */ public Beam createSimilarBeam(Vec3d init, Vec3d dir, Color color) { return new Beam(world, init, dir, color) .setIgnoreEntities(ignoreEntities) .setEnableEffect(enableEffect) .setUUID(uuid) .setAllowedBounceTimes(allowedBounceTimes) .setBouncedTimes(bouncedTimes) .incrementBouncedTimes(); } /** * Will set the amount of times this beam has already bounced or been reflected * * @param bouncedTimes The amount of times this beam has bounced or been reflected * @return This beam itself for the convenience of editing a beam in one line/chain. */ public Beam setBouncedTimes(int bouncedTimes) { this.bouncedTimes = bouncedTimes; return this; } /** * Will set the amount of times this beam will be allowed to bounce or reflect. * * @param allowedBounceTimes The amount of times this beam is allowed to bounce or reflect * @return This beam itself for the convenience of editing a beam in one line/chain. */ public Beam setAllowedBounceTimes(int allowedBounceTimes) { this.allowedBounceTimes = allowedBounceTimes; return this; } /** * Will change the slope or destination or final location the beam will point to. * * @param slope The final location or destination. * @return This beam itself for the convenience of editing a beam in one line/chain. */ public Beam setSlope(@NotNull Vec3d slope) { this.slope = slope; this.finalLoc = slope.normalize().scale(128).add(initLoc); return this; } /** * Will increment the amount of times this beam has bounced or reflected * * @return This beam itself for the convenience of editing a beam in one line/chain. */ public Beam incrementBouncedTimes() { bouncedTimes++; return this; } /** * Will change the color of the beam with the alpha. * * @param color The color of the new beam. * @return This beam itself for the convenience of editing a beam in one line/chain. */ public Beam setColor(@NotNull Color color) { this.color = color; return this; } /** * If set to true, the beam will phase through entities. * * @param ignoreEntities The boolean that will specify if the beam should phase through blocks or not. Default false. * @return This beam itself for the convenience of editing a beam in one line/chain. */ public Beam setIgnoreEntities(boolean ignoreEntities) { this.ignoreEntities = ignoreEntities; return this; } /** * If set to false, the beam will be an aesthetic only beam that will not produce any effect. * * @param enableEffect The boolean that will specify if the beam should enable it's effect or not. Default true. * @return This beam itself for the convenience of editing a beam in one line/chain. */ public Beam setEnableEffect(boolean enableEffect) { this.enableEffect = enableEffect; return this; } /** * Will set the beam's new starting position or origin and will continue on towards the slope still specified. * * @param initLoc The new initial location to set the beam to start from. * @return This beam itself for the convenience of editing a beam in one line/chain. */ public Beam setInitLoc(@NotNull Vec3d initLoc) { this.initLoc = initLoc; this.finalLoc = slope.normalize().scale(128).add(initLoc); return this; } /** * Will set the beam's effect if you don't want it to autodetect the effect by itself from the color * you specified. * * @param effect The new effect this beam will produce. * @return This beam itself for the convenience of editing a beam in one line/chain. */ public Beam setEffect(@Nullable Effect effect) { this.effect = effect; return this; } /** * Will set the range the raytrace will attempt. * * @param range The new range of the beam. Default: Constants.BEAM_RANGE * @return This beam itself for the convenience of editing a beam in one line/chain. */ public Beam setRange(double range) { this.range = range; return this; } public UUID getUUID() { return this.uuid; } public Beam setUUID(UUID uuid) { this.uuid = uuid; return this; } private Beam initializeVariables() { // EFFECT CHECKING // if (effect == null && enableEffect) { Effect tempEffect = EffectTracker.getEffect(this); if (tempEffect != null) { if (tempEffect.getCooldown() == 0) effect = tempEffect; else if (ThreadLocalRandom.current().nextInt(0, tempEffect.getCooldown()) == 0) effect = tempEffect; } } else if (effect != null && !enableEffect) effect = null; // EFFECT CHECKING // // BEAM PHASING CHECKS // if (ignoreEntities || (effect != null && effect.getType() == EffectType.BEAM)) // If anyone of these are true, phase beam trace = EntityTrace.cast(world, initLoc, slope, range, true); else trace = EntityTrace.cast(world, initLoc, slope, range, false); // BEAM PHASING CHECKS // if (trace != null && trace.hitVec != null) this.finalLoc = trace.hitVec; return this; } /** * Will spawn the final complete beam. */ public void spawn() { if (world.isRemote) return; if (color.getAlpha() <= 1) return; if (bouncedTimes > allowedBounceTimes) return; initializeVariables(); if (trace == null) return; if (trace.hitVec == null) return; if (finalLoc == null) return; // EFFECT HANDLING // boolean pass = true; // IBeamHandler handling if (trace.typeOfHit == RayTraceResult.Type.BLOCK) { IBlockState state = world.getBlockState(trace.getBlockPos()); if (state.getBlock() instanceof IBeamHandler) { ReflectionTracker.getInstance(world).recieveBeam(world, trace.getBlockPos(), (IBeamHandler) state.getBlock(), this); pass = false; } } // Effect handling if (effect != null) { if (effect.getType() == EffectType.BEAM) EffectTracker.addEffect(world, this); else if (pass) { if (effect.getType() == EffectType.SINGLE) { if (trace.typeOfHit != RayTraceResult.Type.MISS) EffectTracker.addEffect(world, trace.hitVec, effect); else if (trace.typeOfHit == RayTraceResult.Type.BLOCK) { BlockPos pos = trace.getBlockPos(); EffectTracker.addEffect(world, new Vec3d(pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5), effect); } } } } // EFFECT HANDLING // Particle packet sender PacketHandler.NETWORK.sendToAllAround(new PacketLaserFX(initLoc, finalLoc, color), new NetworkRegistry.TargetPoint(world.provider.getDimension(), initLoc.xCoord, initLoc.yCoord, initLoc.zCoord, 256)); } @Override public boolean equals(Object other) { return other instanceof Beam && ((Beam) other).uuid.equals(uuid); } @Override public int hashCode() { return uuid.hashCode(); } @Override public NBTTagCompound serializeNBT() { NBTTagCompound compound = new NBTTagCompound(); compound.setDouble("init_loc_x", initLoc.xCoord); compound.setDouble("init_loc_y", initLoc.yCoord); compound.setDouble("init_loc_z", initLoc.zCoord); compound.setDouble("slope_x", slope.xCoord); compound.setDouble("slope_y", slope.yCoord); compound.setDouble("slope_z", slope.zCoord); compound.setInteger("color", color.getRGB()); compound.setInteger("color_alpha", color.getAlpha()); compound.setInteger("world", world.provider.getDimension()); compound.setUniqueId("uuid", uuid); compound.setBoolean("ignore_entities", ignoreEntities); compound.setBoolean("enable_effect", enableEffect); return compound; } @Override public void deserializeNBT(NBTTagCompound nbt) { if (nbt.hasKey("world")) world = FMLCommonHandler.instance().getMinecraftServerInstance().worldServerForDimension(nbt.getInteger("dim")); else throw new NullPointerException("'world' key not found or missing in deserialized beam object."); if (nbt.hasKey("init_loc_x") && nbt.hasKey("init_loc_y") && nbt.hasKey("init_loc_z")) initLoc = new Vec3d(nbt.getDouble("init_loc_x"), nbt.getDouble("init_loc_y"), nbt.getDouble("init_loc_z")); else throw new NullPointerException("'init_loc' key not found or missing in deserialized beam object."); if (nbt.hasKey("slope_loc_x") && nbt.hasKey("slope_loc_y") && nbt.hasKey("slope_loc_z")) { slope = new Vec3d(nbt.getDouble("slope_x"), nbt.getDouble("slope_y"), nbt.getDouble("slope_z")); finalLoc = slope.normalize().scale(128).add(initLoc); } else throw new NullPointerException("'slope' key not found or missing in deserialized beam object."); if (nbt.hasKey("color")) { color = new Color(nbt.getInteger("color")); color = new Color(color.getRed(), color.getGreen(), color.getBlue(), nbt.getInteger("color_alpha")); } else throw new NullPointerException("'color' or 'color_alpha' keys not found or missing in deserialized beam object."); if (nbt.hasKey("uuid")) if (nbt.hasKey("uuid")) uuid = nbt.getUniqueId("uuid"); else throw new IllegalValueSetException("'uuid' key not found or missing in deserialized beam object."); if (nbt.hasKey("ignore_entities")) ignoreEntities = nbt.getBoolean("ignore_entities"); if (nbt.hasKey("enable_effect")) enableEffect = nbt.getBoolean("enable_effect"); } }
package com.treasure_data.jdbc; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.ResultSet; import java.sql.RowIdLifetime; import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; import org.json.simple.JSONValue; import com.treasure_data.jdbc.command.ClientAPI; import com.treasure_data.jdbc.command.TDClientAPI; import com.treasure_data.model.TableSummary; public class TDDatabaseMetaData implements DatabaseMetaData, Constants { private ClientAPI api; private static final char SEARCH_STRING_ESCAPE = '\\'; private static final int maxColumnNameLength = 128; public TDDatabaseMetaData(TDConnection conn) { api = new TDClientAPI(conn); } public boolean allProceduresAreCallable() throws SQLException { throw new SQLException(new UnsupportedOperationException()); } public boolean allTablesAreSelectable() throws SQLException { return true; } public boolean autoCommitFailureClosesAllResultSets() throws SQLException { throw new SQLException(new UnsupportedOperationException()); } public boolean dataDefinitionCausesTransactionCommit() throws SQLException { throw new SQLException(new UnsupportedOperationException()); } public boolean dataDefinitionIgnoredInTransactions() throws SQLException { throw new SQLException(new UnsupportedOperationException()); } public boolean deletesAreDetected(int type) throws SQLException { throw new SQLException(new UnsupportedOperationException()); } public boolean doesMaxRowSizeIncludeBlobs() throws SQLException { throw new SQLException(new UnsupportedOperationException()); } public ResultSet getAttributes(String catalog, String schemaPattern, String typeNamePattern, String attributeNamePattern) throws SQLException { throw new SQLException(new UnsupportedOperationException()); } public ResultSet getBestRowIdentifier(String catalog, String schema, String table, int scope, boolean nullable) throws SQLException { throw new SQLException(new UnsupportedOperationException()); } public String getCatalogSeparator() throws SQLException { return "."; } public String getCatalogTerm() throws SQLException { return "database"; } public ResultSet getCatalogs() throws SQLException { try { List<String> names = new ArrayList<String>(); names.add("TABLE_CAT"); List<String> types = new ArrayList<String>(); types.add("STRING"); List<String> data0 = new ArrayList<String>(); data0.add("default"); return new TDMetaDataResultSet<String>(names, types, data0) { private int cnt = 0; public boolean next() throws SQLException { if (cnt < data.size()) { List<Object> a = new ArrayList<Object>(1); // TABLE_CAT String => table // catalog (may be null) a.add(data.get(cnt)); row = a; cnt++; return true; } else { return false; } } }; } catch (Exception e) { throw new SQLException(e); } } public ResultSet getClientInfoProperties() throws SQLException { throw new SQLException(new UnsupportedOperationException()); } public ResultSet getColumnPrivileges(String catalog, String schema, String table, String columnNamePattern) throws SQLException { throw new SQLException(new UnsupportedOperationException()); } /** * Convert a pattern containing JDBC catalog search wildcards into Java * regex patterns. * * @param pattern * input which may contain '%' or '_' wildcard characters, or * these characters escaped using * {@link #getSearchStringEscape()}. * @return replace %/_ with regex search characters, also handle escaped * characters. */ private String convertPattern(final String pattern) { if (pattern == null) { return ".*"; } else { StringBuilder result = new StringBuilder(pattern.length()); boolean escaped = false; for (int i = 0, len = pattern.length(); i < len; i++) { char c = pattern.charAt(i); if (escaped) { if (c != SEARCH_STRING_ESCAPE) { escaped = false; } result.append(c); } else { if (c == SEARCH_STRING_ESCAPE) { escaped = true; continue; } else if (c == '%') { result.append(".*"); } else if (c == '_') { result.append('.'); } else { result.append(c); } } } return result.toString(); } } public ResultSet getColumns(String catalog, final String schemaPattern, final String tableNamePattern, final String columnNamePattern) throws SQLException { List<TDColumn> columns = new ArrayList<TDColumn>(); try { if (catalog == null) { catalog = "default"; } String regtableNamePattern = convertPattern(tableNamePattern); String regcolumnNamePattern = convertPattern(columnNamePattern); List<TableSummary> ts = api.showTables(); for (TableSummary t : ts) { if (t.getName().matches(regtableNamePattern)) { Object o = JSONValue.parse(t.getSchema()); List<List<String>> schemaFields = (List<List<String>>) o; int ordinalPos = 1; for (List<String> schemaField : schemaFields) { String fieldName = schemaField.get(0); String fieldType = schemaField.get(1); if (fieldName.matches(regcolumnNamePattern)) { columns.add(new TDColumn(fieldName, t.getName(), catalog, "TABLE", "comment", ordinalPos)); // TODO ordinalPos++; } } } } // for (String table : tables) { // if (table.matches(regtableNamePattern)) { // List<FieldSchema> fields = client.get_schema(catalog, table); // int ordinalPos = 1; // for (FieldSchema field : fields) { // if (field.getName().matches(regcolumnNamePattern)) { // columns.add(new JdbcColumn(field.getName(), table, // catalog, field.getType(), field // .getComment(), ordinalPos)); // ordinalPos++; Collections.sort(columns, new GetColumnsComparator()); return new TDMetaDataResultSet<TDColumn>( Arrays.asList( "TABLE_CAT", "TABLE_SCHEM", "TABLE_NAME", "COLUMN_NAME", "DATA_TYPE", "TYPE_NAME", "COLUMN_SIZE", "BUFFER_LENGTH", "DECIMAL_DIGITS", "NUM_PREC_RADIX", "NULLABLE", "REMARKS", "COLUMN_DEF", "SQL_DATA_TYPE", "SQL_DATETIME_SUB", "CHAR_OCTET_LENGTH", "ORDINAL_POSITION", "IS_NULLABLE", "SCOPE_CATLOG", "SCOPE_SCHEMA", "SCOPE_TABLE", "SOURCE_DATA_TYPE"), Arrays.asList("STRING", "STRING", "STRING", "STRING", "INT", "STRING", "INT", "INT", "INT", "INT", "INT", "STRING", "STRING", "INT", "INT", "INT", "INT", "STRING", "STRING", "STRING", "STRING", "INT"), columns) { private int cnt = 0; public boolean next() throws SQLException { if (cnt < data.size()) { List<Object> a = new ArrayList<Object>(20); TDColumn column = data.get(cnt); a.add(column.getTableCatalog()); // TABLE_CAT String => // table catalog (may // be null) a.add(null); // TABLE_SCHEM String => table schema (may // be null) a.add(column.getTableName()); // TABLE_NAME String => // table name a.add(column.getColumnName()); // COLUMN_NAME String => // column name a.add(column.getSqlType()); // DATA_TYPE short => SQL // type from java.sql.Types a.add(column.getType()); // TYPE_NAME String => Data // source dependent type name. a.add(column.getColumnSize()); // COLUMN_SIZE int => // column size. a.add(null); // BUFFER_LENGTH is not used. a.add(column.getDecimalDigits()); // DECIMAL_DIGITS int // => number of // fractional digits a.add(column.getNumPrecRadix()); // NUM_PREC_RADIX int // => typically either // 10 or 2 a.add(DatabaseMetaData.columnNullable); // NULLABLE int // => is NULL // allowed? a.add(column.getComment()); // REMARKS String => comment // describing column (may be // null) a.add(null); // COLUMN_DEF String => default value (may // be null) a.add(null); // SQL_DATA_TYPE int => unused a.add(null); // SQL_DATETIME_SUB int => unused a.add(null); // CHAR_OCTET_LENGTH int a.add(column.getOrdinalPos()); // ORDINAL_POSITION int a.add("YES"); // IS_NULLABLE String a.add(null); // SCOPE_CATLOG String a.add(null); // SCOPE_SCHEMA String a.add(null); // SCOPE_TABLE String a.add(null); // SOURCE_DATA_TYPE short row = a; cnt++; return true; } else { return false; } } }; } catch (Exception e) { throw new SQLException(e); } } /** * We sort the output of getColumns to guarantee jdbc compliance. First * check by table name then by ordinal position */ private class GetColumnsComparator implements Comparator<TDColumn> { public int compare(TDColumn o1, TDColumn o2) { int compareName = o1.getTableName().compareTo(o2.getTableName()); if (compareName == 0) { if (o1.getOrdinalPos() > o2.getOrdinalPos()) { return 1; } else if (o1.getOrdinalPos() < o2.getOrdinalPos()) { return -1; } return 0; } else { return compareName; } } } public Connection getConnection() throws SQLException { throw new SQLException("Method not supported"); } public ResultSet getCrossReference(String primaryCatalog, String primarySchema, String primaryTable, String foreignCatalog, String foreignSchema, String foreignTable) throws SQLException { throw new SQLException("Method not supported"); } public int getDatabaseMajorVersion() throws SQLException { throw new SQLException("Method not supported"); } public int getDatabaseMinorVersion() throws SQLException { throw new SQLException("Method not supported"); } public String getDatabaseProductName() throws SQLException { return DATABASE_NAME; } public String getDatabaseProductVersion() throws SQLException { return FULL_VERSION_DATABASE; } public int getDefaultTransactionIsolation() throws SQLException { return Connection.TRANSACTION_NONE; } public int getDriverMajorVersion() { return MAJOR_VERSION; } public int getDriverMinorVersion() { return MINOR_VERSION; } public String getDriverName() throws SQLException { return TreasureDataDriver.class.getName(); } public String getDriverVersion() throws SQLException { return FULL_VERSION; } public ResultSet getExportedKeys(String catalog, String schema, String table) throws SQLException { throw new SQLException("Method not supported"); } public String getExtraNameCharacters() throws SQLException { throw new SQLException("Method not supported"); } public ResultSet getFunctionColumns(String arg0, String arg1, String arg2, String arg3) throws SQLException { throw new SQLException("Method not supported"); } public ResultSet getFunctions(String arg0, String arg1, String arg2) throws SQLException { throw new SQLException("Method not supported"); } public String getIdentifierQuoteString() throws SQLException { throw new SQLException("Method not supported"); } public ResultSet getImportedKeys(String catalog, String schema, String table) throws SQLException { throw new SQLException("Method not supported"); } public ResultSet getIndexInfo(String catalog, String schema, String table, boolean unique, boolean approximate) throws SQLException { throw new SQLException("Method not supported"); } public int getJDBCMajorVersion() throws SQLException { return 3; } public int getJDBCMinorVersion() throws SQLException { return 0; } public int getMaxBinaryLiteralLength() throws SQLException { throw new SQLException("Method not supported"); } public int getMaxCatalogNameLength() throws SQLException { throw new SQLException("Method not supported"); } public int getMaxCharLiteralLength() throws SQLException { throw new SQLException("Method not supported"); } /** * Returns the value of maxColumnNameLength. * * @param int */ public int getMaxColumnNameLength() throws SQLException { return maxColumnNameLength; } public int getMaxColumnsInGroupBy() throws SQLException { throw new SQLException("Method not supported"); } public int getMaxColumnsInIndex() throws SQLException { throw new SQLException("Method not supported"); } public int getMaxColumnsInOrderBy() throws SQLException { throw new SQLException("Method not supported"); } public int getMaxColumnsInSelect() throws SQLException { throw new SQLException("Method not supported"); } public int getMaxColumnsInTable() throws SQLException { throw new SQLException("Method not supported"); } public int getMaxConnections() throws SQLException { throw new SQLException("Method not supported"); } public int getMaxCursorNameLength() throws SQLException { throw new SQLException("Method not supported"); } public int getMaxIndexLength() throws SQLException { throw new SQLException("Method not supported"); } public int getMaxProcedureNameLength() throws SQLException { throw new SQLException("Method not supported"); } public int getMaxRowSize() throws SQLException { throw new SQLException("Method not supported"); } public int getMaxSchemaNameLength() throws SQLException { throw new SQLException("Method not supported"); } public int getMaxStatementLength() throws SQLException { throw new SQLException("Method not supported"); } public int getMaxStatements() throws SQLException { throw new SQLException("Method not supported"); } public int getMaxTableNameLength() throws SQLException { throw new SQLException("Method not supported"); } public int getMaxTablesInSelect() throws SQLException { throw new SQLException("Method not supported"); } public int getMaxUserNameLength() throws SQLException { throw new SQLException("Method not supported"); } public String getNumericFunctions() throws SQLException { return ""; } public ResultSet getPrimaryKeys(String catalog, String schema, String table) throws SQLException { throw new SQLException("TD tables don't have primary keys"); } public ResultSet getProcedureColumns(String catalog, String schemaPattern, String procedureNamePattern, String columnNamePattern) throws SQLException { throw new SQLException("Method not supported"); } public String getProcedureTerm() throws SQLException { throw new SQLException("Method not supported"); } public ResultSet getProcedures(String catalog, String schemaPattern, String procedureNamePattern) throws SQLException { return null; } public int getResultSetHoldability() throws SQLException { throw new SQLException("Method not supported"); } public RowIdLifetime getRowIdLifetime() throws SQLException { throw new SQLException("Method not supported"); } public String getSQLKeywords() throws SQLException { throw new SQLException("Method not supported"); } public int getSQLStateType() throws SQLException { return DatabaseMetaData.sqlStateSQL99; } public String getSchemaTerm() throws SQLException { return ""; } public ResultSet getSchemas() throws SQLException { return getSchemas(null, null); } public ResultSet getSchemas(String catalog, String schemaPattern) throws SQLException { return new TDMetaDataResultSet(Arrays.asList("TABLE_SCHEM", "TABLE_CATALOG"), Arrays.asList("STRING", "STRING"), null) { public boolean next() throws SQLException { return false; } }; } public String getSearchStringEscape() throws SQLException { return String.valueOf(SEARCH_STRING_ESCAPE); } public String getStringFunctions() throws SQLException { return ""; } public ResultSet getSuperTables(String catalog, String schemaPattern, String tableNamePattern) throws SQLException { throw new SQLException("Method not supported"); } public ResultSet getSuperTypes(String catalog, String schemaPattern, String typeNamePattern) throws SQLException { throw new SQLException("Method not supported"); } public String getSystemFunctions() throws SQLException { return ""; } public ResultSet getTablePrivileges(String catalog, String schemaPattern, String tableNamePattern) throws SQLException { throw new SQLException("Method not supported"); } public ResultSet getTableTypes() throws SQLException { final TDTableType[] tt = TDTableType.values(); ResultSet result = new TDMetaDataResultSet<TDTableType>( Arrays.asList("TABLE_TYPE"), Arrays.asList("STRING"), new ArrayList<TDTableType>(Arrays.asList(tt))) { private int cnt = 0; public boolean next() throws SQLException { if (cnt < data.size()) { List<Object> a = new ArrayList<Object>(1); a.add(toTDTableType(data.get(cnt).name())); row = a; cnt++; return true; } else { return false; } } }; return result; } public ResultSet getTables(String catalog, String schemaPattern, String tableNamePattern, String[] types) throws SQLException { /** ## catalog: null schemaPattern: null tableNamePattern: % types: null ## */ final List<String> tablesstr; final List<TDTable> resultTables = new ArrayList<TDTable>(); final String resultCatalog; if (catalog == null) { // On jdbc the default catalog is null but on hive it's "default" resultCatalog = "default"; } else { resultCatalog = catalog; } String regtableNamePattern = convertPattern(tableNamePattern); try { List<TableSummary> ts = api.showTables(); //tablesstr = client.get_tables(resultCatalog, "*"); for (TableSummary t : ts) { if (t.getName().matches(regtableNamePattern)) { resultTables.add(new TDTable(resultCatalog, t.getName(), "TABLE", "comment")); // TODO } else { // TODO } } // for (String tablestr : tablesstr) { // if (tablestr.matches(regtableNamePattern)) { // Table tbl = client.get_table(resultCatalog, tablestr); // if (types == null) { // resultTables.add(new JdbcTable(resultCatalog, tbl // .getTableName(), tbl.getTableType(), tbl // .getParameters().get("comment"))); // } else { // String tableType = toJdbcTableType(tbl.getTableType()); // for (String type : types) { // if (type.equalsIgnoreCase(tableType)) { // resultTables.add(new JdbcTable(resultCatalog, // tbl.getTableName(), tbl.getTableType(), // tbl.getParameters().get("comment"))); // break; Collections.sort(resultTables, new GetTablesComparator()); } catch (Exception e) { throw new SQLException(e); } ResultSet result = new TDMetaDataResultSet<TDTable>( Arrays.asList("TABLE_CAT", "TABLE_SCHEM", "TABLE_NAME", "TABLE_TYPE", "REMARKS"), Arrays.asList("STRING", "STRING", "STRING", "STRING", "STRING"), resultTables) { private int cnt = 0; public boolean next() throws SQLException { if (cnt < data.size()) { List<Object> a = new ArrayList<Object>(5); TDTable t = data.get(cnt); // TABLE_CAT String => table catalog (may be null) a.add(t.getTableCatalog()); // TABLE_SCHEM String => table schema (may be null) a.add(null); // TABLE_NAME String => table name a.add(t.getTableName()); try { // TABLE_TYPE String => "TABLE","VIEW" a.add(t.getSqlTableType()); } catch (Exception e) { throw new SQLException(e); } // REMARKS String => explanatory comment on the table a.add(t.getComment()); row = a; cnt++; return true; } else { return false; } } }; return result; } /** * We sort the output of getTables to guarantee jdbc compliance. First check * by table type then by table name */ private class GetTablesComparator implements Comparator<TDTable> { public int compare(TDTable o1, TDTable o2) { int compareType = o1.getType().compareTo(o2.getType()); if (compareType == 0) { return o1.getTableName().compareTo(o2.getTableName()); } else { return compareType; } } } /** * Translate hive table types into jdbc table types. * * @param hivetabletype * @return */ public static String toTDTableType(String hivetabletype) { if (hivetabletype == null) { return null; } else if (hivetabletype.equals(TDTableType.MANAGED_TABLE.toString())) { return "TABLE"; } else if (hivetabletype.equals(TDTableType.VIRTUAL_VIEW.toString())) { return "VIEW"; } else if (hivetabletype.equals(TDTableType.EXTERNAL_TABLE.toString())) { return "EXTERNAL TABLE"; } else { return hivetabletype; } } public String getTimeDateFunctions() throws SQLException { return ""; } public ResultSet getTypeInfo() throws SQLException { throw new SQLException("Method not supported"); } public ResultSet getUDTs(String catalog, String schemaPattern, String typeNamePattern, int[] types) throws SQLException { return new TDMetaDataResultSet(Arrays.asList("TYPE_CAT", "TYPE_SCHEM", "TYPE_NAME", "CLASS_NAME", "DATA_TYPE", "REMARKS", "BASE_TYPE"), Arrays.asList("STRING", "STRING", "STRING", "STRING", "INT", "STRING", "INT"), null) { public boolean next() throws SQLException { return false; } }; } public String getURL() throws SQLException { throw new SQLException("Method not supported"); } public String getUserName() throws SQLException { throw new SQLException("Method not supported"); } public ResultSet getVersionColumns(String catalog, String schema, String table) throws SQLException { throw new SQLException("Method not supported"); } public boolean insertsAreDetected(int type) throws SQLException { throw new SQLException("Method not supported"); } public boolean isCatalogAtStart() throws SQLException { throw new SQLException("Method not supported"); } public boolean isReadOnly() throws SQLException { throw new SQLException("Method not supported"); } public boolean locatorsUpdateCopy() throws SQLException { throw new SQLException("Method not supported"); } public boolean nullPlusNonNullIsNull() throws SQLException { throw new SQLException("Method not supported"); } public boolean nullsAreSortedAtEnd() throws SQLException { throw new SQLException("Method not supported"); } public boolean nullsAreSortedAtStart() throws SQLException { throw new SQLException("Method not supported"); } public boolean nullsAreSortedHigh() throws SQLException { throw new SQLException("Method not supported"); } public boolean nullsAreSortedLow() throws SQLException { throw new SQLException("Method not supported"); } public boolean othersDeletesAreVisible(int type) throws SQLException { throw new SQLException("Method not supported"); } public boolean othersInsertsAreVisible(int type) throws SQLException { throw new SQLException("Method not supported"); } public boolean othersUpdatesAreVisible(int type) throws SQLException { throw new SQLException("Method not supported"); } public boolean ownDeletesAreVisible(int type) throws SQLException { throw new SQLException("Method not supported"); } public boolean ownInsertsAreVisible(int type) throws SQLException { throw new SQLException("Method not supported"); } public boolean ownUpdatesAreVisible(int type) throws SQLException { throw new SQLException("Method not supported"); } public boolean storesLowerCaseIdentifiers() throws SQLException { throw new SQLException("Method not supported"); } public boolean storesLowerCaseQuotedIdentifiers() throws SQLException { throw new SQLException("Method not supported"); } public boolean storesMixedCaseIdentifiers() throws SQLException { throw new SQLException("Method not supported"); } public boolean storesMixedCaseQuotedIdentifiers() throws SQLException { throw new SQLException("Method not supported"); } public boolean storesUpperCaseIdentifiers() throws SQLException { throw new SQLException("Method not supported"); } public boolean storesUpperCaseQuotedIdentifiers() throws SQLException { throw new SQLException("Method not supported"); } public boolean supportsANSI92EntryLevelSQL() throws SQLException { throw new SQLException("Method not supported"); } public boolean supportsANSI92FullSQL() throws SQLException { throw new SQLException("Method not supported"); } public boolean supportsANSI92IntermediateSQL() throws SQLException { throw new SQLException("Method not supported"); } public boolean supportsAlterTableWithAddColumn() throws SQLException { return true; } public boolean supportsAlterTableWithDropColumn() throws SQLException { return false; } public boolean supportsBatchUpdates() throws SQLException { return false; } public boolean supportsCatalogsInDataManipulation() throws SQLException { return false; } public boolean supportsCatalogsInIndexDefinitions() throws SQLException { return false; } public boolean supportsCatalogsInPrivilegeDefinitions() throws SQLException { return false; } public boolean supportsCatalogsInProcedureCalls() throws SQLException { return false; } public boolean supportsCatalogsInTableDefinitions() throws SQLException { return false; } public boolean supportsColumnAliasing() throws SQLException { return true; } public boolean supportsConvert() throws SQLException { throw new SQLException("Method not supported"); } public boolean supportsConvert(int fromType, int toType) throws SQLException { throw new SQLException("Method not supported"); } public boolean supportsCoreSQLGrammar() throws SQLException { throw new SQLException("Method not supported"); } public boolean supportsCorrelatedSubqueries() throws SQLException { throw new SQLException("Method not supported"); } public boolean supportsDataDefinitionAndDataManipulationTransactions() throws SQLException { throw new SQLException("Method not supported"); } public boolean supportsDataManipulationTransactionsOnly() throws SQLException { throw new SQLException("Method not supported"); } public boolean supportsDifferentTableCorrelationNames() throws SQLException { throw new SQLException("Method not supported"); } public boolean supportsExpressionsInOrderBy() throws SQLException { throw new SQLException("Method not supported"); } public boolean supportsExtendedSQLGrammar() throws SQLException { throw new SQLException("Method not supported"); } public boolean supportsFullOuterJoins() throws SQLException { throw new SQLException("Method not supported"); } public boolean supportsGetGeneratedKeys() throws SQLException { throw new SQLException("Method not supported"); } public boolean supportsGroupBy() throws SQLException { return true; } public boolean supportsGroupByBeyondSelect() throws SQLException { throw new SQLException("Method not supported"); } public boolean supportsGroupByUnrelated() throws SQLException { throw new SQLException("Method not supported"); } public boolean supportsIntegrityEnhancementFacility() throws SQLException { throw new SQLException("Method not supported"); } public boolean supportsLikeEscapeClause() throws SQLException { throw new SQLException("Method not supported"); } public boolean supportsLimitedOuterJoins() throws SQLException { throw new SQLException("Method not supported"); } public boolean supportsMinimumSQLGrammar() throws SQLException { throw new SQLException("Method not supported"); } public boolean supportsMixedCaseIdentifiers() throws SQLException { throw new SQLException("Method not supported"); } public boolean supportsMixedCaseQuotedIdentifiers() throws SQLException { throw new SQLException("Method not supported"); } public boolean supportsMultipleOpenResults() throws SQLException { throw new SQLException("Method not supported"); } public boolean supportsMultipleResultSets() throws SQLException { return false; } public boolean supportsMultipleTransactions() throws SQLException { throw new SQLException("Method not supported"); } public boolean supportsNamedParameters() throws SQLException { throw new SQLException("Method not supported"); } public boolean supportsNonNullableColumns() throws SQLException { return false; } public boolean supportsOpenCursorsAcrossCommit() throws SQLException { throw new SQLException("Method not supported"); } public boolean supportsOpenCursorsAcrossRollback() throws SQLException { throw new SQLException("Method not supported"); } public boolean supportsOpenStatementsAcrossCommit() throws SQLException { throw new SQLException("Method not supported"); } public boolean supportsOpenStatementsAcrossRollback() throws SQLException { throw new SQLException("Method not supported"); } public boolean supportsOrderByUnrelated() throws SQLException { throw new SQLException("Method not supported"); } public boolean supportsOuterJoins() throws SQLException { return true; } public boolean supportsPositionedDelete() throws SQLException { return false; } public boolean supportsPositionedUpdate() throws SQLException { return false; } public boolean supportsResultSetConcurrency(int type, int concurrency) throws SQLException { throw new SQLException("Method not supported"); } public boolean supportsResultSetHoldability(int holdability) throws SQLException { return false; } public boolean supportsResultSetType(int type) throws SQLException { return true; } public boolean supportsSavepoints() throws SQLException { return false; } public boolean supportsSchemasInDataManipulation() throws SQLException { return false; } public boolean supportsSchemasInIndexDefinitions() throws SQLException { return false; } public boolean supportsSchemasInPrivilegeDefinitions() throws SQLException { return false; } public boolean supportsSchemasInProcedureCalls() throws SQLException { return false; } public boolean supportsSchemasInTableDefinitions() throws SQLException { return false; } public boolean supportsSelectForUpdate() throws SQLException { return false; } public boolean supportsStatementPooling() throws SQLException { throw new SQLException("Method not supported"); } public boolean supportsStoredFunctionsUsingCallSyntax() throws SQLException { throw new SQLException("Method not supported"); } public boolean supportsStoredProcedures() throws SQLException { return false; } public boolean supportsSubqueriesInComparisons() throws SQLException { throw new SQLException("Method not supported"); } public boolean supportsSubqueriesInExists() throws SQLException { throw new SQLException("Method not supported"); } public boolean supportsSubqueriesInIns() throws SQLException { throw new SQLException("Method not supported"); } public boolean supportsSubqueriesInQuantifieds() throws SQLException { throw new SQLException("Method not supported"); } public boolean supportsTableCorrelationNames() throws SQLException { throw new SQLException("Method not supported"); } public boolean supportsTransactionIsolationLevel(int level) throws SQLException { throw new SQLException("Method not supported"); } public boolean supportsTransactions() throws SQLException { return false; } public boolean supportsUnion() throws SQLException { throw new SQLException("Method not supported"); } public boolean supportsUnionAll() throws SQLException { throw new SQLException("Method not supported"); } public boolean updatesAreDetected(int type) throws SQLException { throw new SQLException("Method not supported"); } public boolean usesLocalFilePerTable() throws SQLException { throw new SQLException("Method not supported"); } public boolean usesLocalFiles() throws SQLException { throw new SQLException("Method not supported"); } public boolean isWrapperFor(Class<?> iface) throws SQLException { throw new SQLException("Method not supported"); } public <T> T unwrap(Class<T> iface) throws SQLException { throw new SQLException("Method not supported"); } public static void main(String[] args) throws SQLException { TDDatabaseMetaData meta = new TDDatabaseMetaData(null); System.out.println("DriverName: " + meta.getDriverName()); System.out.println("DriverVersion: " + meta.getDriverVersion()); } }
package com.urbanairship.digitalwallet.client; /* Method Path Description GET / list tags for this user GET /{tag}/passes list passes on that tag PUT /{tag}/passes update the passes on this tag DELETE /{tag} Delete a tag and remove it from all of the passes it was associated with. DELETE /{tag}/passes Remove a tag from all of its passes. DELETE /{tag}/pass/{strPassId} Remove the tag from the specified pass id. DELETE /{tag}/pass/id/{externalId} Remove a pass from a tag by it's external id. */ import org.apache.commons.lang.StringUtils; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.HashMap; public class Tag extends PassToolsClient { private Long id; private String tag; private List<Long> passIds; private final static String missingTagError = "Please provide a tag!"; public Tag() { } public Tag(JSONObject o) { assign(o); } public Tag(Long id) { } public Long getId() { return id; } public String getTag() { return tag; } public List<Long> getPassIds() { return passIds; } public static List<Tag> getList(int pageSize, int page) { try { List<Tag> tags = new ArrayList<Tag>(); StringBuilder builder = new StringBuilder(getBaseUrl()); builder.append("?pageSize=").append(pageSize).append("&page=").append(page); PassToolsResponse response = get(builder.toString()); JSONObject jsonResponse = response.getBodyAsJSONObject(); JSONArray tagArray = (JSONArray) jsonResponse.get("tags"); if (tagArray != null) { for (Object o : tagArray.toArray()) { if (o instanceof JSONObject) { tags.add(new Tag((JSONObject) o)); } } } return tags; } catch (RuntimeException rte) { throw rte; } catch (Exception e) { throw new RuntimeException(e); } } public static List<Pass> getPasses(String tag) { try { checkNotNull(tag, missingTagError); List<Pass> passes = new ArrayList<Pass>(); StringBuilder builder = new StringBuilder(getBaseUrl()); builder.append("/").append(URLEncoder.encode(tag, "UTF-8")).append("/passes"); PassToolsResponse response = get(builder.toString()); JSONObject jsonResponse = response.getBodyAsJSONObject(); JSONArray passArray = (JSONArray) jsonResponse.get("passes"); if (passArray != null) { for (Object o : passArray.toArray()) { if (o instanceof JSONObject) { passes.add(new Pass((JSONObject) o)); } } } return passes; } catch (RuntimeException rte) { throw rte; } catch (Exception e) { throw new RuntimeException(e); } } public static Long updatePasses(String tag, Map fields) { try { checkNotNull(tag, missingTagError); StringBuilder builder = new StringBuilder(getBaseUrl()); builder.append("/").append(URLEncoder.encode(tag, "UTF-8")).append("/passes"); Map formParams = new HashMap<String, Object>(); formParams.put("json", new JSONObject(fields)); PassToolsResponse response = put(builder.toString(), formParams); JSONObject jsonObjResponse = response.getBodyAsJSONObject(); Long ticketId = (Long) jsonObjResponse.get("ticketId"); return ticketId; } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException(e); } /* todo implement this */ } public static boolean deleteTag(String tag) { try { checkNotNull(tag, missingTagError); String url = getBaseUrl() + "/" + URLEncoder.encode(tag, "UTF-8"); PassToolsResponse response = delete(url); JSONObject jsonObjResponse = response.getBodyAsJSONObject(); String status = (String) jsonObjResponse.get("status"); if ((!StringUtils.isBlank(status)) && status.equals("success")) { return true; } else { return false; } } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException(e); } /* todo implement this */ } public static boolean removeFromPasses(String tag) { try { checkNotNull(tag, missingTagError); StringBuilder builder = new StringBuilder(getBaseUrl()); builder.append("/").append(URLEncoder.encode(tag, "UTF-8")).append("/passes"); PassToolsResponse response = delete(builder.toString()); JSONObject jsonObjResponse = response.getBodyAsJSONObject(); String status = (String) jsonObjResponse.get("status"); if ((!StringUtils.isBlank(status)) && status.equals("success")) { return true; } else { return false; } } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException(); } /* todo implement this */ } public static void removeFromPass(String tag, Long passId) { try { checkNotNull(tag, missingTagError); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException(); /* todo implement this */ } } public static void removeFromPass(String tag, String externalId) { checkNotNull(tag, missingTagError); /* todo implement this */ } private void reset() { id = null; tag = null; passIds = null; } private void assign(JSONObject o) { reset(); if (o != null) { id = (Long) o.get("id"); tag = (String) o.get("tag"); } } private static String getBaseUrl() { return PassTools.API_BASE + "/tag"; } }
package com.wealoha.ipgeolocation; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Map; import java.util.TreeMap; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public abstract class IpCountryHelper { // iplong // key: start // value: end private static TreeMap<Long, Long> ipRangeMap = new TreeMap<Long, Long>(); private static TreeMap<Long, Long> privateIpRangeMap = new TreeMap<Long, Long>(); // key: ipRangeMap private static Map<Long, String> countryMap = new HashMap<>(); private static Logger logger = LoggerFactory.getLogger(IpCountryHelper.class); static { // "1.0.8.0","1.0.15.255","CN" // "(\d+\.\d+\.\d+\.\d+)","(\d+\.\d+\.\d+\.\d+)","(\w+)" Pattern p = Pattern .compile("\"(\\d+\\.\\d+\\.\\d+\\.\\d+)\",\"(\\d+\\.\\d+\\.\\d+\\.\\d+)\",\"(\\w+)\""); try (BufferedReader reader = new BufferedReader(new InputStreamReader( IpCountryHelper.class.getResourceAsStream("/dbip-country-2015-04.csv")))) { String line = null; do { line = reader.readLine(); if (line != null) { Matcher m = p.matcher(line); if (m.find()) { String ipStart = m.group(1); String ipEnd = m.group(2); String country = m.group(3); Long start = RequestIpHelper.ipv4ToLong(ipStart); Long end = RequestIpHelper.ipv4ToLong(ipEnd); Long exist = ipRangeMap.put(start, end); if (exist != null) { logger.warn("ip: start={}, end={}({}), exist(value)={}", ipStart, ipEnd, end, exist); } countryMap.put(start, country); } else if (!StringUtils.contains(line, ":")) { // ipv6 logger.warn(": {}", line); } } } while (line != null); } catch (IOException e) { throw new RuntimeException("ip", e); } String[] localIpRanges = { "10.0.0.0", "10.255.255.255", "169.254.1.0", "169.254.254.255", "172.16.0.0", "172.31.255.255", "192.168.0.0", "192.168.255.255", "240.0.0.0", "254.255.255.254", }; for (int i = 0; i < localIpRanges.length; i++) { privateIpRangeMap.put(RequestIpHelper.ipv4ToLong(localIpRanges[i]), RequestIpHelper.ipv4ToLong(localIpRanges[++i])); } } private IpCountryHelper() { } public static String getCountry(String ip) { Long longIp = RequestIpHelper.ipv4ToLong(ip); if (longIp == null) { throw new IllegalArgumentException("invalid ip: " + ip); } return getCountry(longIp); } /** * ip * * @param ip * @return null */ public static String getCountry(long ip) { if (isPrivateNetworkIp(ip)) { return null; } Long start = ipRangeMap.floorKey(ip); Long end = ipRangeMap.get(start); if (ip <= end) { return countryMap.get(start); } logger.warn("value: start={}, end={}, ip={}", start, end, ip); return null; } public static boolean isPrivateNetworkIp(String ip) { Long longIp = RequestIpHelper.ipv4ToLong(ip); if (longIp == null) { throw new IllegalArgumentException("invalid ip: " + ip); } return isPrivateNetworkIp(longIp); } /** * * * @param ip * @return */ public static boolean isPrivateNetworkIp(long ip) { Long start = privateIpRangeMap.floorKey(ip); if (start == null) { return false; } Long end = privateIpRangeMap.get(start); return ip <= end; } }
package com.wisdom.rudiment; public class ReverseWordsInAString { public static void main(String[] args) { ReverseWordsInAString rw = new ReverseWordsInAString(); String s = " public static void main "; String str = rw.reverseWords(s); System.out.println(str); } /* public String reverseWords(String s) { if (s.equals(" ")) { return " "; } if (null == s) { return null; } else { // char[] ch = s.toCharArray(); char[] ch2 = new char[ch.length]; for (int x = 0; x < ch.length; x ++) { ch2[x] = ch[ch.length - 1 - x]; } // String[] str = new String(ch2).replaceAll(" +"," ").split(" "); StringBuffer sb = new StringBuffer(); for (int y = 0; y < str.length; y ++) { if (y < str.length - 2) { sb.append(str[str.length - 1 - y]+" "); } else { sb.append(str[str.length - 1 - y]); } } return sb.toString(); } }*/ /** * ~ * @param s * @return * * */ public String reverseWords(String s) { if (s.equals(" ")) { return " "; } if (s.isEmpty()) { return ""; } else { String[] str = s.replaceAll(" +", " ").split(" "); StringBuffer stringBuffer = new StringBuffer(); for (int y = 0; y < str.length; y++) { if (y == str.length - 1) { stringBuffer.append(str[str.length - 1 - y]); } else { stringBuffer.append(str[str.length - 1 - y] + " "); } } return stringBuffer.toString(); } } }
package cz.jiripinkas.example.mailer.entity; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; @Entity public class Email { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "email_id") private Integer emailId; // @Size(min = 1) // @org.hibernate.validator.constraints.Email @Column(name = "email_to") private String emailToRefactory = ""; // @Size(min = 1) @Column(name = "email_subject") private String subject = ""; // @Size(min = 1) @Column(name = "email_body") private String body = ""; @Column(name = "sent_date") private Date sentDate; @ManyToOne @JoinColumn(name = "user_id") private User user; public User getUser() { return user; } public void setUser(User user) { this.user = user; } public Date getSentDate() { return sentDate; } public void setSentDate(Date sentDate) { this.sentDate = sentDate; } public Integer getEmailId() { return emailId; } public void setEmailId(Integer emailId) { this.emailId = emailId; } public String getEmailTo() { return emailToRefactory; } public void setEmailTo(String emailTo) { this.emailToRefactory = emailTo; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public String getBody() { return body; } public void setBody(String body) { this.body = body; } }
package de.dhbw.humbuch.view; import java.util.Collection; import java.util.Date; import java.util.HashSet; import java.util.NoSuchElementException; import java.util.Set; import com.google.common.eventbus.EventBus; import com.google.inject.Inject; import com.vaadin.data.Container.Filter; import com.vaadin.data.Property.ValueChangeEvent; import com.vaadin.data.Property.ValueChangeListener; import com.vaadin.data.Validator.InvalidValueException; import com.vaadin.data.fieldgroup.BeanFieldGroup; import com.vaadin.data.fieldgroup.FieldGroup.CommitException; import com.vaadin.data.util.BeanItemContainer; import com.vaadin.data.util.filter.Or; import com.vaadin.data.util.filter.SimpleStringFilter; import com.vaadin.event.FieldEvents.TextChangeEvent; import com.vaadin.event.FieldEvents.TextChangeListener; import com.vaadin.event.ItemClickEvent; import com.vaadin.event.ShortcutAction.KeyCode; import com.vaadin.event.ShortcutListener; import com.vaadin.navigator.View; import com.vaadin.navigator.ViewChangeListener.ViewChangeEvent; import com.vaadin.ui.AbstractTextField.TextChangeEventMode; import com.vaadin.ui.Alignment; import com.vaadin.ui.Button; import com.vaadin.ui.Button.ClickEvent; import com.vaadin.ui.Button.ClickListener; import com.vaadin.ui.ComboBox; import com.vaadin.ui.DateField; import com.vaadin.ui.FormLayout; import com.vaadin.ui.HorizontalLayout; import com.vaadin.ui.Table; import com.vaadin.ui.Table.ColumnGenerator; import com.vaadin.ui.TextArea; import com.vaadin.ui.TextField; import com.vaadin.ui.UI; import com.vaadin.ui.VerticalLayout; import com.vaadin.ui.Window; import de.davherrmann.mvvm.BasicState; import de.davherrmann.mvvm.State; import de.davherrmann.mvvm.StateChangeListener; import de.davherrmann.mvvm.ViewModelComposer; import de.davherrmann.mvvm.annotations.BindState; import de.dhbw.humbuch.event.ConfirmEvent; import de.dhbw.humbuch.event.MessageEvent; import de.dhbw.humbuch.model.entity.Category; import de.dhbw.humbuch.model.entity.SchoolYear.Term; import de.dhbw.humbuch.model.entity.Subject; import de.dhbw.humbuch.model.entity.TeachingMaterial; import de.dhbw.humbuch.util.BookLookup; import de.dhbw.humbuch.util.BookLookup.Book; import de.dhbw.humbuch.util.BookLookup.BookNotFoundException; import de.dhbw.humbuch.viewmodel.TeachingMaterialViewModel; import de.dhbw.humbuch.viewmodel.TeachingMaterialViewModel.Categories; import de.dhbw.humbuch.viewmodel.TeachingMaterialViewModel.StandardCategory; import de.dhbw.humbuch.viewmodel.TeachingMaterialViewModel.TeachingMaterials; /** * {@link View} to manage the lendable teaching materials. * * @author Martin Wentzel * @author Johannes Idelhauser * */ public class TeachingMaterialView extends VerticalLayout implements View, ViewInformation { private static final long serialVersionUID = -5063268947544706757L; private static final String TITLE = "Lehrmittelverwaltung"; private static final String TABLE_CATEGORY = "category"; private static final String TABLE_NAME = "name"; private static final String TABLE_PROFILE = "profile"; private static final String TABLE_FROMGRADE = "fromGrade"; private static final String TABLE_FROMTERM = "fromTerm"; private static final String TABLE_TOGRADE = "toGrade"; private static final String TABLE_TOTERM = "toTerm"; private static final String TABLE_PRODUCER = "producer"; private static final String TABLE_IDENTNR = "identifyingNumber"; private static final String TABLE_COMMENT = "comment"; private static final String TABLE_VALIDFROM = "validFrom"; private static final String TABLE_VALIDUNTIL = "validUntil"; private EventBus eventBus; private TeachingMaterialViewModel teachingMaterialViewModel; /** * Layout components */ private HorizontalLayout head; private TextField filter; private Button btnEdit; private Button btnNew; private Button btnDelete; private Table materialsTable; private BeanItemContainer<TeachingMaterial> tableData; private BeanFieldGroup<TeachingMaterial> binder = new BeanFieldGroup<TeachingMaterial>(TeachingMaterial.class); @BindState(TeachingMaterials.class) public final State<Collection<TeachingMaterial>> teachingMaterials = new BasicState<>(Collection.class); @BindState(Categories.class) public final State<Collection<Category>> categories = new BasicState<>(Collection.class); @BindState(StandardCategory.class) public final State<Category> standardCategory = new BasicState<>(Category.class); /** * All popup-window components and the corresponding binded states. The * popup-window for adding a new teaching material and editing a teaching * material is the same. Only the caption will be set differently */ private Window windowEditTeachingMaterial; private FormLayout windowContent; private HorizontalLayout windowButtons; private TextField txtTmName = new TextField("Titel"); private TextField txtIdentNr = new TextField(); private TextField txtProducer = new TextField("Hersteller/Verlag"); private TextField txtFromGrade = new TextField(); private TextField txtToGrade = new TextField(); private ComboBox cbProfiles = new ComboBox("Profil"); private ComboBox cbFromTerm = new ComboBox(); private ComboBox cbToTerm = new ComboBox(); private ComboBox cbCategory = new ComboBox("Kategorie"); private DateField dfValidFrom = new DateField("Gültig von"); private DateField dfValidUntil = new DateField("Gültig bis"); private TextArea textAreaComment = new TextArea("Kommentar"); private Button btnWindowSave = new Button("Speichern"); private Button btnWindowCancel = new Button("Abbrechen"); private Button btnISBNImport = new Button("Hole Daten"); @Inject public TeachingMaterialView(ViewModelComposer viewModelComposer, TeachingMaterialViewModel teachingMaterialViewModel, EventBus eventBus) { this.teachingMaterialViewModel = teachingMaterialViewModel; this.eventBus = eventBus; init(); buildLayout(); bindViewModel(viewModelComposer, teachingMaterialViewModel); } /** * Initializes the components and sets attributes. * */ @SuppressWarnings("serial") private void init() { head = new HorizontalLayout(); head.setWidth("100%"); head.setSpacing(true); // Filter filter = new TextField(); filter.setImmediate(true); filter.setInputPrompt("Lehrmittel suchen..."); filter.setWidth("50%"); filter.setTextChangeEventMode(TextChangeEventMode.EAGER); head.addComponent(filter); head.setExpandRatio(filter, 1); head.setComponentAlignment(filter, Alignment.MIDDLE_LEFT); // Buttons HorizontalLayout buttons = new HorizontalLayout(); buttons.setSpacing(true); // Add btnNew = new Button("Hinzufügen"); buttons.addComponent(btnNew); // Delete btnDelete = new Button("Löschen"); btnDelete.setEnabled(false); buttons.addComponent(btnDelete); // Edit btnEdit = new Button("Bearbeiten"); btnEdit.setEnabled(false); btnEdit.setClickShortcut(KeyCode.ENTER); buttons.addComponent(btnEdit); head.addComponent(buttons); head.setComponentAlignment(buttons, Alignment.MIDDLE_RIGHT); // Instantiate table materialsTable = new Table(); materialsTable.setSelectable(true); materialsTable.setImmediate(true); materialsTable.setSizeFull(); materialsTable.setColumnCollapsingAllowed(true); tableData = new BeanItemContainer<TeachingMaterial>( TeachingMaterial.class); materialsTable.setContainerDataSource(tableData); materialsTable.setVisibleColumns(new Object[] { TABLE_NAME, TABLE_PRODUCER, TABLE_PROFILE, TABLE_FROMGRADE, TABLE_TOGRADE, TABLE_CATEGORY, TABLE_IDENTNR }); materialsTable.setColumnHeader(TABLE_CATEGORY, "Kategorie"); materialsTable.setColumnHeader(TABLE_NAME, "Titel"); materialsTable.setColumnHeader(TABLE_PROFILE, "Profil"); materialsTable.setColumnHeader(TABLE_FROMGRADE, "Von Klasse"); materialsTable.setColumnHeader(TABLE_TOGRADE, "Bis Klasse"); materialsTable.setColumnHeader(TABLE_PRODUCER, "Hersteller/Verlag"); materialsTable.setColumnHeader(TABLE_IDENTNR, "Nummer/ISBN"); materialsTable.setColumnHeader(TABLE_COMMENT, "Kommentar"); materialsTable.setColumnHeader(TABLE_VALIDFROM, "Gültig von"); materialsTable.setColumnHeader(TABLE_VALIDUNTIL, "Gültig bis"); materialsTable.addGeneratedColumn(TABLE_PROFILE, new ColumnGenerator() { @Override public Object generateCell(Table source, Object itemId, Object columnId) { TeachingMaterial item = (TeachingMaterial) itemId; String profile = ""; for(Subject subject : item.getProfile()) { profile = subject.toString(); } return profile; } }); binder.setBuffered(true); this.createEditWindow(); this.addListener(); } /** * Creates the window for editing and creating teaching materials * * @return The created Window */ @SuppressWarnings("serial") public void createEditWindow() { // Create Window and set parameters windowEditTeachingMaterial = new Window(); windowEditTeachingMaterial.center(); windowEditTeachingMaterial.setModal(true); windowEditTeachingMaterial.setResizable(false); windowContent = new FormLayout(); windowContent.setMargin(true); windowButtons = new HorizontalLayout(); windowButtons.setSpacing(true); btnWindowSave.addStyleName("default"); // Fill Comboboxes cbFromTerm.addItem(Term.FIRST); cbFromTerm.addItem(Term.SECOND); cbToTerm.addItem(Term.FIRST); cbToTerm.addItem(Term.SECOND); for (Subject subject : Subject.values()) { Set<Subject> subjects = new HashSet<Subject>(); subjects.add(subject); cbProfiles.addItem(subjects); cbProfiles.setItemCaption(subjects, subject.toString()); } // Set Form options cbCategory.setNullSelectionAllowed(false); cbProfiles.setNullSelectionAllowed(false); cbFromTerm.setNullSelectionAllowed(false); cbToTerm.setNullSelectionAllowed(false); txtTmName.setRequired(true); cbCategory.setRequired(true); cbProfiles.setRequired(true); dfValidFrom.setRequired(true); dfValidUntil.setDescription("Leer für unbestimmtes Gültigkeitsdatum"); // Input prompts txtIdentNr.setInputPrompt("ISBN"); txtTmName.setInputPrompt("Titel oder Name"); txtProducer.setInputPrompt("z.B. Klett"); txtFromGrade.setInputPrompt("z.B. 5"); txtToGrade.setInputPrompt("z.B. 7"); textAreaComment.setInputPrompt("Zusätzliche Informationen"); // NullRepresentation txtIdentNr.setNullRepresentation(""); txtTmName.setNullRepresentation(""); txtProducer.setNullRepresentation(""); txtFromGrade.setNullRepresentation(""); txtToGrade.setNullRepresentation(""); textAreaComment.setNullRepresentation(""); // Bind to FieldGroup binder.bind(txtTmName, TABLE_NAME); binder.bind(txtIdentNr, TABLE_IDENTNR); binder.bind(cbCategory, TABLE_CATEGORY); binder.bind(txtProducer, TABLE_PRODUCER); binder.bind(cbProfiles, TABLE_PROFILE); binder.bind(txtFromGrade, TABLE_FROMGRADE); binder.bind(cbFromTerm, TABLE_FROMTERM); binder.bind(txtToGrade, TABLE_TOGRADE); binder.bind(cbToTerm, TABLE_TOTERM); binder.bind(dfValidFrom, TABLE_VALIDFROM); binder.bind(dfValidUntil, TABLE_VALIDUNTIL); binder.bind(textAreaComment, TABLE_COMMENT); // Add all components windowContent.addComponent(txtTmName); windowContent.addComponent(new HorizontalLayout(){ { setSpacing(true); setCaption("ISBN/Nummer"); setStyleName("required"); addComponent(txtIdentNr); addComponent(btnISBNImport); } }); windowContent.addComponent(cbCategory); windowContent.addComponent(txtProducer); windowContent.addComponent(cbProfiles); windowContent.addComponent(new HorizontalLayout() { { setSpacing(true); setCaption("Von Klassenstufe"); txtFromGrade.setWidth("80px"); addComponent(txtFromGrade); addComponent(cbFromTerm); } }); windowContent.addComponent(new HorizontalLayout() { { setSpacing(true); setCaption("Bis Klassenstufe"); txtToGrade.setWidth("80px"); addComponent(txtToGrade); addComponent(cbToTerm); } }); windowContent.addComponent(dfValidFrom); windowContent.addComponent(dfValidUntil); windowContent.addComponent(textAreaComment); windowButtons.addComponent(btnWindowCancel); windowButtons.addComponent(btnWindowSave); windowContent.addComponent(windowButtons); windowEditTeachingMaterial.setContent(windowContent); windowEditTeachingMaterial.setCaption("Lehrmittel bearbeiten"); windowEditTeachingMaterial.setCloseShortcut(KeyCode.ESCAPE, null); } /** * Adds all listener to their corresponding components. * */ @SuppressWarnings("serial") private void addListener() { /** * Fetches the book data by using a given ISBN. After fetching the data * it is inserted into the corresponding fields. */ btnISBNImport.addClickListener(new ClickListener() { @Override public void buttonClick(ClickEvent event) { try { if (txtIdentNr.getValue() == null) { eventBus.post(new MessageEvent("Bitte geben Sie eine ISBN an.")); return; } Book book = BookLookup.lookup(txtIdentNr.getValue()); txtTmName.setValue(book.title); txtProducer.setValue(book.publisher); String commentText = "Autor(en): " + book.author; if (textAreaComment.getValue() != null && !textAreaComment.getValue().isEmpty()) { commentText += '\n' + textAreaComment.getValue(); } textAreaComment.setValue(commentText); } catch (BookNotFoundException e) { eventBus.post(new MessageEvent("Es konnte kein Buch zu der ISBN gefunden werden.")); } } }); /** * Listens for changes in the Collection teachingMaterials and adds them * to the container. */ teachingMaterials.addStateChangeListener(new StateChangeListener() { @Override public void stateChange(Object value) { tableData.removeAllItems(); for (TeachingMaterial material : teachingMaterials.get()) { tableData.addItem(material); } } }); /** * Enables/disables the edit and delete buttons */ materialsTable.addValueChangeListener(new ValueChangeListener() { @Override public void valueChange(ValueChangeEvent event) { TeachingMaterial item = (TeachingMaterial) materialsTable .getValue(); btnEdit.setEnabled(item != null); btnDelete.setEnabled(item != null); } }); // Double click on a row: make it editable materialsTable.addItemClickListener(new ItemClickEvent.ItemClickListener() { @Override public void itemClick(ItemClickEvent itemClickEvent) { if (itemClickEvent.isDoubleClick() && !materialsTable.isEditable()) { materialsTable.setValue(itemClickEvent.getItemId()); btnEdit.click(); } } }); /** * Opens the popup-window for editing a book and inserts the data from * the teachingMaterialInfo-State. */ btnEdit.addClickListener(new ClickListener() { @Override public void buttonClick(ClickEvent event) { TeachingMaterial item = (TeachingMaterial) materialsTable .getValue(); binder.setItemDataSource(item); UI.getCurrent().addWindow(windowEditTeachingMaterial); txtTmName.focus(); } }); /** * Opens a new popup-window with an empty new teaching material */ btnNew.addClickListener(new ClickListener() { @Override public void buttonClick(ClickEvent event) { TeachingMaterial item = new TeachingMaterial.Builder(standardCategory.get(), null, null, new Date()).build(); binder.setItemDataSource(item); UI.getCurrent().addWindow(windowEditTeachingMaterial); txtTmName.focus(); } }); /** * Closes the popup window * */ btnWindowCancel.addClickListener(new ClickListener() { @Override public void buttonClick(ClickEvent event) { windowEditTeachingMaterial.close(); clearWindowFields(); } }); /** * Saves the teachingMaterial and closes the popup-window * */ btnWindowSave.addClickListener(new ClickListener() { @Override public void buttonClick(ClickEvent event) { if (FormFieldsValid()) { try { binder.commit(); teachingMaterialViewModel.doUpdateTeachingMaterial(binder .getItemDataSource().getBean()); windowEditTeachingMaterial.close(); eventBus.post(new MessageEvent( "Lehrmittel gespeichert.")); } catch (CommitException e) { eventBus.post(new MessageEvent(e.getLocalizedMessage())); } } } }); /** * Show a confirm popup and delete the teaching material on confirmation */ btnDelete.addClickListener(new ClickListener() { @Override public void buttonClick(ClickEvent event) { final TeachingMaterial item = (TeachingMaterial) materialsTable .getValue(); if (item != null) { Runnable runnable = new Runnable() { @Override public void run() { teachingMaterialViewModel .doDeleteTeachingMaterial(item); materialsTable.select(null); } }; eventBus.post(new ConfirmEvent.Builder( "Wollen Sie das Lehrmittel wirklich löschen?") .caption("Löschen").confirmRunnable(runnable) .build()); } } }); /** * Provides the live search of the teaching material table by adding a * filter after every keypress in the search field. Currently the * publisher and title search are supported. */ filter.addTextChangeListener(new TextChangeListener() { private static final long serialVersionUID = -1684545652234105334L; @Override public void textChange(TextChangeEvent event) { String text = event.getText(); Filter filter = new Or(new SimpleStringFilter(TABLE_NAME, text, true, false), new SimpleStringFilter(TABLE_PRODUCER, text, true, false), new SimpleStringFilter(TABLE_CATEGORY,text,true,false), new SimpleStringFilter(TABLE_FROMGRADE,text,true,false), new SimpleStringFilter(TABLE_TOGRADE,text,true,false), new SimpleStringFilter(TABLE_IDENTNR,text,true,false)); tableData.removeAllContainerFilters(); tableData.addContainerFilter(filter); } }); /** * Allows to dismiss the filter by hitting ESCAPE */ filter.addShortcutListener(new ShortcutListener("Clear", KeyCode.ESCAPE, null) { @Override public void handleAction(Object sender, Object target) { filter.setValue(""); tableData.removeAllContainerFilters(); } }); /** * Fills the category combobox */ categories.addStateChangeListener(new StateChangeListener() { @Override public void stateChange(Object arg0) { cbCategory.removeAllItems(); for (Category cat : categories.get()) { cbCategory.addItem(cat); cbCategory.setItemCaption(cat, cat.getName()); } } }); } /** * Validates the fields in the edit teaching materials window. * * @return Whether or not the fields in the editor are valid */ private boolean FormFieldsValid() { // Validate if a field is empty if (txtIdentNr.getValue() == null || txtIdentNr.getValue().isEmpty() || txtTmName.getValue() == null || txtTmName.getValue().isEmpty() || cbCategory.getValue() == null || dfValidFrom.getValue() == null || cbProfiles.getValue() == null) { eventBus.post(new MessageEvent( "Bitte füllen Sie alle Pflicht-Felder aus.")); return false; } else { // No field is empty, validate now for right values and lengths if (txtTmName.getValue().length() < 2) { eventBus.post(new MessageEvent( "Der Titel muss mindestens 2 Zeichen enthalten.")); return false; } try { if (txtToGrade.getValue() != null) Integer.parseInt(txtToGrade.getValue()); if (txtFromGrade.getValue() != null) Integer.parseInt(txtFromGrade.getValue()); } catch (NumberFormatException e) { eventBus.post(new MessageEvent( "Die Klassenstufen dürfen nur Zahlen enthalten")); return false; } try { dfValidFrom.validate(); dfValidUntil.validate(); } catch (InvalidValueException e) { eventBus.post(new MessageEvent( "Mindestens ein Datumsfeld ist nicht korrekt.")); return false; } return true; } } /** * Builds the layout by adding all components in their specific order. */ private void buildLayout() { setMargin(true); setSpacing(true); setSizeFull(); addComponent(head); addComponent(materialsTable); setExpandRatio(materialsTable, 1); } /** * Empties the fields of the popup-window to prevent that TextFields already * have content form previous edits. */ private void clearWindowFields() { txtTmName.setValue(""); txtIdentNr.setValue(""); txtProducer.setValue(""); txtFromGrade.setValue(""); txtToGrade.setValue(""); textAreaComment.setValue(""); txtProducer.setValue(""); cbFromTerm.setValue(Term.FIRST); cbToTerm.setValue(Term.SECOND); } @Override public void enter(ViewChangeEvent event) { teachingMaterialViewModel.refresh(); } private void bindViewModel(ViewModelComposer viewModelComposer, Object... viewModels) { try { viewModelComposer.bind(this, viewModels); } catch (IllegalAccessException | NoSuchElementException | UnsupportedOperationException e) { e.printStackTrace(); } } @Override public String getTitle() { return TITLE; } }
package de.reffle.jfsdict.levenshtein; import java.util.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class CharVectors { private static int KEEP_IN_ARRAY = 1000; @SuppressWarnings("unused") private static Logger LOG = LoggerFactory.getLogger(CharVectors.class); private String pattern; private List<Integer> charvecList = new ArrayList<>(); private Map<Character, Integer> charvecMap = new HashMap<>(); private static Integer zero = new Integer(0); public CharVectors() { for(int i=0;i<KEEP_IN_ARRAY;++i) charvecList.add(0); } public void loadPattern(String aPattern) { reset(); pattern = aPattern; computeCharvecs(); } /* * For each character c at position i in the pattern, set the i-th bit of the charVector for c. */ void computeCharvecs() { int movingBit = 1 << (pattern.length()-1); for(int i=0; i < pattern.length(); ++i) { char c = pattern.charAt(i); set(c, get(c) | movingBit ); movingBit = movingBit >> 1; } } public void reset() { if(pattern != null) { for(int i=0; i < pattern.length(); ++i) { set(pattern.charAt(i), 0); } } } private void set(char c, int aCharvec) { if(c < KEEP_IN_ARRAY) { charvecList.set(c, aCharvec); } else { charvecMap.put(c, aCharvec); } } public int get(char c) { if(c < KEEP_IN_ARRAY) { return charvecList.get(c); } else { Integer vector = charvecMap.get(c); return (vector == null) ? zero : vector; } } }
package de.tblsoft.solr.pipeline; import de.tblsoft.solr.compare.SolrCompareFilter; import de.tblsoft.solr.pipeline.bean.Document; import de.tblsoft.solr.pipeline.bean.Filter; import de.tblsoft.solr.pipeline.bean.Pipeline; import de.tblsoft.solr.pipeline.filter.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.Constructor; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.util.*; public class PipelineExecuter { private static Logger LOG = LoggerFactory.getLogger(PipelineExecuter.class); private Pipeline pipeline; private List<FilterIF> filterList; private ReaderIF reader; private String yamlFileName; private Map<String, String> pipelineVariables = new HashMap<String, String>(); private static Map<String, Class> classRegestriy = new HashMap<String, Class>(); static { classRegestriy.put("solrcmdutils.StandardReader", StandardReader.class); classRegestriy.put("solrcmdutils.GrokReader", GrokReader.class); classRegestriy.put("solrcmdutils.GCLogReader", GCLogReader.class); classRegestriy.put("solrcmdutils.ElasticJsonPathReader", ElasticJsonPathReader.class); classRegestriy.put("solrcmdutils.ElasticReader", ElasticReader.class); classRegestriy.put("solrcmdutils.XmlReader", XmlReader.class); classRegestriy.put("solrcmdutils.XmlSitemapReader", XmlSitemapReader.class); classRegestriy.put("solrcmdutils.HttpFilter", HttpFilter.class); classRegestriy.put("solrcmdutils.HtmlJsoupFilter", HtmlJsoupFilter.class); classRegestriy.put("solrcmdutils.EntityExtractionFilter", EntityExtractionFilter.class); classRegestriy.put("solrcmdutils.ValidationFilter", ValidationFilter.class); classRegestriy.put("solrcmdutils.OpenThesaurusReader", OpenThesaurusReader.class); classRegestriy.put("solrcmdutils.DictionaryNormalizationFilter", DictionaryNormalizationFilter.class); classRegestriy.put("solrcmdutils.ThreadDumpReader", ThreadDumpReader.class); classRegestriy.put("solrcmdutils.DateFilter", DateFilter.class); classRegestriy.put("solrcmdutils.UrlSplitter", UrlSplitter.class); classRegestriy.put("solrcmdutils.GrepFilter", GrepFilter.class); classRegestriy.put("solrcmdutils.KeyValueSplitterFilter", KeyValueSplitterFilter.class); classRegestriy.put("solrcmdutils.FieldJoiner", FieldJoiner.class); classRegestriy.put("solrcmdutils.JsonWriter", JsonWriter.class); classRegestriy.put("solrcmdutils.ElasticWriter", ElasticWriter.class); classRegestriy.put("solrcmdutils.CSVReader", CSVReader.class); classRegestriy.put("solrcmdutils.SolrQueryLogReader", SolrQueryLogReader.class); classRegestriy.put("solrcmdutils.SpyFilter", SpyFilter.class); classRegestriy.put("solrcmdutils.StatusFilter", StatusFilter.class); classRegestriy.put("solrcmdutils.StatusTimeFilter", StatusTimeFilter.class); classRegestriy.put("solrcmdutils.StatisticFilter", StatisticFilter.class); classRegestriy.put("solrcmdutils.MappingFilter", MappingFilter.class); classRegestriy.put("solrcmdutils.EncodingCorrectionFilter", EncodingCorrectionFilter.class); classRegestriy.put("solrcmdutils.RegexSplitFilter", RegexSplitFilter.class); classRegestriy.put("solrcmdutils.FieldSplitter", FieldSplitter.class); classRegestriy.put("solrcmdutils.IgnoreDocumentFilter", IgnoreDocumentFilter.class); classRegestriy.put("solrcmdutils.BeanShellFilter", BeanShellFilter.class); classRegestriy.put("solrcmdutils.LookupFilter", LookupFilter.class); classRegestriy.put("solrcmdutils.TokenCounterFilter", TokenCounterFilter.class); classRegestriy.put("solrcmdutils.CharCounterFilter", CharCounterFilter.class); classRegestriy.put("solrcmdutils.CompoundWordFilter", CompoundWordFilter.class); classRegestriy.put("solrcmdutils.LinkCheckerFilter", LinkCheckerFilter.class); classRegestriy.put("solrcmdutils.SolrFeeder", SolrFeeder.class); classRegestriy.put("solrcmdutils.SolrNumFoundFilter", SolrNumFoundFilter.class); classRegestriy.put("solrcmdutils.SolrCompareFilter", SolrCompareFilter.class); classRegestriy.put("solrcmdutils.SystemOutWriter", SystemOutWriter.class); classRegestriy.put("solrcmdutils.NounExtractorFilter", NounExtractorFilter.class); classRegestriy.put("solrcmdutils.FileLineWriter", FileLineWriter.class); classRegestriy.put("solrcmdutils.CSVWriter", CSVWriter.class); classRegestriy.put("solrcmdutils.TestingFilter", TestingFilter.class); classRegestriy.put("solrcmdutils.NoopFilter", NoopFilter.class); } public PipelineExecuter(String yamlFileName) { this.yamlFileName = yamlFileName; } private String getBaseDirFromYamlFile() { File f = new File(yamlFileName).getAbsoluteFile(); return f.getParentFile().getAbsoluteFile().toString(); } public void init() { LOG.debug("Read the pipeline configuration from the yaml file: {}", yamlFileName); try { pipeline = readPipelineFromYamlFile(yamlFileName); LOG.debug("Default variables in the pipeline {}", pipeline.getVariables()); LOG.debug("Configured variables in the pipeline {}", pipelineVariables); pipeline.getVariables().putAll(pipelineVariables); LOG.debug("Effective variables in the pipeline {}", pipeline.getVariables()); reader = (ReaderIF) getInstance(pipeline.getReader().getClazz()); reader.setPipelineExecuter(this); reader.setReader(pipeline.getReader()); reader.setBaseDir(getBaseDirFromYamlFile()); reader.setVariables(pipeline.getVariables()); filterList = new ArrayList<FilterIF>(); FilterIF lastFilter = null; FilterIF filterInstance = null; for(Filter filter : pipeline.getFilter()) { if(filter.getDisabled() != null && filter.getDisabled()) { continue; } filterInstance = createFilterInstance(filter); filterInstance.setBaseDir(getBaseDirFromYamlFile()); filterInstance.setVariables(pipeline.getVariables()); if(lastFilter == null) { lastFilter = filterInstance; continue; } lastFilter.setNextFilter(filterInstance); filterList.add(lastFilter); lastFilter = filterInstance; } filterInstance.setNextFilter(new LastFilter()); filterList.add(filterInstance); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } } public static Object getInstance(String clazz) throws ClassNotFoundException, IllegalAccessException, InstantiationException { Class clazzClass = classRegestriy.get(clazz); if(clazzClass != null) { return Class.forName(clazzClass.getName()).newInstance(); } return Class.forName(clazz).newInstance(); } public static FilterIF createFilterInstance(Filter filter) { try { String filterClazz = filter.getClazz(); FilterIF filterInstance = (FilterIF) getInstance(filterClazz); filterInstance.setFilterConfig(filter); return filterInstance; } catch (Exception e) { throw new RuntimeException(e); } } public void execute() { LOG.debug("Start the initialization."); init(); LOG.debug("Start the initialization for all filters."); filterList.get(0).init(); LOG.debug("Read the input from the configured reader."); reader.read(); LOG.debug("Finalize the pipeline."); end(); } //public void field(String name, String value) { // filterList.get(0).field(name, value); public void document(Document document) { filterList.get(0).document(document); } public void end() { reader.end(); filterList.get(0).end(); } Pipeline readPipelineFromYamlFile(String fileName) { try { InputStream input = new FileInputStream(new File( fileName)); Yaml yaml = new Yaml(new Constructor(Pipeline.class)); Pipeline pipeline = (Pipeline) yaml.load(input); input.close(); return pipeline; } catch (Exception e) { throw new RuntimeException(e); } } public List<FilterIF> getFilterList() { return filterList; } public FilterIF getFilterById(String filterId) { for(FilterIF filter : getFilterList()) { if(filterId.equals(filter.getId())) { return filter; } } throw new IllegalArgumentException("The filter with the id: " + filterId + " does not exists."); } public ReaderIF getReader() { return this.reader; } public Map<String, String> getPipelineVariables() { return pipelineVariables; } public void setPipelineVariables(Map<String, String> pipelineVariables) { this.pipelineVariables = pipelineVariables; } public void addPipelineVariable(String name, String value) { this.pipelineVariables.put(name, value); } }
package to.etc.domui.component.form; import to.etc.domui.component.meta.*; import to.etc.domui.dom.html.*; import to.etc.domui.util.*; abstract public class GenericFormBuilder extends FormBuilderBase { /** * This is the actual workhorse doing the per-builder actual placement and layouting of a {control, label} pair. * * @param label * @param labelnode * @param list * @param mandatory T when the node is mandatory, needed by the label factory * @param editable T when the node is editable, needed by the label factory * @param pmm */ abstract protected void addControl(String label, NodeBase labelnode, NodeBase[] list, boolean mandatory, boolean editable, PropertyMetaModel pmm); abstract protected void addControl(Label label, NodeBase labelnode, NodeBase[] list, boolean mandatory, boolean editable, PropertyMetaModel pmm); /** * Handle placement of a list of property names, all obeying the current mode in effect. * @param editable * @param names */ abstract protected IControl< ? >[] addListOfProperties(boolean editable, final String... names); /** * Complete the visual representation of this form, and return the node representing it. * * @return */ abstract NodeContainer finish(); /** * Default ctor. */ public GenericFormBuilder() {} /** * Create one primed with a model and class. * @param <T> * @param clz * @param mdl */ public <T> GenericFormBuilder(Class<T> clz, IReadOnlyModel<T> mdl) { super(clz, mdl); } /** * {@inheritDoc} * @param <T> * @param instance */ public <T> GenericFormBuilder(T instance) { super(instance); } /* CODING: Core shared public interface - all builders. */ /** * Add an input for the specified property. The property is based at the current input * class. The input model is default (using metadata) and the property is labeled using * the metadata-provided label. * * FORMAL-INTERFACE. * * @param name */ public IControl< ? > addProp(final String name) { return addProp(name, (String) null); } /** * Add an input for the specified property. The property is based at the current input * class. The input model is default (using metadata) and the property is labeled. * * FORMAL-INTERFACE. * * @param name * @param label The label text to use. Use the empty string to prevent a label from being generated. This still adds an empty cell for the label though. */ public IControl< ? > addProp(final String name, String label) { PropertyMetaModel pmm = resolveProperty(name); if(label == null) label = pmm.getDefaultLabel(); boolean editable = true; if(pmm.getReadOnly() == YesNoType.YES) editable = false; return addPropertyControl(name, label, pmm, editable); } /** * Add an input for the specified property. The property is based at the current input * class. The input model is default (using metadata) and the property is labeled using * the metadata-provided label. * * FORMAL-INTERFACE. * * @param name * @param label Add custom label. * @param editable When false this adds a display-only field, when true a fully editable control. * @param mandatory Specify if field is mandatory. This <b>always</b> overrides the mandatoryness of the metadata which is questionable. */ public IControl< ? > addProp(final String name, String label, final boolean editable, final boolean mandatory) { PropertyMetaModel pmm = resolveProperty(name); if(!rights().calculate(pmm)) return null; boolean reallyeditable = editable && rights().isEditable(); final ControlFactoryResult r = createControlFor(getModel(), pmm, reallyeditable); // Add the proper input control for that type addControl(label, r.getLabelNode(), r.getNodeList(), mandatory, reallyeditable, pmm); r.getFormControl().setMandatory(mandatory); //-- jal 20090924 Bug 624 Assign the control label to all it's node so it can specify it in error messages if(label != null) { for(NodeBase b : r.getNodeList()) b.setErrorLocation(label); } if(r.getBinding() != null) getBindings().add(r.getBinding()); else throw new IllegalStateException("No binding for a " + r); return r.getFormControl(); } /** * Add an input for the specified property. The property is based at the current input * class. The input model is default (using metadata) and the property is labeled using * the metadata-provided label. * * FORMAL-INTERFACE. * * @param name * @param editable When false add a display-only control, else add an editable control. */ public IControl< ? > addProp(final String name, final boolean editable) { if(editable) { return addProp(name); } else { return addDisplayProp(name); } } /** * Add an input for the specified property. The property is based at the current input * class. The input model is default (using metadata) and the property is labeled using * the metadata-provided label. * * FORMAL-INTERFACE. * * @param name * @param editable When false this adds a display-only field, when true a fully editable control. * @param mandatory Specify if field is mandatory. This <b>always</b> overrides the mandatoryness of the metadata which is questionable. */ public IControl< ? > addProp(final String name, final boolean editable, final boolean mandatory) { PropertyMetaModel pmm = resolveProperty(name); String label = pmm.getDefaultLabel(); return addProp(name, label, editable, mandatory); } /** * Add a display-only field for the specified property. The field cannot be made * editable. * * @param name */ public IControl< ? > addDisplayProp(final String name) { return addDisplayProp(name, null); } /** * Add an input for the specified property just as <code>addProp(String, String)</code>, * only this input won't be editable (ever). * * @param name * @param label */ public IControl< ? > addDisplayProp(final String name, String label) { PropertyMetaModel pmm = resolveProperty(name); if(label == null) label = pmm.getDefaultLabel(); return addPropertyControl(name, label, pmm, false); } /** * Add a user-specified control for a given property. This adds the control, using * the property-specified label and creates a binding for the property on the * control. <i>If you only want to add the proper structure and find the label for * a property use {@link TabularFormBuilder#addPropertyAndControl(String, NodeBase, boolean)}. * * FORMAL-INTERFACE. * * @param propertyname * @param ctl */ public <V, T extends NodeBase & IInputNode<V>> IControl<V> addProp(final String propertyname, final T ctl) { PropertyMetaModel pmm = resolveProperty(propertyname); String label = pmm.getDefaultLabel(); addControl(label, ctl, new NodeBase[]{ctl}, ctl.isMandatory(), true, pmm); // Since this is a full control it is editable if(label != null) ctl.setErrorLocation(label); SimpleComponentPropertyBinding<V> b = new SimpleComponentPropertyBinding<V>(getModel(), pmm, ctl); getBindings().add(b); return b; } public <V, T extends NodeBase & IDisplayControl<V>> IControl<V> addDisplayProp(final String propertyname, final T ctl) { PropertyMetaModel pmm = resolveProperty(propertyname); String label = pmm.getDefaultLabel(); addControl(label, ctl, new NodeBase[]{ctl}, false, true, pmm); // Since this is a full control it is editable if(label != null) ctl.setErrorLocation(label); DisplayOnlyPropertyBinding<V> b = new DisplayOnlyPropertyBinding<V>(getModel(), pmm, ctl); getBindings().add(b); return b; } /** * Add a user-specified control for a given property. This adds the control, using * the specified label and creates a binding for the property on the * control. * * FORMAL-INTERFACE. * * @param name * @param label The label text to use. Use the empty string to prevent a label from being generated. This still adds an empty cell for the label though. * @param ctl */ public <V, T extends NodeBase & IInputNode<V>> IControl<V> addProp(final String name, String label, final T ctl) { PropertyMetaModel pmm = resolveProperty(name); addControl(label, ctl, new NodeBase[]{ctl}, ctl.isMandatory(), true, pmm); // Since this is a full control it is editable if(label != null) ctl.setErrorLocation(label); SimpleComponentPropertyBinding<V> b = new SimpleComponentPropertyBinding<V>(getModel(), pmm, ctl); getBindings().add(b); return b; } /** * Add a fully manually specified label and control to the layout. This does not create any binding. * @param label * @param control * @param mandatory */ public void addLabelAndControl(final String label, final NodeBase control, final boolean mandatory) { //-- jal 20090924 Bug 624 Assign the control label to all it's node so it can specify it in error messages if(label != null) control.setErrorLocation(label); // FIXME Kludge to determine if the control is meant to be editable! boolean editable = control instanceof IControl< ? >; addControl(label, control, new NodeBase[]{control}, mandatory, editable, null); } /** * Add a fully manually specified label and control to the layout. This does not create any binding. Since label caption can contain extra characters, error location can be assigned additionaly. * @param label * @param errorLocation * @param control * @param mandatory */ public void addLabelAndControl(final Label label, final String errorLocation, final NodeBase control, final boolean mandatory) { //-- jal 20090924 Bug 624 Assign the control label to all it's node so it can specify it in error messages if(errorLocation != null) control.setErrorLocation(errorLocation); // FIXME Kludge to determine if the control is meant to be editable! boolean editable = control instanceof IControl< ? >; addControl(label, control, new NodeBase[]{control}, mandatory, editable, null); } protected IControl< ? > addPropertyControl(final String name, final String label, final PropertyMetaModel pmm, final boolean editable) { if(!rights().calculate(pmm)) return null; boolean reallyeditable = editable && rights().isEditable(); final ControlFactoryResult r = createControlFor(getModel(), pmm, reallyeditable); // Add the proper input control for that type addControl(label, r.getLabelNode(), r.getNodeList(), pmm.isRequired(), reallyeditable, pmm); //-- jal 20090924 Bug 624 Assign the control label to all it's node so it can specify it in error messages if(label != null) { for(NodeBase b : r.getNodeList()) b.setErrorLocation(label); } if(r.getBinding() != null) getBindings().add(r.getBinding()); else throw new IllegalStateException("No binding for a " + r); return r.getFormControl(); } /** * This adds a fully user-specified control for a given property with it's default label, * without creating <i>any<i> binding. The only reason the property is passed is to use * it's metadata to define it's access rights and default label. * * @param propertyName * @param nb * @param mandatory */ public void addPropertyAndControl(final String propertyName, final NodeBase nb, final boolean mandatory) { PropertyMetaModel pmm = resolveProperty(propertyName); String label = pmm.getDefaultLabel(); // FIXME Kludge to determine if the control is meant to be editable! boolean editable = nb instanceof IControl< ? >; addControl(label, nb, new NodeBase[]{nb}, mandatory, editable, pmm); if(label != null) nb.setErrorLocation(label); } /** * Add the specified properties to the form, in the current mode. Watch out: if a * MODIFIER is in place the modifier is obeyed for <b>all properties</b>, not for * the first one only!! This means that when this gets called like: * <pre> * f.append().addProps("a", "b","c"); * </pre> * all three fields are appended to the current row. * * FORMAL-INTERFACE. * * @param names */ public IControl< ? >[] addProps(final String... names) { return addListOfProperties(true, names); } /** * Add the specified properties to the form as display-only properties, in the current * mode. Watch out: if a MODIFIER is in place the modifier is obeyed for <b>all * properties</b>, not for the first one only!! This means that when this gets called * like: * <pre> * f.append().addProps("a", "b","c"); * </pre> * all three fields are appended to the current row. * * FORMAL-INTERFACE. * * @param names */ public IControl< ? >[] addDisplayProps(final String... names) { return addListOfProperties(false, names); } }
package io.viper.app.photon; import io.viper.core.server.Util; import io.viper.core.server.file.*; import java.io.File; import java.io.IOException; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.Executors; import io.viper.core.server.router.*; import org.jboss.netty.bootstrap.ServerBootstrap; import org.jboss.netty.channel.*; import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; import org.jboss.netty.handler.codec.http.*; import org.json.JSONException; import org.json.JSONObject; public class CloudCmdServer { private ServerBootstrap _bootstrap; private final static int MAX_FILE_SIZE = (1024*1024)*1024; public static CloudCmdServer create( String localhostName, int port, String staticFileRoot, String fileStorageRoot) throws IOException, JSONException { CloudCmdServer cloudCmdServer = new CloudCmdServer(); cloudCmdServer._bootstrap = new ServerBootstrap( new NioServerSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool())); String localhost = String.format("http://%s:%s", localhostName, port); new File(fileStorageRoot).mkdir(); ChannelPipelineFactory channelPipelineFactory = new CloudCmdServerChannelPipelineFactory( MAX_FILE_SIZE, staticFileRoot, fileStorageRoot, localhostName); cloudCmdServer._bootstrap.setPipelineFactory(channelPipelineFactory); cloudCmdServer._bootstrap.bind(new InetSocketAddress(port)); return cloudCmdServer; } private static class CloudCmdServerChannelPipelineFactory implements ChannelPipelineFactory { private final int _maxContentLength; private final String _fileStorageRoot; private final String _staticFileRoot; private final FileContentInfoProvider _staticFileProvider; private final FileContentInfoProvider _fileStorageProvider; private final String _downloadHostname; public CloudCmdServerChannelPipelineFactory( int maxContentLength, String staticFileRoot, String uploadFileRoot, String downloadHostname) throws IOException, JSONException { _maxContentLength = maxContentLength; _fileStorageRoot = uploadFileRoot; _staticFileRoot = staticFileRoot; _downloadHostname = downloadHostname; _staticFileProvider = StaticFileContentInfoProvider.create(_staticFileRoot); _fileStorageProvider = new StaticFileContentInfoProvider(_fileStorageRoot); } @Override public ChannelPipeline getPipeline() throws Exception { List<Route> routes = new ArrayList<Route>(); routes.add(new PostRoute("/cas/", new RouteHandler() { @Override public HttpResponse exec(Map<String, String> args) { return null; } })); routes.add(new GetRoute("/cas/$var", new RouteHandler() { @Override public HttpResponse exec(Map<String, String> args) throws Exception { JSONObject obj = new JSONObject(); obj.put("status", "woot!"); obj.put("var", args.get("var")); HttpResponse response = Util.createResponse(obj); return response; } })); routes.add(new GetRoute("/d/$path", new StaticFileServerHandler(_fileStorageProvider))); routes.add(new GetRoute("/$path", new StaticFileServerHandler(_staticFileProvider))); ChannelPipeline lhPipeline = new DefaultChannelPipeline(); lhPipeline.addLast("decoder", new HttpRequestDecoder()); lhPipeline.addLast("encoder", new HttpResponseEncoder()); lhPipeline.addLast("router", new RouterMatcherUpstreamHandler("uri-handlers", routes)); return lhPipeline; } } }
/** * Initializes, saves, and responds to requests to retrieve or update the counter for number of lists enriched and shared. * * @author Edward Y. Chen * @since 09/12/2012 */ package edu.mssm.pharm.maayanlab.Enrichr; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.hibernate.Criteria; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.criterion.Restrictions; import edu.mssm.pharm.maayanlab.common.core.FileUtils; import edu.mssm.pharm.maayanlab.common.web.HibernateUtil; @WebServlet(urlPatterns = {"/count"}, loadOnStartup=1) public class Counters extends HttpServlet { private static final long serialVersionUID = -682732829814620653L; private static Counter count; private static Counter share; @Override public void init() throws ServletException { // Read counters from SQL SessionFactory sf = HibernateUtil.getSessionFactory(); Session session = null; try { session = sf.getCurrentSession(); } catch (HibernateException he) { session = sf.openSession(); } session.beginTransaction(); Criteria criteria = session.createCriteria(Counter.class) .add(Restrictions.eq("name", "enrichment")); count = (Counter) criteria.uniqueResult(); criteria = session.createCriteria(Counter.class) .add(Restrictions.eq("name", "share")); share = (Counter) criteria.uniqueResult(); session.getTransaction().commit(); session.close(); // Try to load the initial count from our saved persistent state BufferedReader bufferedReader = null; try { bufferedReader = new BufferedReader(new FileReader("/datasets/count")); int value = Integer.parseInt(bufferedReader.readLine()); if (value > count.getCount()) count.setCount(value); bufferedReader.close(); bufferedReader = new BufferedReader(new FileReader("/datasets/share")); value = Integer.parseInt(bufferedReader.readLine()); if (value > share.getCount()) share.setCount(value); Counters.updateCounter(count); Counters.updateCounter(share); } catch (FileNotFoundException ignored) { } // no saved state catch (IOException ignored) { } // problem during read catch (NumberFormatException ignored) { } // corrupt saved state finally { // Make sure to close the file try { if (bufferedReader != null) bufferedReader.close(); } catch (IOException ignored) { } } // Save counters to be available servlet wide getServletContext().setAttribute("enrichment_count", count); getServletContext().setAttribute("share_count", share); } @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/plain"); response.getWriter().print(count.getCount()); } @Override public void destroy() { super.destroy(); // entirely optional // Try to save the accumulated count FileUtils.writeString("/datasets/count", Integer.toString(count.getCount())); FileUtils.writeString("/datasets/share", Integer.toString(share.getCount())); } static void updateCounter(Counter counter) { SessionFactory sf = HibernateUtil.getSessionFactory(); Session session = null; try { session = sf.getCurrentSession(); } catch (HibernateException he) { session = sf.openSession(); } session.beginTransaction(); session.update(counter); session.getTransaction().commit(); session.close(); } }
package fr.kisuke.rest.resources; import fr.kisuke.JsonViews; import fr.kisuke.dao.picture.PictureDao; import fr.kisuke.entity.Pictures; import org.codehaus.jackson.map.ObjectWriter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.stereotype.Component; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Response; import java.io.*; @Component @Path("/files") public class DownloadResource { @Autowired private PictureDao pictureDao; @GET @Path("getImage/{imageId}")
package hprose.io.unserialize; import hprose.util.IdentityMap; import java.math.BigDecimal; import java.math.BigInteger; import java.sql.Date; import java.sql.Time; import java.sql.Timestamp; import java.util.AbstractCollection; import java.util.AbstractList; import java.util.AbstractMap; import java.util.AbstractSequentialList; import java.util.AbstractSet; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedMap; import java.util.SortedSet; import java.util.TreeMap; import java.util.TreeSet; import java.util.UUID; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicIntegerArray; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicLongArray; import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReferenceArray; public final class UnserializerFactory { private static final IdentityMap<Class<?>, HproseUnserializer> unserializers = new IdentityMap<Class<?>, HproseUnserializer>(); static { unserializers.put(void.class, DefaultUnserializer.instance); unserializers.put(boolean.class, BooleanUnserializer.instance); unserializers.put(char.class, CharUnserializer.instance); unserializers.put(byte.class, ByteUnserializer.instance); unserializers.put(short.class, ShortUnserializer.instance); unserializers.put(int.class, IntUnserializer.instance); unserializers.put(long.class, LongUnserializer.instance); unserializers.put(float.class, FloatUnserializer.instance); unserializers.put(double.class, DoubleUnserializer.instance); unserializers.put(Object.class, DefaultUnserializer.instance); unserializers.put(Void.class, DefaultUnserializer.instance); unserializers.put(Boolean.class, BooleanObjectUnserializer.instance); unserializers.put(Character.class, CharObjectUnserializer.instance); unserializers.put(Byte.class, ByteObjectUnserializer.instance); unserializers.put(Short.class, ShortObjectUnserializer.instance); unserializers.put(Integer.class, IntObjectUnserializer.instance); unserializers.put(Long.class, LongObjectUnserializer.instance); unserializers.put(Float.class, FloatObjectUnserializer.instance); unserializers.put(Double.class, DoubleObjectUnserializer.instance); unserializers.put(String.class, StringUnserializer.instance); unserializers.put(BigInteger.class, BigIntegerUnserializer.instance); unserializers.put(Date.class, DateUnserializer.instance); unserializers.put(Time.class, TimeUnserializer.instance); unserializers.put(Timestamp.class, TimestampUnserializer.instance); unserializers.put(java.util.Date.class, DateTimeUnserializer.instance); unserializers.put(Calendar.class, CalendarUnserializer.instance); unserializers.put(BigDecimal.class, BigDecimalUnserializer.instance); unserializers.put(StringBuilder.class, StringBuilderUnserializer.instance); unserializers.put(StringBuffer.class, StringBufferUnserializer.instance); unserializers.put(UUID.class, UUIDUnserializer.instance); unserializers.put(boolean[].class, BooleanArrayUnserializer.instance); unserializers.put(char[].class, CharArrayUnserializer.instance); unserializers.put(byte[].class, ByteArrayUnserializer.instance); unserializers.put(short[].class, ShortArrayUnserializer.instance); unserializers.put(int[].class, IntArrayUnserializer.instance); unserializers.put(long[].class, LongArrayUnserializer.instance); unserializers.put(float[].class, FloatArrayUnserializer.instance); unserializers.put(double[].class, DoubleArrayUnserializer.instance); unserializers.put(String[].class, StringArrayUnserializer.instance); unserializers.put(BigInteger[].class, BigIntegerArrayUnserializer.instance); unserializers.put(Date[].class, DateArrayUnserializer.instance); unserializers.put(Time[].class, TimeArrayUnserializer.instance); unserializers.put(Timestamp[].class, TimestampArrayUnserializer.instance); unserializers.put(java.util.Date[].class, DateTimeArrayUnserializer.instance); unserializers.put(Calendar[].class, CalendarArrayUnserializer.instance); unserializers.put(BigDecimal[].class, BigDecimalArrayUnserializer.instance); unserializers.put(StringBuilder[].class, StringBuilderArrayUnserializer.instance); unserializers.put(StringBuffer[].class, StringBufferArrayUnserializer.instance); unserializers.put(UUID[].class, UUIDArrayUnserializer.instance); unserializers.put(char[][].class, CharsArrayUnserializer.instance); unserializers.put(byte[][].class, BytesArrayUnserializer.instance); unserializers.put(ArrayList.class, ArrayListUnserializer.instance); unserializers.put(AbstractList.class, ArrayListUnserializer.instance); unserializers.put(AbstractCollection.class, ArrayListUnserializer.instance); unserializers.put(List.class, ArrayListUnserializer.instance); unserializers.put(Collection.class, ArrayListUnserializer.instance); unserializers.put(LinkedList.class, LinkedListUnserializer.instance); unserializers.put(AbstractSequentialList.class, LinkedListUnserializer.instance); unserializers.put(HashSet.class, HashSetUnserializer.instance); unserializers.put(AbstractSet.class, HashSetUnserializer.instance); unserializers.put(Set.class, HashSetUnserializer.instance); unserializers.put(TreeSet.class, TreeSetUnserializer.instance); unserializers.put(SortedSet.class, TreeSetUnserializer.instance); unserializers.put(HashMap.class, HashMapUnserializer.instance); unserializers.put(AbstractMap.class, HashMapUnserializer.instance); unserializers.put(Map.class, HashMapUnserializer.instance); unserializers.put(TreeMap.class, TreeMapUnserializer.instance); unserializers.put(SortedMap.class, TreeMapUnserializer.instance); unserializers.put(AtomicBoolean.class, AtomicBooleanUnserializer.instance); unserializers.put(AtomicInteger.class, AtomicIntegerUnserializer.instance); unserializers.put(AtomicLong.class, AtomicLongUnserializer.instance); unserializers.put(AtomicReference.class, AtomicReferenceUnserializer.instance); unserializers.put(AtomicIntegerArray.class, AtomicIntegerArrayUnserializer.instance); unserializers.put(AtomicLongArray.class, AtomicLongArrayUnserializer.instance); unserializers.put(AtomicReferenceArray.class, AtomicReferenceArrayUnserializer.instance); } public final static HproseUnserializer get(Class<?> type) { HproseUnserializer unserializer = unserializers.get(type); if (unserializer == null) { if (type.isEnum()) { unserializer = EnumUnserializer.instance; } else if (type.isArray()) { unserializer = OtherTypeArrayUnserializer.instance; } else if (Collection.class.isAssignableFrom(type)) { unserializer = CollectionUnserializer.instance; } else if (Map.class.isAssignableFrom(type)) { unserializer = MapUnserializer.instance; } else { unserializer = OtherTypeUnserializer.instance; } unserializers.put(type, unserializer); } return unserializer; } }
package hudson.plugins.warnings.util; import hudson.FilePath; import hudson.plugins.warnings.util.model.FileAnnotation; import hudson.plugins.warnings.util.model.Priority; import java.io.File; import java.io.IOException; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import edu.umd.cs.findbugs.annotations.SuppressWarnings; /** * Stores the collection of parsed annotations and associated error messages. * * @author Ulli Hafner */ public class ParserResult implements Serializable { /** Unique ID of this class. */ private static final long serialVersionUID = -8414545334379193330L; /** The parsed annotations. */ @SuppressWarnings("Se") private final Set<FileAnnotation> annotations = new HashSet<FileAnnotation>(); /** The collection of error messages. */ @SuppressWarnings("Se") private final List<String> errorMessages = new ArrayList<String>(); /** Number of annotations by priority. */ @SuppressWarnings("Se") private final Map<Priority, Integer> annotationCountByPriority = new HashMap<Priority, Integer>(); /** The set of modules. */ @SuppressWarnings("Se") private final Set<String> modules = new HashSet<String>(); /** The workspace (might be null). */ private final FilePath workspace; /** A mapping of relative file names to absolute file names. */ private final Map<String, String> fileNameCache = new HashMap<String, String>(); /** * Creates a new instance of {@link ParserResult}. */ public ParserResult() { this(null); } /** * Creates a new instance of {@link ParserResult}. * * @param workspace * the workspace to find the files in */ public ParserResult(final FilePath workspace) { this.workspace = workspace; Priority[] priorities = Priority.values(); for (int priority = 0; priority < priorities.length; priority++) { annotationCountByPriority.put(priorities[priority], 0); } } /** * Finds a file with relative filename and replaces the name with the absolute path. * * @param annotation the annotation */ private void findRelativeFile(final FileAnnotation annotation) { try { if (workspace != null && hasRelativeFileName(annotation)) { if (fileNameCache.isEmpty()) { populateFileNameCache(); } if (fileNameCache.containsKey(annotation.getFileName())) { annotation.setFileName(workspace.getRemote() + "/" + fileNameCache.get(annotation.getFileName())); } } } catch (IOException exception) { // ignore } catch (InterruptedException exception) { // ignore } } /** * Builds a cache of file names in the remote file system. * * @throws IOException * if the file could not be read * @throws InterruptedException * if the user cancels the search */ private void populateFileNameCache() throws IOException, InterruptedException { String[] allFiles = workspace.act(new FileFinder("**/*")); for (String file : allFiles) { String fileName = new File(file).getName(); if (fileNameCache.containsKey(fileName)) { fileNameCache.remove(fileName); } else { fileNameCache.put(fileName, file); } } } /** * Returns whether the annotation references a relative filename. * * @param annotation the annotation * @return <code>true</code> if the filename is relative */ private boolean hasRelativeFileName(final FileAnnotation annotation) { String fileName = annotation.getFileName(); return !fileName.startsWith("/") && !fileName.contains(":"); } /** * Adds the specified annotation to this container. * * @param annotation the annotation to add */ public void addAnnotation(final FileAnnotation annotation) { if (!annotations.contains(annotation)) { findRelativeFile(annotation); annotations.add(annotation); Integer count = annotationCountByPriority.get(annotation.getPriority()); annotationCountByPriority.put(annotation.getPriority(), count + 1); } } /** * Adds the specified annotations to this container. * * @param newAnnotations the annotations to add */ public final void addAnnotations(final Collection<? extends FileAnnotation> newAnnotations) { for (FileAnnotation annotation : newAnnotations) { addAnnotation(annotation); } } /** * Adds the specified annotations to this container. * * @param newAnnotations the annotations to add */ public final void addAnnotations(final FileAnnotation[] newAnnotations) { addAnnotations(Arrays.asList(newAnnotations)); } /** * Sets an error message for the specified module name. * * @param message * the error message */ public void addErrorMessage(final String message) { errorMessages.add(message); } /** * Returns the errorMessages. * * @return the errorMessages */ public Collection<String> getErrorMessages() { return Collections.unmodifiableCollection(errorMessages); } /** * Returns the annotations of this result. * * @return the annotations of this result */ public Collection<FileAnnotation> getAnnotations() { return Collections.unmodifiableCollection(annotations); } /** * Returns the total number of annotations for this object. * * @return total number of annotations for this object */ public int getNumberOfAnnotations() { return annotations.size(); } /** * Returns the total number of annotations of the specified priority for * this object. * * @param priority * the priority * @return total number of annotations of the specified priority for this * object */ public int getNumberOfAnnotations(final Priority priority) { return annotationCountByPriority.get(priority); } /** * Returns whether this objects has annotations. * * @return <code>true</code> if this objects has annotations. */ public boolean hasAnnotations() { return !annotations.isEmpty(); } /** * Returns whether this objects has annotations with the specified priority. * * @param priority * the priority * @return <code>true</code> if this objects has annotations. */ public boolean hasAnnotations(final Priority priority) { return annotationCountByPriority.get(priority) > 0; } /** * Returns whether this objects has no annotations. * * @return <code>true</code> if this objects has no annotations. */ public boolean hasNoAnnotations() { return !hasAnnotations(); } /** * Returns whether this objects has no annotations with the specified priority. * * @param priority * the priority * @return <code>true</code> if this objects has no annotations. */ public boolean hasNoAnnotations(final Priority priority) { return !hasAnnotations(priority); } /** * Returns the number of modules. * * @return the number of modules */ public int getNumberOfModules() { return modules.size(); } /** * Returns the parsed modules. * * @return the parsed modules */ public Set<String> getModules() { return Collections.unmodifiableSet(modules); } /** * Adds a new parsed module. * * @param moduleName * the name of the parsed module */ public void addModule(final String moduleName) { modules.add(moduleName); } /** * Adds the specified parsed modules. * * @param additionalModules * the name of the parsed modules */ public void addModules(final Collection<String> additionalModules) { modules.addAll(additionalModules); } }
package innovimax.mixthem.join; import innovimax.mixthem.exceptions.MixException; import innovimax.mixthem.interfaces.IJoinLine; //import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; /** * <p>Joins two lines on a common field.</p> * <p>This is the default implementation of IJoinLine.</p> * @see IJoinLine * @author Innovimax * @version 1.0 */ public class DefaultLineJoining implements IJoinLine { @Override public JoinType getType(List<String> params) { JoinType type; if (params.size() == 0) { type = JoinType._DEFAULT; } else if (params.size() == 1) { type = JoinType._SAME_COL; } else { type = JoinType._DIFF_COL; } return type; } @Override public List<Integer> getColumns(List<String> params) throws MixException { try { return params.stream().map(s -> new Integer(s)).collect(Collectors.toList()); } catch (NumberFormatException e) { throw new MixException("Unexpected join parameter values " + params.toString(), e); } } @Override public String join(String line1, String line2, JoinType type, List<Integer> columns) throws MixException { String join = null; if (line1 != null && line2 != null) { List<String> list1 = Arrays.asList(line1.split("\\s")); List<String> list2 = Arrays.asList(line2.split("\\s")); switch (type) { case _DEFAULT: if (list1.size() > 0 && list2.contains(list1.get(0))) { String part1 = list1.stream().collect(Collectors.joining(" ")); String part2 = list2.stream().filter(s -> !list1.contains(s)).collect(Collectors.joining(" ")); join = part1 + " " + part2; } break; case _SAME_COL: int col = columns.get(0).intValue(); if (list1.size() >= col && list2.size() >= col && list1.get(col - 1).equals(list2.get(col - 1))) { String part1 = list1.get(col - 1); String part2 = list1.stream().filter(s -> !s.equals(part1)).collect(Collectors.joining(" ")); String part3 = list2.stream().filter(s -> !list1.contains(s)).collect(Collectors.joining(" ")); join = part1 + " " + part2 + " " + part3; } break; case _DIFF_COL: int col1 = columns.get(0).intValue(); int col2 = columns.get(1).intValue(); if (list1.size() >= col1 && list2.size() >= col2 && list1.get(col1 - 1).equals(list2.get(col2 - 1))) { String part1 = list1.get(col1 - 1); String part2 = list1.stream().filter(s -> !s.equals(part1)).collect(Collectors.joining(" ")); String part3 = list2.stream().filter(s -> !list1.contains(s)).collect(Collectors.joining(" ")); join = part1 + " " + part2 + " " + part3; } break; } } return join; } }
package io.druid.segment.loading; import io.druid.timeline.DataSegment; import java.util.Map; public interface DataSegmentMover { public DataSegment move(DataSegment segment, Map<String, Object> targetLoadSpec) throws SegmentLoadingException; }
package it.unipi.di.acube.smaph.server; import org.glassfish.grizzly.http.server.HttpServer; import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory; import org.glassfish.jersey.server.ResourceConfig; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import it.unipi.di.acube.smaph.server.rest.RestService; import java.io.IOException; import java.lang.invoke.MethodHandles; import java.net.URI; public class ServerMain { public static final String BASE_URI = "http://localhost:8080/smaph/"; private final static Logger LOG = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); /** * Starts Grizzly HTTP server exposing JAX-RS resources defined in this * application. * * @return Grizzly HTTP server. */ public static HttpServer startServer() { final ResourceConfig rc = new ResourceConfig().packages("it.unipi.di.acube.smaph.server.rest"); return GrizzlyHttpServerFactory.createHttpServer(URI.create(BASE_URI), rc); } /** * Main method. * * @param args * @throws IOException */ public static void main(String[] args) throws IOException { LOG.info("Initializing server."); RestService.initialize(); HttpServer server = startServer(); LOG.info(String.format("Smaph started with WADL available at " + "%sapplication.wadl%nPress Enter to terminate.", BASE_URI)); System.in.read(); server.shutdown(); } }
package kalang.compiler.compile.codegen; import kalang.compiler.AstNotFoundException; import kalang.compiler.CodeGenerationException; import kalang.compiler.CompileException; import kalang.compiler.MalformedAstException; import kalang.compiler.ast.*; import kalang.compiler.compile.AstLoader; import kalang.compiler.compile.CodeGenerator; import kalang.compiler.core.*; import kalang.compiler.core.Type; import kalang.compiler.exception.Exceptions; import kalang.compiler.function.LambdaExpr; import kalang.compiler.tool.OutputManager; import kalang.compiler.util.*; import org.objectweb.asm.*; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.io.IOException; import java.io.OutputStream; import java.lang.invoke.*; import java.lang.reflect.Modifier; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; import static kalang.compiler.core.Types.*; import static org.objectweb.asm.Opcodes.*; /** *The class generate the java class binary data for ast * * @author Kason Yang */ public class Ast2Class extends AbstractAstVisitor<Object> implements CodeGenerator{ private static Logger LOG = Logger.getLogger(Ast2Class.class.getName()); private ClassWriter classWriter; private MethodVisitor md; private OutputManager outputManager; private final AstLoader astLoader; private Map<Integer,Label> lineLabels = new HashMap(); private Map<VarObject,Integer> varIds = new HashMap<>(); private Stack<Integer> varStartIndexOfFrame = new Stack(); private Map<VarObject,Label> varStartLabels = new HashMap(); private VarTable<Integer,LocalVarNode> varTables = new VarTable(); private int varIdCounter = 0; private Stack<Label> breakLabels = new Stack<>(); private Stack<Label> continueLabels = new Stack<>(); private Stack<CatchContext> catchContextStack = new Stack<>(); private final static int T_I = 0, T_L = 1, T_F = 2, T_D = 3, T_A = 4; private ClassNode clazz; private String classInternalName; public Ast2Class(OutputManager outputManager, AstLoader astLoader) { this.outputManager = outputManager; this.astLoader = astLoader; } private int getT(Type type){ int t; if( type.equals(INT_TYPE) ||type.equals(BOOLEAN_TYPE) || type.equals(CHAR_TYPE) || type.equals(BYTE_TYPE) || type.equals(SHORT_TYPE) ){ t = T_I; }else if(type.equals(LONG_TYPE)){ t = T_L; }else if(type.equals(FLOAT_TYPE)){ t = T_F; }else if(type.equals(DOUBLE_TYPE)){ t = T_D; }else{ t = T_A; } return t; } @Nullable private String classSignature(ClassNode c){ GenericType[] genericTypes = c.getGenericTypes(); if(genericTypes==null || genericTypes.length==0){ return null; } StringBuilder gnrTypeStr = new StringBuilder(); for(GenericType t:genericTypes){ gnrTypeStr.append(t.getName()).append(":").append("Ljava/lang/Object;"); } StringBuilder superTypeStr = new StringBuilder(); if(c.getSuperType()!=null) superTypeStr.append(typeSignature(c.getSuperType())); for(ObjectType itf:c.getInterfaces()){ superTypeStr.append(typeSignature(itf)); } return "<" + gnrTypeStr + ">" + superTypeStr ; } private String methodSignature(MethodNode m){ StringBuilder ptype = new StringBuilder(); for(ParameterNode p:m.getParameters()){ ptype.append(typeSignature(p.getType())); } return "(" + ptype + ")" + typeSignature(m.getType()); } @Nullable private String typeSignature(Type type){ if(type instanceof GenericType){ return "T" + type.getName() + ";" ; }else if(type instanceof ClassType){ ClassType pt = (ClassType) type; StringBuilder ptypes = new StringBuilder(); for(Type p:pt.getTypeArguments()){ ptypes.append(typeSignature(p)); } if(ptypes.length() > 0) ptypes = new StringBuilder("<" + ptypes + ">"); return "L" + pt.getClassNode().name.replace('.', '/') + ptypes + ";"; }else if(type instanceof PrimitiveType){ return getTypeDescriptor(type); }else if(type instanceof ArrayType){ return "[" + typeSignature(((ArrayType)type).getComponentType()); }else if(type instanceof WildcardType){ WildcardType wt = (WildcardType) type; Type[] lbs = wt.getLowerBounds(); Type[] ubs = wt.getUpperBounds(); if(lbs.length>0){ //FIXME handle other lowerBounds return "-" + typeSignature(lbs[0]) ; }else if(ubs.length>0){ //FIXME handle other lowerBounds return "+" + typeSignature(ubs[0]) ; }else{ return "*"; } }else{ throw Exceptions.unsupportedTypeException(type); } } private String internalName(String className){ return className.replace(".", "/"); } private String[] internalNames(String[] names){ String[] inames = new String[names.length]; for(int i=0;i<names.length;i++){ inames[i] = internalName(names[i]); } return inames; } protected String getNullableAnnotation(ObjectType type){ NullableKind nullable = type.getNullable(); if(nullable == NullableKind.NONNULL){ return "kalang.annotation.Nonnull"; }else if(nullable == NullableKind.NULLABLE){ return "kalang.annotation.Nullable"; }else{ return null; } } protected void annotationNullable(Object obj,ObjectType type){ String annotation = getNullableAnnotation(type); if(annotation!=null){ try { annotation(obj, new AnnotationNode(AstLoader.BASE_AST_LOADER.loadAst(annotation))); } catch (AstNotFoundException ex) { throw Exceptions.missingRuntimeClass(ex.getMessage()); } } } protected void annotation(Object obj,AnnotationNode... annotations){ for(AnnotationNode an:annotations){ AnnotationVisitor av; String desc = getTypeDescriptor(Types.getClassType(an.getAnnotationType())); //TODO set annotation visible boolean isVisible = true; if(obj instanceof ClassWriter){ av = ((ClassWriter)obj).visitAnnotation(desc,isVisible); }else if(obj instanceof MethodVisitor){ av = ((MethodVisitor)obj).visitAnnotation(desc, isVisible); }else{ throw Exceptions.unsupportedTypeException(obj); } for(String v:an.values.keySet()){ //TODO handle enum value Object javaConst = getJavaConst(an.values.get(v)); av.visit(v, javaConst); } } } @Override public Object visitClassNode(ClassNode node) { ClassNode oldClass = this.clazz; this.clazz = node; String oldClassInternalName = this.classInternalName; this.classInternalName = internalName(clazz); ClassWriter oldClassWriter = this.classWriter; this.classWriter = new KlClassWriter(ClassWriter.COMPUTE_FRAMES, astLoader); annotation(classWriter, clazz.getAnnotations()); String parentName = "java.lang.Object"; ObjectType superType = node.getSuperType(); if(superType!=null){ parentName = internalName(superType); } String[] interfaces = null; if(node.getInterfaces().length>0){ interfaces = internalName(node.getInterfaces()); } int access = node.modifier; classWriter.visit(V1_8, access,internalName(node.name),classSignature(node), internalName(parentName),interfaces); String fileName = node.fileName; if(fileName!=null && !fileName.isEmpty()){ classWriter.visitSource(fileName, null); } visitChildren(node); Map<MethodDescriptor, MethodNode> implementationMap = InterfaceUtil.getImplementationMap(node); for(Map.Entry<MethodDescriptor,MethodNode> e:implementationMap.entrySet()) { MethodDescriptor interfaceMethod = e.getKey(); MethodNode implementedMethod = e.getValue(); if (implementedMethod!=null) { this.createInterfaceBridgeMethodIfNeed(interfaceMethod.getMethodNode(),implementedMethod); } } //clinit if(!node.staticInitStmts.isEmpty()){ md = classWriter.visitMethod(ACC_STATIC, "<clinit>", "()V", null, null); visitAll(node.staticInitStmts); md.visitInsn(RETURN); md.visitMaxs(1, 1); } if(node.enclosingClass!=null){ this.classWriter.visitInnerClass(this.internalName(node), this.internalName(node.enclosingClass), NameUtil.getSimpleClassName(node.name), node.modifier); } for(ClassNode ic:node.classes){ classWriter.visitInnerClass(internalName(ic), internalName(node), NameUtil.getSimpleClassName(ic.name), ic.modifier); } classWriter.visitEnd(); if(outputManager!=null){ try { try (OutputStream os = outputManager.createOutputStream(node.name)) { os.write(this.classWriter.toByteArray()); } } catch (IOException ex) { throw new RuntimeException(ex); } }else{ LOG.log(Level.WARNING, "outputManager is null"); } this.clazz = oldClass; this.classInternalName = oldClassInternalName; this.classWriter = oldClassWriter; return null; } @Override public Object visitMethodNode(MethodNode node) { int access = node.getModifier(); md = classWriter.visitMethod(access, internalName(node.getName()),getMethodDescriptor(node),methodSignature(node),internalName(node.getExceptionTypes()) ); if(node.getType() instanceof ObjectType){ annotationNullable(md,(ObjectType)node.getType()); } annotation(md, node.getAnnotations()); Label methodStartLabel = new Label(); Label methodEndLabel = new Label(); if(AstUtil.isStatic(node.getModifier())){ varIdCounter = 0; }else{ varIdCounter = 1; } BlockStmt body = node.getBody(); ParameterNode[] parameters = node.getParameters(); for(int i=0;i<parameters.length;i++){ ParameterNode p = parameters[i]; visit(p); if(p.getType() instanceof ObjectType){ String nullableAnnotation = getNullableAnnotation((ObjectType)p.getType()); if (nullableAnnotation!=null && nullableAnnotation.isEmpty()) { md.visitParameterAnnotation(i,getClassDescriptor(nullableAnnotation), true).visitEnd(); } } } md.visitLabel(methodStartLabel); if(body!=null){ visit(body); if(node.getType().equals(VOID_TYPE)){ md.visitInsn(RETURN); } md.visitLabel(methodEndLabel); try{ md.visitMaxs(0, 0); }catch(Exception ex){ ex.printStackTrace(System.err); //throw new RuntimeException("exception when visit method:" + node.name, ex); } } md.visitEnd(); return null; } private void newFrame(){ this.varStartIndexOfFrame.push(this.varIdCounter); this.varTables = this.varTables.newStack(); } private void popFrame(){ for(LocalVarNode v:this.varTables.values()){ this.destroyLocalVarNode(v); } this.varIdCounter = this.varStartIndexOfFrame.pop(); this.varTables = this.varTables.popStack(); } private int declareNewVar(Type type) { int vid = varIdCounter; int vSize = asmType(type).getSize(); varIdCounter += vSize; return vid; } private void declareNewVar(VarObject vo){ int vid = varIdCounter; int vSize = asmType(vo.getType()).getSize(); if(vSize==0){ throw Exceptions.unexpectedException(""); } varIdCounter+= vSize; varIds.put(vo, vid); Label startLabel = new Label(); md.visitLabel(startLabel); this.varStartLabels.put(vo,startLabel); if(vo instanceof LocalVarNode){ this.varTables.put(vid, (LocalVarNode) vo); } } private void destroyLocalVarNode(LocalVarNode var){ Integer vid = this.varIds.get(var); //TODO why vid==null // if(vid==null){ // throw Exceptions.unexpectedValue(vid); Label endLabel = new Label(); md.visitLabel(endLabel); this.varIds.remove(var); String name = var.getName(); if(vid!=null && name!=null && !name.isEmpty()){ md.visitLocalVariable(name, getTypeDescriptor(var.getType()),null ,varStartLabels.get(var), endLabel, vid); } } @Override public Object visitBlockStmt(BlockStmt node) { this.newFrame(); visitChildren(node); this.popFrame(); return null; } @Override public Object visitBreakStmt(BreakStmt node) { if (breakLabels.isEmpty()) { throw new MalformedAstException("break outside of loop", node); } md.visitJumpInsn(GOTO, breakLabels.peek()); return null; } @Override public Object visitContinueStmt(ContinueStmt node) { if (continueLabels.isEmpty()) { throw new MalformedAstException("continue outside of loop", node); } md.visitJumpInsn(GOTO, continueLabels.peek()); return null; } private void pop(Type type){ int size = asmType(type).getSize(); if(size==1){ md.visitInsn(POP); }else if(size==2){ md.visitInsn(POP2); }else{ throw new UnsupportedOperationException("It is unsupported to pop for the type:" + type); } } @Override public Object visitExprStmt(ExprStmt node) { visitChildren(node); Type type = node.getExpr().getType(); if(type !=null && !Types.VOID_TYPE.equals(type)){ pop(type); } return null; } private void ifExpr(boolean jumpOnTrue,ExprNode condition,Label label){ if(condition instanceof LogicBinaryExpr){ LogicBinaryExpr be = (LogicBinaryExpr) condition; ExprNode e1 = be.getExpr1(); ExprNode e2 = be.getExpr2(); String op = be.getOperation(); switch(op){ case "&&": if(jumpOnTrue){ Label stopLabel = new Label(); ifExpr(false,e1,stopLabel); ifExpr(false,e2,stopLabel); md.visitJumpInsn(GOTO, label); md.visitLabel(stopLabel); }else{ ifExpr(false, e1, label); ifExpr(false, e2, label); } break; case "||": if(jumpOnTrue){ ifExpr(true, e1, label); ifExpr(true, e2, label); }else{ Label stopLabel = new Label(); ifExpr(true, e1, stopLabel); ifExpr(true, e2, stopLabel); md.visitJumpInsn(GOTO, label); md.visitLabel(stopLabel); } break; default: throw new UnsupportedOperationException("Unsupported operation:" + op); } }else if(condition instanceof CompareBinaryExpr){ ifCompare(jumpOnTrue,((CompareBinaryExpr) condition).getExpr1(), ((CompareBinaryExpr) condition).getExpr2(), ((CompareBinaryExpr) condition).getOperation(), label); }else if(condition instanceof UnaryExpr && ((UnaryExpr)condition).getOperation().equals("!")){ ifExpr(!jumpOnTrue, ((UnaryExpr)condition).getExpr(), label); }else{ visit(condition); md.visitJumpInsn(jumpOnTrue ? IFNE : IFEQ, label); } } @Override public Object visitIfStmt(IfStmt node) { Label stopLabel = new Label(); Label falseLabel = new Label(); ExprNode condition = node.getConditionExpr(); Statement trueBody = node.getTrueBody(); Statement falseBody = node.getFalseBody(); ifExpr(false,condition,falseLabel); if(trueBody!=null){ visit(trueBody); } if(falseBody==null){ md.visitLabel(falseLabel); }else{ md.visitJumpInsn(GOTO, stopLabel); md.visitLabel(falseLabel); visit(falseBody); } md.visitLabel(stopLabel); return null; } @Override public Object visitLoopStmt(LoopStmt node) { //visitAll(node.initStmts); Label startLabel = new Label(); Label continueLabel = new Label(); Label stopLabel = new Label(); continueLabels.push(continueLabel); breakLabels.push(stopLabel); md.visitLabel(startLabel); if(node.getPreConditionExpr()!=null){ ifExpr(false, node.getPreConditionExpr(),stopLabel); } visit(node.getLoopBody()); md.visitLabel(continueLabel); visit(node.getUpdateStmt()); if(node.getPostConditionExpr()!=null){ ifExpr(false, node.getPostConditionExpr(),stopLabel); } md.visitJumpInsn(GOTO, startLabel); md.visitLabel(stopLabel); continueLabels.pop(); breakLabels.pop(); return null; } @Override public Object visitReturnStmt(ReturnStmt node) { int lnsn = RETURN; if(node.expr!=null){ visit(node.expr); Type type = node.expr.getType(); lnsn = asmType(type).getOpcode(IRETURN); } Stack<CatchContext> ccStack = new Stack<>(); while (!catchContextStack.isEmpty()){ CatchContext catchContext = catchContextStack.pop(); ccStack.push(catchContext); Statement finallyStmt = catchContext.getFinallyStatement(); if (finallyStmt!=null) { this.newFrame(); Label startLabel = new Label(); Label endLabel = new Label(); md.visitLabel(startLabel); visit(finallyStmt); md.visitLabel(endLabel); catchContext.addExclude(startLabel, endLabel); } } while(!ccStack.isEmpty()) { catchContextStack.push(ccStack.pop()); } md.visitInsn(lnsn); return null; } @Override public Object visitTryStmt(TryStmt node) { this.newFrame(); Label tryStartLabel = new Label(); Label tryEndLabel = new Label(); Label exitLabel = new Label(); Label finallyStartLabel = new Label(); BlockStmt execStmt = node.getExecStmt(); BlockStmt finallyStmt = node.getFinallyStmt(); boolean hasFinallyStmt = finallyStmt!=null && !finallyStmt.statements.isEmpty(); CatchContext catchContextOfTry = new CatchContext(tryStartLabel, tryEndLabel, finallyStmt); catchContextStack.push(catchContextOfTry); md.visitLabel(tryStartLabel); visit(execStmt); md.visitLabel(tryEndLabel); this.popFrame(); catchContextStack.pop(); if (finallyStmt!=null) { this.newFrame(); visit(finallyStmt); this.popFrame(); } md.visitJumpInsn(GOTO,exitLabel); Label[] catchLabelsOfTry = catchContextOfTry.getCatchLabels(); if(node.getCatchStmts()!=null){ for(CatchBlock s:node.getCatchStmts()){ this.newFrame(); Label catchStartLabel = new Label(); Label catchStopLabel = new Label(); CatchContext catchContextOfCatch = new CatchContext(catchStartLabel,catchStopLabel,finallyStmt); catchContextStack.push(catchContextOfCatch); md.visitLabel(catchStartLabel); visit(s); md.visitLabel(catchStopLabel); this.popFrame(); catchContextStack.pop(); if (finallyStmt!=null) { this.newFrame(); visit(finallyStmt); this.popFrame(); } md.visitJumpInsn(GOTO,exitLabel); Label[] catchLabelsOfCatch = catchContextOfCatch.getCatchLabels(); String type = asmType(s.catchVar.getType()).getInternalName(); for(int j=0;j<catchLabelsOfTry.length;j+=2) { md.visitTryCatchBlock(catchLabelsOfTry[j],catchLabelsOfTry[j+1],catchStartLabel,type); } if (hasFinallyStmt) { for(int j=0;j<catchLabelsOfCatch.length;j+=2) { md.visitTryCatchBlock(catchLabelsOfCatch[j],catchLabelsOfCatch[j+1],finallyStartLabel,null); } } } } if(hasFinallyStmt){//any exception handler for(int i=0;i<catchLabelsOfTry.length-1;i+=2) { md.visitTryCatchBlock(catchLabelsOfTry[i],catchLabelsOfTry[i+1],finallyStartLabel,null); } this.newFrame(); md.visitLabel(finallyStartLabel); int exVarId = this.declareNewVar(Types.getRootType()); md.visitVarInsn(ASTORE,exVarId); visit(finallyStmt); md.visitVarInsn(ALOAD,exVarId); md.visitInsn(ATHROW); this.popFrame(); } md.visitLabel(exitLabel); md.visitInsn(NOP); return null; } @Override public Object visitCatchBlock(CatchBlock node) { visit(node.catchVar); int exVarId = getVarId(node.catchVar); md.visitVarInsn(ASTORE, exVarId); visit(node.execStmt); return null; } @Override public Object visitThrowStmt(ThrowStmt node) { visit(node.expr); md.visitInsn(ATHROW); return null; } private void assignVarObject(VarObject to,ExprNode from){ visit(from); int vid = getVarId(to); md.visitVarInsn(getOpcode(to.getType(),ISTORE), vid); } private void assignField(FieldNode fn,ExprNode target, ExprNode from, int valueVar){ int opc = PUTFIELD; if (AstUtil.isStatic(fn.modifier)) { opc = PUTSTATIC; } else { visit(target); } visit(from); dupX(from.getType()); md.visitVarInsn(getOpcode(from.getType(),ISTORE), valueVar); md.visitFieldInsn(opc, asmType(Types.getClassType(fn.getClassNode())).getInternalName(), fn.getName(), getTypeDescriptor(fn.getType())); } private void assignField(FieldExpr fieldExpr,ExprNode from, int valueVar){ if(fieldExpr instanceof StaticFieldExpr){ assignField(fieldExpr.getField().getFieldNode(), null, from, valueVar); }else if(fieldExpr instanceof ObjectFieldExpr){ assignField(fieldExpr.getField().getFieldNode(), ((ObjectFieldExpr) fieldExpr).getTarget(), from, valueVar); }else{ throw new UnsupportedOperationException(); } } private void astore(ExprNode expr){ visit(expr); org.objectweb.asm.Type type = asmType(expr.getType()); md.visitInsn(type.getOpcode(IASTORE)); } private void assignArrayElement(ExprNode array,ExprNode key,ExprNode from, int valueVar){ Parameters.requireNonNull(array); Parameters.requireNonNull(key); visit(array); visit(key); visit(from); dupX(from.getType()); md.visitVarInsn(getOpcode(from.getType(), ISTORE), valueVar); ArrayType arrayType = (ArrayType) array.getType(); md.visitInsn(getOpcode(arrayType.getComponentType(),IASTORE)); } @Override public Object visitAssignExpr(AssignExpr node) { ExprNode from = node.getFrom(); AssignableExpr to = node.getTo(); int valueVar; if (to instanceof FieldExpr) { valueVar = declareNewVar(from.getType()); assignField((FieldExpr) to, from, valueVar); } else if (to instanceof VarExpr) { LocalVarNode toVar = ((VarExpr) to).getVar(); assignVarObject(toVar, from); valueVar = getVarId(toVar); } else if (to instanceof ElementExpr) { ElementExpr elementExpr = (ElementExpr) to; valueVar = declareNewVar(from.getType()); assignArrayElement(elementExpr.getArrayExpr(), elementExpr.getIndex(), from, valueVar); } else if (to instanceof ParameterExpr) { ParameterNode toParam = ((ParameterExpr) to).getParameter(); assignVarObject(toParam, from); valueVar = getVarId(toParam); } else { throw new UnknownError("unknown expression:" + to); } md.visitVarInsn(getOpcode(from.getType(),ILOAD), valueVar); return null; } @Override public Object visitBinaryExpr(BinaryExpr node) { ExprNode e1 = node.getExpr1(); ExprNode e2 = node.getExpr2(); switch (node.getOperation()){ case BinaryExpr.OP_SHIFT_LEFT: case BinaryExpr.OP_SHIFT_RIGHT: case BinaryExpr.OP_UNSIGNED_SHIFT_RIGHT: break; default: int type1 = getT(e1.getType()); int type2 = getT(e2.getType()); if (type1 != type2) { throw new IllegalArgumentException(String.format("invalid types:%s and %s",type1,type2)); } } int op; org.objectweb.asm.Type at = asmType(node.getExpr1().getType()); switch(node.getOperation()){ case "+": op = IADD;break; case "-" : op = ISUB;break; case "*" : op = IMUL;break; case "/" : op = IDIV;break; case "%":op = IREM;break; //bitwise case BinaryExpr.OP_AND:op = IAND;break; case BinaryExpr.OP_OR:op = IOR;break; case BinaryExpr.OP_XOR: op = IXOR;break; case BinaryExpr.OP_SHIFT_LEFT:op = ISHL;break; case BinaryExpr.OP_SHIFT_RIGHT:op = ISHR;break; case BinaryExpr.OP_UNSIGNED_SHIFT_RIGHT: op = IUSHR;break; default://logic expression Label trueLabel = new Label(); Label stopLabel = new Label(); ifExpr(true,node, trueLabel); constFalse(); md.visitJumpInsn(GOTO, stopLabel); md.visitLabel(trueLabel); constTrue(); md.visitLabel(stopLabel); return null; } visit(e1); visit(e2); md.visitInsn(at.getOpcode(op)); return null; } protected Object getJavaConst(ConstExpr ce){ Object v = ce.getValue(); if(v==null){ return null; }else if(v instanceof Type){ return asmType((Type)v); }else{ Type ct = ce.getType(); if( Types.isNumber(ct) || Types.isBoolean(ct) || Types.isCharType(ct) || ct.equals(Types.getCharClassType()) || ct.equals(Types.getStringClassType()) ){ return ce.getValue(); } throw Exceptions.unsupportedTypeException(ct); } } @Override public Object visitConstExpr(ConstExpr node) { Object v = getJavaConst(node); if(v==null){ md.visitInsn(ACONST_NULL); }else{ md.visitLdcInsn(v); } return null; } @Override public Object visitElementExpr(ElementExpr node) { visit(node.getArrayExpr()); visit(node.getIndex()); org.objectweb.asm.Type t = asmType(node.getType()); md.visitInsn(t.getOpcode(IALOAD)); return null; } @Override public Object visitFieldExpr(FieldExpr node) { int opc ; String owner = internalName(node.getField().getFieldNode().getClassNode()); if(node instanceof ObjectFieldExpr){ ExprNode target =((ObjectFieldExpr)node).getTarget(); visit(target); opc = GETFIELD; }else if(node instanceof StaticFieldExpr){ opc = GETSTATIC; }else{ throw new UnsupportedOperationException("unsupported field type:" + node); } md.visitFieldInsn(opc ,owner , node.getField().getName() ,getTypeDescriptor(node.getType())); return null; } @Override public Object visitInvocationExpr(InvocationExpr node) { int opc; MethodDescriptor method = node.getMethod(); String ownerClass;// = internalName(node.getMethod().classNode); if (node instanceof StaticInvokeExpr) { opc = INVOKESTATIC; ownerClass = internalName(((StaticInvokeExpr) node).getInvokeClass().getReferencedClassNode()); } else if(node instanceof ObjectInvokeExpr) { ObjectInvokeExpr oie = (ObjectInvokeExpr) node; ObjectType targetType = (ObjectType) oie.getInvokeTarget().getType(); ownerClass = internalName(targetType); ExprNode target = oie.getInvokeTarget(); visit(target); if (Modifier.isPrivate(method.getModifier()) || (target instanceof SuperExpr) || method.getName().equals("<init>")) { opc = INVOKESPECIAL; } else { opc = ModifierUtil.isInterface(targetType.getClassNode().modifier) ? INVOKEINTERFACE : INVOKEVIRTUAL; } }else{ throw Exceptions.unsupportedTypeException(node); } visitAll(node.getArguments()); md.visitMethodInsn( opc ,ownerClass ,method.getName() ,getMethodDescriptor(method.getMethodNode()) ); String expectedReturnType = internalName(method.getReturnType()); String actualReturnType = internalName(method.getMethodNode().getType()); if (!expectedReturnType.equals(actualReturnType)) { md.visitTypeInsn(CHECKCAST,expectedReturnType); } return null; } @Override public Object visitUnaryExpr(UnaryExpr node) { Type exprType = node.getExpr().getType(); org.objectweb.asm.Type t = asmType(exprType); visit(node.getExpr()); switch(node.getOperation()){ case UnaryExpr.OPERATION_POS: break; case UnaryExpr.OPERATION_NEG: md.visitInsn(t.getOpcode(INEG)); break; case UnaryExpr.OPERATION_NOT: //TODO here I am not sure constX(exprType, -1); md.visitInsn(t.getOpcode(IXOR)); break; //md.visitInsn(ICONST_M1); case UnaryExpr.OPERATION_LOGIC_NOT: Label falseLabel = new Label(); Label stopLabel = new Label(); md.visitJumpInsn(IFEQ, falseLabel); constFalse(); md.visitJumpInsn(GOTO, stopLabel); md.visitLabel(falseLabel); constTrue(); md.visitLabel(stopLabel); break; default: throw new UnsupportedOperationException("unsupported unary operation:" + node.getOperation()); } return null; } @Override public Object visitVarExpr(VarExpr node) { visitVarObject(node.getVar()); return null; } @Override public Object visitParameterExpr(ParameterExpr node) { visitVarObject(node.getParameter()); return null; } @Override public Object visitCastExpr(CastExpr node) { visit(node.getExpr()); md.visitTypeInsn(CHECKCAST, internalName(node.getToType())); return null; } @Override public Object visitNewArrayExpr(NewArrayExpr node) { ExprNode[] sizes = node.getSizes(); visitAll(sizes); Type ct = node.getComponentType(); if (sizes.length < 1) { throw new IllegalArgumentException("illegal sizes length " + sizes); } if (sizes.length == 1) { int opr = -1; int op = NEWARRAY; if(ct.equals(BOOLEAN_TYPE)){ opr = T_BOOLEAN; }else if(ct.equals(CHAR_TYPE)){ opr = T_CHAR; }else if(ct.equals(SHORT_TYPE)){ opr = T_SHORT; }else if(ct.equals(INT_TYPE)){ opr = T_INT; }else if(ct.equals(LONG_TYPE)){ opr = T_LONG; }else if(ct.equals(FLOAT_TYPE)){ opr = T_FLOAT; }else if(ct.equals(DOUBLE_TYPE)){ opr = T_DOUBLE; }else if(ct.equals(BYTE_TYPE)){ opr = T_BYTE; }else{ op = ANEWARRAY; } if(op == NEWARRAY){ md.visitIntInsn(op, opr); }else{ md.visitTypeInsn(ANEWARRAY, internalName(ct)); } } else { md.visitMultiANewArrayInsn(getTypeDescriptor(node.getType()), sizes.length); } return null; } @Override public Object visitThisExpr(ThisExpr node) { md.visitVarInsn(ALOAD, 0); return null; } @Override public Object visitMultiStmtExpr(MultiStmtExpr node) { visitAll(node.getStatements()); visit(node.reference); return null; } private String getTypeDescriptor(Type[] types){ if(types==null) return null; if(types.length==0) return null; StringBuilder ts = new StringBuilder(); for(Type t:types){ ts.append(getTypeDescriptor(t)); } return ts.toString(); } private String getTypeDescriptor(Type t){ if(t instanceof PrimitiveType){ if(t.equals(VOID_TYPE)){ return "V"; }else if(t.equals(BOOLEAN_TYPE)){ return "Z"; }else if(t.equals(LONG_TYPE)){ return "J"; }else if(t.equals(INT_TYPE)){ return "I"; }else if(t.equals(CHAR_TYPE)){ return "C"; }else if(t.equals(SHORT_TYPE)){ return "S"; }else if(t.equals(BYTE_TYPE)){ return "B"; }else if(t.equals(FLOAT_TYPE)){ return "F"; }else if(t.equals(DOUBLE_TYPE)){ return "D"; }else if(t.equals(NULL_TYPE)){ return "Ljava/lang/Object;"; }else{ throw Exceptions.unsupportedTypeException(t); } }else if(t instanceof ArrayType){ return "[" + getTypeDescriptor(((ArrayType)t).getComponentType()); }else if(t instanceof GenericType){ GenericType gt = (GenericType) t; ObjectType st = gt.getSuperType(); ObjectType[] itfs = gt.getInterfaces(); if (itfs.length == 1 && st != null && st.isAssignableFrom(itfs[0])) { st = itfs[0]; } return getTypeDescriptor(st); }else if(t instanceof ClassType){ return "L" + internalName(((ClassType) t).getClassNode().name) + ";"; }else if(t instanceof WildcardType){ return getTypeDescriptor(((WildcardType) t).getSuperType()); }else{ throw Exceptions.unsupportedTypeException(t); } } private String getClassDescriptor(String className){ return "L" + internalName(className) + ";" ; } private String getMethodDescriptor(Type returnType,Type[] parameterTypes){ StringBuilder desc = new StringBuilder(); String retTyp = getTypeDescriptor(returnType); if(parameterTypes!=null){ for(Type t:parameterTypes){ desc.append(getTypeDescriptor(t)); } } return "(" + desc + ")" + retTyp; } private String getMethodDescriptor(MethodNode node) { return getMethodDescriptor(node.getType(), MethodUtil.getParameterTypes(node)); } private org.objectweb.asm.Type asmType(Type type){ String typeDesc = getTypeDescriptor(type); return org.objectweb.asm.Type.getType(typeDesc); } private int getVarId(VarObject var) { Integer vid = varIds.get(var); if(vid==null){ throw new UnknownError("unknown var:" + var); } return vid; } private void visitVarObject(VarObject vo){ org.objectweb.asm.Type type = asmType(vo.getType()); int vid = getVarId(vo); md.visitVarInsn(type.getOpcode(ILOAD),vid); } @Nonnull private String[] internalName(@Nonnull ClassNode[] clazz){ String[] names = new String[clazz.length]; for(int i=0;i<clazz.length;i++){ names[i] = internalName(clazz[i]); } return names; } private String internalName(ClassNode clazz){ return internalName(Types.getClassType(clazz)); } private String internalName(Type t) { org.objectweb.asm.Type asmType = asmType(t); Objects.requireNonNull(asmType, "couldn't get asm type for " + t); try{ return asmType.getInternalName(); }catch(Exception ex){ throw new RuntimeException("couldn't get asm type for " + t); } } private String[] internalName(Type[] types){ String[] ts = new String[types.length]; for(int i=0;i<types.length;i++){ ts[i] = internalName(types[i]); } return ts; } @Override public void generate(ClassNode classNode){ try { visitClassNode(classNode); } catch (CompileException | MalformedAstException ex) { throw ex; } catch (Exception ex) { throw new CodeGenerationException("fail to generate class:" + classNode.name, classNode, ex); } } @Override public Object visitVarDeclStmt(VarDeclStmt node) { return visitChildren(node); } private void primitiveCast(Type fromType,Type toType){ if ((fromType instanceof PrimitiveType) && (toType instanceof PrimitiveType)) { String fn = fromType.getName(); String tn = toType.getName(); if (BYTE_NAME.equals(tn)) { switch (fn){ case DOUBLE_NAME: case LONG_NAME: case FLOAT_NAME: primitiveCast(fromType,INT_TYPE); case INT_NAME: case SHORT_NAME: case CHAR_NAME: md.visitInsn(I2B); return; } } else if (CHAR_NAME.equals(tn)) { switch (fn){ case DOUBLE_NAME: case LONG_NAME: case FLOAT_NAME: primitiveCast(fromType,INT_TYPE); case INT_NAME: case SHORT_NAME: case BYTE_NAME: md.visitInsn(I2C); return; } } else if (SHORT_NAME.equals(tn)) { switch (fn) { case LONG_NAME: case FLOAT_NAME: case DOUBLE_NAME: primitiveCast(fromType,INT_TYPE); case INT_NAME: case CHAR_NAME: case BYTE_NAME: md.visitInsn(I2S); return; } } else if (INT_NAME.equals(tn)) { switch (fn) { case BYTE_NAME: case CHAR_NAME: case SHORT_NAME: return; case FLOAT_NAME: md.visitInsn(F2I); return; case LONG_NAME: md.visitInsn(L2I); return; case DOUBLE_NAME: md.visitInsn(D2I); return; } } else if (FLOAT_NAME.equals(tn)) { switch (fn) { case BYTE_NAME: case CHAR_NAME: case SHORT_NAME: case INT_NAME: md.visitInsn(I2F); return; case LONG_NAME: md.visitInsn(L2F); return; case DOUBLE_NAME: md.visitInsn(D2F); return; } } else if (LONG_NAME.equals(tn)) { switch (fn) { case BYTE_NAME: case CHAR_NAME: case SHORT_NAME: case INT_NAME: md.visitInsn(I2L); return; case FLOAT_NAME: md.visitInsn(F2L); return; case DOUBLE_NAME: md.visitInsn(D2L); return; } } else if (DOUBLE_NAME.equals(tn)) { switch (fn) { case BYTE_NAME: case CHAR_NAME: case SHORT_NAME: case INT_NAME: md.visitInsn(I2D); return; case LONG_NAME: md.visitInsn(L2D); return; case FLOAT_NAME: md.visitInsn(F2D); return; } } } throw Exceptions.unexpectedException("It is unable to cast " + fromType + " to " + toType); } @Override public Object visitPrimitiveCastExpr(PrimitiveCastExpr node) { ExprNode expr = node.getExpr(); visit(expr); Type ft = expr.getType(); Type tt = node.getToType(); primitiveCast(ft, tt); return null; } @Override public Object visitLocalVarNode(LocalVarNode localVarNode) { this.declareNewVar(localVarNode); return null; } @Override public Object visitParameterNode(ParameterNode parameterNode) { md.visitParameter(parameterNode.getName(), parameterNode.modifier); this.declareNewVar(parameterNode); return null; } @Override public Object visitFieldNode(FieldNode fieldNode) { classWriter.visitField(fieldNode.modifier, fieldNode.getName(), getTypeDescriptor(fieldNode.getType()), null, null); return null; } @Override public Object visitNewObjectExpr(NewObjectExpr node) { org.objectweb.asm.Type t = asmType(node.getObjectType()); md.visitTypeInsn(NEW, t.getInternalName()); md.visitInsn(DUP); visitAll(node.getConstructor().getArguments()); md.visitMethodInsn( INVOKESPECIAL , t.getInternalName() , "<init>" ,getMethodDescriptor(node.getConstructor().getMethod().getMethodNode()) , false); return null; } private void dupX(Type type){ int size = asmType(type).getSize(); if(size==1) md.visitInsn(DUP); else if(size==2) md.visitInsn(DUP2); else throw new UnsupportedOperationException("unsupported type:" + type); } private ConstExpr getConstX(Type type, int i) { Object obj; int t = getT(type); switch (t) { case T_I: obj = i; break; case T_L: obj = (long) i; break; case T_F: obj = (float) i; break; case T_D: obj = (double) i; break; default: throw new UnsupportedOperationException("unsupported type:" + type); } return new ConstExpr(obj); } private void constX(Object x){ md.visitLdcInsn(x); } private void constX(Type type,int i) { visitConstExpr(getConstX(type, i)); } @Override public Object visit(AstNode node) { int lineNum = node.offset.startLine; if(lineNum>0 && (node instanceof Statement || node instanceof ExprNode) && !lineLabels.containsKey(lineNum)){ Label lb = new Label(); md.visitLabel(lb); md.visitLineNumber(lineNum, lb); lineLabels.put(lineNum, lb); } return super.visit(node); } @Override public Object visitArrayLengthExpr(ArrayLengthExpr node) { visit(node.getArrayExpr()); md.visitInsn(ARRAYLENGTH); return null; } private void constTrue(){ constX(1); } private void constFalse(){ constX(0); } @Override public Object visitUnknownFieldExpr(UnknownFieldExpr node) { throw new UnsupportedOperationException("BUG:invoking unknown method:" + node.getFieldName()); } @Override public Object visitUnknownInvocationExpr(UnknownInvocationExpr node) { throw new UnsupportedOperationException("BUG:invoking unknown method:" + node.getMethodName()); } @Override public Object visitClassReference(ClassReference node) { //do nothing return null; } @Override public Object visitSuperExpr(SuperExpr node) { md.visitVarInsn(ALOAD, 0); return null; } @Override public Object visitErrorousExpr(ErrorousExpr node) { throw new UnsupportedOperationException("Not supported yet."); } @Override public Object visitInstanceOfExpr(InstanceOfExpr node) { visit(node.getExpr()); md.visitTypeInsn(INSTANCEOF, internalName(node.getTarget().getReferencedClassNode())); return null; } private void ifCompare(boolean jumpOnTrue,ExprNode expr1, ExprNode expr2, String op, Label label) { Type type = expr1.getType(); visit(expr1); visit(expr2); int t = getT(type); if(T_I == t){ int opc; switch(op){ case "==" : opc = jumpOnTrue ? IF_ICMPEQ : IF_ICMPNE; break; case ">" : opc =jumpOnTrue ? IF_ICMPGT : IF_ICMPLE; break; case ">=" : opc =jumpOnTrue ? IF_ICMPGE : IF_ICMPLT; break; case "<" : opc = jumpOnTrue ? IF_ICMPLT : IF_ICMPGE; break; case "<=" : opc =jumpOnTrue ? IF_ICMPLE : IF_ICMPGT; break; case "!=" : opc = jumpOnTrue ? IF_ICMPNE : IF_ICMPEQ; break; default: throw new UnsupportedOperationException("Unsupported operation:" + op); } md.visitJumpInsn(opc, label); }else if(T_A==t){//object type if(op.equals("==")){ md.visitJumpInsn(jumpOnTrue ? IF_ACMPEQ : IF_ACMPNE,label); }else if(op.equals("!=")){ md.visitJumpInsn(jumpOnTrue ? IF_ACMPNE:IF_ACMPEQ,label); }else{ throw new UnsupportedOperationException("It is unsupported to compare object type:" + type); } }else{//type is not int,not object if(T_L==t){ md.visitInsn(LCMP); }else if(T_F==t){ md.visitInsn(FCMPL); }else if(T_D==t){ md.visitInsn(DCMPL); }else{ throw new UnsupportedOperationException("It is unsupported to compare object type:" + type); } int opc; switch(op){ case "==" : opc =jumpOnTrue ? IFEQ : IFNE;break; case ">" : opc =jumpOnTrue ? IFGT : IFLE ;break; case ">=" : opc =jumpOnTrue ? IFGE : IFLT ;break; case "<" : opc =jumpOnTrue ? IFLT:IFGE;break; case "<=" : opc =jumpOnTrue ? IFLE:IFGT;break; case "!=" : opc =jumpOnTrue ? IFNE:IFEQ;break; default: throw new UnsupportedOperationException("Unsupported operation:" + op); } md.visitJumpInsn(opc, label); } } @Override public Object visitMultiStmt(MultiStmt node) { visitAll(node.statements); return null; } @Override public Object visitLambdaExpr(LambdaExpr node) { MethodNode invokeMethod = node.getInvokeMethod(); boolean isStatic = ModifierUtil.isStatic(invokeMethod.getModifier()); if (!isStatic) { md.visitVarInsn(ALOAD, 0); } for (ExprNode arg: node.getCaptureArguments()) { visit(arg); } MethodDescriptor interfaceMd = node.getInterfaceMethod(); List<Type> invokeTypes = new LinkedList<>(); if (!isStatic){ invokeTypes.add(Types.getClassType(invokeMethod.getClassNode())); } for (ExprNode arg: node.getCaptureArguments()) { invokeTypes.add(arg.getType()); } String invokeMdDesc = getMethodDescriptor(Types.getClassType(interfaceMd.getMethodNode().getClassNode()), invokeTypes.toArray(new Type[0])); String mdDesc = getMethodDescriptor(interfaceMd.getReturnType(), interfaceMd.getParameterTypes()); String metafactoryDesc = org.objectweb.asm.Type.getMethodDescriptor( org.objectweb.asm.Type.getType(CallSite.class) , org.objectweb.asm.Type.getType(MethodHandles.Lookup.class) , org.objectweb.asm.Type.getType(String.class) , org.objectweb.asm.Type.getType(MethodType.class) , org.objectweb.asm.Type.getType(MethodType.class) , org.objectweb.asm.Type.getType(MethodHandle.class) , org.objectweb.asm.Type.getType(MethodType.class) ); int invokeTag = isStatic ? H_INVOKESTATIC : H_INVOKESPECIAL; Object[] bootstrapArgs = new Object[] { org.objectweb.asm.Type.getMethodType(getMethodDescriptor(interfaceMd.getMethodNode())) , new Handle(invokeTag, internalName(invokeMethod.getClassNode()), invokeMethod.getName(), getMethodDescriptor(invokeMethod), false) , org.objectweb.asm.Type.getMethodType(mdDesc) }; Handle bootstrapMd = new Handle(H_INVOKESTATIC, internalName(LambdaMetafactory.class.getName()), "metafactory", metafactoryDesc, false); md.visitInvokeDynamicInsn(interfaceMd.getName(), invokeMdDesc, bootstrapMd, bootstrapArgs); return null; } private void createInterfaceBridgeMethodIfNeed(MethodNode interfaceMethod,MethodNode implementMethod) { String desc = getMethodDescriptor(interfaceMethod); String implementDesc = getMethodDescriptor(implementMethod); if (desc.equals(implementDesc)) { return; } int access = interfaceMethod.getModifier() & ~Modifier.ABSTRACT; String name = interfaceMethod.getName(); MethodVisitor methodVisitor = classWriter.visitMethod(access, name, desc, methodSignature(interfaceMethod), null); ParameterNode[] params = interfaceMethod.getParameters(); for(ParameterNode p : params) { methodVisitor.visitParameter(p.getName(),p.modifier); } ParameterNode[] implementedParams = implementMethod.getParameters(); methodVisitor.visitVarInsn(ALOAD,0); int varIdx = 1; for(int i=0;i<params.length;i++) { Type implementedParamType = implementedParams[i].getType(); Type interfaceParamType = params[i].getType(); org.objectweb.asm.Type interfaceParamAsmType = asmType(interfaceParamType); methodVisitor.visitVarInsn(interfaceParamAsmType.getOpcode(ILOAD),varIdx); if (!implementedParamType.isAssignableFrom(interfaceParamType)) { methodVisitor.visitTypeInsn(CHECKCAST,internalName(implementedParamType)); } varIdx += interfaceParamAsmType.getSize(); } String owner = internalName(implementMethod.getClassNode()); methodVisitor.visitMethodInsn(INVOKEVIRTUAL,owner,implementMethod.getName(),implementDesc,false); Type returnType = interfaceMethod.getType(); if (VOID_TYPE.equals(returnType)) { methodVisitor.visitInsn(RETURN); } else { methodVisitor.visitInsn(asmType(returnType).getOpcode(IRETURN)); } methodVisitor.visitMaxs(0,0); methodVisitor.visitEnd(); } private int getOpcode(Type type, int opcode) { return asmType(type).getOpcode(opcode); } private static class KlClassWriter extends ClassWriter { private AstLoader astLoader; public KlClassWriter(int flags, AstLoader astLoader) { super(flags); this.astLoader = astLoader; } @Override protected String getCommonSuperClass(String type1, String type2) { ClassNode cn1; try { cn1 = astLoader.loadAst(type1.replace('/', '.')); } catch (AstNotFoundException e) { throw new TypeNotPresentException(type1, e); } ClassNode cn2; try { cn2 = astLoader.loadAst(type2.replace('/', '.')); } catch (AstNotFoundException e) { throw new TypeNotPresentException(type2, e); } ObjectType t1 = getClassType(cn1); ObjectType t2 = getClassType(cn2); if (t1.isAssignableFrom(t2)) { return type1; } if (t2.isAssignableFrom(t1)) { return type2; } if (ModifierUtil.isInterface(cn1.modifier) || ModifierUtil.isInterface(cn2.modifier)) { return "java/lang/Object"; } else { do { t1 = t1.getSuperType(); } while (!t1.isAssignableFrom(t2)); return t1.getName().replace('.', '/'); } } } }
package mx.infotec.dads.kukulkan.util; import static mx.infotec.dads.kukulkan.util.JavaFileNameParser.formatToPackageStatement; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.metamodel.DataContext; import org.apache.metamodel.schema.Column; import org.apache.metamodel.schema.Table; import mx.infotec.dads.kukulkan.engine.domain.core.DataModelElement; import mx.infotec.dads.kukulkan.engine.domain.core.DataModelGroup; import mx.infotec.dads.kukulkan.engine.domain.core.JavaProperty; import mx.infotec.dads.kukulkan.engine.domain.core.PrimaryKey; import mx.infotec.dads.kukulkan.engine.domain.core.ProjectConfiguration; import mx.infotec.dads.kukulkan.engine.service.layers.LayerTask; /** * DataMapping utility class * * @author Daniel Cortes Pichardo * */ public class DataMapping { private DataMapping() { } /** * Create a DataModelGroup Class * * @param dataContext * @return DataModelGroup */ public static DataModelGroup createDataModelGroup(DataContext dataContext, List<String> tablesToProcess) { DataModelGroup dmg = new DataModelGroup(); dmg.setName(""); dmg.setDescription("Default package"); dmg.setBriefDescription("Default package"); dmg.setDataModelElements(new ArrayList<>()); Table[] tables = dataContext.getDefaultSchema().getTables(); List<DataModelElement> dmeList = new ArrayList<>(); createDataModelElement(tablesToProcess, tables, dmeList); dmg.setDataModelElements(dmeList); return dmg; } private static void createDataModelElement(List<String> tablesToProcess, Table[] tables, List<DataModelElement> dmeList) { for (Table table : tables) { if ((tablesToProcess.contains(table.getName()) || tablesToProcess.isEmpty()) && hasPrimaryKey(table.getPrimaryKeys())) { DataModelElement dme = DataModelElement.createOrderedDataModel(); String singularName = InflectorProcessor.getInstance().singularize(table.getName()); dme.setTableName(table.getName()); dme.setName(SchemaPropertiesParser.parseToClassName(singularName)); dme.setPropertyName(SchemaPropertiesParser.parseToPropertyName(singularName)); extractPrimaryKey(dme, singularName, table.getPrimaryKeys()); extractProperties(dme, table); dmeList.add(dme); } } } public static void extractPrimaryKey(DataModelElement dme, String singularName, Column[] columns) { dme.setPrimaryKey(mapPrimaryKeyElements(singularName, columns)); if (!dme.getPrimaryKey().isComposed()) { if(dme.getPrimaryKey().getQualifiedLabel().equals("java.lang.Double")){ dme.getPrimaryKey().setQualifiedLabel("java.lang.Long"); dme.getPrimaryKey().setType("Double"); } dme.getImports().add(dme.getPrimaryKey().getQualifiedLabel()); } } public static void extractProperties(DataModelElement dme, Table table) { Column[] columns = table.getColumns(); for (Column column : columns) { if (!column.isPrimaryKey()) { String propertyName = SchemaPropertiesParser.parseToPropertyName(column.getName()); String propertyType = column.getType().getJavaEquivalentClass().getSimpleName(); String qualifiedName = column.getType().getJavaEquivalentClass().getCanonicalName(); if ("Blob".equals(propertyType) || "Clob".equals(propertyType)) { propertyType = "byte[]"; } else { dme.getImports().add(qualifiedName); } dme.addProperty(JavaProperty.builder().withPropertyName(propertyName).withPropertyType(propertyType) .withColumnName(column.getName()).withColumnType(column.getNativeType()) .withQualifiedName(qualifiedName).isNullable(column.isNullable()).isPrimaryKey(false) .isIndexed(column.isIndexed()).build()); } } } public static boolean hasPrimaryKey(Column[] columns) { return columns.length == 0 ? false : true; } public static PrimaryKey mapPrimaryKeyElements(String singularName, Column[] columns) { PrimaryKey pk = PrimaryKey.createOrderedDataModel(); // Not found primary key if (columns.length == 0) { return null; } // Simple Primary key if (columns.length == 1) { pk.setType(columns[0].getType().getJavaEquivalentClass().getSimpleName()); pk.setName(SchemaPropertiesParser.parseToPropertyName(columns[0].getName())); pk.setQualifiedLabel(columns[0].getType().getJavaEquivalentClass().getCanonicalName()); pk.setComposed(false); } else { // Composed Primary key pk.setType(SchemaPropertiesParser.parseToClassName(singularName) + "PK"); pk.setName(SchemaPropertiesParser.parseToPropertyName(singularName) + "PK"); pk.setComposed(true); for (Column columnElement : columns) { String propertyName = SchemaPropertiesParser.parseToPropertyName(columnElement.getName()); String propertyType = columnElement.getType().getJavaEquivalentClass().getSimpleName(); String qualifiedLabel = columnElement.getType().getJavaEquivalentClass().toString(); pk.addProperty(JavaProperty.builder().withPropertyName(propertyName).withPropertyType(propertyType) .withColumnName(columnElement.getName()).withColumnType(columnElement.getNativeType()) .withQualifiedName(qualifiedLabel).isNullable(columnElement.isNullable()).isPrimaryKey(true) .isIndexed(columnElement.isIndexed()).build()); } } return pk; } /** * Create a List of DataModelGroup into a single group from a DataContext * Element * * @param dataContext * @return */ public static List<DataModelGroup> createSingleDataModelGroupList(DataContext dataContext, List<String> tablesToProcess) { List<DataModelGroup> dataModelGroupList = new ArrayList<>(); dataModelGroupList.add(createDataModelGroup(dataContext, tablesToProcess)); return dataModelGroupList; } public static List<LayerTask> createLaterTaskList(Map<String, LayerTask> map, ArchetypeType archetype) { List<LayerTask> layerTaskList = new ArrayList<>(); for (Map.Entry<String, LayerTask> layerTaskEntry : map.entrySet()) { if (layerTaskEntry.getValue().getArchetypeType().equals(archetype)) { layerTaskList.add(layerTaskEntry.getValue()); } } return layerTaskList; } public void mapCommonProperties(ProjectConfiguration pConf, Map<String, Object> model, DataModelElement dmElement, String basePackage) { model.put("package", formatToPackageStatement(basePackage, pConf.getWebLayerName())); model.put("propertyName", dmElement.getPropertyName()); model.put("name", dmElement.getName()); model.put("id", "Long"); } }
package my.ostrea.blog.controllers; import my.ostrea.blog.exceptions.ArticleNotFoundException; import my.ostrea.blog.exceptions.CantDeleteNotYoursArticlesException; import my.ostrea.blog.exceptions.CantEditNotYoursArticlesException; import my.ostrea.blog.models.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import java.util.Optional; @Controller @RequestMapping("/") public class BaseController { private final UserRepository userRepository; private final ArticleRepository articleRepository; private Long editedArticleId; private String editedArticleAuthor; @Autowired public BaseController(UserRepository userRepository, ArticleRepository articleRepository) { this.userRepository = userRepository; this.articleRepository = articleRepository; } /** * Handles '/' * @param model model to which add attributes * @return view name */ @RequestMapping public String index(Model model) { if (!SecurityContextHolder.getContext().getAuthentication().getName().equals("anonymousUser")) { getUserFromDbAndAddHisInfoToThePage(model, SecurityContextHolder.getContext().getAuthentication().getName()); } return "index"; } private void getUserFromDbAndAddHisInfoToThePage(Model model, String username) { Optional<MyUser> userFromDb = userRepository .findByUsername(username); userFromDb.map(user -> model.addAttribute("articles", user.getArticles())); } @RequestMapping("/administrator_control_panel") public String administratorControlPanel() { return "administrator_control_panel"; } @RequestMapping("/{username}") public String showUsersArticles(Model model, @PathVariable String username) { String currentlyLoggedUser = SecurityContextHolder.getContext().getAuthentication().getName(); if (currentlyLoggedUser.equals(username)) { return "redirect:/"; } getUserFromDbAndAddHisInfoToThePage(model, username); return "index"; } @RequestMapping("/delete_article") public String deleteArticle(@RequestParam("article_id") Long articleId) { Optional<Article> articleFromDb = Optional.ofNullable(articleRepository.findOne(articleId)); articleFromDb.map(article -> { if (article.getAuthor().getUsername() .equals(SecurityContextHolder.getContext().getAuthentication().getName())) { articleRepository.delete(article); } else { throw new CantDeleteNotYoursArticlesException(); } return Optional.of(article); }).orElseThrow(ArticleNotFoundException::new); Optional<String> username = articleFromDb.map(Article::getAuthor).map(MyUser::getUsername); if (username.isPresent()) { return "redirect:" + username.get(); } else { throw new RuntimeException("Something went completely wrong!"); } } @RequestMapping(value = "/create_article", method = RequestMethod.GET) public String createArticle(Model model) { model.addAttribute("articleDto", new ArticleDto()); return "create_article"; } @RequestMapping(value = "/create_article", method = RequestMethod.POST) public String createArticle(Model model, @ModelAttribute ArticleDto article) { boolean errors = false; if (article.getTitle().length() > 255) { errors = true; model.addAttribute("titleError", true); } if (article.getContent().length() > 255) { errors = true; model.addAttribute("contentError", true); } if (errors) { return "create_article"; } MyUser author = userRepository.findByUsername( SecurityContextHolder.getContext().getAuthentication().getName()).get(); Article articleForDb = new Article(article.getTitle(), article.getContent(), author); articleRepository.save(articleForDb); return "redirect:/"; } @RequestMapping(value = "/edit_article", method = RequestMethod.GET) public String editArticle(Model model, @RequestParam("article_id") Long articleId) { Optional<Article> articleFromDb = Optional.ofNullable(articleRepository.findOne(articleId)); articleFromDb.map(article -> { if (!article.getAuthor().getUsername() .equals(SecurityContextHolder.getContext().getAuthentication().getName())) { throw new CantEditNotYoursArticlesException(); } model.addAttribute("articleDto", new ArticleDto(article.getTitle(), article.getContent())); editedArticleAuthor = article.getAuthor().getUsername(); editedArticleId = articleId; return Optional.of(article); }).orElseThrow(ArticleNotFoundException::new); return "edit_article"; } @RequestMapping(value = "/edit_article", method = RequestMethod.POST) public String editArticle(Model model, @ModelAttribute ArticleDto article) { if (editedArticleId == null || editedArticleAuthor == null || !editedArticleAuthor.equals( SecurityContextHolder.getContext().getAuthentication().getName())) { throw new CantEditNotYoursArticlesException(); } boolean errors = false; if (article.getTitle().length() > 5) { errors = true; model.addAttribute("titleError", true); } if (article.getContent().length() > 5) { errors = true; model.addAttribute("contentError", true); } if (errors) { return "edit_article?article_id=" + editedArticleId; } MyUser author = userRepository.findByUsername( SecurityContextHolder.getContext().getAuthentication().getName()).get(); Article articleForDb = new Article(article.getTitle(), article.getContent(), author); articleForDb.setId(editedArticleId); articleRepository.save(articleForDb); editedArticleId = null; editedArticleAuthor = null; return "redirect:/"; } }
package net.iponweb.disthene.reader; /** * @author Andrei Ivanov */ public class Configuration { public static int PORT = 9080; public static String[] CASSANDRA_CPS = { "cassandra11.devops.iponweb.net", "cassandra12.devops.iponweb.net", "cassandra17.devops.iponweb.net", "cassandra18.devops.iponweb.net" }; public static String ES_CLUSTER_NAME = "cyanite"; public static String ES_INDEX = "cyanite_paths"; public static int ES_SCROLL_SIZE = 50000; public static int ES_TIMEOUT = 120000; public static String[] ES_NODES = { "es5.devops.iponweb.net", "es6.devops.iponweb.net", "es7.devops.iponweb.net", "es8.devops.iponweb.net" }; public static int ES_NATIVE_PORT = 9300; }
package net.openhft.chronicle.queue; import net.openhft.chronicle.bytes.Bytes; public interface BatchAppender { /** * @return the maximum number of messages that can be written directly to the off heap memory * before calling {@link net.openhft.chronicle.queue.BatchAppender#update(net.openhft.chronicle.bytes.Bytes, long, long)}, this is based on the indexing used. */ int rawMaxMessage(); /** * @return the maximum number of bytes that can be written directly to the off heap memory * before calling {@link net.openhft.chronicle.queue.BatchAppender#update(net.openhft.chronicle.bytes.Bytes, long, long)}, this is based on the block size used. */ int rawMaxBytes(); /** * @return the address of where to start to write a batch of messages to the off heap memory. */ long rawAddress(); /** * You should make this call at the end of each batch, in other words if the number of * messages in this batch is now equal to rawMaxMessage() or there is no sufficient space to * write any more data based on the rawMaxBytes(). You should also add the 4 byte length to * the size of each message. * * @param bytes the data to be written to the chronicle-queue * @param address the address of the last message written. * @param numberOfMessages the number of messages that where written in the last batch */ void update(Bytes bytes, long address, long numberOfMessages); }
package baseCode.util; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.StringReader; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.ArrayList; import baseCode.dataStructure.matrix.DoubleMatrixNamed; import cern.colt.list.DoubleArrayList; import cern.colt.matrix.DoubleMatrix2D; /** * Tools to help make regression testing easier, but also useful for other purposes. * * @author pavlidis * @version $Id$ */ public class RegressionTesting { private RegressionTesting() { /* block instantiation */ } // private String resourcePath = ""; /** * Test whether two AbstractNamedDoubleMatrix are 'close enough' to call equal. * * @param a * @param b * @param tolerance * @return try if all the values in both matrices are within 'tolerance' of each other. */ public static boolean closeEnough( DoubleMatrixNamed a, DoubleMatrixNamed b, double tolerance ) { if ( a.rows() != b.rows() || a.columns() != b.columns() ) return false; for ( int i = 0; i < a.rows(); i++ ) { for ( int j = 0; j < a.columns(); j++ ) { if ( Math.abs( a.getQuick( i, j ) - b.getQuick( i, j ) ) > tolerance ) return false; } } return true; } /** * @param a * @param b * @param tolerance */ public static boolean closeEnough( double[] a, double[] b, double tolerance ) { if ( a.length != b.length ) return false; for ( int i = 0; i < a.length; i++ ) { if ( Math.abs( a[i] - b[i] ) > tolerance ) return false; } return true; } /** * Test whether two DoubleArrayLists are 'close enough' to call equal. * * @param a * @param b * @param tolerance * @return */ public static boolean closeEnough( DoubleArrayList a, DoubleArrayList b, double tolerance ) { if ( a.size() != b.size() ) return false; for ( int i = 0; i < a.size(); i++ ) { if ( Math.abs( a.getQuick( i ) - b.getQuick( i ) ) > tolerance ) return false; } return true; } public static boolean closeEnough( DoubleMatrix2D a, DoubleMatrix2D b, double tolerance ) { if ( a.rows() != b.rows() || a.columns() != b.columns() ) return false; for ( int i = 0; i < a.rows(); i++ ) { for ( int j = 0; j < a.columns(); j++ ) { if ( Math.abs( a.getQuick( i, j ) - b.getQuick( i, j ) ) > tolerance ) return false; } } return true; } /** * Test whether two object arrays are the same. * * @param a * @param b * @return */ public static boolean closeEnough( Object[] a, Object[] b ) { if ( a.length != b.length ) { return false; } for ( int i = 0; i < a.length; i++ ) { if ( !a[i].equals( b[i] ) ) { return false; } } return true; } /** * Test whether two collections contain the same items. * * @param a * @param b * @return */ public static boolean containsSame( Collection a, Collection b ) { if ( a.size() != b.size() ) return false; if ( !a.containsAll( b ) ) return false; return true; } /** * Test whether two lists contain the same items in the <em>same</em> order * * @param a * @param b * @return */ public static boolean containsSame( List a, List b ) { if ( a.size() != b.size() ) return false; Iterator ita = a.iterator(); for ( Iterator iter = b.iterator(); iter.hasNext(); ) { Object elb = iter.next(); Object ela = ita.next(); if ( !ela.equals( elb ) ) { return false; } } return true; } /** * Test whether two double arrays contain the same items in any order (tolerance is ZERO) * * @param a * @param b * @return */ public static boolean containsSame( double[] a, double[] b ) { if ( a.length != b.length ) return false; ArrayList av = new ArrayList( a.length ); ArrayList bv = new ArrayList( b.length ); for ( int i = 0; i < b.length; i++ ) { av.add( new Double( a[i] ) ); bv.add( new Double( b[i] ) ); } return av.containsAll( bv ); } /** * Test whether two object arrays contain the same items in any order. The arrays are treated as Sets - repeats are * not considered. * * @param a * @param b * @return */ public static boolean containsSame( Object[] a, Object[] b ) { if ( a.length != b.length ) return false; ArrayList av = new ArrayList( a.length ); ArrayList bv = new ArrayList( b.length ); for ( int i = 0; i < b.length; i++ ) { av.add( a[i] ); bv.add( b[i] ); } return av.containsAll( bv ); } /** * @param istream * @return * @throws IOException */ public static String readTestResult( InputStream istream ) throws IOException { if ( istream == null ) { throw new IllegalStateException( "Null stream" ); } BufferedReader buf = new BufferedReader( new InputStreamReader( istream ) ); String line = ""; StringBuffer testOutput = new StringBuffer( line ); while ( ( line = buf.readLine() ) != null ) { testOutput.append( line + "\n" ); } buf.close(); return testOutput.toString(); } /** * @param resourceName * @return the contents of the resource as a String * @throws IOException */ public static String readTestResult( String resourceName ) throws IOException { InputStream istream = RegressionTesting.class.getResourceAsStream( resourceName ); if ( istream == null ) return null; String result = readTestResult( istream ); istream.close(); return result; } /** * @throws IOException * @param fileName - the full path of the file to be read. * @return */ public static String readTestResultFromFile( String fileName ) throws IOException { InputStream is = new FileInputStream( fileName ); return readTestResult( is ); } /** * Test whether two double arrays contain the same items in the same order * * @param a * @param b * @return */ public static boolean sameArray( int[] a, int[] b ) { if ( a.length != b.length ) return false; for ( int i = 0; i < b.length; i++ ) { if ( b[i] != a[i] ) return false; } return true; } public static void writeTestResult( String result, String fileName ) throws IOException { BufferedWriter buf = new BufferedWriter( new OutputStreamWriter( new FileOutputStream( new File( fileName ) ) ) ); BufferedReader resultBuf = new BufferedReader( new StringReader( result ) ); String line = null; while ( ( line = resultBuf.readLine() ) != null ) { buf.write( line + "\n" ); } buf.close(); resultBuf.close(); } /** * Convenience for using Stuart D. Gathman's Diff. * * @param expected String * @param actual String * @return String edit list */ /** * public static String regress( String expected, String actual ) { Diff diff = new Diff( new Object[] {expected} , * new Object[] {actual} ); Diff.change script = diff.diff_2( false ); DiffPrint.Base p = new * DiffPrint.UnifiedPrint( new Object[] {expected} , new Object[] {actual} ); StringWriter wtr = new StringWriter(); * p.setOutput( wtr ); p.print_script( script ); return wtr.toString(); } */ }