code
stringlengths
3
1.18M
language
stringclasses
1 value
/* * PluginTest.java * * Copyright (c) 2008, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.remote; import java.net.URI; import java.net.URISyntaxException; import java.util.Collection; import net.xeoh.plugins.base.Plugin; import net.xeoh.plugins.base.PluginManager; import net.xeoh.plugins.base.impl.PluginManagerFactory; import net.xeoh.plugins.remotediscovery.DiscoveredPlugin; import net.xeoh.plugins.remotediscovery.RemoteDiscovery; import net.xeoh.plugins.testplugins.testannotations.TestAnnotations; import org.junit.After; import org.junit.Before; import org.junit.Test; /** * @author rb * */ public class DirectDiscoveryTest { private PluginManager pm; /** * @throws Exception */ @Before public void setUp() throws Exception { this.pm = PluginManagerFactory.createPluginManager(); this.pm.addPluginsFrom(new URI("classpath://*")); } /** * @throws Exception */ @After public void tearDown() throws Exception { this.pm.shutdown(); } /** * @throws URISyntaxException * @throws InterruptedException */ @Test public void testDiscovery() throws URISyntaxException, InterruptedException { TestAnnotations p2 = this.pm.getPlugin(TestAnnotations.class); RemoteDiscovery p = this.pm.getPlugin(RemoteDiscovery.class); System.out.println(1); p.announcePlugin(p2, PublishMethod.ERMI, new URI("ermi://lala:123/Jojo")); System.out.println(2); Collection<DiscoveredPlugin> discover = p.discover(Plugin.class); System.out.println(3); for (DiscoveredPlugin dp : discover) { int distance = dp.getDistance(); System.out.println(dp.getPublishURI() + " " + distance); } } }
Java
/* * PluginTest.java * * Copyright (c) 2008, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.remote; import java.net.URI; import java.net.URISyntaxException; import junit.framework.Assert; import net.xeoh.plugins.base.Plugin; import net.xeoh.plugins.base.PluginManager; import net.xeoh.plugins.base.impl.PluginManagerFactory; import net.xeoh.plugins.base.util.JSPFProperties; import net.xeoh.plugins.testplugins.testannotations.TestAnnotations; import org.junit.After; import org.junit.Before; import org.junit.Test; /** * @author rb * */ public class DiscoverPluginTest { private PluginManager pm; /** * @throws Exception */ @Before public void setUp() throws Exception { final JSPFProperties props = new JSPFProperties(); props.setProperty(PluginManager.class, "cache.enabled", "false"); props.setProperty(PluginManager.class, "cache.file", "/tmp/xxxjspf.cache"); props.setProperty(PluginManager.class, "logging.level", "ALL"); this.pm = PluginManagerFactory.createPluginManager(props); this.pm.addPluginsFrom(new URI("classpath://*")); } /** * @throws Exception */ @After public void tearDown() throws Exception { this.pm.shutdown(); } /** * @throws URISyntaxException */ @Test public void testDiscovery() throws URISyntaxException { RemoteAPILipe p = this.pm.getPlugin(RemoteAPILipe.class); TestAnnotations p2 = this.pm.getPlugin(TestAnnotations.class); System.out.println("GO"); ExportResult exportPlugin = p.exportPlugin(p2); System.out.println("1"); Assert.assertNotNull(exportPlugin); System.out.println("2"); Plugin rp = p.getRemoteProxy(new URI("discover://nearest"), TestAnnotations.class); System.out.println(rp); Plugin remoteProxy = p.getRemoteProxy(new URI("discover://any"), Plugin.class); Assert.assertNotNull(remoteProxy); TestAnnotations remoteProxy2 = p.getRemoteProxy(new URI("discover://nearest"), TestAnnotations.class); Assert.assertNotNull(remoteProxy2); String injectionStatus = remoteProxy2.getInjectionStatus(); Assert.assertEquals(injectionStatus, "INJECTION OK"); System.out.println("YO"); Plugin youngest = p.getRemoteProxy(new URI("discover://youngest"), Plugin.class); Assert.assertNotNull(youngest); Plugin oldest = p.getRemoteProxy(new URI("discover://oldest"), Plugin.class); Assert.assertNotNull(oldest); } }
Java
/* * TestInitImpl.java * * Copyright (c) 2008, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.testplugins.testannotations.impl; import java.lang.reflect.Method; import net.xeoh.plugins.base.annotations.PluginImplementation; import net.xeoh.plugins.base.annotations.configuration.ConfigurationFile; import net.xeoh.plugins.base.annotations.meta.Author; import net.xeoh.plugins.base.annotations.meta.Version; /** * @author rb * */ @Author(name = "AUTHOR OK") @Version(version = 667) @ConfigurationFile(file="config.properties") @PluginImplementation public class TestAnnotationsImpl extends TestAnnotationsAbtractImpl { public static void main(String[] args) { for (final Method method : TestAnnotationsImpl.class.getMethods()) { String implementationMethodId = method.toString(); System.out.println(implementationMethodId); } } }
Java
/* * TestInitImpl.java * * Copyright (c) 2008, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.testplugins.testannotations.impl; import net.xeoh.plugins.base.annotations.Capabilities; import net.xeoh.plugins.base.annotations.PluginImplementation; import net.xeoh.plugins.base.annotations.Timer; import net.xeoh.plugins.base.annotations.configuration.IsDisabled; import net.xeoh.plugins.base.annotations.meta.Author; import net.xeoh.plugins.base.annotations.meta.Version; import net.xeoh.plugins.testplugins.testannotations.TestAnnotations; /** * @author rb * */ @IsDisabled @Version(version = 1000000) @Author(name = "Ralf Biedert") @PluginImplementation public class TestIsDisabled implements TestAnnotations { /** * @return . */ @Capabilities public String[] getCapabilities() { return new String[] { "IsDisabled" }; } /** * @return . */ @Timer(period = 50) public boolean timerMeLala() { System.out.println("THIS MUST NEVER BE PRINTED OR YOUR IsDisabled does not work!"); return false; } public String getInitStatus() { // TODO Auto-generated method stub return null; } public String getInjectionStatus() { // TODO Auto-generated method stub return null; } public String getThreadStatus() { // TODO Auto-generated method stub return null; } public String getTimerStatus() { // TODO Auto-generated method stub return null; } }
Java
/* * TestInitImpl.java * * Copyright (c) 2008, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.testplugins.testannotations.impl; import net.xeoh.plugins.base.annotations.Capabilities; import net.xeoh.plugins.base.annotations.Thread; import net.xeoh.plugins.base.annotations.Timer; import net.xeoh.plugins.base.annotations.events.Init; import net.xeoh.plugins.base.annotations.events.PluginLoaded; import net.xeoh.plugins.base.annotations.injections.InjectPlugin; import net.xeoh.plugins.informationbroker.InformationBroker; import net.xeoh.plugins.informationbroker.util.InformationBrokerUtil; import net.xeoh.plugins.remote.RemoteAPI; import net.xeoh.plugins.testplugins.testannotations.TestAnnotations; /** * @author rb * */ public class TestAnnotationsAbtractImpl implements TestAnnotations { /** * */ @InjectPlugin public InformationBrokerUtil bus; @InjectPlugin public InformationBroker busbus; String init = "INIT FAILED"; String thread = "THREAD FAILED"; String timer = "TIMER FAILED"; /** * @return . */ @Capabilities public String[] getCapabilities() { return new String[] { "SUNSHINE", "RAIN" }; } public String getInitStatus() { return this.init; } public String getInjectionStatus() { System.out.println("GET STATUS CALLED " + this.bus); return this.bus != null && this.busbus != null && this.bus.getObject() == this.busbus ? "INJECTION OK" : "INJECTION FAILED"; } public String getThreadStatus() { return this.thread; } public String getTimerStatus() { return this.timer; } /** * */ @Init public void initMeLala() { this.init = "INIT OK"; System.out.println("Plugin Initialized"); // throw new NullPointerException(); } /** * */ @Thread public void threadMeLala() { this.thread = "THREAD OK"; } /** * */ //@Thread public void bigbang() { System.out.println("Testing VisualVM Big Bang Theory"); double d = 3.14; while (true) { System.getenv("" + System.currentTimeMillis()); d *= Math.sin(d); } } /** * @return . */ @Timer(period = 50) public boolean timerMeLala() { this.timer = "TIMER OK"; return true; } /** * @param p */ @SuppressWarnings("boxing") @PluginLoaded public void newPlugin(RemoteAPI p) { System.out.printf("PluginLoaded (%d): %s\n", System.currentTimeMillis(), p); } }
Java
/* * TestInit.java * * Copyright (c) 2008, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.testplugins.testannotations; import net.xeoh.plugins.testplugins.core.TestCore; /** * @author rb * */ public interface TestAnnotations extends TestCore { /** * @return . */ public String getInitStatus(); // 'INIT OK' /** * @return . */ public String getInjectionStatus(); // 'INJECTION OK' /** * @return . */ public String getThreadStatus(); // 'THREAD OK' /** * @return . */ public String getTimerStatus(); // 'TIMER OK' }
Java
/* * TestInitImpl.java * * Copyright (c) 2008, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.testplugins.testdoubleinclude.impl; import net.xeoh.plugins.base.annotations.PluginImplementation; import net.xeoh.plugins.base.annotations.events.Init; import net.xeoh.plugins.base.annotations.injections.InjectPlugin; import net.xeoh.plugins.testplugins.testannotations.TestAnnotations; import net.xeoh.plugins.testplugins.testdoubleinclude.TestDoubleInclude; /** * @author rb * */ @PluginImplementation public class TestDoubleIncludeImpl implements TestDoubleInclude { /** * */ @InjectPlugin public TestAnnotations annotations; /** * */ @Init public void init() { final String initStatus = this.annotations.getInitStatus(); System.out.println("I am fine if this is sensible: " + initStatus); } }
Java
/* * TestDoubleIncludePlugin.java * * Copyright (c) 2008, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.testplugins.testdoubleinclude; import net.xeoh.plugins.testplugins.core.TestCore; /** * @author rb * */ public interface TestDoubleInclude extends TestCore { // }
Java
/* * TestInit.java * * Copyright (c) 2008, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.testplugins.core; /** * @author rb * */ public interface Test2Core extends TestCore { // }
Java
/* * TestInit.java * * Copyright (c) 2008, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.testplugins.core; import net.xeoh.plugins.base.Plugin; /** * @author rb * */ public interface TestCore extends Plugin { // }
Java
/* * TestInner.java * * Copyright (c) 2011, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.testplugins.testinner; import net.xeoh.plugins.base.annotations.PluginImplementation; import net.xeoh.plugins.base.annotations.events.Init; public class TestInner { @PluginImplementation public static class TestInnerInner implements TestInnerInterface { @Init public void init() { System.out.println("I am there"); } } }
Java
/* * TestInit.java * * Copyright (c) 2008, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.testplugins.testinner; import net.xeoh.plugins.base.Plugin; /** * @author rb * */ public interface TestInnerInterface extends Plugin { // }
Java
/* * Class.java * * Copyright (c) 2010, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.testplugins.classification; import net.xeoh.plugins.base.Plugin; /** * @author rb * */ public interface Class extends Plugin { /** * @return . */ public int classy(); }
Java
/* * Class.java * * Copyright (c) 2010, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.testplugins.classification.impl; import net.xeoh.plugins.base.annotations.PluginImplementation; /** * @author rb * */ @PluginImplementation public class Class implements net.xeoh.plugins.testplugins.classification.Class { /* (non-Javadoc) * @see net.xeoh.plugins.testplugins.classification.Class#classy() */ @Override public int classy() { return 123; } }
Java
/* * PluginTest.java * * Copyright (c) 2008, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.core; import java.net.URI; import java.util.Collection; import junit.framework.Assert; import net.xeoh.plugins.base.PluginInformation; import net.xeoh.plugins.base.PluginInformation.Information; import net.xeoh.plugins.base.PluginManager; import net.xeoh.plugins.base.impl.PluginManagerFactory; import net.xeoh.plugins.base.util.JSPFProperties; import net.xeoh.plugins.testplugins.testannotations.TestAnnotations; import org.junit.After; import org.junit.Before; import org.junit.Test; /** * @author rb * */ public class PluginManagerCapabilities { private PluginManager pm; /** * @throws Exception */ @Before public void setUp() throws Exception { final JSPFProperties props = new JSPFProperties(); props.setProperty(PluginManager.class, "cache.enabled", "true"); props.setProperty(PluginManager.class, "cache.mode", "weak"); props.setProperty(PluginManager.class, "cache.file", "jspf.cache"); props.setProperty(PluginManager.class, "supervision.enabled", "true"); this.pm = PluginManagerFactory.createPluginManager(props); this.pm.addPluginsFrom(new URI("classpath://*")); } /** * @throws Exception */ @After public void tearDown() throws Exception { this.pm.shutdown(); } /** * */ @Test public void testGetPluginClassOfP() { final PluginInformation pi = this.pm.getPlugin(PluginInformation.class); final TestAnnotations ta = this.pm.getPlugin(TestAnnotations.class); Assert.assertNotNull(ta); Collection<String> information = pi.getInformation(Information.CAPABILITIES, ta); Assert.assertNotNull(information); Assert.assertTrue(information.size() > 0); } }
Java
/* * PluginTest.java * * Copyright (c) 2008, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.core; import java.io.File; import net.xeoh.plugins.base.PluginManager; import net.xeoh.plugins.base.impl.PluginManagerFactory; import net.xeoh.test.coolplugin.CoolPlugin; import org.junit.After; import org.junit.Before; import org.junit.Test; /** * @author rb * */ public class PluginManagerCompatibility { private PluginManager pm; /** * @throws Exception */ @Before public void setUp() throws Exception { this.pm = PluginManagerFactory.createPluginManager(); } /** * @throws Exception */ @After public void tearDown() throws Exception { this.pm.shutdown(); } /** * @throws InterruptedException * */ @Test public void testGetPluginClassOfP() throws InterruptedException { this.pm.addPluginsFrom(new File("tests/plugins/coolplugin.jar").toURI()); final CoolPlugin plugin = this.pm.getPlugin(CoolPlugin.class); System.out.println(plugin); // System.out.println("..."); } }
Java
/* * PluginTest.java * * Copyright (c) 2008, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.core; import net.xeoh.plugins.base.PluginManager; import net.xeoh.plugins.base.impl.PluginManagerFactory; import net.xeoh.plugins.base.util.uri.ClassURI; import net.xeoh.plugins.remotediscovery.RemoteDiscovery; import net.xeoh.plugins.remotediscovery.impl.v4.RemoteDiscoveryImpl; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; /** * @author rb * */ public class PluginManagerLoadDirectly { private PluginManager pm; /** * @throws Exception */ @Before public void setUp() throws Exception { this.pm = PluginManagerFactory.createPluginManager(); } /** * @throws Exception */ @After public void tearDown() throws Exception { this.pm.shutdown(); } /** * */ @Test public void testGetPluginClassOfP() { Assert.assertNotNull(this.pm); RemoteDiscovery plugin = this.pm.getPlugin(RemoteDiscovery.class); Assert.assertNull("Plugin must not be there at this point", plugin); this.pm.addPluginsFrom(ClassURI.PLUGIN(RemoteDiscoveryImpl.class)); this.pm.addPluginsFrom(new ClassURI(RemoteDiscoveryImpl.class).toURI()); this.pm.addPluginsFrom(new ClassURI(RemoteDiscoveryImpl.class).toURI()); this.pm.addPluginsFrom(new ClassURI(RemoteDiscoveryImpl.class).toURI()); this.pm.addPluginsFrom(new ClassURI(RemoteDiscoveryImpl.class).toURI()); this.pm.addPluginsFrom(new ClassURI(RemoteDiscoveryImpl.class).toURI()); plugin = this.pm.getPlugin(RemoteDiscovery.class); Assert.assertNotNull("Now plugin must be there", plugin); } }
Java
/* * PluginTest.java * * Copyright (c) 2008, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.core; import static net.jcores.jre.CoreKeeper.$; import java.io.File; import net.xeoh.plugins.base.PluginInformation; import net.xeoh.plugins.base.PluginInformation.Information; import net.xeoh.plugins.base.PluginManager; import net.xeoh.plugins.base.impl.PluginManagerFactory; import net.xeoh.plugins.base.options.addpluginsfrom.OptionReportAfter; import net.xeoh.plugins.base.util.JSPFProperties; import net.xeoh.plugins.testplugins.testannotations.TestAnnotations; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; /** * @author rb * */ public class PluginManagerLoadMulti { private PluginManager pm; /** * @throws Exception */ @Before public void setUp() throws Exception { final JSPFProperties props = new JSPFProperties(); props.setProperty(PluginManager.class, "cache.enabled", "true"); props.setProperty(PluginManager.class, "cache.mode", "weak"); props.setProperty(PluginManager.class, "cache.file", "jspf.cache"); props.setProperty(PluginManager.class, "logging.level", "FINE"); this.pm = PluginManagerFactory.createPluginManager(props); } /** * @throws Exception */ @After public void tearDown() throws Exception { this.pm.shutdown(); } /** * */ @Test public void testGetPluginClassOfP() { Assert.assertNotNull("Pluginmanager must be there", this.pm); this.pm.addPluginsFrom(new File("tests/plugins/").toURI(), new OptionReportAfter()); final TestAnnotations p1 = this.pm.getPlugin(TestAnnotations.class); final PluginInformation p2 = this.pm.getPlugin(PluginInformation.class); $(p2.getInformation(Information.CLASSPATH_ORIGIN, p1)).string().print(); } }
Java
/* * PluginTest.java * * Copyright (c) 2008, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.core; import static net.jcores.jre.CoreKeeper.$; import java.net.MalformedURLException; import java.net.URI; import java.util.ArrayList; import java.util.Collection; import net.xeoh.plugins.base.Plugin; import net.xeoh.plugins.base.PluginInformation; import net.xeoh.plugins.base.PluginInformation.Information; import net.xeoh.plugins.base.PluginManager; import net.xeoh.plugins.base.impl.PluginManagerFactory; import net.xeoh.plugins.base.options.getplugin.OptionPluginSelector; import net.xeoh.plugins.base.options.getplugin.PluginSelector; import net.xeoh.plugins.testplugins.testannotations.TestAnnotations; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; /** * @author rb * */ public class PluginManagerTest { private PluginManager pm; /** * @throws Exception */ @Before public void setUp() throws Exception { this.pm = PluginManagerFactory.createPluginManager(); this.pm.addPluginsFrom(new URI("classpath://*")); //this.pm.addPluginsFrom(new File("dist/").toURI()); } /** * @throws Exception */ @After public void tearDown() throws Exception { this.pm.shutdown(); } /** * @throws MalformedURLException */ @Test public void testAddPluginsFrom() throws MalformedURLException { final PluginManager pm2 = PluginManagerFactory.createPluginManager(); Assert.assertNull(pm2.getPlugin(TestAnnotations.class)); //pm2.addPluginsFrom(new File("tests/plugins/test.coredefinition.jar").toURI()); //pm2.addPluginsFrom(new File("tests/plugins/test.annotation.jar").toURI()); //Assert.assertNotNull(pm2.getPlugin(TestAnnotations.class)); } /** * */ //@Test public void testGetPluginClassOfP() { Assert.assertNotNull(this.pm); final TestAnnotations plugin = this.pm.getPlugin(TestAnnotations.class); Assert.assertNotNull(plugin); Assert.assertEquals(plugin.getInitStatus(), "INIT OK"); Assert.assertEquals(plugin.getInjectionStatus(), "INJECTION OK"); try { Thread.sleep(100); } catch (final InterruptedException e) { e.printStackTrace(); } Assert.assertEquals(plugin.getThreadStatus(), "THREAD OK"); Assert.assertEquals(plugin.getTimerStatus(), "TIMER OK"); } /** * */ @Test public void testAllInterfaces() { final TestAnnotations plugin = this.pm.getPlugin(TestAnnotations.class); Collection<Class<? extends Plugin>> allPluginClasses = getAllPluginClasses(plugin); for (Class<? extends Plugin> class1 : allPluginClasses) { System.out.println(class1.getCanonicalName()); } } /** * */ @Test public void testVersion() { PluginInformation pi = this.pm.getPlugin(PluginInformation.class); Collection<String> information = pi.getInformation(Information.VERSION, pm); $(information).print(); } @SuppressWarnings("unchecked") private static Collection<Class<? extends Plugin>> getAllPluginClasses(Plugin plugin) { Collection<Class<? extends Plugin>> rval = new ArrayList<Class<? extends Plugin>>(); Class<? extends Plugin> c = plugin.getClass(); Class<?>[] i = c.getInterfaces(); for (Class<?> cc : i) { if (!Plugin.class.isAssignableFrom(cc)) continue; Collection<Class<?>> allSuperInterfaces = getAllSuperInterfaces(cc); for (Class<?> class1 : allSuperInterfaces) { if (!rval.contains(class1)) rval.add((Class<? extends Plugin>) class1); } } return rval; } private static Collection<Class<?>> getAllSuperInterfaces(Class<?> c) { Collection<Class<?>> rval = new ArrayList<Class<?>>(); rval.add(c); Class<?>[] interfaces = c.getInterfaces(); for (Class<?> class1 : interfaces) { Collection<Class<?>> allSuperInterfaces = getAllSuperInterfaces(class1); for (Class<?> class2 : allSuperInterfaces) { if (rval.contains(class2)) continue; rval.add(class2); } } return rval; } /** * */ //@Test public void testGetPluginClassOfPPluginSelectorOfP() { Assert.assertNotNull(this.pm); final TestAnnotations plugin = this.pm.getPlugin(TestAnnotations.class, new OptionPluginSelector<TestAnnotations>(new PluginSelector<TestAnnotations>() { public boolean selectPlugin(final TestAnnotations plugiN) { return false; } })); Assert.assertNull(plugin); } }
Java
/* * TestFrameworkManager.java * * Copyright (c) 2009, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.core; import net.xeoh.plugins.base.PluginManager; import net.xeoh.plugins.base.impl.PluginManagerFactory; import sun.applet.AppletSecurity; /** * @author rb * */ public class PluginManagerApplet { private PluginManager pluginManager; /** * */ public PluginManagerApplet() { System.setSecurityManager(new AppletSecurity()); this.pluginManager = PluginManagerFactory.createPluginManager(); this.pluginManager.shutdown(); } /** * @param args */ public static void main(String[] args) { new PluginManagerApplet(); } }
Java
/* * PluginTest.java * * Copyright (c) 2008, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.core; import net.xeoh.plugins.base.PluginManager; import net.xeoh.plugins.base.impl.PluginManagerFactory; import net.xeoh.plugins.base.util.JSPFProperties; import net.xeoh.plugins.base.util.uri.ClassURI; import net.xeoh.plugins.testplugins.testannotations.TestAnnotations; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; /** * @author rb * */ public class PluginManagerAnnotations { private PluginManager pm; /** * @throws Exception */ @Before public void setUp() throws Exception { final JSPFProperties props = new JSPFProperties(); this.pm = PluginManagerFactory.createPluginManager(props); this.pm.addPluginsFrom(ClassURI.CLASSPATH); } /** * @throws Exception */ @After public void tearDown() throws Exception { this.pm.shutdown(); } /** * */ @Test public void testAnnotations() { Assert.assertNotNull(this.pm); final TestAnnotations plugin = this.pm.getPlugin(TestAnnotations.class); Assert.assertNotNull(plugin); Assert.assertEquals(plugin.getInitStatus(), "INIT OK"); Assert.assertEquals(plugin.getInjectionStatus(), "INJECTION OK"); try { Thread.sleep(100); } catch (final InterruptedException e) { e.printStackTrace(); } Assert.assertEquals(plugin.getThreadStatus(), "THREAD OK"); Assert.assertEquals(plugin.getTimerStatus(), "TIMER OK"); } }
Java
/* * PluginTest.java * * Copyright (c) 2008, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.core; import java.net.URI; import java.net.URISyntaxException; import net.xeoh.plugins.base.PluginManager; import net.xeoh.plugins.base.impl.PluginManagerFactory; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; /** * @author rb * */ public class PluginManagerLoadHTTP { private PluginManager pm; /** * @throws Exception */ @Before public void setUp() throws Exception { this.pm = PluginManagerFactory.createPluginManager(); } /** * @throws Exception */ @After public void tearDown() throws Exception { //this.pm.shutdown(); } /** * */ @Test public void testGetPluginClassOfP() { Assert.assertNotNull(this.pm); try { this.pm.addPluginsFrom(new URI("http://jspf.googlecode.com/files/coolplugin.jar")); } catch (URISyntaxException e) { e.printStackTrace(); } } }
Java
/* * PluginTest.java * * Copyright (c) 2008, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.core; import java.net.URI; import net.xeoh.plugins.base.PluginInformation; import net.xeoh.plugins.base.PluginManager; import net.xeoh.plugins.base.impl.PluginManagerFactory; import net.xeoh.plugins.base.util.JSPFProperties; import net.xeoh.plugins.testplugins.testannotations.TestAnnotations; import net.xeoh.plugins.testplugins.testannotations.impl.TestAnnotationsImpl; import org.junit.After; import org.junit.Before; import org.junit.Test; /** * @author rb * */ public class PluginManagerDisablingPlugins { private PluginManager pm; /** * @throws Exception */ @Before public void setUp() throws Exception { final JSPFProperties props = new JSPFProperties(); props.setProperty(PluginManager.class, "cache.enabled", "true"); props.setProperty(PluginManager.class, "cache.mode", "weak"); props.setProperty(PluginManager.class, "cache.file", "jspf.cache"); props.setProperty(PluginManager.class, "supervision.enabled", "true"); // Enable and disable plugins like this: props.setProperty(TestAnnotationsImpl.class, "plugin.disabled", "false"); this.pm = PluginManagerFactory.createPluginManager(props); this.pm.addPluginsFrom(new URI("classpath://*")); } /** * @throws Exception */ @After public void tearDown() throws Exception { this.pm.shutdown(); } /** * */ @Test public void testGetPluginClassOfP() { final PluginInformation pi = this.pm.getPlugin(PluginInformation.class); final TestAnnotations ta = this.pm.getPlugin(TestAnnotations.class); } }
Java
/* * PluginTest.java * * Copyright (c) 2008, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.core; import java.io.File; import java.net.MalformedURLException; import java.util.ArrayList; import java.util.Collection; import net.xeoh.plugins.base.Plugin; import net.xeoh.plugins.base.PluginManager; import net.xeoh.plugins.base.impl.PluginManagerFactory; import net.xeoh.plugins.base.options.getplugin.OptionPluginSelector; import net.xeoh.plugins.base.options.getplugin.PluginSelector; import net.xeoh.plugins.testplugins.testannotations.TestAnnotations; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; /** * @author rb * */ public class PluginManagerLoadByPath { private PluginManager pm; /** * @throws Exception */ @Before public void setUp() throws Exception { this.pm = PluginManagerFactory.createPluginManager(); this.pm.addPluginsFrom(new File("tests/plugins/").toURI()); //this.pm.addPluginsFrom(new File("dist/").toURI()); } /** * @throws Exception */ @After public void tearDown() throws Exception { this.pm.shutdown(); } /** * @throws MalformedURLException */ @Test public void testAddPluginsFrom() throws MalformedURLException { final PluginManager pm2 = PluginManagerFactory.createPluginManager(); Assert.assertNull(pm2.getPlugin(TestAnnotations.class)); } /** * @throws InterruptedException * */ @Test public void testClassName() throws InterruptedException { net.xeoh.plugins.testplugins.classification.Class plugin = this.pm.getPlugin(net.xeoh.plugins.testplugins.classification.Class.class); Assert.assertEquals(plugin.classy(), 123); } /** * */ @Test public void testGetPluginClassOfP() { Assert.assertNotNull(this.pm); final TestAnnotations plugin = this.pm.getPlugin(TestAnnotations.class); Assert.assertNotNull(plugin); Assert.assertEquals(plugin.getInitStatus(), "INIT OK"); Assert.assertEquals(plugin.getInjectionStatus(), "INJECTION OK"); try { Thread.sleep(100); } catch (final InterruptedException e) { e.printStackTrace(); } Assert.assertEquals(plugin.getThreadStatus(), "THREAD OK"); Assert.assertEquals(plugin.getTimerStatus(), "TIMER OK"); } /** * */ @Test public void testAllInterfaces() { final TestAnnotations plugin = this.pm.getPlugin(TestAnnotations.class); System.out.println(plugin); Collection<Class<? extends Plugin>> allPluginClasses = getAllPluginClasses(plugin); for (Class<? extends Plugin> class1 : allPluginClasses) { System.out.println(class1.getCanonicalName()); } } @SuppressWarnings("unchecked") private static Collection<Class<? extends Plugin>> getAllPluginClasses(Plugin plugin) { Collection<Class<? extends Plugin>> rval = new ArrayList<Class<? extends Plugin>>(); Class<? extends Plugin> c = plugin.getClass(); Class<?>[] i = c.getInterfaces(); for (Class<?> cc : i) { if (!Plugin.class.isAssignableFrom(cc)) continue; Collection<Class<?>> allSuperInterfaces = getAllSuperInterfaces(cc); for (Class<?> class1 : allSuperInterfaces) { if (!rval.contains(class1)) rval.add((Class<? extends Plugin>) class1); } } return rval; } private static Collection<Class<?>> getAllSuperInterfaces(Class<?> c) { Collection<Class<?>> rval = new ArrayList<Class<?>>(); rval.add(c); Class<?>[] interfaces = c.getInterfaces(); for (Class<?> class1 : interfaces) { Collection<Class<?>> allSuperInterfaces = getAllSuperInterfaces(class1); for (Class<?> class2 : allSuperInterfaces) { if (rval.contains(class2)) continue; rval.add(class2); } } return rval; } /** * */ //@Test public void testGetPluginClassOfPPluginSelectorOfP() { Assert.assertNotNull(this.pm); final TestAnnotations plugin = this.pm.getPlugin(TestAnnotations.class, new OptionPluginSelector<TestAnnotations>(new PluginSelector<TestAnnotations>() { public boolean selectPlugin(final TestAnnotations plugiN) { return false; } })); Assert.assertNull(plugin); } }
Java
/* * PluginTest.java * * Copyright (c) 2008, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.core; import java.net.URI; import net.xeoh.plugins.base.PluginConfiguration; import net.xeoh.plugins.base.PluginManager; import net.xeoh.plugins.base.impl.PluginManagerFactory; import net.xeoh.plugins.base.util.JSPFProperties; import net.xeoh.plugins.base.util.uri.ClassURI; import net.xeoh.plugins.testplugins.testannotations.TestAnnotations; import org.junit.Assert; import org.junit.Before; import org.junit.Test; /** * @author rb * */ public class ShutdownTest { private PluginManager pm; /** * @throws Exception */ @Before public void setUp() throws Exception { JSPFProperties pros = new JSPFProperties(); pros.setProperty(PluginManager.class, "logging.level", "WARNING"); this.pm = PluginManagerFactory.createPluginManager(pros); this.pm.addPluginsFrom(new URI("classpath://*")); } /** * */ @Test public void testShutdown() { Assert.assertNotNull(this.pm); TestAnnotations plugin = this.pm.getPlugin(TestAnnotations.class); Assert.assertNotNull(plugin); this.pm.shutdown(); plugin = this.pm.getPlugin(TestAnnotations.class); Assert.assertNull(plugin); Assert.assertNull(this.pm.getPlugin(PluginConfiguration.class)); } /** * */ @Test public void testMany() { for(int i=0; i<10000; i++) { System.out.println(); System.out.println("Run " + i); PluginManager manager = PluginManagerFactory.createPluginManager(); manager.addPluginsFrom(ClassURI.CLASSPATH); manager.shutdown(); } } }
Java
/* * PluginTest.java * * Copyright (c) 2008, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.core; import java.net.URI; import java.net.URISyntaxException; import net.xeoh.plugins.base.PluginManager; import net.xeoh.plugins.base.impl.PluginManagerFactory; import net.xeoh.plugins.base.options.getplugin.OptionCapabilities; import net.xeoh.plugins.remote.RemoteAPI; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; /** * @author rb * */ public class PluginManagerOptions { private PluginManager pm; /** * @throws Exception */ @Before public void setUp() throws Exception { this.pm = PluginManagerFactory.createPluginManager(); } /** * @throws Exception */ @After public void tearDown() throws Exception { this.pm.shutdown(); } /** * */ @Test public void testGetPluginClassOfP() { Assert.assertNotNull("Pluginmanager must be there", this.pm); RemoteAPI plugin = this.pm.getPlugin(RemoteAPI.class); Assert.assertNull("Plugin must not be there at this point", plugin); try { this.pm.addPluginsFrom(new URI("classpath://*")); } catch (URISyntaxException e) { e.printStackTrace(); } plugin = this.pm.getPlugin(RemoteAPI.class, new OptionCapabilities("ASOIDASJdasjkdhasdiasoDASOJd")); Assert.assertNull("This plugins must not exist", plugin); plugin = this.pm.getPlugin(RemoteAPI.class, new OptionCapabilities("XMLRPC")); Assert.assertNotNull("Now plugin must be there", plugin); } }
Java
/* * PluginTest.java * * Copyright (c) 2008, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.core; import net.xeoh.plugins.base.PluginManager; import net.xeoh.plugins.base.impl.PluginManagerFactory; import net.xeoh.plugins.base.util.JSPFProperties; import net.xeoh.plugins.base.util.uri.ClassURI; import net.xeoh.plugins.diagnosis.local.Diagnosis; import net.xeoh.plugins.remote.RemoteAPI; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; /** * @author rb * */ public class PluginManagerLoadClasspath { private PluginManager pm; /** * @throws Exception */ @Before public void setUp() throws Exception { final JSPFProperties props = new JSPFProperties(); props.setProperty(PluginManager.class, "cache.enabled", "true"); props.setProperty(PluginManager.class, "cache.mode", "weak"); props.setProperty(PluginManager.class, "cache.file", "jspf.cache"); // props.setProperty(PluginManager.class, "logging.level", "ALL"); props.setProperty(PluginManager.class, "classpath.filter.default.pattern", ""); props.setProperty(Diagnosis.class, "recording.enabled", "true"); props.setProperty(Diagnosis.class, "recording.file", "diagnosis.record"); props.setProperty(Diagnosis.class, "recording.format", "java/serialization"); props.setProperty(Diagnosis.class, "analysis.stacktraces.enabled", "true"); props.setProperty(Diagnosis.class, "analysis.stacktraces.depth", "10000"); this.pm = PluginManagerFactory.createPluginManager(props); } /** * @throws Exception */ @After public void tearDown() throws Exception { this.pm.shutdown(); } /** * */ @Test public void testGetPluginClassOfP() { Assert.assertNotNull("Pluginmanager must be there", this.pm); RemoteAPI plugin = this.pm.getPlugin(RemoteAPI.class); Assert.assertNull("Plugin must not be there at this point", plugin); this.pm.addPluginsFrom(ClassURI.CLASSPATH); // this.pm.addPluginsFrom(new File("bin/").toURI()); // this.pm.addPluginsFrom(new URI("classpath://net.xeoh.plugins.remote.impl.*.*"), // new OptionReportAfter()); // this.pm.addPluginsFrom(new URI("classpath://*")); plugin = this.pm.getPlugin(RemoteAPI.class); Assert.assertNotNull("Now plugin must be there", plugin); System.out.println("Fin"); } }
Java
/* * PluginTest.java * * Copyright (c) 2008, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.core; import java.net.URI; import net.xeoh.plugins.base.PluginManager; import net.xeoh.plugins.base.impl.PluginManagerFactory; import net.xeoh.plugins.base.util.JSPFProperties; import net.xeoh.plugins.testplugins.testinner.TestInnerInterface; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; /** * @author rb * */ public class PluginManagerLoadInner { private PluginManager pm; /** * @throws Exception */ @Before public void setUp() throws Exception { final JSPFProperties props = new JSPFProperties(); this.pm = PluginManagerFactory.createPluginManager(props); this.pm.addPluginsFrom(URI.create("classpath://*")); } /** * @throws Exception */ @After public void tearDown() throws Exception { this.pm.shutdown(); } /** * */ @Test public void testInner() { TestInnerInterface plugin = this.pm.getPlugin(TestInnerInterface.class); Assert.assertNotNull(plugin); } }
Java
/* * BusTest.java * * Copyright (c) 2008, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.core; import java.net.URI; import java.util.Collection; import net.xeoh.plugins.base.PluginInformation; import net.xeoh.plugins.base.PluginInformation.Information; import net.xeoh.plugins.base.PluginManager; import net.xeoh.plugins.base.impl.PluginManagerFactory; import net.xeoh.plugins.testplugins.testannotations.TestAnnotations; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; /** * @author rb * */ public class PluginInformationTest { private PluginManager pm; /** * @throws Exception */ @Before public void setUp() throws Exception { this.pm = PluginManagerFactory.createPluginManager(); this.pm.addPluginsFrom(new URI("classpath://*")); } /** * @throws Exception */ @After public void tearDown() throws Exception { this.pm.shutdown(); } /** * */ @Test public void testPluginInformation() { Assert.assertNotNull(this.pm); final TestAnnotations ta = this.pm.getPlugin(TestAnnotations.class); final PluginInformation pi = this.pm.getPlugin(PluginInformation.class); Assert.assertNotNull("TestAnnotaions must be there!", ta); Assert.assertNotNull("Plugin Information must be there", pi); final Collection<String> caps = pi.getInformation(Information.CAPABILITIES, ta); final Collection<String> author = pi.getInformation(Information.AUTHORS, ta); final Collection<String> version = pi.getInformation(Information.VERSION, ta); final Collection<String> origin = pi.getInformation(Information.CLASSPATH_ORIGIN, ta); Assert.assertTrue("Caps must contain SUNSHINE", caps.contains("SUNSHINE")); Assert.assertTrue("Caps must contain RAIN", caps.contains("RAIN")); Assert.assertTrue("Author must contain AUTHOR OK", author.contains("AUTHOR OK")); Assert.assertTrue("Version must be 667", version.contains("667")); System.out.println(origin); } }
Java
/* * PluginTest.java * * Copyright (c) 2008, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.diagnosis; import java.io.Serializable; import net.xeoh.plugins.base.PluginManager; import net.xeoh.plugins.base.impl.PluginManagerFactory; import net.xeoh.plugins.base.util.JSPFProperties; import net.xeoh.plugins.diagnosis.diagnosis.channels.LoggingChannel1; import net.xeoh.plugins.diagnosis.diagnosis.channels.LoggingChannel2; import net.xeoh.plugins.diagnosis.diagnosis.channels.TestChannel; import net.xeoh.plugins.diagnosis.local.Diagnosis; import net.xeoh.plugins.diagnosis.local.DiagnosisChannel; import net.xeoh.plugins.diagnosis.local.DiagnosisMonitor; import net.xeoh.plugins.diagnosis.local.DiagnosisStatus; import net.xeoh.plugins.diagnosis.local.options.status.OptionInfo; import net.xeoh.plugins.diagnosis.local.util.DiagnosisChannelUtil; import net.xeoh.plugins.diagnosis.local.util.DiagnosisUtil; import net.xeoh.plugins.diagnosis.local.util.conditions.TwoStateMatcherAND; import net.xeoh.plugins.diagnosis.local.util.conditions.matcher.Contains; import net.xeoh.plugins.diagnosis.local.util.conditions.matcher.Is; import net.xeoh.plugins.testplugins.testannotations.impl.TestAnnotationsImpl; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; /** * @author rb * */ public class DiagnosisGeneralTest { private static PluginManager pm; /** * @throws Exception */ @BeforeClass public static void setUp() { final JSPFProperties props = new JSPFProperties(); props.setProperty(Diagnosis.class, "recording.enabled", "true"); props.setProperty(Diagnosis.class, "recording.file", "diagnosis.record"); props.setProperty(Diagnosis.class, "recording.format", "java/serialization"); props.setProperty(Diagnosis.class, "analysis.stacktraces.enabled", "true"); props.setProperty(Diagnosis.class, "analysis.stacktraces.depth", "10000"); // Enable and disable plugins like this: props.setProperty(TestAnnotationsImpl.class, "plugin.disabled", "false"); try { pm = PluginManagerFactory.createPluginManager(props); } catch (Exception e) { e.printStackTrace(); } //pm.addPluginsFrom(URI.create("xxx:yyy")); } /** * @throws Exception */ @AfterClass public static void tearDown() throws Exception { pm.shutdown(); } /** * */ @Test public void benchmark() { Assert.assertNotNull(this.pm); final Diagnosis diagnosis = this.pm.getPlugin(Diagnosis.class); long a = System.currentTimeMillis(); for(int i=0; i<10000;i++) { diagnosis.channel(LoggingChannel1.class).status(""+i); } long b = System.currentTimeMillis(); System.out.println(b-a); DiagnosisChannel<String> channel = diagnosis.channel(LoggingChannel2.class); a = System.currentTimeMillis(); for(int i=0; i<10000;i++) { channel.status(""+i); } b = System.currentTimeMillis(); System.out.println(b-a); DiagnosisChannelUtil<String> c = new DiagnosisChannelUtil<String>(null); c.status("null"); c.status("null", "a", "b"); c.status("null", new OptionInfo("a", "b")); } /** * */ @SuppressWarnings("boxing") @Test public void testGetPluginClassOfP() { Assert.assertNotNull(this.pm); final Diagnosis diagnosis = this.pm.getPlugin(Diagnosis.class); diagnosis.channel(LoggingChannel1.class).status("Starting Test."); diagnosis.channel(TestChannel.class).status(100); diagnosis.channel(TestChannel.class).status(100); diagnosis.channel(TestChannel.class).status(100); diagnosis.channel(TestChannel.class).status(3000); diagnosis.channel(LoggingChannel1.class).status("Initializing Status"); DiagnosisUtil util = new DiagnosisUtil(diagnosis); util.registerMonitors(new DiagnosisMonitor<Serializable>() { @Override public void onStatusChange(DiagnosisStatus<Serializable> status) { if(status.getChannel().equals(TestChannel.class)) System.out.println("TC"); System.out.println(">>> " + status.getValue()); } }, TestChannel.class, LoggingChannel1.class); diagnosis.channel(TestChannel.class).status(6667); diagnosis.channel(TestChannel.class).status(100); util.registerCondition(new TwoStateMatcherAND() { /** */ @Override protected void setupMatcher() { match(TestChannel.class, new Is(100)); match(LoggingChannel1.class, new Contains("xtatus")); } /** */ @Override public void stateChanged(STATE state) { System.out.println("STATE CJAMGE" + state); } }); diagnosis.channel(TestChannel.class).status(3000); diagnosis.channel(TestChannel.class).status(100); //D2 d; //diagnosis.status(URI.create(TestChannel.class, "xxx"), 300); //diagnosis.channel(LoggingChannel1.class).status("start/x"); //DiagnosisCondition condition = new TestCondition(); //condition //diagnosis.registerCondition(condition); // Was ist mit Multi-Threading? // T1: start() -> state1 -> state2 .... -> state4 // T2: start() -> state1 // In dem Fall würde der Sensor sehen // s1 s2 s1 s4 s2 s5 ... // Und könnte nicht wirklich eine sinnvolle condition definieren. // Andererseits, wir haben den Thread-Status dabei, so dass jeder Thread seine eigene // time-line bekommt, bzw. bekommen kann // Das würde bedeuten, dass es keinen einzigen Zustand s gibt, sondern eine unbestimmte menge davon. // Wie macht man das nun mit conditions? // if(s == 1 && t == 3)? // if(s(threadA) == 1 && t(threadA) == 3)? // Frage, wie kann ich einzelne Kanäle deaktivieren, die z.b: eine Hohe Last oder Debugausgaben verursachen? // An die komme ich nämlich nicht einfach ran, wenn die in einem Plugin verborgen sind. // --> InformationBroker // Soll es eine Replay-API geben? // --> Nicht notwendig, wenn es Tools zur Analyse in JSPF mit dazu gibt (z.B. Extraktor & Konverter) // Was ist mit den serialisierten Werten, die können vom Tool nicht zurückgelesen werden, sofern es spezielle // Werte sind. // --> Müssen im Classpath mit aufgenommen werden, oder werden halt nicht wiede de-serialisiert // Wird das nicht langsam sein? // --> Ist nicht gedacht für high-volume recording, sondern eher für sagen wir <100 Nachrichten pro Sekunde // auf Pluginebene. // Was ist mit Erklärungen f. Messwerte, Conditions, usw. Die wären im Replay-Tool nicht verfügbar, insbesondere // nicht, wenn die zur Laufzeit zusammengeschuhstert werden müssen // --> Muss auf Klassenebene der Channels passieren, dort Konverter usw. reinzumachen // Würde ein Recording auf den Channels mit primitiven Typen nicht viel schneller sein? // z.B. diagnosis.channel(TestChannel.class).reportInt(30) // dann hätte man auch keine Probleme beim De-Serialisieren // --> Mmhm, ist was dran. Ist aber weniger elegant, außerdem können dann auf einem Channel // Werte gemischt werden. Ich behaupte einfach mal dass in Richtung Java 7,8,9 Boxing-Typen // irgendwann gleichschnell wie primitive Typen behandelt werden können. Und das Problem // beim entpacken kann der Entwickler einfach dadurch lösen, dass er halt nur eingebaute Typen // nimmt ... // Q1: How does the condition access diagnosis-internal functions/variables? // Q2: How do we associate conditions with messages / remedies / ...? // Q3: Who fires *when* and *how* and triggers *what* when a condition is met? diagnosis.channel(LoggingChannel1.class).status("Ending Test."); } }
Java
/* * TestChannel.java * * Copyright (c) 2011, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.diagnosis.diagnosis.channels; import net.xeoh.plugins.diagnosis.local.DiagnosisChannelID; public class TestChannel extends DiagnosisChannelID<Integer> { }
Java
/* * TestChannel.java * * Copyright (c) 2011, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.diagnosis.diagnosis.channels; import net.xeoh.plugins.diagnosis.local.DiagnosisChannelID; public class LoggingChannel1 extends DiagnosisChannelID<String> { }
Java
/* * TestChannel.java * * Copyright (c) 2011, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.diagnosis.diagnosis.channels; import net.xeoh.plugins.diagnosis.local.DiagnosisChannelID; public class LoggingChannel2 extends DiagnosisChannelID<String> { }
Java
/* * D2.java * * Copyright (c) 2011, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.diagnosis.diagnosis; import java.io.Serializable; import java.net.URI; import net.xeoh.plugins.diagnosis.local.DiagnosisChannel; import net.xeoh.plugins.diagnosis.local.DiagnosisChannelID; import net.xeoh.plugins.diagnosis.local.options.ChannelOption; import net.xeoh.plugins.diagnosis.local.options.StatusOption; public interface D2 { public <T extends Serializable> DiagnosisChannel<T> channel(Class<? extends DiagnosisChannelID<T>> channel, ChannelOption... options); public void status(URI channel, Object object, StatusOption...options); }
Java
/* * PluginTest.java * * Copyright (c) 2008, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.diagnosis; import java.net.URI; import net.xeoh.plugins.base.PluginManager; import net.xeoh.plugins.base.impl.PluginManagerFactory; import net.xeoh.plugins.base.util.JSPFProperties; import net.xeoh.plugins.diagnosis.diagnosis.channels.LoggingChannel1; import net.xeoh.plugins.diagnosis.local.Diagnosis; import net.xeoh.plugins.testplugins.testannotations.impl.TestAnnotationsImpl; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; /** * @author rb * */ public class DiagnosisMiniTest { private static PluginManager pm; /** * @throws Exception */ @BeforeClass public static void setUp() throws Exception { final JSPFProperties props = new JSPFProperties(); props.setProperty(Diagnosis.class, "recording.enabled", "true"); props.setProperty(Diagnosis.class, "recording.file", "diagnosis.record"); props.setProperty(Diagnosis.class, "recording.format", "java/serialization"); props.setProperty(Diagnosis.class, "analysis.stacktraces.enabled", "true"); props.setProperty(Diagnosis.class, "analysis.stacktraces.depth", "10000"); // Enable and disable plugins like this: props.setProperty(TestAnnotationsImpl.class, "plugin.disabled", "false"); pm = PluginManagerFactory.createPluginManager(props); pm.addPluginsFrom(URI.create("xxx:yyy")); } /** * @throws Exception */ @AfterClass public static void tearDown() throws Exception { pm.shutdown(); } /** * */ @Test public void benchmark() { Assert.assertNotNull(this.pm); final Diagnosis diagnosis = this.pm.getPlugin(Diagnosis.class); diagnosis.channel(LoggingChannel1.class).status("XXX"); } }
Java
/* * BusTest.java * * Copyright (c) 2008, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.informationbroker; import java.net.URI; import net.xeoh.plugins.base.PluginManager; import net.xeoh.plugins.base.impl.PluginManagerFactory; import net.xeoh.plugins.informationbroker.util.InformationBrokerUtil; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; /** * @author rb * */ public class InformationBrokerTest2 { private PluginManager pm; boolean called1 = false; boolean called2 = false; /** * @throws Exception */ @Before public void setUp() throws Exception { this.pm = PluginManagerFactory.createPluginManager(); this.pm.addPluginsFrom(new URI("classpath://*")); } /** * @throws Exception */ @After public void tearDown() throws Exception { this.pm.shutdown(); } /** * @throws InterruptedException */ /* * @Test * public void testBroker() throws InterruptedException { * Assert.assertNotNull(this.pm); * * final InformationBroker plugin = this.pm.getPlugin(InformationBroker.class); * * plugin.publish(new StringItem("device:location", "Kaiserslautern, Germany")); * plugin.subscribe(new StringID("device:location"), new InformationListener<String>() * { * public void update(InformationItem<String> item) { * System.out.println(item.getContent()); * } * }); * plugin.publish(new StringItem("device:location", "World's End.")); * * final InformationBrokerUtil ibu = new InformationBrokerUtil(plugin); * System.out.println(ibu.get(new StringID("device:location"))); * * } */ @Test public void testBroker() throws InterruptedException { Assert.assertNotNull(this.pm); final InformationBroker plugin = this.pm.getPlugin(InformationBroker.class); plugin.subscribe(TestItemA.class, new InformationListener<String>() { @Override public void update(String item) { System.out.println("Hello World"); } }); final InformationBrokerUtil util = new InformationBrokerUtil(plugin); util.subscribeAll(new InformationListener<Void>() {; @Override public void update(Void item) { System.out.println("Got both"); System.out.println(item); System.out.println(util.get(TestItemA.class)); System.out.println(util.get(TestItemB.class)); System.out.println(util.get(TestItemA.class)); System.out.println(util.get(TestItemB.class)); } }, TestItemA.class, TestItemB.class); System.out.println("1"); plugin.publish(TestItemA.class, "A) Hello"); System.out.println("2"); plugin.publish(TestItemB.class, "B) World"); System.out.println("3"); // plugin.publish(TestItem.class, new Object()); } }
Java
/* * TestChannel.java * * Copyright (c) 2010, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.informationbroker; public class TestItemA implements InformationItem<String> { }
Java
/* * TestChannel.java * * Copyright (c) 2010, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.informationbroker; public class TestItemB implements InformationItem<String> { }
Java
package org.poly2tri.triangulation.point.ardor3d; import java.util.ArrayList; import java.util.List; import org.poly2tri.geometry.polygon.PolygonPoint; import org.poly2tri.triangulation.TriangulationPoint; import com.ardor3d.math.Vector3; public class ArdorVector3PolygonPoint extends PolygonPoint { private final Vector3 _p; public ArdorVector3PolygonPoint( Vector3 point ) { super( point.getX(), point.getY() ); _p = point; } public final double getX() { return _p.getX(); } public final double getY() { return _p.getY(); } public final double getZ() { return _p.getZ(); } public final float getXf() { return _p.getXf(); } public final float getYf() { return _p.getYf(); } public final float getZf() { return _p.getZf(); } public static List<PolygonPoint> toPoints( Vector3[] vpoints ) { ArrayList<PolygonPoint> points = new ArrayList<PolygonPoint>(vpoints.length); for( int i=0; i<vpoints.length; i++ ) { points.add( new ArdorVector3PolygonPoint(vpoints[i]) ); } return points; } public static List<PolygonPoint> toPoints( ArrayList<Vector3> vpoints ) { int i=0; ArrayList<PolygonPoint> points = new ArrayList<PolygonPoint>(vpoints.size()); for( Vector3 point : vpoints ) { points.add( new ArdorVector3PolygonPoint(point) ); } return points; } }
Java
package org.poly2tri.triangulation.point.ardor3d; import java.util.ArrayList; import java.util.List; import org.poly2tri.triangulation.TriangulationPoint; import com.ardor3d.math.Vector3; public class ArdorVector3Point extends TriangulationPoint { private final Vector3 _p; public ArdorVector3Point( Vector3 point ) { _p = point; } public final double getX() { return _p.getX(); } public final double getY() { return _p.getY(); } public final double getZ() { return _p.getZ(); } public final float getXf() { return _p.getXf(); } public final float getYf() { return _p.getYf(); } public final float getZf() { return _p.getZf(); } @Override public void set( double x, double y, double z ) { _p.set( x, y, z ); } public static List<TriangulationPoint> toPoints( Vector3[] vpoints ) { ArrayList<TriangulationPoint> points = new ArrayList<TriangulationPoint>(vpoints.length); for( int i=0; i<vpoints.length; i++ ) { points.add( new ArdorVector3Point(vpoints[i]) ); } return points; } public static List<TriangulationPoint> toPoints( ArrayList<Vector3> vpoints ) { int i=0; ArrayList<TriangulationPoint> points = new ArrayList<TriangulationPoint>(vpoints.size()); for( Vector3 point : vpoints ) { points.add( new ArdorVector3Point(point) ); } return points; } public static List<TriangulationPoint> toPolygonPoints( Vector3[] vpoints ) { ArrayList<TriangulationPoint> points = new ArrayList<TriangulationPoint>(vpoints.length); for( int i=0; i<vpoints.length; i++ ) { points.add( new ArdorVector3PolygonPoint(vpoints[i]) ); } return points; } public static List<TriangulationPoint> toPolygonPoints( ArrayList<Vector3> vpoints ) { int i=0; ArrayList<TriangulationPoint> points = new ArrayList<TriangulationPoint>(vpoints.size()); for( Vector3 point : vpoints ) { points.add( new ArdorVector3PolygonPoint(point) ); } return points; } }
Java
package org.poly2tri.triangulation.tools.ardor3d; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.util.HashMap; import java.util.List; import org.poly2tri.geometry.polygon.Polygon; import org.poly2tri.geometry.primitives.Point; import org.poly2tri.transform.coordinate.CoordinateTransform; import org.poly2tri.transform.coordinate.NoTransform; import org.poly2tri.triangulation.TriangulationPoint; import org.poly2tri.triangulation.delaunay.DelaunayTriangle; import org.poly2tri.triangulation.point.TPoint; import org.poly2tri.triangulation.sets.PointSet; import com.ardor3d.math.Vector3; import com.ardor3d.renderer.IndexMode; import com.ardor3d.scenegraph.Mesh; import com.ardor3d.util.geom.BufferUtils; public class ArdorMeshMapper { private static final CoordinateTransform _ct = new NoTransform(); public static void updateTriangleMesh( Mesh mesh, List<DelaunayTriangle> triangles ) { updateTriangleMesh( mesh, triangles, _ct ); } public static void updateTriangleMesh( Mesh mesh, List<DelaunayTriangle> triangles, CoordinateTransform pc ) { FloatBuffer vertBuf; TPoint point; mesh.getMeshData().setIndexMode( IndexMode.Triangles ); if( triangles == null || triangles.size() == 0 ) { return; } point = new TPoint(0,0,0); int size = 3*3*triangles.size(); prepareVertexBuffer( mesh, size ); vertBuf = mesh.getMeshData().getVertexBuffer(); vertBuf.rewind(); for( DelaunayTriangle t : triangles ) { for( int i=0; i<3; i++ ) { pc.transform( t.points[i], point ); vertBuf.put(point.getXf()); vertBuf.put(point.getYf()); vertBuf.put(point.getZf()); } } } public static void updateFaceNormals( Mesh mesh, List<DelaunayTriangle> triangles ) { updateFaceNormals( mesh, triangles, _ct ); } public static void updateFaceNormals( Mesh mesh, List<DelaunayTriangle> triangles, CoordinateTransform pc ) { FloatBuffer nBuf; Vector3 fNormal; HashMap<DelaunayTriangle,Vector3> fnMap; int size = 3*3*triangles.size(); fnMap = calculateFaceNormals( triangles, pc ); prepareNormalBuffer( mesh, size ); nBuf = mesh.getMeshData().getNormalBuffer(); nBuf.rewind(); for( DelaunayTriangle t : triangles ) { fNormal = fnMap.get( t ); for( int i=0; i<3; i++ ) { nBuf.put(fNormal.getXf()); nBuf.put(fNormal.getYf()); nBuf.put(fNormal.getZf()); } } } public static void updateVertexNormals( Mesh mesh, List<DelaunayTriangle> triangles ) { updateVertexNormals( mesh, triangles, _ct ); } public static void updateVertexNormals( Mesh mesh, List<DelaunayTriangle> triangles, CoordinateTransform pc ) { FloatBuffer nBuf; TriangulationPoint vertex; Vector3 vNormal, fNormal; HashMap<DelaunayTriangle,Vector3> fnMap; HashMap<TriangulationPoint,Vector3> vnMap = new HashMap<TriangulationPoint,Vector3>(3*triangles.size()); int size = 3*3*triangles.size(); fnMap = calculateFaceNormals( triangles, pc ); // Calculate a vertex normal for each vertex for( DelaunayTriangle t : triangles ) { fNormal = fnMap.get( t ); for( int i=0; i<3; i++ ) { vertex = t.points[i]; vNormal = vnMap.get( vertex ); if( vNormal == null ) { vNormal = new Vector3( fNormal.getX(), fNormal.getY(), fNormal.getZ() ); vnMap.put( vertex, vNormal ); } else { vNormal.addLocal( fNormal ); } } } // Normalize all normals for( Vector3 normal : vnMap.values() ) { normal.normalizeLocal(); } prepareNormalBuffer( mesh, size ); nBuf = mesh.getMeshData().getNormalBuffer(); nBuf.rewind(); for( DelaunayTriangle t : triangles ) { for( int i=0; i<3; i++ ) { vertex = t.points[i]; vNormal = vnMap.get( vertex ); nBuf.put(vNormal.getXf()); nBuf.put(vNormal.getYf()); nBuf.put(vNormal.getZf()); } } } private static HashMap<DelaunayTriangle,Vector3> calculateFaceNormals( List<DelaunayTriangle> triangles, CoordinateTransform pc ) { HashMap<DelaunayTriangle,Vector3> normals = new HashMap<DelaunayTriangle,Vector3>(triangles.size()); TPoint point = new TPoint(0,0,0); // calculate the Face Normals for all triangles float x1,x2,x3,y1,y2,y3,z1,z2,z3,nx,ny,nz,ux,uy,uz,vx,vy,vz; double norm; for( DelaunayTriangle t : triangles ) { pc.transform( t.points[0], point ); x1 = point.getXf(); y1 = point.getYf(); z1 = point.getZf(); pc.transform( t.points[1], point ); x2 = point.getXf(); y2 = point.getYf(); z2 = point.getZf(); pc.transform( t.points[2], point ); x3 = point.getXf(); y3 = point.getYf(); z3 = point.getZf(); ux = x2 - x1; uy = y2 - y1; uz = z2 - z1; vx = x3 - x1; vy = y3 - y1; vz = z3 - z1; nx = uy*vz - uz*vy; ny = uz*vx - ux*vz; nz = ux*vy - uy*vx; norm = 1/Math.sqrt( nx*nx + ny*ny + nz*nz ); nx *= norm; ny *= norm; nz *= norm; normals.put( t, new Vector3(nx,ny,nz) ); } return normals; } /** * For now very primitive! * * Assumes a single texture and that the triangles form a xy-monotone surface * <p> * A continuous surface S in R3 is called xy-monotone, if every line parallel * to the z-axis intersects it at a single point at most. * * @param mesh * @param scale */ public static void updateTextureCoordinates( Mesh mesh, List<DelaunayTriangle> triangles, double scale, double angle ) { TriangulationPoint vertex; FloatBuffer tcBuf; float width,maxX,minX,maxY,minY,x,y,xn,yn; maxX = Float.NEGATIVE_INFINITY; minX = Float.POSITIVE_INFINITY; maxY = Float.NEGATIVE_INFINITY; minY = Float.POSITIVE_INFINITY; for( DelaunayTriangle t : triangles ) { for( int i=0; i<3; i++ ) { vertex = t.points[i]; x = vertex.getXf(); y = vertex.getYf(); maxX = x > maxX ? x : maxX; minX = x < minX ? x : minX; maxY = y > maxY ? y : maxY; minY = y < minY ? x : minY; } } width = maxX-minX > maxY-minY ? maxX-minX : maxY-minY; width *= scale; tcBuf = prepareTextureCoordinateBuffer(mesh,0,2*3*triangles.size()); tcBuf.rewind(); for( DelaunayTriangle t : triangles ) { for( int i=0; i<3; i++ ) { vertex = t.points[i]; x = vertex.getXf()-(maxX-minX)/2; y = vertex.getYf()-(maxY-minY)/2; xn = (float)(x*Math.cos(angle)-y*Math.sin(angle)); yn = (float)(y*Math.cos(angle)+x*Math.sin(angle)); tcBuf.put( xn/width ); tcBuf.put( yn/width ); } } } /** * Assuming: * 1. That given U anv V aren't collinear. * 2. That O,U and V can be projected in the XY plane * * @param mesh * @param triangles * @param o * @param u * @param v */ public static void updateTextureCoordinates( Mesh mesh, List<DelaunayTriangle> triangles, double scale, Point o, Point u, Point v ) { FloatBuffer tcBuf; float x,y,a,b; final float ox = (float)scale*o.getXf(); final float oy = (float)scale*o.getYf(); final float ux = (float)scale*u.getXf(); final float uy = (float)scale*u.getYf(); final float vx = (float)scale*v.getXf(); final float vy = (float)scale*v.getYf(); final float vCu = (vx*uy-vy*ux); final boolean doX = Math.abs( ux ) > Math.abs( uy ); tcBuf = prepareTextureCoordinateBuffer(mesh,0,2*3*triangles.size()); tcBuf.rewind(); for( DelaunayTriangle t : triangles ) { for( int i=0; i<3; i++ ) { x = t.points[i].getXf()-ox; y = t.points[i].getYf()-oy; // Calculate the texture coordinate in the UV plane a = (uy*x - ux*y)/vCu; if( doX ) { b = (x - a*vx)/ux; } else { b = (y - a*vy)/uy; } tcBuf.put( a ); tcBuf.put( b ); } } } // FloatBuffer vBuf,tcBuf; // float width,maxX,minX,maxY,minY,x,y,xn,yn; // // maxX = Float.NEGATIVE_INFINITY; // minX = Float.POSITIVE_INFINITY; // maxY = Float.NEGATIVE_INFINITY; // minY = Float.POSITIVE_INFINITY; // // vBuf = mesh.getMeshData().getVertexBuffer(); // for( int i=0; i < vBuf.limit()-1; i+=3 ) // { // x = vBuf.get(i); // y = vBuf.get(i+1); // // maxX = x > maxX ? x : maxX; // minX = x < minX ? x : minX; // maxY = y > maxY ? y : maxY; // minY = y < minY ? x : minY; // } // // width = maxX-minX > maxY-minY ? maxX-minX : maxY-minY; // width *= scale; // // vBuf = mesh.getMeshData().getVertexBuffer(); // tcBuf = prepareTextureCoordinateBuffer(mesh,0,2*vBuf.limit()/3); // tcBuf.rewind(); // // for( int i=0; i < vBuf.limit()-1; i+=3 ) // { // x = vBuf.get(i)-(maxX-minX)/2; // y = vBuf.get(i+1)-(maxY-minY)/2; // xn = (float)(x*Math.cos(angle)-y*Math.sin(angle)); // yn = (float)(y*Math.cos(angle)+x*Math.sin(angle)); // tcBuf.put( xn/width ); // tcBuf.put( yn/width ); // } public static void updateTriangleMesh( Mesh mesh, PointSet ps, CoordinateTransform pc ) { updateTriangleMesh( mesh, ps.getTriangles(), pc ); } /** * Will populate a given Mesh's vertex,index buffer and set IndexMode.Triangles<br> * Will also increase buffer sizes if needed by creating new buffers. * * @param mesh * @param ps */ public static void updateTriangleMesh( Mesh mesh, PointSet ps ) { updateTriangleMesh( mesh, ps.getTriangles() ); } public static void updateTriangleMesh( Mesh mesh, Polygon p ) { updateTriangleMesh( mesh, p.getTriangles() ); } public static void updateTriangleMesh( Mesh mesh, Polygon p, CoordinateTransform pc ) { updateTriangleMesh( mesh, p.getTriangles(), pc ); } public static void updateVertexBuffer( Mesh mesh, List<? extends Point> list ) { FloatBuffer vertBuf; int size = 3*list.size(); prepareVertexBuffer( mesh, size ); if( size == 0 ) { return; } vertBuf = mesh.getMeshData().getVertexBuffer(); vertBuf.rewind(); for( Point p : list ) { vertBuf.put(p.getXf()).put(p.getYf()).put(p.getZf()); } } public static void updateIndexBuffer( Mesh mesh, int[] index ) { IntBuffer indexBuf; if( index == null || index.length == 0 ) { return; } int size = index.length; prepareIndexBuffer( mesh, size ); indexBuf = mesh.getMeshData().getIndexBuffer(); indexBuf.rewind(); for( int i=0; i<size; i+=2 ) { indexBuf.put(index[i]).put( index[i+1] ); } } private static void prepareVertexBuffer( Mesh mesh, int size ) { FloatBuffer vertBuf; vertBuf = mesh.getMeshData().getVertexBuffer(); if( vertBuf == null || vertBuf.capacity() < size ) { vertBuf = BufferUtils.createFloatBuffer( size ); mesh.getMeshData().setVertexBuffer( vertBuf ); } else { vertBuf.limit( size ); mesh.getMeshData().updateVertexCount(); } } private static void prepareNormalBuffer( Mesh mesh, int size ) { FloatBuffer nBuf; nBuf = mesh.getMeshData().getNormalBuffer(); if( nBuf == null || nBuf.capacity() < size ) { nBuf = BufferUtils.createFloatBuffer( size ); mesh.getMeshData().setNormalBuffer( nBuf ); } else { nBuf.limit( size ); } } private static void prepareIndexBuffer( Mesh mesh, int size) { IntBuffer indexBuf = mesh.getMeshData().getIndexBuffer(); if( indexBuf == null || indexBuf.capacity() < size ) { indexBuf = BufferUtils.createIntBuffer( size ); mesh.getMeshData().setIndexBuffer( indexBuf ); } else { indexBuf.limit( size ); } } private static FloatBuffer prepareTextureCoordinateBuffer( Mesh mesh, int index, int size ) { FloatBuffer tcBuf; tcBuf = mesh.getMeshData().getTextureBuffer( index ); if( tcBuf == null || tcBuf.capacity() < size ) { tcBuf = BufferUtils.createFloatBuffer( size ); mesh.getMeshData().setTextureBuffer( tcBuf, index ); } else { tcBuf.limit( size ); } return tcBuf; } }
Java
package org.poly2tri.polygon.ardor3d; import java.util.ArrayList; import org.poly2tri.geometry.polygon.Polygon; import org.poly2tri.triangulation.point.ardor3d.ArdorVector3Point; import org.poly2tri.triangulation.point.ardor3d.ArdorVector3PolygonPoint; import com.ardor3d.math.Vector3; public class ArdorPolygon extends Polygon { public ArdorPolygon( Vector3[] points ) { super( ArdorVector3PolygonPoint.toPoints( points ) ); } public ArdorPolygon( ArrayList<Vector3> points ) { super( ArdorVector3PolygonPoint.toPoints( points ) ); } }
Java
package org.poly2tri.examples.ardor3d; import java.util.ArrayList; import org.poly2tri.Poly2Tri; import org.poly2tri.examples.ardor3d.base.P2TSimpleExampleBase; import org.poly2tri.geometry.polygon.Polygon; import org.poly2tri.geometry.polygon.PolygonPoint; import org.poly2tri.triangulation.tools.ardor3d.ArdorMeshMapper; import com.ardor3d.framework.FrameHandler; import com.ardor3d.input.logical.LogicalLayer; import com.ardor3d.math.ColorRGBA; import com.ardor3d.renderer.state.WireframeState; import com.ardor3d.scenegraph.Mesh; import com.ardor3d.scenegraph.Node; import com.google.inject.Inject; public class CDTHoleExample extends P2TSimpleExampleBase { public static void main(final String[] args) { start(CDTHoleExample.class); } @Inject public CDTHoleExample( LogicalLayer logicalLayer, FrameHandler frameHandler ) { super( logicalLayer, frameHandler ); } @Override protected void initExample() { super.initExample(); Node node = new Node(); node.setRenderState( new WireframeState() ); _node.attachChild( node ); Polygon circle; Polygon hole; circle = createCirclePolygon( 64, 25, 1 ); hole = createCirclePolygon( 32, 25, 0.25, -0.5, -0.5 ); circle.addHole( hole ); hole = createCirclePolygon( 64, 25, 0.5, 0.25, 0.25 ); circle.addHole( hole ); Mesh mesh = new Mesh(); mesh.setDefaultColor( ColorRGBA.RED ); mesh.setTranslation( 0, 0, 0.01 ); node.attachChild( mesh ); Mesh mesh2 = new Mesh(); mesh2.setDefaultColor( ColorRGBA.BLUE ); _node.attachChild( mesh2 ); Poly2Tri.triangulate( circle ); ArdorMeshMapper.updateTriangleMesh( mesh, circle ); ArdorMeshMapper.updateTriangleMesh( mesh2, circle ); } private Polygon createCirclePolygon( int n, double scale, double radius ) { return createCirclePolygon( n, scale, radius, 0, 0 ); } private Polygon createCirclePolygon( int n, double scale, double radius, double x, double y ) { if( n < 3 ) n=3; PolygonPoint[] points = new PolygonPoint[n]; for( int i=0; i<n; i++ ) { points[i] = new PolygonPoint( scale*(x + radius*Math.cos( (2.0*Math.PI*i)/n )), scale*(y + radius*Math.sin( (2.0*Math.PI*i)/n ) )); } return new Polygon( points ); } }
Java
package org.poly2tri.examples.ardor3d.base; import java.net.URISyntaxException; import org.lwjgl.opengl.Display; import com.ardor3d.example.ExampleBase; import com.ardor3d.framework.FrameHandler; import com.ardor3d.image.Texture; import com.ardor3d.image.Image.Format; import com.ardor3d.input.logical.LogicalLayer; import com.ardor3d.renderer.queue.RenderBucketType; import com.ardor3d.renderer.state.BlendState; import com.ardor3d.renderer.state.TextureState; import com.ardor3d.renderer.state.WireframeState; import com.ardor3d.scenegraph.Node; import com.ardor3d.scenegraph.hint.LightCombineMode; import com.ardor3d.scenegraph.shape.Quad; import com.ardor3d.util.TextureManager; import com.ardor3d.util.resource.ResourceLocatorTool; import com.ardor3d.util.resource.SimpleResourceLocator; import com.google.inject.Inject; public abstract class P2TSimpleExampleBase extends ExampleBase { protected Node _node; protected Quad _logotype; protected int _width,_height; @Inject public P2TSimpleExampleBase( LogicalLayer logicalLayer, FrameHandler frameHandler ) { super( logicalLayer, frameHandler ); } @Override protected void initExample() { _canvas.setVSyncEnabled( true ); _canvas.getCanvasRenderer().getCamera().setLocation(0, 0, 65); _width = Display.getDisplayMode().getWidth(); _height = Display.getDisplayMode().getHeight(); _root.getSceneHints().setLightCombineMode( LightCombineMode.Off ); _node = new Node(); _node.getSceneHints().setLightCombineMode( LightCombineMode.Off ); // _node.setRenderState( new WireframeState() ); _root.attachChild( _node ); try { SimpleResourceLocator srl = new SimpleResourceLocator(ExampleBase.class.getClassLoader().getResource("org/poly2tri/examples/data/")); ResourceLocatorTool.addResourceLocator(ResourceLocatorTool.TYPE_MODEL, srl); SimpleResourceLocator sr2 = new SimpleResourceLocator(ExampleBase.class.getClassLoader().getResource("org/poly2tri/examples/textures/")); ResourceLocatorTool.addResourceLocator(ResourceLocatorTool.TYPE_TEXTURE, sr2); } catch (final URISyntaxException ex) { ex.printStackTrace(); } _logotype = new Quad("box", 128, 128 ); _logotype.setTranslation( 74, _height - 74, 0 ); _logotype.getSceneHints().setRenderBucketType( RenderBucketType.Ortho ); BlendState bs = new BlendState(); bs.setBlendEnabled( true ); bs.setEnabled( true ); bs.setSourceFunction(BlendState.SourceFunction.SourceAlpha); bs.setDestinationFunction(BlendState.DestinationFunction.OneMinusSourceAlpha); _logotype.setRenderState( bs ); TextureState ts = new TextureState(); ts.setEnabled(true); ts.setTexture(TextureManager.load("poly2tri_logotype_256x256.png", Texture.MinificationFilter.Trilinear, Format.GuessNoCompression, true)); _logotype.setRenderState(ts); _root.attachChild( _logotype ); } }
Java
package org.poly2tri.examples.ardor3d.base; import java.nio.FloatBuffer; import java.util.List; import org.poly2tri.geometry.polygon.PolygonSet; import org.poly2tri.triangulation.TriangulationAlgorithm; import org.poly2tri.triangulation.TriangulationPoint; import org.poly2tri.triangulation.TriangulationProcess; import org.poly2tri.triangulation.delaunay.DelaunayTriangle; import org.poly2tri.triangulation.delaunay.sweep.DTSweepContext; import org.poly2tri.triangulation.tools.ardor3d.ArdorMeshMapper; import com.ardor3d.framework.Canvas; import com.ardor3d.framework.FrameHandler; import com.ardor3d.input.Key; import com.ardor3d.input.logical.InputTrigger; import com.ardor3d.input.logical.KeyPressedCondition; import com.ardor3d.input.logical.LogicalLayer; import com.ardor3d.input.logical.TriggerAction; import com.ardor3d.input.logical.TwoInputStates; import com.ardor3d.math.ColorRGBA; import com.ardor3d.math.Vector3; import com.ardor3d.renderer.IndexMode; import com.ardor3d.renderer.queue.RenderBucketType; import com.ardor3d.renderer.state.WireframeState; import com.ardor3d.scenegraph.Mesh; import com.ardor3d.scenegraph.MeshData; import com.ardor3d.scenegraph.Node; import com.ardor3d.scenegraph.Point; import com.ardor3d.scenegraph.hint.LightCombineMode; import com.ardor3d.ui.text.BasicText; import com.ardor3d.util.ReadOnlyTimer; import com.ardor3d.util.geom.BufferUtils; public abstract class P2TExampleBase extends P2TSimpleExampleBase { protected TriangulationProcess _process; protected CDTSweepMesh _cdtSweepMesh; protected CDTSweepPoints _cdtSweepPoints; protected PolygonSet _polygonSet; private long _processTimestamp; /** Text fields used to present info about the example. */ protected final BasicText _exampleInfo[] = new BasicText[7]; public P2TExampleBase( LogicalLayer logicalLayer, FrameHandler frameHandler ) { super( logicalLayer, frameHandler ); } @Override protected void initExample() { super.initExample(); // Warmup the triangulation code for better performance // when we need triangulation during runtime // Poly2Tri.warmup(); _process = new TriangulationProcess(TriangulationAlgorithm.DTSweep); _cdtSweepPoints = new CDTSweepPoints(); _cdtSweepMesh = new CDTSweepMesh(); _node.attachChild( _cdtSweepPoints.getSceneNode() ); _node.attachChild( _cdtSweepMesh.getSceneNode() ); final Node textNodes = new Node("Text"); textNodes.getSceneHints().setRenderBucketType(RenderBucketType.Ortho); textNodes.getSceneHints().setLightCombineMode(LightCombineMode.Off); _root.attachChild( textNodes ); for (int i = 0; i < _exampleInfo.length; i++) { _exampleInfo[i] = BasicText.createDefaultTextLabel("Text", "", 16); _exampleInfo[i].setTranslation(new Vector3(10, (_exampleInfo.length-i-1) * 20 + 10, 0)); textNodes.attachChild(_exampleInfo[i]); } updateText(); } protected DTSweepContext getContext() { return (DTSweepContext)_process.getContext(); } /** * Update text information. */ protected void updateText() { _exampleInfo[0].setText(""); _exampleInfo[1].setText("[Home] Toggle wireframe"); _exampleInfo[2].setText("[End] Toggle vertex points"); } @Override protected void updateExample(final ReadOnlyTimer timer) { if( _process.isDone() && _processTimestamp != _process.getTimestamp() ) { _processTimestamp = _process.getTimestamp(); updateMesh(); _exampleInfo[0].setText("[" + _process.getTriangulationTime() + "ms] " + _process.getPointCount() + " points" ); } } public void exit() { super.exit(); _process.shutdown(); } protected void triangulate() { _process.triangulate( _polygonSet ); } protected void updateMesh() { if( _process.getContext().getTriangulatable() != null ) { if( _process.getContext().isDebugEnabled() ) { if( _process.isDone() ) { _cdtSweepMesh.update( _process.getContext().getTriangulatable().getTriangles() ); _cdtSweepPoints.update( _process.getContext().getTriangulatable().getPoints() ); } else { _cdtSweepMesh.update( _process.getContext().getTriangles() ); _cdtSweepPoints.update( _process.getContext().getPoints() ); } } else { _cdtSweepMesh.update( _polygonSet.getPolygons().get(0).getTriangles() ); _cdtSweepPoints.update( _polygonSet.getPolygons().get(0).getPoints() ); } } } @Override public void registerInputTriggers() { super.registerInputTriggers(); _controlHandle.setMoveSpeed( 10 ); // HOME - toogleWireframe _logicalLayer.registerTrigger( new InputTrigger( new KeyPressedCondition( Key.HOME ), new TriggerAction() { public void perform( final Canvas canvas, final TwoInputStates inputState, final double tpf ) { _cdtSweepMesh.toogleWireframe(); } } ) ); // END - tooglePoints _logicalLayer.registerTrigger( new InputTrigger( new KeyPressedCondition( Key.END ), new TriggerAction() { public void perform( final Canvas canvas, final TwoInputStates inputState, final double tpf ) { _cdtSweepPoints.toogleVisibile(); } } ) ); } protected abstract class SceneElement<A> { protected Node _node; public SceneElement(String name) { _node = new Node(name); _node.getSceneHints().setAllPickingHints( false ); } public abstract void update( A element ); public Node getSceneNode() { return _node; } } protected class CDTSweepPoints extends SceneElement<List<TriangulationPoint>> { private Point m_point = new Point(); private boolean _pointsVisible = true; public CDTSweepPoints() { super("Mesh"); m_point.setDefaultColor( ColorRGBA.RED ); m_point.setPointSize( 1 ); m_point.setTranslation( 0, 0, 0.01 ); _node.attachChild( m_point ); MeshData md = m_point.getMeshData(); int size = 1000; FloatBuffer vertBuf = BufferUtils.createFloatBuffer( (int)size*3 ); md.setVertexBuffer( vertBuf ); } public void toogleVisibile() { if( _pointsVisible ) { m_point.removeFromParent(); _pointsVisible = false; } else { _node.attachChild( m_point ); _pointsVisible = true; } } @Override public void update( List<TriangulationPoint> list ) { ArdorMeshMapper.updateVertexBuffer( m_point, list ); } } protected class CDTSweepMesh extends SceneElement<List<DelaunayTriangle>> { private Mesh m_mesh = new Mesh(); private WireframeState _ws = new WireframeState(); public CDTSweepMesh() { super("Mesh"); MeshData md; m_mesh.setDefaultColor( ColorRGBA.BLUE ); m_mesh.setRenderState( _ws ); _node.attachChild( m_mesh ); md = m_mesh.getMeshData(); int size = 1000; FloatBuffer vertBuf = BufferUtils.createFloatBuffer( (int)size*3*3 ); md.setVertexBuffer( vertBuf ); md.setIndexMode( IndexMode.Triangles ); } public void toogleWireframe() { if( _ws.isEnabled() ) { _ws.setEnabled( false ); } else { _ws.setEnabled( true ); } } @Override public void update( List<DelaunayTriangle> triangles ) { ArdorMeshMapper.updateTriangleMesh( m_mesh, triangles ); } } }
Java
package org.poly2tri.examples.ardor3d.misc; public enum ExampleModels { Test ("test.dat",1,0,0,true), Two ("2.dat",1,0,0,true), Debug ("debug.dat",1,0,0,false), Debug2 ("debug2.dat",1,0,0,false), Bird ("bird.dat",1,0,0,false), Custom ("funny.dat",1,0,0,false), Diamond ("diamond.dat",1,0,0,false), Dude ("dude.dat",1,-0.1,0,true), Nazca_heron ("nazca_heron.dat",1.3,0,0.35,false), Nazca_monkey ("nazca_monkey.dat",1,0,0,false), Star ("star.dat",1,0,0,false), Strange ("strange.dat",1,0,0,true), Tank ("tank.dat",1.3,0,0,true); private final static String m_basePath = "org/poly2tri/examples/data/"; private String m_filename; private double m_scale; private double m_x; private double m_y; private boolean _invertedYAxis; ExampleModels( String filename, double scale, double x, double y, boolean invertedY ) { m_filename = filename; m_scale = scale; m_x = x; m_y = y; _invertedYAxis = invertedY; } public String getFilename() { return m_basePath + m_filename; } public double getScale() { return m_scale; } public double getX() { return m_x; } public double getY() { return m_y; } public boolean invertedYAxis() { return _invertedYAxis; } }
Java
/** * Copyright (c) 2008-2009 Ardor Labs, Inc. * * This file is part of Ardor3D. * * Ardor3D is free software: you can redistribute it and/or modify it * under the terms of its license which may be found in the accompanying * LICENSE file or at <http://www.ardor3d.com/LICENSE>. */ package org.poly2tri.examples.ardor3d.misc; import java.nio.FloatBuffer; import com.ardor3d.math.Vector3; import com.ardor3d.math.type.ReadOnlyVector3; import com.ardor3d.scenegraph.Mesh; import com.ardor3d.util.geom.BufferUtils; public class Triangle extends Mesh { private static final long serialVersionUID = 1L; public Triangle() { this( "Triangle" ); } public Triangle(final String name ) { this( name, new Vector3( Math.cos( Math.toRadians( 90 ) ), Math.sin( Math.toRadians( 90 ) ), 0 ), new Vector3( Math.cos( Math.toRadians( 210 ) ), Math.sin( Math.toRadians( 210 ) ), 0 ), new Vector3( Math.cos( Math.toRadians( 330 ) ), Math.sin( Math.toRadians( 330 ) ), 0 )); } public Triangle(final String name, ReadOnlyVector3 a, ReadOnlyVector3 b, ReadOnlyVector3 c ) { super(name); initialize(a,b,c); } /** * <code>resize</code> changes the width and height of the given quad by altering its vertices. * * @param width * the new width of the <code>Quad</code>. * @param height * the new height of the <code>Quad</code>. */ // public void resize( double radius ) // { // _meshData.getVertexBuffer().clear(); // _meshData.getVertexBuffer().put((float) (-width / 2)).put((float) (height / 2)).put(0); // _meshData.getVertexBuffer().put((float) (-width / 2)).put((float) (-height / 2)).put(0); // _meshData.getVertexBuffer().put((float) (width / 2)).put((float) (-height / 2)).put(0); // _meshData.getVertexBuffer().put((float) (width / 2)).put((float) (height / 2)).put(0); // } /** * <code>initialize</code> builds the data for the <code>Quad</code> object. * * @param width * the width of the <code>Quad</code>. * @param height * the height of the <code>Quad</code>. */ private void initialize(ReadOnlyVector3 a, ReadOnlyVector3 b, ReadOnlyVector3 c ) { final int verts = 3; _meshData.setVertexBuffer(BufferUtils.createVector3Buffer(3)); _meshData.setNormalBuffer(BufferUtils.createVector3Buffer(3)); final FloatBuffer tbuf = BufferUtils.createVector2Buffer(3); _meshData.setTextureBuffer(tbuf, 0); _meshData.setIndexBuffer(BufferUtils.createIntBuffer(3)); Vector3 ba = Vector3.fetchTempInstance(); Vector3 ca = Vector3.fetchTempInstance(); ba.set( b ).subtractLocal( a ); ca.set( c ).subtractLocal( a ); ba.crossLocal( ca ).normalizeLocal(); _meshData.getNormalBuffer().put(ba.getXf()).put(ba.getYf()).put(ba.getZf()); _meshData.getNormalBuffer().put(ba.getXf()).put(ba.getYf()).put(ba.getZf()); _meshData.getNormalBuffer().put(ba.getXf()).put(ba.getYf()).put(ba.getZf()); Vector3.releaseTempInstance( ba ); Vector3.releaseTempInstance( ca ); tbuf.put(0).put(1); tbuf.put(0).put(0); tbuf.put(1).put(0); _meshData.getIndexBuffer().put(0); _meshData.getIndexBuffer().put(1); _meshData.getIndexBuffer().put(2); _meshData.getVertexBuffer().put(a.getXf()).put(a.getYf()).put(a.getZf()); _meshData.getVertexBuffer().put(b.getXf()).put(b.getYf()).put(b.getZf()); _meshData.getVertexBuffer().put(c.getXf()).put(c.getYf()).put(c.getZf()); } }
Java
package org.poly2tri.examples.ardor3d.misc; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.StringTokenizer; import org.poly2tri.geometry.polygon.Polygon; import org.poly2tri.polygon.ardor3d.ArdorPolygon; import org.poly2tri.triangulation.TriangulationPoint; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.ardor3d.math.Vector3; public class PolygonLoader { private final static Logger logger = LoggerFactory.getLogger( PolygonLoader.class ); public static Polygon loadModel( ExampleModels model, double scale ) throws FileNotFoundException, IOException { String line; ArrayList<Vector3> points = new ArrayList<Vector3>(); InputStream istream = PolygonLoader.class.getClassLoader().getResourceAsStream( model.getFilename() ); if( istream == null ) { throw new FileNotFoundException( "Couldn't find " + model ); } InputStreamReader ir = new InputStreamReader( istream ); BufferedReader reader = new BufferedReader( ir ); while( ( line = reader.readLine() ) != null ) { StringTokenizer tokens = new StringTokenizer( line, " ," ); points.add( new Vector3( Float.valueOf( tokens.nextToken() ).floatValue(), Float.valueOf( tokens.nextToken() ).floatValue(), 0f )); } if( points.isEmpty() ) { throw new IOException( "no data in file " + model ); } // Rescale models so they are centered at 0,0 and don't fall outside the // unit square double maxX, maxY, minX, minY; maxX = minX = points.get( 0 ).getX(); if( model.invertedYAxis() ) { maxY = minY = -points.get( 0 ).getY(); } else { maxY = minY = points.get( 0 ).getY(); } for( Vector3 p : points ) { if( model.invertedYAxis() ) { p.setY( -p.getY() ); } maxX = p.getX() > maxX ? p.getX() : maxX; maxY = p.getY() > maxY ? p.getY() : maxY; minX = p.getX() < minX ? p.getX() : minX; minY = p.getY() < minY ? p.getY() : minY; } double width, height, xScale, yScale; width = maxX - minX; height = maxY - minY; xScale = scale * 1f / width; yScale = scale * 1f / height; // System.out.println("scale/height=" + SCALE + "/" + height ); // System.out.println("scale=" + yScale); for( Vector3 p : points ) { if( model.invertedYAxis() ) { p.subtractLocal( maxX - width / 2, maxY - height / 2, 0 ); } else { p.subtractLocal( maxX - width / 2, maxY - height / 2, 0 ); } p.multiplyLocal( xScale < yScale ? xScale : yScale ); } return new ArdorPolygon( points); } public static void saveModel( String path, TriangulationPoint[] points ) { FileWriter writer = null; BufferedWriter w = null; String file = path+System.currentTimeMillis()+".dat"; try { writer = new FileWriter(file); w = new BufferedWriter(writer); for( TriangulationPoint p : points ) { w.write( Float.toString( p.getXf() ) +" "+ Float.toString( p.getYf() )); w.newLine(); } logger.info( "Saved polygon\n" + file ); } catch( IOException e ) { logger.error( "Failed to save model" ); } finally { if( w != null ) { try { w.close(); } catch( IOException e2 ) { } } } } /** * This is a very unoptimal dump of the triangles as absolute lines. * For manual importation to an SVG<br> * * @param path * @param ps */ // public static void saveTriLine( String path, PolygonSet ps ) // { // FileWriter writer = null; // BufferedWriter w = null; // String file = path+System.currentTimeMillis()+".tri"; // // if( ps.getTriangles() == null || ps.getTriangles().isEmpty() ) // { // return; // } // // try // { // // writer = new FileWriter(file); // w = new BufferedWriter(writer); // for( DelaunayTriangle t : ps.getTriangles() ) // { // for( int i=0; i<3; i++ ) // { // w.write( Float.toString( t.points[i].getXf() ) +","+ Float.toString( t.points[i].getYf() )+" "); // } //// w.newLine(); // } // logger.info( "Saved triangle lines\n" + file ); // } // catch( IOException e ) // { // logger.error( "Failed to save triangle lines" + e.getMessage() ); // } // finally // { // if( w != null ) // { // try // { // w.close(); // } // catch( IOException e2 ) // { // } // } // } // } }
Java
package org.poly2tri.examples.ardor3d.misc; public enum ExampleSets { Example1 ("example1.dat",1,0,0,true), Example2 ("example2.dat",1,0,0,true), Example3 ("example3.dat",1,0,0,false), Example4 ("example4.dat",1,0,0,false); private final static String m_basePath = "org/poly2tri/examples/data/pointsets/"; private String m_filename; private double m_scale; private double m_x; private double m_y; private boolean _invertedYAxis; ExampleSets( String filename, double scale, double x, double y, boolean invertedY ) { m_filename = filename; m_scale = scale; m_x = x; m_y = y; _invertedYAxis = invertedY; } public String getFilename() { return m_basePath + m_filename; } public double getScale() { return m_scale; } public double getX() { return m_x; } public double getY() { return m_y; } public boolean invertedYAxis() { return _invertedYAxis; } }
Java
package org.poly2tri.examples.ardor3d.misc; import org.poly2tri.triangulation.point.TPoint; public class MyPoint extends TPoint { int index; public MyPoint( double x, double y ) { super( x, y ); } public void setIndex(int i) { index = i; } public int getIndex() { return index; } public boolean equals(Object other) { if (!(other instanceof MyPoint)) return false; MyPoint p = (MyPoint)other; return getX() == p.getX() && getY() == p.getY(); } public int hashCode() { return (int)getX() + (int)getY(); } }
Java
package org.poly2tri.examples.ardor3d.misc; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.StringTokenizer; import org.poly2tri.geometry.polygon.Polygon; import org.poly2tri.geometry.polygon.PolygonSet; import org.poly2tri.polygon.ardor3d.ArdorPolygon; import org.poly2tri.triangulation.TriangulationPoint; import org.poly2tri.triangulation.delaunay.DelaunayTriangle; import org.poly2tri.triangulation.point.TPoint; import org.poly2tri.triangulation.sets.PointSet; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.ardor3d.math.Vector3; public class DataLoader { private final static Logger logger = LoggerFactory.getLogger( DataLoader.class ); public static Polygon loadModel( ExampleModels model, double scale ) throws FileNotFoundException, IOException { String line; ArrayList<Vector3> points = new ArrayList<Vector3>(); InputStream istream = DataLoader.class.getClassLoader().getResourceAsStream( model.getFilename() ); if( istream == null ) { throw new FileNotFoundException( "Couldn't find " + model ); } InputStreamReader ir = new InputStreamReader( istream ); BufferedReader reader = new BufferedReader( ir ); while( ( line = reader.readLine() ) != null ) { StringTokenizer tokens = new StringTokenizer( line, " ," ); points.add( new Vector3( Double.valueOf( tokens.nextToken() ).doubleValue(), Double.valueOf( tokens.nextToken() ).doubleValue(), 0f )); } if( points.isEmpty() ) { throw new IOException( "no data in file " + model ); } // Rescale models so they are centered at 0,0 and don't fall outside the // unit square double maxX, maxY, minX, minY; maxX = minX = points.get( 0 ).getX(); if( model.invertedYAxis() ) { maxY = minY = -points.get( 0 ).getY(); } else { maxY = minY = points.get( 0 ).getY(); } for( Vector3 p : points ) { if( model.invertedYAxis() ) { p.setY( -p.getY() ); } maxX = p.getX() > maxX ? p.getX() : maxX; maxY = p.getY() > maxY ? p.getY() : maxY; minX = p.getX() < minX ? p.getX() : minX; minY = p.getY() < minY ? p.getY() : minY; } double width, height, xScale, yScale; width = maxX - minX; height = maxY - minY; xScale = scale * 1f / width; yScale = scale * 1f / height; // System.out.println("scale/height=" + SCALE + "/" + height ); // System.out.println("scale=" + yScale); for( Vector3 p : points ) { if( model.invertedYAxis() ) { p.subtractLocal( maxX - width / 2, maxY - height / 2, 0 ); } else { p.subtractLocal( maxX - width / 2, maxY - height / 2, 0 ); } p.multiplyLocal( xScale < yScale ? xScale : yScale ); } return new ArdorPolygon( points); } public static PointSet loadPointSet( ExampleSets set, double scale ) throws FileNotFoundException, IOException { String line; ArrayList<TriangulationPoint> points = new ArrayList<TriangulationPoint>(); InputStream istream = DataLoader.class.getClassLoader().getResourceAsStream( set.getFilename() ); if( istream == null ) { throw new FileNotFoundException( "Couldn't find " + set ); } InputStreamReader ir = new InputStreamReader( istream ); BufferedReader reader = new BufferedReader( ir ); while( ( line = reader.readLine() ) != null ) { StringTokenizer tokens = new StringTokenizer( line, " ," ); points.add( new TPoint( scale*Float.valueOf( tokens.nextToken() ).floatValue(), scale*Float.valueOf( tokens.nextToken() ).floatValue() )); } if( points.isEmpty() ) { throw new IOException( "no data in file " + set ); } // Rescale models so they are centered at 0,0 and don't fall outside the // unit square // double maxX, maxY, minX, minY; // maxX = minX = points.get( 0 ).getX(); // if( set.invertedYAxis() ) // { // maxY = minY = -points.get( 0 ).getY(); // } // else // { // maxY = minY = points.get( 0 ).getY(); // } // for( TPoint p : points ) // { // if( set.invertedYAxis() ) // { // p.setY( -p.getY() ); // } // maxX = p.getX() > maxX ? p.getX() : maxX; // maxY = p.getY() > maxY ? p.getY() : maxY; // minX = p.getX() < minX ? p.getX() : minX; // minY = p.getY() < minY ? p.getY() : minY; // } // // double width, height, xScale, yScale; // width = maxX - minX; // height = maxY - minY; // xScale = scale * 1f / width; // yScale = scale * 1f / height; // // // System.out.println("scale/height=" + SCALE + "/" + height ); // // System.out.println("scale=" + yScale); // // for( TPoint p : points ) // { // if( set.invertedYAxis() ) // { // p.subtractLocal( maxX - width / 2, maxY - height / 2, 0 ); // } // else // { // p.subtractLocal( maxX - width / 2, maxY - height / 2, 0 ); // } // p.multiplyLocal( xScale < yScale ? xScale : yScale ); // } return new PointSet( points ); } public static void saveModel( String path, TriangulationPoint[] points ) { FileWriter writer = null; BufferedWriter w = null; String file = path+System.currentTimeMillis()+".dat"; try { writer = new FileWriter(file); w = new BufferedWriter(writer); for( TriangulationPoint p : points ) { w.write( Float.toString( p.getXf() ) +" "+ Float.toString( p.getYf() )); w.newLine(); } logger.info( "Saved polygon\n" + file ); } catch( IOException e ) { logger.error( "Failed to save model" ); } finally { if( w != null ) { try { w.close(); } catch( IOException e2 ) { } } } } /** * This is a very unoptimal dump of the triangles as absolute lines. * For manual importation to an SVG<br> * * @param path * @param ps */ public static void saveTriLine( String path, PolygonSet ps ) { FileWriter writer = null; BufferedWriter w = null; String file = path+System.currentTimeMillis()+".tri"; if( ps.getPolygons() == null || ps.getPolygons().isEmpty() ) { return; } try { writer = new FileWriter(file); w = new BufferedWriter(writer); for( DelaunayTriangle t : ps.getPolygons().get(0).getTriangles() ) { for( int i=0; i<3; i++ ) { w.write( Float.toString( t.points[i].getXf() ) +","+ Float.toString( t.points[i].getYf() )+" "); } // w.newLine(); } logger.info( "Saved triangle lines\n" + file ); } catch( IOException e ) { logger.error( "Failed to save triangle lines" + e.getMessage() ); } finally { if( w != null ) { try { w.close(); } catch( IOException e2 ) { } } } } }
Java
/* Poly2Tri * Copyright (c) 2009-2010, Poly2Tri Contributors * http://code.google.com/p/poly2tri/ * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Poly2Tri nor the names of its contributors may be * used to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.poly2tri.examples.ardor3d; import java.io.IOException; import java.nio.FloatBuffer; import java.util.ArrayList; import java.util.List; import org.poly2tri.examples.ardor3d.base.P2TExampleBase; import org.poly2tri.examples.ardor3d.misc.DataLoader; import org.poly2tri.examples.ardor3d.misc.ExampleModels; import org.poly2tri.examples.ardor3d.misc.Triangle; import org.poly2tri.geometry.polygon.Polygon; import org.poly2tri.geometry.polygon.PolygonSet; import org.poly2tri.triangulation.TriangulationPoint; import org.poly2tri.triangulation.delaunay.DelaunayTriangle; import org.poly2tri.triangulation.delaunay.sweep.AdvancingFront; import org.poly2tri.triangulation.delaunay.sweep.AdvancingFrontNode; import org.poly2tri.triangulation.delaunay.sweep.DTSweepConstraint; import org.poly2tri.triangulation.delaunay.sweep.DTSweepContext; import org.poly2tri.triangulation.point.TPoint; import org.poly2tri.triangulation.sets.ConstrainedPointSet; import org.poly2tri.triangulation.sets.PointSet; import org.poly2tri.triangulation.util.PolygonGenerator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.ardor3d.framework.Canvas; import com.ardor3d.framework.FrameHandler; import com.ardor3d.input.Key; import com.ardor3d.input.logical.InputTrigger; import com.ardor3d.input.logical.KeyPressedCondition; import com.ardor3d.input.logical.LogicalLayer; import com.ardor3d.input.logical.TriggerAction; import com.ardor3d.input.logical.TwoInputStates; import com.ardor3d.math.ColorRGBA; import com.ardor3d.renderer.IndexMode; import com.ardor3d.renderer.state.WireframeState; import com.ardor3d.scenegraph.Line; import com.ardor3d.scenegraph.Point; import com.ardor3d.util.ReadOnlyTimer; import com.ardor3d.util.geom.BufferUtils; import com.google.inject.Inject; /** * Toggle Model with PageUp and PageDown<br> * Toggle Wireframe with Home<br> * Toggle Vertex points with End<br> * Use 1 and 2 to generate random polygons<br> * * @author Thomas * */ public class CDTModelExample extends P2TExampleBase { private final static Logger logger = LoggerFactory.getLogger( CDTModelExample.class ); private ExampleModels m_currentModel = ExampleModels.Two; private static double SCALE = 50; private Line m_line; // Build parameters private int m_vertexCount = 10000; // Scene components private CDTSweepAdvancingFront _cdtSweepAdvancingFront; private CDTSweepActiveNode _cdtSweepActiveNode; private CDTSweepActiveTriangles _cdtSweepActiveTriangle; private CDTSweepActiveEdge _cdtSweepActiveEdge; // private GUICircumCircle m_circumCircle; private int m_stepCount = 0; private boolean m_autoStep = true; private final String m_dataPath = "src/main/resources/org/poly2tri/examples/data/"; public static void main(final String[] args) { start(CDTModelExample.class); } @Inject public CDTModelExample( LogicalLayer logicalLayer, FrameHandler frameHandler ) { super( logicalLayer, frameHandler ); } protected void updateExample(final ReadOnlyTimer timer) { super.updateExample( timer ); if( getContext().isDebugEnabled() ) { int count = _process.getStepCount(); if( m_stepCount < count ) { _process.requestRead(); if( _process.isReadable() ) { updateMesh(); m_stepCount = count; if( m_autoStep ) { _process.resume(); } } } } } @Override protected void initExample() { super.initExample(); // getContext().isDebugEnabled( true ); if( getContext().isDebugEnabled() ) { _cdtSweepAdvancingFront = new CDTSweepAdvancingFront(); _node.attachChild( _cdtSweepAdvancingFront.getSceneNode() ); _cdtSweepActiveNode = new CDTSweepActiveNode(); _node.attachChild( _cdtSweepActiveNode.getSceneNode() ); _cdtSweepActiveTriangle = new CDTSweepActiveTriangles(); _node.attachChild( _cdtSweepActiveTriangle.getSceneNode() ); _cdtSweepActiveEdge = new CDTSweepActiveEdge(); _node.attachChild( _cdtSweepActiveEdge.getSceneNode() ); // m_circumCircle = new GUICircumCircle(); // m_node.attachChild( m_circumCircle.getSceneNode() ); } buildModel(m_currentModel); triangulate(); } /** * Update text information. */ protected void updateText() { super.updateText(); _exampleInfo[3].setText("[PageUp] Next model"); _exampleInfo[4].setText("[PageDown] Previous model"); _exampleInfo[5].setText("[1] Generate polygon type A "); _exampleInfo[6].setText("[2] Generate polygon type B "); } private void buildModel( ExampleModels model ) { Polygon poly; if( model != null ) { try { poly = DataLoader.loadModel( model, SCALE ); _polygonSet = new PolygonSet( poly ); } catch( IOException e ) { logger.info( "Failed to load model {}", e.getMessage() ); model = null; } } if( model == null ) { _polygonSet = new PolygonSet( PolygonGenerator.RandomCircleSweep( SCALE, m_vertexCount ) ); } } private ConstrainedPointSet buildCustom() { ArrayList<TriangulationPoint> list = new ArrayList<TriangulationPoint>(20); int[] index; list.add( new TPoint(2.2715518,-4.5233157) ); list.add( new TPoint(3.4446202,-3.5232647) ); list.add( new TPoint(4.7215156,-4.5233157) ); list.add( new TPoint(6.0311967,-3.5232647) ); list.add( new TPoint(3.4446202,-7.2578132) ); list.add( new TPoint(.81390847,-3.5232647) ); index = new int[]{3,5}; return new ConstrainedPointSet( list, index ); } protected void triangulate() { super.triangulate(); m_stepCount = 0; } protected void updateMesh() { super.updateMesh(); DTSweepContext tcx = getContext(); if( tcx.isDebugEnabled() ) { _cdtSweepActiveTriangle.update( tcx ); _cdtSweepActiveEdge.update( tcx ); _cdtSweepActiveNode.update( tcx ); _cdtSweepAdvancingFront.update( tcx ); // m_circumCircle.update( tcx.getCircumCircle() ); } } @Override public void registerInputTriggers() { super.registerInputTriggers(); // SPACE - toggle models _logicalLayer.registerTrigger( new InputTrigger( new KeyPressedCondition( Key.PAGEUP_PRIOR ), new TriggerAction() { public void perform( final Canvas canvas, final TwoInputStates inputState, final double tpf ) { int index; index = (m_currentModel.ordinal()+1)%ExampleModels.values().length; m_currentModel = ExampleModels.values()[index]; buildModel(m_currentModel); _node.setScale( m_currentModel.getScale() ); triangulate(); } } ) ); // SPACE - toggle models backwards _logicalLayer.registerTrigger( new InputTrigger( new KeyPressedCondition( Key.PAGEDOWN_NEXT ), new TriggerAction() { public void perform( final Canvas canvas, final TwoInputStates inputState, final double tpf ) { int index; index = ((m_currentModel.ordinal()-1)%ExampleModels.values().length + ExampleModels.values().length)%ExampleModels.values().length; m_currentModel = ExampleModels.values()[index]; buildModel(m_currentModel); _node.setScale( m_currentModel.getScale() ); triangulate(); } } ) ); _logicalLayer.registerTrigger( new InputTrigger( new KeyPressedCondition( Key.ONE ), new TriggerAction() { public void perform( final Canvas canvas, final TwoInputStates inputState, final double tpf ) { _polygonSet = new PolygonSet( PolygonGenerator.RandomCircleSweep( SCALE, m_vertexCount ) ); triangulate(); } } ) ); _logicalLayer.registerTrigger( new InputTrigger( new KeyPressedCondition( Key.TWO ), new TriggerAction() { public void perform( final Canvas canvas, final TwoInputStates inputState, final double tpf ) { _polygonSet = new PolygonSet( PolygonGenerator.RandomCircleSweep2( SCALE, 200 ) ); triangulate(); } } ) ); // X -start _logicalLayer.registerTrigger( new InputTrigger( new KeyPressedCondition( Key.X ), new TriggerAction() { public void perform( final Canvas canvas, final TwoInputStates inputState, final double tpf ) { // Lets create a TriangulationProcess that allows you to step thru the TriangulationAlgorithm // _process.getContext().isDebugEnabled( true ); // _process.triangulate(); // m_stepCount = 0; } } ) ); // C - step _logicalLayer.registerTrigger( new InputTrigger( new KeyPressedCondition( Key.C ), new TriggerAction() { public void perform( final Canvas canvas, final TwoInputStates inputState, final double tpf ) { // updateMesh(); _process.resume(); } } ) ); // Z - toggle autostep _logicalLayer.registerTrigger( new InputTrigger( new KeyPressedCondition( Key.Z ), new TriggerAction() { public void perform( final Canvas canvas, final TwoInputStates inputState, final double tpf ) { m_autoStep = m_autoStep ? false : true; } } ) ); // space - save triangle lines _logicalLayer.registerTrigger( new InputTrigger( new KeyPressedCondition( Key.SPACE ), new TriggerAction() { public void perform( final Canvas canvas, final TwoInputStates inputState, final double tpf ) { // PolygonLoader.saveTriLine( m_dataPath, _polygonSet ); m_stepCount = 0; _process.triangulate( buildCustom() ); } } ) ); } class CDTSweepAdvancingFront extends SceneElement<DTSweepContext> { protected Line m_nodeLines; protected Point m_frontPoints; protected Line m_frontLine; public CDTSweepAdvancingFront() { super("AdvancingFront"); m_frontLine = new Line(); m_frontLine.getMeshData().setIndexMode( IndexMode.LineStrip ); m_frontLine.getMeshData().setVertexBuffer( BufferUtils.createVector3Buffer( 800 ) ); m_frontLine.setDefaultColor( ColorRGBA.ORANGE ); m_frontLine.setTranslation( 0, 0.05, 0 ); _node.attachChild( m_frontLine ); m_frontPoints = new Point(); m_frontPoints.getMeshData().setVertexBuffer( m_frontLine.getMeshData().getVertexBuffer() ); m_frontPoints.setPointSize( 6 ); m_frontPoints.setDefaultColor( ColorRGBA.ORANGE ); m_frontPoints.setTranslation( 0, 0.05, 0 ); _node.attachChild( m_frontPoints ); m_nodeLines = new Line(); m_nodeLines.getMeshData().setIndexMode( IndexMode.Lines ); m_nodeLines.getMeshData().setVertexBuffer( BufferUtils.createVector3Buffer( 2*800 ) ); m_nodeLines.setDefaultColor( ColorRGBA.YELLOW ); m_nodeLines.setTranslation( 0, 0.05, 0 ); _node.attachChild( m_nodeLines ); } @Override public void update( DTSweepContext tcx ) { AdvancingFront front = ((DTSweepContext)tcx).getAdvancingFront(); AdvancingFrontNode node; DelaunayTriangle tri; if( front == null ) return; FloatBuffer fb = m_frontLine.getMeshData().getVertexBuffer(); FloatBuffer nodeVert = m_nodeLines.getMeshData().getVertexBuffer(); fb.limit( fb.capacity() ); nodeVert.limit( fb.capacity() ); fb.rewind(); nodeVert.rewind(); int count=0; node = front.head; TriangulationPoint point; do { point = node.getPoint(); fb.put( point.getXf() ).put( point.getYf() ).put( point.getZf() ); tri = node.getTriangle(); if( tri != null ) { nodeVert.put( point.getXf() ).put( point.getYf() ).put( point.getZf() ); nodeVert.put( ( tri.points[0].getXf() + tri.points[1].getXf() + tri.points[2].getXf() )/3 ); nodeVert.put( ( tri.points[0].getYf() + tri.points[1].getYf() + tri.points[2].getYf() )/3 ); nodeVert.put( ( tri.points[0].getZf() + tri.points[1].getZf() + tri.points[2].getZf() )/3 ); } count++; } while( (node = node.getNext()) != null ); fb.limit( 3*count ); nodeVert.limit( 2*count*3 ); } } // class GUICircumCircle extends SceneElement<Tuple2<TriangulationPoint,Double>> // { // private int VCNT = 64; // private Line m_circle = new Line(); // // public GUICircumCircle() // { // super("CircumCircle"); // m_circle.getMeshData().setIndexMode( IndexMode.LineLoop ); // m_circle.getMeshData().setVertexBuffer( BufferUtils.createVector3Buffer( VCNT ) ); // m_circle.setDefaultColor( ColorRGBA.WHITE ); // m_circle.setLineWidth( 1 ); // m_node.attachChild( m_circle ); // } // // @Override // public void update( Tuple2<TriangulationPoint,Double> circle ) // { // float x,y; // if( circle.a != null ) // { // FloatBuffer fb = m_circle.getMeshData().getVertexBuffer(); // fb.rewind(); // for( int i=0; i < VCNT; i++ ) // { // x = (float)circle.a.getX() + (float)(circle.b*Math.cos( 2*Math.PI*((double)i%VCNT)/VCNT )); // y = (float)circle.a.getY() + (float)(circle.b*Math.sin( 2*Math.PI*((double)i%VCNT)/VCNT )); // fb.put( x ).put( y ).put( 0 ); // } // } // else // { // m_node.detachAllChildren(); // } // } // } class CDTSweepMeshExtended extends CDTSweepMesh { // private Line m_conLine = new Line(); public CDTSweepMeshExtended() { super(); // Line that show the connection between triangles // m_conLine.setDefaultColor( ColorRGBA.RED ); // m_conLine.getMeshData().setIndexMode( IndexMode.Lines ); // m_node.attachChild( m_conLine ); // // vertBuf = BufferUtils.createFloatBuffer( size*3*3*3 ); // m_conLine.getMeshData().setVertexBuffer( vertBuf ); } @Override public void update( List<DelaunayTriangle> triangles ) { super.update( triangles ); // MeshData md; // Vector3 v1 = Vector3.fetchTempInstance(); // Vector3 v2 = Vector3.fetchTempInstance(); // FloatBuffer v2Buf; // // // md = m_mesh.getMeshData(); // v2Buf = m_conLine.getMeshData().getVertexBuffer(); // //// logger.info( "Triangle count [{}]", tcx.getMap().size() ); // // int size = 2*3*3*ps.getTriangles().size(); // if( v2Buf.capacity() < size ) // { // v2Buf = BufferUtils.createFloatBuffer( size ); // m_conLine.getMeshData().setVertexBuffer( v2Buf ); // } // else // { // v2Buf.limit( 2*size ); // } // // v2Buf.rewind(); // int lineCount=0; // ArdorVector3Point p; // for( DelaunayTriangle t : ps.getTriangles() ) // { // v1.set( t.points[0] ).addLocal( t.points[1] ).addLocal( t.points[2] ).multiplyLocal( 1.0d/3 ); // if( t.neighbors[0] != null ) // { // v2.set( t.points[2] ).subtractLocal( t.points[1] ).multiplyLocal( 0.5 ).addLocal( t.points[1] ); // v2Buf.put( v1.getXf() ).put( v1.getYf() ).put( v1.getZf() ); // v2Buf.put( v2.getXf() ).put( v2.getYf() ).put( v2.getZf() ); // lineCount++; // } // if( t.neighbors[1] != null ) // { // v2.set( t.points[0] ).subtractLocal( t.points[2] ).multiplyLocal( 0.5 ).addLocal( t.points[2] ); // v2Buf.put( v1.getXf() ).put( v1.getYf() ).put( v1.getZf() ); // v2Buf.put( v2.getXf() ).put( v2.getYf() ).put( v2.getZf() ); // lineCount++; // } // if( t.neighbors[2] != null ) // { // v2.set( t.points[1] ).subtractLocal( t.points[0] ).multiplyLocal( 0.5 ).addLocal( t.points[0] ); // v2Buf.put( v1.getXf() ).put( v1.getYf() ).put( v1.getZf() ); // v2Buf.put( v2.getXf() ).put( v2.getYf() ).put( v2.getZf() ); // lineCount++; // } // } // v2Buf.limit( 2*3*lineCount ); // Vector3.releaseTempInstance( v1 ); // Vector3.releaseTempInstance( v2 ); } } class CDTSweepActiveEdge extends SceneElement<DTSweepContext> { private Line m_edgeLine = new Line(); public CDTSweepActiveEdge() { super("ActiveEdge"); m_edgeLine.getMeshData().setIndexMode( IndexMode.Lines ); m_edgeLine.getMeshData().setVertexBuffer( BufferUtils.createVector3Buffer( 2 ) ); m_edgeLine.setDefaultColor( ColorRGBA.YELLOW ); m_edgeLine.setLineWidth( 3 ); } @Override public void update( DTSweepContext tcx ) { DTSweepConstraint edge = tcx.getDebugContext().getActiveConstraint(); if( edge != null ) { FloatBuffer fb = m_edgeLine.getMeshData().getVertexBuffer(); fb.rewind(); fb.put( edge.getP().getXf() ).put( edge.getP().getYf() ).put( 0 ); fb.put( edge.getQ().getXf() ).put( edge.getQ().getYf() ).put( 0 ); _node.attachChild( m_edgeLine ); } else { _node.detachAllChildren(); } } } class CDTSweepActiveTriangles extends SceneElement<DTSweepContext> { private Triangle m_a = new Triangle(); private Triangle m_b = new Triangle(); public CDTSweepActiveTriangles() { super("ActiveTriangles"); _node.getSceneHints().setAllPickingHints( false ); m_a.setDefaultColor( new ColorRGBA( 0.8f,0.8f,0.8f,1.0f ) ); m_b.setDefaultColor( new ColorRGBA( 0.5f,0.5f,0.5f,1.0f ) ); } public void setScale( double scale ) { m_a.setScale( scale ); m_b.setScale( scale ); } @Override public void update( DTSweepContext tcx ) { DelaunayTriangle t,t2; t = tcx.getDebugContext().getPrimaryTriangle(); t2 = tcx.getDebugContext().getSecondaryTriangle(); _node.detachAllChildren(); if( t != null ) { FloatBuffer fb = m_a.getMeshData().getVertexBuffer(); fb.rewind(); fb.put( t.points[0].getXf() ).put( t.points[0].getYf() ).put( t.points[0].getZf() ); fb.put( t.points[1].getXf() ).put( t.points[1].getYf() ).put( t.points[1].getZf() ); fb.put( t.points[2].getXf() ).put( t.points[2].getYf() ).put( t.points[2].getZf() ); _node.attachChild( m_a ); } if( t2 != null ) { FloatBuffer fb = m_b.getMeshData().getVertexBuffer(); fb.rewind(); fb.put( t2.points[0].getXf() ).put( t2.points[0].getYf() ).put( t2.points[0].getZf() ); fb.put( t2.points[1].getXf() ).put( t2.points[1].getYf() ).put( t2.points[1].getZf() ); fb.put( t2.points[2].getXf() ).put( t2.points[2].getYf() ).put( t2.points[2].getZf() ); _node.attachChild( m_b ); } } } class CDTSweepActiveNode extends SceneElement<DTSweepContext> { private Triangle m_a = new Triangle(); private Triangle m_b = new Triangle(); private Triangle m_c = new Triangle(); public CDTSweepActiveNode() { super("WorkingNode"); _node.setRenderState( new WireframeState() ); m_a.setDefaultColor( ColorRGBA.DARK_GRAY ); m_b.setDefaultColor( ColorRGBA.LIGHT_GRAY ); m_c.setDefaultColor( ColorRGBA.DARK_GRAY ); setScale( 0.5 ); } public void setScale( double scale ) { m_a.setScale( scale ); m_b.setScale( scale ); m_c.setScale( scale ); } @Override public void update( DTSweepContext tcx ) { AdvancingFrontNode node = tcx.getDebugContext().getActiveNode(); TriangulationPoint p; if( node != null ) { if( node.getPrevious() != null ) { p = node.getPrevious().getPoint(); m_a.setTranslation( p.getXf(), p.getYf(), p.getZf() ); } p = node.getPoint(); m_b.setTranslation( p.getXf(), p.getYf(), p.getZf() ); if( node.getNext() != null ) { p = node.getNext().getPoint(); m_c.setTranslation( p.getXf(), p.getYf(), p.getZf() ); } _node.attachChild( m_a ); _node.attachChild( m_b ); _node.attachChild( m_c ); } else { _node.detachAllChildren(); } } } }
Java
package org.poly2tri.examples.ardor3d; import java.io.IOException; import java.util.ArrayList; import org.poly2tri.Poly2Tri; import org.poly2tri.examples.ardor3d.base.P2TSimpleExampleBase; import org.poly2tri.examples.ardor3d.misc.DataLoader; import org.poly2tri.examples.ardor3d.misc.ExampleSets; import org.poly2tri.triangulation.TriangulationAlgorithm; import org.poly2tri.triangulation.TriangulationContext; import org.poly2tri.triangulation.TriangulationPoint; import org.poly2tri.triangulation.point.TPoint; import org.poly2tri.triangulation.sets.PointSet; import org.poly2tri.triangulation.tools.ardor3d.ArdorMeshMapper; import org.poly2tri.triangulation.util.PointGenerator; import com.ardor3d.framework.FrameHandler; import com.ardor3d.input.logical.LogicalLayer; import com.ardor3d.math.ColorRGBA; import com.ardor3d.renderer.state.WireframeState; import com.ardor3d.scenegraph.Mesh; import com.google.inject.Inject; public class DTUniformDistributionExample extends P2TSimpleExampleBase { public static void main(final String[] args) { start(DTUniformDistributionExample.class); } @Inject public DTUniformDistributionExample( LogicalLayer logicalLayer, FrameHandler frameHandler ) { super( logicalLayer, frameHandler ); } @Override protected void initExample() { super.initExample(); PointSet ps; Mesh mesh; mesh = new Mesh(); mesh.setDefaultColor( ColorRGBA.BLUE ); mesh.setRenderState( new WireframeState() ); _node.attachChild( mesh ); try { ps = DataLoader.loadPointSet( ExampleSets.Example2, 0.1 ); ps = new PointSet( PointGenerator.uniformDistribution( 10000, 60 ) ); Poly2Tri.triangulate( ps ); ArdorMeshMapper.updateTriangleMesh( mesh, ps ); } catch( IOException e ) {} } }
Java
package org.poly2tri.examples.ardor3d; import java.util.List; import org.poly2tri.Poly2Tri; import org.poly2tri.examples.ardor3d.base.P2TSimpleExampleBase; import org.poly2tri.triangulation.TriangulationPoint; import org.poly2tri.triangulation.point.TPoint; import org.poly2tri.triangulation.sets.ConstrainedPointSet; import org.poly2tri.triangulation.tools.ardor3d.ArdorMeshMapper; import org.poly2tri.triangulation.util.PointGenerator; import com.ardor3d.framework.FrameHandler; import com.ardor3d.input.logical.LogicalLayer; import com.ardor3d.math.ColorRGBA; import com.ardor3d.scenegraph.Mesh; import com.google.inject.Inject; public class CDTUniformDistributionExample extends P2TSimpleExampleBase { public static void main(final String[] args) { start(CDTUniformDistributionExample.class); } @Inject public CDTUniformDistributionExample( LogicalLayer logicalLayer, FrameHandler frameHandler ) { super( logicalLayer, frameHandler ); } @Override protected void initExample() { super.initExample(); Mesh mesh = new Mesh(); mesh.setDefaultColor( ColorRGBA.BLUE ); _node.attachChild( mesh ); double scale = 100; int size = 1000; int index = (int)(Math.random()*size); List<TriangulationPoint> points = PointGenerator.uniformDistribution( size, scale ); // Lets add a constraint that cuts the uniformDistribution in half points.add( new TPoint(0,scale/2) ); points.add( new TPoint(0,-scale/2) ); index = size; ConstrainedPointSet cps = new ConstrainedPointSet( points, new int[]{ index, index+1 } ); Poly2Tri.triangulate( cps ); ArdorMeshMapper.updateTriangleMesh( mesh, cps ); } }
Java
package org.poly2tri.examples.ardor3d; import java.util.ArrayList; import org.poly2tri.Poly2Tri; import org.poly2tri.examples.ardor3d.base.P2TSimpleExampleBase; import org.poly2tri.geometry.polygon.Polygon; import org.poly2tri.geometry.polygon.PolygonPoint; import org.poly2tri.triangulation.point.TPoint; import org.poly2tri.triangulation.tools.ardor3d.ArdorMeshMapper; import org.poly2tri.triangulation.util.PolygonGenerator; import com.ardor3d.framework.FrameHandler; import com.ardor3d.input.logical.LogicalLayer; import com.ardor3d.math.ColorRGBA; import com.ardor3d.renderer.state.WireframeState; import com.ardor3d.scenegraph.Mesh; import com.ardor3d.scenegraph.Node; import com.google.inject.Inject; public class CDTSteinerPointExample extends P2TSimpleExampleBase { public static void main(final String[] args) { start(CDTSteinerPointExample.class); } @Inject public CDTSteinerPointExample( LogicalLayer logicalLayer, FrameHandler frameHandler ) { super( logicalLayer, frameHandler ); } @Override protected void initExample() { super.initExample(); Node node = new Node(); node.setRenderState( new WireframeState() ); _node.attachChild( node ); Polygon poly; poly = createCirclePolygon( 32, 1.5 ); // top left Mesh mesh = new Mesh(); mesh.setDefaultColor( ColorRGBA.BLUE ); mesh.setTranslation( -2, 2, 0 ); node.attachChild( mesh ); Poly2Tri.triangulate( poly ); ArdorMeshMapper.updateTriangleMesh( mesh, poly ); // bottom left mesh = new Mesh(); mesh.setDefaultColor( ColorRGBA.RED ); mesh.setTranslation( -2, -2, 0 ); node.attachChild( mesh ); poly.addSteinerPoint( new TPoint(0,0) ); Poly2Tri.triangulate( poly ); ArdorMeshMapper.updateTriangleMesh( mesh, poly ); poly = PolygonGenerator.RandomCircleSweep2( 4, 200 ); // top right mesh = new Mesh(); mesh.setDefaultColor( ColorRGBA.BLUE ); mesh.setTranslation( 2, 2, 0 ); node.attachChild( mesh ); Poly2Tri.triangulate( poly ); ArdorMeshMapper.updateTriangleMesh( mesh, poly ); // bottom right mesh = new Mesh(); mesh.setDefaultColor( ColorRGBA.RED ); mesh.setTranslation( 2, -2, 0 ); node.attachChild( mesh ); poly.addSteinerPoint( new TPoint(0,0) ); Poly2Tri.triangulate( poly ); ArdorMeshMapper.updateTriangleMesh( mesh, poly ); } private Polygon createCirclePolygon( int n, double radius ) { if( n < 3 ) n=3; PolygonPoint[] points = new PolygonPoint[n]; for( int i=0; i<n; i++ ) { points[i] = new PolygonPoint( radius*Math.cos( (2.0*Math.PI*i)/n ), radius*Math.sin( (2.0*Math.PI*i)/n ) ); } return new Polygon( points ); } }
Java
package org.poly2tri.examples; import org.poly2tri.Poly2Tri; import org.poly2tri.triangulation.sets.PointSet; import org.poly2tri.triangulation.util.PointGenerator; public class ProfilingExample { public static void main(final String[] args) throws Exception { PointSet ps = new PointSet( PointGenerator.uniformDistribution( 50, 500000 ) ); for( int i=0; i<1; i++ ) { Poly2Tri.triangulate( ps ); } Thread.sleep( 10000000 ); } public void startProfiling() throws Exception { } }
Java
package org.poly2tri.examples.geotools; import java.io.IOException; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import org.geotools.data.FeatureSource; import org.geotools.data.shapefile.ShapefileDataStore; import org.geotools.feature.FeatureCollection; import org.geotools.feature.FeatureIterator; import org.opengis.feature.Feature; import org.opengis.feature.GeometryAttribute; import org.poly2tri.Poly2Tri; import org.poly2tri.examples.ardor3d.base.P2TSimpleExampleBase; import org.poly2tri.geometry.polygon.Polygon; import org.poly2tri.geometry.polygon.PolygonPoint; import org.poly2tri.geometry.polygon.PolygonSet; import org.poly2tri.transform.coordinate.CoordinateTransform; import org.poly2tri.triangulation.tools.ardor3d.ArdorMeshMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.ardor3d.example.ExampleBase; import com.ardor3d.framework.Canvas; import com.ardor3d.framework.FrameHandler; import com.ardor3d.image.Image; import com.ardor3d.image.Texture; import com.ardor3d.image.Texture.WrapMode; import com.ardor3d.input.MouseButton; import com.ardor3d.input.logical.InputTrigger; import com.ardor3d.input.logical.LogicalLayer; import com.ardor3d.input.logical.MouseButtonClickedCondition; import com.ardor3d.input.logical.TriggerAction; import com.ardor3d.input.logical.TwoInputStates; import com.ardor3d.math.ColorRGBA; import com.ardor3d.math.MathUtils; import com.ardor3d.math.Matrix3; import com.ardor3d.math.Vector3; import com.ardor3d.renderer.queue.RenderBucketType; import com.ardor3d.renderer.state.BlendState; import com.ardor3d.renderer.state.MaterialState; import com.ardor3d.renderer.state.WireframeState; import com.ardor3d.renderer.state.ZBufferState; import com.ardor3d.renderer.state.BlendState.BlendEquation; import com.ardor3d.scenegraph.FloatBufferData; import com.ardor3d.scenegraph.Mesh; import com.ardor3d.scenegraph.Node; import com.ardor3d.scenegraph.extension.Skybox; import com.ardor3d.scenegraph.extension.Skybox.Face; import com.ardor3d.scenegraph.hint.LightCombineMode; import com.ardor3d.scenegraph.shape.Sphere; import com.ardor3d.util.ReadOnlyTimer; import com.ardor3d.util.TextureManager; import com.ardor3d.util.resource.ResourceLocatorTool; import com.ardor3d.util.resource.SimpleResourceLocator; import com.google.inject.Inject; import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jts.geom.LinearRing; import com.vividsolutions.jts.geom.MultiLineString; import com.vividsolutions.jts.geom.MultiPolygon; /** * Hello world! * */ public class WorldExample extends P2TSimpleExampleBase { private final static Logger logger = LoggerFactory.getLogger( WorldExample.class ); private final static CoordinateTransform _wgs84 = new WGS84GeodeticTransform(100); private Node _worldNode; private Skybox _skybox; private final Matrix3 rotate = new Matrix3(); private double angle = 0; private boolean _doRotate = true; /** * We use one PolygonSet for each country since countries can have islands * and be composed of multiple polygons */ private ArrayList<PolygonSet> _countries = new ArrayList<PolygonSet>(); @Inject public WorldExample( LogicalLayer logicalLayer, FrameHandler frameHandler ) { super( logicalLayer, frameHandler ); } public static void main( String[] args ) throws Exception { try { start(WorldExample.class); } catch( RuntimeException e ) { logger.error( "WorldExample failed due to a runtime exception" ); } } @Override protected void updateExample( ReadOnlyTimer timer ) { if( _doRotate ) { angle += timer.getTimePerFrame() * 10; angle %= 360; rotate.fromAngleNormalAxis(angle * MathUtils.DEG_TO_RAD, Vector3.UNIT_Z); _worldNode.setRotation(rotate); } } @Override protected void initExample() { super.initExample(); try { importShape(100); } catch( IOException e ) { } _canvas.getCanvasRenderer().getCamera().setLocation(200, 200, 200); _canvas.getCanvasRenderer().getCamera().lookAt( 0, 0, 0, Vector3.UNIT_Z ); _worldNode = new Node("shape"); // _worldNode.setRenderState( new WireframeState() ); _node.attachChild( _worldNode ); buildSkyBox(); Sphere seas = new Sphere("seas", Vector3.ZERO, 64, 64, 100.2f); seas.setDefaultColor( new ColorRGBA(0,0,0.5f,0.25f) ); seas.getSceneHints().setRenderBucketType( RenderBucketType.Transparent ); BlendState bs = new BlendState(); bs.setBlendEnabled( true ); bs.setEnabled( true ); bs.setBlendEquationAlpha( BlendEquation.Max ); bs.setSourceFunction(BlendState.SourceFunction.SourceAlpha); bs.setDestinationFunction(BlendState.DestinationFunction.OneMinusSourceAlpha); seas.setRenderState( bs ); ZBufferState zb = new ZBufferState(); zb.setEnabled( true ); zb.setWritable( false ); seas.setRenderState( zb ); _worldNode.attachChild( seas ); Sphere core = new Sphere("seas", Vector3.ZERO, 16, 16, 10f); core.getSceneHints().setLightCombineMode( LightCombineMode.Replace ); MaterialState ms = new MaterialState(); ms.setEmissive( new ColorRGBA(0.8f,0.2f,0,0.9f) ); core.setRenderState( ms ); _worldNode.attachChild( core ); Mesh mesh; for( PolygonSet ps : _countries ) { Poly2Tri.triangulate( ps ); float value = 1-0.9f*(float)Math.random(); for( Polygon p : ps.getPolygons() ) { mesh = new Mesh(); mesh.setDefaultColor( new ColorRGBA( value, value, value, 1.0f ) ); _worldNode.attachChild( mesh ); ArdorMeshMapper.updateTriangleMesh( mesh, p, _wgs84 ); } } } protected void importShape( double rescale ) throws IOException { // URL url = WorldExample.class.getResource( "/z5UKI.shp" ); URL url = WorldExample.class.getResource( "/earth/countries.shp" ); url.getFile(); ShapefileDataStore ds = new ShapefileDataStore(url); FeatureSource featureSource = ds.getFeatureSource(); // for( int i=0; i < ds.getTypeNames().length; i++) // { // System.out.println("ShapefileDataStore.typename=" + ds.getTypeNames()[i] ); // } FeatureCollection fc = featureSource.getFeatures(); // System.out.println( "featureCollection.ID=" + fc.getID() ); // System.out.println( "featureCollection.schema=" + fc.getSchema() ); // System.out.println( "featureCollection.Bounds[minX,maxX,minY,maxY]=[" // + fc.getBounds().getMinX() + "," + // + fc.getBounds().getMaxX() + "," + // + fc.getBounds().getMinY() + "," + // + fc.getBounds().getMaxY() + "]" ); // double width, height, xScale, yScale, scale, dX, dY; // width = fc.getBounds().getMaxX() - fc.getBounds().getMinX(); // height = fc.getBounds().getMaxY() - fc.getBounds().getMinY(); // dX = fc.getBounds().getMinX() + width/2; // dY = fc.getBounds().getMinY() + height/2; // xScale = rescale * 1f / width; // yScale = rescale * 1f / height; // scale = xScale < yScale ? xScale : yScale; FeatureIterator fi; Feature f; GeometryAttribute geoAttrib; Polygon polygon; PolygonSet polygonSet; fi = fc.features(); while( fi.hasNext() ) { polygonSet = new PolygonSet(); f = fi.next(); geoAttrib = f.getDefaultGeometryProperty(); // System.out.println( "Feature.Identifier:" + f.getIdentifier() ); // System.out.println( "Feature.Name:" + f.getName() ); // System.out.println( "Feature.Type:" + f.getType() ); // System.out.println( "Feature.Descriptor:" + geoAttrib.getDescriptor() ); // System.out.println( "GeoAttrib.Identifier=" + geoAttrib.getIdentifier() ); // System.out.println( "GeoAttrib.Name=" + geoAttrib.getName() ); // System.out.println( "GeoAttrib.Type.Name=" + geoAttrib.getType().getName() ); // System.out.println( "GeoAttrib.Type.Binding=" + geoAttrib.getType().getBinding() ); // System.out.println( "GeoAttrib.Value=" + geoAttrib.getValue() ); if( geoAttrib.getType().getBinding() == MultiLineString.class ) { MultiLineString mls = (MultiLineString)geoAttrib.getValue(); Coordinate[] coords = mls.getCoordinates(); // System.out.println( "MultiLineString.coordinates=" + coords.length ); ArrayList<PolygonPoint> points = new ArrayList<PolygonPoint>(coords.length); for( int i=0; i<coords.length; i++) { points.add( new PolygonPoint(coords[i].x,coords[i].y) ); // System.out.println( "[x,y]=[" + coords[i].x + "," + coords[i].y + "]" ); } polygonSet.add( new Polygon(points) ); } else if( geoAttrib.getType().getBinding() == MultiPolygon.class ) { MultiPolygon mp = (MultiPolygon)geoAttrib.getValue(); // System.out.println( "MultiPolygon.NumGeometries=" + mp.getNumGeometries() ); for( int i=0; i<mp.getNumGeometries(); i++ ) { com.vividsolutions.jts.geom.Polygon jtsPolygon = (com.vividsolutions.jts.geom.Polygon)mp.getGeometryN(i); polygon = buildPolygon( jtsPolygon ); polygonSet.add( polygon ); } } _countries.add( polygonSet ); } } private static Polygon buildPolygon( com.vividsolutions.jts.geom.Polygon jtsPolygon ) { Polygon polygon; LinearRing shell; ArrayList<PolygonPoint> points; // Envelope envelope; // System.out.println( "MultiPolygon.points=" + jtsPolygon.getNumPoints() ); // System.out.println( "MultiPolygon.NumInteriorRing=" + jtsPolygon.getNumInteriorRing() ); // envelope = jtsPolygon.getEnvelopeInternal(); shell = (LinearRing)jtsPolygon.getExteriorRing(); Coordinate[] coords = shell.getCoordinates(); points = new ArrayList<PolygonPoint>(coords.length); // Skipping last coordinate since JTD defines a shell as a LineString that start with // same first and last coordinate for( int j=0; j<coords.length-1; j++) { points.add( new PolygonPoint(coords[j].x,coords[j].y) ); } polygon = new Polygon(points); return polygon; } // // private void refinePolygon() // { // // } /** * Builds the sky box. */ private void buildSkyBox() { _skybox = new Skybox("skybox", 300, 300, 300); try { SimpleResourceLocator sr2 = new SimpleResourceLocator(ExampleBase.class.getClassLoader().getResource("org/poly2tri/examples/geotools/textures/")); ResourceLocatorTool.addResourceLocator(ResourceLocatorTool.TYPE_TEXTURE, sr2); } catch (final URISyntaxException ex) { ex.printStackTrace(); } final String dir = ""; final Texture stars = TextureManager.load(dir + "stars.gif", Texture.MinificationFilter.Trilinear, Image.Format.GuessNoCompression, true); _skybox.setTexture(Skybox.Face.North, stars); _skybox.setTexture(Skybox.Face.West, stars); _skybox.setTexture(Skybox.Face.South, stars); _skybox.setTexture(Skybox.Face.East, stars); _skybox.setTexture(Skybox.Face.Up, stars); _skybox.setTexture(Skybox.Face.Down, stars); _skybox.getTexture( Skybox.Face.North ).setWrap( WrapMode.Repeat ); for( Face f : Face.values() ) { FloatBufferData fbd = _skybox.getFace(f).getMeshData().getTextureCoords().get( 0 ); fbd.getBuffer().clear(); fbd.getBuffer().put( 0 ).put( 4 ); fbd.getBuffer().put( 0 ).put( 0 ); fbd.getBuffer().put( 4 ).put( 0 ); fbd.getBuffer().put( 4 ).put( 4 ); } _node.attachChild( _skybox ); } @Override public void registerInputTriggers() { super.registerInputTriggers(); // SPACE - toggle models _logicalLayer.registerTrigger( new InputTrigger( new MouseButtonClickedCondition(MouseButton.RIGHT), new TriggerAction() { public void perform( final Canvas canvas, final TwoInputStates inputState, final double tpf ) { _doRotate = _doRotate ? false : true; } } ) ); } /* * http://en.wikipedia.org/wiki/Longitude#Degree_length * http://www.colorado.edu/geography/gcraft/notes/datum/gif/llhxyz.gif * * x (in m) = Latitude * 60 * 1852 * y (in m) = (PI/180) * cos(Longitude) * (637813.7^2 / sqrt( (637813.7 * cos(Longitude))^2 + (635675.23 * sin(Longitude))^2 ) ) * z (in m) = Altitude * * The 'quick and dirty' method (assuming the Earth is a perfect sphere): * * x = longitude*60*1852*cos(latitude) * y = latitude*60*1852 * * Latitude and longitude must be in decimal degrees, x and y are in meters. * The origin of the xy-grid is the intersection of the 0-degree meridian * and the equator, where x is positive East and y is positive North. * * So, why the 1852? I'm using the (original) definition of a nautical mile * here: 1 nautical mile = the length of one arcminute on the equator (hence * the 60*1852; I'm converting the lat/lon degrees to lat/lon minutes). */ }
Java
package org.poly2tri.geometry.primitives; public abstract class Point { public abstract double getX(); public abstract double getY(); public abstract double getZ(); public abstract float getXf(); public abstract float getYf(); public abstract float getZf(); public abstract void set( double x, double y, double z ); protected static int calculateHashCode( double x, double y, double z) { int result = 17; final long a = Double.doubleToLongBits(x); result += 31 * result + (int) (a ^ (a >>> 32)); final long b = Double.doubleToLongBits(y); result += 31 * result + (int) (b ^ (b >>> 32)); final long c = Double.doubleToLongBits(z); result += 31 * result + (int) (c ^ (c >>> 32)); return result; } }
Java
package org.poly2tri.geometry.primitives; public abstract class Edge<A extends Point> { protected A p; protected A q; public A getP() { return p; } public A getQ() { return q; } }
Java
/* Poly2Tri * Copyright (c) 2009-2010, Poly2Tri Contributors * http://code.google.com/p/poly2tri/ * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Poly2Tri nor the names of its contributors may be * used to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.poly2tri.geometry.polygon; import java.util.ArrayList; import java.util.List; public class PolygonSet { protected ArrayList<Polygon> _polygons = new ArrayList<Polygon>(); public PolygonSet() { } public PolygonSet( Polygon poly ) { _polygons.add( poly ); } public void add( Polygon p ) { _polygons.add( p ); } public List<Polygon> getPolygons() { return _polygons; } }
Java
package org.poly2tri.geometry.polygon; import org.poly2tri.triangulation.point.TPoint; public class PolygonPoint extends TPoint { protected PolygonPoint _next; protected PolygonPoint _previous; public PolygonPoint( double x, double y ) { super( x, y ); } public PolygonPoint( double x, double y, double z ) { super( x, y, z ); } public void setPrevious( PolygonPoint p ) { _previous = p; } public void setNext( PolygonPoint p ) { _next = p; } public PolygonPoint getNext() { return _next; } public PolygonPoint getPrevious() { return _previous; } }
Java
package org.poly2tri.geometry.polygon; public class PolygonUtil { /** * TODO * @param polygon */ public static void validate( Polygon polygon ) { // TODO: implement // 1. Check for duplicate points // 2. Check for intersecting sides } }
Java
package org.poly2tri.geometry.polygon; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.poly2tri.triangulation.Triangulatable; import org.poly2tri.triangulation.TriangulationContext; import org.poly2tri.triangulation.TriangulationMode; import org.poly2tri.triangulation.TriangulationPoint; import org.poly2tri.triangulation.delaunay.DelaunayTriangle; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Polygon implements Triangulatable { private final static Logger logger = LoggerFactory.getLogger( Polygon.class ); protected ArrayList<TriangulationPoint> _points = new ArrayList<TriangulationPoint>(); protected ArrayList<TriangulationPoint> _steinerPoints; protected ArrayList<Polygon> _holes; protected List<DelaunayTriangle> m_triangles; protected PolygonPoint _last; /** * To create a polygon we need atleast 3 separate points * * @param p1 * @param p2 * @param p3 */ public Polygon( PolygonPoint p1, PolygonPoint p2, PolygonPoint p3 ) { p1._next = p2; p2._next = p3; p3._next = p1; p1._previous = p3; p2._previous = p1; p3._previous = p2; _points.add( p1 ); _points.add( p2 ); _points.add( p3 ); } /** * Requires atleast 3 points * @param points - ordered list of points forming the polygon. * No duplicates are allowed */ public Polygon( List<PolygonPoint> points ) { // Lets do one sanity check that first and last point hasn't got same position // Its something that often happen when importing polygon data from other formats if( points.get(0).equals( points.get(points.size()-1) ) ) { logger.warn( "Removed duplicate point"); points.remove( points.size()-1 ); } _points.addAll( points ); } /** * Requires atleast 3 points * * @param points */ public Polygon( PolygonPoint[] points ) { this( Arrays.asList( points ) ); } public TriangulationMode getTriangulationMode() { return TriangulationMode.POLYGON; } public int pointCount() { int count = _points.size(); if( _steinerPoints != null ) { count += _steinerPoints.size(); } return count; } public void addSteinerPoint( TriangulationPoint point ) { if( _steinerPoints == null ) { _steinerPoints = new ArrayList<TriangulationPoint>(); } _steinerPoints.add( point ); } public void addSteinerPoints( List<TriangulationPoint> points ) { if( _steinerPoints == null ) { _steinerPoints = new ArrayList<TriangulationPoint>(); } _steinerPoints.addAll( points ); } public void clearSteinerPoints() { if( _steinerPoints != null ) { _steinerPoints.clear(); } } /** * Assumes: that given polygon is fully inside the current polygon * @param poly - a subtraction polygon */ public void addHole( Polygon poly ) { if( _holes == null ) { _holes = new ArrayList<Polygon>(); } _holes.add( poly ); // XXX: tests could be made here to be sure it is fully inside // addSubtraction( poly.getPoints() ); } /** * Will insert a point in the polygon after given point * * @param a * @param b * @param p */ public void insertPointAfter( PolygonPoint a, PolygonPoint newPoint ) { // Validate that int index = _points.indexOf( a ); if( index != -1 ) { newPoint.setNext( a.getNext() ); newPoint.setPrevious( a ); a.getNext().setPrevious( newPoint ); a.setNext( newPoint ); _points.add( index+1, newPoint ); } else { throw new RuntimeException( "Tried to insert a point into a Polygon after a point not belonging to the Polygon" ); } } public void addPoints( List<PolygonPoint> list ) { PolygonPoint first; for( PolygonPoint p : list ) { p.setPrevious( _last ); if( _last != null ) { p.setNext( _last.getNext() ); _last.setNext( p ); } _last = p; _points.add( p ); } first = (PolygonPoint)_points.get(0); _last.setNext( first ); first.setPrevious( _last ); } /** * Will add a point after the last point added * * @param p */ public void addPoint(PolygonPoint p ) { p.setPrevious( _last ); p.setNext( _last.getNext() ); _last.setNext( p ); _points.add( p ); } public void removePoint( PolygonPoint p ) { PolygonPoint next, prev; next = p.getNext(); prev = p.getPrevious(); prev.setNext( next ); next.setPrevious( prev ); _points.remove( p ); } public PolygonPoint getPoint() { return _last; } public List<TriangulationPoint> getPoints() { return _points; } public List<DelaunayTriangle> getTriangles() { return m_triangles; } public void addTriangle( DelaunayTriangle t ) { m_triangles.add( t ); } public void addTriangles( List<DelaunayTriangle> list ) { m_triangles.addAll( list ); } public void clearTriangulation() { if( m_triangles != null ) { m_triangles.clear(); } } /** * Creates constraints and populates the context with points */ public void prepareTriangulation( TriangulationContext<?> tcx ) { if( m_triangles == null ) { m_triangles = new ArrayList<DelaunayTriangle>( _points.size() ); } else { m_triangles.clear(); } // Outer constraints for( int i = 0; i < _points.size()-1 ; i++ ) { tcx.newConstraint( _points.get( i ), _points.get( i+1 ) ); } tcx.newConstraint( _points.get( 0 ), _points.get( _points.size()-1 ) ); tcx.addPoints( _points ); // Hole constraints if( _holes != null ) { for( Polygon p : _holes ) { for( int i = 0; i < p._points.size()-1 ; i++ ) { tcx.newConstraint( p._points.get( i ), p._points.get( i+1 ) ); } tcx.newConstraint( p._points.get( 0 ), p._points.get( p._points.size()-1 ) ); tcx.addPoints( p._points ); } } if( _steinerPoints != null ) { tcx.addPoints( _steinerPoints ); } } }
Java
package org.poly2tri.triangulation; public abstract class TriangulationDebugContext { protected TriangulationContext<?> _tcx; public TriangulationDebugContext( TriangulationContext<?> tcx ) { _tcx = tcx; } public abstract void clear(); }
Java
package org.poly2tri.triangulation; public enum TriangulationMode { UNCONSTRAINED,CONSTRAINED,POLYGON; }
Java
/* Poly2Tri * Copyright (c) 2009-2010, Poly2Tri Contributors * http://code.google.com/p/poly2tri/ * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Poly2Tri nor the names of its contributors may be * used to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.poly2tri.triangulation.point; import org.poly2tri.triangulation.TriangulationPoint; public class TPoint extends TriangulationPoint { private double _x; private double _y; private double _z; public TPoint( double x, double y ) { this( x, y, 0 ); } public TPoint( double x, double y, double z ) { _x = x; _y = y; _z = z; } public double getX() { return _x; } public double getY() { return _y; } public double getZ() { return _z; } public float getXf() { return (float)_x; } public float getYf() { return (float)_y; } public float getZf() { return (float)_z; } @Override public void set( double x, double y, double z ) { _x = x; _y = y; _z = z; } }
Java
/* Poly2Tri * Copyright (c) 2009-2010, Poly2Tri Contributors * http://code.google.com/p/poly2tri/ * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Poly2Tri nor the names of its contributors may be * used to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.poly2tri.triangulation.point; import java.nio.FloatBuffer; import org.poly2tri.triangulation.TriangulationPoint; public class FloatBufferPoint extends TriangulationPoint { private final FloatBuffer _fb; private final int _ix,_iy,_iz; public FloatBufferPoint( FloatBuffer fb, int index ) { _fb = fb; _ix = index; _iy = index+1; _iz = index+2; } public final double getX() { return _fb.get( _ix ); } public final double getY() { return _fb.get( _iy ); } public final double getZ() { return _fb.get( _iz ); } public final float getXf() { return _fb.get( _ix ); } public final float getYf() { return _fb.get( _iy ); } public final float getZf() { return _fb.get( _iz ); } @Override public void set( double x, double y, double z ) { _fb.put( _ix, (float)x ); _fb.put( _iy, (float)y ); _fb.put( _iz, (float)z ); } public static TriangulationPoint[] toPoints( FloatBuffer fb ) { FloatBufferPoint[] points = new FloatBufferPoint[fb.limit()/3]; for( int i=0,j=0; i<points.length; i++, j+=3 ) { points[i] = new FloatBufferPoint(fb, j); } return points; } }
Java
/* Poly2Tri * Copyright (c) 2009-2010, Poly2Tri Contributors * http://code.google.com/p/poly2tri/ * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Poly2Tri nor the names of its contributors may be * used to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.poly2tri.triangulation; import java.util.ArrayList; import java.util.List; import org.poly2tri.triangulation.delaunay.DelaunayTriangle; public abstract class TriangulationContext<A extends TriangulationDebugContext> { protected A _debug; protected boolean _debugEnabled = false; protected ArrayList<DelaunayTriangle> _triList = new ArrayList<DelaunayTriangle>(); protected ArrayList<TriangulationPoint> _points = new ArrayList<TriangulationPoint>(200); protected TriangulationMode _triangulationMode; protected Triangulatable _triUnit; private boolean _terminated = false; private boolean _waitUntilNotified; private int _stepTime = -1; private int _stepCount = 0; public int getStepCount() { return _stepCount; } public void done() { _stepCount++; } public abstract TriangulationAlgorithm algorithm(); public void prepareTriangulation( Triangulatable t ) { _triUnit = t; _triangulationMode = t.getTriangulationMode(); t.prepareTriangulation( this ); } public abstract TriangulationConstraint newConstraint( TriangulationPoint a, TriangulationPoint b ); public void addToList( DelaunayTriangle triangle ) { _triList.add( triangle ); } public List<DelaunayTriangle> getTriangles() { return _triList; } public Triangulatable getTriangulatable() { return _triUnit; } public List<TriangulationPoint> getPoints() { return _points; } public synchronized void update(String message) { if( _debugEnabled ) { try { synchronized( this ) { _stepCount++; if( _stepTime > 0 ) { wait( (int)_stepTime ); /** Can we resume execution or are we expected to wait? */ if( _waitUntilNotified ) { wait(); } } else { wait(); } // We have been notified _waitUntilNotified = false; } } catch( InterruptedException e ) { update("Triangulation was interrupted"); } } if( _terminated ) { throw new RuntimeException( "Triangulation process terminated before completion"); } } public void clear() { _points.clear(); _terminated = false; if( _debug != null ) { _debug.clear(); } _stepCount=0; } public TriangulationMode getTriangulationMode() { return _triangulationMode; } public synchronized void waitUntilNotified(boolean b) { _waitUntilNotified = b; } public void terminateTriangulation() { _terminated=true; } public boolean isDebugEnabled() { return _debugEnabled; } public abstract void isDebugEnabled( boolean b ); public A getDebugContext() { return _debug; } public void addPoints( List<TriangulationPoint> points ) { _points.addAll( points ); } }
Java
package org.poly2tri.triangulation; import java.util.List; import org.poly2tri.triangulation.delaunay.DelaunayTriangle; public interface Triangulatable { /** * Preparations needed before triangulation start should be handled here * @param tcx */ public void prepareTriangulation( TriangulationContext<?> tcx ); public List<DelaunayTriangle> getTriangles(); public List<TriangulationPoint> getPoints(); public void addTriangle( DelaunayTriangle t ); public void addTriangles( List<DelaunayTriangle> list ); public void clearTriangulation(); public TriangulationMode getTriangulationMode(); }
Java
/* Poly2Tri * Copyright (c) 2009-2010, Poly2Tri Contributors * http://code.google.com/p/poly2tri/ * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Poly2Tri nor the names of its contributors may be * used to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.poly2tri.triangulation; import java.util.ArrayList; import org.poly2tri.geometry.primitives.Point; import org.poly2tri.triangulation.delaunay.sweep.DTSweepConstraint; public abstract class TriangulationPoint extends Point { // List of edges this point constitutes an upper ending point (CDT) private ArrayList<DTSweepConstraint> edges; @Override public String toString() { return "[" + getX() + "," + getY() + "]"; } public abstract double getX(); public abstract double getY(); public abstract double getZ(); public abstract float getXf(); public abstract float getYf(); public abstract float getZf(); public abstract void set( double x, double y, double z ); public ArrayList<DTSweepConstraint> getEdges() { return edges; } public void addEdge( DTSweepConstraint e ) { if( edges == null ) { edges = new ArrayList<DTSweepConstraint>(); } edges.add( e ); } public boolean hasEdges() { return edges != null; } /** * @param p - edge destination point * @return the edge from this point to given point */ public DTSweepConstraint getEdge( TriangulationPoint p ) { for( DTSweepConstraint c : edges ) { if( c.p == p ) { return c; } } return null; } public boolean equals(Object obj) { if( obj instanceof TriangulationPoint ) { TriangulationPoint p = (TriangulationPoint)obj; return getX() == p.getX() && getY() == p.getY(); } return super.equals( obj ); } public int hashCode() { long bits = java.lang.Double.doubleToLongBits(getX()); bits ^= java.lang.Double.doubleToLongBits(getY()) * 31; return (((int) bits) ^ ((int) (bits >> 32))); } }
Java
/* Poly2Tri * Copyright (c) 2009-2010, Poly2Tri Contributors * http://code.google.com/p/poly2tri/ * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Poly2Tri nor the names of its contributors may be * used to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.poly2tri.triangulation.delaunay; import java.util.ArrayList; import org.poly2tri.triangulation.TriangulationPoint; import org.poly2tri.triangulation.delaunay.sweep.DTSweepConstraint; import org.poly2tri.triangulation.point.TPoint; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class DelaunayTriangle { private final static Logger logger = LoggerFactory.getLogger( DelaunayTriangle.class ); /** Neighbor pointers */ public final DelaunayTriangle[] neighbors = new DelaunayTriangle[3]; /** Flags to determine if an edge is a Constrained edge */ public final boolean[] cEdge = new boolean[] { false, false, false }; /** Flags to determine if an edge is a Delauney edge */ public final boolean[] dEdge = new boolean[] { false, false, false }; /** Has this triangle been marked as an interior triangle? */ protected boolean interior = false; public final TriangulationPoint[] points = new TriangulationPoint[3]; public DelaunayTriangle( TriangulationPoint p1, TriangulationPoint p2, TriangulationPoint p3 ) { points[0] = p1; points[1] = p2; points[2] = p3; } public int index( TriangulationPoint p ) { if( p == points[0] ) { return 0; } else if( p == points[1] ) { return 1; } else if( p == points[2] ) { return 2; } throw new RuntimeException("Calling index with a point that doesn't exist in triangle"); } public int indexCW( TriangulationPoint p ) { int index = index(p); switch( index ) { case 0: return 2; case 1: return 0; default: return 1; } } public int indexCCW( TriangulationPoint p ) { int index = index(p); switch( index ) { case 0: return 1; case 1: return 2; default: return 0; } } public boolean contains( TriangulationPoint p ) { return ( p == points[0] || p == points[1] || p == points[2] ); } public boolean contains( DTSweepConstraint e ) { return ( contains( e.p ) && contains( e.q ) ); } public boolean contains( TriangulationPoint p, TriangulationPoint q ) { return ( contains( p ) && contains( q ) ); } // Update neighbor pointers private void markNeighbor( TriangulationPoint p1, TriangulationPoint p2, DelaunayTriangle t ) { if( ( p1 == points[2] && p2 == points[1] ) || ( p1 == points[1] && p2 == points[2] ) ) { neighbors[0] = t; } else if( ( p1 == points[0] && p2 == points[2] ) || ( p1 == points[2] && p2 == points[0] ) ) { neighbors[1] = t; } else if( ( p1 == points[0] && p2 == points[1] ) || ( p1 == points[1] && p2 == points[0] ) ) { neighbors[2] = t; } else { logger.error( "Neighbor error, please report!" ); // throw new Exception("Neighbor error, please report!"); } } /* Exhaustive search to update neighbor pointers */ public void markNeighbor( DelaunayTriangle t ) { if( t.contains( points[1], points[2] ) ) { neighbors[0] = t; t.markNeighbor( points[1], points[2], this ); } else if( t.contains( points[0], points[2] ) ) { neighbors[1] = t; t.markNeighbor( points[0], points[2], this ); } else if( t.contains( points[0], points[1] ) ) { neighbors[2] = t; t.markNeighbor( points[0], points[1], this ); } else { logger.error( "markNeighbor failed" ); } } public void clearNeighbors() { neighbors[0] = neighbors[1] = neighbors[2] = null; } public void clearNeighbor( DelaunayTriangle triangle ) { if( neighbors[0] == triangle ) { neighbors[0] = null; } else if( neighbors[1] == triangle ) { neighbors[1] = null; } else { neighbors[2] = null; } } /** * Clears all references to all other triangles and points */ public void clear() { DelaunayTriangle t; for( int i=0; i<3; i++ ) { t = neighbors[i]; if( t != null ) { t.clearNeighbor( this ); } } clearNeighbors(); points[0]=points[1]=points[2]=null; } /** * @param t - opposite triangle * @param p - the point in t that isn't shared between the triangles * @return */ public TriangulationPoint oppositePoint( DelaunayTriangle t, TriangulationPoint p ) { assert t != this : "self-pointer error"; return pointCW( t.pointCW(p) ); } // The neighbor clockwise to given point public DelaunayTriangle neighborCW( TriangulationPoint point ) { if( point == points[0] ) { return neighbors[1]; } else if( point == points[1] ) { return neighbors[2]; } return neighbors[0]; } // The neighbor counter-clockwise to given point public DelaunayTriangle neighborCCW( TriangulationPoint point ) { if( point == points[0] ) { return neighbors[2]; } else if( point == points[1] ) { return neighbors[0]; } return neighbors[1]; } // The neighbor across to given point public DelaunayTriangle neighborAcross( TriangulationPoint opoint ) { if( opoint == points[0] ) { return neighbors[0]; } else if( opoint == points[1] ) { return neighbors[1]; } return neighbors[2]; } // The point counter-clockwise to given point public TriangulationPoint pointCCW( TriangulationPoint point ) { if( point == points[0] ) { return points[1]; } else if( point == points[1] ) { return points[2]; } else if( point == points[2] ) { return points[0]; } logger.error( "point location error" ); throw new RuntimeException("[FIXME] point location error"); } // The point counter-clockwise to given point public TriangulationPoint pointCW( TriangulationPoint point ) { if( point == points[0] ) { return points[2]; } else if( point == points[1] ) { return points[0]; } else if( point == points[2] ) { return points[1]; } logger.error( "point location error" ); throw new RuntimeException("[FIXME] point location error"); } // Legalize triangle by rotating clockwise around oPoint public void legalize( TriangulationPoint oPoint, TriangulationPoint nPoint ) { if( oPoint == points[0] ) { points[1] = points[0]; points[0] = points[2]; points[2] = nPoint; } else if( oPoint == points[1] ) { points[2] = points[1]; points[1] = points[0]; points[0] = nPoint; } else if( oPoint == points[2] ) { points[0] = points[2]; points[2] = points[1]; points[1] = nPoint; } else { logger.error( "legalization error" ); throw new RuntimeException("legalization bug"); } } public void printDebug() { System.out.println( points[0] + "," + points[1] + "," + points[2] ); } // Finalize edge marking public void markNeighborEdges() { for( int i = 0; i < 3; i++ ) { if( cEdge[i] ) { switch( i ) { case 0: if( neighbors[0] != null ) neighbors[0].markConstrainedEdge( points[1], points[2] ); break; case 1: if( neighbors[1] != null ) neighbors[1].markConstrainedEdge( points[0], points[2] ); break; case 2: if( neighbors[2] != null ) neighbors[2].markConstrainedEdge( points[0], points[1] ); break; } } } } public void markEdge( DelaunayTriangle triangle ) { for( int i = 0; i < 3; i++ ) { if( cEdge[i] ) { switch( i ) { case 0: triangle.markConstrainedEdge( points[1], points[2] ); break; case 1: triangle.markConstrainedEdge( points[0], points[2] ); break; case 2: triangle.markConstrainedEdge( points[0], points[1] ); break; } } } } public void markEdge( ArrayList<DelaunayTriangle> tList ) { for( DelaunayTriangle t : tList ) { for( int i = 0; i < 3; i++ ) { if( t.cEdge[i] ) { switch( i ) { case 0: markConstrainedEdge( t.points[1], t.points[2] ); break; case 1: markConstrainedEdge( t.points[0], t.points[2] ); break; case 2: markConstrainedEdge( t.points[0], t.points[1] ); break; } } } } } public void markConstrainedEdge( int index ) { cEdge[index] = true; } public void markConstrainedEdge( DTSweepConstraint edge ) { markConstrainedEdge( edge.p, edge.q ); if( ( edge.q == points[0] && edge.p == points[1] ) || ( edge.q == points[1] && edge.p == points[0] ) ) { cEdge[2] = true; } else if( ( edge.q == points[0] && edge.p == points[2] ) || ( edge.q == points[2] && edge.p == points[0] ) ) { cEdge[1] = true; } else if( ( edge.q == points[1] && edge.p == points[2] ) || ( edge.q == points[2] && edge.p == points[1] ) ) { cEdge[0] = true; } } // Mark edge as constrained public void markConstrainedEdge( TriangulationPoint p, TriangulationPoint q ) { if( ( q == points[0] && p == points[1] ) || ( q == points[1] && p == points[0] ) ) { cEdge[2] = true; } else if( ( q == points[0] && p == points[2] ) || ( q == points[2] && p == points[0] ) ) { cEdge[1] = true; } else if( ( q == points[1] && p == points[2] ) || ( q == points[2] && p == points[1] ) ) { cEdge[0] = true; } } public double area() { double a = (points[0].getX() - points[2].getX())*(points[1].getY() - points[0].getY()); double b = (points[0].getX() - points[1].getX())*(points[2].getY() - points[0].getY()); return 0.5*Math.abs( a - b ); } public TPoint centroid() { double cx = ( points[0].getX() + points[1].getX() + points[2].getX() ) / 3d; double cy = ( points[0].getY() + points[1].getY() + points[2].getY() ) / 3d; return new TPoint( cx, cy ); } /** * Get the neighbor that share this edge * * @param constrainedEdge * @return index of the shared edge or -1 if edge isn't shared */ public int edgeIndex( TriangulationPoint p1, TriangulationPoint p2 ) { if( points[0] == p1 ) { if( points[1] == p2 ) { return 2; } else if( points[2] == p2 ) { return 1; } } else if( points[1] == p1 ) { if( points[2] == p2 ) { return 0; } else if( points[0] == p2 ) { return 2; } } else if( points[2] == p1 ) { if( points[0] == p2 ) { return 1; } else if( points[1] == p2 ) { return 0; } } return -1; } public boolean getConstrainedEdgeCCW( TriangulationPoint p ) { if( p == points[0] ) { return cEdge[2]; } else if( p == points[1] ) { return cEdge[0]; } return cEdge[1]; } public boolean getConstrainedEdgeCW( TriangulationPoint p ) { if( p == points[0] ) { return cEdge[1]; } else if( p == points[1] ) { return cEdge[2]; } return cEdge[0]; } public boolean getConstrainedEdgeAcross( TriangulationPoint p ) { if( p == points[0] ) { return cEdge[0]; } else if( p == points[1] ) { return cEdge[1]; } return cEdge[2]; } public void setConstrainedEdgeCCW( TriangulationPoint p, boolean ce ) { if( p == points[0] ) { cEdge[2] = ce; } else if( p == points[1] ) { cEdge[0] = ce; } else { cEdge[1] = ce; } } public void setConstrainedEdgeCW( TriangulationPoint p, boolean ce ) { if( p == points[0] ) { cEdge[1] = ce; } else if( p == points[1] ) { cEdge[2] = ce; } else { cEdge[0] = ce; } } public void setConstrainedEdgeAcross( TriangulationPoint p, boolean ce ) { if( p == points[0] ) { cEdge[0] = ce; } else if( p == points[1] ) { cEdge[1] = ce; } else { cEdge[2] = ce; } } public boolean getDelunayEdgeCCW( TriangulationPoint p ) { if( p == points[0] ) { return dEdge[2]; } else if( p == points[1] ) { return dEdge[0]; } return dEdge[1]; } public boolean getDelunayEdgeCW( TriangulationPoint p ) { if( p == points[0] ) { return dEdge[1]; } else if( p == points[1] ) { return dEdge[2]; } return dEdge[0]; } public boolean getDelunayEdgeAcross( TriangulationPoint p ) { if( p == points[0] ) { return dEdge[0]; } else if( p == points[1] ) { return dEdge[1]; } return dEdge[2]; } public void setDelunayEdgeCCW( TriangulationPoint p, boolean e ) { if( p == points[0] ) { dEdge[2] = e; } else if( p == points[1] ) { dEdge[0] = e; } else { dEdge[1] = e; } } public void setDelunayEdgeCW( TriangulationPoint p, boolean e ) { if( p == points[0] ) { dEdge[1] = e; } else if( p == points[1] ) { dEdge[2] = e; } else { dEdge[0] = e; } } public void setDelunayEdgeAcross( TriangulationPoint p, boolean e ) { if( p == points[0] ) { dEdge[0] = e; } else if( p == points[1] ) { dEdge[1] = e; } else { dEdge[2] = e; } } public void clearDelunayEdges() { dEdge[0] = false; dEdge[1] = false; dEdge[2] = false; } public boolean isInterior() { return interior; } public void isInterior( boolean b ) { interior = b; } }
Java
/* Poly2Tri * Copyright (c) 2009-2010, Poly2Tri Contributors * http://code.google.com/p/poly2tri/ * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Poly2Tri nor the names of its contributors may be * used to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.poly2tri.triangulation.delaunay.sweep; import org.poly2tri.triangulation.TriangulationPoint; import org.poly2tri.triangulation.delaunay.DelaunayTriangle; public class AdvancingFrontNode { protected AdvancingFrontNode next = null; protected AdvancingFrontNode prev = null; protected final Double key; // XXX: BST protected final double value; protected final TriangulationPoint point; protected DelaunayTriangle triangle; public AdvancingFrontNode( TriangulationPoint point ) { this.point = point; value = point.getX(); key = Double.valueOf( value ); // XXX: BST } public AdvancingFrontNode getNext() { return next; } public AdvancingFrontNode getPrevious() { return prev; } public TriangulationPoint getPoint() { return point; } public DelaunayTriangle getTriangle() { return triangle; } public boolean hasNext() { return next != null; } public boolean hasPrevious() { return prev != null; } }
Java
package org.poly2tri.triangulation.delaunay.sweep; import org.poly2tri.triangulation.TriangulationContext; import org.poly2tri.triangulation.TriangulationDebugContext; import org.poly2tri.triangulation.TriangulationPoint; import org.poly2tri.triangulation.delaunay.DelaunayTriangle; public class DTSweepDebugContext extends TriangulationDebugContext { /* * Fields used for visual representation of current triangulation */ protected DelaunayTriangle _primaryTriangle; protected DelaunayTriangle _secondaryTriangle; protected TriangulationPoint _activePoint; protected AdvancingFrontNode _activeNode; protected DTSweepConstraint _activeConstraint; public DTSweepDebugContext( DTSweepContext tcx ) { super( tcx ); } public boolean isDebugContext() { return true; } // private Tuple2<TPoint,Double> m_circumCircle = new Tuple2<TPoint,Double>( new TPoint(), new Double(0) ); // public Tuple2<TPoint,Double> getCircumCircle() { return m_circumCircle; } public DelaunayTriangle getPrimaryTriangle() { return _primaryTriangle; } public DelaunayTriangle getSecondaryTriangle() { return _secondaryTriangle; } public AdvancingFrontNode getActiveNode() { return _activeNode; } public DTSweepConstraint getActiveConstraint() { return _activeConstraint; } public TriangulationPoint getActivePoint() { return _activePoint; } public void setPrimaryTriangle( DelaunayTriangle triangle ) { _primaryTriangle = triangle; _tcx.update("setPrimaryTriangle"); } public void setSecondaryTriangle( DelaunayTriangle triangle ) { _secondaryTriangle = triangle; _tcx.update("setSecondaryTriangle"); } public void setActivePoint( TriangulationPoint point ) { _activePoint = point; } public void setActiveConstraint( DTSweepConstraint e ) { _activeConstraint = e; _tcx.update("setWorkingSegment"); } public void setActiveNode( AdvancingFrontNode node ) { _activeNode = node; _tcx.update("setWorkingNode"); } @Override public void clear() { _primaryTriangle = null; _secondaryTriangle = null; _activePoint = null; _activeNode = null; _activeConstraint = null; } // public void setWorkingCircumCircle( TPoint point, TPoint point2, TPoint point3 ) // { // double dx,dy; // // CircleXY.circumCenter( point, point2, point3, m_circumCircle.a ); // dx = m_circumCircle.a.getX()-point.getX(); // dy = m_circumCircle.a.getY()-point.getY(); // m_circumCircle.b = Double.valueOf( Math.sqrt( dx*dx + dy*dy ) ); // // } }
Java
package org.poly2tri.triangulation.delaunay.sweep; import java.util.Comparator; import org.poly2tri.triangulation.TriangulationPoint; public class DTSweepPointComparator implements Comparator<TriangulationPoint> { public int compare( TriangulationPoint p1, TriangulationPoint p2 ) { if(p1.getY() < p2.getY() ) { return -1; } else if( p1.getY() > p2.getY()) { return 1; } else { if(p1.getX() < p2.getX()) { return -1; } else if( p1.getX() > p2.getX() ) { return 1; } else { return 0; } } } }
Java
package org.poly2tri.triangulation.delaunay.sweep; public class PointOnEdgeException extends RuntimeException { /** * */ private static final long serialVersionUID = 1L; public PointOnEdgeException( String msg ) { super(msg); } }
Java
package org.poly2tri.triangulation.delaunay.sweep; public class AdvancingFrontIndex<A> { double _min,_max; IndexNode<A> _root; public AdvancingFrontIndex( double min, double max, int depth ) { if( depth > 5 ) depth = 5; _root = createIndex( depth ); } private IndexNode<A> createIndex( int n ) { IndexNode<A> node = null; if( n > 0 ) { node = new IndexNode<A>(); node.bigger = createIndex( n-1 ); node.smaller = createIndex( n-1 ); } return node; } public A fetchAndRemoveIndex( A key ) { return null; } public A fetchAndInsertIndex( A key ) { return null; } class IndexNode<A> { A value; IndexNode<A> smaller; IndexNode<A> bigger; double range; } }
Java
/* Poly2Tri * Copyright (c) 2009-2010, Poly2Tri Contributors * http://code.google.com/p/poly2tri/ * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Poly2Tri nor the names of its contributors may be * used to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.poly2tri.triangulation; public enum TriangulationAlgorithm { DTSweep }
Java
/* Poly2Tri * Copyright (c) 2009-2010, Poly2Tri Contributors * http://code.google.com/p/poly2tri/ * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Poly2Tri nor the names of its contributors may be * used to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.poly2tri.triangulation; public enum TriangulationProcessEvent { Started,Waiting,Failed,Aborted,Done }
Java
/* Poly2Tri * Copyright (c) 2009-2010, Poly2Tri Contributors * http://code.google.com/p/poly2tri/ * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Poly2Tri nor the names of its contributors may be * used to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.poly2tri.triangulation.sets; import java.util.ArrayList; import java.util.List; import org.poly2tri.triangulation.Triangulatable; import org.poly2tri.triangulation.TriangulationContext; import org.poly2tri.triangulation.TriangulationMode; import org.poly2tri.triangulation.TriangulationPoint; import org.poly2tri.triangulation.delaunay.DelaunayTriangle; public class PointSet implements Triangulatable { List<TriangulationPoint> _points; List<DelaunayTriangle> _triangles; public PointSet( List<TriangulationPoint> points ) { _points = new ArrayList<TriangulationPoint>(); _points.addAll( points ); } public TriangulationMode getTriangulationMode() { return TriangulationMode.UNCONSTRAINED; } public List<TriangulationPoint> getPoints() { return _points; } public List<DelaunayTriangle> getTriangles() { return _triangles; } public void addTriangle( DelaunayTriangle t ) { _triangles.add( t ); } public void addTriangles( List<DelaunayTriangle> list ) { _triangles.addAll( list ); } public void clearTriangulation() { _triangles.clear(); } public void prepareTriangulation( TriangulationContext<?> tcx ) { if( _triangles == null ) { _triangles = new ArrayList<DelaunayTriangle>( _points.size() ); } else { _triangles.clear(); } tcx.addPoints( _points ); } }
Java
/* Poly2Tri * Copyright (c) 2009-2010, Poly2Tri Contributors * http://code.google.com/p/poly2tri/ * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Poly2Tri nor the names of its contributors may be * used to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.poly2tri.triangulation.util; public class Tuple2<A,B> { public A a; public B b; public Tuple2(A a,B b) { this.a = a; this.b = b; } }
Java
/* Poly2Tri * Copyright (c) 2009-2010, Poly2Tri Contributors * http://code.google.com/p/poly2tri/ * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Poly2Tri nor the names of its contributors may be * used to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.poly2tri.triangulation.util; public class Tuple3<A,B,C> { public A a; public B b; public C c; public Tuple3(A a,B b,C c) { this.a = a; this.b = b; this.c = c; } }
Java
/* Poly2Tri * Copyright (c) 2009-2010, Poly2Tri Contributors * http://code.google.com/p/poly2tri/ * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Poly2Tri nor the names of its contributors may be * used to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.poly2tri.triangulation.util; import org.poly2tri.geometry.polygon.Polygon; import org.poly2tri.geometry.polygon.PolygonPoint; public class PolygonGenerator { private static final double PI_2 = 2.0*Math.PI; public static Polygon RandomCircleSweep( double scale, int vertexCount ) { PolygonPoint point; PolygonPoint[] points; double radius = scale/4; points = new PolygonPoint[vertexCount]; for(int i=0; i<vertexCount; i++) { do { if( i%250 == 0 ) { radius += scale/2*(0.5 - Math.random()); } else if( i%50 == 0 ) { radius += scale/5*(0.5 - Math.random()); } else { radius += 25*scale/vertexCount*(0.5 - Math.random()); } radius = radius > scale/2 ? scale/2 : radius; radius = radius < scale/10 ? scale/10 : radius; } while( radius < scale/10 || radius > scale/2 ); point = new PolygonPoint( radius*Math.cos( (PI_2*i)/vertexCount ), radius*Math.sin( (PI_2*i)/vertexCount ) ); points[i] = point; } return new Polygon( points ); } public static Polygon RandomCircleSweep2( double scale, int vertexCount ) { PolygonPoint point; PolygonPoint[] points; double radius = scale/4; points = new PolygonPoint[vertexCount]; for(int i=0; i<vertexCount; i++) { do { radius += scale/5*(0.5 - Math.random()); radius = radius > scale/2 ? scale/2 : radius; radius = radius < scale/10 ? scale/10 : radius; } while( radius < scale/10 || radius > scale/2 ); point = new PolygonPoint( radius*Math.cos( (PI_2*i)/vertexCount ), radius*Math.sin( (PI_2*i)/vertexCount ) ); points[i] = point; } return new Polygon( points ); } }
Java
package org.poly2tri.triangulation.util; import java.util.ArrayList; import java.util.List; import org.poly2tri.triangulation.TriangulationPoint; import org.poly2tri.triangulation.point.TPoint; public class PointGenerator { public static List<TriangulationPoint> uniformDistribution( int n, double scale ) { ArrayList<TriangulationPoint> points = new ArrayList<TriangulationPoint>(); for( int i=0; i<n; i++ ) { points.add( new TPoint( scale*(0.5 - Math.random()), scale*(0.5 - Math.random()) ) ); } return points; } public static List<TriangulationPoint> uniformGrid( int n, double scale ) { double x=0; double size = scale/n; double halfScale = 0.5*scale; ArrayList<TriangulationPoint> points = new ArrayList<TriangulationPoint>(); for( int i=0; i<n+1; i++ ) { x = halfScale - i*size; for( int j=0; j<n+1; j++ ) { points.add( new TPoint( x, halfScale - j*size ) ); } } return points; } }
Java
/* Poly2Tri * Copyright (c) 2009-2010, Poly2Tri Contributors * http://code.google.com/p/poly2tri/ * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Poly2Tri nor the names of its contributors may be * used to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.poly2tri.triangulation; public interface TriangulationProcessListener { public void triangulationEvent( TriangulationProcessEvent e, Triangulatable unit ); }
Java
package org.poly2tri.transform.coordinate; /** * A transform that aligns the XY plane normal [0,0,1] with any given target normal * * http://www.cs.brown.edu/~jfh/papers/Moller-EBA-1999/paper.pdf * * @author thahlen@gmail.com * */ public class XYToAnyTransform extends Matrix3Transform { /** * Assumes target normal is normalized */ public XYToAnyTransform( double nx, double ny, double nz ) { setTargetNormal( nx, ny, nz ); } /** * Assumes target normal is normalized * * @param nx * @param ny * @param nz */ public void setTargetNormal( double nx, double ny, double nz ) { double h,f,c,vx,vy,hvx; vx = ny; vy = -nx; c = nz; h = (1-c)/(1-c*c); hvx = h*vx; f = (c < 0) ? -c : c; if( f < 1.0 - 1.0E-4 ) { m00=c + hvx*vx; m01=hvx*vy; m02=-vy; m10=hvx*vy; m11=c + h*vy*vy; m12=vx; m20=vy; m21=-vx; m22=c; } else { // if "from" and "to" vectors are nearly parallel m00=1; m01=0; m02=0; m10=0; m11=1; m12=0; m20=0; m21=0; if( c > 0 ) { m22=1; } else { m22=-1; } } } }
Java
package org.poly2tri.transform.coordinate; import java.util.List; import org.poly2tri.geometry.primitives.Point; public class NoTransform implements CoordinateTransform { public void transform( Point p, Point store ) { store.set( p.getX(), p.getY(), p.getZ() ); } public void transform( Point p ) { } public void transform( List<? extends Point> list ) { } }
Java
package org.poly2tri.transform.coordinate; /** * A transform that aligns given source normal with the XY plane normal [0,0,1] * * @author thahlen@gmail.com */ public class AnyToXYTransform extends Matrix3Transform { /** * Assumes source normal is normalized */ public AnyToXYTransform( double nx, double ny, double nz ) { setSourceNormal( nx, ny, nz ); } /** * Assumes source normal is normalized * * @param nx * @param ny * @param nz */ public void setSourceNormal( double nx, double ny, double nz ) { double h,f,c,vx,vy,hvx; vx = -ny; vy = nx; c = nz; h = (1-c)/(1-c*c); hvx = h*vx; f = (c < 0) ? -c : c; if( f < 1.0 - 1.0E-4 ) { m00=c + hvx*vx; m01=hvx*vy; m02=-vy; m10=hvx*vy; m11=c + h*vy*vy; m12=vx; m20=vy; m21=-vx; m22=c; } else { // if "from" and "to" vectors are nearly parallel m00=1; m01=0; m02=0; m10=0; m11=1; m12=0; m20=0; m21=0; if( c > 0 ) { m22=1; } else { m22=-1; } } } }
Java
package org.poly2tri.transform.coordinate; import java.util.List; import org.poly2tri.geometry.primitives.Point; public abstract class Matrix3Transform implements CoordinateTransform { protected double m00,m01,m02,m10,m11,m12,m20,m21,m22; public void transform( Point p, Point store ) { final double px = p.getX(); final double py = p.getY(); final double pz = p.getZ(); store.set(m00 * px + m01 * py + m02 * pz, m10 * px + m11 * py + m12 * pz, m20 * px + m21 * py + m22 * pz ); } public void transform( Point p ) { final double px = p.getX(); final double py = p.getY(); final double pz = p.getZ(); p.set(m00 * px + m01 * py + m02 * pz, m10 * px + m11 * py + m12 * pz, m20 * px + m21 * py + m22 * pz ); } public void transform( List<? extends Point> list ) { for( Point p : list ) { transform( p ); } } }
Java
package org.poly2tri.transform.coordinate; import java.util.List; import org.poly2tri.geometry.primitives.Point; public abstract interface CoordinateTransform { public abstract void transform( Point p, Point store ); public abstract void transform( Point p ); public abstract void transform( List<? extends Point> list ); }
Java
/* Poly2Tri * Copyright (c) 2009-2010, Poly2Tri Contributors * http://code.google.com/p/poly2tri/ * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Poly2Tri nor the names of its contributors may be * used to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.poly2tri; import org.poly2tri.geometry.polygon.Polygon; import org.poly2tri.geometry.polygon.PolygonSet; import org.poly2tri.triangulation.Triangulatable; import org.poly2tri.triangulation.TriangulationAlgorithm; import org.poly2tri.triangulation.TriangulationContext; import org.poly2tri.triangulation.TriangulationMode; import org.poly2tri.triangulation.TriangulationProcess; import org.poly2tri.triangulation.delaunay.sweep.DTSweep; import org.poly2tri.triangulation.delaunay.sweep.DTSweepContext; import org.poly2tri.triangulation.sets.ConstrainedPointSet; import org.poly2tri.triangulation.sets.PointSet; import org.poly2tri.triangulation.util.PolygonGenerator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Poly2Tri { private final static Logger logger = LoggerFactory.getLogger( Poly2Tri.class ); private static final TriangulationAlgorithm _defaultAlgorithm = TriangulationAlgorithm.DTSweep; public static void triangulate( PolygonSet ps ) { TriangulationContext<?> tcx = createContext( _defaultAlgorithm ); for( Polygon p : ps.getPolygons() ) { tcx.prepareTriangulation( p ); triangulate( tcx ); tcx.clear(); } } public static void triangulate( Polygon p ) { triangulate( _defaultAlgorithm, p ); } public static void triangulate( ConstrainedPointSet cps ) { triangulate( _defaultAlgorithm, cps ); } public static void triangulate( PointSet ps ) { triangulate( _defaultAlgorithm, ps ); } public static TriangulationContext<?> createContext( TriangulationAlgorithm algorithm ) { switch( algorithm ) { case DTSweep: default: return new DTSweepContext(); } } public static void triangulate( TriangulationAlgorithm algorithm, Triangulatable t ) { TriangulationContext<?> tcx; // long time = System.nanoTime(); tcx = createContext( algorithm ); tcx.prepareTriangulation( t ); triangulate( tcx ); // logger.info( "Triangulation of {} points [{}ms]", tcx.getPoints().size(), ( System.nanoTime() - time ) / 1e6 ); } public static void triangulate( TriangulationContext<?> tcx ) { switch( tcx.algorithm() ) { case DTSweep: default: DTSweep.triangulate( (DTSweepContext)tcx ); } } /** * Will do a warmup run to let the JVM optimize the triangulation code */ public static void warmup() { /* * After a method is run 10000 times, the Hotspot compiler will compile * it into native code. Periodically, the Hotspot compiler may recompile * the method. After an unspecified amount of time, then the compilation * system should become quiet. */ Polygon poly = PolygonGenerator.RandomCircleSweep2( 50, 50000 ); TriangulationProcess process = new TriangulationProcess(); process.triangulate( poly ); } }
Java
/*************************************** * * Android Bluetooth Oscilloscope * yus - projectproto.blogspot.com * September 2010 * ***************************************/ package org.projectproto.yuscope; import android.graphics.Canvas; import android.view.SurfaceHolder; public class WaveformPlotThread extends Thread { private SurfaceHolder holder; private WaveformView plot_area; private boolean _run = false; public WaveformPlotThread(SurfaceHolder surfaceHolder, WaveformView view){ holder = surfaceHolder; plot_area = view; } public void setRunning(boolean run){ _run = run; } @Override public void run(){ Canvas c; while(_run){ c = null; try{ c = holder.lockCanvas(null); synchronized (holder) { plot_area.PlotPoints(c); } }finally{ if(c!=null){ holder.unlockCanvasAndPost(c); } } } } }
Java
/*************************************** * * Android Bluetooth Oscilloscope * yus - projectproto.blogspot.com * September 2010 * ***************************************/ package org.projectproto.yuscope; import android.app.Activity; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.os.PowerManager; import android.view.View; import android.view.Window; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.RadioButton; import android.widget.TextView; import android.widget.Toast; import android.widget.ToggleButton; public class BluetoothOscilloscope extends Activity implements Button.OnClickListener{ // Message types sent from the BluetoothRfcommClient Handler public static final int MESSAGE_STATE_CHANGE = 1; public static final int MESSAGE_READ = 2; public static final int MESSAGE_WRITE = 3; public static final int MESSAGE_DEVICE_NAME = 4; public static final int MESSAGE_TOAST = 5; // Key names received from the BluetoothRfcommClient Handler public static final String DEVICE_NAME = "device_name"; public static final String TOAST = "toast"; // Intent request codes private static final int REQUEST_CONNECT_DEVICE = 1; private static final int REQUEST_ENABLE_BT = 2; // bt-uart constants private static final int MAX_SAMPLES = 640; private static final int MAX_LEVEL = 240; private static final int DATA_START = (MAX_LEVEL + 1); private static final int DATA_END = (MAX_LEVEL + 2); private static final byte REQ_DATA = 0x00; private static final byte ADJ_HORIZONTAL = 0x01; private static final byte ADJ_VERTICAL = 0x02; private static final byte ADJ_POSITION = 0x03; private static final byte CHANNEL1 = 0x01; private static final byte CHANNEL2 = 0x02; // Run/Pause status private boolean bReady = false; // receive data private int[] ch1_data = new int[MAX_SAMPLES/2]; private int[] ch2_data = new int[MAX_SAMPLES/2]; private int dataIndex=0, dataIndex1=0, dataIndex2=0; private boolean bDataAvailable=false; // Layout Views private TextView mBTStatus; private Button mConnectButton; private RadioButton rb1, rb2; private TextView ch1pos_label, ch2pos_label; private Button btn_pos_up, btn_pos_down; private TextView ch1_scale, ch2_scale; private Button btn_scale_up, btn_scale_down; private TextView time_per_div; private Button timebase_inc, timebase_dec; private ToggleButton run_buton; public WaveformView mWaveform = null; // Name of the connected device private String mConnectedDeviceName = null; // Local Bluetooth adapter private BluetoothAdapter mBluetoothAdapter = null; // Member object for the RFCOMM services private BluetoothRfcommClient mRfcommClient = null; static String[] timebase = {"5us", "10us", "20us", "50us", "100us", "200us", "500us", "1ms", "2ms", "5ms", "10ms", "20ms", "50ms" }; static String[] ampscale = {"10mV", "20mV", "50mV", "100mV", "200mV", "500mV", "1V", "2V", "GND"}; static byte timebase_index = 5; static byte ch1_index = 4, ch2_index = 5; static byte ch1_pos = 24, ch2_pos = 17; // 0 to 40 // stay awake protected PowerManager.WakeLock mWakeLock; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Set up the window layout requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.main); // Get local Bluetooth adapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); // If the adapter is null, then Bluetooth is not supported if (mBluetoothAdapter == null) { Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show(); finish(); return; } // Prevent phone from sleeping PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); this.mWakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "My Tag"); this.mWakeLock.acquire(); } @Override public void onStart(){ super.onStart(); // If BT is not on, request that it be enabled. if (!mBluetoothAdapter.isEnabled()){ Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableIntent, REQUEST_ENABLE_BT); } // Otherwise, setup the Oscillosope session else{ if (mRfcommClient == null) setupOscilloscope(); } } @Override public synchronized void onResume(){ super.onResume(); // Performing this check in onResume() covers the case in which BT was // not enabled during onStart(), so we were paused to enable it... // onResume() will be called when ACTION_REQUEST_ENABLE activity returns. if (mRfcommClient != null) { // Only if the state is STATE_NONE, do we know that we haven't started already if (mRfcommClient.getState() == BluetoothRfcommClient.STATE_NONE) { // Start the Bluetooth RFCOMM services mRfcommClient.start(); } } } @Override public void onClick(View v){ int buttonID; buttonID = v.getId(); switch (buttonID){ case R.id.btn_position_up : if(rb1.isChecked() && (ch1_pos<38) ){ ch1_pos += 1; ch1pos_label.setPadding(0, toScreenPos(ch1_pos), 0, 0); sendMessage( new String(new byte[] {ADJ_POSITION, CHANNEL1, ch1_pos}) ); } else if(rb2.isChecked() && (ch2_pos<38) ){ ch2_pos += 1; ch2pos_label.setPadding(0, toScreenPos(ch2_pos), 0, 0); sendMessage( new String(new byte[] {ADJ_POSITION, CHANNEL2, ch2_pos}) ); } break; case R.id.btn_position_down : if(rb1.isChecked() && (ch1_pos>4) ){ ch1_pos -= 1; ch1pos_label.setPadding(0, toScreenPos(ch1_pos), 0, 0); sendMessage( new String(new byte[] {ADJ_POSITION, CHANNEL1, ch1_pos}) ); } else if(rb2.isChecked() && (ch2_pos>4) ){ ch2_pos -= 1; ch2pos_label.setPadding(0, toScreenPos(ch2_pos), 0, 0); sendMessage( new String(new byte[] {ADJ_POSITION, CHANNEL2, ch2_pos}) ); } break; case R.id.btn_scale_increase : if(rb1.isChecked() && (ch1_index>0)){ ch1_scale.setText(ampscale[--ch1_index]); sendMessage( new String(new byte[] {ADJ_VERTICAL, CHANNEL1, ch1_index}) ); } else if(rb2.isChecked() && (ch2_index>0)){ ch2_scale.setText(ampscale[--ch2_index]); sendMessage( new String(new byte[] {ADJ_VERTICAL, CHANNEL2, ch2_index}) ); } break; case R.id.btn_scale_decrease : if(rb1.isChecked() && (ch1_index<(ampscale.length-1))){ ch1_scale.setText(ampscale[++ch1_index]); sendMessage( new String(new byte[] {ADJ_VERTICAL, CHANNEL1, ch1_index}) ); } else if(rb2.isChecked() && (ch2_index<(ampscale.length-1))){ ch2_scale.setText(ampscale[++ch2_index]); sendMessage( new String(new byte[] {ADJ_VERTICAL, CHANNEL2, ch2_index}) ); } break; case R.id.btn_timebase_increase : if(timebase_index<(timebase.length-1)){ time_per_div.setText(timebase[++timebase_index]); sendMessage( new String(new byte[] {ADJ_HORIZONTAL, timebase_index}) ); } break; case R.id.btn_timebase_decrease : if(timebase_index>0){ time_per_div.setText(timebase[--timebase_index]); sendMessage( new String(new byte[] {ADJ_HORIZONTAL, timebase_index}) ); } break; case R.id.tbtn_runtoggle : if(run_buton.isChecked()){ sendMessage( new String(new byte[] { ADJ_HORIZONTAL, timebase_index, ADJ_VERTICAL, CHANNEL1, ch1_index, ADJ_VERTICAL, CHANNEL2, ch2_index, ADJ_POSITION, CHANNEL1, ch1_pos, ADJ_POSITION, CHANNEL2, ch2_pos, REQ_DATA}) ); bReady = true; }else{ bReady = false; } break; } } @Override public void onDestroy(){ super.onDestroy(); // Stop the Bluetooth RFCOMM services if (mRfcommClient != null) mRfcommClient.stop(); // release screen being on if (mWakeLock.isHeld()) { mWakeLock.release(); } } /** * Sends a message. * @param message A string of text to send. */ private void sendMessage(String message){ // Check that we're actually connected before trying anything if (mRfcommClient.getState() != BluetoothRfcommClient.STATE_CONNECTED) { Toast.makeText(this, R.string.not_connected, Toast.LENGTH_SHORT).show(); return; } // Check that there's actually something to send if (message.length() > 0) { // Get the message bytes and tell the BluetoothRfcommClient to write byte[] send = message.getBytes(); mRfcommClient.write(send); } } private void setupOscilloscope(){ mBTStatus = (TextView) findViewById(R.id.txt_btstatus); mConnectButton = (Button) findViewById(R.id.button_connect); mConnectButton.setOnClickListener(new OnClickListener(){ public void onClick(View arg0) { BTConnect(); } }); rb1 = (RadioButton)findViewById(R.id.rbtn_ch1); rb2 = (RadioButton)findViewById(R.id.rbtn_ch2); ch1pos_label = (TextView) findViewById(R.id.txt_ch1pos); ch2pos_label = (TextView) findViewById(R.id.txt_ch2pos); ch1pos_label.setPadding(0, toScreenPos(ch1_pos), 0, 0); ch2pos_label.setPadding(0, toScreenPos(ch2_pos), 0, 0); btn_pos_up = (Button) findViewById(R.id.btn_position_up); btn_pos_down = (Button) findViewById(R.id.btn_position_down); btn_pos_up.setOnClickListener(this); btn_pos_down.setOnClickListener(this); ch1_scale = (TextView) findViewById(R.id.txt_ch1_scale); ch2_scale = (TextView) findViewById(R.id.txt_ch2_scale); ch1_scale.setText(ampscale[ch1_index]); ch2_scale.setText(ampscale[ch2_index]); btn_scale_up = (Button) findViewById(R.id.btn_scale_increase); btn_scale_down = (Button) findViewById(R.id.btn_scale_decrease); btn_scale_up.setOnClickListener(this); btn_scale_down.setOnClickListener(this); time_per_div = (TextView)findViewById(R.id.txt_timebase); time_per_div.setText(timebase[timebase_index]); timebase_inc = (Button) findViewById(R.id.btn_timebase_increase); timebase_dec = (Button) findViewById(R.id.btn_timebase_decrease); timebase_inc.setOnClickListener(this); timebase_dec.setOnClickListener(this); run_buton = (ToggleButton) findViewById(R.id.tbtn_runtoggle); run_buton.setOnClickListener(this); // Initialize the BluetoothRfcommClient to perform bluetooth connections mRfcommClient = new BluetoothRfcommClient(this, mHandler); // waveform / plot area mWaveform = (WaveformView)findViewById(R.id.WaveformArea); } private void BTConnect(){ Intent serverIntent = new Intent(this, DeviceListActivity.class); startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE); } private int toScreenPos(byte position){ //return ( (int)MAX_LEVEL - (int)position*6 ); return ( (int)MAX_LEVEL - (int)position*6 - 7); } // The Handler that gets information back from the BluetoothRfcommClient private final Handler mHandler = new Handler(){ @Override public void handleMessage(Message msg){ switch (msg.what){ case MESSAGE_STATE_CHANGE: switch (msg.arg1){ case BluetoothRfcommClient.STATE_CONNECTED: mBTStatus.setText(R.string.title_connected_to); mBTStatus.append("\n" + mConnectedDeviceName); break; case BluetoothRfcommClient.STATE_CONNECTING: mBTStatus.setText(R.string.title_connecting); break; case BluetoothRfcommClient.STATE_NONE: mBTStatus.setText(R.string.title_not_connected); break; } break; case MESSAGE_READ: // todo: implement receive data buffering byte[] readBuf = (byte[]) msg.obj; int data_length = msg.arg1; for(int x=0; x<data_length; x++){ int raw = UByte(readBuf[x]); if( raw>MAX_LEVEL ){ if( raw==DATA_START ){ bDataAvailable = true; dataIndex = 0; dataIndex1=0; dataIndex2=0; } else if( (raw==DATA_END) || (dataIndex>=MAX_SAMPLES) ){ bDataAvailable = false; dataIndex = 0; dataIndex1=0; dataIndex2=0; mWaveform.set_data(ch1_data, ch2_data); if(bReady){ // send "REQ_DATA" again BluetoothOscilloscope.this.sendMessage( new String(new byte[] {REQ_DATA}) ); } //break; } } else if( (bDataAvailable) && (dataIndex<(MAX_SAMPLES)) ){ // valid data if((dataIndex++)%2==0) ch1_data[dataIndex1++] = raw; // even data else ch2_data[dataIndex2++] = raw; // odd data } } break; case MESSAGE_DEVICE_NAME: // save the connected device's name mConnectedDeviceName = msg.getData().getString(DEVICE_NAME); Toast.makeText(getApplicationContext(), "Connected to " + mConnectedDeviceName, Toast.LENGTH_SHORT).show(); break; case MESSAGE_TOAST: Toast.makeText(getApplicationContext(), msg.getData().getString(TOAST), Toast.LENGTH_SHORT).show(); break; } } // signed to unsigned private int UByte(byte b){ if(b<0) // if negative return (int)( (b&0x7F) + 128 ); else return (int)b; } }; public void onActivityResult(int requestCode, int resultCode, Intent data){ switch (requestCode) { case REQUEST_CONNECT_DEVICE: // When DeviceListActivity returns with a device to connect if (resultCode == Activity.RESULT_OK){ // Get the device MAC address String address = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS); // Get the BLuetoothDevice object BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address); // Attempt to connect to the device mRfcommClient.connect(device); } break; case REQUEST_ENABLE_BT: // When the request to enable Bluetooth returns if (resultCode == Activity.RESULT_OK){ // Bluetooth is now enabled, so set up the oscilloscope setupOscilloscope(); }else{ // User did not enable Bluetooth or an error occured Toast.makeText(this, R.string.bt_not_enabled_leaving, Toast.LENGTH_SHORT).show(); finish(); } break; } } }
Java
/*************************************** * * Android Bluetooth Oscilloscope * yus - projectproto.blogspot.com * September 2010 * ***************************************/ package org.projectproto.yuscope; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.UUID; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothSocket; import android.content.Context; import android.os.Bundle; import android.os.Handler; import android.os.Message; /** * **/ public class BluetoothRfcommClient { // Unique UUID for this application private static final UUID MY_UUID = //UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66"); UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); // Member fields private final BluetoothAdapter mAdapter; private final Handler mHandler; private ConnectThread mConnectThread; private ConnectedThread mConnectedThread; private int mState; // Constants that indicate the current connection state public static final int STATE_NONE = 0; // we're doing nothing //public static final int STATE_LISTEN = 1; // now listening for incoming connections public static final int STATE_CONNECTING = 2; // now initiating an outgoing connection public static final int STATE_CONNECTED = 3; // now connected to a remote device /** * Constructor. Prepares a new BluetoothChat session. * - context - The UI Activity Context * - handler - A Handler to send messages back to the UI Activity */ public BluetoothRfcommClient(Context context, Handler handler) { mAdapter = BluetoothAdapter.getDefaultAdapter(); mState = STATE_NONE; mHandler = handler; } /** * Set the current state o * */ private synchronized void setState(int state) { mState = state; // Give the new state to the Handler so the UI Activity can update mHandler.obtainMessage(BluetoothOscilloscope.MESSAGE_STATE_CHANGE, state, -1).sendToTarget(); } /** * Return the current connection state. */ public synchronized int getState() { return mState; } /** * Start the Rfcomm client service. * */ public synchronized void start() { // Cancel any thread attempting to make a connection if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;} // Cancel any thread currently running a connection if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;} setState(STATE_NONE); } /** * Start the ConnectThread to initiate a connection to a remote device. * - device - The BluetoothDevice to connect */ public synchronized void connect(BluetoothDevice device) { // Cancel any thread attempting to make a connection if (mState == STATE_CONNECTING) { if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;} } // Cancel any thread currently running a connection if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;} // Start the thread to connect with the given device mConnectThread = new ConnectThread(device); mConnectThread.start(); setState(STATE_CONNECTING); } /** * Start the ConnectedThread to begin managing a Bluetooth connection * - socket - The BluetoothSocket on which the connection was made * - device - The BluetoothDevice that has been connected */ public synchronized void connected(BluetoothSocket socket, BluetoothDevice device) { // Cancel the thread that completed the connection if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;} // Cancel any thread currently running a connection if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;} // Start the thread to manage the connection and perform transmissions mConnectedThread = new ConnectedThread(socket); mConnectedThread.start(); // Send the name of the connected device back to the UI Activity Message msg = mHandler.obtainMessage(BluetoothOscilloscope.MESSAGE_DEVICE_NAME); Bundle bundle = new Bundle(); bundle.putString(BluetoothOscilloscope.DEVICE_NAME, device.getName()); msg.setData(bundle); mHandler.sendMessage(msg); setState(STATE_CONNECTED); } /** * Stop all threads */ public synchronized void stop() { if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;} if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;} setState(STATE_NONE); } /** * Write to the ConnectedThread in an unsynchronized manner * - out - The bytes to write - ConnectedThread#write(byte[]) */ public void write(byte[] out) { // Create temporary object ConnectedThread r; // Synchronize a copy of the ConnectedThread synchronized (this) { if (mState != STATE_CONNECTED) return; r = mConnectedThread; } // Perform the write unsynchronized r.write(out); } /** * Indicate that the connection attempt failed and notify the UI Activity. */ private void connectionFailed() { setState(STATE_NONE); // Send a failure message back to the Activity Message msg = mHandler.obtainMessage(BluetoothOscilloscope.MESSAGE_TOAST); Bundle bundle = new Bundle(); bundle.putString(BluetoothOscilloscope.TOAST, "Unable to connect device"); msg.setData(bundle); mHandler.sendMessage(msg); } /** * Indicate that the connection was lost and notify the UI Activity. */ private void connectionLost() { setState(STATE_NONE); // Send a failure message back to the Activity Message msg = mHandler.obtainMessage(BluetoothOscilloscope.MESSAGE_TOAST); Bundle bundle = new Bundle(); bundle.putString(BluetoothOscilloscope.TOAST, "Device connection was lost"); msg.setData(bundle); mHandler.sendMessage(msg); } /** * This thread runs while attempting to make an outgoing connection * with a device. It runs straight through; the connection either * succeeds or fails. */ private class ConnectThread extends Thread { private final BluetoothSocket mmSocket; private final BluetoothDevice mmDevice; public ConnectThread(BluetoothDevice device) { mmDevice = device; BluetoothSocket tmp = null; // Get a BluetoothSocket for a connection with the given BluetoothDevice try { tmp = device.createRfcommSocketToServiceRecord(MY_UUID); } catch (IOException e) { // } mmSocket = tmp; } public void run() { setName("ConnectThread"); // Always cancel discovery because it will slow down a connection mAdapter.cancelDiscovery(); // Make a connection to the BluetoothSocket try { // This is a blocking call and will only return on a successful connection or an exception mmSocket.connect(); } catch (IOException e) { connectionFailed(); // Close the socket try { mmSocket.close(); } catch (IOException e2) { // } // Start the service over to restart listening mode BluetoothRfcommClient.this.start(); return; } // Reset the ConnectThread because we're done synchronized (BluetoothRfcommClient.this) { mConnectThread = null; } // Start the connected thread connected(mmSocket, mmDevice); } public void cancel() { try { mmSocket.close(); } catch (IOException e) { // } } } /** * This thread runs during a connection with a remote device. * It handles all incoming and outgoing transmissions. */ private class ConnectedThread extends Thread { private final BluetoothSocket mmSocket; private final InputStream mmInStream; private final OutputStream mmOutStream; public ConnectedThread(BluetoothSocket socket) { mmSocket = socket; InputStream tmpIn = null; OutputStream tmpOut = null; // Get the BluetoothSocket input and output streams try { tmpIn = socket.getInputStream(); tmpOut = socket.getOutputStream(); } catch (IOException e) { } mmInStream = tmpIn; mmOutStream = tmpOut; } public void run() { byte[] buffer = new byte[1024]; int bytes; // Keep listening to the InputStream while connected while (true) { try { // Read from the InputStream bytes = mmInStream.read(buffer); // Send the obtained bytes to the UI Activity mHandler.obtainMessage(BluetoothOscilloscope.MESSAGE_READ, bytes, -1, buffer) .sendToTarget(); } catch (IOException e) { // connectionLost(); break; } } } /** * Write to the connected OutStream. */ public void write(byte[] buffer) { try { mmOutStream.write(buffer); // Share the sent message back to the UI Activity mHandler.obtainMessage(BluetoothOscilloscope.MESSAGE_WRITE, -1, -1, buffer) .sendToTarget(); } catch (IOException e) { // } } public void cancel() { try { mmSocket.close(); } catch (IOException e) { // } } } }
Java
/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.projectproto.yuscope; import java.util.Set; import android.app.Activity; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.view.View; import android.view.Window; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import android.widget.AdapterView.OnItemClickListener; /** * This Activity appears as a dialog. It lists any paired devices and * devices detected in the area after discovery. When a device is chosen * by the user, the MAC address of the device is sent back to the parent * Activity in the result Intent. */ public class DeviceListActivity extends Activity { // Return Intent extra public static String EXTRA_DEVICE_ADDRESS = "device_address"; // Member fields private BluetoothAdapter mBtAdapter; private ArrayAdapter<String> mPairedDevicesArrayAdapter; private ArrayAdapter<String> mNewDevicesArrayAdapter; @Override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); // Setup the window requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); setContentView(R.layout.device_list); // Set result CANCELED incase the user backs out setResult(Activity.RESULT_CANCELED); // Initialize the button to perform device discovery Button scanButton = (Button) findViewById(R.id.button_scan); scanButton.setOnClickListener(new OnClickListener(){ public void onClick(View v){ doDiscovery(); v.setVisibility(View.GONE); } }); // Initialize array adapters. One for already paired devices and // one for newly discovered devices mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name); mNewDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name); // Find and set up the ListView for paired devices ListView pairedListView = (ListView) findViewById(R.id.paired_devices); pairedListView.setAdapter(mPairedDevicesArrayAdapter); pairedListView.setOnItemClickListener(mDeviceClickListener); // Find and set up the ListView for newly discovered devices ListView newDevicesListView = (ListView) findViewById(R.id.new_devices); newDevicesListView.setAdapter(mNewDevicesArrayAdapter); newDevicesListView.setOnItemClickListener(mDeviceClickListener); // Register for broadcasts when a device is discovered IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); this.registerReceiver(mReceiver, filter); // Register for broadcasts when discovery has finished filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); this.registerReceiver(mReceiver, filter); // Get the local Bluetooth adapter mBtAdapter = BluetoothAdapter.getDefaultAdapter(); // Get a set of currently paired devices Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices(); // If there are paired devices, add each one to the ArrayAdapter if (pairedDevices.size() > 0){ findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE); for (BluetoothDevice device : pairedDevices){ mPairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress()); } }else{ String noDevices = getResources().getText(R.string.none_paired).toString(); mPairedDevicesArrayAdapter.add(noDevices); } } @Override protected void onDestroy(){ super.onDestroy(); // Make sure we're not doing discovery anymore if (mBtAdapter != null) { mBtAdapter.cancelDiscovery(); } // Unregister broadcast listeners this.unregisterReceiver(mReceiver); } /** * Start device discover with the BluetoothAdapter */ private void doDiscovery(){ // Indicate scanning in the title setProgressBarIndeterminateVisibility(true); setTitle(R.string.scanning); // Turn on sub-title for new devices findViewById(R.id.title_new_devices).setVisibility(View.VISIBLE); // If we're already discovering, stop it if (mBtAdapter.isDiscovering()) { mBtAdapter.cancelDiscovery(); } // Request discover from BluetoothAdapter mBtAdapter.startDiscovery(); } // The on-click listener for all devices in the ListViews private OnItemClickListener mDeviceClickListener = new OnItemClickListener(){ public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3){ // Cancel discovery because it's costly and we're about to connect mBtAdapter.cancelDiscovery(); // Get the device MAC address, which is the last 17 chars in the View String info = ((TextView) v).getText().toString(); String address = info.substring(info.length() - 17); // Create the result Intent and include the MAC address Intent intent = new Intent(); intent.putExtra(EXTRA_DEVICE_ADDRESS, address); // Set result and finish this Activity setResult(Activity.RESULT_OK, intent); finish(); } }; // The BroadcastReceiver that listens for discovered devices and // changes the title when discovery is finished private final BroadcastReceiver mReceiver = new BroadcastReceiver(){ @Override public void onReceive(Context context, Intent intent){ String action = intent.getAction(); // When discovery finds a device if (BluetoothDevice.ACTION_FOUND.equals(action)){ // Get the BluetoothDevice object from the Intent BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); // If it's already paired, skip it, because it's been listed already if (device.getBondState() != BluetoothDevice.BOND_BONDED){ mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress()); } } // When discovery is finished, change the Activity title else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){ setProgressBarIndeterminateVisibility(false); setTitle(R.string.select_device); if (mNewDevicesArrayAdapter.getCount() == 0){ String noDevices = getResources().getText(R.string.none_found).toString(); mNewDevicesArrayAdapter.add(noDevices); } } } }; }
Java
/*************************************** * * Android Bluetooth Oscilloscope * yus - projectproto.blogspot.com * September 2010 * ***************************************/ package org.projectproto.yuscope; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.util.AttributeSet; import android.view.SurfaceHolder; import android.view.SurfaceView; public class WaveformView extends SurfaceView implements SurfaceHolder.Callback{ // plot area size private final static int WIDTH = 320; private final static int HEIGHT = 240; private static int[] ch1_data = new int[WIDTH]; private static int[] ch2_data = new int[WIDTH]; private static int ch1_pos = 100; //HEIGHT/2; private static int ch2_pos = 140; //HEIGHT/2; private WaveformPlotThread plot_thread; private Paint ch1_color = new Paint(); private Paint ch2_color = new Paint(); private Paint grid_paint = new Paint(); private Paint cross_paint = new Paint(); private Paint outline_paint = new Paint(); public WaveformView(Context context, AttributeSet attrs){ super(context, attrs); getHolder().addCallback(this); // initial values for(int x=0; x<WIDTH; x++){ ch1_data[x] = ch1_pos; ch2_data[x] = ch2_pos; } plot_thread = new WaveformPlotThread(getHolder(), this); ch1_color.setColor(Color.YELLOW); ch2_color.setColor(Color.RED); grid_paint.setColor(Color.rgb(100, 100, 100)); cross_paint.setColor(Color.rgb(70, 100, 70)); outline_paint.setColor(Color.GREEN); } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height){ } @Override public void surfaceCreated(SurfaceHolder holder){ plot_thread.setRunning(true); plot_thread.start(); } @Override public void surfaceDestroyed(SurfaceHolder holder){ boolean retry = true; plot_thread.setRunning(false); while (retry){ try{ plot_thread.join(); retry = false; }catch(InterruptedException e){ } } } @Override public void onDraw(Canvas canvas){ PlotPoints(canvas); } public void set_data(int[] data1, int[] data2 ){ plot_thread.setRunning(false); for(int x=0; x<WIDTH; x++){ // channel 1 if(x<(data1.length)){ ch1_data[x] = HEIGHT-data1[x]+1; }else{ ch1_data[x] = ch1_pos; } // channel 2 if(x<(data1.length)){ ch2_data[x] = HEIGHT-data2[x]+1; }else{ ch2_data[x] = ch2_pos; } } plot_thread.setRunning(true); } public void PlotPoints(Canvas canvas){ // clear screen canvas.drawColor(Color.rgb(20, 20, 20)); // draw vertical grids for(int vertical = 1; vertical<10; vertical++){ canvas.drawLine( vertical*(WIDTH/10)+1, 1, vertical*(WIDTH/10)+1, HEIGHT+1, grid_paint); } // draw horizontal grids for(int horizontal = 1; horizontal<10; horizontal++){ canvas.drawLine( 1, horizontal*(HEIGHT/10)+1, WIDTH+1, horizontal*(HEIGHT/10)+1, grid_paint); } // draw outline canvas.drawLine(0, 0, (WIDTH+1), 0, outline_paint); // top canvas.drawLine((WIDTH+1), 0, (WIDTH+1), (HEIGHT+1), outline_paint); //right canvas.drawLine(0, (HEIGHT+1), (WIDTH+1), (HEIGHT+1), outline_paint); // bottom canvas.drawLine(0, 0, 0, (HEIGHT+1), outline_paint); //left // plot data for(int x=0; x<(WIDTH-1); x++){ canvas.drawLine(x+1, ch2_data[x], x+2, ch2_data[x+1], ch2_color); canvas.drawLine(x+1, ch1_data[x], x+2, ch1_data[x+1], ch1_color); } } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks; import com.google.android.apps.mytracks.content.Waypoint; import com.google.android.apps.mytracks.maps.SingleColorTrackPathPainter; import com.google.android.maps.MapView; import android.graphics.Canvas; import android.graphics.Path; import android.location.Location; import android.test.AndroidTestCase; /** * Tests for the MyTracks map overlay. * * @author Bartlomiej Niechwiej * @author Vangelis S. */ public class MapOverlayTest extends AndroidTestCase { private Canvas canvas; private MockMyTracksOverlay myTracksOverlay; private MapView mockView; @Override protected void setUp() throws Exception { super.setUp(); canvas = new Canvas(); myTracksOverlay = new MockMyTracksOverlay(getContext()); // Enable drawing. myTracksOverlay.setTrackDrawingEnabled(true); // Set a TrackPathPainter with a MockPath. myTracksOverlay.setTrackPathPainter(new SingleColorTrackPathPainter(getContext()) { @Override public Path newPath() { return new MockPath(); } }); mockView = null; } public void testAddLocation() throws Exception { Location location = new Location("gps"); location.setLatitude(10); location.setLongitude(20); myTracksOverlay.addLocation(location); assertEquals(1, myTracksOverlay.getNumLocations()); assertEquals(0, myTracksOverlay.getNumWaypoints()); location.setLatitude(20); location.setLongitude(30); myTracksOverlay.addLocation(location); assertEquals(2, myTracksOverlay.getNumLocations()); assertEquals(0, myTracksOverlay.getNumWaypoints()); assertNull(myTracksOverlay.getTrackPathPainter().getLastPath()); // Draw and make sure that we don't lose any point. myTracksOverlay.draw(canvas, mockView, false); assertEquals(2, myTracksOverlay.getNumLocations()); assertEquals(0, myTracksOverlay.getNumWaypoints()); assertNotNull(myTracksOverlay.getTrackPathPainter().getLastPath()); assertTrue(myTracksOverlay.getTrackPathPainter().getLastPath() instanceof MockPath); MockPath path = (MockPath) myTracksOverlay.getTrackPathPainter().getLastPath(); assertEquals(2, path.totalPoints); myTracksOverlay.draw(canvas, mockView, true); assertEquals(2, myTracksOverlay.getNumLocations()); assertEquals(0, myTracksOverlay.getNumWaypoints()); assertNotNull(myTracksOverlay.getTrackPathPainter().getLastPath()); } public void testClearPoints() throws Exception { Location location = new Location("gps"); location.setLatitude(10); location.setLongitude(20); myTracksOverlay.addLocation(location); assertEquals(1, myTracksOverlay.getNumLocations()); myTracksOverlay.clearPoints(); assertEquals(0, myTracksOverlay.getNumLocations()); // Same after drawing on canvas. final int locations = 100; for (int i = 0; i < locations; ++i) { myTracksOverlay.addLocation(location); } assertEquals(locations, myTracksOverlay.getNumLocations()); myTracksOverlay.draw(canvas, mockView, false); myTracksOverlay.draw(canvas, mockView, true); myTracksOverlay.clearPoints(); assertEquals(0, myTracksOverlay.getNumLocations()); } public void testAddWaypoint() throws Exception { Location location = new Location("gps"); location.setLatitude(10); location.setLongitude(20); Waypoint waypoint = new Waypoint(); waypoint.setLocation(location); myTracksOverlay.addWaypoint(waypoint); assertEquals(1, myTracksOverlay.getNumWaypoints()); assertEquals(0, myTracksOverlay.getNumLocations()); assertNull(myTracksOverlay.getTrackPathPainter().getLastPath()); final int waypoints = 10; for (int i = 0; i < waypoints; ++i) { waypoint = new Waypoint(); waypoint.setLocation(location); myTracksOverlay.addWaypoint(waypoint); } assertEquals(1 + waypoints, myTracksOverlay.getNumWaypoints()); assertEquals(0, myTracksOverlay.getNumLocations()); assertNull(myTracksOverlay.getTrackPathPainter().getLastPath()); } public void testClearWaypoints() throws Exception { Location location = new Location("gps"); location.setLatitude(10); location.setLongitude(20); Waypoint waypoint = new Waypoint(); waypoint.setLocation(location); myTracksOverlay.addWaypoint(waypoint); assertEquals(1, myTracksOverlay.getNumWaypoints()); myTracksOverlay.clearWaypoints(); assertEquals(0, myTracksOverlay.getNumWaypoints()); } public void testDrawing() { Location location = new Location("gps"); location.setLatitude(10); for (int i = 0; i < 40; ++i) { location.setLongitude(20 + i); Waypoint waypoint = new Waypoint(); waypoint.setLocation(location); myTracksOverlay.addWaypoint(waypoint); } for (int i = 0; i < 100; ++i) { location = new Location("gps"); location.setLatitude(20 + i / 2); location.setLongitude(150 - i); myTracksOverlay.addLocation(location); } // Shadow. myTracksOverlay.draw(canvas, mockView, true); // We don't expect to do anything if assertNull(myTracksOverlay.getTrackPathPainter().getLastPath()); assertEquals(40, myTracksOverlay.getNumWaypoints()); assertEquals(100, myTracksOverlay.getNumLocations()); // No shadow. myTracksOverlay.draw(canvas, mockView, false); assertNotNull(myTracksOverlay.getTrackPathPainter().getLastPath()); assertTrue(myTracksOverlay.getTrackPathPainter().getLastPath() instanceof MockPath); MockPath path = (MockPath) myTracksOverlay.getTrackPathPainter().getLastPath(); assertEquals(40, myTracksOverlay.getNumWaypoints()); assertEquals(100, myTracksOverlay.getNumLocations()); assertEquals(100, path.totalPoints); // TODO: Check the points from the path (and the segments). } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.services; import android.content.Context; import android.test.AndroidTestCase; import java.text.DateFormat; import java.util.Date; /** * Tests {@link DefaultTrackNameFactory} * * @author Matthew Simmons */ public class DefaultTrackNameFactoryTest extends AndroidTestCase { /** * A version of the factory which allows us to supply our own answer as to * whether a timestamp-based track name should be used. */ private static class MockDefaultTrackNameFactory extends DefaultTrackNameFactory { private final boolean useTimestamp; MockDefaultTrackNameFactory(Context context, boolean useTimestamp) { super(context); this.useTimestamp = useTimestamp; } @Override protected boolean useTimestampTrackName() { return useTimestamp; } } private static final long TIMESTAMP = 1288213406000L; public void testTimestampTrackName() { DefaultTrackNameFactory factory = new MockDefaultTrackNameFactory(getContext(), true); DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT); assertEquals(formatter.format(new Date(TIMESTAMP)), factory.newTrackName(1, TIMESTAMP)); } public void testIncrementingTrackName() { DefaultTrackNameFactory factory = new MockDefaultTrackNameFactory(getContext(), false); assertEquals("Track 1", factory.newTrackName(1, TIMESTAMP)); } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.services.tasks; import static com.google.android.testing.mocking.AndroidMock.capture; import static com.google.android.testing.mocking.AndroidMock.eq; import static com.google.android.testing.mocking.AndroidMock.expect; import static com.google.android.testing.mocking.AndroidMock.same; import com.google.android.apps.mytracks.stats.TripStatistics; import com.google.android.apps.mytracks.util.StringUtils; import com.google.android.testing.mocking.AndroidMock; import com.google.android.testing.mocking.UsesMocks; import android.content.Context; import android.speech.tts.TextToSpeech; import android.speech.tts.TextToSpeech.OnInitListener; import android.speech.tts.TextToSpeech.OnUtteranceCompletedListener; import android.telephony.PhoneStateListener; import android.telephony.TelephonyManager; import android.test.AndroidTestCase; import java.util.HashMap; import java.util.Locale; import java.util.concurrent.atomic.AtomicBoolean; import org.easymock.Capture; /** * Tests for {@link StatusAnnouncerTask}. * WARNING: I'm not responsible if your eyes start bleeding while reading this * code. You have been warned. It's still better than no test, though. * * @author Rodrigo Damazio */ public class StatusAnnouncerTaskTest extends AndroidTestCase { // Use something other than our hardcoded value private static final Locale DEFAULT_LOCALE = Locale.KOREAN; private static final String ANNOUNCEMENT = "I can haz cheeseburger?"; private Locale oldDefaultLocale; private StatusAnnouncerTask task; private StatusAnnouncerTask mockTask; private Capture<OnInitListener> initListenerCapture; private Capture<PhoneStateListener> phoneListenerCapture; private TextToSpeechDelegate ttsDelegate; private TextToSpeechInterface tts; /** * Mockable interface that we delegate TTS calls to. */ interface TextToSpeechInterface { int addEarcon(String earcon, String packagename, int resourceId); int addEarcon(String earcon, String filename); int addSpeech(String text, String packagename, int resourceId); int addSpeech(String text, String filename); boolean areDefaultsEnforced(); String getDefaultEngine(); Locale getLanguage(); int isLanguageAvailable(Locale loc); boolean isSpeaking(); int playEarcon(String earcon, int queueMode, HashMap<String, String> params); int playSilence(long durationInMs, int queueMode, HashMap<String, String> params); int setEngineByPackageName(String enginePackageName); int setLanguage(Locale loc); int setOnUtteranceCompletedListener(OnUtteranceCompletedListener listener); int setPitch(float pitch); int setSpeechRate(float speechRate); void shutdown(); int speak(String text, int queueMode, HashMap<String, String> params); int stop(); int synthesizeToFile(String text, HashMap<String, String> params, String filename); } /** * Subclass of {@link TextToSpeech} which delegates calls to the interface * above. * The logic here is stupid and the author is ashamed of having to write it * like this, but basically the issue is that TextToSpeech cannot be mocked * without running its constructor, its constructor runs async operations * which call other methods (and then if the methods are part of a mock we'd * have to set a behavior, but we can't 'cause the object hasn't been fully * built yet). * The logic is that calls made during the constructor (when tts is not yet * set) will go up to the original class, but after tts is set we'll forward * them all to the mock. */ private class TextToSpeechDelegate extends TextToSpeech implements TextToSpeechInterface { public TextToSpeechDelegate(Context context, OnInitListener listener) { super(context, listener); } @Override public int addEarcon(String earcon, String packagename, int resourceId) { if (tts == null) { return super.addEarcon(earcon, packagename, resourceId); } return tts.addEarcon(earcon, packagename, resourceId); } @Override public int addEarcon(String earcon, String filename) { if (tts == null) { return super.addEarcon(earcon, filename); } return tts.addEarcon(earcon, filename); } @Override public int addSpeech(String text, String packagename, int resourceId) { if (tts == null) { return super.addSpeech(text, packagename, resourceId); } return tts.addSpeech(text, packagename, resourceId); } @Override public int addSpeech(String text, String filename) { if (tts == null) { return super.addSpeech(text, filename); } return tts.addSpeech(text, filename); } @Override public Locale getLanguage() { if (tts == null) { return super.getLanguage(); } return tts.getLanguage(); } @Override public int isLanguageAvailable(Locale loc) { if (tts == null) { return super.isLanguageAvailable(loc); } return tts.isLanguageAvailable(loc); } @Override public boolean isSpeaking() { if (tts == null) { return super.isSpeaking(); } return tts.isSpeaking(); } @Override public int playEarcon(String earcon, int queueMode, HashMap<String, String> params) { if (tts == null) { return super.playEarcon(earcon, queueMode, params); } return tts.playEarcon(earcon, queueMode, params); } @Override public int playSilence(long durationInMs, int queueMode, HashMap<String, String> params) { if (tts == null) { return super.playSilence(durationInMs, queueMode, params); } return tts.playSilence(durationInMs, queueMode, params); } @Override public int setLanguage(Locale loc) { if (tts == null) { return super.setLanguage(loc); } return tts.setLanguage(loc); } @Override public int setOnUtteranceCompletedListener( OnUtteranceCompletedListener listener) { if (tts == null) { return super.setOnUtteranceCompletedListener(listener); } return tts.setOnUtteranceCompletedListener(listener); } @Override public int setPitch(float pitch) { if (tts == null) { return super.setPitch(pitch); } return tts.setPitch(pitch); } @Override public int setSpeechRate(float speechRate) { if (tts == null) { return super.setSpeechRate(speechRate); } return tts.setSpeechRate(speechRate); } @Override public void shutdown() { if (tts == null) { super.shutdown(); return; } tts.shutdown(); } @Override public int speak( String text, int queueMode, HashMap<String, String> params) { if (tts == null) { return super.speak(text, queueMode, params); } return tts.speak(text, queueMode, params); } @Override public int stop() { if (tts == null) { return super.stop(); } return tts.stop(); } @Override public int synthesizeToFile(String text, HashMap<String, String> params, String filename) { if (tts == null) { return super.synthesizeToFile(text, params, filename); } return tts.synthesizeToFile(text, params, filename); } } @UsesMocks({ StatusAnnouncerTask.class, StringUtils.class, }) @Override protected void setUp() throws Exception { super.setUp(); oldDefaultLocale = Locale.getDefault(); Locale.setDefault(DEFAULT_LOCALE); // Eww, the effort required just to mock TextToSpeech is insane final AtomicBoolean listenerCalled = new AtomicBoolean(); OnInitListener blockingListener = new OnInitListener() { @Override public void onInit(int status) { synchronized (this) { listenerCalled.set(true); notify(); } } }; ttsDelegate = new TextToSpeechDelegate(getContext(), blockingListener); // Wait for all async operations done in the constructor to finish. synchronized (blockingListener) { while (!listenerCalled.get()) { // Releases the synchronized lock until we're woken up. blockingListener.wait(); } } // Phew, done, now we can start forwarding calls tts = AndroidMock.createMock(TextToSpeechInterface.class); initListenerCapture = new Capture<OnInitListener>(); phoneListenerCapture = new Capture<PhoneStateListener>(); // Create a partial forwarding mock mockTask = AndroidMock.createMock(StatusAnnouncerTask.class, getContext()); task = new StatusAnnouncerTask(getContext()) { @Override protected TextToSpeech newTextToSpeech(Context ctx, OnInitListener onInitListener) { return mockTask.newTextToSpeech(ctx, onInitListener); } @Override protected String getAnnouncement(TripStatistics stats) { return mockTask.getAnnouncement(stats); } @Override protected void listenToPhoneState( PhoneStateListener listener, int events) { mockTask.listenToPhoneState(listener, events); } }; } @Override protected void tearDown() { Locale.setDefault(oldDefaultLocale); } public void testStart() { doStart(); OnInitListener ttsInitListener = initListenerCapture.getValue(); assertNotNull(ttsInitListener); expect(tts.isLanguageAvailable(DEFAULT_LOCALE)) .andStubReturn(TextToSpeech.LANG_AVAILABLE); expect(tts.setLanguage(DEFAULT_LOCALE)) .andReturn(TextToSpeech.LANG_AVAILABLE); expect(tts.setSpeechRate(StatusAnnouncerTask.TTS_SPEECH_RATE)) .andReturn(TextToSpeech.SUCCESS); AndroidMock.replay(tts); ttsInitListener.onInit(TextToSpeech.SUCCESS); AndroidMock.verify(mockTask, tts); } public void testStart_languageNotSupported() { doStart(); OnInitListener ttsInitListener = initListenerCapture.getValue(); assertNotNull(ttsInitListener); expect(tts.isLanguageAvailable(DEFAULT_LOCALE)) .andStubReturn(TextToSpeech.LANG_NOT_SUPPORTED); expect(tts.setLanguage(Locale.ENGLISH)) .andReturn(TextToSpeech.LANG_AVAILABLE); expect(tts.setSpeechRate(StatusAnnouncerTask.TTS_SPEECH_RATE)) .andReturn(TextToSpeech.SUCCESS); AndroidMock.replay(tts); ttsInitListener.onInit(TextToSpeech.SUCCESS); AndroidMock.verify(mockTask, tts); } public void testStart_notReady() { doStart(); OnInitListener ttsInitListener = initListenerCapture.getValue(); assertNotNull(ttsInitListener); AndroidMock.replay(tts); ttsInitListener.onInit(TextToSpeech.ERROR); AndroidMock.verify(mockTask, tts); } public void testShutdown() { // First, start doStart(); AndroidMock.verify(mockTask); AndroidMock.reset(mockTask); // Then, shut down PhoneStateListener phoneListener = phoneListenerCapture.getValue(); mockTask.listenToPhoneState( same(phoneListener), eq(PhoneStateListener.LISTEN_NONE)); tts.shutdown(); AndroidMock.replay(mockTask, tts); task.shutdown(); AndroidMock.verify(mockTask, tts); } public void testRun() throws Exception { // Expect service data calls TripStatistics stats = new TripStatistics(); // Expect announcement building call expect(mockTask.getAnnouncement(same(stats))).andStubReturn(ANNOUNCEMENT); // Put task in "ready" state startTask(TextToSpeech.SUCCESS); // Expect actual announcement call expect(tts.speak( eq(ANNOUNCEMENT), eq(TextToSpeech.QUEUE_FLUSH), AndroidMock.<HashMap<String, String>>isNull())) .andReturn(TextToSpeech.SUCCESS); // Run the announcement AndroidMock.replay(tts); task.runWithStatistics(stats); AndroidMock.verify(mockTask, tts); } public void testRun_notReady() throws Exception { // Put task in "not ready" state startTask(TextToSpeech.ERROR); // Run the announcement AndroidMock.replay(tts); task.runWithStatistics(null); AndroidMock.verify(mockTask, tts); } public void testRun_duringCall() throws Exception { startTask(TextToSpeech.SUCCESS); expect(tts.isSpeaking()).andStubReturn(false); // Run the announcement AndroidMock.replay(tts); PhoneStateListener phoneListener = phoneListenerCapture.getValue(); phoneListener.onCallStateChanged(TelephonyManager.CALL_STATE_OFFHOOK, null); task.runWithStatistics(null); AndroidMock.verify(mockTask, tts); } public void testRun_ringWhileSpeaking() throws Exception { startTask(TextToSpeech.SUCCESS); expect(tts.isSpeaking()).andStubReturn(true); expect(tts.stop()).andReturn(TextToSpeech.SUCCESS); AndroidMock.replay(tts); // Update the state to ringing - this should stop the current announcement. PhoneStateListener phoneListener = phoneListenerCapture.getValue(); phoneListener.onCallStateChanged(TelephonyManager.CALL_STATE_RINGING, null); // Run the announcement - this should do nothing. task.runWithStatistics(null); AndroidMock.verify(mockTask, tts); } public void testRun_whileRinging() throws Exception { startTask(TextToSpeech.SUCCESS); expect(tts.isSpeaking()).andStubReturn(false); // Run the announcement AndroidMock.replay(tts); PhoneStateListener phoneListener = phoneListenerCapture.getValue(); phoneListener.onCallStateChanged(TelephonyManager.CALL_STATE_RINGING, null); task.runWithStatistics(null); AndroidMock.verify(mockTask, tts); } public void testRun_noService() throws Exception { startTask(TextToSpeech.SUCCESS); // Run the announcement AndroidMock.replay(tts); task.run(null); AndroidMock.verify(mockTask, tts); } public void testRun_noStats() throws Exception { // Expect service data calls startTask(TextToSpeech.SUCCESS); // Run the announcement AndroidMock.replay(tts); task.runWithStatistics(null); AndroidMock.verify(mockTask, tts); } /** * Tests {@link StatusAnnouncerTask#getAnnounceTime(long)} with time zero. */ public void testGetAnnounceTime_time_zero() { long time = 0; // 0 seconds assertEquals("0 minutes 0 seconds", task.getAnnounceTime(time)); } /** * Tests {@link StatusAnnouncerTask#getAnnounceTime(long)} with time one. */ public void testGetAnnounceTime_time_one() { long time = 1 * 1000; // 1 second assertEquals("0 minutes 1 second", task.getAnnounceTime(time)); } /** * Tests {@link StatusAnnouncerTask#getAnnounceTime(long)} with singular * numbers with the hour unit. */ public void testGetAnnounceTime_singular_has_hour() { long time = (1 * 60 * 60 * 1000) + (1 * 60 * 1000) + (1 * 1000); // 1 hour 1 minute 1 second assertEquals("1 hour 1 minute", task.getAnnounceTime(time)); } /** * Tests {@link StatusAnnouncerTask#getAnnounceTime(long)} with plural numbers * with the hour unit. */ public void testGetAnnounceTime_plural_has_hour() { long time = (2 * 60 * 60 * 1000) + (2 * 60 * 1000) + (2 * 1000); // 2 hours 2 minutes 2 seconds assertEquals("2 hours 2 minutes", task.getAnnounceTime(time)); } /** * Tests {@link StatusAnnouncerTask#getAnnounceTime(long)} with singular * numbers without the hour unit. */ public void testGetAnnounceTime_singular_no_hour() { long time = (1 * 60 * 1000) + (1 * 1000); // 1 minute 1 second assertEquals("1 minute 1 second", task.getAnnounceTime(time)); } /** * Tests {@link StatusAnnouncerTask#getAnnounceTime(long)} with plural numbers * without the hour unit. */ public void testGetAnnounceTime_plural_no_hour() { long time = (2 * 60 * 1000) + (2 * 1000); // 2 minutes 2 seconds assertEquals("2 minutes 2 seconds", task.getAnnounceTime(time)); } private void startTask(int state) { AndroidMock.resetToNice(tts); AndroidMock.replay(tts); doStart(); OnInitListener ttsInitListener = initListenerCapture.getValue(); ttsInitListener.onInit(state); AndroidMock.resetToDefault(tts); } private void doStart() { mockTask.listenToPhoneState(capture(phoneListenerCapture), eq(PhoneStateListener.LISTEN_CALL_STATE)); expect(mockTask.newTextToSpeech( same(getContext()), capture(initListenerCapture))) .andStubReturn(ttsDelegate); AndroidMock.replay(mockTask); task.start(); } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.services.tasks; import com.google.android.apps.mytracks.services.tasks.PeriodicTask; import com.google.android.apps.mytracks.services.tasks.StatusAnnouncerFactory; import com.google.android.apps.mytracks.services.tasks.StatusAnnouncerTask; import com.google.android.apps.mytracks.util.ApiFeatures; import android.media.AudioManager; import android.speech.tts.TextToSpeech; import android.test.AndroidTestCase; /** * Tests for {@link StatusAnnouncerFactory}. * These tests require Donut+ to run. * * @author Rodrigo Damazio */ public class StatusAnnouncerFactoryTest extends AndroidTestCase { /** * Mock version of the {@link ApiFeatures} class. */ private class MockApiFeatures extends ApiFeatures { private boolean hasTts; public void setHasTextToSpeech(boolean hasTts) { this.hasTts = hasTts; } @Override public boolean hasTextToSpeech() { return hasTts; } } private MockApiFeatures apiFeatures; @Override protected void setUp() throws Exception { super.setUp(); apiFeatures = new MockApiFeatures(); } public void testCreate() { apiFeatures.setHasTextToSpeech(true); PeriodicTaskFactory factory = new StatusAnnouncerFactory(apiFeatures); PeriodicTask task = factory.create(getContext()); assertTrue(task instanceof StatusAnnouncerTask); } public void testCreate_notAvailable() { apiFeatures.setHasTextToSpeech(false); PeriodicTaskFactory factory = new StatusAnnouncerFactory(apiFeatures); PeriodicTask task = factory.create(getContext()); assertNull(task); } public void testGetVolumeStream() { apiFeatures.setHasTextToSpeech(true); StatusAnnouncerFactory factory = new StatusAnnouncerFactory(apiFeatures); assertEquals( TextToSpeech.Engine.DEFAULT_STREAM, factory.getVolumeStream()); } public void testGetVolumeStream_notAvailable() { apiFeatures.setHasTextToSpeech(false); StatusAnnouncerFactory factory = new StatusAnnouncerFactory(apiFeatures); assertEquals( AudioManager.USE_DEFAULT_STREAM_TYPE, factory.getVolumeStream()); } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.services; import static com.google.android.apps.mytracks.Constants.RESUME_TRACK_EXTRA_NAME; import com.google.android.apps.mytracks.Constants; import com.google.android.apps.mytracks.content.MyTracksProvider; import com.google.android.apps.mytracks.content.MyTracksProviderUtils; import com.google.android.apps.mytracks.content.Track; import com.google.android.apps.mytracks.content.Waypoint; import com.google.android.apps.mytracks.content.WaypointCreationRequest; import com.google.android.apps.mytracks.stats.TripStatistics; import com.google.android.apps.mytracks.util.ApiFeatures; import com.google.android.maps.mytracks.R; import android.content.BroadcastReceiver; import android.content.ContentResolver; import android.content.Context; import android.content.ContextWrapper; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.location.Location; import android.os.IBinder; import android.test.RenamingDelegatingContext; import android.test.ServiceTestCase; import android.test.mock.MockContentResolver; import android.test.suitebuilder.annotation.MediumTest; import android.test.suitebuilder.annotation.SmallTest; import android.util.Log; import java.util.ArrayList; import java.util.List; /** * Tests for the MyTracks track recording service. * * @author Bartlomiej Niechwiej * * TODO: The original class, ServiceTestCase, has a few limitations, e.g. * it's not possible to properly shutdown the service, unless tearDown() * is called, which prevents from testing multiple scenarios in a single * test (see runFunctionTest for more details). */ public class TrackRecordingServiceTest extends ServiceTestCase<TrackRecordingService> { private Context context; private MyTracksProviderUtils providerUtils; private SharedPreferences sharedPreferences; /* * In order to support starting and binding to the service in the same * unit test, we provide a workaround, as the original class doesn't allow * to bind after the service has been previously started. */ private boolean bound; private Intent serviceIntent; public TrackRecordingServiceTest() { super(TrackRecordingService.class); } /** * A context wrapper with the user provided {@link ContentResolver}. * * TODO: Move to test utils package. */ public static class MockContext extends ContextWrapper { private final ContentResolver contentResolver; public MockContext(ContentResolver contentResolver, Context base) { super(base); this.contentResolver = contentResolver; } @Override public ContentResolver getContentResolver() { return contentResolver; } } /** * A mock class that forces API level < 5 to make sure we can workaround a bug * in ServiceTestCase (throwing a NPE). * See http://code.google.com/p/android/issues/detail?id=12122 for more * details. */ private static class MockApiFeatures extends ApiFeatures { @Override protected int getApiLevel() { return 4; } } @Override protected IBinder bindService(Intent intent) { if (getService() != null) { if (bound) { throw new IllegalStateException( "Service: " + getService() + " is already bound"); } bound = true; serviceIntent = intent.cloneFilter(); return getService().onBind(intent); } else { return super.bindService(intent); } } @Override protected void shutdownService() { if (bound) { assertNotNull(getService()); getService().onUnbind(serviceIntent); bound = false; } super.shutdownService(); } @Override protected void setUp() throws Exception { super.setUp(); ApiFeatures.injectInstance(new MockApiFeatures()); MockContentResolver mockContentResolver = new MockContentResolver(); RenamingDelegatingContext targetContext = new RenamingDelegatingContext( getContext(), getContext(), "test."); context = new MockContext(mockContentResolver, targetContext); MyTracksProvider provider = new MyTracksProvider(); provider.attachInfo(context, null); mockContentResolver.addProvider(MyTracksProviderUtils.AUTHORITY, provider); setContext(context); providerUtils = MyTracksProviderUtils.Factory.get(context); sharedPreferences = context.getSharedPreferences(Constants.SETTINGS_NAME, Context.MODE_PRIVATE); // Let's use default values. sharedPreferences.edit().clear().apply(); // Disable auto resume by default. updateAutoResumePrefs(0, -1); // No recording track. Editor editor = sharedPreferences.edit(); editor.putLong(context.getString(R.string.recording_track_key), -1); editor.apply(); } @SmallTest public void testStartable() { startService(createStartIntent()); assertNotNull(getService()); } @MediumTest public void testBindable() { IBinder service = bindService(createStartIntent()); assertNotNull(service); } @MediumTest public void testResumeAfterReboot_shouldResume() throws Exception { // Insert a dummy track and mark it as recording track. createDummyTrack(123, System.currentTimeMillis(), true); // Clear the number of attempts and set the timeout to 10 min. updateAutoResumePrefs(0, 10); // Start the service in "resume" mode (simulates the on-reboot action). Intent startIntent = createStartIntent(); startIntent.putExtra(RESUME_TRACK_EXTRA_NAME, true); startService(startIntent); assertNotNull(getService()); // We expect to resume the previous track. assertTrue(getService().isRecording()); ITrackRecordingService service = bindAndGetService(createStartIntent()); assertEquals(123, service.getRecordingTrackId()); } // TODO: shutdownService() has a bug and doesn't set mServiceCreated // to false, thus preventing from a second call to onCreate(). // Report the bug to Android team. Until then, the following tests // and checks must be commented out. // // TODO: If fixed, remove "disabled" prefix from the test name. @MediumTest public void disabledTestResumeAfterReboot_simulateReboot() throws Exception { updateAutoResumePrefs(0, 10); ITrackRecordingService service = bindAndGetService(createStartIntent()); assertFalse(service.isRecording()); // Simulate recording a track. long id = service.startNewTrack(); assertTrue(service.isRecording()); assertEquals(id, service.getRecordingTrackId()); shutdownService(); assertEquals(id, sharedPreferences.getLong( context.getString(R.string.recording_track_key), -1)); // Start the service in "resume" mode (simulates the on-reboot action). Intent startIntent = createStartIntent(); startIntent.putExtra(RESUME_TRACK_EXTRA_NAME, true); startService(startIntent); assertNotNull(getService()); assertTrue(getService().isRecording()); } @MediumTest public void testResumeAfterReboot_noRecordingTrack() throws Exception { // Insert a dummy track and mark it as recording track. createDummyTrack(123, System.currentTimeMillis(), false); // Clear the number of attempts and set the timeout to 10 min. updateAutoResumePrefs(0, 10); // Start the service in "resume" mode (simulates the on-reboot action). Intent startIntent = createStartIntent(); startIntent.putExtra(RESUME_TRACK_EXTRA_NAME, true); startService(startIntent); assertNotNull(getService()); // We don't expect to resume the previous track, because it was stopped. assertFalse(getService().isRecording()); ITrackRecordingService service = bindAndGetService(createStartIntent()); assertEquals(-1, service.getRecordingTrackId()); } @MediumTest public void testResumeAfterReboot_expiredTrack() throws Exception { // Insert a dummy track last updated 20 min ago. createDummyTrack(123, System.currentTimeMillis() - 20 * 60 * 1000, true); // Clear the number of attempts and set the timeout to 10 min. updateAutoResumePrefs(0, 10); // Start the service in "resume" mode (simulates the on-reboot action). Intent startIntent = createStartIntent(); startIntent.putExtra(RESUME_TRACK_EXTRA_NAME, true); startService(startIntent); assertNotNull(getService()); // We don't expect to resume the previous track, because it has expired. assertFalse(getService().isRecording()); ITrackRecordingService service = bindAndGetService(createStartIntent()); assertEquals(-1, service.getRecordingTrackId()); } @MediumTest public void testResumeAfterReboot_tooManyAttempts() throws Exception { // Insert a dummy track. createDummyTrack(123, System.currentTimeMillis(), true); // Set the number of attempts to max. updateAutoResumePrefs( TrackRecordingService.MAX_AUTO_RESUME_TRACK_RETRY_ATTEMPTS, 10); // Start the service in "resume" mode (simulates the on-reboot action). Intent startIntent = createStartIntent(); startIntent.putExtra(RESUME_TRACK_EXTRA_NAME, true); startService(startIntent); assertNotNull(getService()); // We don't expect to resume the previous track, because there were already // too many attempts. assertFalse(getService().isRecording()); ITrackRecordingService service = bindAndGetService(createStartIntent()); assertEquals(-1, service.getRecordingTrackId()); } @MediumTest public void testRecording_noTracks() throws Exception { List<Track> tracks = providerUtils.getAllTracks(); assertTrue(tracks.isEmpty()); ITrackRecordingService service = bindAndGetService(createStartIntent()); // Test if we start in no-recording mode by default. assertFalse(service.isRecording()); assertEquals(-1, service.getRecordingTrackId()); } @MediumTest public void testRecording_oldTracks() throws Exception { createDummyTrack(123, -1, false); ITrackRecordingService service = bindAndGetService(createStartIntent()); assertFalse(service.isRecording()); assertEquals(-1, service.getRecordingTrackId()); } @MediumTest public void testRecording_orphanedRecordingTrack() throws Exception { // Just set recording track to a bogus value. setRecordingTrack(256); // Make sure that the service will not start recording and will clear // the bogus track. ITrackRecordingService service = bindAndGetService(createStartIntent()); assertFalse(service.isRecording()); assertEquals(-1, service.getRecordingTrackId()); } /** * Synchronous/waitable broadcast receiver to be used in testing. */ private class BlockingBroadcastReceiver extends BroadcastReceiver { private static final long MAX_WAIT_TIME_MS = 10000; private List<Intent> receivedIntents = new ArrayList<Intent>(); public List<Intent> getReceivedIntents() { return receivedIntents; } @Override public void onReceive(Context ctx, Intent intent) { Log.d("MyTracksTest", "Got broadcast: " + intent); synchronized (receivedIntents) { receivedIntents.add(intent); receivedIntents.notifyAll(); } } public boolean waitUntilReceived(int receiveCount) { long deadline = System.currentTimeMillis() + MAX_WAIT_TIME_MS; synchronized (receivedIntents) { while (receivedIntents.size() < receiveCount) { try { // Wait releases synchronized lock until it returns receivedIntents.wait(500); } catch (InterruptedException e) { // Do nothing } if (System.currentTimeMillis() > deadline) { return false; } } } return true; } } @MediumTest public void testStartNewTrack_noRecording() throws Exception { // NOTICE: due to the way Android permissions work, if this fails, // uninstall the test apk then retry - the test must be installed *after* // My Tracks (go figure). // Reference: http://code.google.com/p/android/issues/detail?id=5521 BlockingBroadcastReceiver startReceiver = new BlockingBroadcastReceiver(); String startAction = context.getString(R.string.track_started_broadcast_action); context.registerReceiver(startReceiver, new IntentFilter(startAction)); List<Track> tracks = providerUtils.getAllTracks(); assertTrue(tracks.isEmpty()); ITrackRecordingService service = bindAndGetService(createStartIntent()); assertFalse(service.isRecording()); long id = service.startNewTrack(); assertTrue(id >= 0); assertTrue(service.isRecording()); Track track = providerUtils.getTrack(id); assertNotNull(track); assertEquals(id, track.getId()); assertEquals(sharedPreferences.getString(context.getString(R.string.default_activity_key), ""), track.getCategory()); assertEquals(id, sharedPreferences.getLong( context.getString(R.string.recording_track_key), -1)); assertEquals(id, service.getRecordingTrackId()); // Verify that the start broadcast was received. assertTrue(startReceiver.waitUntilReceived(1)); List<Intent> receivedIntents = startReceiver.getReceivedIntents(); assertEquals(1, receivedIntents.size()); Intent broadcastIntent = receivedIntents.get(0); assertEquals(startAction, broadcastIntent.getAction()); assertEquals(id, broadcastIntent.getLongExtra( context.getString(R.string.track_id_broadcast_extra), -1)); context.unregisterReceiver(startReceiver); } @MediumTest public void testStartNewTrack_alreadyRecording() throws Exception { createDummyTrack(123, -1, true); ITrackRecordingService service = bindAndGetService(createStartIntent()); assertTrue(service.isRecording()); // Starting a new track when there is a recording should just return -1L. long newTrack = service.startNewTrack(); assertEquals(-1L, newTrack); assertEquals(123, sharedPreferences.getLong( context.getString(R.string.recording_track_key), 0)); assertEquals(123, service.getRecordingTrackId()); } @MediumTest public void testEndCurrentTrack_alreadyRecording() throws Exception { // See comment above if this fails randomly. BlockingBroadcastReceiver stopReceiver = new BlockingBroadcastReceiver(); String stopAction = context.getString(R.string.track_stopped_broadcast_action); context.registerReceiver(stopReceiver, new IntentFilter(stopAction)); createDummyTrack(123, -1, true); ITrackRecordingService service = bindAndGetService(createStartIntent()); assertTrue(service.isRecording()); // End the current track. service.endCurrentTrack(); assertFalse(service.isRecording()); assertEquals(-1, sharedPreferences.getLong( context.getString(R.string.recording_track_key), 0)); assertEquals(-1, service.getRecordingTrackId()); // Verify that the stop broadcast was received. assertTrue(stopReceiver.waitUntilReceived(1)); List<Intent> receivedIntents = stopReceiver.getReceivedIntents(); assertEquals(1, receivedIntents.size()); Intent broadcastIntent = receivedIntents.get(0); assertEquals(stopAction, broadcastIntent.getAction()); assertEquals(123, broadcastIntent.getLongExtra( context.getString(R.string.track_id_broadcast_extra), -1)); context.unregisterReceiver(stopReceiver); } @MediumTest public void testEndCurrentTrack_noRecording() throws Exception { ITrackRecordingService service = bindAndGetService(createStartIntent()); assertFalse(service.isRecording()); // Ending the current track when there is no recording should not result in any error. service.endCurrentTrack(); assertEquals(-1, sharedPreferences.getLong( context.getString(R.string.recording_track_key), 0)); assertEquals(-1, service.getRecordingTrackId()); } @MediumTest public void testIntegration_completeRecordingSession() throws Exception { List<Track> tracks = providerUtils.getAllTracks(); assertTrue(tracks.isEmpty()); fullRecordingSession(); } @MediumTest public void testInsertStatisticsMarker_noRecordingTrack() throws Exception { ITrackRecordingService service = bindAndGetService(createStartIntent()); assertFalse(service.isRecording()); try { service.insertWaypoint(WaypointCreationRequest.DEFAULT_STATISTICS); fail("Expecting IllegalStateException"); } catch (IllegalStateException e) { // Expected. } } @MediumTest public void testInsertStatisticsMarker_validLocation() throws Exception { createDummyTrack(123, -1, true); ITrackRecordingService service = bindAndGetService(createStartIntent()); assertTrue(service.isRecording()); assertEquals(1, service.insertWaypoint(WaypointCreationRequest.DEFAULT_STATISTICS)); assertEquals(2, service.insertWaypoint(WaypointCreationRequest.DEFAULT_STATISTICS)); Waypoint wpt = providerUtils.getWaypoint(1); assertEquals(getContext().getString(R.string.marker_statistics_icon_url), wpt.getIcon()); assertEquals(getContext().getString(R.string.marker_type_statistics), wpt.getName()); assertEquals(Waypoint.TYPE_STATISTICS, wpt.getType()); assertEquals(123, wpt.getTrackId()); assertEquals(0.0, wpt.getLength()); assertNotNull(wpt.getLocation()); assertNotNull(wpt.getStatistics()); // TODO check the rest of the params. // TODO: Check waypoint 2. } @MediumTest public void testInsertWaypointMarker_noRecordingTrack() throws Exception { ITrackRecordingService service = bindAndGetService(createStartIntent()); assertFalse(service.isRecording()); try { service.insertWaypoint(WaypointCreationRequest.DEFAULT_MARKER); fail("Expecting IllegalStateException"); } catch (IllegalStateException e) { // Expected. } } @MediumTest public void testInsertWaypointMarker_validWaypoint() throws Exception { createDummyTrack(123, -1, true); ITrackRecordingService service = bindAndGetService(createStartIntent()); assertTrue(service.isRecording()); assertEquals(1, service.insertWaypoint(WaypointCreationRequest.DEFAULT_MARKER)); Waypoint wpt = providerUtils.getWaypoint(1); assertEquals(getContext().getString(R.string.marker_waypoint_icon_url), wpt.getIcon()); assertEquals(getContext().getString(R.string.marker_type_waypoint), wpt.getName()); assertEquals(Waypoint.TYPE_WAYPOINT, wpt.getType()); assertEquals(123, wpt.getTrackId()); assertEquals(0.0, wpt.getLength()); assertNotNull(wpt.getLocation()); assertNull(wpt.getStatistics()); } @MediumTest public void testWithProperties_noAnnouncementFreq() throws Exception { functionalTest(R.string.announcement_frequency_key, (Object) null); } @MediumTest public void testWithProperties_defaultAnnouncementFreq() throws Exception { functionalTest(R.string.announcement_frequency_key, 1); } @MediumTest public void testWithProperties_noMaxRecordingDist() throws Exception { functionalTest(R.string.max_recording_distance_key, (Object) null); } @MediumTest public void testWithProperties_defaultMaxRecordingDist() throws Exception { functionalTest(R.string.max_recording_distance_key, 5); } @MediumTest public void testWithProperties_noMinRecordingDist() throws Exception { functionalTest(R.string.min_recording_distance_key, (Object) null); } @MediumTest public void testWithProperties_defaultMinRecordingDist() throws Exception { functionalTest(R.string.min_recording_distance_key, 2); } @MediumTest public void testWithProperties_noSplitFreq() throws Exception { functionalTest(R.string.split_frequency_key, (Object) null); } @MediumTest public void testWithProperties_defaultSplitFreqByDist() throws Exception { functionalTest(R.string.split_frequency_key, 5); } @MediumTest public void testWithProperties_defaultSplitFreqByTime() throws Exception { functionalTest(R.string.split_frequency_key, -2); } @MediumTest public void testWithProperties_noMetricUnits() throws Exception { functionalTest(R.string.metric_units_key, (Object) null); } @MediumTest public void testWithProperties_metricUnitsEnabled() throws Exception { functionalTest(R.string.metric_units_key, true); } @MediumTest public void testWithProperties_metricUnitsDisabled() throws Exception { functionalTest(R.string.metric_units_key, false); } @MediumTest public void testWithProperties_noMinRecordingInterval() throws Exception { functionalTest(R.string.min_recording_interval_key, (Object) null); } @MediumTest public void testWithProperties_defaultMinRecordingInterval() throws Exception { functionalTest(R.string.min_recording_interval_key, 3); } @MediumTest public void testWithProperties_noMinRequiredAccuracy() throws Exception { functionalTest(R.string.min_required_accuracy_key, (Object) null); } @MediumTest public void testWithProperties_defaultMinRequiredAccuracy() throws Exception { functionalTest(R.string.min_required_accuracy_key, 500); } @MediumTest public void testWithProperties_noSensorType() throws Exception { functionalTest(R.string.sensor_type_key, (Object) null); } @MediumTest public void testWithProperties_zephyrSensorType() throws Exception { functionalTest(R.string.sensor_type_key, context.getString(R.string.sensor_type_value_zephyr)); } private ITrackRecordingService bindAndGetService(Intent intent) { ITrackRecordingService service = ITrackRecordingService.Stub.asInterface( bindService(intent)); assertNotNull(service); return service; } private Track createDummyTrack(long id, long stopTime, boolean isRecording) { Track dummyTrack = new Track(); dummyTrack.setId(id); dummyTrack.setName("Dummy Track"); TripStatistics tripStatistics = new TripStatistics(); tripStatistics.setStopTime(stopTime); dummyTrack.setStatistics(tripStatistics); addTrack(dummyTrack, isRecording); return dummyTrack; } private void updateAutoResumePrefs(int attempts, int timeoutMins) { Editor editor = sharedPreferences.edit(); editor.putInt(context.getString( R.string.auto_resume_track_current_retry_key), attempts); editor.putInt(context.getString( R.string.auto_resume_track_timeout_key), timeoutMins); editor.apply(); } private Intent createStartIntent() { Intent startIntent = new Intent(); startIntent.setClass(context, TrackRecordingService.class); return startIntent; } private void addTrack(Track track, boolean isRecording) { assertTrue(track.getId() >= 0); providerUtils.insertTrack(track); assertEquals(track.getId(), providerUtils.getTrack(track.getId()).getId()); setRecordingTrack(isRecording ? track.getId() : -1); } private void setRecordingTrack(long id) { Editor editor = sharedPreferences.edit(); editor.putLong(context.getString(R.string.recording_track_key), id); editor.apply(); } // TODO: We support multiple values for readability, however this test's // base class doesn't properly shutdown the service, so it's not possible // to pass more than 1 value at a time. private void functionalTest(int resourceId, Object ...values) throws Exception { final String key = context.getString(resourceId); for (Object value : values) { // Remove all properties and set the property for the given key. Editor editor = sharedPreferences.edit(); editor.clear(); if (value instanceof String) { editor.putString(key, (String) value); } else if (value instanceof Long) { editor.putLong(key, (Long) value); } else if (value instanceof Integer) { editor.putInt(key, (Integer) value); } else if (value instanceof Boolean) { editor.putBoolean(key, (Boolean) value); } else if (value == null) { // Do nothing, as clear above has already removed this property. } editor.apply(); fullRecordingSession(); } } private void fullRecordingSession() throws Exception { ITrackRecordingService service = bindAndGetService(createStartIntent()); assertFalse(service.isRecording()); // Start a track. long id = service.startNewTrack(); assertTrue(id >= 0); assertTrue(service.isRecording()); Track track = providerUtils.getTrack(id); assertNotNull(track); assertEquals(id, track.getId()); assertEquals(id, sharedPreferences.getLong( context.getString(R.string.recording_track_key), -1)); assertEquals(id, service.getRecordingTrackId()); // Insert a few points, markers and statistics. long startTime = System.currentTimeMillis(); for (int i = 0; i < 30; i++) { Location loc = new Location("gps"); loc.setLongitude(35.0f + i / 10.0f); loc.setLatitude(45.0f - i / 5.0f); loc.setAccuracy(5); loc.setSpeed(10); loc.setTime(startTime + i * 10000); loc.setBearing(3.0f); service.recordLocation(loc); if (i % 10 == 0) { service.insertWaypoint(WaypointCreationRequest.DEFAULT_STATISTICS); } else if (i % 7 == 0) { service.insertWaypoint(WaypointCreationRequest.DEFAULT_MARKER); } } // Stop the track. Validate if it has correct data. service.endCurrentTrack(); assertFalse(service.isRecording()); assertEquals(-1, service.getRecordingTrackId()); track = providerUtils.getTrack(id); assertNotNull(track); assertEquals(id, track.getId()); TripStatistics tripStatistics = track.getStatistics(); assertNotNull(tripStatistics); assertTrue(tripStatistics.getStartTime() > 0); assertTrue(tripStatistics.getStopTime() >= tripStatistics.getStartTime()); } }
Java