answer
stringlengths
17
10.2M
package org.jboss.as.embedded; import static org.jboss.as.embedded.EmbeddedMessages.MESSAGES; import org.jboss.modules.Module; import org.jboss.modules.ModuleClassLoader; import org.jboss.modules.ModuleIdentifier; import org.jboss.modules.ModuleLoadException; import org.jboss.modules.ModuleLoader; import org.jboss.modules.log.JDKModuleLogger; import java.io.File; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Map; import java.util.Properties; import java.util.logging.LogManager; /** * <p> * ServerFactory that sets up a standalone server using modular classloading. * </p> * <p> * To use this class the <code>jboss.home.dir</code> system property must be set to the * application server home directory. By default it will use the directories * <code>{$jboss.home.dir}/standalone/config</code> as the <i>configuration</i> directory and * <code>{$jboss.home.dir}/standalone/data</code> as the <i>data</i> directory. This can be overridden * with the <code>${jboss.server.base.dir}</code>, <code>${jboss.server.config.dir}</code> or <code>${jboss.server.config.dir}</code> * system properties as for normal server startup. * </p> * <p> * If a clean run is wanted, you can specify <code>${jboss.embedded.root}</code> to an existing directory * which will copy the contents of the data and configuration directories under a temporary folder. This * has the effect of this run not polluting later runs of the embedded server. * </p> * * @author <a href="kabir.khan@jboss.com">Kabir Khan</a> * @author Thomas.Diesler@jboss.com */ public class EmbeddedServerFactory { private static final String MODULE_ID_EMBEDDED = "org.jboss.as.embedded"; private static final String MODULE_ID_LOGMANAGER = "org.jboss.logmanager"; private static final String MODULE_ID_VFS = "org.jboss.vfs"; private static final String SYSPROP_KEY_CLASS_PATH = "java.class.path"; private static final String SYSPROP_KEY_MODULE_PATH = "module.path"; private static final String SYSPROP_KEY_BUNDLE_PATH = "jboss.bundles.dir"; private static final String SYSPROP_KEY_LOGMANAGER = "java.util.logging.manager"; private static final String SYSPROP_KEY_JBOSS_HOME_DIR = "jboss.home.dir"; private static final String SYSPROP_VALUE_JBOSS_LOGMANAGER = "org.jboss.logmanager.LogManager"; private EmbeddedServerFactory() { } public static StandaloneServer create(String jbossHomePath, String modulePath, String bundlePath, String... systemPackages) { if (jbossHomePath == null || jbossHomePath.isEmpty()) { throw MESSAGES.invalidJBossHome(jbossHomePath); } File jbossHomeDir = new File(jbossHomePath); if (!jbossHomeDir.isDirectory()) { throw MESSAGES.invalidJBossHome(jbossHomePath); } if (modulePath == null) modulePath = jbossHomeDir.getAbsolutePath() + File.separator + "modules"; if (bundlePath == null) bundlePath = jbossHomeDir.getAbsolutePath() + File.separator + "bundles"; setupBundlePath(bundlePath); return create(setupModuleLoader(modulePath, systemPackages), jbossHomeDir); } public static StandaloneServer create(ModuleLoader moduleLoader, File jbossHomeDir) { setupVfsModule(moduleLoader); setupLoggingSystem(moduleLoader); // Embedded Server wants this, too. Seems redundant, but supply it. SecurityActions.setSystemProperty(SYSPROP_KEY_JBOSS_HOME_DIR, jbossHomeDir.getAbsolutePath()); // Load the Embedded Server Module final Module embeddedModule; try { embeddedModule = moduleLoader.loadModule(ModuleIdentifier.create(MODULE_ID_EMBEDDED)); } catch (final ModuleLoadException mle) { throw MESSAGES.moduleLoaderError(mle, MODULE_ID_EMBEDDED, moduleLoader); } // Load the Embedded Server Factory via the modular environment final ModuleClassLoader embeddedModuleCL = embeddedModule.getClassLoader(); final Class<?> embeddedServerFactoryClass; final Class<?> standaloneServerClass; try { embeddedServerFactoryClass = embeddedModuleCL.loadClass(EmbeddedStandAloneServerFactory.class.getName()); standaloneServerClass = embeddedModuleCL.loadClass(StandaloneServer.class.getName()); } catch (final ClassNotFoundException cnfe) { throw MESSAGES.cannotLoadEmbeddedServerFactory(cnfe, EmbeddedStandAloneServerFactory.class.getName()); } // Get a handle to the method which will create the server final Method createServerMethod; try { createServerMethod = embeddedServerFactoryClass.getMethod("create", File.class, ModuleLoader.class, Properties.class, Map.class); } catch (final NoSuchMethodException nsme) { throw MESSAGES.cannotGetReflectiveMethod(nsme, "create", embeddedServerFactoryClass.getName()); } // Create the server Object standaloneServerImpl; try { standaloneServerImpl = createServerMethod.invoke(null, jbossHomeDir, moduleLoader, SecurityActions.getSystemProperties(), SecurityActions.getSystemEnvironment()); } catch (final InvocationTargetException ite) { throw MESSAGES.cannotCreateStandaloneServer(ite.getCause(), createServerMethod); } catch (final IllegalAccessException iae) { throw MESSAGES.cannotCreateStandaloneServer(iae, createServerMethod); } return new StandaloneServerIndirection(standaloneServerClass, standaloneServerImpl); } private static ModuleLoader setupModuleLoader(String modulePath, String... systemPackages) { assert modulePath != null : "modulePath not null"; final String classPath = SecurityActions.getSystemProperty(SYSPROP_KEY_CLASS_PATH); try { // Set up sysprop env SecurityActions.clearSystemProperty(SYSPROP_KEY_CLASS_PATH); SecurityActions.setSystemProperty(SYSPROP_KEY_MODULE_PATH, modulePath); StringBuffer packages = new StringBuffer("org.jboss.modules,org.jboss.msc,org.jboss.dmr,org.jboss.threads,org.jboss.as.controller.client"); if (systemPackages != null) { for (String packageName : systemPackages) packages.append("," + packageName); } SecurityActions.setSystemProperty("jboss.modules.system.pkgs", packages.toString()); // Get the module loader final ModuleLoader moduleLoader = Module.getBootModuleLoader(); return moduleLoader; } finally { // Return to previous state for classpath prop SecurityActions.setSystemProperty(SYSPROP_KEY_CLASS_PATH, classPath); } } private static void setupBundlePath(final String bundlePath) { assert bundlePath != null : "bundlePath not null"; final File bundlesDir = new File(bundlePath); assert bundlesDir.isDirectory() : "bundlesDir not a directory"; SecurityActions.setSystemProperty(SYSPROP_KEY_BUNDLE_PATH, bundlePath); } private static void setupVfsModule(final ModuleLoader moduleLoader) { final ModuleIdentifier vfsModuleID = ModuleIdentifier.create(MODULE_ID_VFS); final Module vfsModule; try { vfsModule = moduleLoader.loadModule(vfsModuleID); } catch (final ModuleLoadException mle) { throw MESSAGES.moduleLoaderError(mle, MODULE_ID_VFS, moduleLoader); } Module.registerURLStreamHandlerFactoryModule(vfsModule); } private static void setupLoggingSystem(ModuleLoader moduleLoader) { final ModuleIdentifier logModuleId = ModuleIdentifier.create(MODULE_ID_LOGMANAGER); final Module logModule; try { logModule = moduleLoader.loadModule(logModuleId); } catch (final ModuleLoadException mle) { throw MESSAGES.moduleLoaderError(mle, MODULE_ID_LOGMANAGER, moduleLoader); } final ModuleClassLoader logModuleClassLoader = logModule.getClassLoader(); final ClassLoader tccl = SecurityActions.getContextClassLoader(); try { SecurityActions.setContextClassLoader(logModuleClassLoader); SecurityActions.setSystemProperty(SYSPROP_KEY_LOGMANAGER, SYSPROP_VALUE_JBOSS_LOGMANAGER); final Class<?> actualLogManagerClass = LogManager.getLogManager().getClass(); if (actualLogManagerClass == LogManager.class) { System.err.println("Cannot not load JBoss LogManager. The LogManager has likely been accessed prior to this initialization."); } else { Module.setModuleLogger(new JDKModuleLogger()); } } finally { // Reset TCCL SecurityActions.setContextClassLoader(tccl); } } }
package com.unb.tracker; import com.unb.tracker.model.Course; import com.unb.tracker.model.Seat; import com.unb.tracker.model.User; import com.unb.tracker.repository.CourseRepository; import com.unb.tracker.repository.UserRepository; import com.unb.tracker.web.CourseController; import com.unb.tracker.web.UserController; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Matchers; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.MediaType; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.mock.http.MockHttpOutputMessage; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import java.io.IOException; import java.sql.Date; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.in; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.mockito.AdditionalAnswers.returnsFirstArg; import static org.mockito.Mockito.when; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders.logout; import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; @RunWith(SpringRunner.class) @SpringBootTest public class TrackerApplicationTests { protected final DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy"); private HttpMessageConverter mappingJackson2HttpMessageConverter; @Autowired private CourseController courseController; @Autowired private UserController userController; @Autowired private WebApplicationContext context; private MockMvc mockMvc; @MockBean private CourseRepository courseRepository; @MockBean private UserRepository userRepository; //TODO: //- Loading the index(login) should render //- Selecting one of the buttons should render the login card //- Selecting sign up should render the sign up card //- logging in with invalid credentials should redirect to index with error message //- attempting to create an account without an email address, username or password should redirect to index with error message //- test username and password validation (unique username with 6 to 32 length, matching passwords with length 8 to 32) //- Creating a new user should correctly store their information in the database //- Creating a new student should redirect to their student view //- Creating a new instructor should redirect to their instructor view //- Attempting to login as instructor or user should redirect them correctly //- Test that a student is not able to create courses @Autowired void setConverters(HttpMessageConverter<?>[] converters) { this.mappingJackson2HttpMessageConverter = Arrays.asList(converters).stream() .filter(hmc -> hmc instanceof MappingJackson2HttpMessageConverter) .findAny() .orElse(null); assertNotNull("the JSON message converter must not be null", this.mappingJackson2HttpMessageConverter); } @Before public void setup() { mockMvc = MockMvcBuilders .webAppContextSetup(context) .apply(springSecurity()) .build(); } @Test public void contextLoads() throws Exception { assertThat(courseController).isNotNull(); assertThat(userController).isNotNull(); } @Test public void shouldReturnIndex() throws Exception { this.mockMvc .perform(get("/")) .andDo(print()) .andExpect(status().isOk()) .andExpect(view().name("index")); } @Test public void shouldBeRedirected() throws Exception { this.mockMvc.perform(get("/thisdoesnotexist")) .andDo(print()) .andExpect(status().isFound()) .andExpect(redirectedUrl("http://localhost/")); // redirected } @Test @WithMockUser("test") public void saveCourse() throws Exception { User instructor = new User(); instructor.setUsername("test"); instructor.setHasExtendedPrivileges(true); when(userRepository.findByUsername("test")).thenReturn(instructor); when(courseRepository.save(Matchers.anyCollection())).then(returnsFirstArg()); String name = "DGDUSMMYVK"; String timeSlot = "8:30"; String startDate = "2017-01-01"; String endDate = "2017-01-01"; String section = "section"; Integer rows = 10; Integer cols = 11; Course myCourse = new Course(); myCourse.setName(name); myCourse.setRows(rows); myCourse.setCols(cols); myCourse.setSection(section); myCourse.setStartDate(convertToSqlDate(startDate)); myCourse.setEndDate(convertToSqlDate(endDate)); myCourse.setTimeSlot(timeSlot); this.mockMvc.perform(post("/course") .contentType(MediaType.APPLICATION_FORM_URLENCODED) .param("name", name) .param("timeSlot", timeSlot) .param("startDate", startDate) .param("endDate", endDate) .param("cols", cols.toString()) .param("rows", rows.toString()) .param("section", section)) .andDo(print()) .andExpect(status().isFound()) .andExpect(redirectedUrl("/test/DGDUSMMYVK/section")); //redirected } @Test public void testSignup() throws Exception { when(userRepository.save(Matchers.anyCollection())).then(returnsFirstArg()); this.mockMvc.perform(post("/signup") .contentType(MediaType.APPLICATION_FORM_URLENCODED) .param("email", "test@unb.ca") .param("username", "name") .param("password", "password") .param("passwordConfirm", "password") .param("hasExtendedPrivileges", "false")) .andDo(print()) .andExpect(status().isOk()); } @Test @WithMockUser("test") public void hitCourseValidation() throws Exception { String name = "name"; String timeSlot = "8:30"; String startDate = "this isn't a real date"; String endDate = "2017-01-01"; //Dummy placeholder string to solve ambiguous argument problem String s = null; this.mockMvc.perform(post("/course") .contentType(MediaType.APPLICATION_FORM_URLENCODED) .param("name", name) .param("timeSlot", timeSlot) .param("startDate", startDate) .param("endDate", endDate)) .andDo(print()) .andExpect(status().isBadRequest()); } @Test @WithMockUser("test") public void coursePage() throws Exception { User intructor = new User(); intructor.setUsername("test"); Course course = new Course(); course.setInstructor(intructor); course.setName("test"); when(courseRepository.findByInstructorUsernameAndName("test", "test")).thenReturn(new ArrayList<Course>() {{ add(course); }}); mockMvc.perform(get("/test/test")) .andDo(print()) .andExpect(status().isOk()); } @Test @WithMockUser("test") public void coursePageWithSection() throws Exception { User instructor = new User(); instructor.setUsername("test"); Course course = new Course(); course.setInstructor(instructor); course.setSection("test"); course.setName("test"); when(courseRepository.findByInstructorUsernameAndNameAndSection("test", "test", "test")).thenReturn(new ArrayList<Course>() {{ add(course); }}); when(userRepository.findByUsername("test")).thenReturn(instructor); mockMvc.perform(get("/test/test/test")) .andDo(print()) .andExpect(status().isOk()); } @Test @WithMockUser("test") public void loginRedirect() throws Exception { mockMvc.perform(get("/login/success")) .andDo(print()) .andExpect(status().isFound()) .andExpect(redirectedUrl("/test")); } @Test @WithMockUser public void getCourses() throws Exception { when(courseRepository.findAll()).thenReturn(null); mockMvc.perform(get("/courses")) .andDo(print()) .andExpect(status().isOk()); } @Test @WithMockUser("test") public void getCourseThatExists() throws Exception { Course course = new Course(); course.setId(1l); when(courseRepository.findOne(1l)).thenReturn(course); mockMvc.perform(get("/courses/1")) .andDo(print()) .andExpect(status().isOk()); } @Test @WithMockUser("test") public void getCourseThatDoesNotExists() throws Exception { Course course = new Course(); course.setId(1l); when(courseRepository.findOne(1l)).thenReturn(null); mockMvc.perform(get("/courses/1")) .andDo(print()) .andExpect(status().isNotFound()); } @Test @WithMockUser("test") public void postSeat() throws Exception { Course course = new Course(); course.setId(1l); when(courseRepository.findOne(1l)).thenReturn(course); User user = new User(); user.setId(1); when(userRepository.findByUsername("test")).thenReturn(user); Seat seat = new Seat(); seat.setId(1l); seat.setCourse(course); seat.setStudent(user); seat.setCol(7); Seat s = new Seat(); s.setId(1l); List<Seat> seats = new ArrayList<>(); seats.add(s); course.setSeats(seats); mockMvc.perform(get("/courses/1/seat") .content(this.json(seat))) .andDo(print()) .andExpect(status().isOk()); //.andExpect(content().string("saved")); } /*@Test public void testLogin() throws Exception { mockMvc.perform(formLogin("/").user("jsmith21").password("jsmith21jsmith21")) .andDo(print()) .andExpect(authenticated()) .andExpect(redirectedUrl("/jsmith21")); }*/ @Test @WithMockUser public void testLogout() throws Exception { mockMvc.perform(logout()) .andDo(print()) .andExpect(status().isFound()) .andExpect(redirectedUrl("/")); } private Date convertToSqlDate(String dateString) throws Exception { return new java.sql.Date(dateFormat.parse(dateString).getTime()); } protected String json(Object o) throws IOException { MockHttpOutputMessage mockHttpOutputMessage = new MockHttpOutputMessage(); this.mappingJackson2HttpMessageConverter.write( o, MediaType.APPLICATION_JSON, mockHttpOutputMessage); return mockHttpOutputMessage.getBodyAsString(); } }
package eu.amidst.core.learning; import com.google.common.base.Stopwatch; import eu.amidst.core.datastream.Attribute; import eu.amidst.core.datastream.DataInstance; import eu.amidst.core.datastream.DataOnMemory; import eu.amidst.core.datastream.DataStream; import eu.amidst.core.datastream.filereaders.arffFileReader.ARFFDataReader; import eu.amidst.core.datastream.filereaders.arffFileReader.ARFFDataWriter; import eu.amidst.core.distribution.*; import eu.amidst.core.inference.VMP; import eu.amidst.core.io.BayesianNetworkLoader; import eu.amidst.core.io.DataStreamLoader; import eu.amidst.core.models.BayesianNetwork; import eu.amidst.core.models.DAG; import eu.amidst.core.utils.BayesianNetworkSampler; import eu.amidst.core.variables.StaticVariables; import eu.amidst.core.variables.Variable; import junit.framework.TestCase; import org.apache.commons.math.stat.descriptive.rank.Max; import java.io.IOException; import java.util.Iterator; import java.util.Random; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Stream; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; public class BayesianVMPTest extends TestCase { public static void testMultinomials1() throws IOException, ClassNotFoundException { StaticVariables variables = new StaticVariables(); Variable varA = variables.newMultionomialVariable("A", 2); DAG dag = new DAG(variables); BayesianNetwork bn = BayesianNetwork.newBayesianNetwork(dag); Multinomial distA = bn.getDistribution(varA); distA.setProbabilities(new double[]{0.6, 0.4}); BayesianNetworkSampler sampler = new BayesianNetworkSampler(bn); sampler.setSeed(2); DataStream<DataInstance> data = sampler.sampleToDataBase(1000); BayesianNetwork learntNormalVarBN = LearningEngineForBN.learnParameters(bn.getDAG(), data); System.out.println(learntNormalVarBN.toString()); StreamingVariationalBayesVMP svb = new StreamingVariationalBayesVMP(); svb.setWindowsSize(1000); svb.setSeed(5); VMP vmp = svb.getPlateuVMP().getVMP(); vmp.setTestELBO(true); vmp.setMaxIter(1000); vmp.setThreshold(0.0001); BayesianLearningEngineForBN.setBayesianLearningAlgorithmForBN(svb); BayesianLearningEngineForBN.setDAG(bn.getDAG()); BayesianLearningEngineForBN.setDataStream(data); BayesianLearningEngineForBN.runLearning(); BayesianNetwork learnBN = BayesianLearningEngineForBN.getLearntBayesianNetwork(); System.out.println(bn.toString()); System.out.println(learnBN.toString()); assertTrue(bn.equalBNs(learnBN,0.05)); } public static void testMultinomials2() throws IOException, ClassNotFoundException { StaticVariables variables = new StaticVariables(); Variable varA = variables.newMultionomialVariable("A", 2); Variable varB = variables.newMultionomialVariable("B", 2); DAG dag = new DAG(variables); dag.getParentSet(varB).addParent(varA); BayesianNetwork bn = BayesianNetwork.newBayesianNetwork(dag); Multinomial distA = bn.getDistribution(varA); Multinomial_MultinomialParents distB = bn.getDistribution(varB); distA.setProbabilities(new double[]{0.6, 0.4}); distB.getMultinomial(0).setProbabilities(new double[]{0.75, 0.25}); distB.getMultinomial(1).setProbabilities(new double[]{0.25, 0.75}); BayesianNetworkSampler sampler = new BayesianNetworkSampler(bn); sampler.setSeed(2); DataStream<DataInstance> data = sampler.sampleToDataBase(1000); System.out.println(LearningEngineForBN.learnParameters(bn.getDAG(), data).toString()); StreamingVariationalBayesVMP svb = new StreamingVariationalBayesVMP(); svb.setWindowsSize(1000); svb.setSeed(5); VMP vmp = svb.getPlateuVMP().getVMP(); vmp.setTestELBO(true); vmp.setMaxIter(1000); vmp.setThreshold(0.0001); BayesianLearningEngineForBN.setBayesianLearningAlgorithmForBN(svb); BayesianLearningEngineForBN.setDAG(bn.getDAG()); BayesianLearningEngineForBN.setDataStream(data); BayesianLearningEngineForBN.runLearning(); BayesianNetwork learnBN = BayesianLearningEngineForBN.getLearntBayesianNetwork(); System.out.println(bn.toString()); System.out.println(learnBN.toString()); assertTrue(bn.equalBNs(learnBN,0.05)); } public static void testMultinomials3() throws IOException, ClassNotFoundException { StaticVariables variables = new StaticVariables(); Variable varA = variables.newMultionomialVariable("A", 2); Variable varB = variables.newMultionomialVariable("B", 2); Variable varC = variables.newMultionomialVariable("C", 2); DAG dag = new DAG(variables); dag.getParentSet(varB).addParent(varA); dag.getParentSet(varC).addParent(varA); BayesianNetwork bn = BayesianNetwork.newBayesianNetwork(dag); bn.randomInitialization(new Random(6)); BayesianNetworkSampler sampler = new BayesianNetworkSampler(bn); sampler.setSeed(2); sampler.setHiddenVar(varA); DataStream<DataInstance> data = sampler.sampleToDataBase(20000); StreamingVariationalBayesVMP svb = new StreamingVariationalBayesVMP(); svb.setWindowsSize(1000); svb.setSeed(5); VMP vmp = svb.getPlateuVMP().getVMP(); vmp.setTestELBO(true); vmp.setMaxIter(1000); vmp.setThreshold(0.0001); BayesianLearningEngineForBN.setBayesianLearningAlgorithmForBN(svb); BayesianLearningEngineForBN.setDAG(bn.getDAG()); BayesianLearningEngineForBN.setDataStream(data); BayesianLearningEngineForBN.runLearning(); BayesianNetwork learnBN = BayesianLearningEngineForBN.getLearntBayesianNetwork(); System.out.println(bn.toString()); System.out.println(learnBN.toString()); assertTrue(bn.equalBNs(learnBN,0.1)); } public static void testMultinomials4() throws IOException, ClassNotFoundException { StaticVariables variables = new StaticVariables(); Variable varA = variables.newMultionomialVariable("A", 2); Variable varB = variables.newMultionomialVariable("B", 2); Variable varC = variables.newMultionomialVariable("C", 2); DAG dag = new DAG(variables); dag.getParentSet(varC).addParent(varB); dag.getParentSet(varB).addParent(varA); BayesianNetwork bn = BayesianNetwork.newBayesianNetwork(dag); bn.randomInitialization(new Random(5)); BayesianNetworkSampler sampler = new BayesianNetworkSampler(bn); sampler.setSeed(5); sampler.setHiddenVar(varB); DataStream<DataInstance> data = sampler.sampleToDataBase(50000); StreamingVariationalBayesVMP svb = new StreamingVariationalBayesVMP(); svb.setWindowsSize(1000); svb.setSeed(5); VMP vmp = svb.getPlateuVMP().getVMP(); vmp.setTestELBO(true); vmp.setMaxIter(1000); vmp.setThreshold(0.0001); BayesianLearningEngineForBN.setBayesianLearningAlgorithmForBN(svb); BayesianLearningEngineForBN.setDAG(bn.getDAG()); BayesianLearningEngineForBN.setDataStream(data); BayesianLearningEngineForBN.runLearning(); BayesianNetwork learnBN = BayesianLearningEngineForBN.getLearntBayesianNetwork(); System.out.println(bn.toString()); System.out.println(learnBN.toString()); assertTrue(bn.equalBNs(learnBN, 0.1)); } public static void testMultinomials5() throws IOException, ClassNotFoundException { StaticVariables variables = new StaticVariables(); Variable varA = variables.newMultionomialVariable("A", 5); Variable varB = variables.newMultionomialVariable("B", 5); Variable varC = variables.newMultionomialVariable("C", 5); DAG dag = new DAG(variables); dag.getParentSet(varC).addParent(varB); dag.getParentSet(varB).addParent(varA); BayesianNetwork bn = BayesianNetwork.newBayesianNetwork(dag); bn.randomInitialization(new Random(5)); BayesianNetworkSampler sampler = new BayesianNetworkSampler(bn); sampler.setSeed(5); sampler.setHiddenVar(varB); DataStream<DataInstance> data = sampler.sampleToDataBase(10000); StreamingVariationalBayesVMP svb = new StreamingVariationalBayesVMP(); svb.setWindowsSize(1000); svb.setSeed(5); VMP vmp = svb.getPlateuVMP().getVMP(); vmp.setTestELBO(true); vmp.setMaxIter(1000); vmp.setThreshold(0.0001); BayesianLearningEngineForBN.setBayesianLearningAlgorithmForBN(svb); BayesianLearningEngineForBN.setDAG(bn.getDAG()); BayesianLearningEngineForBN.setDataStream(data); BayesianLearningEngineForBN.runLearning(); BayesianNetwork learnBN = BayesianLearningEngineForBN.getLearntBayesianNetwork(); System.out.println(bn.toString()); System.out.println(learnBN.toString()); //assertTrue(bn.equalBNs(learnBN, 0.1)); } public static void testMultinomial6() throws IOException, ClassNotFoundException { StaticVariables variables = new StaticVariables(); Variable varB = variables.newMultionomialVariable("B",4); DAG dag = new DAG(variables); for (int i = 0; i < 10; i++) { BayesianNetwork bn = BayesianNetwork.newBayesianNetwork(dag); bn.randomInitialization(new Random(0)); bn.randomInitialization(new Random(0)); BayesianNetworkSampler sampler = new BayesianNetworkSampler(bn); sampler.setSeed(i+299); sampler.setHiddenVar(varB); DataStream<DataInstance> data = sampler.sampleToDataBase(10000); StreamingVariationalBayesVMP svb = new StreamingVariationalBayesVMP(); svb.setWindowsSize(1000); svb.setSeed(i); VMP vmp = svb.getPlateuVMP().getVMP(); vmp.setTestELBO(true); vmp.setMaxIter(1000); vmp.setThreshold(0.0001); BayesianLearningEngineForBN.setBayesianLearningAlgorithmForBN(svb); BayesianLearningEngineForBN.setDAG(bn.getDAG()); BayesianLearningEngineForBN.setDataStream(data); BayesianLearningEngineForBN.runLearning(); BayesianNetwork learnBN = BayesianLearningEngineForBN.getLearntBayesianNetwork(); System.out.println(bn.toString()); System.out.println(learnBN.toString()); //assertTrue(bn.equalBNs(learnBN, 0.5)); } } public static void testAsia() throws IOException, ClassNotFoundException{ BayesianNetwork asianet = BayesianNetworkLoader.loadFromFile("networks/asia.bn"); asianet.randomInitialization(new Random(0)); System.out.println("\nAsia network \n "); BayesianNetworkSampler sampler = new BayesianNetworkSampler(asianet); sampler.setSeed(0); DataStream<DataInstance> data = sampler.sampleToDataBase(10000); StreamingVariationalBayesVMP svb = new StreamingVariationalBayesVMP(); svb.setWindowsSize(1000); svb.setSeed(5); VMP vmp = svb.getPlateuVMP().getVMP(); vmp.setTestELBO(true); vmp.setMaxIter(1000); vmp.setThreshold(0.0001); BayesianLearningEngineForBN.setBayesianLearningAlgorithmForBN(svb); BayesianLearningEngineForBN.setDAG(asianet.getDAG()); BayesianLearningEngineForBN.setDataStream(data); BayesianLearningEngineForBN.runLearning(); System.out.println(BayesianLearningEngineForBN.getLogMarginalProbability()); BayesianNetwork learnAsianet = BayesianLearningEngineForBN.getLearntBayesianNetwork(); System.out.println(asianet.toString()); System.out.println(learnAsianet.toString()); assertTrue(asianet.equalBNs(learnAsianet,0.05)); } public static void testAsia2() throws IOException, ClassNotFoundException{ BayesianNetwork asianet = BayesianNetworkLoader.loadFromFile("networks/asia.bn"); System.out.println(asianet.toString()); asianet.randomInitialization(new Random(0)); System.out.println("\nAsia network \n "); BayesianNetworkSampler sampler = new BayesianNetworkSampler(asianet); sampler.setHiddenVar(asianet.getStaticVariables().getVariableByName("E")); sampler.setHiddenVar(asianet.getStaticVariables().getVariableByName("L")); //sampler.setMARVar(asianet.getStaticVariables().getVariableByName("E"),0.5); //sampler.setMARVar(asianet.getStaticVariables().getVariableByName("L"),0.5); sampler.setSeed(0); DataStream<DataInstance> data = sampler.sampleToDataBase(10000); StreamingVariationalBayesVMP svb = new StreamingVariationalBayesVMP(); svb.setWindowsSize(100); svb.setSeed(5); VMP vmp = svb.getPlateuVMP().getVMP(); vmp.setTestELBO(true); vmp.setMaxIter(1000); vmp.setThreshold(0.0001); BayesianLearningEngineForBN.setBayesianLearningAlgorithmForBN(svb); BayesianLearningEngineForBN.setDAG(asianet.getDAG()); BayesianLearningEngineForBN.setDataStream(data); BayesianLearningEngineForBN.runLearning(); System.out.println(BayesianLearningEngineForBN.getLogMarginalProbability()); BayesianNetwork learnAsianet = BayesianLearningEngineForBN.getLearntBayesianNetwork(); //System.out.println(asianet.toString()); //System.out.println(learnAsianet.toString()); //assertTrue(asianet.equalBNs(learnAsianet,0.05)); } public static void testGaussian0() throws IOException, ClassNotFoundException{ BayesianNetwork oneNormalVarBN = BayesianNetworkLoader.loadFromFile("networks/Normal.bn"); for (int i = 0; i < 10; i++) { Variable varA = oneNormalVarBN.getStaticVariables().getVariableByName("A"); Normal dist = oneNormalVarBN.getDistribution(varA); dist.setMean(2000); dist.setVariance(30); oneNormalVarBN.randomInitialization(new Random(i)); System.out.println("\nOne normal variable network \n "); BayesianNetworkSampler sampler = new BayesianNetworkSampler(oneNormalVarBN); sampler.setSeed(0); DataStream<DataInstance> data = sampler.sampleToDataBase(1000); System.out.println(LearningEngineForBN.learnParameters(oneNormalVarBN.getDAG(), data).toString()); StreamingVariationalBayesVMP svb = new StreamingVariationalBayesVMP(); svb.setWindowsSize(100); svb.setSeed(i); VMP vmp = svb.getPlateuVMP().getVMP(); vmp.setOutput(true); vmp.setTestELBO(true); vmp.setMaxIter(1000); vmp.setThreshold(0.0001); BayesianLearningEngineForBN.setBayesianLearningAlgorithmForBN(svb); BayesianLearningEngineForBN.setDAG(oneNormalVarBN.getDAG()); BayesianLearningEngineForBN.setDataStream(data); BayesianLearningEngineForBN.runLearning(); System.out.println(BayesianLearningEngineForBN.getLogMarginalProbability()); BayesianNetwork learntOneNormalVarBN = BayesianLearningEngineForBN.getLearntBayesianNetwork(); System.out.println(oneNormalVarBN.toString()); System.out.println(learntOneNormalVarBN.toString()); assertTrue(oneNormalVarBN.equalBNs(learntOneNormalVarBN, 0.1)); } } public static void testWasteIncinerator() throws IOException, ClassNotFoundException{ BayesianNetwork normalVarBN = BayesianNetworkLoader.loadFromFile("networks/WasteIncinerator.bn"); //normalVarBN.randomInitialization(new Random(0)); System.out.println("\nNormal|2Normal variable network \n "); BayesianNetworkSampler sampler = new BayesianNetworkSampler(normalVarBN); sampler.setSeed(1); DataStream<DataInstance> data = sampler.sampleToDataBase(10000); BayesianNetwork learntNormalVarBN = LearningEngineForBN.learnParameters(normalVarBN.getDAG(), data); System.out.println(normalVarBN.toString()); System.out.println(learntNormalVarBN.toString()); assertTrue(normalVarBN.equalBNs(learntNormalVarBN, 0.2)); StreamingVariationalBayesVMP svb = new StreamingVariationalBayesVMP(); svb.setWindowsSize(1000); svb.setSeed(5); VMP vmp = svb.getPlateuVMP().getVMP(); vmp.setTestELBO(true); vmp.setMaxIter(1000); vmp.setThreshold(0.0001); BayesianLearningEngineForBN.setBayesianLearningAlgorithmForBN(svb); BayesianLearningEngineForBN.setDAG(normalVarBN.getDAG()); BayesianLearningEngineForBN.setDataStream(data); BayesianLearningEngineForBN.runLearning(); System.out.println(BayesianLearningEngineForBN.getLogMarginalProbability()); learntNormalVarBN = BayesianLearningEngineForBN.getLearntBayesianNetwork(); System.out.println(normalVarBN.toString()); System.out.println(learntNormalVarBN.toString()); assertTrue(normalVarBN.equalBNs(learntNormalVarBN,0.2)); } public static void testGaussian1() throws IOException, ClassNotFoundException{ BayesianNetwork normalVarBN = BayesianNetworkLoader.loadFromFile("networks/Normal_1NormalParents.bn"); for (int i = 0; i < 10; i++) { System.out.println("\nNormal|Normal variable network \n "); normalVarBN.randomInitialization(new Random(i)); BayesianNetworkSampler sampler = new BayesianNetworkSampler(normalVarBN); sampler.setSeed(2); DataStream<DataInstance> data = sampler.sampleToDataBase(10000); BayesianNetwork learntNormalVarBN = LearningEngineForBN.learnParameters(normalVarBN.getDAG(), data); System.out.println(normalVarBN.toString()); System.out.println(learntNormalVarBN.toString()); assertTrue(normalVarBN.equalBNs(learntNormalVarBN, 0.1)); StreamingVariationalBayesVMP svb = new StreamingVariationalBayesVMP(); svb.setParallelMode(false); svb.setWindowsSize(1000); svb.setSeed(i); VMP vmp = svb.getPlateuVMP().getVMP(); vmp.setOutput(false); vmp.setTestELBO(true); vmp.setMaxIter(1000); vmp.setThreshold(0.0001); BayesianLearningEngineForBN.setBayesianLearningAlgorithmForBN(svb); BayesianLearningEngineForBN.setDAG(normalVarBN.getDAG()); BayesianLearningEngineForBN.setDataStream(data); BayesianLearningEngineForBN.runLearning(); System.out.println(BayesianLearningEngineForBN.getLogMarginalProbability()); learntNormalVarBN = BayesianLearningEngineForBN.getLearntBayesianNetwork(); System.out.println(normalVarBN.toString()); System.out.println(learntNormalVarBN.toString()); assertTrue(normalVarBN.equalBNs(learntNormalVarBN, 0.1)); } } public static void testGaussian2() throws IOException, ClassNotFoundException{ BayesianNetwork normalVarBN = BayesianNetworkLoader.loadFromFile("networks/Normal_NormalParents.bn"); int cont=0; for (int i = 0; i < 10; i++) { normalVarBN.randomInitialization(new Random(i)); System.out.println("\nNormal|2Normal variable network \n "); BayesianNetworkSampler sampler = new BayesianNetworkSampler(normalVarBN); sampler.setSeed(0); DataStream<DataInstance> data = sampler.sampleToDataBase(10000); BayesianNetwork learntNormalVarBN = LearningEngineForBN.learnParameters(normalVarBN.getDAG(), data); System.out.println(normalVarBN.toString()); System.out.println(learntNormalVarBN.toString()); assertTrue(normalVarBN.equalBNs(learntNormalVarBN, 0.1)); StreamingVariationalBayesVMP svb = new StreamingVariationalBayesVMP(); svb.setWindowsSize(1000); svb.setSeed(i); VMP vmp = svb.getPlateuVMP().getVMP(); vmp.setTestELBO(true); vmp.setMaxIter(1000); vmp.setThreshold(0.0001); BayesianLearningEngineForBN.setBayesianLearningAlgorithmForBN(svb); BayesianLearningEngineForBN.setDAG(normalVarBN.getDAG()); BayesianLearningEngineForBN.setDataStream(data); BayesianLearningEngineForBN.runLearning(); learntNormalVarBN = BayesianLearningEngineForBN.getLearntBayesianNetwork(); System.out.println(normalVarBN.toString()); System.out.println(learntNormalVarBN.toString()); assertTrue(normalVarBN.equalBNs(learntNormalVarBN, 0.1)); } } public static void testGaussian3() throws IOException, ClassNotFoundException{ BayesianNetwork normalVarBN = BayesianNetworkLoader.loadFromFile("networks/Normal_MultinomialParents.bn"); for (int i = 0; i < 10; i++) { normalVarBN.randomInitialization(new Random(i)); System.out.println("\nNormal|2Normal variable network \n "); BayesianNetworkSampler sampler = new BayesianNetworkSampler(normalVarBN); sampler.setSeed(0); DataStream<DataInstance> data = sampler.sampleToDataBase(10000); BayesianNetwork learntNormalVarBN = LearningEngineForBN.learnParameters(normalVarBN.getDAG(), data); System.out.println(normalVarBN.toString()); System.out.println(learntNormalVarBN.toString()); assertTrue(normalVarBN.equalBNs(learntNormalVarBN, 0.2)); StreamingVariationalBayesVMP svb = new StreamingVariationalBayesVMP(); svb.setWindowsSize(1000); svb.setSeed(i); VMP vmp = svb.getPlateuVMP().getVMP(); vmp.setTestELBO(true); vmp.setMaxIter(1000); vmp.setThreshold(0.0001); BayesianLearningEngineForBN.setBayesianLearningAlgorithmForBN(svb); BayesianLearningEngineForBN.setDAG(normalVarBN.getDAG()); BayesianLearningEngineForBN.setDataStream(data); BayesianLearningEngineForBN.runLearning(); learntNormalVarBN = BayesianLearningEngineForBN.getLearntBayesianNetwork(); System.out.println(normalVarBN.toString()); System.out.println(learntNormalVarBN.toString()); assertTrue(normalVarBN.equalBNs(learntNormalVarBN, 0.2)); } } public static void testGaussian4() throws IOException, ClassNotFoundException{ BayesianNetwork normalVarBN = BayesianNetworkLoader.loadFromFile("networks/Normal_MultinomialNormalParents.bn"); int contA=0; int contB=0; for (int i = 1; i < 2; i++) { normalVarBN.randomInitialization(new Random(i)); System.out.println("\nNormal|2Normal variable network \n "); BayesianNetworkSampler sampler = new BayesianNetworkSampler(normalVarBN); sampler.setSeed(0); DataStream<DataInstance> data = sampler.sampleToDataBase(10000); BayesianNetwork learntNormalVarBN = LearningEngineForBN.learnParameters(normalVarBN.getDAG(), data); System.out.println(normalVarBN.toString()); System.out.println(learntNormalVarBN.toString()); assertTrue(normalVarBN.equalBNs(learntNormalVarBN, 0.3)); if (normalVarBN.equalBNs(learntNormalVarBN, 0.3)) contA++; StreamingVariationalBayesVMP svb = new StreamingVariationalBayesVMP(); svb.setWindowsSize(1000); svb.setSeed(i); VMP vmp = svb.getPlateuVMP().getVMP(); vmp.setTestELBO(true); vmp.setMaxIter(1000); vmp.setThreshold(0.0001); BayesianLearningEngineForBN.setBayesianLearningAlgorithmForBN(svb); BayesianLearningEngineForBN.setDAG(normalVarBN.getDAG()); BayesianLearningEngineForBN.setDataStream(data); BayesianLearningEngineForBN.runLearning(); learntNormalVarBN = BayesianLearningEngineForBN.getLearntBayesianNetwork(); System.out.println(normalVarBN.toString()); System.out.println(learntNormalVarBN.toString()); assertTrue(normalVarBN.equalBNs(learntNormalVarBN, 0.3)); if (normalVarBN.equalBNs(learntNormalVarBN, 0.3)) contB++; } System.out.println(contA); System.out.println(contB); } public static void testGaussian5() throws IOException, ClassNotFoundException { StaticVariables variables = new StaticVariables(); Variable varA = variables.newGaussianVariable("A"); Variable varB = variables.newGaussianVariable("B"); Variable varC = variables.newGaussianVariable("C"); DAG dag = new DAG(variables); dag.getParentSet(varB).addParent(varA); dag.getParentSet(varC).addParent(varA); BayesianNetwork bn = BayesianNetwork.newBayesianNetwork(dag); bn.randomInitialization(new Random(0)); System.out.println(bn.toString()); BayesianNetworkSampler sampler = new BayesianNetworkSampler(bn); sampler.setSeed(2); sampler.setHiddenVar(varA); DataStream<DataInstance> data = sampler.sampleToDataBase(50); StreamingVariationalBayesVMP svb = new StreamingVariationalBayesVMP(); svb.setWindowsSize(5); //Set to 2 and an exception is raised. Numerical instability. svb.setSeed(1); VMP vmp = svb.getPlateuVMP().getVMP(); vmp.setTestELBO(true); vmp.setMaxIter(1000); vmp.setThreshold(0.001); BayesianLearningEngineForBN.setBayesianLearningAlgorithmForBN(svb); BayesianLearningEngineForBN.setDAG(bn.getDAG()); BayesianLearningEngineForBN.setDataStream(data); BayesianLearningEngineForBN.runLearning(); BayesianNetwork learnBN = BayesianLearningEngineForBN.getLearntBayesianNetwork(); System.out.println(bn.toString()); System.out.println(learnBN.toString()); //assertTrue(bn.equalBNs(learnBN,0.1)); } public static void testGaussian6() throws IOException, ClassNotFoundException { StaticVariables variables = new StaticVariables(); Variable varA = variables.newGaussianVariable("A"); Variable varB = variables.newGaussianVariable("B"); Variable varC = variables.newGaussianVariable("C"); DAG dag = new DAG(variables); dag.getParentSet(varB).addParent(varA); dag.getParentSet(varC).addParent(varB); for (int i = 0; i < 1; i++) { BayesianNetwork bn = BayesianNetwork.newBayesianNetwork(dag); bn.randomInitialization(new Random(i)); System.out.println(bn.toString()); BayesianNetworkSampler sampler = new BayesianNetworkSampler(bn); sampler.setSeed(i); sampler.setMARVar(varB, 0.9); DataStream<DataInstance> data = sampler.sampleToDataBase(10000); StreamingVariationalBayesVMP svb = new StreamingVariationalBayesVMP(); svb.setWindowsSize(1000); svb.setSeed(i); VMP vmp = svb.getPlateuVMP().getVMP(); vmp.setTestELBO(true); vmp.setMaxIter(1000); vmp.setThreshold(0.0001); BayesianLearningEngineForBN.setBayesianLearningAlgorithmForBN(svb); BayesianLearningEngineForBN.setDAG(bn.getDAG()); BayesianLearningEngineForBN.setDataStream(data); BayesianLearningEngineForBN.runLearning(); System.out.println("Data Prob: " + BayesianLearningEngineForBN.getLogMarginalProbability()); BayesianNetwork learnBN = BayesianLearningEngineForBN.getLearntBayesianNetwork(); System.out.println(bn.toString()); System.out.println(learnBN.toString()); assertTrue(bn.equalBNs(learnBN, 0.2)); } } public static void testGaussian7() throws IOException, ClassNotFoundException { StaticVariables variables = new StaticVariables(); Variable varB = variables.newGaussianVariable("B"); DAG dag = new DAG(variables); for (int i = 0; i < 10; i++) { BayesianNetwork bn = BayesianNetwork.newBayesianNetwork(dag); bn.randomInitialization(new Random(0)); bn.randomInitialization(new Random(0)); BayesianNetworkSampler sampler = new BayesianNetworkSampler(bn); sampler.setSeed(i); sampler.setHiddenVar(varB); DataStream<DataInstance> data = sampler.sampleToDataBase(10); StreamingVariationalBayesVMP svb = new StreamingVariationalBayesVMP(); svb.setWindowsSize(10); //Set to 2 and an exception is raised. Numerical instability. svb.setSeed(i); VMP vmp = svb.getPlateuVMP().getVMP(); vmp.setTestELBO(true); vmp.setMaxIter(1000); vmp.setThreshold(0.0001); BayesianLearningEngineForBN.setBayesianLearningAlgorithmForBN(svb); BayesianLearningEngineForBN.setDAG(bn.getDAG()); BayesianLearningEngineForBN.setDataStream(data); BayesianLearningEngineForBN.runLearning(); System.out.println("Data Prob: " + BayesianLearningEngineForBN.getLogMarginalProbability()); BayesianNetwork learnBN = BayesianLearningEngineForBN.getLearntBayesianNetwork(); System.out.println(bn.toString()); System.out.println(learnBN.toString()); //assertTrue(bn.equalBNs(learnBN, 0.5)); } } public static void testGaussian8() throws IOException, ClassNotFoundException { StaticVariables variables = new StaticVariables(); Variable varA = variables.newGaussianVariable("A"); Variable varB = variables.newGaussianVariable("B"); Variable varC = variables.newGaussianVariable("C"); DAG dag = new DAG(variables); dag.getParentSet(varB).addParent(varA); dag.getParentSet(varC).addParent(varB); for (int i = 1; i < 2; i++) { BayesianNetwork bn = BayesianNetwork.newBayesianNetwork(dag); bn.randomInitialization(new Random(0)); bn.randomInitialization(new Random(i)); //System.out.println(bn.toString()); BayesianNetworkSampler sampler = new BayesianNetworkSampler(bn); sampler.setSeed(i+299); sampler.setHiddenVar(varB); DataStream<DataInstance> data = sampler.sampleToDataBase(10000); StreamingVariationalBayesVMP svb = new StreamingVariationalBayesVMP(); svb.setWindowsSize(10); svb.setSeed(i); VMP vmp = svb.getPlateuVMP().getVMP(); vmp.setTestELBO(true); vmp.setMaxIter(1000); vmp.setThreshold(0.001); BayesianLearningEngineForBN.setBayesianLearningAlgorithmForBN(svb); BayesianLearningEngineForBN.setDAG(bn.getDAG()); BayesianLearningEngineForBN.setDataStream(data); BayesianLearningEngineForBN.runLearning(); System.out.println("Data Prob: " + BayesianLearningEngineForBN.getLogMarginalProbability()); BayesianNetwork learnBN = BayesianLearningEngineForBN.getLearntBayesianNetwork(); System.out.println(bn.toString()); System.out.println(learnBN.toString()); ConditionalLinearGaussian distCP = bn.getDistribution(varC); ConditionalLinearGaussian distCQ = learnBN.getDistribution(varC); assertEquals(distCP.getSd(), distCQ.getSd(), 0.05); } } public static void testCompareBatchSizes() throws IOException, ClassNotFoundException { BayesianNetwork normalVarBN = BayesianNetworkLoader.loadFromFile("networks/Normal_1NormalParents.bn"); for (int i = 0; i < 1; i++) { System.out.println("\nNormal|Normal variable network \n "); normalVarBN.randomInitialization(new Random(i)); BayesianNetworkSampler sampler = new BayesianNetworkSampler(normalVarBN); sampler.setSeed(i); DataStream<DataInstance> data = sampler.sampleToDataBase(10000); Attribute attVarA = data.getAttributes().getAttributeByName("A"); Attribute attVarB = data.getAttributes().getAttributeByName("B"); Variable varA = normalVarBN.getStaticVariables().getVariableByName("A"); Variable varB = normalVarBN.getStaticVariables().getVariableByName("B"); BayesianNetwork learntNormalVarBN = LearningEngineForBN.learnParameters(normalVarBN.getDAG(), data); String beta0fromML = Double.toString(((ConditionalLinearGaussian)learntNormalVarBN. getConditionalDistribution(varA)).getIntercept()); String beta1fromML = Double.toString(((ConditionalLinearGaussian)learntNormalVarBN. getConditionalDistribution(varA)).getCoeffParents()[0]); /** * Incremental sample mean */ String sampleMeanB = ""; double incrementalMeanB = 0; double index = 1; for(DataInstance dataInstance: data){ incrementalMeanB = incrementalMeanB + (dataInstance.getValue(attVarB) - incrementalMeanB)/index; sampleMeanB += incrementalMeanB+", "; index++; } /** * Streaming Variational Bayes for batches of 1 sample */ StreamingVariationalBayesVMP svb = new StreamingVariationalBayesVMP(); svb.setSeed(i); VMP vmp = svb.getPlateuVMP().getVMP(); vmp.setTestELBO(true); vmp.setMaxIter(1000); vmp.setThreshold(0.0001); BayesianLearningEngineForBN.setBayesianLearningAlgorithmForBN(svb); BayesianLearningEngineForBN.setDAG(normalVarBN.getDAG()); BayesianLearningEngineForBN.setDataStream(data); String varA_Beta0output = "Variable A beta0 (CLG)\n"+beta0fromML+ "\n", varA_Beta1output = "Variable A beta1 (CLG)\n"+beta1fromML+ "\n", varBoutput = "Variable B mean (univ. normal)\n"+sampleMeanB + "\n"; int[] windowsSizes = {1,10,100, 1000}; for (int j = 0; j < windowsSizes.length; j++) { svb.setWindowsSize(windowsSizes[j]); svb.initLearning(); String svbBeta0A = "", svbBeta1A = "",svbMeanB = ""; Iterator<DataOnMemory<DataInstance>> batchIterator = data.streamOfBatches(windowsSizes[j]).iterator(); while(batchIterator.hasNext()){ DataOnMemory<DataInstance> batch = batchIterator.next(); svb.updateModel(batch); ConditionalLinearGaussian distAsample = svb.getLearntBayesianNetwork(). getConditionalDistribution(varA); double beta0A = distAsample.getIntercept(); double beta1A = distAsample.getCoeffParents()[0]; svbBeta0A += beta0A+", "; svbBeta1A += beta1A+", "; Normal distBsample = (Normal)((BaseDistribution_MultinomialParents)svb.getLearntBayesianNetwork(). getConditionalDistribution(varB)).getBaseDistribution(0); svbMeanB += distBsample.getMean()+", "; } varA_Beta0output += svbBeta0A +"\n"; varA_Beta1output += svbBeta1A +"\n"; varBoutput += svbMeanB +"\n"; } System.out.println(varA_Beta0output); System.out.println(varA_Beta1output); System.out.println(varBoutput); } } public static void testCompareBatchSizesParallelMode() throws IOException, ClassNotFoundException { BayesianNetwork normalVarBN = BayesianNetworkLoader.loadFromFile("networks/Normal_1NormalParents.bn"); for (int i = 0; i < 1; i++) { System.out.println("\nNormal|Normal variable network \n "); normalVarBN.randomInitialization(new Random(i)); BayesianNetworkSampler sampler = new BayesianNetworkSampler(normalVarBN); sampler.setSeed(i); DataStream<DataInstance> data = sampler.sampleToDataBase(10000); Attribute attVarA = data.getAttributes().getAttributeByName("A"); Attribute attVarB = data.getAttributes().getAttributeByName("B"); Variable varA = normalVarBN.getStaticVariables().getVariableByName("A"); Variable varB = normalVarBN.getStaticVariables().getVariableByName("B"); BayesianNetwork learntNormalVarBN = LearningEngineForBN.learnParameters(normalVarBN.getDAG(), data); //System.out.println(learntNormalVarBN.toString()); String meanfromML = Double.toString(((Normal) ((BaseDistribution_MultinomialParents) learntNormalVarBN. getConditionalDistribution(varB)).getBaseDistribution(0)).getMean()); String beta0fromML = Double.toString(((ConditionalLinearGaussian)learntNormalVarBN. getConditionalDistribution(varA)).getIntercept()); String beta1fromML = Double.toString(((ConditionalLinearGaussian)learntNormalVarBN. getConditionalDistribution(varA)).getCoeffParents()[0]); /** * Incremental sample mean */ String sampleMeanB = ""; double incrementalMeanB = 0; double index = 1; for(DataInstance dataInstance: data){ incrementalMeanB = incrementalMeanB + (dataInstance.getValue(attVarB) - incrementalMeanB)/index; sampleMeanB += incrementalMeanB+", "; index++; } /** * Streaming Variational Bayes for batches of different sizes */ StreamingVariationalBayesVMP svb = new StreamingVariationalBayesVMP(); svb.setParallelMode(false); svb.setSeed(i); VMP vmp = svb.getPlateuVMP().getVMP(); vmp.setOutput(false); vmp.setTestELBO(true); vmp.setMaxIter(1000); vmp.setThreshold(0.0001); svb.setDAG(normalVarBN.getDAG()); svb.setDataStream(data); String[] meanBSerial = new String[4]; String[] beta0Serial = new String[4]; String[] beta1Serial = new String[4]; String[] meanBParallelSeqQ = new String[4]; String[] beta0ParallelSeqQ = new String[4]; String[] beta1ParallelSeqQ = new String[4]; String[] meanBParallelRandQ = new String[4]; String[] beta0ParallelRandQ = new String[4]; String[] beta1ParallelRandQ = new String[4]; String[] iterSerial = new String[4]; String[] iterParallelSeqQ = new String[4]; String[] iterParallelRandQ = new String[4]; int[] windowsSizes = {1,2,10,1000}; svb.setParallelMode(false); for (int j = 0; j < windowsSizes.length; j++) { System.out.println("Window: "+windowsSizes[j]); svb.setWindowsSize(windowsSizes[j]); svb.initLearning(); svb.runLearning(); BayesianNetwork svbSerial = svb.getLearntBayesianNetwork(); meanBSerial[j] = Double.toString(((Normal) ((BaseDistribution_MultinomialParents) svbSerial. getConditionalDistribution(varB)).getBaseDistribution(0)).getMean()); beta0Serial[j] = Double.toString(((ConditionalLinearGaussian)svbSerial. getConditionalDistribution(varA)).getIntercept()); beta1Serial[j] = Double.toString(((ConditionalLinearGaussian)svbSerial. getConditionalDistribution(varA)).getCoeffParents()[0]); iterSerial[j] = Double.toString(svb.getAverageNumOfIterations()); } vmp.setOutput(false); svb.setParallelMode(true); svb.setRandomRestart(false); for (int j = 0; j < windowsSizes.length; j++) { System.out.println("Window: "+windowsSizes[j]); svb.setWindowsSize(windowsSizes[j]); svb.initLearning(); svb.runLearning(); BayesianNetwork svbSerial = svb.getLearntBayesianNetwork(); meanBParallelSeqQ[j] = Double.toString(((Normal) ((BaseDistribution_MultinomialParents)svbSerial. getConditionalDistribution(varB)).getBaseDistribution(0)).getMean()); beta0ParallelSeqQ[j] = Double.toString(((ConditionalLinearGaussian)svbSerial. getConditionalDistribution(varA)).getIntercept()); beta1ParallelSeqQ[j] = Double.toString(((ConditionalLinearGaussian)svbSerial. getConditionalDistribution(varA)).getCoeffParents()[0]); iterParallelSeqQ[j] = Double.toString(svb.getAverageNumOfIterations()); } vmp.setOutput(true); svb.setParallelMode(true); svb.setRandomRestart(true); for (int j = 0; j < windowsSizes.length; j++) { System.out.println("Window: "+windowsSizes[j]); svb.setWindowsSize(windowsSizes[j]); svb.initLearning(); svb.runLearning(); BayesianNetwork svbSerial = svb.getLearntBayesianNetwork(); meanBParallelRandQ[j] = Double.toString(((Normal) ((BaseDistribution_MultinomialParents)svbSerial. getConditionalDistribution(varB)).getBaseDistribution(0)).getMean()); beta0ParallelRandQ[j] = Double.toString(((ConditionalLinearGaussian)svbSerial. getConditionalDistribution(varA)).getIntercept()); beta1ParallelRandQ[j] = Double.toString(((ConditionalLinearGaussian)svbSerial. getConditionalDistribution(varA)).getCoeffParents()[0]); iterParallelRandQ[j] = Double.toString((svb.getAverageNumOfIterations())); } System.out.println("Mean of B"); System.out.println("WindowSize \t ML \t Serial \t ParallelSeqQ \t ParallelRandQ"); for (int j = 0; j < windowsSizes.length; j++) { System.out.println(windowsSizes[j]+ "\t" + meanfromML + "\t" + meanBSerial[j] + "\t" + meanBParallelSeqQ[j]+ "\t" + meanBParallelRandQ[j]); } System.out.println("Beta0 of A"); System.out.println("WindowSize\t ML \t Serial \t ParallelSeqQ \t ParallelRandQ"); for (int j = 0; j < windowsSizes.length; j++) { System.out.println(windowsSizes[j]+ "\t" + beta0fromML + "\t" + beta0Serial[j] + "\t" + beta0ParallelSeqQ[j]+ "\t" + beta0ParallelRandQ[j]); } System.out.println("Beta1 of A"); System.out.println("WindowSize\t ML \t Serial \t ParallelSeqQ \t ParallelRandQ"); for (int j = 0; j < windowsSizes.length; j++) { System.out.println(windowsSizes[j]+ "\t" + beta1fromML + "\t" + beta1Serial[j] + "\t" + beta1ParallelSeqQ[j] + "\t" + beta1ParallelRandQ[j]); } System.out.println("WindowSize \t Serial \t ParallelSeqQ \t ParallelRandQ"); for (int j = 0; j < windowsSizes.length; j++) { System.out.println(windowsSizes[j]+ "\t" + iterSerial[j] + "\t" + iterParallelSeqQ[j] + "\t" + iterParallelRandQ[j]); } //svb.runLearningOnParallelForDifferentBatchWindows(windowsSizes, beta0fromML, beta1fromML, sampleMeanB); } } public static void testCompareBatchSizesFadingVMP() throws IOException, ClassNotFoundException { BayesianNetwork normalVarBN = BayesianNetworkLoader.loadFromFile("networks/Normal_1NormalParents.bn"); for (int i = 0; i < 1; i++) { System.out.println("\nNormal|Normal variable network \n "); normalVarBN.randomInitialization(new Random(i)); Variable varA = normalVarBN.getStaticVariables().getVariableByName("A"); Variable varB = normalVarBN.getStaticVariables().getVariableByName("B"); BayesianNetworkSampler sampler = new BayesianNetworkSampler(normalVarBN); sampler.setSeed(0); //sampler.setMARVar(varB,0.5); DataStream<DataInstance> data = sampler.sampleToDataBase(10000); ARFFDataWriter.writeToARFFFile(data, "./data/tmp.arff"); data = DataStreamLoader.loadFromFile("./data/tmp.arff"); Attribute attVarA = data.getAttributes().getAttributeByName("A"); Attribute attVarB = data.getAttributes().getAttributeByName("B"); BayesianNetwork learntNormalVarBN = LearningEngineForBN.learnParameters(normalVarBN.getDAG(), data); //System.out.println(learntNormalVarBN.toString()); String meanfromML = Double.toString(((Normal) ((BaseDistribution_MultinomialParents) learntNormalVarBN. getConditionalDistribution(varB)).getBaseDistribution(0)).getMean()); String beta0fromML = Double.toString(((ConditionalLinearGaussian)learntNormalVarBN. getConditionalDistribution(varA)).getIntercept()); String beta1fromML = Double.toString(((ConditionalLinearGaussian)learntNormalVarBN. getConditionalDistribution(varA)).getCoeffParents()[0]); /** * Incremental sample mean */ String sampleMeanB = ""; double incrementalMeanB = 0; double index = 1; for(DataInstance dataInstance: data){ incrementalMeanB = incrementalMeanB + (dataInstance.getValue(attVarB) - incrementalMeanB)/index; sampleMeanB += incrementalMeanB+", "; index++; } /** * Streaming Variational Bayes for batches of different sizes */ StreamingVariationalBayesVMP svb = new StreamingVariationalBayesVMP(); svb.setParallelMode(false); svb.setSeed(i); VMP vmp = svb.getPlateuVMP().getVMP(); vmp.setOutput(false); vmp.setTestELBO(true); vmp.setMaxIter(1000); vmp.setThreshold(0.0001); svb.setDAG(normalVarBN.getDAG()); svb.setDataStream(data); String[] meanBSerial = new String[4]; String[] beta0Serial = new String[4]; String[] beta1Serial = new String[4]; String[] meanBParallelSeqQ = new String[4]; String[] beta0ParallelSeqQ = new String[4]; String[] beta1ParallelSeqQ = new String[4]; String[] meanBParallelRandQ = new String[4]; String[] beta0ParallelRandQ = new String[4]; String[] beta1ParallelRandQ = new String[4]; String[] iterSerial = new String[4]; String[] iterParallelSeqQ = new String[4]; String[] iterParallelRandQ = new String[4]; int[] windowsSizes = {1,10,50,100}; svb.setParallelMode(false); svb.setFading(0.99); for (int j = 0; j < windowsSizes.length; j++) { //System.out.println("Window: "+windowsSizes[j]); svb.setWindowsSize(windowsSizes[j]); svb.initLearning(); svb.runLearning(); BayesianNetwork svbSerial = svb.getLearntBayesianNetwork(); meanBSerial[j] = Double.toString(((Normal) ((BaseDistribution_MultinomialParents) svbSerial. getConditionalDistribution(varB)).getBaseDistribution(0)).getMean()); beta0Serial[j] = Double.toString(((ConditionalLinearGaussian)svbSerial. getConditionalDistribution(varA)).getIntercept()); beta1Serial[j] = Double.toString(((ConditionalLinearGaussian)svbSerial. getConditionalDistribution(varA)).getCoeffParents()[0]); iterSerial[j] = Double.toString(svb.getAverageNumOfIterations()); } vmp.setOutput(false); svb.setParallelMode(false); svb.setFading(0.9); for (int j = 0; j < windowsSizes.length; j++) { //System.out.println("Window: "+windowsSizes[j]); svb.setWindowsSize(windowsSizes[j]); svb.initLearning(); svb.runLearning(); BayesianNetwork svbSerial = svb.getLearntBayesianNetwork(); //svb.getPlateuVMP().getEFParameterPosterior() meanBParallelSeqQ[j] = Double.toString(((Normal) ((BaseDistribution_MultinomialParents)svbSerial. getConditionalDistribution(varB)).getBaseDistribution(0)).getMean()); beta0ParallelSeqQ[j] = Double.toString(((ConditionalLinearGaussian)svbSerial. getConditionalDistribution(varA)).getIntercept()); beta1ParallelSeqQ[j] = Double.toString(((ConditionalLinearGaussian)svbSerial. getConditionalDistribution(varA)).getCoeffParents()[0]); iterParallelSeqQ[j] = Double.toString(svb.getAverageNumOfIterations()); } svb.setParallelMode(false); svb.setFading(0.2); for (int j = 0; j < windowsSizes.length; j++) { //System.out.println("Window: "+windowsSizes[j]); svb.setWindowsSize(windowsSizes[j]); svb.initLearning(); svb.runLearning(); BayesianNetwork svbSerial = svb.getLearntBayesianNetwork(); meanBParallelRandQ[j] = Double.toString(((Normal) ((BaseDistribution_MultinomialParents)svbSerial. getConditionalDistribution(varB)).getBaseDistribution(0)).getMean()); beta0ParallelRandQ[j] = Double.toString(((ConditionalLinearGaussian)svbSerial. getConditionalDistribution(varA)).getIntercept()); beta1ParallelRandQ[j] = Double.toString(((ConditionalLinearGaussian)svbSerial. getConditionalDistribution(varA)).getCoeffParents()[0]); iterParallelRandQ[j] = Double.toString(svb.getAverageNumOfIterations()); } System.out.println("Mean of B"); System.out.println("WindowSize \t ML \t Fading_1 \t Fading_2 \t Fading_3"); for (int j = 0; j < windowsSizes.length; j++) { System.out.println(windowsSizes[j]+ "\t" + meanfromML + "\t" + meanBSerial[j] + "\t" + meanBParallelSeqQ[j]+ "\t" + meanBParallelRandQ[j]); } System.out.println("Beta0 of A"); System.out.println("WindowSize\t ML \t Fading_1 \t Fading_2 \t Fading_3"); for (int j = 0; j < windowsSizes.length; j++) { System.out.println(windowsSizes[j]+ "\t" + beta0fromML + "\t" + beta0Serial[j] + "\t" + beta0ParallelSeqQ[j]+ "\t" + beta0ParallelRandQ[j]); } System.out.println("Beta1 of A"); System.out.println("WindowSize\t ML \t Fading_1 \t Fading_2 \t Fading_3"); for (int j = 0; j < windowsSizes.length; j++) { System.out.println(windowsSizes[j]+ "\t" + beta1fromML + "\t" + beta1Serial[j] + "\t" + beta1ParallelSeqQ[j] + "\t" + beta1ParallelRandQ[j]); } System.out.println("WindowSize \t Fading_1 \t Fading_2 \t Fading_3"); for (int j = 0; j < windowsSizes.length; j++) { System.out.println(windowsSizes[j]+ "\t" + iterSerial[j] + "\t" + iterParallelSeqQ[j] + "\t" + iterParallelRandQ[j]); } //svb.runLearningOnParallelForDifferentBatchWindows(windowsSizes, beta0fromML, beta1fromML, sampleMeanB); } } public static void testCompareBatchSizesFadingML() throws IOException, ClassNotFoundException { BayesianNetwork normalVarBN = BayesianNetworkLoader.loadFromFile("networks/Normal_1NormalParents.bn"); for (int i = 0; i < 1; i++) { System.out.println("\nNormal|Normal variable network \n "); normalVarBN.randomInitialization(new Random(i)); Variable varA = normalVarBN.getStaticVariables().getVariableByName("A"); Variable varB = normalVarBN.getStaticVariables().getVariableByName("B"); BayesianNetworkSampler sampler = new BayesianNetworkSampler(normalVarBN); sampler.setSeed(0); //sampler.setMARVar(varB,0.5); DataStream<DataInstance> data = sampler.sampleToDataBase(10000); ARFFDataWriter.writeToARFFFile(data, "./data/tmp.arff"); data = DataStreamLoader.loadFromFile("./data/tmp.arff"); int[] windowsSizes = {1, 2, 10, 100, 1000}; double[] fadingFactor = {1.0, 0.9999, 0.999, 0.99, 0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2}; //[mean, beta0, beta1][windowSizes.length] String[][] outputPerWindowSize = new String[3][windowsSizes.length]; for (int j = 0; j < windowsSizes.length; j++) { outputPerWindowSize[0][j]=windowsSizes[j]+ "\t"; outputPerWindowSize[1][j]=windowsSizes[j]+ "\t"; outputPerWindowSize[2][j]=windowsSizes[j]+ "\t"; for (int f = 0; f < fadingFactor.length; f++) { BayesianNetwork MLlearntBN = MaximumLikelihoodForBN. learnParametersStaticModelFading(normalVarBN.getDAG(), data, fadingFactor[f], windowsSizes[j]); outputPerWindowSize[0][j] += Double.toString(((Normal) ((BaseDistribution_MultinomialParents) MLlearntBN. getConditionalDistribution(varB)).getBaseDistribution(0)).getMean()) + "\t"; outputPerWindowSize[1][j] += Double.toString(((ConditionalLinearGaussian) MLlearntBN. getConditionalDistribution(varA)).getIntercept()) + "\t"; outputPerWindowSize[2][j] += Double.toString(((ConditionalLinearGaussian) MLlearntBN. getConditionalDistribution(varA)).getCoeffParents()[0]) + "\t"; } } String fadingOutput = ""; for (int j = 0; j < fadingFactor.length; j++) { fadingOutput+=fadingFactor[j]+"\t"; } System.out.println("Mean of B"); System.out.println("WindowSize \t"+fadingOutput); for (int j = 0; j < windowsSizes.length; j++) { System.out.println(outputPerWindowSize[0][j]); } System.out.println("Beta0 of A"); System.out.println("WindowSize \t"+fadingOutput); for (int j = 0; j < windowsSizes.length; j++) { System.out.println(outputPerWindowSize[1][j]); } System.out.println("Beta1 of A"); System.out.println("WindowSize \t"+fadingOutput); for (int j = 0; j < windowsSizes.length; j++) { System.out.println(outputPerWindowSize[2][j]); } } } public static void testLogProbOfEvidenceForDiffBatches_WasteIncinerator() throws IOException, ClassNotFoundException { BayesianNetwork normalVarBN = BayesianNetworkLoader.loadFromFile("networks/WasteIncinerator.bn"); //normalVarBN.randomInitialization(new Random(0)); System.out.println("\nWaste Incinerator - \n "); for (int j = 0; j < 1; j++) { BayesianNetworkSampler sampler = new BayesianNetworkSampler(normalVarBN); //sampler.setHiddenVar(null); sampler.setSeed(j); DataStream<DataInstance> data = sampler.sampleToDataBase(10000); StreamingVariationalBayesVMP svb = new StreamingVariationalBayesVMP(); svb.setSeed(j); VMP vmp = svb.getPlateuVMP().getVMP(); vmp.setTestELBO(true); vmp.setMaxIter(1000); vmp.setThreshold(0.0001); BayesianLearningEngineForBN.setBayesianLearningAlgorithmForBN(svb); BayesianLearningEngineForBN.setDAG(normalVarBN.getDAG()); BayesianLearningEngineForBN.setDataStream(data); String fadingOutput = "\t"; String header = "Window Size"; int[] windowsSizes = {1, 2, 50, 100, 1000, 5000, 10000}; double[] fadingFactor = {1.0, 0.9999, 0.999, 0.99, 0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2}; for (int i = 0; i < fadingFactor.length; i++) { header += " \t logProg(D) \t Time \t nIter"; fadingOutput+=fadingFactor[i]+"\t\t\t"; } System.out.println(fadingOutput+"\n"+header); for (int i = 0; i < windowsSizes.length; i++) { System.out.println("window: "+windowsSizes[i]); svb.setWindowsSize(windowsSizes[i]); String output = windowsSizes[i] + "\t"; for (int f = 0; f < fadingFactor.length; f++) { System.out.println(" fading: "+fadingFactor[f]); svb.initLearning(); svb.setFading(fadingFactor[f]); Stopwatch watch = Stopwatch.createStarted(); double logProbOfEv_Batch1 = data.streamOfBatches(windowsSizes[i]).sequential().mapToDouble(svb::updateModel).sum(); output+= logProbOfEv_Batch1 + "\t" + watch.stop() + "\t" + svb.getAverageNumOfIterations()+"\t"; } System.out.println(output); } } } public static void testLogProbOfEvidenceForDiffBatches_WasteIncineratorWithLatentVars() throws IOException, ClassNotFoundException { BayesianNetwork normalVarBN = BayesianNetworkLoader.loadFromFile("networks/WasteIncinerator.bn"); //normalVarBN.randomInitialization(new Random(0)); System.out.println("\nWaste Incinerator + latent vars - \n "); BayesianNetworkSampler sampler = new BayesianNetworkSampler(normalVarBN); sampler.setHiddenVar(normalVarBN.getStaticVariables().getVariableByName("Mout")); sampler.setHiddenVar(normalVarBN.getStaticVariables().getVariableByName("D")); sampler.setSeed(0); DataStream<DataInstance> data = sampler.sampleToDataBase(10000); StreamingVariationalBayesVMP svb = new StreamingVariationalBayesVMP(); svb.setSeed(0); VMP vmp = svb.getPlateuVMP().getVMP(); vmp.setTestELBO(true); vmp.setMaxIter(1000); vmp.setThreshold(0.0001); BayesianLearningEngineForBN.setBayesianLearningAlgorithmForBN(svb); BayesianLearningEngineForBN.setDAG(normalVarBN.getDAG()); BayesianLearningEngineForBN.setDataStream(data); System.out.println("Window Size \t logProg(D) \t Time"); int[] windowsSizes = {1, 50, 100, 1000, 5000, 10000}; for (int i = 0; i < windowsSizes.length; i++) { svb.setWindowsSize(windowsSizes[i]); svb.initLearning(); Stopwatch watch = Stopwatch.createStarted(); double logProbOfEv_Batch1 = data.streamOfBatches(windowsSizes[i]).sequential().mapToDouble(svb::updateModel).sum(); System.out.println(windowsSizes[i] + "\t" + logProbOfEv_Batch1 + "\t" + watch.stop()); } } public static void testLogProbOfEvidenceForDiffBatches_Normal1Normal() throws IOException, ClassNotFoundException { BayesianNetwork normalVarBN = BayesianNetworkLoader.loadFromFile("networks/Normal_1NormalParents.bn"); normalVarBN.randomInitialization(new Random(0)); System.out.println("\nNormal_1NormalParent - \n "); BayesianNetworkSampler sampler = new BayesianNetworkSampler(normalVarBN); sampler.setSeed(0); DataStream<DataInstance> data = sampler.sampleToDataBase(10000); StreamingVariationalBayesVMP svb = new StreamingVariationalBayesVMP(); svb.setSeed(0); VMP vmp = svb.getPlateuVMP().getVMP(); vmp.setTestELBO(true); vmp.setMaxIter(1000); vmp.setThreshold(0.0001); BayesianLearningEngineForBN.setBayesianLearningAlgorithmForBN(svb); BayesianLearningEngineForBN.setDAG(normalVarBN.getDAG()); BayesianLearningEngineForBN.setDataStream(data); System.out.println("Window Size \t logProg(D) \t Time"); int[] windowsSizes = {1, 50, 100, 1000, 5000, 10000}; for (int i = 0; i < windowsSizes.length; i++) { svb.setWindowsSize(windowsSizes[i]); svb.initLearning(); Stopwatch watch = Stopwatch.createStarted(); double logProbOfEv_Batch1 = data.streamOfBatches(windowsSizes[i]).sequential().mapToDouble(svb::updateModel).sum(); System.out.println(windowsSizes[i] + "\t" + logProbOfEv_Batch1 + "\t" + watch.stop()); } } public static void testLogProbOfEvidenceForDiffBatches_Normal1Normal_LatentVariable() throws IOException, ClassNotFoundException { BayesianNetwork normalVarBN = BayesianNetworkLoader.loadFromFile("networks/Normal_1NormalParents.bn"); normalVarBN.randomInitialization(new Random(0)); System.out.println("\nNormal_1NormalParent - \n "); BayesianNetworkSampler sampler = new BayesianNetworkSampler(normalVarBN); sampler.setHiddenVar(normalVarBN.getStaticVariables().getVariableByName("A")); sampler.setSeed(0); DataStream<DataInstance> data = sampler.sampleToDataBase(10000); StreamingVariationalBayesVMP svb = new StreamingVariationalBayesVMP(); svb.setSeed(0); VMP vmp = svb.getPlateuVMP().getVMP(); vmp.setTestELBO(true); vmp.setMaxIter(1000); vmp.setThreshold(0.0001); BayesianLearningEngineForBN.setBayesianLearningAlgorithmForBN(svb); BayesianLearningEngineForBN.setDAG(normalVarBN.getDAG()); BayesianLearningEngineForBN.setDataStream(data); System.out.println("Window Size \t logProg(D) \t Time"); int[] windowsSizes = {1, 50, 100, 1000, 5000, 10000}; for (int i = 0; i < windowsSizes.length; i++) { svb.setWindowsSize(windowsSizes[i]); svb.initLearning(); Stopwatch watch = Stopwatch.createStarted(); double logProbOfEv_Batch1 = data.streamOfBatches(windowsSizes[i]).sequential().mapToDouble(svb::updateModel).sum(); System.out.println(windowsSizes[i] + "\t" + logProbOfEv_Batch1 + "\t" + watch.stop()); } } public static void testLogProbOfEvidenceForDiffBatches_Asia() throws IOException, ClassNotFoundException { BayesianNetwork normalVarBN = BayesianNetworkLoader.loadFromFile("networks/asia.bn"); System.out.println("\nAsia - \n "); normalVarBN.randomInitialization(new Random(0)); BayesianNetworkSampler sampler = new BayesianNetworkSampler(normalVarBN); sampler.setSeed(0); DataStream<DataInstance> data = sampler.sampleToDataBase(10000); StreamingVariationalBayesVMP svb = new StreamingVariationalBayesVMP(); svb.setSeed(0); VMP vmp = svb.getPlateuVMP().getVMP(); vmp.setTestELBO(true); vmp.setMaxIter(1000); vmp.setThreshold(0.0001); BayesianLearningEngineForBN.setBayesianLearningAlgorithmForBN(svb); BayesianLearningEngineForBN.setDAG(normalVarBN.getDAG()); BayesianLearningEngineForBN.setDataStream(data); System.out.println("Window Size \t logProg(D) \t Time"); int[] windowsSizes = {1, 50, 100, 1000, 5000, 10000}; for (int i = 0; i < windowsSizes.length; i++) { svb.setWindowsSize(windowsSizes[i]); svb.initLearning(); Stopwatch watch = Stopwatch.createStarted(); double logProbOfEv_Batch1 = data.streamOfBatches(windowsSizes[i]).sequential().mapToDouble(svb::updateModel).sum(); System.out.println(windowsSizes[i] + "\t" + logProbOfEv_Batch1 + "\t" + watch.stop()); } } public static void testLogProbOfEvidenceForDiffBatches_AsiaLatentVars() throws IOException, ClassNotFoundException { BayesianNetwork normalVarBN = BayesianNetworkLoader.loadFromFile("networks/asia.bn"); System.out.println("\nAsia - \n "); normalVarBN.randomInitialization(new Random(0)); BayesianNetworkSampler sampler = new BayesianNetworkSampler(normalVarBN); //sampler.setHiddenVar(normalVarBN.getStaticVariables().getVariableByName("D")); sampler.setHiddenVar(normalVarBN.getStaticVariables().getVariableByName("E")); sampler.setSeed(0); DataStream<DataInstance> data = sampler.sampleToDataBase(10000); StreamingVariationalBayesVMP svb = new StreamingVariationalBayesVMP(); svb.setSeed(0); VMP vmp = svb.getPlateuVMP().getVMP(); vmp.setTestELBO(true); vmp.setMaxIter(1000); vmp.setThreshold(0.0001); BayesianLearningEngineForBN.setBayesianLearningAlgorithmForBN(svb); BayesianLearningEngineForBN.setDAG(normalVarBN.getDAG()); BayesianLearningEngineForBN.setDataStream(data); System.out.println("Window Size \t logProg(D) \t Time"); int[] windowsSizes = {1, 50, 100, 1000, 5000, 10000}; for (int i = 0; i < windowsSizes.length; i++) { svb.setWindowsSize(windowsSizes[i]); svb.initLearning(); Stopwatch watch = Stopwatch.createStarted(); double logProbOfEv_Batch1 = data.streamOfBatches(windowsSizes[i]).sequential().mapToDouble(svb::updateModel).sum(); System.out.println(windowsSizes[i] + "\t" + logProbOfEv_Batch1 + "\t" + watch.stop()); } } }
package guitests.guihandles; import static org.junit.Assert.assertTrue; import java.util.List; import java.util.Optional; import java.util.Set; import guitests.GuiRobot; import javafx.geometry.Point2D; import javafx.scene.Node; import javafx.scene.control.ListView; import javafx.stage.Stage; import seedu.geekeep.TestApp; import seedu.geekeep.model.task.ReadOnlyTask; import seedu.geekeep.model.task.Task; import seedu.geekeep.testutil.TestUtil; /** * Provides a handle for the panel containing the task list. */ public class TaskListPanelHandle extends GuiHandle { public static final int NOT_FOUND = -1; public static final String CARD_PANE_ID = "#cardPane"; private static final String PERSON_LIST_VIEW_ID = "#allListView"; public TaskListPanelHandle(GuiRobot guiRobot, Stage primaryStage) { super(guiRobot, primaryStage, TestApp.APP_TITLE); } /** * Clicks on the ListView. */ public void clickOnListView() { Point2D point = TestUtil.getScreenMidPoint(getListView()); guiRobot.clickOn(point.getX(), point.getY()); } /** * Returns true if the {@code persons} appear as the sub list (in that order) at position {@code startPosition}. */ public boolean containsInOrder(int startPosition, ReadOnlyTask... persons) { List<ReadOnlyTask> personsInList = getListView().getItems(); // Return false if the list in panel is too short to contain the given list if (startPosition + persons.length > personsInList.size()) { return false; } // Return false if any of the persons doesn't match for (int i = 0; i < persons.length; i++) { if (!personsInList.get(startPosition + i).getTitle().fullTitle.equals(persons[i].getTitle().fullTitle)) { return false; } } return true; } protected Set<Node> getAllCardNodes() { return guiRobot.lookup(CARD_PANE_ID).queryAll(); } public ListView<ReadOnlyTask> getListView() { return getNode(PERSON_LIST_VIEW_ID); } public int getNumberOfPeople() { return getListView().getItems().size(); } /** * Gets a person from the list by index */ public ReadOnlyTask getPerson(int index) { return getListView().getItems().get(index); } public PersonCardHandle getPersonCardHandle(int index) { return getPersonCardHandle(new Task(getListView().getItems().get(index))); } public PersonCardHandle getPersonCardHandle(ReadOnlyTask person) { Set<Node> nodes = getAllCardNodes(); Optional<Node> personCardNode = nodes.stream() .filter(n -> new PersonCardHandle(guiRobot, primaryStage, n).isSamePerson(person)) .findFirst(); if (personCardNode.isPresent()) { return new PersonCardHandle(guiRobot, primaryStage, personCardNode.get()); } else { return null; } } /** * Returns the position of the person given, {@code NOT_FOUND} if not found in the list. */ public int getPersonIndex(ReadOnlyTask targetPerson) { List<ReadOnlyTask> personsInList = getListView().getItems(); for (int i = 0; i < personsInList.size(); i++) { if (personsInList.get(i).getTitle().equals(targetPerson.getTitle())) { return i; } } return NOT_FOUND; } public List<ReadOnlyTask> getSelectedPersons() { ListView<ReadOnlyTask> personList = getListView(); return personList.getSelectionModel().getSelectedItems(); } /** * Returns true if the list is showing the person details correctly and in correct order. * @param startPosition The starting position of the sub list. * @param persons A list of person in the correct order. */ public boolean isListMatching(int startPosition, ReadOnlyTask... persons) throws IllegalArgumentException { if (persons.length + startPosition != getListView().getItems().size()) { throw new IllegalArgumentException("List size mismatched\n" + "Expected " + (getListView().getItems().size() - 1) + " persons"); } assertTrue(this.containsInOrder(startPosition, persons)); for (int i = 0; i < persons.length; i++) { final int scrollTo = i + startPosition; guiRobot.interact(() -> getListView().scrollTo(scrollTo)); guiRobot.sleep(200); if (!TestUtil.compareCardAndPerson(getPersonCardHandle(startPosition + i), persons[i])) { return false; } } return true; } /** * Returns true if the list is showing the person details correctly and in correct order. * @param persons A list of person in the correct order. */ public boolean isListMatching(ReadOnlyTask... persons) { return this.isListMatching(0, persons); } /** * Navigates the listview to display and select the person. */ public PersonCardHandle navigateToPerson(ReadOnlyTask person) { int index = getPersonIndex(person); guiRobot.interact(() -> { getListView().scrollTo(index); guiRobot.sleep(150); getListView().getSelectionModel().select(index); }); guiRobot.sleep(100); return getPersonCardHandle(person); } public PersonCardHandle navigateToPerson(String name) { guiRobot.sleep(500); //Allow a bit of time for the list to be updated final Optional<ReadOnlyTask> person = getListView().getItems().stream() .filter(p -> p.getTitle().fullTitle.equals(name)) .findAny(); if (!person.isPresent()) { throw new IllegalStateException("Name not found: " + name); } return navigateToPerson(person.get()); } }
package imcode.server.user; import com.imcode.imcms.domain.exception.DocumentNotExistException; import com.imcode.imcms.model.Roles; import com.imcode.imcms.persistence.entity.Meta; import org.junit.Before; import org.junit.Test; import java.util.HashMap; import java.util.HashSet; import java.util.Set; import static org.junit.Assert.*; public class UserDomainObjectTest { private UserDomainObject user; private Meta meta; @Before public void setUp() { meta = new Meta(); meta.setId(0); final HashMap<Integer, Meta.Permission> roleRights = new HashMap<>(); roleRights.put(Roles.USER.getId(), Meta.Permission.NONE); roleRights.put(Roles.USER_ADMIN.getId(), Meta.Permission.EDIT); roleRights.put(Roles.SUPER_ADMIN.getId(), Meta.Permission.EDIT); meta.setRoleIdToPermission(roleRights); user = new UserDomainObject(); } @Test public void testUserAlwaysHasUsersRole() { assertTrue(user.hasRoleId(Roles.USER.getId())); assertTrue(user.getRoleIds().contains(Roles.USER.getId())); user.removeRoleId(Roles.USER.getId()); assertTrue(user.hasRoleId(Roles.USER.getId())); assertTrue(user.getRoleIds().contains(Roles.USER.getId())); final Set<Integer> roleIds = new HashSet<>(1); roleIds.add(0); user.setRoleIds(roleIds); assertTrue(user.hasRoleId(Roles.USER.getId())); assertTrue(user.getRoleIds().contains(Roles.USER.getId())); } @Test public void hasUserAccessToDoc_When_MetaLinkedForUnauthorizedUsersAndUserNotHasRights_Expect_True() { meta.setLinkedForUnauthorizedUsers(true); assertTrue(user.hasUserAccessToDoc(meta)); } @Test public void hasUserAccessToDoc_When_MetaNotLinkedForUnauthorizedUsersAndUserHasRights_Expect_True() { meta.setLinkedForUnauthorizedUsers(false); user.addRoleId(Roles.USER.getId()); user.addRoleId(Roles.USER_ADMIN.getId()); assertTrue(user.hasUserAccessToDoc(meta)); } @Test public void hasUserAccessToDoc_When_MetaNotLinkedForUnauthorizedUsersAndUserNotHasRights_Expect_False() { meta.setLinkedForUnauthorizedUsers(false); assertFalse(user.hasUserAccessToDoc(meta)); } @Test(expected = DocumentNotExistException.class) public void hasUserAccessToDoc_When_DocIsNull_Expect_DocumentNotExistException() { assertTrue(user.hasUserAccessToDoc(null)); } }
package net.davidlauzon.logshaper; import net.davidlauzon.logshaper.event.Event; import org.junit.*; import static com.jcabi.matchers.RegexMatchers.*; import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.*; public class LogShaperTest { static private SubstriberMock subscriber; @BeforeClass static public void setUp() throws Exception { subscriber = new SubstriberMock(); LogShaper.getDefaultJournal().subscribe( subscriber ); } @AfterClass static public void tearDown() throws Exception { subscriber = null; } @Test public void testBroadcastLevel() { // ERROR > WARN > INFO > DEBUG > TRACE LogShaper.createRootEvent("TestBroadcast").publishError(); assertThat(subscriber.getLastMessage(), startsWith("ERROR")); LogShaper.createRootEvent("TestBroadcast").publishWarn(); assertThat( subscriber.getLastMessage(), startsWith("WARN") ); LogShaper.createRootEvent("TestBroadcast").publishInfo(); assertThat( subscriber.getLastMessage(), startsWith("INFO") ); LogShaper.createRootEvent("TestBroadcast").publishDebug(); assertThat( subscriber.getLastMessage(), startsWith("DEBUG") ); LogShaper.createRootEvent("TestBroadcast").publishTrace(); assertThat( subscriber.getLastMessage(), startsWith("TRACE") ); } @Test public void testStopDuration() { Event event; event = LogShaper.createRootEvent("TestStopDuration").publishInfo(); assertThat( subscriber.getLastMessage(), containsString("started") ); event.stop().publishInfo(); assertThat( subscriber.getLastMessage(), containsPattern("ended in [0-9.]+s") ); } @Test public void testEventAttributes() { Event event; event = LogShaper.createRootEvent("TestEventAttribute") .attr("KEY1", "val1").attr("KEY2", "val2") .publishInfo(); assertThat( subscriber.getLastMessage(), allOf( containsString("KEY1=\"val1\""), containsString("KEY2=\"val2\"") )); event.stop() .attr("KEY3", "stopped") .publishInfo(); assertThat( subscriber.getLastMessage(), allOf( containsString("KEY1=\"val1\""), containsString("KEY2=\"val2\""), containsString("KEY3=\"stopped\"") )); } @Test public void testEventHierarchy() throws InterruptedException { Event eventParent; Event eventChild1; Event eventChild2; Event eventChild2Child1; Event eventChild2Child2; Event eventChild2Child3; eventParent = LogShaper.createRootEvent("Request").attr("ACTION", "Person.Update").publishInfo(); eventChild1 = eventParent.createChild("JSON Parsing").count("JSON.BYTES", 4000).publishInfo(); Thread.sleep(1); // Expensive computation / external system eventChild1.stop().publishInfo(); eventChild2 = eventParent.createChild("Resource processing").publishInfo(); eventChild2Child1 = eventChild2.createChild("SQL").attr("QUERY", "SELECT FROM ...").publishInfo(); Thread.sleep(1); // Expensive computation / external system eventChild2Child1.stop().publishInfo(); eventChild2Child2 = eventChild2.createChild("BIRT").publishInfo(); Thread.sleep(1); // Expensive computation / external system eventChild2Child2.stop().publishInfo(); eventChild2.stop().publishInfo(); eventChild2Child3 = eventChild2.createChild("SQL").attr("QUERY", "UPDATE ...").publishInfo(); Thread.sleep(1); // Expensive computation / external system eventChild2Child3.stop().publishInfo(); eventParent.stop().publishInfo(); } @Test public void testPonctualEvent() { Event event; event = LogShaper.createRootEvent("TestPonctualEvent") .ponctualEvent() .attr("KEY1", "val1").attr("KEY2", "val2") .publishInfo(); assertThat( subscriber.getLastMessage(), allOf( containsString("KEY1=\"val1\""), containsString("KEY2=\"val2\""), containsString("occured") )); event = LogShaper.createRootEvent("TestPonctualEventParent").attr("KEY1", "val1").publishInfo(); event.createChild("TestPonctualEventChild").ponctualEvent().publishInfo(); assertThat(subscriber.getLastMessage(), containsString("occured") ); event.stop().publishInfo(); } @Test public void testThrowableEvent() { Event event; event = LogShaper.createRootEvent("TestThrowableEvent") .attr("KEY1", "val1").attr("KEY2", "val2") .publishInfo(); event.createChild("TestThrowableEventException", new Throwable("Something got wrong")).publishInfo(); event.stop().publishInfo(); } }
package nom.bdezonia.zorbage.algorithm; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import org.junit.Test; import nom.bdezonia.zorbage.algebras.G; import nom.bdezonia.zorbage.procedure.Procedure2; import nom.bdezonia.zorbage.type.data.float64.real.Float64Member; import nom.bdezonia.zorbage.type.data.int32.SignedInt32Member; import nom.bdezonia.zorbage.type.storage.Storage; import nom.bdezonia.zorbage.type.storage.array.ArrayStorage; import nom.bdezonia.zorbage.type.storage.datasource.IndexedDataSource; /** * * @author Barry DeZonia * */ public class TestSort { @Test public void test1() { IndexedDataSource<SignedInt32Member> storage = ArrayStorage.allocateInts( new int[] {6,3,99,-1,66,-50,0,0,3}); SignedInt32Member value = G.INT32.construct(); Sort.compute(G.INT32, storage); storage.get(0, value); assertEquals(-50, value.v()); storage.get(1, value); assertEquals(-1, value.v()); storage.get(2, value); assertEquals(0, value.v()); storage.get(3, value); assertEquals(0, value.v()); storage.get(4, value); assertEquals(3, value.v()); storage.get(5, value); assertEquals(3, value.v()); storage.get(6, value); assertEquals(6, value.v()); storage.get(7, value); assertEquals(66, value.v()); storage.get(8, value); assertEquals(99, value.v()); Sort.compute(G.INT32, storage); storage.get(0, value); assertEquals(-50, value.v()); storage.get(1, value); assertEquals(-1, value.v()); storage.get(2, value); assertEquals(0, value.v()); storage.get(3, value); assertEquals(0, value.v()); storage.get(4, value); assertEquals(3, value.v()); storage.get(5, value); assertEquals(3, value.v()); storage.get(6, value); assertEquals(6, value.v()); storage.get(7, value); assertEquals(66, value.v()); storage.get(8, value); assertEquals(99, value.v()); Sort.compute(G.INT32, G.INT32.isGreater(), storage); storage.get(8, value); assertEquals(-50, value.v()); storage.get(7, value); assertEquals(-1, value.v()); storage.get(6, value); assertEquals(0, value.v()); storage.get(5, value); assertEquals(0, value.v()); storage.get(4, value); assertEquals(3, value.v()); storage.get(3, value); assertEquals(3, value.v()); storage.get(2, value); assertEquals(6, value.v()); storage.get(1, value); assertEquals(66, value.v()); storage.get(0, value); assertEquals(99, value.v()); } @Test public void test2() { for (int i = 0; i < 25; i++) { Float64Member value = G.DBL.construct(); IndexedDataSource<Float64Member> nums = Storage.allocate(1000+i, value); Fill.compute(G.DBL, G.DBL.random(), nums); Procedure2<Float64Member, Float64Member> proc = new Procedure2<Float64Member, Float64Member>() { @Override public void call(Float64Member a, Float64Member b) { b.setV(a.v() - 0.5); } }; InplaceTransform2.compute(G.DBL, proc, nums); Sort.compute(G.DBL, nums); assertTrue(IsSorted.compute(G.DBL, nums)); Sort.compute(G.DBL, G.DBL.isGreater(), nums); assertTrue(IsSorted.compute(G.DBL, G.DBL.isGreater(), nums)); } } }
package org.cactoos.collection; import org.cactoos.iterable.IterableOf; import org.cactoos.list.ListOf; import org.hamcrest.MatcherAssert; import org.hamcrest.core.IsEqual; import org.junit.Test; /** * Test Case for {@link CollectionOf}. * * @since 0.23 * @checkstyle JavadocMethodCheck (500 lines) */ public final class CollectionOfTest { @Test public void behavesAsCollection() throws Exception { MatcherAssert.assertThat( "Can't behave as a collection", new CollectionOf<>(1, 2, 0, -1), new BehavesAsCollection<>(-1) ); } @Test public void buildsCollectionFromIterable() throws Exception { MatcherAssert.assertThat( "Can't build a collection from iterator", new CollectionOf<>(new ListOf<>(new IterableOf<>(1, 2, 0, -1))), new BehavesAsCollection<>(-1) ); } @Test public void testToString() throws Exception { MatcherAssert.assertThat( "Wrong toString output. Expected \"[1, 2, 0, -1]\".", new CollectionOf<>(new ListOf<>(1, 2, 0, -1)).toString(), new IsEqual<>("[1, 2, 0, -1]") ); } @Test public void testToStringEmpty() throws Exception { MatcherAssert.assertThat( "Wrong toString output. Expected \"[]\".", new CollectionOf<>(new ListOf<>()).toString(), new IsEqual<>("[]") ); } }
package sotechat.controller; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.http.MediaType; import org.springframework.messaging.Message; import org.springframework.messaging.MessageChannel; import org.springframework.messaging.simp.SimpMessagingTemplate; import org.springframework.mock.web.MockServletContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import sotechat.data.Mapper; import sotechat.data.MapperImpl; import sotechat.data.SessionRepo; import sotechat.data.SessionRepoImpl; import sotechat.data.*; import sotechat.data.QueueImpl; import sotechat.domain.Conversation; import sotechat.domainService.ConversationService; import sotechat.domainService.MessageService; import sotechat.domainService.PersonService; import sotechat.repo.ConversationRepo; import sotechat.repo.MessageRepo; import sotechat.repo.PersonRepo; import sotechat.service.DatabaseService; import sotechat.util.MockPrincipal; import sotechat.service.QueueService; import sotechat.service.StateService; import static org.hamcrest.Matchers.*; import static org.junit.Assert.assertEquals; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result .MockMvcResultMatchers.*; /** * StateControllerTest. */ @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = MockServletContext.class) @WebAppConfiguration public class StateControllerTest { private MockMvc mvc; /** * Before. * @throws Exception */ @Before public void setUp() throws Exception { ChatLogger chatLogger = new ChatLogger(); Mapper mapper = new MapperImpl(); SubscribeEventListener listener = new SubscribeEventListener(); QueueService qService = new QueueService(new QueueImpl()); SessionRepo sessions = new SessionRepoImpl(mapper); ConversationRepo mockConversationRepo = mock(ConversationRepo.class); MessageRepo mockMessageRepo = mock(MessageRepo.class); when(mockConversationRepo.findOne(any(String.class))) .thenReturn(new Conversation()); PersonRepo mockPersonRepo = mock(PersonRepo.class); ConversationService conversationService = new ConversationService( mockConversationRepo, mockPersonRepo); PersonService personService = new PersonService(mockPersonRepo); MessageService messageService = new MessageService(mockMessageRepo); SimpMessagingTemplate broker = new SimpMessagingTemplate( new MessageChannel() { @Override public boolean send(Message<?> message) { return true; } @Override public boolean send(Message<?> message, long l) { return true; } }); QueueBroadcaster broadcaster = new QueueBroadcaster(qService, broker); ChatLogBroadcaster logBroadcaster = new ChatLogBroadcaster( chatLogger, broker); DatabaseService databaseService = new DatabaseService(personService, conversationService, messageService); StateService state = new StateService( mapper, listener, qService, chatLogger, sessions, databaseService); mvc = MockMvcBuilders .standaloneSetup(new StateController( state, sessions, broadcaster, logBroadcaster, conversationService)) .build(); } /** Get pyynto polkuun "/userState" palauttaa statukseksen OK. * @throws Exception */ @Test public void testGetUserStateReturnsOK() throws Exception { mvc.perform(MockMvcRequestBuilders .get("/userState").accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()); } /** GET polkuun /userState palauttaa uskottavat arvot. * @throws Exception */ @Test public void testGetUserStateReturnsPlausibleValues() throws Exception { mvc.perform(MockMvcRequestBuilders .get("/userState").accept(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$.*", hasSize(5))) .andExpect(jsonPath("$.state", is("start"))) .andExpect(jsonPath("$.username", is("Anon"))) .andExpect(jsonPath("$.channelId").isNotEmpty()) .andExpect(jsonPath("$.userId").isNotEmpty()) .andExpect(jsonPath("$.category").isNotEmpty()); } @Test public void testGetProStateReturnsOK() throws Exception { mvc.perform(MockMvcRequestBuilders .get("/proState").accept(MediaType.APPLICATION_JSON) .principal(new MockPrincipal("hoitaja"))) .andExpect(status().isOk()); } @Test public void testGetProStateReturnsPlausibleValues() throws Exception { mvc.perform(MockMvcRequestBuilders .get("/proState") .accept(MediaType.APPLICATION_JSON) .principal(new MockPrincipal("hoitaja"))) .andExpect(jsonPath("$.*", hasSize(6))) .andExpect(jsonPath("$.state").isNotEmpty()) .andExpect(jsonPath("$.username").isNotEmpty()) .andExpect(jsonPath("$.userId").isNotEmpty()) .andExpect(jsonPath("$.online").isNotEmpty()) .andExpect(jsonPath("$.qbcc", is("QBCC"))) .andExpect(jsonPath("$.channelIds", is("[]"))); } @Test public void joiningChatPoolSucceedsWithNormalUserIfStateIsStart() throws Exception { String json = "{\"username\":\"Anon\",\"startMessage\":\"Hei!\"}"; System.out.println(mvc.perform(MockMvcRequestBuilders .get("/userState") .accept(MediaType.APPLICATION_JSON)) .andReturn() .getResponse() .getContentAsString()); mvc.perform(post("/joinPool") .contentType(MediaType.APPLICATION_JSON).content(json) .sessionAttr("channelId", "2") .sessionAttr("state", "start") .sessionAttr("userId", "4") .sessionAttr("category", "DRUGS")) .andExpect(status().isOk()) .andExpect(jsonPath("$.*", hasSize(1))) .andExpect(jsonPath("$.content", is("OK, please request new state now."))); } @Test public void joiningChatPoolFailsWithNormalUserIfStateIsNotStart() throws Exception { String json = "{\"username\":\"Anon\",\"startMessage\":\"Hei!\"}"; mvc.perform(post("/joinPool") .contentType(MediaType.APPLICATION_JSON).content(json) .sessionAttr("channelId", "2") .sessionAttr("state", "chat") .sessionAttr("userId", "4") .sessionAttr("category", "DRUGS")) .andExpect(status().isOk()) .andExpect(jsonPath("$.*", hasSize(1))) .andExpect(jsonPath("$.content", is("Denied join pool request due to bad state."))); } @Test public void joiningChatPoolFailsIfUserTriesToJoinWithProfessionalIdAndUsername() throws Exception { String json = "{\"username\":\"Hoitaja\",\"startMessage\":\"Hei!\"}"; mvc.perform(post("/joinPool") .contentType(MediaType.APPLICATION_JSON).content(json) .sessionAttr("channelId", "2") .sessionAttr("state", "start") .sessionAttr("userId", "666") .sessionAttr("category", "DRUGS")) .andExpect(status().isOk()) .andExpect(jsonPath("$.*", hasSize(1))) .andExpect(jsonPath("$.content", is("Denied join pool request due to reserved username."))); } }
package org.tuckey.web.testhelper; import org.tuckey.web.filters.urlrewrite.UrlRewriteFilterTest; import javax.servlet.RequestDispatcher; import javax.servlet.Servlet; import javax.servlet.ServletContext; import javax.servlet.ServletException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.util.Enumeration; import java.util.Set; public class MockServletContext implements ServletContext { public ServletContext getContext(String s) { return new MockServletContext(); } public int getMajorVersion() { return 0; } public int getMinorVersion() { return 0; } public String getMimeType(String s) { return null; } public Set getResourcePaths(String s) { return null; } public URL getResource(String s) throws MalformedURLException { return null; } public InputStream getResourceAsStream(String s) { return null; } public RequestDispatcher getRequestDispatcher(String s) { return null; } public RequestDispatcher getNamedDispatcher(String s) { return null; } public Servlet getServlet(String s) throws ServletException { return null; } public Enumeration getServlets() { return null; } public Enumeration getServletNames() { return null; } public void log(String s) { } public void log(Exception e, String s) { } public void log(String s, Throwable throwable) { } public String getRealPath(String s) { String basePath = UrlRewriteFilterTest.class.getResource("").getFile(); if (basePath.endsWith("/")) basePath = basePath.substring(0, basePath.length() - 1); return basePath + (s == null ? "" : s); } public String getServerInfo() { return null; } public String getInitParameter(String s) { return null; } public Enumeration getInitParameterNames() { return null; } public Object getAttribute(String s) { return null; } public Enumeration getAttributeNames() { return null; } public void setAttribute(String s, Object o) { } public void removeAttribute(String s) { } public String getServletContextName() { return null; } }
package us.kbase.narrativejobservice.db; import java.io.IOException; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.stream.Collectors; import org.bson.BSONObject; import org.bson.LazyBSONList; import org.jongo.Jongo; import org.jongo.MongoCollection; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import us.kbase.common.mongo.GetMongoDB; import us.kbase.common.mongo.exceptions.InvalidHostException; import us.kbase.common.mongo.exceptions.MongoAuthException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.Lists; import com.mongodb.BasicDBObject; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.DBCursor; import com.mongodb.DBObject; import com.mongodb.DuplicateKeyException; import com.mongodb.MongoClient; import com.mongodb.MongoClientOptions; import com.mongodb.MongoException; import com.mongodb.ServerAddress; public class ExecEngineMongoDb { private Jongo jongo; private DBCollection taskCol; private DBCollection logCol; private DBCollection propCol; private MongoCollection srvProps; private static final Map<String, MongoClient> HOSTS_TO_CLIENT = new HashMap<>(); private static final String COL_EXEC_TASKS = "exec_tasks"; private static final String PK_EXEC_TASKS = "ujs_job_id"; private static final String COL_EXEC_LOGS = "exec_logs"; private static final String PK_EXEC_LOGS = "ujs_job_id"; private static final String COL_SRV_PROPS = "srv_props"; private static final String PK_SRV_PROPS = "prop_id"; private static final String SRV_PROPS_VALUE = "value"; private static final String SRV_PROP_DB_VERSION = "db_version"; private static final String DB_VERSION = "1.0"; private static final ObjectMapper MAPPER = new ObjectMapper(); // should really inject the DB, but worry about that later. public ExecEngineMongoDb( final String hosts, final String db, final String user, final String pwd) throws Exception { final DB mongo = getDB(hosts, db, user, pwd, 0, 10); taskCol = mongo.getCollection(COL_EXEC_TASKS); logCol = mongo.getCollection(COL_EXEC_LOGS); propCol = mongo.getCollection(COL_SRV_PROPS); jongo = new Jongo(mongo); srvProps = jongo.getCollection(COL_SRV_PROPS); // Indexing final BasicDBObject unique = new BasicDBObject("unique", true); taskCol.createIndex(new BasicDBObject(PK_EXEC_TASKS, 1), unique); logCol.createIndex(new BasicDBObject(PK_EXEC_LOGS, 1), unique); propCol.createIndex(new BasicDBObject(PK_SRV_PROPS, 1), unique); try { // at some point check that the db ver = sw ver propCol.insert(new BasicDBObject(PK_SRV_PROPS, SRV_PROP_DB_VERSION) .append(SRV_PROPS_VALUE, DB_VERSION)); } catch (DuplicateKeyException e) { //version is already there so do nothing } } private Map<String, Object> toMap(final Object obj) { return MAPPER.convertValue(obj, new TypeReference<Map<String, Object>>() {}); } private DBObject toDBObj(final Object obj) { return new BasicDBObject(toMap(obj)); } private <T> T toObj(final DBObject dbo, final Class<T> clazz) { return dbo == null ? null : MAPPER.convertValue(toMapRec(dbo), clazz); } private Map<String, Object> toMapRec(final BSONObject dbo) { @SuppressWarnings("unchecked") final Map<String, Object> ret = (Map<String, Object>) cleanObject(dbo); return ret; } // this assumes there aren't BSONObjects embedded in standard object, which should // be the case for stuff returned from mongo // Unimplemented error for dbo.toMap() // dbo is read only // can't call convertValue() on dbo since it has a 'size' field outside of the internal map // and just weird shit happens when you do anyway private Object cleanObject(final Object dbo) { if (dbo instanceof LazyBSONList) { final List<Object> ret = new LinkedList<>(); // don't stream, sometimes has issues with nulls for (final Object obj: (LazyBSONList) dbo) { ret.add(cleanObject(obj)); } return ret; } else if (dbo instanceof BSONObject) { // can't stream because streams don't like null values at HashMap.merge() final BSONObject m = (BSONObject) dbo; final Map<String, Object> ret = new HashMap<>(); for (final String k: m.keySet()) { if (!k.equals("_id")) { final Object v = m.get(k); ret.put(k, cleanObject(v)); } } return ret; } return dbo; } public String[] getSubJobIds(String ujsJobId) throws Exception{ // there should be a null/empty check for the ujs id here final DBCursor dbc = taskCol.find( new BasicDBObject("parent_job_id", ujsJobId), new BasicDBObject("ujs_job_id", 1)); List<String> idList = new ArrayList<String>(); for (final DBObject dbo: dbc) { idList.add((String) dbo.get("ujs_job_id")); } return idList.toArray(new String[idList.size()]); } public ExecLog getExecLog(String ujsJobId) throws Exception { // there should be a null/empty check for the ujs id here // should make these strings constants final DBObject log = logCol.findOne( new BasicDBObject(PK_EXEC_LOGS, ujsJobId), new BasicDBObject(PK_EXEC_LOGS, 1) .append("original_line_count", 1) .append("stored_line_count", 1)); final ExecLog ret; if (log == null) { ret = null; } else { ret = new ExecLog(); ret.setOriginalLineCount((Integer) log.get("original_line_count")); ret.setStoredLineCount((Integer) log.get("stored_line_count")); ret.setUjsJobId((String) log.get(PK_EXEC_LOGS)); } return ret; } public void insertExecLog(ExecLog execLog) throws Exception { // should be a null check here insertExecLogs(Arrays.asList(execLog)); } public void insertExecLogs(List<ExecLog> execLogList) throws Exception { // should be a null collection contents check here logCol.insert(execLogList.stream().map(l -> toDBObj(l)).collect(Collectors.toList())); } public void updateExecLogLines(String ujsJobId, int newLineCount, List<ExecLogLine> newLines) throws Exception { // needs input checking logCol.update(new BasicDBObject(PK_EXEC_LOGS, ujsJobId), new BasicDBObject("$set", new BasicDBObject("original_line_count", newLineCount) .append("stored_line_count", newLineCount)) .append("$push", new BasicDBObject("lines", new BasicDBObject("$each", newLines.stream().map(l -> toDBObj(l)) .collect(Collectors.toList()))))); } public void updateExecLogOriginalLineCount(String ujsJobId, int newLineCount) throws Exception { //input checking logCol.update(new BasicDBObject(PK_EXEC_LOGS, ujsJobId), new BasicDBObject("$set", new BasicDBObject("original_line_count", newLineCount))); } public List<ExecLogLine> getExecLogLines(String ujsJobId, int from, int count) throws Exception { //input checking @SuppressWarnings("unchecked") final List<DBObject> lines = (List<DBObject>) logCol.findOne( new BasicDBObject(PK_EXEC_LOGS, ujsJobId), new BasicDBObject("lines", new BasicDBObject("$slice", Arrays.asList(from, count)))).get("lines"); return lines.stream().map(dbo -> { final ExecLogLine line = new ExecLogLine(); line.setIsError((Boolean) dbo.get("is_error")); line.setLine((String) dbo.get("line")); line.setLinePos((Integer) dbo.get("line_pos")); return line; }).collect(Collectors.toList()); } public void insertExecTask(ExecTask execTask) throws Exception { // needs input checking taskCol.insert(toDBObj(execTask)); } // note that result must be sanitized before storing in mongo. See {@link SanitizeMongoObject}. // the sanitization should really happen here. public void addExecTaskResult(final String ujsJobId, final Map<String, Object> result) { // input checking taskCol.update(new BasicDBObject(PK_EXEC_TASKS, ujsJobId), new BasicDBObject("$set", new BasicDBObject("job_output", result))); } // note that job inputs and outputs must be un-sanitized before use. // See {@link SanitizeMongoObject}. // the un-santization should really happen here. public ExecTask getExecTask(String ujsJobId) throws Exception { // input checking return toObj(taskCol.findOne(new BasicDBObject(PK_EXEC_TASKS, ujsJobId)), ExecTask.class); } public void updateExecTaskTime(String ujsJobId, boolean finishTime, long time) throws Exception { //inputs taskCol.update(new BasicDBObject(PK_EXEC_TASKS, ujsJobId), new BasicDBObject("$set", new BasicDBObject(finishTime ? "finish_time" : "exec_start_time", time))); } public String getServiceProperty(String propId) throws Exception { @SuppressWarnings("rawtypes") List<Map> ret = Lists.newArrayList(srvProps.find(String.format("{%s:#}", PK_SRV_PROPS), propId) .projection(String.format("{%s:1}", SRV_PROPS_VALUE)).as(Map.class)); if (ret.size() == 0) return null; return (String)ret.get(0).get(SRV_PROPS_VALUE); } public void setServiceProperty(String propId, String value) throws Exception { srvProps.update(String.format("{%s:#}", PK_SRV_PROPS), propId).upsert().with( String.format("{$set:{%s:#}}", SRV_PROPS_VALUE), value); } private synchronized static MongoClient getMongoClient(final String hosts) throws UnknownHostException, InvalidHostException { //Only make one instance of MongoClient per JVM per mongo docs final MongoClient client; if (!HOSTS_TO_CLIENT.containsKey(hosts)) { // Don't print to stderr java.util.logging.Logger.getLogger("com.mongodb") .setLevel(Level.OFF); @SuppressWarnings("deprecation") final MongoClientOptions opts = MongoClientOptions.builder() .autoConnectRetry(true).build(); try { List<ServerAddress> addr = new ArrayList<ServerAddress>(); for (String s: hosts.split(",")) addr.add(new ServerAddress(s)); client = new MongoClient(addr, opts); } catch (NumberFormatException nfe) { //throw a better exception if 10gen ever fixes this throw new InvalidHostException(hosts + " is not a valid mongodb host"); } HOSTS_TO_CLIENT.put(hosts, client); } else { client = HOSTS_TO_CLIENT.get(hosts); } return client; } @SuppressWarnings("deprecation") private static DB getDB(final String hosts, final String database, final String user, final String pwd, final int retryCount, final int logIntervalCount) throws UnknownHostException, InvalidHostException, IOException, MongoAuthException, InterruptedException { if (database == null || database.isEmpty()) { throw new IllegalArgumentException( "database may not be null or the empty string"); } final DB db = getMongoClient(hosts).getDB(database); if (user != null && pwd != null) { int retries = 0; while (true) { try { db.authenticate(user, pwd.toCharArray()); break; } catch (MongoException.Network men) { if (retries >= retryCount) { throw (IOException) men.getCause(); } if (retries % logIntervalCount == 0) { getLogger().info( "Retrying MongoDB connection {}/{}, attempt {}/{}", hosts, database, retries, retryCount); } Thread.sleep(1000); } retries++; } } try { db.getCollectionNames(); } catch (MongoException me) { throw new MongoAuthException("Not authorized for database " + database, me); } return db; } private static Logger getLogger() { return LoggerFactory.getLogger(GetMongoDB.class); } }
package us.kbase.narrativemethodstore.test; import static org.junit.Assert.*; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.lang.reflect.Field; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.TreeSet; import junit.framework.Assert; import org.apache.commons.io.FileUtils; import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.Logger; import org.ini4j.Ini; import org.ini4j.Profile.Section; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import us.kbase.common.service.JsonServerSyslog; import us.kbase.common.service.ServerException; import us.kbase.common.service.Tuple4; import us.kbase.narrativemethodstore.*; import us.kbase.narrativemethodstore.db.DynamicRepoDB; import us.kbase.narrativemethodstore.db.mongo.test.MongoDBHelper; public class FullServerTest { private static File tempDir; private static NarrativeMethodStoreServer SERVER; private static NarrativeMethodStoreClient CLIENT; private static boolean removeTempDir; private static String tempDirName; private static String gitRepo; private static String gitRepoBranch; private static String gitRepoRefreshRate; private static String gitRepoCacheSize; private static String mongoExePath; private static MongoDBHelper dbHelper; private static final String dbName = "method_store_full_server_test_temp_db"; private static final String admin1 = "admin1"; private static final String admin2 = "admin2"; private static class ServerThread extends Thread { private NarrativeMethodStoreServer server; private ServerThread(NarrativeMethodStoreServer server) { this.server = server; } public void run() { try { server.startupServer(); } catch (Exception e) { System.err.println("Can't start server:"); e.printStackTrace(); } } } @SuppressWarnings("unchecked") private static Map<String, String> getenv() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { Map<String, String> unmodifiable = System.getenv(); Class<?> cu = unmodifiable.getClass(); Field m = cu.getDeclaredField("m"); m.setAccessible(true); return (Map<String, String>) m.get(unmodifiable); } @Test public void testVersion() throws Exception { String ver = CLIENT.ver(); assertTrue("Testing that ver() returns a version string that looks valid", ver.matches("^\\d+\\.\\d+\\.\\d+(\\-.+)?$")); System.out.println("Testing NMS Server Version "+ver); } @Test public void testStatus() throws Exception { Status status = CLIENT.status(); assertTrue("Testing that status() returns a git spec branch that is not null", status.getGitSpecBranch()!=null); assertTrue("Testing that status() returns a git spec branch that is not empty", status.getGitSpecBranch().length()>0); assertTrue("Testing that status() returns a git spec commit that is not null", status.getGitSpecCommit()!=null); assertTrue("Testing that status() returns a git spec commit that is not empty", status.getGitSpecCommit().length()>0); assertTrue("Testing that status() returns a git spec repo url that is not null", status.getGitSpecUrl()!=null); assertTrue("Testing that status() returns a git spec repo url that is not empty", status.getGitSpecUrl().length()>0); assertTrue("Testing that status() returns a git spec update interval that is not null", status.getUpdateInterval()!=null); assertTrue("Testing that status() returns a git spec update interval that is not empty", status.getUpdateInterval().length()>0); } @Test public void testListMethodIds() throws Exception { Map<String, String> methods = CLIENT.listMethodIdsAndNames(new ListMethodIdsAndNamesParams()); assertTrue("Testing that test_method_1 returns from listMethodIdsAndNames()", methods.get("test_method_1").equals("Test Method 1")); } @Test public void testListMethods() throws Exception { ListParams params = new ListParams(); List<MethodBriefInfo> methods = CLIENT.listMethods(params); boolean foundTestMethod1 = false; boolean foundTestMethod8 = false; for(MethodBriefInfo m : methods) { // check specific things in specific test methods if(m.getId().equals("test_method_1")) { foundTestMethod1 = true; assertTrue("Testing that test_method_1 name in brief info from listMethods is correct", m.getName().equals("Test Method 1")); assertTrue("Testing that test_method_1 ver in brief info from listMethods is correct", m.getVer().equals("1.0.1")); assertTrue("Testing that test_method_1 id in brief info from listMethods is correct", m.getId().equals("test_method_1")); assertTrue("Testing that test_method_1 categories in brief info from listMethods is correct", m.getCategories().get(0).equals("testmethods")); } if(m.getId().equals("test_method_8")) { foundTestMethod8 = true; } } assertTrue("Testing that test_method_1 was returned from listMethods", foundTestMethod1); assertTrue("Testing that test_method_8 was returned from listMethods", foundTestMethod8); } @Test public void testGetCategory() throws Exception { //first just check that we didn't get anything if we didn't ask for anything GetCategoryParams params = new GetCategoryParams().withIds(new ArrayList<String>()); List<Category> categories = CLIENT.getCategory(params); assertTrue("Get categories without categories should return an empty list", categories.size()==0); //next check that what we asked for is returned params = new GetCategoryParams().withIds(Arrays.asList("testmethods")); categories = CLIENT.getCategory(params); assertTrue("Get categories with one valid category should return exactly one thing", categories.size()==1); assertTrue("The one category should be the one we asked for", categories.get(0).getId().compareTo("testmethods")==0); assertTrue("The one category should have the right name", categories.get(0).getName().compareTo("Test Methods")==0); // test that we don't get something if it doesn't exist try { params = new GetCategoryParams().withIds(Arrays.asList("blah_blah_blah_category")); categories = CLIENT.getCategory(params); fail("Get category with an invalid category id worked, but it shouldn't"); } catch (ServerException e) { assertTrue("Getting an invalid category throws an error, and the error has the correct message", e.getMessage().compareTo("No category with id=blah_blah_blah_category")==0); } } @Test public void testListCategories() throws Exception { ListCategoriesParams params = new ListCategoriesParams().withLoadMethods(0L); Tuple4<Map<String,Category>, Map<String,MethodBriefInfo>, Map<String,AppBriefInfo>, Map<String,TypeInfo>> methods = CLIENT.listCategories(params); //first just check that the method did not return methods if we did not request them assertTrue("We should not get methods from listCategories if we did not ask.", methods.getE2().size()==0); assertTrue("We should get categories from listCategories.", methods.getE1().size()>0); assertTrue("We should get the proper category name for testmethods.", methods.getE1().get("testmethods").getName().equals("Test Methods")); params = new ListCategoriesParams().withLoadMethods(1L); methods = CLIENT.listCategories(params); //check that the method did not return methods if we did not request them assertTrue("We should get methods from listCategories if we asked for it.", methods.getE2().size()>0); assertTrue("We should get a proper method in the methods returned by listCategories.", methods.getE2().get("test_method_1").getName().equals("Test Method 1")); assertTrue("We should get categories from listCategories.", methods.getE1().size()>0); assertTrue("We should get the proper category name for testmethods.", methods.getE1().get("testmethods").getName().equals("Test Methods")); } @Test public void testListMethodsBriefInfo() throws Exception { ListParams params = new ListParams(); List<MethodBriefInfo> methods = CLIENT.listMethods(params); boolean foundTestMethod1 = false; boolean foundTestMethod7 = false; for(MethodBriefInfo m : methods) { // check specific things in specific test methods if(m.getId().equals("test_method_1")) { foundTestMethod1 = true; assertTrue("Testing that test_method_1 name from listMethodsFullInfo is correct", m.getName().equals("Test Method 1")); assertTrue("Testing that test_method_1 ver from listMethodsFullInfo is correct", m.getVer().equals("1.0.1")); assertTrue("Testing that test_method_1 id from listMethodsFullInfo is correct", m.getId().equals("test_method_1")); assertTrue("Testing that test_method_1 categories from listMethodsFullInfo is correct", m.getCategories().get(0).equals("testmethods")); assertTrue("Testing that test_method_1 does not have an icon", m.getIcon()==null); } // check specific things in specific test methods if(m.getId().equals("test_method_7")) { foundTestMethod7 = true; assertTrue("Testing that test_method_7 has an icon", m.getIcon()!=null); assertTrue("Testing that test_method_7 has an icon url", m.getIcon().getUrl()!=null); assertEquals("img?method_id=test_method_7&image_name=icon.png",m.getIcon().getUrl()); } } assertTrue("Testing that test_method_1 was returned from listMethodsFullInfo", foundTestMethod1); assertTrue("Testing that test_method_7 was returned from listMethodsFullInfo", foundTestMethod7); } @Test public void testListAppIdsAndNames() throws Exception { Map<String, String> apps = CLIENT.listAppIdsAndNames(); assertTrue("listing apps and names got test_app_1",apps.containsKey("test_app_1")); assertTrue("listing apps and names got test_app_1, and name is correct",apps.get("test_app_1").compareTo("Test All 1")==0); assertTrue("listing apps and names got test_app_2",apps.containsKey("test_app_2")); assertTrue("listing apps and names got test_app_2, and name is correct",apps.get("test_app_1").compareTo("Test All 1")==0); } @Test public void testListAppSpecs() throws Exception { List<AppSpec> apps = CLIENT.listAppsSpec(new ListParams()); boolean foundApp1 = false; boolean foundApp2 = false; for(AppSpec a:apps) { if(a.getInfo().getId().compareTo("test_app_1")==0) { foundApp1 = true; } else if (a.getInfo().getId().compareTo("test_app_2")==0) { foundApp2 = true; } } assertTrue("Testing that test_app_1 was returned from listAppsSpec", foundApp1); assertTrue("Testing that test_app_2 was returned from listAppsSpec", foundApp2); } @Test public void testGetAppBriefInfo() throws Exception { GetAppParams params = new GetAppParams().withIds(Arrays.asList("test_app_1")); List<AppBriefInfo> apps = CLIENT.getAppBriefInfo(params); boolean foundTestApp1 = false; boolean foundTestApp2 = false; assertTrue("Testing that exactly one app was returned as requested",apps.size()==1); for(AppBriefInfo a : apps) { // check specific things in specific test methods if(a.getId().equals("test_app_1")) { foundTestApp1 = true; assertTrue("Testing that test_app_1 does not have an icon", a.getIcon()==null); } if(a.getId().equals("test_app_2")) { foundTestApp2 = true; } } assertTrue("Testing that test_app_1 was returned from getAppBriefInfo", foundTestApp1); assertFalse("Testing that test_app_2 was not returned from getAppBriefInfo because it was not in arguements", foundTestApp2); } @Test public void testListApps() throws Exception { ListParams params = new ListParams(); List<AppBriefInfo> apps = CLIENT.listApps(params); boolean foundTestApp1 = false; boolean foundTestApp2 = false; for(AppBriefInfo a : apps) { // check specific things in specific test methods if(a.getId().equals("test_app_1")) { foundTestApp1 = true; assertTrue("Testing that test_app_1 does not have an icon", a.getIcon()==null); } if(a.getId().equals("test_app_2")) { foundTestApp2 = true; assertTrue("Testing that test_app_2 has an icon", a.getIcon()!=null); assertTrue("Testing that test_app_2 has an icon url", a.getIcon().getUrl()!=null); assertEquals("img?method_id=test_app_2&image_name=someIcon.png",a.getIcon().getUrl()); } } assertTrue("Testing that test_app_1 was returned from listApps", foundTestApp1); assertTrue("Testing that test_app_2 was returned from listApps", foundTestApp2); } @Test public void testListAppsFullInfo() throws Exception { ListParams params = new ListParams(); List<AppFullInfo> methods = CLIENT.listAppsFullInfo(params); boolean foundTestApp1 = false; boolean foundTestApp2 = false; for(AppFullInfo a : methods) { // check specific things in specific test methods if(a.getId().equals("test_app_1")) { foundTestApp1 = true; assertTrue("Testing that test_app_1 does not have an icon", a.getIcon()==null); assertTrue("Testing that test_app_1 has suggestions defined", a.getSuggestions()!=null); assertTrue("Testing that test_app_1 has suggestions for related apps defined", a.getSuggestions().getRelatedApps()!=null); assertTrue("Testing that test_app_1 has suggestions for next apps defined", a.getSuggestions().getNextApps()!=null); assertTrue("Testing that test_app_1 has suggestions for related methods defined", a.getSuggestions().getRelatedMethods()!=null); assertTrue("Testing that test_app_1 has suggestions for next methods defined", a.getSuggestions().getNextMethods()!=null); assertTrue("Testing that test_app_1 has no suggestions for related apps", a.getSuggestions().getRelatedApps().size()==0); assertTrue("Testing that test_app_1 has no suggestions for next apps", a.getSuggestions().getNextApps().size()==0); assertTrue("Testing that test_app_1 has no suggestions for related methods", a.getSuggestions().getRelatedMethods().size()==0); assertTrue("Testing that test_app_1 has no suggestions for next methods", a.getSuggestions().getNextMethods().size()==0); } // check specific things in specific test methods if(a.getId().equals("test_app_2")) { foundTestApp2 = true; assertTrue("Testing that test_app_2 technical description is empty", a.getTechnicalDescription().trim().length()==0); assertTrue("Testing that test_app_2 has an icon", a.getIcon()!=null); assertTrue("Testing that test_app_2 has an icon url", a.getIcon().getUrl()!=null); assertEquals("img?method_id=test_app_2&image_name=someIcon.png",a.getIcon().getUrl()); assertTrue("Testing that test_app_2 has suggestions defined", a.getSuggestions()!=null); assertTrue("Testing that test_app_2 has suggestions for related apps defined", a.getSuggestions().getRelatedApps()!=null); assertTrue("Testing that test_app_2 has suggestions for next apps defined", a.getSuggestions().getNextApps()!=null); assertTrue("Testing that test_app_2 has suggestions for related methods defined", a.getSuggestions().getRelatedMethods()!=null); assertTrue("Testing that test_app_2 has suggestions for next methods defined", a.getSuggestions().getNextMethods()!=null); assertTrue("Testing that test_app_2 has suggestions for related apps", a.getSuggestions().getRelatedApps().size()==1); assertTrue("Testing that test_app_2 has suggestions for next apps", a.getSuggestions().getNextApps().size()==1); assertTrue("Testing that test_app_2 has no suggestions for related methods", a.getSuggestions().getRelatedMethods().size()==0); assertTrue("Testing that test_app_2 has no suggestions for next methods", a.getSuggestions().getNextMethods().size()==0); } } assertTrue("Testing that test_app_1 was returned from listAppsFullInfo", foundTestApp1); assertTrue("Testing that test_app_2 was returned from listAppsFullInfo", foundTestApp2); } @Test public void testListMethodsFullInfo() throws Exception { ListParams params = new ListParams(); List<MethodFullInfo> methods = CLIENT.listMethodsFullInfo(params); boolean foundTestMethod1 = false; boolean foundTestMethod7 = false; boolean foundTestMethod8 = false; for(MethodFullInfo m : methods) { // check specific things in specific test methods if(m.getId().equals("test_method_1")) { foundTestMethod1 = true; assertTrue("Testing that test_method_1 name from listMethodsFullInfo is correct", m.getName().equals("Test Method 1")); assertTrue("Testing that test_method_1 ver from listMethodsFullInfo is correct", m.getVer().equals("1.0.1")); assertTrue("Testing that test_method_1 id from listMethodsFullInfo is correct", m.getId().equals("test_method_1")); assertTrue("Testing that test_method_1 categories from listMethodsFullInfo is correct", m.getCategories().get(0).equals("testmethods")); assertTrue("Testing that test_method_1 description from listMethodsFullInfo is present", m.getDescription().trim().length()>0); assertTrue("Testing that test_method_1 technical description from listMethodsFullInfo is present", m.getTechnicalDescription().trim().length()>0); assertTrue("Testing that test_method_1 does not have an icon", m.getIcon()==null); assertTrue("Testing that test_method_1 has suggestions defined", m.getSuggestions()!=null); assertTrue("Testing that test_method_1 has suggestions for related apps defined", m.getSuggestions().getRelatedApps()!=null); assertTrue("Testing that test_method_1 has suggestions for next apps defined", m.getSuggestions().getNextApps()!=null); assertTrue("Testing that test_method_1 has suggestions for related methods defined", m.getSuggestions().getRelatedMethods()!=null); assertTrue("Testing that test_method_1 has suggestions for next methods defined", m.getSuggestions().getNextMethods()!=null); assertTrue("Testing that test_method_1 has no suggestions for related apps", m.getSuggestions().getRelatedApps().size()==0); assertTrue("Testing that test_method_1 has no suggestions for next apps", m.getSuggestions().getNextApps().size()==0); assertTrue("Testing that test_method_1 has no suggestions for related methods", m.getSuggestions().getRelatedMethods().size()==0); assertTrue("Testing that test_method_1 has no suggestions for next methods", m.getSuggestions().getNextMethods().size()==0); } // check specific things in specific test methods if(m.getId().equals("test_method_7")) { foundTestMethod7 = true; assertTrue("Testing that test_method_7 technical description is empty", m.getTechnicalDescription().trim().length()==0); assertTrue("Testing that test_method_7 has an icon", m.getIcon()!=null); assertTrue("Testing that test_method_7 has an icon url", m.getIcon().getUrl()!=null); assertEquals("img?method_id=test_method_7&image_name=icon.png",m.getIcon().getUrl()); assertTrue("Testing that test_method_7 has suggestions defined", m.getSuggestions()!=null); assertTrue("Testing that test_method_7 has suggestions for related apps defined", m.getSuggestions().getRelatedApps()!=null); assertTrue("Testing that test_method_7 has suggestions for next apps defined", m.getSuggestions().getNextApps()!=null); assertTrue("Testing that test_method_7 has suggestions for related methods defined", m.getSuggestions().getRelatedMethods()!=null); assertTrue("Testing that test_method_7 has suggestions for next methods defined", m.getSuggestions().getNextMethods()!=null); assertTrue("Testing that test_method_7 has suggestions for related apps", m.getSuggestions().getRelatedApps().size()==1); assertTrue("Testing that test_method_7 has suggestions for next apps", m.getSuggestions().getNextApps().size()==1); assertTrue("Testing that test_method_7 has suggestions for related methods", m.getSuggestions().getRelatedMethods().size()==1); assertEquals("test_method_3", m.getSuggestions().getRelatedMethods().get(0)); assertTrue("Testing that test_method_7 has suggestions for next methods", m.getSuggestions().getNextMethods().size()==2); assertEquals("test_method_1", m.getSuggestions().getNextMethods().get(0)); assertEquals("test_method_2", m.getSuggestions().getNextMethods().get(1)); } // check subdata parameter in test_method_8 if(m.getId().equals("test_method_8")) { foundTestMethod8 = true; assertTrue("Testing that test_method_8 technical description is empty", m.getTechnicalDescription().trim().length()==0); assertTrue("Testing that test_method_8 has no icon", m.getIcon() == null); } } assertTrue("Testing that test_method_1 was returned from listMethodsFullInfo", foundTestMethod1); assertTrue("Testing that test_method_7 was returned from listMethodsFullInfo", foundTestMethod7); assertTrue("Testing that test_method_8 was returned from listMethodsFullInfo", foundTestMethod8); } @Test public void testListMethodsSpec() throws Exception { ListParams params = new ListParams(); List<MethodSpec> methods = CLIENT.listMethodsSpec(params); boolean foundTestMethod1 = false; boolean foundTestMethod3 = false; boolean foundTestMethod4 = false; boolean foundTestMethod5 = false; boolean foundTestMethod7 = false; boolean foundTestMethod8 = false; boolean foundTestMethod10 = false; boolean foundTestMethod12 = false; for(MethodSpec m : methods) { // check specific things in specific test methods if(m.getInfo().getId().equals("test_method_1")) { foundTestMethod1 = true; assertEquals(0, m.getFixedParameters().size()); assertTrue("Testing that test_method_1 name from listMethodSpec is correct", m.getInfo().getName().equals("Test Method 1")); assertTrue("Testing that test_method_1 ver from listMethodSpec is correct", m.getInfo().getVer().equals("1.0.1")); assertTrue("Testing that test_method_1 id from listMethodSpec is correct", m.getInfo().getId().equals("test_method_1")); assertTrue("Testing that test_method_1 categories from listMethodSpec is correct", m.getInfo().getCategories().get(0).equals("testmethods")); assertTrue("Testing that test_method_1 from listMethodSpec has 2 parameters", m.getParameters().size()==2); assertTrue("Testing that test_method_1 from listMethodSpec parameter id is correct", m.getParameters().get(0).getId().equals("genome")); assertTrue("Testing that test_method_1 from listMethodSpec parameter name is correct", m.getParameters().get(0).getUiName().equals("Genome")); assertTrue("Testing that test_method_1 from listMethodSpec parameter short hint is correct", m.getParameters().get(0).getShortHint().equals("The genome object you wish to test.")); assertTrue("Testing that test_method_1 from listMethodSpec parameter short hint is correct", m.getParameters().get(0).getShortHint().equals("The genome object you wish to test.")); assertTrue("Testing that test_method_1 from listMethodSpec parameter valid ws type is correct", m.getParameters().get(0).getTextOptions().getValidWsTypes().get(0).equals("KBaseGenomes.Genome")); assertTrue("Testing that test_method_1 from listMethodSpec parameter valid ws type is correct", m.getParameters().get(0).getTextOptions().getValidWsTypes().get(1).equals("KBaseGenomes.PlantGenome")); assertTrue("Testing that test_method_1 output widget from listMethodSpec is correct", m.getWidgets().getOutput().equals("KBaseDefaultViewer")); } else if (m.getInfo().getId().equals("test_method_3")) { foundTestMethod3 = true; assertEquals(7, m.getParameters().size()); assertEquals(0, m.getFixedParameters().size()); assertEquals("param0", m.getParameters().get(0).getId()); assertEquals("checkbox", m.getParameters().get(0).getFieldType()); assertEquals(10L, (long)m.getParameters().get(0).getCheckboxOptions().getCheckedValue()); assertEquals(-10L, (long)m.getParameters().get(0).getCheckboxOptions().getUncheckedValue()); assertEquals("param0.1", m.getParameters().get(1).getId()); assertEquals("text", m.getParameters().get(1).getFieldType()); assertEquals("parameter",m.getParameters().get(1).getUiClass()); assertEquals("param1", m.getParameters().get(2).getId()); assertEquals("floatslider", m.getParameters().get(2).getFieldType()); assertEquals(1.0, (double)m.getParameters().get(2).getFloatsliderOptions().getMin(), 1e-10); assertEquals(10.0, (double)m.getParameters().get(2).getFloatsliderOptions().getMax(), 1e-10); assertEquals("param2", m.getParameters().get(3).getId()); assertEquals("textarea", m.getParameters().get(3).getFieldType()); assertEquals(10L, (long)m.getParameters().get(3).getTextareaOptions().getNRows()); assertEquals("place holder here", m.getParameters().get(3).getTextareaOptions().getPlaceholder()); assertEquals("param2.2", m.getParameters().get(4).getId()); assertEquals("textarea", m.getParameters().get(4).getFieldType()); assertEquals(10L, (long)m.getParameters().get(4).getTextareaOptions().getNRows()); assertEquals("", m.getParameters().get(4).getTextareaOptions().getPlaceholder()); assertEquals("param3", m.getParameters().get(5).getId()); assertEquals("dropdown", m.getParameters().get(5).getFieldType()); assertEquals(2, m.getParameters().get(5).getDropdownOptions().getOptions().size()); assertEquals("item0", m.getParameters().get(5).getDropdownOptions().getOptions().get(0).getValue()); assertEquals("param4", m.getParameters().get(6).getId()); assertEquals("radio", m.getParameters().get(6).getFieldType()); assertEquals(2, m.getParameters().get(6).getRadioOptions().getIdsToOptions().size()); assertEquals("First", m.getParameters().get(6).getRadioOptions().getIdsToOptions().get("item0")); assertEquals("First tooltip", m.getParameters().get(6).getRadioOptions().getIdsToTooltip().get("item0")); } else if (m.getInfo().getId().equals("test_method_4")) { foundTestMethod4 = true; assertEquals(0, m.getFixedParameters().size()); assertEquals("Test Method 4 was run on {{genome}} to produce a new genome named {{output_genome}}.", m.getReplacementText()); assertEquals(new Long(1), m.getParameters().get(1).getTextOptions().getIsOutputName()); assertEquals("output",m.getParameters().get(1).getUiClass()); assertEquals("select a genome", m.getParameters().get(0).getTextOptions().getPlaceholder()); assertEquals("input",m.getParameters().get(0).getUiClass()); } else if (m.getInfo().getId().equals("test_method_5")) { foundTestMethod5 = true; assertEquals(4, m.getParameters().size()); assertEquals(0, m.getFixedParameters().size()); assertEquals("text_int_number", m.getParameters().get(0).getId()); assertEquals("text", m.getParameters().get(0).getFieldType()); assertEquals(new Long(0), m.getParameters().get(0).getTextOptions().getMinInt()); assertEquals(new Long(20), m.getParameters().get(0).getTextOptions().getMaxInt()); assertEquals(new Long(0), m.getParameters().get(0).getDisabled()); assertEquals("parameter",m.getParameters().get(0).getUiClass()); assertEquals("text_int_number_disabled", m.getParameters().get(1).getId()); assertEquals("text", m.getParameters().get(1).getFieldType()); assertEquals(new Long(0), m.getParameters().get(1).getTextOptions().getMinInt()); assertEquals(new Long(20), m.getParameters().get(1).getTextOptions().getMaxInt()); assertEquals(new Long(1), m.getParameters().get(1).getDisabled()); assertEquals("parameter",m.getParameters().get(1).getUiClass()); assertEquals("text_float_number", m.getParameters().get(2).getId()); assertEquals("text", m.getParameters().get(2).getFieldType()); assertEquals(new Double(0.5), m.getParameters().get(2).getTextOptions().getMinFloat()); assertEquals(new Double(20.2), m.getParameters().get(2).getTextOptions().getMaxFloat()); assertEquals("parameter",m.getParameters().get(2).getUiClass()); assertEquals("regex", m.getParameters().get(3).getId()); assertEquals("text", m.getParameters().get(3).getFieldType()); assertEquals("parameter",m.getParameters().get(3).getUiClass()); List<RegexMatcher> rm = m.getParameters().get(3).getTextOptions().getRegexConstraint(); assertEquals(new Long(1), rm.get(0).getMatch()); assertEquals("^good", rm.get(0).getRegex()); assertEquals("input must start with good", rm.get(0).getErrorText()); assertEquals(new Long(0), rm.get(1).getMatch()); assertEquals("bad$", rm.get(1).getRegex()); assertEquals("input cannot end in bad", rm.get(1).getErrorText()); } else if (m.getInfo().getId().equals("test_method_7")) { foundTestMethod7 = true; assertEquals(2, m.getFixedParameters().size()); assertEquals("FixedParam1", m.getFixedParameters().get(0).getUiName()); assertEquals("a fixed parameter", m.getFixedParameters().get(0).getDescription()); assertEquals("FixedParam2", m.getFixedParameters().get(1).getUiName()); assertEquals("another fixed parameter", m.getFixedParameters().get(1).getDescription()); } else if (m.getInfo().getId().equals("test_method_8")) { foundTestMethod8 = true; assertEquals(3, m.getParameters().size()); assertEquals("genome_input", m.getParameters().get(0).getId()); assertEquals("text", m.getParameters().get(0).getFieldType()); assertNotNull(m.getParameters().get(0).getTextOptions()); assertNull(m.getParameters().get(0).getTextsubdataOptions()); assertEquals("feature_input", m.getParameters().get(1).getId()); assertEquals("textsubdata", m.getParameters().get(1).getFieldType()); assertNotNull(m.getParameters().get(1).getTextsubdataOptions()); TextSubdataOptions tso = m.getParameters().get(1).getTextsubdataOptions(); assertNotNull(tso.getSubdataSelection()); assertEquals(new Long(0), tso.getMultiselection()); assertEquals(new Long(1), tso.getShowSrcObj()); assertEquals(new Long(0), tso.getAllowCustom()); assertEquals("genome_input", tso.getSubdataSelection().getParameterId()); assertNull(tso.getSubdataSelection().getConstantRef()); assertEquals(3, tso.getSubdataSelection().getSubdataIncluded().size()); assertEquals("features/[*]/id", tso.getSubdataSelection().getSubdataIncluded().get(0)); assertEquals("features/[*]/aliases", tso.getSubdataSelection().getSubdataIncluded().get(1)); assertEquals("features/[*]/function", tso.getSubdataSelection().getSubdataIncluded().get(2)); assertEquals(1, tso.getSubdataSelection().getPathToSubdata().size()); assertEquals("features", tso.getSubdataSelection().getPathToSubdata().get(0)); assertEquals("id", tso.getSubdataSelection().getSelectionId()); assertEquals(2, tso.getSubdataSelection().getSelectionDescription().size()); assertEquals("aliases", tso.getSubdataSelection().getSelectionDescription().get(0)); assertEquals("function", tso.getSubdataSelection().getSelectionDescription().get(1)); assertEquals("({{aliases}}, {{function}})", tso.getSubdataSelection().getDescriptionTemplate()); assertEquals("more_features", m.getParameters().get(2).getId()); assertEquals("textsubdata", m.getParameters().get(2).getFieldType()); assertNotNull(m.getParameters().get(2).getTextsubdataOptions()); tso = m.getParameters().get(2).getTextsubdataOptions(); assertNotNull(tso.getSubdataSelection()); assertEquals(new Long(1), tso.getMultiselection()); assertEquals(new Long(1), tso.getShowSrcObj()); assertEquals(new Long(0), tso.getAllowCustom()); assertNull(tso.getSubdataSelection().getParameterId()); assertEquals(2,tso.getSubdataSelection().getConstantRef().size()); assertEquals("12/31",tso.getSubdataSelection().getConstantRef().get(0)); assertEquals("ws/MyObj",tso.getSubdataSelection().getConstantRef().get(1)); assertEquals(2, tso.getSubdataSelection().getSubdataIncluded().size()); assertEquals("features/[*]/id", tso.getSubdataSelection().getSubdataIncluded().get(0)); assertEquals("features/[*]/aliases", tso.getSubdataSelection().getSubdataIncluded().get(1)); assertEquals(1, tso.getSubdataSelection().getPathToSubdata().size()); assertEquals("features", tso.getSubdataSelection().getPathToSubdata().get(0)); assertEquals("id", tso.getSubdataSelection().getSelectionId()); assertNull(tso.getSubdataSelection().getSelectionDescription()); assertNull(tso.getSubdataSelection().getDescriptionTemplate()); } else if (m.getInfo().getId().equals("test_method_10")) { foundTestMethod10 = true; assertEquals(3, m.getParameters().size()); assertEquals("ftp", m.getParameters().get(0).getId()); assertEquals("dynamic_dropdown", m.getParameters().get(0).getFieldType()); DynamicDropdownOptions ddo0 = m.getParameters().get(0).getDynamicDropdownOptions(); assertNotNull(ddo0); assertEquals("ftp_staging", ddo0.getDataSource()); assertEquals("search", m.getParameters().get(1).getId()); assertEquals("dynamic_dropdown", m.getParameters().get(1).getFieldType()); DynamicDropdownOptions ddo1 = m.getParameters().get(1).getDynamicDropdownOptions(); assertNotNull(ddo1); assertEquals(new Long(0), ddo1.getMultiselection()); assertNotNull(ddo1.getServiceParams().toString()); assertEquals("taxon_name", ddo1.getSelectionId()); assertEquals("<strong>{{scientific_name}}</strong>: {{scientific_lineage}}", ddo1.getDescriptionTemplate()); assertEquals("custom", m.getParameters().get(2).getId()); assertEquals("dynamic_dropdown", m.getParameters().get(2).getFieldType()); DynamicDropdownOptions ddo2 = m.getParameters().get(2).getDynamicDropdownOptions(); assertNotNull(ddo2); assertEquals(new Long(1), ddo2.getMultiselection()); assertEquals("BiochemistryAPI.get_reactions", ddo2.getServiceFunction()); assertEquals("beta", ddo2.getServiceVersion()); assertEquals("UObject [userObj=[{\"reactions\":[\"{{dynamic_dropdown_input}}\"]}]]", ddo2.getServiceParams().toString()); assertEquals("id", ddo2.getSelectionId()); assertEquals("<strong>{{name}}</strong>: {{equation}}", ddo2.getDescriptionTemplate()); } else if (m.getInfo().getId().equals("test_method_12")) { foundTestMethod12 = true; int listSize = 6; assertEquals(listSize, m.getParameters().size()); // names of the parameters, minus the initial "param_" String[] ParamNameList = { "multiselection_false", "multiselection_true", "multiselection_default", "multiselection_false_allow_multiple", "multiselection_true_allow_multiple", "multiselection_default_allow_multiple", }; // whether or not the multiselection parameter is true int[] IsTrueList = {0, 1, 0, 0, 1, 0}; for (int n = 0; n < listSize; n++) { String ParamName = ParamNameList[n]; int IsTrue = IsTrueList[n]; assertEquals("param_" + ParamName, m.getParameters().get(n).getId()); assertEquals("dropdown", m.getParameters().get(n).getFieldType()); assertEquals(2, m.getParameters().get(n).getDropdownOptions().getOptions().size()); DropdownOptions ddo = m.getParameters().get(n).getDropdownOptions(); assertNotNull(ddo); assertEquals(new Long(IsTrue), ddo.getMultiselection()); assertEquals("item_" + ParamName + "_0", ddo.getOptions().get(0).getValue()); } } } assertTrue("Testing that test_method_1 was returned from listMethodSpec", foundTestMethod1); assertTrue("Testing that test_method_3 was returned from listMethodSpec", foundTestMethod3); assertTrue("Testing that test_method_4 was returned from listMethodSpec", foundTestMethod4); assertTrue("Testing that test_method_5 was returned from listMethodSpec", foundTestMethod5); assertTrue("Testing that test_method_7 was returned from listMethodSpec", foundTestMethod7); assertTrue("Testing that test_method_8 was returned from listMethodSpec", foundTestMethod8); assertTrue("Testing that test_method_10 was returned from listMethodSpec", foundTestMethod10); assertTrue("Testing that test_method_12 was returned from listMethodSpec", foundTestMethod12); } @Test public void getMethodBriefInfo() throws Exception { GetMethodParams params = new GetMethodParams().withIds(Arrays.asList("test_method_1")); List<MethodBriefInfo> methods = CLIENT.getMethodBriefInfo(params); assertTrue("Testing that test_method_1 can be fetched from getMethodBriefInfo", methods.size()==1); MethodBriefInfo m = methods.get(0); assertTrue("Testing that test_method_1 name from getMethodBriefInfo is correct", m.getName().equals("Test Method 1")); assertTrue("Testing that test_method_1 ver from getMethodBriefInfo is correct", m.getVer().equals("1.0.1")); assertTrue("Testing that test_method_1 id from getMethodBriefInfo is correct", m.getId().equals("test_method_1")); assertTrue("Testing that test_method_1 categories from getMethodBriefInfo is correct", m.getCategories().get(0).equals("testmethods")); m = CLIENT.getMethodBriefInfo(new GetMethodParams().withIds(Arrays.asList("test_method_4"))).get(0); assertTrue(new TreeSet<String>(m.getAuthors()).contains("wstester1")); assertEquals(2, m.getInputTypes().size()); assertEquals(1, m.getOutputTypes().size()); assertEquals("KBaseGenomes.Genome", m.getOutputTypes().get(0)); } @Test public void getAppType() throws Exception { GetMethodParams params = new GetMethodParams().withIds(Arrays.asList("test_method_9")); Assert.assertEquals("editor", CLIENT.getMethodBriefInfo(params).get(0).getAppType()); Assert.assertEquals("editor", CLIENT.getMethodFullInfo(params).get(0).getAppType()); } @Test public void testGetMethodFullInfo() throws Exception { GetMethodParams params = new GetMethodParams().withIds(Arrays.asList("test_method_1")); List<MethodFullInfo> methods = CLIENT.getMethodFullInfo(params); assertTrue("Testing that test_method_1 can be fetched from getMethodFullInfo", methods.size()==1); MethodFullInfo m = methods.get(0); assertTrue("Testing that test_method_1 name from getMethodFullInfo is correct", m.getName().equals("Test Method 1")); assertTrue("Testing that test_method_1 ver from getMethodFullInfo is correct", m.getVer().equals("1.0.1")); assertTrue("Testing that test_method_1 id from getMethodFullInfo is correct", m.getId().equals("test_method_1")); assertTrue("Testing that test_method_1 categories from getMethodFullInfo is correct", m.getCategories().get(0).equals("testmethods")); assertTrue("Testing that test_method_1 description from getMethodFullInfo is present", m.getDescription().trim().length()>0); assertTrue("Testing that test_method_1 technical description from getMethodFullInfo is present", m.getTechnicalDescription().trim().length()>0); List<Publication> pubs = m.getPublications(); assertTrue("Publications are returned",pubs!=null); assertTrue("4 publications are present",pubs.size()==4); assertEquals("pub 0 pmid is correct",pubs.get(0).getPmid(),"2231712"); assertEquals("pub 0 text is correct",pubs.get(0).getDisplayText(),"Basic local alignment search tool."); assertEquals("pub 0 link is correct",pubs.get(0).getLink(),"http: assertEquals("pub 1 pmid is correct",pubs.get(1).getPmid(),null); assertEquals("pub 1 text is correct",pubs.get(1).getDisplayText(),"Some made up paper"); assertEquals("pub 1 link is correct",pubs.get(1).getLink(),null); assertEquals("pub 2 pmid is correct",pubs.get(2).getPmid(),null); assertEquals("pub 2 text is correct",pubs.get(2).getDisplayText(),"http: assertEquals("pub 2 link is correct",pubs.get(2).getLink(),"http: assertEquals("pub 3 pmid is correct",pubs.get(3).getPmid(),"2231712"); assertEquals("pub 3 text is correct",pubs.get(3).getDisplayText(),"2231712"); assertEquals("pub 3 link is correct",pubs.get(3).getLink(),null); List<String> authors = m.getAuthors(); assertTrue("Authors are returned",authors!=null); assertTrue("4 publications are present",authors.size()==2); assertEquals("first author",authors.get(0),"msneddon"); assertEquals("second author",authors.get(1),"wstester1"); List<String> kb_contributors = m.getKbContributors(); assertTrue("KB Contributers are returned",kb_contributors!=null); assertEquals("first contributer",kb_contributors.get(0),"wstester3"); } @Test public void testGetMethodSpec() throws Exception { GetMethodParams params = new GetMethodParams().withIds(Arrays.asList("test_method_1")); List<MethodSpec> methods = CLIENT.getMethodSpec(params); assertTrue("Testing that test_method_1 can be fetched from getMethodSpec", methods.size()==1); MethodSpec m = methods.get(0); assertTrue("Testing that test_method_1 name from listMethodSpec is correct", m.getInfo().getName().equals("Test Method 1")); assertTrue("Testing that test_method_1 ver from listMethodSpec is correct", m.getInfo().getVer().equals("1.0.1")); assertTrue("Testing that test_method_1 id from listMethodSpec is correct", m.getInfo().getId().equals("test_method_1")); assertTrue("Testing that test_method_1 categories from listMethodSpec is correct", m.getInfo().getCategories().get(0).equals("testmethods")); assertTrue("Testing that test_method_1 from listMethodSpec has 2 parameters", m.getParameters().size()==2); assertTrue("Testing that test_method_1 from listMethodSpec parameter id is correct", m.getParameters().get(0).getId().equals("genome")); assertTrue("Testing that test_method_1 from listMethodSpec parameter name is correct", m.getParameters().get(0).getUiName().equals("Genome")); assertTrue("Testing that test_method_1 from listMethodSpec parameter short hint is correct", m.getParameters().get(0).getShortHint().equals("The genome object you wish to test.")); assertTrue("Testing that test_method_1 from listMethodSpec parameter short hint is correct", m.getParameters().get(0).getShortHint().equals("The genome object you wish to test.")); assertTrue("Testing that test_method_1 from listMethodSpec parameter valid ws type is correct", m.getParameters().get(0).getTextOptions().getValidWsTypes().get(0).equals("KBaseGenomes.Genome")); assertTrue("Testing that test_method_1 from listMethodSpec parameter valid ws type is correct", m.getParameters().get(0).getTextOptions().getValidWsTypes().get(1).equals("KBaseGenomes.PlantGenome")); assertTrue("Testing that test_method_1 output widget from listMethodSpec is correct", m.getWidgets().getOutput().equals("KBaseDefaultViewer")); } @Test public void testErrors() throws Exception { Tuple4<Map<String,Category>, Map<String,MethodBriefInfo>, Map<String,AppBriefInfo>, Map<String,TypeInfo>> ret = CLIENT.listCategories(new ListCategoriesParams().withLoadMethods(1L).withLoadApps(1L).withLoadTypes(1L)); Map<String, MethodBriefInfo> methodBriefInfo = ret.getE2(); MethodBriefInfo error1 = methodBriefInfo.get("test_error_1"); Assert.assertTrue(error1.getLoadingError(), error1.getLoadingError().contains("Unexpected character ('{' (code 123)): was expecting double-quote to start field name\n at [Source: java.io.StringReader")); MethodBriefInfo error2 = methodBriefInfo.get("test_error_2"); Assert.assertEquals(error2.getLoadingError(), "Can't find sub-node [parameters] within path [/] in spec.json"); MethodBriefInfo error3 = methodBriefInfo.get("test_error_3"); Assert.assertEquals(error3.getLoadingError(), "Can't find sub-node [id] within path [parameters/0] in spec.json"); MethodBriefInfo error4 = methodBriefInfo.get("test_error_4"); Assert.assertEquals(error4.getLoadingError(), "Can't find property [name] within path [/] in display.yaml"); MethodBriefInfo error5 = methodBriefInfo.get("test_error_5"); Assert.assertEquals(error5.getLoadingError(), "Can't find property [ui-name] within path [parameters/genome] in display.yaml"); for (String errorId : methodBriefInfo.keySet()) { if (methodBriefInfo.get(errorId).getLoadingError() != null && !errorId.startsWith("test_error_")) { System.out.println("Unexpected error [" + errorId + "]: " + methodBriefInfo.get(errorId).getLoadingError()); Assert.fail(methodBriefInfo.get(errorId).getLoadingError()); } } Map<String, AppBriefInfo> appBriefInfo = ret.getE3(); for (String errorId : appBriefInfo.keySet()) { if (appBriefInfo.get(errorId).getLoadingError() != null && !errorId.startsWith("test_error_")) { System.out.println("Unexpected error[" + errorId + "]: " + appBriefInfo.get(errorId).getLoadingError()); Assert.fail(appBriefInfo.get(errorId).getLoadingError()); } } Map<String, TypeInfo> typeInfo = ret.getE4(); for (String errorId : typeInfo.keySet()) { if (typeInfo.get(errorId).getLoadingError() != null && !errorId.startsWith("Test.Error")) { System.out.println("Unexpected error[" + errorId + "]: " + typeInfo.get(errorId).getLoadingError()); Assert.fail(typeInfo.get(errorId).getLoadingError()); } } MethodFullInfo err6 = CLIENT.getMethodFullInfo(new GetMethodParams().withIds(Arrays.asList("test_error_6"))).get(0); String text = err6.getPublications().get(0).getDisplayText(); int pos1 = text.indexOf("977"); int pos2 = text.indexOf("982"); Assert.assertTrue(pos1 > 0 && pos2 > 0); } @Test public void testApp() throws Exception { Map<String, AppBriefInfo> appBriefInfo = CLIENT.listCategories(new ListCategoriesParams().withLoadMethods(1L).withLoadApps(1L)).getE3(); assertNotNull(appBriefInfo.get("test_app_1")); //System.out.println(appBriefInfo.get("test_app_1")); AppSpec as = CLIENT.getAppSpec(new GetAppParams().withIds(Arrays.asList("test_app_1"))).get(0); assertEquals(2, as.getSteps().size()); assertEquals("step_1", as.getSteps().get(0).getStepId()); assertEquals("step_1", as.getSteps().get(1).getInputMapping().get(0).getStepSource()); List<AppSpec> spec = CLIENT.getAppSpec(new GetAppParams().withIds(Arrays.asList("test_app_1"))); //System.out.println(spec.get(0)); assertEquals(1, spec.size()); } @Test public void testServiceParamMapping() throws Exception { MethodSpec spec = CLIENT.getMethodSpec(new GetMethodParams().withIds(Arrays.asList("test_method_2"))).get(0); assertEquals("https://ci.kbase.us:555/services/neverservice", spec.getBehavior().getKbServiceUrl()); assertNotNull(spec.getBehavior().getKbServiceName()); assertNotNull(spec.getBehavior().getKbServiceMethod()); assertEquals("genome", spec.getBehavior().getKbServiceInputMapping().get(0).getInputParameter()); assertNotNull(spec.getBehavior().getKbServiceInputMapping().get(0).getTargetProperty()); assertNotNull(spec.getBehavior().getKbServiceInputMapping().get(0).getTargetTypeTransform()); assertEquals("genome_", spec.getBehavior().getKbServiceInputMapping().get(0).getGeneratedValue().getPrefix()); assertEquals(8L, (long)spec.getBehavior().getKbServiceInputMapping().get(0).getGeneratedValue().getSymbols()); assertEquals(".obj", spec.getBehavior().getKbServiceInputMapping().get(0).getGeneratedValue().getSuffix()); assertEquals("workspace", spec.getBehavior().getKbServiceInputMapping().get(1).getNarrativeSystemVariable()); assertNotNull(spec.getBehavior().getKbServiceInputMapping().get(1).getTargetArgumentPosition()); assertEquals("[0,\"1\",2.0]", spec.getBehavior().getKbServiceOutputMapping().get(0).getConstantValue().toJsonString()); assertEquals("ret1", spec.getBehavior().getKbServiceOutputMapping().get(0).getTargetProperty()); assertEquals("[key1, key2]", spec.getBehavior().getKbServiceOutputMapping().get(1).getServiceMethodOutputPath().toString()); assertEquals("re2", spec.getBehavior().getKbServiceOutputMapping().get(1).getTargetProperty()); assertEquals("re2", spec.getJobIdOutputField()); } @Test public void testListTypes() throws Exception { List<TypeInfo> typeInfo = CLIENT.listTypes(new ListParams()); assertTrue("Got list of types", typeInfo.size()>0); boolean foundTestType1 = false; for(TypeInfo ti : typeInfo) { if(ti.getTypeName().compareTo("Test.Type1")==0) { foundTestType1 = true; assertTrue("Test.Type1 has name Genome", ti.getName().compareTo("Genome")==0); assertEquals(1, ti.getExportFunctions().size()); assertTrue("Unexpected exporting function name", ti.getExportFunctions().get("TSV").contains("/")); } } assertTrue("Type1 was returned successfully in list types.",foundTestType1); } @Test public void testType() throws Exception { Map<String, TypeInfo> typeInfo = CLIENT.listCategories(new ListCategoriesParams().withLoadTypes(1L)).getE4(); TypeInfo ti = typeInfo.get("Test.Type1"); assertNotNull(ti); assertEquals("Genome", ti.getName()); assertEquals(1, ti.getViewMethodIds().size()); assertEquals(1, ti.getImportMethodIds().size()); assertEquals("genomes", ti.getLandingPageUrlPrefix()); ti = CLIENT.getTypeInfo(new GetTypeParams().withTypeNames(Arrays.asList("Test.Type1"))).get(0); assertEquals("Genome", ti.getName()); assertEquals(1, ti.getViewMethodIds().size()); assertEquals(1, ti.getImportMethodIds().size()); assertEquals("genomes", ti.getLandingPageUrlPrefix()); } @Test public void testValidateMethod() throws Exception { // Test a valid spec ValidateMethodParams params = new ValidateMethodParams() .withId("test_method_1") .withDisplayYaml(getTestFileFromSpecsRepo("methods/test_method_1/display.yaml")) .withSpecJson(getTestFileFromSpecsRepo("methods/test_method_1/spec.json")); ValidationResults results = CLIENT.validateMethod(params); assertTrue("Method validation results of test_method_1 returns is valid", results.getIsValid()==1L); assertTrue("Method validation contains an empty error report",results.getErrors().isEmpty()); assertTrue("Method validation results of test_method_1 spec is not null", results.getMethodSpec()!=null); assertTrue("Method validation results of test_method_1 full info is not null", results.getMethodFullInfo()!=null); assertTrue("Method validation results of test_method_1 app spec is null", results.getAppSpec()==null); assertTrue("Method validation results of test_method_1 app full info info is null", results.getAppFullInfo()==null); assertTrue("Method validation results of test_method_1 type info is null", results.getTypeInfo()==null); // Test an error case params = new ValidateMethodParams() .withId("test_error_1") .withDisplayYaml(getTestFileFromSpecsRepo("methods/test_error_1/display.yaml")) .withSpecJson(getTestFileFromSpecsRepo("methods/test_error_1/spec.json")); results = CLIENT.validateMethod(params); assertTrue("Method validation results of test_error_1 returns is not valid", results.getIsValid()==0L); assertTrue("Method validation contains some error report",results.getErrors().size()>0); assertTrue("Method validation results of test_method_1 spec is null", results.getMethodSpec()==null); assertTrue("Method validation results of test_method_1 full info is null", results.getMethodFullInfo()==null); assertTrue("Method validation results of test_method_1 app spec is null", results.getAppSpec()==null); assertTrue("Method validation results of test_method_1 app full info info is null", results.getAppFullInfo()==null); assertTrue("Method validation results of test_method_1 type info is null", results.getTypeInfo()==null); results = CLIENT.validateMethod(new ValidateMethodParams().withId("test_method_9") .withDisplayYaml(getTestFileFromSpecsRepo("methods/test_method_9/display.yaml")) .withSpecJson(getTestFileFromSpecsRepo("methods/test_method_9/spec.json"))); assertTrue(results.getIsValid() == 1L); } @Test public void testValidateMethodWithEstimator() throws Exception { ValidateMethodParams params = new ValidateMethodParams() .withId("test_method_11") .withDisplayYaml(getTestFileFromSpecsRepo("methods/test_method_11/display.yaml")) .withSpecJson(getTestFileFromSpecsRepo("methods/test_method_11/spec.json")); ValidationResults results = CLIENT.validateMethod(params); assertTrue("Method validation results of test_method_11 returns is valid", results.getIsValid()==1L); assertTrue("Method validation contains an empty error report", results.getErrors().isEmpty()); assertTrue("Method validation results of test_method_11 got the right name", results.getMethodFullInfo().getName().compareTo("Test Method Estimator")==0); assertTrue("Method validation results of test_method_11 got the right estimator module", results.getMethodSpec().getBehavior().getResourceEstimatorModule().compareTo("SomeService")==0); assertTrue("Method validation results of test_method_11 got the right estimator method", results.getMethodSpec().getBehavior().getResourceEstimatorMethod().compareTo("estimator_method")==0); assertTrue("Method validation results of test_method_11 spec is not null", results.getMethodSpec()!=null); assertTrue("Method validation results of test_method_11 full info is not null", results.getMethodFullInfo()!=null); assertTrue("Method validation results of test_method_11 app spec is null", results.getAppSpec()==null); assertTrue("Method validation results of test_method_11 app full info info is null", results.getAppFullInfo()==null); assertTrue("Method validation results of test_method_11 type info is null", results.getTypeInfo()==null); } @Test public void testValidateMethodWithEstimatorError() throws Exception { ValidateMethodParams params = new ValidateMethodParams() .withId("test_error_7") .withDisplayYaml(getTestFileFromSpecsRepo("methods/test_error_7/display.yaml")) .withSpecJson(getTestFileFromSpecsRepo("methods/test_error_7/spec.json")); ValidationResults results = CLIENT.validateMethod(params); assertTrue("Method validation results of test_error_7 returns is not valid", results.getIsValid()==0L); assertTrue("Method validation contains an error report", !results.getErrors().isEmpty()); assertTrue("Method validation error looks right", results.getErrors().get(0).contains("If resource_estimator_module is defined, then resource_estimator_method must also be defined.")); assertTrue("Method validation results of test_error_7 spec is null", results.getMethodSpec()==null); assertTrue("Method validation results of test_error_7 full info is null", results.getMethodFullInfo()==null); assertTrue("Method validation results of test_error_7 app spec is null", results.getAppSpec()==null); assertTrue("Method validation results of test_error_7 app full info is null", results.getAppFullInfo()==null); assertTrue("Method validation results of test_error_7 type info is null", results.getTypeInfo()==null); } @Test public void testValidateApp() throws Exception { // Test a valid spec ValidateAppParams params = new ValidateAppParams() .withId("test_method_1") .withDisplayYaml(getTestFileFromSpecsRepo("apps/test_app_1/display.yaml")) .withSpecJson(getTestFileFromSpecsRepo("apps/test_app_1/spec.json")); ValidationResults results = CLIENT.validateApp(params); assertTrue("App validation results of test_app_1 returns is valid", results.getIsValid()==1L); assertTrue("App validation contains an empty error report",results.getErrors().isEmpty()); assertTrue("App validation results of test_app_1 spec is not null", results.getAppSpec()!=null); assertTrue("App validation results of test_app_1 full info is not null", results.getAppFullInfo()!=null); assertTrue("App validation results of test_app_1 method spec is null", results.getMethodSpec()==null); assertTrue("App validation results of test_app_1 method full info info is null", results.getMethodFullInfo()==null); assertTrue("App validation results of test_app_1 type info is null", results.getTypeInfo()==null); assertTrue("App validation results of test_app_1 got the right name", results.getAppFullInfo().getName().compareTo("Test All 1")==0); // Test an error case params = new ValidateAppParams() .withId("test_error_1") .withDisplayYaml("madeup: nothing") .withSpecJson(getTestFileFromSpecsRepo("methods/test_error_1/spec.json")); results = CLIENT.validateApp(params); assertTrue("App validation results of test_error_1 returns is not valid", results.getIsValid()==0L); assertTrue("App validation contains some error report",results.getErrors().size()>0); assertTrue("App validation results of test_method_1 spec is null", results.getMethodSpec()==null); assertTrue("App validation results of test_method_1 full info is null", results.getMethodFullInfo()==null); assertTrue("App validation results of test_method_1 app spec is null", results.getAppSpec()==null); assertTrue("App validation results of test_method_1 app full info info is null", results.getAppFullInfo()==null); assertTrue("App validation results of test_method_1 type info is null", results.getTypeInfo()==null); } @Test public void testValidateType() throws Exception { // Test a valid spec ValidateTypeParams params = new ValidateTypeParams() .withId("Test.Type1") .withDisplayYaml(getTestFileFromSpecsRepo("types/Test.Type1/display.yaml")) .withSpecJson(getTestFileFromSpecsRepo("types/Test.Type1/spec.json")); ValidationResults results = CLIENT.validateType(params); assertTrue("Type validation results of Test.Type1 returns is valid", results.getIsValid()==1L); assertTrue("Type validation contains an empty error report",results.getErrors().isEmpty()); assertTrue("Type validation results of Test.Type1 spec is null", results.getMethodSpec()==null); assertTrue("Type validation results of Test.Type1 full info is null", results.getMethodFullInfo()==null); assertTrue("Type validation results of Test.Type1 app spec is null", results.getAppSpec()==null); assertTrue("Type validation results of Test.Type1 app full info info is null", results.getAppFullInfo()==null); assertTrue("Type validation results of Test.Type1 type info is not null", results.getTypeInfo()!=null); assertTrue("Type validation results of Test.Type1 got the right name", results.getTypeInfo().getName().compareTo("Genome")==0); // Test an error case params = new ValidateTypeParams() .withId("Test.Type1") .withDisplayYaml("not a field: 23\n\n").withSpecJson("{}"); results = CLIENT.validateType(params); assertTrue("Type validation results of test_error_1 returns is not valid", results.getIsValid()==0L); assertTrue("Type validation contains some error report",results.getErrors().size()>0); assertTrue("Type validation results of test_method_1 spec is null", results.getMethodSpec()==null); assertTrue("Type validation results of test_method_1 full info is null", results.getMethodFullInfo()==null); assertTrue("Type validation results of test_method_1 app spec is null", results.getAppSpec()==null); assertTrue("Type validation results of test_method_1 app full info info is null", results.getAppFullInfo()==null); assertTrue("Type validation results of test_method_1 type info is null", results.getTypeInfo()==null); } @SuppressWarnings("static-access") @Test public void testDynamicRepos() throws Exception { try { String moduleName = "onerepotest"; String gitUrl = "https://github.com/kbaseIncubator/onerepotest"; String methodId = moduleName + "/send_data"; Map<String,MethodBriefInfo> methods = CLIENT.listCategories(new ListCategoriesParams().withLoadMethods(1L)).getE2(); MethodBriefInfo bi = methods.get(methodId); Assert.assertNull(bi); SERVER.getLocalGitDB().registerRepo(admin1, gitUrl, null); Assert.assertEquals(2, CLIENT.listMethods(new ListParams().withTag("dev")).size() - CLIENT.listMethods(new ListParams().withTag("release")).size()); Assert.assertEquals(2, CLIENT.listMethodsSpec(new ListParams().withTag("dev")).size() - CLIENT.listMethodsSpec(new ListParams().withTag("release")).size()); Assert.assertEquals(2, CLIENT.listMethodsFullInfo(new ListParams().withTag("dev")).size() - CLIENT.listMethodsFullInfo(new ListParams().withTag("release")).size()); Assert.assertEquals(2, CLIENT.listMethodIdsAndNames(new ListMethodIdsAndNamesParams().withTag("dev")).size() - CLIENT.listMethodIdsAndNames(new ListMethodIdsAndNamesParams().withTag("release")).size()); Assert.assertNull(CLIENT.listCategories(new ListCategoriesParams().withLoadMethods(1L).withTag("beta")).getE2().get(methodId)); SERVER.getLocalGitDB().pushRepoToTag(moduleName, "beta", admin1); Assert.assertNotNull(CLIENT.listCategories(new ListCategoriesParams().withLoadMethods(1L).withTag("beta")).getE2().get(methodId)); methods = CLIENT.listCategories(new ListCategoriesParams().withLoadMethods(1L).withTag("dev")).getE2(); bi = methods.get(methodId); Assert.assertNotNull(bi); Assert.assertEquals("Async Docker Test", bi.getName()); Assert.assertEquals("Perform Async Docker Test.", bi.getTooltip().trim()); Assert.assertEquals("[active]", bi.getCategories().toString()); Assert.assertEquals(moduleName, bi.getModuleName()); Assert.assertEquals("0.0.2", bi.getVer()); MethodFullInfo fi = CLIENT.getMethodFullInfo(new GetMethodParams().withIds(Arrays.asList(methodId)).withTag("dev")).get(0); Assert.assertNotNull(fi); Assert.assertTrue("Description: " + fi.getDescription(), fi.getDescription().contains("Async Docker Test")); Assert.assertEquals(moduleName, fi.getModuleName()); MethodSpec ms = CLIENT.getMethodSpec(new GetMethodParams().withIds(Arrays.asList(methodId)).withTag("dev")).get(0); Assert.assertNotNull(ms); Assert.assertEquals(2, ms.getParameters().size()); Assert.assertEquals("param0", ms.getParameters().get(0).getId()); Assert.assertEquals("Genome1 ID", ms.getParameters().get(0).getUiName().trim()); Assert.assertEquals("Source genome 1", ms.getParameters().get(0).getShortHint().trim()); Assert.assertEquals("text", ms.getParameters().get(0).getFieldType()); Assert.assertEquals("[KBaseGenomes.Genome]", ms.getParameters().get(0).getTextOptions().getValidWsTypes().toString()); DynamicRepoDB db = SERVER.getLocalGitDB().getDynamicRepos(); Assert.assertEquals(1, db.listRepoVersions(moduleName, null).size()); String commitHash1 = db.getRepoDetails(moduleName, null).getGitCommitHash(); Assert.assertEquals(40, commitHash1.length()); Assert.assertEquals(commitHash1, ms.getBehavior().getKbServiceVersion()); RepoDetails rd = SERVER.getLocalGitDB().getRepoDetails(moduleName, null, null, null); Assert.assertEquals(moduleName, rd.getModuleName()); Assert.assertEquals("[ResultView.js]", rd.getWidgetIds().toString()); Assert.assertNotNull(CLIENT.loadWidgetJavaScript(new LoadWidgetParams().withModuleName(moduleName) .withWidgetId("ResultView.js").withTag("dev"))); Assert.assertEquals("img?method_id=onerepotest/send_data&image_name=icon.png&tag=dev", fi.getIcon().getUrl()); String owner = "rsutormin"; try { SERVER.getLocalGitDB().registerRepo(owner, gitUrl, null); Assert.fail("Only admin can register dynamic repos"); } catch (Exception ex) { Assert.assertEquals("User " + owner + " is not global admin", ex.getMessage()); } String commitHash2 = "00f008a265785ddfa70f21794738953bbf5895d0"; SERVER.getLocalGitDB().registerRepo(admin1, gitUrl, commitHash2); Assert.assertNull(CLIENT.listCategories(new ListCategoriesParams().withLoadMethods(1L)).getE2().get(methodId)); checkMethod(methodId, 2, "genomeA", "Genome A", "dev"); MethodBriefInfo mbi2 = CLIENT.getMethodBriefInfo(new GetMethodParams().withIds(Arrays.asList(methodId)).withTag("dev")).get(0); Assert.assertEquals(mbi2.getGitCommitHash(), commitHash2); mbi2 = CLIENT.getMethodBriefInfo(new GetMethodParams().withIds(Arrays.asList(methodId)).withTag(commitHash2)).get(0); Assert.assertEquals(mbi2.getGitCommitHash(), commitHash2); MethodFullInfo mfi2 = CLIENT.getMethodFullInfo(new GetMethodParams().withIds(Arrays.asList(methodId)).withTag("dev")).get(0); Assert.assertEquals(mfi2.getGitCommitHash(), commitHash2); MethodSpec ms2 = CLIENT.getMethodSpec(new GetMethodParams().withIds(Arrays.asList(methodId)).withTag("dev")).get(0); Assert.assertEquals(ms2.getInfo().getGitCommitHash(), commitHash2); checkMethod(methodId, 2, "param0", "Genome1 ID", "beta"); SERVER.getLocalGitDB().pushRepoToTag(moduleName, "release", admin1); SERVER.getLocalGitDB().pushRepoToTag(moduleName, "beta", admin1); checkMethod(methodId, 2, "genomeA", "Genome A", "beta"); checkMethod(methodId, 2, "param0", "Genome1 ID", "release"); checkMethod(methodId, 2, "param0", "Genome1 ID", null); SERVER.getLocalGitDB().pushRepoToTag(moduleName, "release", admin1); checkMethod(methodId, 2, "genomeA", "Genome A", null); checkMethod(methodId, 2, "param0", "Genome1 ID", commitHash1); checkMethod(methodId, 2, "genomeA", "Genome A", commitHash2); try { checkMethod(methodId, 2, "genomeA", "Genome A", "unknown_version"); Assert.fail("Unexpected tags shouldn't be supported"); } catch (Exception ex) { Assert.assertEquals("Repo-tag [unknown_version] is not supported", ex.getMessage()); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); SERVER.getLocalGitDB().saveScreenshotIntoStream(moduleName, "send_data", "icon.png", commitHash1, baos); Assert.assertEquals(62124, baos.toByteArray().length); methods = null; bi = null; fi = null; try { SERVER.getLocalGitDB().setRepoState(owner, moduleName, "disabled"); Assert.fail("Only admin can disable dynamic repos"); } catch (Exception ex) { Assert.assertEquals("User " + owner + " is not global admin", ex.getMessage()); } SERVER.getLocalGitDB().setRepoState(admin1, moduleName, "disabled"); methods = CLIENT.listCategories(new ListCategoriesParams().withLoadMethods(1L)).getE2(); bi = methods.get(methodId); Assert.assertNull(bi); String gitUrl2 = "https://github.com/kbaseIncubator/contigcount"; String moduleName2 = "contigcount"; String methodId2 = "contigcount/count_contigs_in_set_async"; SERVER.getLocalGitDB().registerRepo(admin1, gitUrl2, "0a11f2d6d2011f5590dd07ccfa6679b0166dd922"); try { SERVER.getLocalGitDB().pushRepoToTag(moduleName2, "release", admin1); Assert.fail("Pushing to release cannot be done before pushing to beta"); } catch (Exception ex) { Assert.assertEquals("Repository contigcount cannot be released cause it was never pushed to beta tag", ex.getMessage()); } SERVER.getLocalGitDB().pushRepoToTag(moduleName2, "beta", admin1); SERVER.getLocalGitDB().pushRepoToTag(moduleName2, "release", admin1); checkMethod(methodId2, 1, "contigset_id", "Contig Set Id", "dev"); checkMethod(methodId2, 1, "contigset_id", "Contig Set Id", "beta"); checkMethod(methodId2, 1, "contigset_id", "Contig Set Id", "release"); // try to disable, method should be gone and enable again, method should exists SERVER.getLocalGitDB().setRepoState(admin1, moduleName, "disabled"); methods = CLIENT.listCategories(new ListCategoriesParams().withLoadMethods(1L)).getE2(); bi = methods.get(methodId); Assert.assertNull(bi); SERVER.getLocalGitDB().setRepoState(admin1, moduleName, "ready"); methods = CLIENT.listCategories(new ListCategoriesParams().withLoadMethods(1L)).getE2(); checkMethod(methodId2, 1, "contigset_id", "Contig Set Id", "dev"); checkMethod(methodId2, 1, "contigset_id", "Contig Set Id", "beta"); checkMethod(methodId2, 1, "contigset_id", "Contig Set Id", "release"); } catch (ServerException ex) { System.err.println(ex.getData()); throw ex; } } private static void checkMethod(String methodId, int paramCount, String param1id, String param1name, String tag) throws Exception { MethodSpec ms = CLIENT.getMethodSpec(new GetMethodParams().withIds(Arrays.asList(methodId)).withTag(tag)).get(0); Assert.assertEquals(paramCount, ms.getParameters().size()); Assert.assertEquals(param1id, ms.getParameters().get(0).getId()); Assert.assertEquals(param1name, ms.getParameters().get(0).getUiName().trim()); } private static String getTestFileFromSpecsRepo(String path) { StringBuilder content = new StringBuilder(); try { URL githubFile = new URL(gitRepo + "/raw/" + gitRepoBranch + "/"+path); BufferedReader in = new BufferedReader(new InputStreamReader(githubFile.openStream())); String line; while ((line = in.readLine()) != null) { content.append(line+"\n"); } in.close(); } catch (IOException e) { throw new IllegalStateException(e); } return content.toString(); } @BeforeClass public static void setUpClass() throws Exception { Log.setLog(new Logger() { @Override public void warn(String arg0, Object arg1, Object arg2) {} @Override public void warn(String arg0, Throwable arg1) {} @Override public void warn(String arg0) {} @Override public void setDebugEnabled(boolean arg0) {} @Override public boolean isDebugEnabled() { return false; } @Override public void info(String arg0, Object arg1, Object arg2) {} @Override public void info(String arg0) {} @Override public String getName() { return null; } @Override public Logger getLogger(String arg0) { return this; } @Override public void debug(String arg0, Object arg1, Object arg2) {} @Override public void debug(String arg0, Throwable arg1) {} @Override public void debug(String arg0) {} }); // Parse the test config variables tempDirName = System.getProperty("test.temp-dir"); gitRepo = System.getProperty("test.method-spec-git-repo"); gitRepoBranch = System.getProperty("test.method-spec-git-repo-branch"); gitRepoRefreshRate = System.getProperty("test.method-spec-git-repo-refresh-rate"); gitRepoCacheSize = System.getProperty("test.method-spec-cache-size"); mongoExePath = System.getProperty("test.mongo-exe-path"); String s = System.getProperty("test.remove-temp-dir"); removeTempDir = false; if(s!=null) { if(s.trim().equals("1") || s.trim().equals("yes") || s.trim().equals("true")) { removeTempDir = true; } } String authServiceUrl = System.getProperty("test.auth-service-url"); String authInsecure = System.getProperty("test.auth-service-url-allow-insecure"); System.out.println("test.temp-dir = " + tempDirName); System.out.println("test.method-spec-git-repo = " + gitRepo); System.out.println("test.method-spec-git-repo-branch = " + gitRepoBranch); System.out.println("test.method-spec-git-repo-refresh-rate = " + gitRepoRefreshRate); System.out.println("test.method-spec-cache-size = " + gitRepoCacheSize); System.out.println("test.mongo-exe-path = " + mongoExePath); System.out.println("test.auth-service-url = " + authServiceUrl); System.out.println("test.auth-service-url-allow-insecure = " + authInsecure); //create the temp directory for this test tempDir = new File(tempDirName); if (!tempDir.exists()) tempDir.mkdirs(); //create the server config file File iniFile = File.createTempFile("test", ".cfg", tempDir); if (iniFile.exists()) { iniFile.delete(); } dbHelper = new MongoDBHelper("narrative_method_db", tempDirName); dbHelper.startup(mongoExePath); System.out.println("Created temporary config file: " + iniFile.getAbsolutePath()); Ini ini = new Ini(); Section ws = ini.add("NarrativeMethodStore"); ws.add("method-spec-git-repo", gitRepo); ws.add("method-spec-git-repo-branch", gitRepoBranch); ws.add("method-spec-git-repo-local-dir", tempDir.getAbsolutePath()+"/narrative_method_specs"); ws.add("method-spec-git-repo-refresh-rate", gitRepoRefreshRate); ws.add("method-spec-cache-size", gitRepoCacheSize); ws.add("method-spec-temp-dir", dbHelper.getWorkDir()); ws.add("method-spec-mongo-host", "localhost:" + dbHelper.getMongoPort()); ws.add("method-spec-mongo-dbname", dbName); ws.add("method-spec-admin-users", admin1 + "," + admin2); ws.add("endpoint-host", "https://ci.kbase.us"); ws.add("endpoint-base", "/services"); ws.add(NarrativeMethodStoreServer.CFG_PROP_DEFAULT_TAG, "release"); ws.add(NarrativeMethodStoreServer.CFG_PROP_AUTH_SERVICE_URL, authServiceUrl); if (authInsecure != null) { ws.add(NarrativeMethodStoreServer.CFG_PROP_AUTH_INSECURE, authInsecure); } ini.store(iniFile); Map<String, String> env = getenv(); env.put("KB_DEPLOYMENT_CONFIG", iniFile.getAbsolutePath()); env.put("KB_SERVICE_NAME", "NarrativeMethodStore"); JsonServerSyslog.setStaticUseSyslog(false); JsonServerSyslog.setStaticMlogFile(new File(tempDir, "service.log").getAbsolutePath()); SERVER = new NarrativeMethodStoreServer(); new ServerThread(SERVER).start(); System.out.println("Main thread waiting for server to start up"); while (SERVER.getServerPort() == null) { Thread.sleep(100); } System.out.println("Test server listening on "+SERVER.getServerPort() ); CLIENT = new NarrativeMethodStoreClient(new URL("http://localhost:" + SERVER.getServerPort())); System.out.println("Server status: " + CLIENT.status()); } @AfterClass public static void tearDownClass() throws Exception { try { if (SERVER != null) { System.out.print("Killing narrative method store server... "); SERVER.stopServer(); System.out.println("Done"); } } finally { try { if (dbHelper != null) dbHelper.shutdown(removeTempDir); } finally { if (removeTempDir) FileUtils.deleteDirectory(tempDir); } } } public static void main(String[] args) throws Exception { setUpClass(); int port = SERVER.getServerPort(); System.out.println("NarrativeMethodStore was started up on port: " + port); String moduleName = "onerepotest"; String gitUrl = "https://github.com/kbaseIncubator/onerepotest"; NarrativeMethodStoreServer.getLocalGitDB().registerRepo(admin1, gitUrl, null); DynamicRepoDB db = NarrativeMethodStoreServer.getLocalGitDB().getDynamicRepos(); String commitHash = db.getRepoDetails(moduleName, null).getGitCommitHash(); System.out.println("Repo " + moduleName + " was registered with version: " + commitHash); } }
package com.flipkart.foxtrot.sql; import com.flipkart.foxtrot.common.ActionRequest; import com.flipkart.foxtrot.common.Period; import com.flipkart.foxtrot.common.count.CountRequest; import com.flipkart.foxtrot.common.distinct.DistinctRequest; import com.flipkart.foxtrot.common.group.GroupRequest; import com.flipkart.foxtrot.common.histogram.HistogramRequest; import com.flipkart.foxtrot.common.query.Filter; import com.flipkart.foxtrot.common.query.Query; import com.flipkart.foxtrot.common.query.ResultSort; import com.flipkart.foxtrot.common.query.datetime.LastFilter; import com.flipkart.foxtrot.common.query.general.*; import com.flipkart.foxtrot.common.query.numeric.*; import com.flipkart.foxtrot.common.query.string.ContainsFilter; import com.flipkart.foxtrot.common.stats.StatsRequest; import com.flipkart.foxtrot.common.stats.StatsTrendRequest; import com.flipkart.foxtrot.common.trend.TrendRequest; import com.flipkart.foxtrot.sql.extendedsql.ExtendedSqlStatement; import com.flipkart.foxtrot.sql.extendedsql.desc.Describe; import com.flipkart.foxtrot.sql.extendedsql.showtables.ShowTables; import com.flipkart.foxtrot.sql.query.FqlActionQuery; import com.flipkart.foxtrot.sql.query.FqlDescribeTable; import com.flipkart.foxtrot.sql.query.FqlShowTablesQuery; import com.flipkart.foxtrot.sql.util.QueryUtils; import com.google.common.collect.Lists; import io.dropwizard.util.Duration; import net.sf.jsqlparser.expression.*; import net.sf.jsqlparser.expression.operators.conditional.AndExpression; import net.sf.jsqlparser.expression.operators.relational.*; import net.sf.jsqlparser.parser.CCJSqlParserManager; import net.sf.jsqlparser.schema.Column; import net.sf.jsqlparser.schema.Table; import net.sf.jsqlparser.statement.Statement; import net.sf.jsqlparser.statement.select.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.StringReader; import java.util.List; public class QueryTranslator extends SqlElementVisitor { private static final Logger logger = LoggerFactory.getLogger(QueryTranslator.class.getSimpleName()); private static final MetaStatementMatcher metastatementMatcher = new MetaStatementMatcher(); private FqlQueryType queryType = FqlQueryType.select; private String tableName; private List<String> groupBycolumnsList = Lists.newArrayList(); private ResultSort resultSort; private boolean hasLimit = false; private long limitFrom; private long limitCount; private ActionRequest calledAction; private List<Filter> filters; private List<String> selectedColumns = Lists.newArrayList(); private List<ResultSort> columnsWithSort = Lists.newArrayList(); @Override public void visit(PlainSelect plainSelect) { List selectItems = plainSelect.getSelectItems(); //selectItems.accept(this); for(Object selectItem : selectItems) { SelectItem selectExpressionItem = (SelectItem)selectItem; //System.out.println(selectExpressionItem.getExpression()); FunctionReader functionReader = new FunctionReader(); selectExpressionItem.accept(functionReader); final String columnName = functionReader.columnName; if(null != columnName && !columnName.isEmpty()) { selectedColumns.add(columnName); continue; } calledAction = functionReader.actionRequest; queryType = functionReader.queryType; } plainSelect.getFromItem().accept(this); //Populate table name List groupByItems = plainSelect.getGroupByColumnReferences(); if(null != groupByItems) { queryType = FqlQueryType.group; for(Object groupByItem : groupByItems) { if(groupByItem instanceof Column) { Column column = (Column) groupByItem; groupBycolumnsList.add(column.getFullyQualifiedName()); } } } if(FqlQueryType.select == queryType) { List orderByElements = plainSelect.getOrderByElements(); resultSort = generateResultSort(orderByElements); if (null != plainSelect.getLimit()) { hasLimit = true; limitFrom = plainSelect.getLimit().getOffset(); limitCount = plainSelect.getLimit().getRowCount(); } } if(null != plainSelect.getWhere()) { FilterParser filterParser = new FilterParser(); plainSelect.getWhere().accept(filterParser); filters = (filterParser.filters.isEmpty()) ? null : filterParser.filters; } // Handle distinct List<ResultSort> tempColumnsWithSort = generateColumnSort(plainSelect.getOrderByElements()); if (null != plainSelect.getDistinct()){ for (String selectedColumn : selectedColumns){ boolean alreadyAdded = false; for (ResultSort columnWithSort : tempColumnsWithSort){ if (selectedColumn.equalsIgnoreCase(columnWithSort.getField())){ columnsWithSort.add(columnWithSort); alreadyAdded = true; break; } } if (!alreadyAdded){ ResultSort resultSort = new ResultSort(); resultSort.setField(selectedColumn); resultSort.setOrder(ResultSort.Order.desc); columnsWithSort.add(resultSort); } } this.queryType = FqlQueryType.distinct; } } @Override public void visit(Select select) { select.getSelectBody().accept(this); } @Override public void visit(Table tableName) { this.tableName = tableName.getName().replaceAll(Constants.SQL_TABLE_REGEX, ""); } @Override public void visit(Function function) { List params = function.getParameters().getExpressions(); ((Expression)params.toArray()[0]).accept(this); //TODO } @Override public void visit(ExpressionList expressionList) { ExpressionList expressions = (ExpressionList)expressionList.getExpressions(); for(Object expression : expressions.getExpressions()) { System.out.println(expression.getClass()); } } @Override public void visit(SelectExpressionItem selectExpressionItem) { selectExpressionItem.getExpression().accept(this); } public FqlQuery translate(String sql) throws Exception { ExtendedSqlStatement extendedSqlStatement = metastatementMatcher.parse(sql); if(null != extendedSqlStatement) { ExtendedSqlParser parser = new ExtendedSqlParser(); extendedSqlStatement.receive(parser); return parser.getQuery(); } CCJSqlParserManager ccjSqlParserManager = new CCJSqlParserManager(); Statement statement = ccjSqlParserManager.parse(new StringReader(sql)); Select select = (Select) statement; select.accept(this); ActionRequest request = null; switch (queryType) { case select: { Query query = new Query(); query.setTable(tableName); query.setSort(resultSort); if(hasLimit) { query.setFrom((int)limitFrom); query.setLimit((int) limitCount); } query.setFilters(filters); request = query; break; } case group: { GroupRequest group = new GroupRequest(); group.setTable(tableName); group.setNesting(groupBycolumnsList); group.setFilters(filters); setUniqueCountOn(group); request = group; break; } case trend: { TrendRequest trend = (TrendRequest)calledAction; trend.setTable(tableName); trend.setFilters(filters); request = trend; break; } case statstrend: { StatsTrendRequest statsTrend = (StatsTrendRequest)calledAction; statsTrend.setTable(tableName); statsTrend.setFilters(filters); request = statsTrend; break; } case stats: { StatsRequest stats = (StatsRequest)calledAction; stats.setTable(tableName); stats.setFilters(filters); request = stats; break; } case histogram: { HistogramRequest histogram = (HistogramRequest)calledAction; histogram.setTable(tableName); histogram.setFilters(filters); request = histogram; break; } case count: { CountRequest countRequest = (CountRequest)calledAction; countRequest.setTable(tableName); countRequest.setFilters(filters); request = countRequest; break; } case distinct: { DistinctRequest distinctRequest = new DistinctRequest(); distinctRequest.setTable(tableName); distinctRequest.setFilters(filters); distinctRequest.setNesting(columnsWithSort); request = distinctRequest; } } if(null == request) { throw new Exception("Could not parse provided FQL."); } return new FqlActionQuery(queryType, request, selectedColumns); } private ResultSort generateResultSort(List orderByElements) { if(null == orderByElements) { return null; } for(Object orderByElementObject : orderByElements) { OrderByElement orderByElement = (OrderByElement)orderByElementObject; Column sortColumn = (Column)orderByElement.getExpression(); ResultSort resultSort = new ResultSort(); resultSort.setField(sortColumn.getFullyQualifiedName()); resultSort.setOrder(orderByElement.isAsc()? ResultSort.Order.asc : ResultSort.Order.desc); logger.info("ResultSort: " + resultSort); return resultSort; } return null; } private void setUniqueCountOn(GroupRequest group) { if(calledAction instanceof CountRequest) { CountRequest calledAction = (CountRequest)this.calledAction; boolean distinct = calledAction.isDistinct(); if(distinct) { group.setUniqueCountOn(calledAction.getField()); } } } private List<ResultSort> generateColumnSort(List<OrderByElement> orderItems) { List<ResultSort> resultSortList = Lists.newArrayList(); if (orderItems == null || orderItems.isEmpty()){ return resultSortList; } for (OrderByElement orderByElement : orderItems){ Column sortColumn = (Column)orderByElement.getExpression(); ResultSort resultSort = new ResultSort(); resultSort.setField(sortColumn.getFullyQualifiedName()); resultSort.setOrder(orderByElement.isAsc()? ResultSort.Order.asc : ResultSort.Order.desc); resultSortList.add(resultSort); } return resultSortList; } private static final class FunctionReader extends SqlElementVisitor { private boolean allColumn = false; private ActionRequest actionRequest; public FqlQueryType queryType = FqlQueryType.select; private String columnName = null; @Override public void visit(SelectExpressionItem selectExpressionItem) { Expression expression = selectExpressionItem.getExpression(); if(expression instanceof Function) { Function function = (Function)expression; queryType = getType(function.getName()); switch (queryType) { case trend: actionRequest = parseTrendFunction(function.getParameters().getExpressions()); break; case statstrend: actionRequest = parseStatsTrendFunction(function.getParameters().getExpressions()); break; case stats: actionRequest = parseStatsFunction(function.getParameters().getExpressions()); break; case histogram: actionRequest = parseHistogramRequest(function.getParameters()); break; case count: actionRequest = parseCountRequest(function.getParameters(), function.isAllColumns(), function.isDistinct()); break; case desc: case select: case group: break; } } else { if (expression instanceof Parenthesis){ columnName = ((Column)((Parenthesis)expression).getExpression()).getFullyQualifiedName(); } else if(expression instanceof Column) { columnName = ((Column)expression).getFullyQualifiedName(); } } } private FqlQueryType getType(String function) { if(function.equalsIgnoreCase("trend")) { return FqlQueryType.trend; } if(function.equalsIgnoreCase("statstrend")) { return FqlQueryType.statstrend; } if(function.equalsIgnoreCase("stats")) { return FqlQueryType.stats; } if(function.equalsIgnoreCase("histogram")) { return FqlQueryType.histogram; } if(function.equalsIgnoreCase("count")) { return FqlQueryType.count; } return FqlQueryType.select; } private TrendRequest parseTrendFunction(List expressions) { if(expressions == null || expressions.isEmpty() || expressions.size() > 3) { throw new RuntimeException("trend function has following format: trend(fieldname, [period, [timestamp field]])"); } TrendRequest trendRequest = new TrendRequest(); trendRequest.setField(QueryUtils.expressionToString((Expression) expressions.get(0))); if(expressions.size() > 1) { trendRequest.setPeriod(Period.valueOf(QueryUtils.expressionToString((Expression) expressions.get(1)).toLowerCase())); } if(expressions.size() > 2) { trendRequest.setTimestamp(QueryUtils.expressionToString((Expression) expressions.get(2))); } return trendRequest; } private StatsTrendRequest parseStatsTrendFunction(List expressions) { if(expressions == null || expressions.isEmpty() || expressions.size() > 2) { throw new RuntimeException("statstrend function has following format: statstrend(fieldname, [period])"); } StatsTrendRequest statsTrendRequest = new StatsTrendRequest(); statsTrendRequest.setField(QueryUtils.expressionToString((Expression) expressions.get(0))); if(expressions.size() > 1) { statsTrendRequest.setPeriod(Period.valueOf(QueryUtils.expressionToString((Expression) expressions.get(1)).toLowerCase())); } return statsTrendRequest; } private StatsRequest parseStatsFunction(List expressions) { if(expressions == null || expressions.isEmpty() || expressions.size() > 1) { throw new RuntimeException("stats function has following format: stats(fieldname)"); } StatsRequest statsRequest = new StatsRequest(); statsRequest.setField(QueryUtils.expressionToString((Expression) expressions.get(0))); return statsRequest; } private HistogramRequest parseHistogramRequest(ExpressionList expressionList) { if(expressionList != null && (expressionList.getExpressions() != null && expressionList.getExpressions().size() > 2)) { throw new RuntimeException("histogram function has the following format: histogram([period, [timestamp field]])"); } HistogramRequest histogramRequest = new HistogramRequest(); if(null != expressionList) { List expressions = expressionList.getExpressions(); histogramRequest.setPeriod(Period.valueOf(QueryUtils.expressionToString((Expression) expressions.get(0)).toLowerCase())); if(expressions.size() > 1) { histogramRequest.setField(QueryUtils.expressionToString((Expression) expressions.get(1))); } } return histogramRequest; } private ActionRequest parseCountRequest(ExpressionList expressionList, boolean allColumns, boolean isDistinct) { CountRequest countRequest = new CountRequest(); if (allColumns){ countRequest.setField(null); return countRequest; } if (expressionList != null && (expressionList.getExpressions() != null && expressionList.getExpressions().size() == 1)) { List<Expression> expressions = expressionList.getExpressions(); if (allColumns){ countRequest.setField(null); } else { countRequest.setField(expressionToString(expressions.get(0))); countRequest.setDistinct(isDistinct); } return countRequest; } throw new RuntimeException("count function has the following format: count([distinct] */column_name)"); } private String expressionToString(Expression expression) { if(expression instanceof Column) { return ((Column)expression).getFullyQualifiedName(); } if(expression instanceof StringValue) { return ((StringValue)expression).getValue(); } return null; } @Override public void visit(AllColumns allColumns) { allColumn = true; } public boolean isAllColumn() { return allColumn; } } private static final class FilterParser extends SqlElementVisitor { private List<Filter> filters = Lists.newArrayList(); @Override public void visit(EqualsTo equalsTo) { EqualsFilter equalsFilter = new EqualsFilter(); String field = ((Column)equalsTo.getLeftExpression()).getFullyQualifiedName(); equalsFilter.setField(field.replaceAll(Constants.SQL_FIELD_REGEX, "")); equalsFilter.setValue(getValueFromExpression(equalsTo.getRightExpression())); filters.add(equalsFilter); } @Override public void visit(NotEqualsTo notEqualsTo) { NotEqualsFilter notEqualsFilter = new NotEqualsFilter(); String field = ((Column)notEqualsTo.getLeftExpression()).getFullyQualifiedName(); notEqualsFilter.setField(field.replaceAll(Constants.SQL_FIELD_REGEX, "")); notEqualsFilter.setValue(getValueFromExpression(notEqualsTo.getRightExpression())); filters.add(notEqualsFilter); } @Override public void visit(AndExpression andExpression) { andExpression.getLeftExpression().accept(this); andExpression.getRightExpression().accept(this); } @Override public void visit(Between between) { BetweenFilter betweenFilter = new BetweenFilter(); ColumnData columnData = setupColumn(between.getLeftExpression()); betweenFilter.setField(columnData.getColumnName().replaceAll(Constants.SQL_FIELD_REGEX, "")); betweenFilter.setTemporal(columnData.isTemporal()); Number from = getNumbericValue(between.getBetweenExpressionStart()); Number to = getNumbericValue(between.getBetweenExpressionEnd()); betweenFilter.setFrom(from); betweenFilter.setTo(to); filters.add(betweenFilter); } @Override public void visit(GreaterThan greaterThan) { GreaterThanFilter greaterThanFilter = new GreaterThanFilter(); ColumnData columnData = setupColumn(greaterThan.getLeftExpression()); greaterThanFilter.setField(columnData.getColumnName().replaceAll(Constants.SQL_FIELD_REGEX, "")); greaterThanFilter.setTemporal(columnData.isTemporal()); greaterThanFilter.setValue(getNumbericValue(greaterThan.getRightExpression())); filters.add(greaterThanFilter); } @Override public void visit(GreaterThanEquals greaterThanEquals) { GreaterEqualFilter greaterEqualFilter = new GreaterEqualFilter(); ColumnData columnData = setupColumn(greaterThanEquals.getLeftExpression()); greaterEqualFilter.setField(columnData.getColumnName().replaceAll(Constants.SQL_FIELD_REGEX, "")); greaterEqualFilter.setTemporal(columnData.isTemporal()); greaterEqualFilter.setValue(getNumbericValue(greaterThanEquals.getRightExpression())); filters.add(greaterEqualFilter); } @Override public void visit(InExpression inExpression) { InFilter inFilter = new InFilter(); inFilter.setField(((Column)inExpression.getLeftExpression()).getFullyQualifiedName().replaceAll(Constants.SQL_FIELD_REGEX, "")); ItemsList itemsList = inExpression.getRightItemsList(); if(!(itemsList instanceof ExpressionList)) { throw new RuntimeException("Sub selects not supported"); } ExpressionList expressionList = (ExpressionList)itemsList; List<Object> filterValues = Lists.newArrayList(); for(Object expressionObject : expressionList.getExpressions()) { Expression expression = (Expression) expressionObject; filterValues.add(getValueFromExpression(expression)); } inFilter.setValues(filterValues); filters.add(inFilter); } @Override public void visit(IsNullExpression isNullExpression) { super.visit(isNullExpression); ColumnData columnData = setupColumn(isNullExpression.getLeftExpression()); if (isNullExpression.isNot()) { ExistsFilter existsFilter = new ExistsFilter(); existsFilter.setField(columnData.getColumnName().replaceAll(Constants.SQL_FIELD_REGEX, "")); filters.add(existsFilter); } else { MissingFilter missingFilter = new MissingFilter(); missingFilter.setField(columnData.getColumnName().replaceAll(Constants.SQL_FIELD_REGEX, "")); filters.add(missingFilter); } } @Override public void visit(LikeExpression likeExpression) { super.visit(likeExpression); ContainsFilter containsFilter = new ContainsFilter(); containsFilter.setValue(getStringValue(likeExpression.getRightExpression())); containsFilter.setField(((Column)likeExpression.getLeftExpression()).getFullyQualifiedName().replaceAll(Constants.SQL_FIELD_REGEX, "")); filters.add(containsFilter); } @Override public void visit(MinorThan minorThan) { LessThanFilter lessThanFilter = new LessThanFilter(); ColumnData columnData = setupColumn(minorThan.getLeftExpression()); lessThanFilter.setField(columnData.getColumnName().replaceAll(Constants.SQL_FIELD_REGEX, "")); lessThanFilter.setTemporal(columnData.isTemporal()); lessThanFilter.setValue(getNumbericValue(minorThan.getRightExpression())); filters.add(lessThanFilter); } @Override public void visit(MinorThanEquals minorThanEquals) { LessEqualFilter lessEqualFilter = new LessEqualFilter(); ColumnData columnData = setupColumn(minorThanEquals.getLeftExpression()); lessEqualFilter.setField(columnData.getColumnName().replaceAll(Constants.SQL_FIELD_REGEX, "")); lessEqualFilter.setTemporal(columnData.isTemporal()); lessEqualFilter.setValue(getNumbericValue(minorThanEquals.getRightExpression())); filters.add(lessEqualFilter); } @Override public void visit(Function function) { if(function.getName().equalsIgnoreCase("last")) { LastFilter lastFilter = parseWindowFunction(function.getParameters().getExpressions()); filters.add(lastFilter); return; } throw new RuntimeException("Only last() function is supported"); } private LastFilter parseWindowFunction(List expressions) { if(expressions == null || expressions.isEmpty() || expressions.size() > 3) { throw new RuntimeException("last function has following format: last(duration, [start-time, [timestamp field]])"); } LastFilter lastFilter = new LastFilter(); lastFilter.setDuration(Duration.parse(QueryUtils.expressionToString((Expression) expressions.get(0)))); if(expressions.size() > 1) { lastFilter.setCurrentTime(QueryUtils.expressionToNumber((Expression) expressions.get(1)).longValue()); } if(expressions.size() > 2) { lastFilter.setField(QueryUtils.expressionToString((Expression) expressions.get(2)).replaceAll(Constants.SQL_FIELD_REGEX, "")); } return lastFilter; } private Object getValueFromExpression(Expression expression) { if(expression instanceof StringValue) { return ((StringValue) expression).getValue(); } return getNumbericValue(expression); } private String getStringValue(Expression expression) { if(expression instanceof StringValue) { return ((StringValue) expression).getValue(); } throw new RuntimeException("Unsupported value type."); } private Number getNumbericValue(Expression expression) { if(expression instanceof DoubleValue) { return ((DoubleValue)expression).getValue(); } if(expression instanceof LongValue) { return ((LongValue)expression).getValue(); } if(expression instanceof DateValue) { return ((DateValue)expression).getValue().getTime(); } if(expression instanceof TimeValue) { return ((TimeValue)expression).getValue().getTime(); } throw new RuntimeException("Unsupported value type."); } private static final class ColumnData { private final String columnName; private boolean temporal = false; private boolean window = false; private ColumnData(String columnName) { this.columnName = columnName; } static ColumnData temporal(String columnName) { ColumnData columnData = new ColumnData(columnName); columnData.temporal = true; return columnData; } static ColumnData window(String columnName) { ColumnData columnData = new ColumnData(columnName); columnData.window = true; return columnData; } public String getColumnName() { return columnName; } public boolean isTemporal() { return temporal; } public boolean isWindow() { return window; } } private ColumnData setupColumn(Expression expression) { if(expression instanceof Function) { Function function = (Function) expression; if(function.getName().equalsIgnoreCase("temporal")) { List parameters = function.getParameters().getExpressions(); if(parameters.size() != 1 || ! (parameters.get(0) instanceof Column)) { throw new RuntimeException("temporal function must have a fieldname as parameter"); } return ColumnData.temporal(((Column)parameters.get(0)).getFullyQualifiedName()); } throw new RuntimeException("Only the function 'temporal' is supported in where clause"); } if(expression instanceof Column) { return new ColumnData(((Column)expression).getFullyQualifiedName()); } throw new RuntimeException("Only the function 'temporal([fieldname)' and fieldname is supported in where clause"); } } private static final class ExtendedSqlParser extends SqlElementVisitor { private FqlQuery query; @Override public void visit(Describe describe) { query = new FqlDescribeTable(describe.getTable().getName()); } @Override public void visit(ShowTables showTables) { query = new FqlShowTablesQuery(); } public FqlQuery getQuery() { return query; } } }
package org.jnosql.javaone.gameon.map; import org.jnosql.artemis.graph.EdgeEntity; public interface SiteCreator { SiteFromCreator create(Site site) throws NullPointerException; interface SiteFromCreator { SiteFromCreator from(Site site) throws NullPointerException; } interface SiteDestination { EdgeEntity north(); EdgeEntity south(); EdgeEntity west(); EdgeEntity east(); } }
package org.epics.graphene; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.geom.Path2D; import java.awt.geom.Path2D.Double; import java.util.List; import org.epics.util.array.ListNumber; /** * * @author carcassi */ public class IntensityGraph2DRenderer { private int width = 300; private int height = 200; private ValueColorScheme colorScheme; private boolean rangeFromDataset = true; private double startPlotX = java.lang.Double.MIN_VALUE; private double endPlotX = java.lang.Double.MAX_VALUE; private double startPlotY = java.lang.Double.MIN_VALUE; private double endPlotY = java.lang.Double.MAX_VALUE; private double integratedMinX = java.lang.Double.MAX_VALUE; private double integratedMinY = java.lang.Double.MAX_VALUE; private double integratedMaxX = java.lang.Double.MIN_VALUE; private double integratedMaxY = java.lang.Double.MIN_VALUE; public IntensityGraph2DRenderer(int width, int height) { this.width = width; this.height = height; } public IntensityGraph2DRenderer() { this(300, 200); } public int getImageHeight() { return height; } public int getImageWidth() { return width; } public double getEndPlotX() { return endPlotX; } public double getEndPlotY() { return endPlotY; } public double getIntegratedMaxX() { return integratedMaxX; } public double getIntegratedMaxY() { return integratedMaxY; } public double getIntegratedMinX() { return integratedMinX; } public double getIntegratedMinY() { return integratedMinY; } public double getStartPlotX() { return startPlotX; } public double getStartPlotY() { return startPlotY; } public void update(IntensityGraph2DRendererUpdate update) { if (update.getImageHeight() != null) { height = update.getImageHeight(); } if (update.getImageWidth() != null) { width = update.getImageWidth(); } if (update.isRangeFromDataset() != null) { rangeFromDataset = update.isRangeFromDataset(); } if (update.getStartX() != null) { startPlotX = update.getStartX(); } if (update.getStartY() != null) { startPlotY = update.getStartY(); } if (update.getEndX() != null) { endPlotX = update.getEndX(); } if (update.getEndY() != null) { endPlotY = update.getEndY(); } } public void draw(Graphics2D g, Cell2DDataset data) { // Retain the integrated min/max integratedMinX = java.lang.Double.isNaN(data.getXRange().getMinimum().doubleValue()) ? integratedMinX : Math.min(integratedMinX, data.getXRange().getMinimum().doubleValue()); integratedMinY = java.lang.Double.isNaN(data.getYRange().getMinimum().doubleValue()) ? integratedMinY : Math.min(integratedMinY, data.getYRange().getMinimum().doubleValue()); integratedMaxX = java.lang.Double.isNaN(data.getXRange().getMaximum().doubleValue()) ? integratedMaxX : Math.max(integratedMaxX, data.getXRange().getMaximum().doubleValue()); integratedMaxY = java.lang.Double.isNaN(data.getYRange().getMaximum().doubleValue()) ? integratedMaxY : Math.max(integratedMaxY, data.getYRange().getMaximum().doubleValue()); // Determine range of the plot. // If no range is set, use the one from the dataset double startXPlot; double startYPlot; double endXPlot; double endYPlot; if (rangeFromDataset) { startXPlot = integratedMinX; startYPlot = integratedMinY; endXPlot = integratedMaxX; endYPlot = integratedMaxY; } else { startXPlot = startPlotX; startYPlot = startPlotY; endXPlot = endPlotX; endYPlot = endPlotY; } int margin = 3; g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.setColor(Color.WHITE); g.fillRect(0, 0, width, height); g.setColor(Color.BLACK); // Compute axis ValueAxis xAxis = ValueAxis.createAutoAxis(startXPlot, endXPlot, Math.max(2, width / 60)); ValueAxis yAxis = ValueAxis.createAutoAxis(startYPlot, endYPlot, Math.max(2, height / 60)); HorizontalAxisRenderer xAxisRenderer = new HorizontalAxisRenderer(xAxis, margin, g); VerticalAxisRenderer yAxisRenderer = new VerticalAxisRenderer(yAxis, margin, g); // Compute graph area int xStartGraph = yAxisRenderer.getAxisWidth(); int xEndGraph = width - margin; int yStartGraph = margin; int yEndGraph = height - xAxisRenderer.getAxisHeight(); int plotWidth = xEndGraph - xStartGraph; int plotHeight = yEndGraph - yStartGraph; // Draw axis xAxisRenderer.draw(g, 0, xStartGraph, xEndGraph, width, yEndGraph); yAxisRenderer.draw(g, 0, yStartGraph, yEndGraph, height, xStartGraph); double rangeX = endXPlot - startXPlot; double rangeY = endYPlot - startYPlot; // Draw reference lines g.setColor(new Color(240, 240, 240)); int[] xTicks = xAxisRenderer.horizontalTickPositions(); for (int xTick : xTicks) { g.drawLine(xTick, yStartGraph, xTick, yEndGraph); } int[] yTicks = yAxisRenderer.verticalTickPositions(); for (int yTick : yTicks) { g.drawLine(xStartGraph, height - yTick, xEndGraph, height - yTick); } // Set color scheme colorScheme = ValueColorSchemes.grayScale(data.getStatistics()); //double xBoundaries = data.getXBoundaries().getDouble(3); int countY = 0; int countX = 0; int valuey = 10; int xPosition = xStartGraph; int yPosition = yStartGraph; int xWidthTotal = xEndGraph - xStartGraph; int yHeightTotal = yEndGraph - yStartGraph; int xRange = data.getXBoundaries().getInt(data.getXCount()) - data.getXBoundaries().getInt(0); int yRange = data.getYBoundaries().getInt(data.getYCount()) - data.getYBoundaries().getInt(0); while (countY < data.getYBoundaries().getDouble(data.getYCount())) { int valuex = 0; int cellHeight = ((data.getYBoundaries().getInt(countY) - data.getYBoundaries().getInt(countY+1))/yRange)*yHeightTotal; while (countX < data.getXBoundaries().getDouble(data.getXCount())) { int cellWidth = ((data.getXBoundaries().getInt(countX) - data.getXBoundaries().getInt(countX+1))/xRange)*xWidthTotal; g.setColor(new Color(colorScheme.colorFor(data.getValue(valuex, valuey)))); g.fillRect(xPosition, yPosition, cellWidth, cellHeight); valuex++; countX++; } valuey countY++; } } }
package com.google.gwt.query.client.js; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.core.client.JsArrayString; /** * A Lightweight JSO class to store data. */ public class JsCache extends JavaScriptObject { protected JsCache() { } public static JsCache create() { return createObject().cast(); } public final native void concat(Object ary) /*-{ if (ary) this.concat(ary); }-*/; public final void pushAll(JavaScriptObject prevElem) { JsCache c = prevElem.cast(); for (int i = 0, ilen = c.length(); i < ilen; i++) { put(length(), c.get(i)); } } public final native void delete(int name) /*-{ delete this[name]; }-*/; public final native void delete(String name) /*-{ delete this[name]; }-*/; public final native boolean exists(String name) /*-{ return !!this[name]; }-*/; public final native boolean exists(int id) /*-{ return !!this[id]; }-*/; public final native <T> T get(int id) /*-{ return this[id] || null; }-*/; public final native <T> T get(String id) /*-{ return this[id] || null; }-*/; public final JsCache getCache(int id) { return (JsCache)get(id); } public final native double getDouble(int id) /*-{ return this[id] || 0; }-*/; public final native double getDouble(String id) /*-{ return this[id] || 0; }-*/; public final native int getInt(int id) /*-{ return this[id] || 0; }-*/; public final native int getInt(String id) /*-{ return this[id] || 0; }-*/; public final native String getString(int id) /*-{ return this[id]; }-*/; public final native String getString(String id) /*-{ return this[id] || null; }-*/; public final native boolean isEmpty() /*-{ var foo = ""; for (foo in this) break; return !foo; }-*/; public final native void put(int id, Object obj) /*-{ this[id] = obj; }-*/; public final native void put(String id, Object obj) /*-{ this[id] = obj; }-*/; public final native int length() /*-{ if (typeof(this.length) == 'number') return this.length; var key, ret = 0; // Chrome in DevMode injects a property to JS objects for (key in this) if (key != "__gwt_ObjectId") ret ++; return ret; }-*/; public final int[] indexes() { JsArrayString a = keysImpl(); int[] ret = new int[a.length()]; for (int i = 0; i < a.length(); i++) { try { ret[i] = Integer.valueOf(a.get(i)); } catch (Exception e) { ret[i] = i; } } return ret; } public final String[] keys() { JsArrayString a = keysImpl(); String[] ret = new String[a.length()]; for (int i = 0; i < a.length(); i++) { ret[i] = a.get(i); } return ret; } public final Object[] elements() { String[] keys = keys(); Object[] ret = new Object[keys.length]; int i=0; for (String s: keys) { ret[i++] = get(s); } return ret; } public final String tostring() { String ret = getClass().getName() + "{ "; for (String k: keys()){ ret += k + "=" + get(k) + " "; } return ret + "}"; } private final native JsArrayString keysImpl() /*-{ var key, keys=[]; // Chrome in DevMode injects a property to JS objects for(key in this) if (key != '__gwt_ObjectId') keys.push(String(key)); return keys; }-*/; }
package org.hudsonci.test.ui; import com.thoughtworks.selenium.Selenium; import org.junit.Test; public class FreestyleJobTest extends BaseUITest { private static final String BUILD_SUCCESS_TEXT = "Finished: SUCCESS"; private static final String BUILD_FAILURE_TEXT = "Finished: FAILURE"; private static final String SUBVERSION_LBL_SELECT_EXP = "//label[contains(text(),'Subversion')]"; private static final String GIT_LBL_SELECT_EXP = "//label[contains(text(),'Git')]"; private static final String CVS_LBL_SELECT_EXP = "//label[contains(text(),'CVS')]"; @Test public void testSubversionScm() { Selenium selenium = getSelenium(); selenium.open("/"); waitForTextPresent("New Job"); selenium.click("link=New Job"); selenium.waitForPageToLoad("30000"); selenium.type("name", "subversion-plugin"); selenium.click("mode"); selenium.click("//button[@type='button']"); selenium.waitForPageToLoad("30000"); selenium.click(SUBVERSION_LBL_SELECT_EXP); selenium.type("svn.remote.loc", "https://svn.java.net/svn/hudson~svn/trunk/hudson/plugins/subversion"); selenium.click("//span[@id='yui-gen2']/span/button"); selenium.click("link=Invoke top-level Maven targets"); selenium.type("textarea._.targets", "clean install -DskipTests"); selenium.click("//span[@id='yui-gen19']/span/button"); selenium.waitForPageToLoad("30000"); selenium.click("link=Build Now"); selenium.waitForPageToLoad("30000"); selenium.open("/job/subversion-plugin/1/console"); waitForTextPresent(BUILD_SUCCESS_TEXT, BUILD_FAILURE_TEXT); } @Test public void testGitScm() { Selenium selenium = getSelenium(); selenium.open("/"); waitForTextPresent("New Job"); selenium.click("link=New Job"); selenium.waitForPageToLoad("30000"); selenium.type("name", "git-plugin"); selenium.click("mode"); selenium.click("//button[@type='button']"); selenium.waitForPageToLoad("30000"); selenium.click(GIT_LBL_SELECT_EXP); selenium.type("git.repo.url", "git://github.com/hudson-plugins/git-plugin.git"); selenium.click("//span[@id='yui-gen2']/span/button"); selenium.click("link=Invoke top-level Maven targets"); selenium.type("textarea._.targets", "clean install -DskipTests"); selenium.click("//span[@id='yui-gen19']/span/button"); selenium.waitForPageToLoad("30000"); selenium.click("link=Build Now"); selenium.waitForPageToLoad("30000"); selenium.open("/job/git-plugin/1/console"); waitForTextPresent(BUILD_SUCCESS_TEXT, BUILD_FAILURE_TEXT); } @Test public void testCvsScm() { Selenium selenium = getSelenium(); selenium.open("/"); waitForTextPresent("New Job"); selenium.click("link=New Job"); selenium.waitForPageToLoad("30000"); selenium.type("name", "cvs-plugin"); selenium.click("mode"); selenium.click("//button[@type='button']"); selenium.waitForPageToLoad("30000"); selenium.click(CVS_LBL_SELECT_EXP); selenium.type("cvs_root", ":pserver:anonymous@proftp.cvs.sourceforge.net:2401/cvsroot/proftp"); selenium.click("//span[@id='yui-gen19']/span/button"); selenium.waitForPageToLoad("30000"); selenium.click("link=Build Now"); selenium.waitForPageToLoad("30000"); selenium.open("/job/cvs-plugin/1/console"); waitForTextPresent(BUILD_SUCCESS_TEXT, BUILD_FAILURE_TEXT); } }
package org.intermine.api.profile; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import org.apache.tools.ant.BuildException; import org.intermine.api.template.TemplateQuery; import org.intermine.metadata.ClassDescriptor; import org.intermine.metadata.Model; import org.intermine.model.userprofile.SavedBag; import org.intermine.model.userprofile.UserProfile; import org.intermine.objectstore.ObjectStore; import org.intermine.objectstore.ObjectStoreException; import org.intermine.objectstore.ObjectStoreWriter; import org.intermine.objectstore.query.BagConstraint; import org.intermine.objectstore.query.ConstraintOp; import org.intermine.objectstore.query.Query; import org.intermine.objectstore.query.QueryClass; import org.intermine.objectstore.query.QueryField; import org.intermine.objectstore.query.Results; import org.intermine.objectstore.query.ResultsRow; import org.intermine.pathquery.PathException; import org.intermine.pathquery.PathQuery; public class ModelUpdate { private ObjectStoreWriter uosw; private ProfileManager pm; private Model model; private Model oldModel; private Set<String> deletedClasses = new HashSet<String>(); private Map<String, String> renamedClasses = new HashMap<String, String>(); private Map<String, String> renamedFields = new HashMap<String, String>(); public static final String DELETE = "delete"; public static final String RENAME = "rename-"; public static String OLD = "_OldBackup"; public ModelUpdate(ObjectStore os, ObjectStoreWriter uosw) { this.uosw = uosw; pm = new ProfileManager(os, uosw); model = os.getModel(); oldModel = Model.getInstanceByName("old" + model.getName()); Properties modelUpdateProps = new Properties(); try { modelUpdateProps.load(this.getClass().getClassLoader() .getResourceAsStream("modelUpdate.properties")); } catch (Exception e) { e.printStackTrace(); } loadModelUpdate(modelUpdateProps); } private void loadModelUpdate(Properties modelUpdateProps) { String keyAsString; String className; String fieldName; String update; for(Object key : modelUpdateProps.keySet()) { keyAsString = (String) key; update = (String) modelUpdateProps.getProperty(keyAsString); if (!keyAsString.contains(".")) { //it's a class update className = keyAsString; verifyClassAndField(className, null, oldModel); if (update.equals(DELETE)) { deletedClasses.add(className); } else if (update.contains(RENAME)) { String newClassName = update.replace(RENAME, "").trim(); verifyClassAndField(newClassName, null, model); renamedClasses.put(className, newClassName); } else { throw new BuildException("For the class " + className + " only deleted or renamed- permitted."); } } else { //it's a field update int index = keyAsString.indexOf("."); className = keyAsString.substring(0, index); fieldName = keyAsString.substring(index + 1); verifyClassAndField(className, fieldName, oldModel); if (update.contains(RENAME)) { update = update.replace(RENAME, "").trim(); index = update.indexOf("."); if (index == -1) { throw new BuildException("Field " + keyAsString + " has to contain class.newfield"); } String newClassName = update.substring(0, index); String newFieldName = update.substring(index + 1); if (fieldName.equals(newFieldName)) { throw new BuildException(keyAsString + " = " + RENAME + update + " not permitted. Field has to be renamed. Please check" + " modelUpdate.properties file"); } verifyClassAndField(newClassName, newFieldName, model); if (!className.equals(newClassName)) { //there is a renamed attribute in a renamed class. //add in renamedClasses this renamed class if (!renamedClasses.containsKey(className)) { renamedClasses.put(className, newClassName); } else { if (!renamedClasses.get(className).equals(newClassName)) { throw new BuildException("Class " + className + " has been " + "renamed in two different classes. Please check" + " modelUpdate.properties file"); } } } renamedFields.put(className + "." + fieldName, newFieldName); } else if (!update.contains(DELETE)) { throw new BuildException("For the field " + keyAsString + " only " + DELETE + " or " + RENAME + " permitted."); } } } } private void verifyClassAndField(String className, String fieldName, Model model) throws BuildException { String checkFileMsg = "Please check modelUpdate.properties file"; if ("".equals(className)) { throw new BuildException("Class " + className + " can not be blank. " + checkFileMsg); } ClassDescriptor cd = model.getClassDescriptorByName(className); if (cd == null) { if (fieldName != null) { throw new BuildException("Class " + className + " containing " + fieldName + " not defined in the model " + model.getName() + ". " + checkFileMsg); } else { throw new BuildException("Class " + className + " not defined in the model " + model.getName() + ". " + checkFileMsg); } } if (fieldName != null) { if (fieldName.equals("")) { throw new BuildException("Attribute " + fieldName + " in the class " + className + " can not be blank. " + checkFileMsg); } if (cd.getAttributeDescriptorByName(fieldName) == null && cd.getReferenceDescriptorByName(fieldName) == null && cd.getCollectionDescriptorByName(fieldName) == null) { throw new BuildException("The " + fieldName + " in the class " + className + " not defined in the model " + model.getName() + ". " + checkFileMsg); } } } public Set<String> getDeletedClasses() { return deletedClasses; } public Map<String, String> getRenamedClasses() { return renamedClasses; } public Map<String, String> getRenamedFields() { return renamedFields; } public void update() throws PathException { if(!deletedClasses.isEmpty()) { deleteBags(); } if(!renamedClasses.isEmpty()) { updateTypeBag(); } if(!renamedClasses.isEmpty() || !renamedFields.isEmpty()) { updateReferredQueryAndTemplate(); } } public void deleteBags() { Query q = new Query(); QueryClass qc = new QueryClass(SavedBag.class); q.addToSelect(qc); q.addFrom(qc); QueryField typeField = new QueryField(qc, "type"); BagConstraint constraint = new BagConstraint(typeField, ConstraintOp.IN, deletedClasses); q.setConstraint(constraint); Results bagsToDelete = uosw.execute(q, 1000, false, false, true); for (Iterator i = bagsToDelete.iterator(); i.hasNext();) { ResultsRow row = (ResultsRow) i.next(); SavedBag savedBag = (SavedBag) row.get(0); Profile profile = pm.getProfile(savedBag.getUserProfile().getUsername()); try { profile.deleteBag(savedBag.getName()); System.out.println("Deleted the list: " + savedBag.getName() + " having type " + savedBag.getType()); } catch (ObjectStoreException ose) { System.out.println("Problems deleting bag: " + savedBag.getName()); } } } public void updateTypeBag() { Query q = new Query(); QueryClass qc = new QueryClass(SavedBag.class); q.addToSelect(qc); q.addFrom(qc); QueryField typeField = new QueryField(qc, "type"); BagConstraint constraint = new BagConstraint(typeField, ConstraintOp.IN, renamedClasses.keySet()); q.setConstraint(constraint); Results bagsToUpdate = uosw.execute(q, 1000, false, false, true); for (Iterator i = bagsToUpdate.iterator(); i.hasNext();) { ResultsRow row = (ResultsRow) i.next(); SavedBag savedBag = (SavedBag) row.get(0); String type = savedBag.getType(); String newType = renamedClasses.get(type); Profile profile = pm.getProfile(savedBag.getUserProfile().getUsername()); try { if (newType != null) { profile.updateBagType(savedBag.getName(), newType); System.out.println("Updated the type of the list: " + savedBag.getName()); } } catch (ObjectStoreException ose) { System.out.println("Problems updating savedBag " + savedBag.getName() + ose.getMessage()); } } } public void updateReferredQueryAndTemplate() throws PathException { Map<String, SavedQuery> savedQueries; Map<String, TemplateQuery> templateQueries; String cls, prevField; List<String> problems; Query q = new Query(); QueryClass qc = new QueryClass(UserProfile.class); q.addToSelect(qc); q.addFrom(qc); Results userprofiles = uosw.execute(q, 1000, false, false, true); for (Iterator i = userprofiles.iterator(); i.hasNext();) { ResultsRow row = (ResultsRow) i.next(); UserProfile user = (UserProfile) row.get(0); Profile profile = pm.getProfile(user.getUsername()); savedQueries = new HashMap<String, SavedQuery>(profile.getSavedQueries()); for (SavedQuery savedQuery : savedQueries.values()) { PathQuery pathQuery = savedQuery.getPathQuery(); if (!savedQuery.getName().contains(OLD) && !pathQuery.isValid()) { PathQueryUpdate pathQueryUpdate = new PathQueryUpdate(pathQuery, model, oldModel); try { problems = pathQueryUpdate.update(renamedClasses, renamedFields); if (!problems.isEmpty()) { System.out.println("Problems updating pathQuery in savedQuery " + savedQuery.getName() + ". " + problems); continue; } if (pathQueryUpdate.isUpdated()) { SavedQuery updatedSavedQuery = new SavedQuery(savedQuery.getName(), savedQuery.getDateCreated(), pathQueryUpdate.getUpdatedPathQuery()); profile.deleteQuery(savedQuery.getName()); String backupSavedQueryName = savedQuery.getName() + OLD; SavedQuery backupSavedQuery = new SavedQuery(backupSavedQueryName, savedQuery.getDateCreated(), savedQuery.getPathQuery()); profile.saveQuery(backupSavedQueryName, backupSavedQuery); profile.saveQuery(savedQuery.getName(), updatedSavedQuery); System.out.println("Updated the saved query: " + savedQuery.getName()); } } catch (PathException pe) { System.out.println("Problems updating pathQuery in savedQuery " + savedQuery.getName() + " caused by the wrong path " + pe.getPathString()); continue; } } } templateQueries = new HashMap<String, TemplateQuery>(profile.getSavedTemplates()); for (TemplateQuery templateQuery : templateQueries.values()) { PathQuery pathQuery = templateQuery.getPathQuery(); if (!templateQuery.getName().contains(OLD) && !pathQuery.isValid()) { TemplateQueryUpdate templateQueryUpdate = new TemplateQueryUpdate(templateQuery, model, oldModel); try { problems = templateQueryUpdate.update(renamedClasses, renamedFields); if (!problems.isEmpty()) { System.out.println("Problems updating pathQuery in templateQuery " + templateQuery.getName() + ". " + problems); continue; } if (templateQueryUpdate.isUpdated()) { TemplateQuery updatedTemplateQuery = templateQueryUpdate.getNewTemplateQuery(); String backupTemplateName = templateQuery.getName() + OLD; TemplateQuery backupTemplateQuery = templateQuery.clone(); backupTemplateQuery.setName(backupTemplateName); profile.saveTemplate(backupTemplateName, backupTemplateQuery); profile.saveTemplate(templateQuery.getName(), updatedTemplateQuery); System.out.println("Updated the template query: " + templateQuery.getName()); } } catch (PathException pe) { System.out.println("Problems updating pathQuery in templateQuery " + templateQuery.getName() + " caused by the wrong path " + pe.getPathString()); continue; } } } } } }
package org.intermine.dataloader; /** * Represents a data source, by name and skeleton status. * * @author Matthew Wakeling */ public class Source { private String name; private boolean skeleton; /** * Getter for name. * * @return a String */ public String getName() { return name; } /** * Setter for name. * * @param name a String */ public void setName(String name) { this.name = name; } /** * Getter for skeleton. * * @return a boolean */ public boolean getSkeleton() { return skeleton; } /** * Setter for skeleton. * * @param skeleton a boolean */ public void setSkeleton(boolean skeleton) { this.skeleton = skeleton; } /** * @see Object#toString() */ public String toString() { return "<Source: name=\"" + getName() + "\", skeleton=" + getSkeleton() + ">"; } }
package org.intermine.web.struts; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionMapping; /** * Form to handle input from the template page * @author Mark Woodbridge */ public class TemplateForm extends ActionForm { private Map<String, Object> attributeOps; private Map<String, Object> attributeValues; private Map<String, String[]> multiValues; private Map<String, String> multiValueAttribute; private Map<String, Boolean> useBagConstraint; private Map<String, Object> extraValues, selectedBags; private Map<String, Object> nullConstraint; private Map<String, String> bagOps; private Map<String, String> switchOff; private String scope, name, view; /** * Constructor */ public TemplateForm() { super(); reset(); } /** * Set the attribute ops * @param attributeOps the attribute ops */ public void setAttributeOps(Map<String, Object> attributeOps) { this.attributeOps = attributeOps; } /** * Get the attribute ops * @return the attribute ops */ public Map<String, Object> getAttributeOps() { return attributeOps; } /** * Set an attribute op * @param key the key * @param value the value */ public void setAttributeOps(String key, String value) { attributeOps.put(key, value); } /** * Get an attribute op * @param key the key * @return the value */ public Object getAttributeOps(String key) { return attributeOps.get(key); } /** * Set the nullConstraint * @param nullConstraint the nullConstraint */ public void setNullConstraint(Map<String, Object> nullConstraint) { this.nullConstraint = nullConstraint; } /** * Get the nullConstraint * @return the nullConstraint */ public Map<String, Object> getNullConstraint() { return nullConstraint; } /** * Set a nullConstraint * @param key the key * @param value the value */ public void setNullConstraint(String key, String value) { nullConstraint.put(key, value); } /** * Get a nullConstraint * @param key the key * @return the value */ public Object getNullConstraint(String key) { return nullConstraint.get(key); } /** * Set the attribute values * @param attributeValues the attribute values */ public void setAttributeValues(Map<String, Object> attributeValues) { this.attributeValues = attributeValues; } /** * Get the attribute values * @return the attribute values */ public Map<String, Object> getAttributeValues() { return attributeValues; } /** * Set an attribute value * @param key the key * @param value the value */ public void setAttributeValues(String key, Object value) { attributeValues.put(key, value); } /** * Get an attribute value * @param key the key * @return the value */ public Object getAttributeValues(String key) { return attributeValues.get(key); } /** * Set the multiValues * @param multiValues the multi values */ public void setMultiValues(Map<String, String[]> multiValues) { this.multiValues = multiValues; } /** * Returns the multiValues * @return the map containing the multi values */ public Map<String, String[]> getMultiValues() { return this.multiValues; } /** * Get a multi value * @param key the key * @return the value */ public String[] getMultiValues(String key) { return multiValues.get(key); } /** * Set a multiselect attribute value * @param key the key * @param values the value */ public void setMultiValues(String key, String[] values) { multiValues.put(key, values); String multiValueAttributeTemp = ""; for (String value : values) { if (!"".equals(multiValueAttributeTemp)) { multiValueAttributeTemp += ","; } multiValueAttributeTemp += value; } setMultiValueAttribute(key, multiValueAttributeTemp); } /** * Set the multivalueattribute * @param multiValueAttribute the map containing the multiVAlueAttribute */ public void setMultiValueAttribute(Map<String, String> multiValueAttribute) { this.multiValueAttribute = multiValueAttribute; } /** * Returns the multivalueattribute * @return the map containing the multiVAlueAttribute */ public Map<String, String> getMultiValueAttribute() { return this.multiValueAttribute; } /** * Returns the multivalueattribute given a key * @param key the key * @return multiVAlueAttribute */ public String getMultiValueAttribute(String key) { return multiValueAttribute.get(key); } /** * Set the multivalueattribute * @param key the key * @param value the value */ public void setMultiValueAttribute(String key, String value) { multiValueAttribute.put(key, value); } /** * Sets the extra values * @param extraValues the extra values */ public void setExtraValues(Map<String, Object> extraValues) { this.extraValues = extraValues; } /** * Get the extra values * @return the extra values */ public Map<String, Object> getExtraValues() { return extraValues; } /** * Set an extra value * @param key the key * @param value the value */ public void setExtraValues(String key, Object value) { extraValues.put(key, value); } /** * Get an extra value * @param key the key * @return the value */ public Object getExtraValues(String key) { return extraValues.get(key); } /** * Set value of useBagConstraint for given constraint key. * @param key the key * @param value the value */ public void setUseBagConstraint(String key, boolean value) { useBagConstraint.put(key, value ? Boolean.TRUE : Boolean.FALSE); } /** * Get the value of useBagConstraint for given constraint key. * @param key the key * @return the value */ public boolean getUseBagConstraint(String key) { return Boolean.TRUE.equals(useBagConstraint.get(key)); } /** * Set the bag name. * @param key the key * @param bag bag name */ public void setBag(String key, Object bag) { selectedBags.put(key, bag); } /** * Get the bag name selected. * @param key the key * @return the bag selected */ public Object getBag(String key) { return selectedBags.get(key); } /** * Get the bag operation selected. * @param key the key * @return the bag operation selected */ public String getBagOp(String key) { return bagOps.get(key); } /** * Set bag operation. * @param bagOp the bag operation selected * @param key the key */ public void setBagOp(String key, String bagOp) { bagOps.put(key, bagOp); } /** * Get the template name. * @return the template name */ public String getName() { return name; } /** * Set the template name. * @param templateName the template name */ public void setName(String templateName) { this.name = templateName; } /** * Get the selected alternative view name. * @return selected alternative view name */ public String getView() { return view; } /** * Set the selected alternative view name. * @param view selected alternative view name */ public void setView(String view) { this.view = view; } /** * Get the template scope. * @return the template scope */ public String getScope() { return scope; } /** * Set the template scope. * @param scope the template scope */ public void setScope(String scope) { this.scope = scope; } /** * Get the SwitchOff ability. * @param key the key * @return the SwitchOff */ public String getSwitchOff(String key) { return switchOff.get(key); } /** * Set the SwitchOff ability. * @param key the key * @param switchOffAbility the switchOffAbility */ public void setSwitchOff(String key, String switchOffAbility) { this.switchOff.put(key, switchOffAbility); } /** * {@inheritDoc} */ public void reset(@SuppressWarnings("unused") ActionMapping mapping, @SuppressWarnings("unused") HttpServletRequest request) { reset(); } /** * Reset the form */ protected void reset() { attributeOps = new HashMap<String, Object>(); attributeValues = new HashMap<String, Object>(); multiValues = new HashMap<String, String[]>(); multiValueAttribute = new HashMap<String, String>(); useBagConstraint = new HashMap<String, Boolean>(); selectedBags = new HashMap<String, Object>(); bagOps = new HashMap<String, String>(); extraValues = new HashMap<String, Object>(); nullConstraint = new HashMap<String, Object>(); switchOff = new HashMap<String, String>(); name = null; scope = null; view = ""; } }
package cn.cerc.ui.fields; import cn.cerc.core.Record; import cn.cerc.ui.parts.UIComponent; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class RadioField extends AbstractField { private final List<String> items = new ArrayList<>(); public RadioField(UIComponent owner, String name, String field, int width) { super(owner, name, width); this.setField(field); } @Override public String getText(Record record) { if (record == null) { return null; } int val = record.getInt(field); if (val < 0 || val > items.size() - 1) { return "" + val; } String result = items.get(val); if (result == null) { return "" + val; } else { return result; } } public RadioField add(String... items) { this.items.addAll(Arrays.asList(items)); return this; } }
package de.kimminich.kata.tcg.strategy; import org.junit.Test; import java.util.OptionalInt; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; public class SmartStrategyTest { Strategy strategy; @Test public void smartStrategyShouldPlayCardsToMaximizeCombinedDamage() { strategy = new SmartStrategy(); assertThat(strategy.nextCard(10, new int[]{2, 2, 3, 8, 9}), is(card(8))); assertThat(strategy.nextCard(2, new int[]{2, 2, 3, 9}), is(card(2))); assertThat(strategy.nextCard(10, new int[]{1, 2, 2, 3, 8, 9}), is(card(9))); assertThat(strategy.nextCard(1, new int[]{1, 2, 2, 3, 8}), is(card(1))); assertThat(strategy.nextCard(10, new int[]{2, 3, 4, 5}), is(card(5))); assertThat(strategy.nextCard(5, new int[]{2, 3, 4}), is(card(3))); assertThat(strategy.nextCard(2, new int[]{2, 4}), is(card(2))); } @Test public void strategyShouldReturnNoCardIfInsufficientManaForAnyHandCard() { strategy = new SmartStrategy(); assertThat(strategy.nextCard(1, new int[]{2, 3, 8}), is(noCard())); } private OptionalInt card(int card) { return OptionalInt.of(card); } private OptionalInt noCard() { return OptionalInt.empty(); } }
package net.fortuna.ical4j.model.component; import junit.framework.TestCase; import net.fortuna.ical4j.model.Calendar; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.util.TimeZone; /** * A test case for VTimeZone. * * @author benfortuna */ public class VTimeZoneTest extends TestCase { private static Log log = LogFactory.getLog(VTimeZoneTest.class); public final void testGetDefault() { VTimeZone timezone = VTimeZone.getDefault(); assertNotNull(timezone); log.debug(timezone); } /** * Test creation of specific timezones. */ public final void testGetVTimeZone() { TimeZone tz = TimeZone.getTimeZone("Asia/Singapore"); VTimeZone timezone = VTimeZone.getVTimeZone(tz.getID()); assertNotNull(timezone); log.info(timezone); } public void testCreateDefinition() { Calendar calendar = new Calendar(); calendar.getComponents().add(VTimeZone.getDefault()); log.info(calendar); } public void testGetTimeZone() { VTimeZone melbourne = VTimeZone.getVTimeZone("Australia/Melbourne"); log.info("VTimeZone (Melbourne): " + melbourne); log.info("VTimeZone (Melbourne): " + melbourne.getTimeZone()); VTimeZone vTz = VTimeZone.getDefault(); log.info("VTimeZone: " + vTz.getTimeZone()); TimeZone tz = TimeZone.getDefault(); log.info("TimeZone: " + tz); assertTrue("Timezone rules are not the same", vTz.getTimeZone().hasSameRules(tz)); } }
package net.ssehub.kernel_haven.config; import static net.ssehub.kernel_haven.config.Setting.Type.BOOLEAN; import java.util.Properties; import org.junit.Assert; import org.junit.Test; import net.ssehub.kernel_haven.SetUpException; /** * Tests the {@link Configuration}. * @author El-Sharkawy * */ public class ConfigurationTest { /** * Tests that Boolean config values are handled correctly by the {@link Configuration}. * @throws SetUpException Must not occur, is not tested by this test. */ @Test public void testBooleanValues() throws SetUpException { Setting<Boolean> falseValue = new Setting<>("value.false", BOOLEAN, false, "false", ""); Setting<Boolean> trueValue = new Setting<>("value.true", BOOLEAN, false, "true", ""); Setting<Boolean> overwriteableValue = new Setting<>("value.x", BOOLEAN, false, "true", ""); Properties prop = new Properties(); prop.setProperty(overwriteableValue.getKey(), "false"); Configuration config = new Configuration(prop); config.registerSetting(falseValue); config.registerSetting(trueValue); config.registerSetting(overwriteableValue); boolean value = config.getValue(falseValue); Assert.assertFalse("False value is treated as true", value); value = config.getValue(trueValue); Assert.assertTrue("True value is treated as false", value); value = config.getValue(overwriteableValue); Assert.assertFalse("False value is treated as true", value); } }
package jenkins.widgets; import com.gargoylesoftware.htmlunit.html.HtmlAnchor; import com.gargoylesoftware.htmlunit.html.HtmlPage; import hudson.model.FreeStyleProject; import hudson.model.ListView; import java.net.URI; import java.net.URL; import org.junit.Test; import static org.junit.Assert.*; import org.junit.Rule; import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.MockFolder; public class BuildListTableTest { @Rule public JenkinsRule r = new JenkinsRule(); @Issue("JENKINS-19310") @Test public void linksFromFolders() throws Exception { MockFolder d = r.createFolder("d"); ListView v1 = new ListView("v1", r.jenkins); v1.add(d); r.jenkins.addView(v1); MockFolder d2 = d.createProject(MockFolder.class, "d2"); FreeStyleProject p = d2.createProject(FreeStyleProject.class, "p"); r.buildAndAssertSuccess(p); ListView v2 = new ListView("v2", d); v2.setRecurse(true); v2.add(p); d.addView(v2); JenkinsRule.WebClient wc = r.createWebClient(); HtmlPage page = wc.goTo("view/v1/job/d/view/v2/builds?suppressTimelineControl=true"); assertEquals(0, wc.waitForBackgroundJavaScript(120000)); HtmlAnchor anchor = page.getAnchorByText("d » d2 » p"); String href = anchor.getHrefAttribute(); URL target = URI.create(page.getUrl().toExternalForm()).resolve(href).toURL(); wc.getPage(target); assertEquals(href, r.getURL() + "view/v1/job/d/view/v2/job/d2/job/p/", target.toString()); page = wc.goTo("job/d/view/All/builds?suppressTimelineControl=true"); assertEquals(0, wc.waitForBackgroundJavaScript(120000)); anchor = page.getAnchorByText("d » d2 » p"); href = anchor.getHrefAttribute(); target = URI.create(page.getUrl().toExternalForm()).resolve(href).toURL(); wc.getPage(target); assertEquals(href, r.getURL() + "job/d/job/d2/job/p/", target.toString()); } }
package play.test; import akka.actor.ActorSystem; import akka.actor.Terminated; import akka.stream.Materializer; import akka.util.ByteString; import org.hamcrest.CoreMatchers; import org.junit.Test; import play.Application; import play.mvc.Http; import play.mvc.Result; import play.mvc.Results; import play.twirl.api.Content; import play.twirl.api.Html; import scala.concurrent.Await; import scala.concurrent.Future; import scala.concurrent.duration.Duration; import java.util.HashMap; import java.util.Map; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertThat; public class HelpersTest { @Test public void shouldCreateASimpleFakeRequest() { Http.RequestImpl request = Helpers.fakeRequest().build(); assertThat(request.method(), equalTo("GET")); assertThat(request.path(), equalTo("/")); } @Test public void shouldCreateAFakeRequestWithMethodAndUri() { Http.RequestImpl request = Helpers.fakeRequest("POST", "/my-uri").build(); assertThat(request.method(), equalTo("POST")); assertThat(request.path(), equalTo("/my-uri")); } @Test public void shouldAddHostHeaderToFakeRequests() { Http.RequestImpl request = Helpers.fakeRequest().build(); assertThat(request.host(), equalTo("localhost")); } @Test public void shouldCreateFakeApplicationsWithAnInMemoryDatabase() { Application application = Helpers.fakeApplication(Helpers.inMemoryDatabase()); assertThat(application.config().getString("db.default.driver"), CoreMatchers.notNullValue()); assertThat(application.config().getString("db.default.url"), CoreMatchers.notNullValue()); } @Test public void shouldCreateFakeApplicationsWithAnNamedInMemoryDatabase() { Application application = Helpers.fakeApplication(Helpers.inMemoryDatabase("testDb")); assertThat(application.config().getString("db.testDb.driver"), CoreMatchers.notNullValue()); assertThat(application.config().getString("db.testDb.url"), CoreMatchers.notNullValue()); } @Test public void shouldCreateFakeApplicationsWithAnNamedInMemoryDatabaseAndConnectionOptions() { Map<String, String> options = new HashMap<>(); options.put("username", "testUsername"); options.put("ttl", "10"); Application application = Helpers.fakeApplication(Helpers.inMemoryDatabase("testDb", options)); assertThat(application.config().getString("db.testDb.driver"), CoreMatchers.notNullValue()); assertThat(application.config().getString("db.testDb.url"), CoreMatchers.notNullValue()); assertThat( application.config().getString("db.testDb.url"), CoreMatchers.containsString("username")); assertThat(application.config().getString("db.testDb.url"), CoreMatchers.containsString("ttl")); } @Test public void shouldExtractContentAsBytesFromAResult() { Result result = Results.ok("Test content"); ByteString contentAsBytes = Helpers.contentAsBytes(result); assertThat(contentAsBytes, equalTo(ByteString.fromString("Test content"))); } @Test public void shouldExtractContentAsBytesFromAResultUsingAMaterializer() throws Exception { ActorSystem actorSystem = ActorSystem.create("TestSystem"); try { Materializer mat = Materializer.matFromSystem(actorSystem); Result result = Results.ok("Test content"); ByteString contentAsBytes = Helpers.contentAsBytes(result, mat); assertThat(contentAsBytes, equalTo(ByteString.fromString("Test content"))); } finally { Future<Terminated> future = actorSystem.terminate(); Await.result(future, Duration.create("5s")); } } @Test public void shouldExtractContentAsBytesFromTwirlContent() { Content content = Html.apply("Test content"); ByteString contentAsBytes = Helpers.contentAsBytes(content); assertThat(contentAsBytes, equalTo(ByteString.fromString("Test content"))); } @Test public void shouldExtractContentAsStringFromTwirlContent() { Content content = Html.apply("Test content"); String contentAsString = Helpers.contentAsString(content); assertThat(contentAsString, equalTo("Test content")); } @Test public void shouldExtractContentAsStringFromAResult() { Result result = Results.ok("Test content"); String contentAsString = Helpers.contentAsString(result); assertThat(contentAsString, equalTo("Test content")); } @Test public void shouldExtractContentAsStringFromAResultUsingAMaterializer() throws Exception { ActorSystem actorSystem = ActorSystem.create("TestSystem"); try { Materializer mat = Materializer.matFromSystem(actorSystem); Result result = Results.ok("Test content"); String contentAsString = Helpers.contentAsString(result, mat); assertThat(contentAsString, equalTo("Test content")); } finally { Future<Terminated> future = actorSystem.terminate(); Await.result(future, Duration.create("5s")); } } @Test public void shouldSuccessfullyExecutePostRequestWithEmptyBody() { Http.RequestBuilder request = Helpers.fakeRequest("POST", "/uri"); Application app = Helpers.fakeApplication(); Result result = Helpers.route(app, request); assertThat(result.status(), equalTo(404)); } }
package playn.tests.core; import java.util.ArrayList; import java.util.List; import pythagoras.f.FloatMath; import pythagoras.f.Rectangle; import playn.core.ImmediateLayer; import playn.core.AssetWatcher; import playn.core.GroupLayer; import playn.core.Image; import playn.core.Pattern; import playn.core.Surface; import playn.core.SurfaceLayer; import static playn.core.PlayN.*; public class SurfaceTest extends Test { private List<SurfaceLayer> dots = new ArrayList<SurfaceLayer>(); private SurfaceLayer paintUpped; private Rectangle dotBox; private float elapsed; @Override public String getName() { return "SurfaceTest"; } @Override public String getDescription() { return "Tests various Surface rendering features."; } @Override public void init() { final Image tile = assets().getImage("images/tile.png"); final Image orange = assets().getImage("images/orange.png"); AssetWatcher watcher = new AssetWatcher(new AssetWatcher.Listener() { public void done() { addTests(orange, tile); } public void error(Throwable err) { addDescrip("Error: " + err.getMessage(), 10, errY, graphics().width()-20); errY += 30; } private float errY = 10; }); watcher.add(tile); watcher.add(orange); watcher.start(); } @Override public void dispose() { dots.clear(); paintUpped = null; } protected void addTests (final Image orange, Image tile) { final Pattern pattern = tile.toPattern(); int samples = 128; // big enough to force a buffer size increase final float[] verts = new float[(samples+1)*4]; final int[] indices = new int[samples*6]; tessellateCurve(0, 40*(float)Math.PI, verts, indices, new F() { public float apply (float x) { return (float)Math.sin(x/20)*50; } }); float ygap = 20, ypos = 10; // draw some wide lines ypos = ygap + addTest(10, ypos, new ImmediateLayer.Renderer() { public void render (Surface surf) { drawLine(surf, 0, 0, 50, 50, 15); drawLine(surf, 70, 50, 120, 0, 10); drawLine(surf, 0, 70, 120, 120, 10); } }, 120, 120, "drawLine with width"); ypos = ygap + addTest(20, ypos, new ImmediateLayer.Renderer() { public void render (Surface surf) { surf.setFillColor(0xFF0000FF).fillRect(0, 0, 100, 25); // these two alpha fills should look the same surf.setFillColor(0x80FF0000).fillRect(0, 0, 50, 25); surf.setAlpha(0.5f).setFillColor(0xFFFF0000).fillRect(50, 0, 50, 25).setAlpha(1f); } }, 100, 25, "left and right half both same color"); ypos = ygap + addTest(20, ypos, new ImmediateLayer.Renderer() { public void render (Surface surf) { surf.setFillColor(0xFF0000FF).fillRect(0, 0, 100, 50); surf.setAlpha(0.5f); surf.drawImage(orange, 55, 5); surf.fillRect(0, 50, 50, 50); surf.drawImage(orange, 55, 55); surf.setAlpha(1f); } }, 100, 100, "fillRect and drawImage at 50% alpha"); ypos = 10; ypos = ygap + addTest(160, ypos, new ImmediateLayer.Renderer() { public void render (Surface surf) { // fill some shapes with patterns surf.setFillPattern(pattern).fillRect(10, 0, 100, 100); // use same fill pattern for the triangles surf.translate(0, 160); surf.fillTriangles(verts, indices); } }, 120, 210, "ImmediateLayer patterned fillRect, fillTriangles"); SurfaceLayer slayer = graphics().createSurfaceLayer(100, 100); slayer.surface().setFillPattern(pattern).fillRect(0, 0, 100, 100); ypos = ygap + addTest(170, ypos, slayer, "SurfaceLayer patterned fillRect"); ypos = 10; // fill a patterned quad in a clipped group layer final int twidth = 150, theight = 75; GroupLayer group = graphics().createGroupLayer(); ypos = ygap + addTest(315, 10, group, twidth, theight, "Clipped pattern should not exceed grey rectangle"); group.add(graphics().createImmediateLayer(new ImmediateLayer.Renderer() { public void render (Surface surf) { surf.setFillColor(0xFFCCCCCC).fillRect(0, 0, twidth, theight); } })); group.add(graphics().createImmediateLayer(twidth, theight, new ImmediateLayer.Renderer() { public void render (Surface surf) { surf.setFillPattern(pattern).fillRect(-10, -10, twidth+20, theight+20); } })); // draw some randomly jiggling dots inside a bounded region dotBox = new Rectangle(315, ypos, 200, 100); ypos = ygap + addTest(dotBox.x, dotBox.y, new ImmediateLayer.Renderer() { public void render (Surface surf) { surf.setFillColor(0xFFCCCCCC).fillRect(0, 0, dotBox.width, dotBox.height); } }, dotBox.width, dotBox.height, "Randomly positioned SurfaceLayers"); for (int ii = 0; ii < 10; ii++) { SurfaceLayer dot = graphics().createSurfaceLayer(10, 10); dot.surface().setFillColor(0xFFFF0000); dot.surface().fillRect(0, 0, 5, 5); dot.surface().fillRect(5, 5, 5, 5); dot.surface().setFillColor(0xFF0000FF); dot.surface().fillRect(5, 0, 5, 5); dot.surface().fillRect(0, 5, 5, 5); dot.setTranslation(dotBox.x + random()*(dotBox.width-10), dotBox.y + random()*(dotBox.height-10)); dots.add(dot); // System.err.println("Created dot at " + dot.transform()); graphics().rootLayer().add(dot); } // add a surface layer that is updated on every call to paint (a bad practice, but one that // should actually work) paintUpped = graphics().createSurfaceLayer(100, 100); ypos = ygap + addTest(315, ypos, paintUpped, "SurfaceLayer updated in paint()"); } protected float addTest(float lx, float ly, ImmediateLayer.Renderer renderer, float lwidth, float lheight, String descrip) { return addTest(lx, ly, graphics().createImmediateLayer(renderer), lwidth, lheight, descrip); } @Override public void update(float delta) { super.update(delta); elapsed += delta; } @Override public void paint(float alpha) { super.paint(alpha); for (SurfaceLayer dot : dots) { if (random() > 0.95) { dot.setTranslation(dotBox.x + random()*(dotBox.width-10), dotBox.y + random()*(dotBox.height-10)); } } if (paintUpped != null) { float sin = Math.abs(FloatMath.sin(elapsed)), cos = Math.abs(FloatMath.cos(elapsed)); int sinColor = (int)(sin * 255), cosColor = (int)(cos * 255); int c1 = (0xFF << 24) | (sinColor << 16) | (cosColor << 8); int c2 = (0xFF << 24) | (cosColor << 16) | (sinColor << 8); paintUpped.surface().clear(); paintUpped.surface().setFillColor(c1).fillRect(0, 0, 50, 50); paintUpped.surface().setFillColor(c2).fillRect(50, 50, 50, 50); } } void drawLine(Surface surf, float x1, float y1, float x2, float y2, float width) { float xmin = Math.min(x1, x2), xmax = Math.max(x1, x2); float ymin = Math.min(y1, y2), ymax = Math.max(y1, y2); surf.setFillColor(0xFF0000AA); surf.fillRect(xmin, ymin, xmax-xmin, ymax-ymin); surf.setFillColor(0xFF99FFCC); surf.drawLine(x1, y1, x2, y2, width); surf.setFillColor(0xFFFF0000); surf.fillRect(x1, y1, 1, 1); surf.fillRect(x2, y2, 1, 1); } private interface F { public float apply (float x); } void tessellateCurve (float minx, float maxx, float[] verts, int[] indices, F f) { int slices = (verts.length-1)/4, vv = 0; float dx = (maxx-minx)/slices; for (float x = minx; x < maxx; x += dx) { verts[vv++] = x; verts[vv++] = 0; verts[vv++] = x; verts[vv++] = f.apply(x); } for (int ss = 0, ii = 0; ss < slices; ss++) { int base = ss*2; indices[ii++] = base; indices[ii++] = base+1; indices[ii++] = base+3; indices[ii++] = base; indices[ii++] = base+3; indices[ii++] = base+2; } } }
package main.java.org.wikidata.analyzer; import main.java.org.wikidata.analyzer.Fetcher.DumpDateFetcher; import main.java.org.wikidata.analyzer.Processor.*; import main.java.org.wikidata.analyzer.Fetcher.DumpFetcher; import org.wikidata.wdtk.dumpfiles.DumpProcessingController; import org.wikidata.wdtk.dumpfiles.MwDumpFile; import java.io.*; import java.nio.file.Files; import java.util.*; /** * @author Addshore */ public class WikidataAnalyzer { /** * Folder that all data should be stored in */ private File dataDir = null; /** * The target date string */ private String targetDate; /** * A list of processorClasses that need to be run */ private List<Class<?>> processorClasses = new ArrayList<>(); /** * A list of processor objects that are being run */ private List<WikidataAnalyzerProcessor> processorObjects = new ArrayList<>(); /** * Main entry point. * Instantiates and runs the analyzer * * @param args Command line arguments */ public static void main(String[] args) throws IOException { WikidataAnalyzer analyzer = new WikidataAnalyzer(); analyzer.run(args); } /** * Main entry point of the WikidataAnalyzer class * * @param args Command line arguments * A collection of Processors to run (each as a single argument) eg. BadDate Map * The data directory to use eg. ~/data * The date of the dump to target eg. latest OR 20151230 * eg. java -Xmx2g -jar ~/wikidata-analyzer.jar Reference ~/data latest */ public void run( String[] args ) { this.printHeader(); long startTime = System.currentTimeMillis(); try { this.scan(args); System.out.println("All Done!"); } catch (IOException e) { System.out.println("Something went wrong!"); e.printStackTrace(); } long elapsedSeconds = (System.currentTimeMillis() - startTime) / 1000; System.out.println("Execution time: " + elapsedSeconds / 60 + ":" + elapsedSeconds % 60); } private void printHeader() { System.out.println("**************************************************************************************"); System.out.println("*** Wikidata Toolkit: ToolkitAnalyzer ***"); System.out.println("********************************** Example Usage ************************************"); System.out.println("* toolkit-analyzer.jar Metric ~/toolkit-analyzer/data latest *"); System.out.println("* toolkit-analyzer.jar Metric ~/toolkit-analyzer/data 20160104 *"); System.out.println("* toolkit-analyzer.jar BadDate Map MonolingualTest ~/toolkit-analyzer/data 20150104 *"); System.out.println("******************************* Data Directory Layout ********************************"); System.out.println("* Data directory: data/ *"); System.out.println("* Downloaded dump locations: data/dumpfiles/json-<DATE>/<DATE>-all.json.gz *"); System.out.println("* Processor output location: data/<DATE>/ *"); System.out.println("**************************************************************************************"); } private void printMemoryWarning() { // Check memory limit if (Runtime.getRuntime().maxMemory() / 1024 / 1024 <= 1500) { System.out.println("WARNING: You may need to increase your memory limit!"); } } public void scan(String[] args) throws IOException { // Get the parameters try { targetDate = args[args.length - 1]; dataDir = new File(args[args.length - 2]); } catch (ArrayIndexOutOfBoundsException exception) { System.out.println("Error: Not enough parameters. You must pass a data dir and a target date!"); System.exit(1); } this.printMemoryWarning(); // Check the date if (targetDate.equals("latest")) { DumpDateFetcher dateFetcher = new DumpDateFetcher(); targetDate = dateFetcher.getLatestOnlineDumpDate(); System.out.println("Targeting latest dump: " + targetDate); } else if (targetDate.matches("[0-9]+")) { System.out.println("Targeting dump from: " + targetDate); } else { System.out.println("Error: Date looks wrong. Must be in the format '20160101' or 'latest'."); System.exit(1); } // Check the data directory if (!dataDir.exists()) { System.out.println("Error: Data directory specified does not exist."); System.exit(1); } System.out.println("Using data directory: " + dataDir.getAbsolutePath()); // And create the output directory if it doesn't already exist File outputDir = new File(dataDir.getAbsolutePath() + File.separator + targetDate); if (!outputDir.exists()) { Files.createDirectory( outputDir.toPath() ); } // Get the list of processorClasses for (String value : Arrays.copyOf(args, args.length - 2)) { try { processorClasses.add(Class.forName("main.java.org.wikidata.analyzer.Processor." + value + "Processor")); } catch (ClassNotFoundException e) { System.out.println("Error: " + value + "Processor not found"); System.exit(1); } System.out.println(value + "Processor enabled"); } // Set up controller DumpProcessingController controller = new DumpProcessingController("wikidatawiki"); controller.setOfflineMode(false); // Set all the processors up and add them to the controller for (Class<?> classObject : this.processorClasses) { try { WikidataAnalyzerProcessor processor = (WikidataAnalyzerProcessor) classObject.newInstance(); processor.setOutputDir( outputDir ); processor.setUp(); controller.registerEntityDocumentProcessor( processor, null, true ); this.processorObjects.add( processor ); } catch (InstantiationException | IllegalAccessException e) { e.printStackTrace(); System.exit(1); } } // Always add the noisy processor.... controller.registerEntityDocumentProcessor(new NoisyProcessor(), null, true); // Fetch and process dump DumpFetcher fetcher = new DumpFetcher(dataDir); System.out.println("Fetching dump"); MwDumpFile dump = fetcher.getDump(targetDate); System.out.println("Processing dump"); controller.processDump(dump); System.out.println("Processed!"); System.out.println("Memory Usage (MB): " + Runtime.getRuntime().totalMemory() / 1024 / 1024); // Tear all the processors down for (WikidataAnalyzerProcessor processor : this.processorObjects) { processor.tearDown(); } } }
package project.ilyagorban.model.figures; import static project.ilyagorban.model.ChessModel.*; import project.ilyagorban.model.XY; import project.ilyagorban.model.Rank; // figures public class Pawn extends Figure { private static final long serialVersionUID = -8229158180905631041L; public Pawn(int xy, Rank r) { super(xy, r); } @Override public int checkIllegalMove(Figure[] board, int to, Figure lastMoved, int lastFrom) { int from = this.getXY(); if (to > 63 || to < 0 || from == to) { return INCORRECT_INPUT; } boolean owner = this.getRank().getOwner(); int dirY = owner == WHITE ? 1 : -1; Figure figTo = board[to]; int[] difXY = XY.getDifferenceXY(from, to); int output = INCORRECT_MOVE; if (difXY[0] == 0) { boolean isMovingOneSquare = difXY[1] * dirY == 1 && figTo == null; if (isMovingOneSquare == true) { output = CORRECT_MOVE; } // check in XY.addToIndex should not make problem because isTouched checking boolean isMovingTwoSquare = output != CORRECT_MOVE && this.isTouched() == false && difXY[1] * dirY == 2 && figTo == null && board[XY.addToIndex(this.getXY(), 0, dirY)] == null; if (isMovingTwoSquare) { output = CORRECT_MOVE; } } boolean isTaking = output != CORRECT_MOVE && difXY[1] * dirY * Math.abs(difXY[0]) == 1; if (isTaking) { boolean isAbleToTakeFigureRegular = figTo != null && figTo.isEnemy(this) == true; if (isAbleToTakeFigureRegular) { output = CORRECT_MOVE; } int rightEnpassantY = output != CORRECT_MOVE && owner == WHITE ? 4 : 3; int y = XY.getY(this.getXY()); if (y == rightEnpassantY) { Figure victimOfEnpassant = board[XY.addToIndex(from, difXY[0], 0)]; if (victimOfEnpassant != null && (XY.getY(lastFrom) == 1 || XY.getY(lastFrom) == 6) && victimOfEnpassant.equals(lastMoved)) { return EN_PASSANT; } } } if (output == CORRECT_MOVE) { int yTo = XY.getY(to); if (yTo == 0 || yTo == 7) { output = PAWN_PROMOTION; } } return output; } }
package org.biojava.bio.seq.io; import org.biojava.bio.symbol.*; import org.biojava.utils.*; import org.biojava.bio.seq.*; import org.biojava.bio.seq.io.*; import org.biojava.bio.dist.*; import java.util.*; import junit.framework.Test; import junit.framework.TestSuite; import junit.framework.TestCase; /** * JUnit test for SymbolList objects * @author David Huen * @since 1.3 */ public class SmartSequenceBuilderTest extends TestCase { // SymbolList lengths to run tests at. int testLengths[] = {100, 16384, 2000000}; // number of times to repeat each test to deal with chance // matches in last symbol. int noRepeats = 3; public SmartSequenceBuilderTest(String string) { super(string); } /** * creates a random SymbolList * * @param the Alphabet from which Symbols are to be drawn. Can include ambiguity symbols. */ protected Symbol [] createRandomSymbolArray(FiniteAlphabet alpha, int length) throws Exception { int alfaSize = alpha.size(); AlphabetIndex indx = AlphabetManager.getAlphabetIndex(alpha); Random rand = new Random(); Symbol [] array = new Symbol [length]; for (int i=0; i < length; i++) { array[i] = indx.symbolForIndex(rand.nextInt(alfaSize)); } return array; } /** * compares a SymbolList against a Symbol array */ protected boolean compareSymbolLists(SymbolList list, Symbol [] array) { // array must be at least as long as SymbolList int length = list.length(); if (length > array.length) return false; // compare symbol lists across length for (int i =1; i <= length; i++) { if (list.symbolAt(i) != array[i-1]) return false; } return true; } /** * Note that arrayAlpha <b>MUST NOT</b> have Symbols that are incompatible with symListAlpha!!! * e.g. arrayAlpha may have ambiguity symbols in it that are only implicitly defined by symListAlpha. * @param arrayAlpha the Alphabet from which the Symbols in the Symbol[] are to be drawn. * @param symListAlpha the Alphabet on which the symbolList is to be defined. */ protected boolean runSymbolListTest(FiniteAlphabet arrayAlpha, FiniteAlphabet symListAlpha, int length, SequenceBuilder builder) throws Exception { // create a Symbol array of the kind required Symbol [] array = createRandomSymbolArray(arrayAlpha, length); assertNotNull(array); // create the required SymbolList builder.addSymbols(symListAlpha, array, 0, length); org.biojava.bio.seq.Sequence seq = builder.makeSequence(); assertNotNull(seq); // verify and return result. return compareSymbolLists(seq, array); } /** * runs repeated tests for the constructor * that takes a SymbolList argument */ private boolean runRepeatedSymbolListTests(FiniteAlphabet arrayAlpha, FiniteAlphabet symListAlpha, SequenceBuilder builder) throws Exception { for (int i=0; i < testLengths.length; i++) { // setup test for specified length int length = testLengths[i]; for (int j=0; j < noRepeats; j++ ) { assertTrue(runSymbolListTest(arrayAlpha, symListAlpha, length, builder)); } } return true; } /** * set that generates a DNA alphabet including ambiguity symbols. */ private FiniteAlphabet generateAmbiguousDNA() { FiniteAlphabet dna = DNATools.getDNA(); FiniteAlphabet ambiguous = new SimpleAlphabet(); try { ambiguous.addSymbol(DNATools.a()); ambiguous.addSymbol(DNATools.c()); ambiguous.addSymbol(DNATools.g()); ambiguous.addSymbol(DNATools.t()); Set chars = new HashSet(); chars.add(DNATools.a()); chars.add(DNATools.c()); ambiguous.addSymbol(dna.getAmbiguity(chars)); chars = new HashSet(); chars.add(DNATools.a()); chars.add(DNATools.g()); ambiguous.addSymbol(dna.getAmbiguity(chars)); chars = new HashSet(); chars.add(DNATools.a()); chars.add(DNATools.t()); ambiguous.addSymbol(dna.getAmbiguity(chars)); chars = new HashSet(); chars.add(DNATools.c()); chars.add(DNATools.g()); ambiguous.addSymbol(dna.getAmbiguity(chars)); chars = new HashSet(); chars.add(DNATools.c()); chars.add(DNATools.t()); ambiguous.addSymbol(dna.getAmbiguity(chars)); chars = new HashSet(); chars.add(DNATools.g()); chars.add(DNATools.t()); ambiguous.addSymbol(dna.getAmbiguity(chars)); chars = new HashSet(); chars.add(DNATools.a()); chars.add(DNATools.c()); chars.add(DNATools.g()); ambiguous.addSymbol(dna.getAmbiguity(chars)); chars = new HashSet(); chars.add(DNATools.a()); chars.add(DNATools.c()); chars.add(DNATools.t()); ambiguous.addSymbol(dna.getAmbiguity(chars)); chars = new HashSet(); chars.add(DNATools.a()); chars.add(DNATools.g()); chars.add(DNATools.t()); ambiguous.addSymbol(dna.getAmbiguity(chars)); chars = new HashSet(); chars.add(DNATools.c()); chars.add(DNATools.g()); chars.add(DNATools.t()); ambiguous.addSymbol(dna.getAmbiguity(chars)); chars.add(DNATools.n()); return ambiguous; } catch (IllegalSymbolException ise) { return null; } catch (ChangeVetoException cve) { return null; } } /** * test for PackedSymbolList under auto-select mode. */ public void testSmartSequenceBuilder() throws Exception { // create an alphabet with ambiguity symbols FiniteAlphabet symListAlpha = (FiniteAlphabet) DNATools.getDNA(); FiniteAlphabet arrayAlpha = generateAmbiguousDNA(); assertNotNull(arrayAlpha); assertNotNull(symListAlpha); // exercise the ChunkedSymbolList implementation assertTrue(runRepeatedSymbolListTests(arrayAlpha, symListAlpha, SmartSequenceBuilder.FACTORY.makeSequenceBuilder())); } // creates a suite public static Test suite() { TestSuite suite = new TestSuite(SmartSequenceBuilderTest.class); return suite; } // harness for tests public static void main(String [] args) { junit.textui.TestRunner.run(suite()); } }
package org.ccci.gto.android.thekey; import static org.ccci.gto.android.thekey.Constant.CAS_SERVER; import static org.ccci.gto.android.thekey.Constant.OAUTH_GRANT_TYPE_AUTHORIZATION_CODE; import static org.ccci.gto.android.thekey.Constant.OAUTH_GRANT_TYPE_REFRESH_TOKEN; import static org.ccci.gto.android.thekey.Constant.OAUTH_PARAM_ACCESS_TOKEN; import static org.ccci.gto.android.thekey.Constant.OAUTH_PARAM_CLIENT_ID; import static org.ccci.gto.android.thekey.Constant.OAUTH_PARAM_CODE; import static org.ccci.gto.android.thekey.Constant.OAUTH_PARAM_GRANT_TYPE; import static org.ccci.gto.android.thekey.Constant.OAUTH_PARAM_REDIRECT_URI; import static org.ccci.gto.android.thekey.Constant.OAUTH_PARAM_REFRESH_TOKEN; import static org.ccci.gto.android.thekey.Constant.OAUTH_PARAM_STATE; import static org.ccci.gto.android.thekey.Constant.OAUTH_PARAM_THEKEY_GUID; import static org.ccci.gto.android.thekey.Constant.REDIRECT_URI; import static org.ccci.gto.android.thekey.Constant.THEKEY_PARAM_SERVICE; import static org.ccci.gto.android.thekey.Constant.THEKEY_PARAM_TICKET; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; import java.util.HashMap; import java.util.Map; import javax.net.ssl.HttpsURLConnection; import me.thekey.android.TheKey; import me.thekey.android.TheKeySocketException; import org.json.JSONException; import org.json.JSONObject; import android.annotation.TargetApi; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.net.Uri; import android.net.Uri.Builder; import android.os.Build; import android.support.v4.util.LongSparseArray; import android.util.Pair; /** * The Key interaction library, handles all interactions with The Key OAuth API * endpoints and correctly stores/utilizes OAuth access_tokens locally */ public final class TheKeyImpl implements TheKey { private static final String PREFFILE_THEKEY = "thekey"; private static final String PREF_ACCESS_TOKEN = "access_token"; private static final String PREF_EXPIRE_TIME = "expire_time"; private static final String PREF_GUID = "guid"; private static final String PREF_REFRESH_TOKEN = "refresh_token"; private static final Object LOCK_INSTANCE = new Object(); private static final LongSparseArray<TheKeyImpl> instances = new LongSparseArray<TheKeyImpl>(); private final Context context; private final Uri casServer; private final Long clientId; private final Object lock_auth = new Object(); private TheKeyImpl(final Context context, final long clientId, final Uri casServer) { this.context = context; this.clientId = clientId; this.casServer = casServer; } public static TheKeyImpl getInstance(final Context context, final long clientId) { if (instances.get(clientId) == null) { synchronized (LOCK_INSTANCE) { if (instances.get(clientId) == null) { instances.put(clientId, new TheKeyImpl(context.getApplicationContext(), clientId, CAS_SERVER)); } } } return instances.get(clientId); } protected Uri getCasUri() { return this.casServer; } protected Uri getCasUri(final String... segments) { final Builder uri = this.casServer.buildUpon(); for (final String segment : segments) { uri.appendPath(segment); } return uri.build(); } protected Long getClientId() { return this.clientId; } public String getGuid() { return this.getPrefs().getString(PREF_GUID, null); } protected Uri getAuthorizeUri() { return this.getAuthorizeUri(null); } protected Uri getAuthorizeUri(final String state) { // build oauth authorize url final Builder uri = this.getCasUri("oauth", "authorize").buildUpon() .appendQueryParameter(OAUTH_PARAM_CLIENT_ID, this.getClientId().toString()) .appendQueryParameter(OAUTH_PARAM_REDIRECT_URI, REDIRECT_URI.toString()); if (state != null) { uri.appendQueryParameter(OAUTH_PARAM_STATE, state); } return uri.build(); } /** * This method returns a ticket for the specified service. This method is a * blocking method, this should never be called directly on the UI thread. * * @param service * @return The ticket */ public String getTicket(final String service) throws TheKeySocketException { final Pair<String, Attributes> ticketPair = this.getTicketAndAttributes(service); return ticketPair != null ? ticketPair.first : null; } /** * This method returns a ticket for the specified service and attributes the ticket was issued for. This is a * blocking method, this should never be called directly on the UI thread. * * @param service * @return The ticket & attributes */ public Pair<String, Attributes> getTicketAndAttributes(final String service) throws TheKeySocketException { Pair<String, Attributes> credentials = null; while ((credentials = this.getValidAccessTokenAndAttributes(0)) != null) { // fetch a ticket final String ticket = this.getTicket(credentials.first, service); if (ticket != null) { return Pair.create(ticket, credentials.second); } // the access token didn't work, remove it and restart processing this.removeAccessToken(credentials.first); } // the user needs to authenticate before a ticket can be retrieved return null; } private String getTicket(final String accessToken, final String service) throws TheKeySocketException { HttpsURLConnection conn = null; try { // generate & send request final Uri ticketUri = this.getCasUri("api", "oauth", "ticket").buildUpon() .appendQueryParameter(OAUTH_PARAM_ACCESS_TOKEN, accessToken) .appendQueryParameter(THEKEY_PARAM_SERVICE, service).build(); conn = (HttpsURLConnection) new URL(ticketUri.toString()).openConnection(); // parse the json response final JSONObject json = this.parseJsonResponse(conn.getInputStream()); return json.optString(THEKEY_PARAM_TICKET, null); } catch (final MalformedURLException e) { throw new RuntimeException("malformed CAS URL", e); } catch (final IOException e) { throw new TheKeySocketException("connect error", e); } finally { if (conn != null) { conn.disconnect(); } } } private Pair<String, Attributes> getAccessTokenAndAttributes() { // we use getAll to access the preferences to reduce the chance of a // race condition final Map<String, ?> attrs = new HashMap<String, Object>(this.getPrefs().getAll()); final long currentTime = System.currentTimeMillis(); final long expireTime; { final Long v = (Long) attrs.get(PREF_EXPIRE_TIME); expireTime = v != null ? v : currentTime; } final String accessToken = expireTime >= currentTime ? (String) attrs.get(PREF_ACCESS_TOKEN) : null; // return the access_token, attributes pair if we have an access_token return accessToken != null ? Pair.create(accessToken, (Attributes) new AttributesImpl(attrs)) : null; } private String getRefreshToken() { return this.getPrefs().getString(PREF_REFRESH_TOKEN, null); } private Pair<String, Attributes> getValidAccessTokenAndAttributes(final int depth) throws TheKeySocketException { // prevent infinite recursion if (depth > 2) { return null; } synchronized (this.lock_auth) { // check for an existing accessToken final Pair<String, Attributes> credentials = this.getAccessTokenAndAttributes(); if (credentials != null && credentials.first != null) { return credentials; } // try fetching a new access_token using a refresh_token final String refreshToken = this.getRefreshToken(); if (refreshToken != null) { if (this.processRefreshTokenGrant(refreshToken)) { return this.getValidAccessTokenAndAttributes(depth + 1); } // the refresh_token isn't valid anymore this.removeRefreshToken(); } // no valid access_token was found, clear auth state this.clearAuthState(); } return null; } @TargetApi(Build.VERSION_CODES.GINGERBREAD) private void removeAccessToken(final String token) { synchronized (this.lock_auth) { if (token != null && token.equals(this.getPrefs().getString(PREF_ACCESS_TOKEN, null))) { final Editor prefs = this.getPrefs().edit(); prefs.remove(PREF_ACCESS_TOKEN); prefs.remove(PREF_EXPIRE_TIME); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) { prefs.apply(); } else { prefs.commit(); } } } } @TargetApi(Build.VERSION_CODES.GINGERBREAD) private void removeRefreshToken() { final Editor prefs = this.getPrefs().edit(); prefs.remove(PREF_REFRESH_TOKEN); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) { prefs.apply(); } else { prefs.commit(); } } @TargetApi(Build.VERSION_CODES.GINGERBREAD) private void clearAuthState() { final Editor prefs = this.getPrefs().edit(); prefs.remove(PREF_ACCESS_TOKEN); prefs.remove(PREF_REFRESH_TOKEN); prefs.remove(PREF_EXPIRE_TIME); prefs.remove(PREF_GUID); synchronized (this.lock_auth) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) { prefs.apply(); } else { prefs.commit(); } } } protected boolean processCodeGrant(final String code, final Uri redirectUri) throws TheKeySocketException { final Uri tokenUri = this.getCasUri("api", "oauth", "token"); HttpsURLConnection conn = null; try { // generate & send request conn = (HttpsURLConnection) new URL(tokenUri.toString()).openConnection(); conn.setDoOutput(true); conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded"); final byte[] data = (encodeParam(OAUTH_PARAM_GRANT_TYPE, OAUTH_GRANT_TYPE_AUTHORIZATION_CODE) + "&" + encodeParam(OAUTH_PARAM_CLIENT_ID, this.clientId.toString()) + "&" + encodeParam(OAUTH_PARAM_REDIRECT_URI, redirectUri.toString()) + "&" + encodeParam( OAUTH_PARAM_CODE, code)).getBytes("UTF-8"); conn.setFixedLengthStreamingMode(data.length); conn.getOutputStream().write(data); // parse the json response final JSONObject json = this.parseJsonResponse(conn.getInputStream()); this.storeGrants(json); // return success return true; } catch (final MalformedURLException e) { throw new RuntimeException("invalid CAS URL", e); } catch (final UnsupportedEncodingException e) { throw new RuntimeException("Unsupported encoding??? this shouldn't happen", e); } catch (final IOException e) { throw new TheKeySocketException(e); } finally { if (conn != null) { conn.disconnect(); } } } private boolean processRefreshTokenGrant(final String refreshToken) throws TheKeySocketException { final Uri tokenUri = this.getCasUri("api", "oauth", "token"); HttpsURLConnection conn = null; try { // generate & send request conn = (HttpsURLConnection) new URL(tokenUri.toString()).openConnection(); conn.setDoOutput(true); conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded"); final byte[] data = (encodeParam(OAUTH_PARAM_GRANT_TYPE, OAUTH_GRANT_TYPE_REFRESH_TOKEN) + "&" + encodeParam(OAUTH_PARAM_CLIENT_ID, this.clientId.toString()) + "&" + encodeParam( OAUTH_PARAM_REFRESH_TOKEN, refreshToken)).getBytes("UTF-8"); conn.setFixedLengthStreamingMode(data.length); conn.getOutputStream().write(data); // parse the json response final JSONObject json = this.parseJsonResponse(conn.getInputStream()); this.storeGrants(json); // return success return true; } catch (final MalformedURLException e) { throw new RuntimeException("invalid CAS URL", e); } catch (final UnsupportedEncodingException e) { throw new RuntimeException("Unsupported encoding??? this shouldn't happen", e); } catch (final IOException e) { throw new TheKeySocketException(e); } finally { if (conn != null) { conn.disconnect(); } } } @TargetApi(Build.VERSION_CODES.GINGERBREAD) private void storeGrants(final JSONObject json) { final Editor prefs = this.getPrefs().edit(); // store access_token if (json.has(OAUTH_PARAM_ACCESS_TOKEN)) { try { prefs.putString(PREF_ACCESS_TOKEN, json.getString(OAUTH_PARAM_ACCESS_TOKEN)); prefs.remove(PREF_EXPIRE_TIME); if (json.has("expires_in")) { prefs.putLong(PREF_EXPIRE_TIME, System.currentTimeMillis() + json.getLong("expires_in") * 1000); } prefs.remove(PREF_GUID); if (json.has(OAUTH_PARAM_THEKEY_GUID)) { prefs.putString(PREF_GUID, json.getString(OAUTH_PARAM_THEKEY_GUID)); } } catch (final JSONException e) { prefs.remove(PREF_ACCESS_TOKEN); prefs.remove(PREF_EXPIRE_TIME); prefs.remove(PREF_GUID); } } // store refresh_token if (json.has(OAUTH_PARAM_REFRESH_TOKEN)) { try { prefs.putString(PREF_REFRESH_TOKEN, json.getString(OAUTH_PARAM_REFRESH_TOKEN)); } catch (final JSONException e) { prefs.remove(PREF_REFRESH_TOKEN); } } // we synchronize this to prevent race conditions with using the // access_token synchronized (this.lock_auth) { // store updates if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) { prefs.apply(); } else { prefs.commit(); } } } private SharedPreferences getPrefs() { return this.context.getSharedPreferences(PREFFILE_THEKEY, Context.MODE_PRIVATE); } @SuppressWarnings("deprecation") private String encodeParam(final String name, final String value) { try { return URLEncoder.encode(name, "UTF-8") + "=" + URLEncoder.encode(value, "UTF-8"); } catch (final UnsupportedEncodingException e) { // we should never get here, but if for some odd reason we do, use // the default encoder which should be UTF-8 return URLEncoder.encode(name) + "=" + URLEncoder.encode(value); } } private JSONObject parseJsonResponse(final InputStream in) { try { final BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8")); final StringBuilder json = new StringBuilder(); String buffer; while ((buffer = reader.readLine()) != null) { json.append(buffer); } return new JSONObject(json.toString()); } catch (final Exception e) { // return an empty object on error return new JSONObject(); } } private static final class AttributesImpl implements Attributes { private final Map<String, ?> attrs; private AttributesImpl(final Map<String, ?> prefsMap) { this.attrs = new HashMap<String, Object>(prefsMap); } public String getGuid() { return (String) this.attrs.get(PREF_GUID); } } }
package org.jgrapht.traverse; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import java.util.Random; import java.util.Set; import org.jgrapht.Graph; import org.jgrapht.Graphs; import org.jgrapht.event.EdgeTraversalEvent; import org.jgrapht.event.VertexTraversalEvent; public class RandomWalkIterator<V, E> extends AbstractGraphIterator<V, E> { private V currentVertex; private final Graph<V, E> graph; private final boolean isWeighted; private boolean sinkReached; private long maxSteps; private Random random; public RandomWalkIterator(Graph<V, E> graph) { this(graph, null); } public RandomWalkIterator(Graph<V, E> graph, V startVertex) { this(graph, startVertex, true); } public RandomWalkIterator(Graph<V, E> graph, V startVertex, boolean isWeighted) { this(graph, startVertex, isWeighted, Long.MAX_VALUE); } public RandomWalkIterator(Graph<V, E> graph, V startVertex, boolean isWeighted, long maxSteps) { if (graph == null) { throw new IllegalArgumentException("graph must not be null"); } //do not cross components. setCrossComponentTraversal(false); this.graph = graph; this.isWeighted = isWeighted; this.maxSteps = maxSteps; this.specifics = createGraphSpecifics(graph); //select a random start vertex in case not provided. if (startVertex == null) { if (graph.vertexSet().size() > 0) { currentVertex = graph.vertexSet().iterator().next(); } } else if (graph.containsVertex(startVertex)){ currentVertex = startVertex; } else { throw new IllegalArgumentException("graph must contain the start vertex"); } this.sinkReached = false; this.random = new Random(); } /** * Check if this walk is exhausted. Calling {@link #next()} on * exhausted iterator will throw {@link NoSuchElementException}. * * @return <code>true</code>if this iterator is exhausted, * <code>false</code> otherwise. */ protected boolean isExhausted() { return maxSteps == 0; } /** * Update data structures every time we see a vertex. * * @param vertex the vertex encountered * @param edge the edge via which the vertex was encountered, or null if the * vertex is a starting point */ protected void encounterVertex(V vertex, E edge) { maxSteps } /** * @see java.util.Iterator#hasNext() */ @Override public boolean hasNext() { return currentVertex != null && !isExhausted() && !sinkReached; } /** * @see java.util.Iterator#next() */ @Override public V next() { if (!hasNext()) { throw new NoSuchElementException(); } Set<? extends E> potentialEdges = specifics.edgesOf(currentVertex); //randomly select an edge from the set of potential edges. E nextEdge = drawEdge(potentialEdges); if (nextEdge != null) { V nextVertex; nextVertex = Graphs.getOppositeVertex(graph, nextEdge, currentVertex); encounterVertex(nextVertex, nextEdge); fireEdgeTraversed(createEdgeTraversalEvent(nextEdge)); fireVertexTraversed(createVertexTraversalEvent(nextVertex)); currentVertex = nextVertex; return nextVertex; } else { sinkReached = true; return currentVertex; } } /** * Randomly draws an edges out of the provided set. In case of un-weighted walk, * edge will be selected with uniform distribution across all outgoing edges. * In case of a weighted walk, edge will be selected with probability respective * to its weight across all outgoing edges. * * @param edges the set to select the edge from * @return the drawn edges or null if set is empty. */ private E drawEdge(Set<? extends E> edges) { if (edges.isEmpty()) { return null; } int drawn; List<E> list = new ArrayList<E>(edges); if (isWeighted) { Iterator<E> safeIter = list.iterator(); double border = random.nextDouble() * getTotalWeight(list); double d = 0; drawn = -1; do { d += graph.getEdgeWeight(safeIter.next()); drawn++; } while (d < border); } else { drawn = random.nextInt(list.size()); } return list.get(drawn); } private EdgeTraversalEvent<E> createEdgeTraversalEvent(E edge) { if (isReuseEvents()) { reusableEdgeEvent.setEdge(edge); return reusableEdgeEvent; } else { return new EdgeTraversalEvent<E>(this, edge); } } private VertexTraversalEvent<V> createVertexTraversalEvent(V vertex) { if (isReuseEvents()) { reusableVertexEvent.setVertex(vertex); return reusableVertexEvent; } else { return new VertexTraversalEvent<V>(this, vertex); } } private double getTotalWeight(Collection<E> edges) { double total = 0; for (E e : edges) { total += graph.getEdgeWeight(e); } return total; } }
package to.etc.domui.component.tbl; import java.util.*; import to.etc.domui.dom.html.*; import to.etc.domui.util.*; public class DataTable<T> extends TabularComponentBase<T> { private Table m_table = new Table(); protected IRowRenderer<T> m_rowRenderer; /** The size of the page */ private int m_pageSize; /** If a result is visible this is the data table */ private TBody m_dataBody; /** When the query has 0 results this is set to the div displaying that message. */ private Div m_errorDiv; public DataTable(IRowRenderer<T> r) { m_rowRenderer = r; } public DataTable(ITableModel<T> m, IRowRenderer<T> r) { super(m); m_rowRenderer = r; } public DataTable(Class<T> actualClass, ITableModel<T> model, IRowRenderer<T> r) { super(actualClass, model); m_rowRenderer = r; } public DataTable(Class<T> actualClass, IRowRenderer<T> r) { super(actualClass); m_rowRenderer = r; } /** * Return the backing table for this data browser. For component extension only - DO NOT MAKE PUBLIC. * @return */ protected Table getTable() { return m_table; } /** * UNSTABLE INTERFACE - UNDER CONSIDERATION. * @param dataBody */ protected void setDataBody(TBody dataBody) { m_dataBody = dataBody; } protected TBody getDataBody() { return m_dataBody; } @Override public void createContent() throws Exception { m_dataBody = null; m_errorDiv = null; setCssClass("ui-dt"); //-- Ask the renderer for a sort order, if applicable m_rowRenderer.beforeQuery(this); // ORDER!! BEFORE CALCINDICES or any other call that materializes the result. calcIndices(); // Calculate rows to show. List<T> list = getPageItems(); // Data to show if(list.size() == 0) { setNoResults(); return; } setResults(); // m_table.removeAllChildren(); // add(m_table); // //-- Render the header. // THead hd = new THead(); // HeaderContainer<T> hc = new HeaderContainer<T>(this); // TR tr = new TR(); // tr.setCssClass("ui-dt-hdr"); // hd.add(tr); // hc.setParent(tr); // m_rowRenderer.renderHeader(this, hc); // if(hc.hasContent()) { // m_table.add(hd); // } else { // hc = null; // hd = null; // tr = null; // //-- Render loop: add rows && ask the renderer to add columns. // m_dataBody = new TBody(); // m_table.add(m_dataBody); ColumnContainer<T> cc = new ColumnContainer<T>(this); int ix = m_six; for(T o : list) { TR tr = new TR(); m_dataBody.add(tr); cc.setParent(tr); m_rowRenderer.renderRow(this, cc, ix, o); ix++; } } private void setResults() throws Exception { if(m_errorDiv != null) { m_errorDiv.remove(); m_errorDiv = null; } if(m_dataBody != null) return; m_table.removeAllChildren(); add(m_table); //-- Render the header. THead hd = new THead(); HeaderContainer<T> hc = new HeaderContainer<T>(this); TR tr = new TR(); tr.setCssClass("ui-dt-hdr"); hd.add(tr); hc.setParent(tr); m_rowRenderer.renderHeader(this, hc); if(hc.hasContent()) { m_table.add(hd); } else { hc = null; hd = null; tr = null; } //-- Render loop: add rows && ask the renderer to add columns. m_dataBody = new TBody(); m_table.add(m_dataBody); // b.setOverflow(Overflow.SCROLL); // b.setHeight("400px"); // b.setWidth("100%"); } /** * Removes any data table, and presents the "no results found" div. */ private void setNoResults() { if(m_errorDiv != null) return; if(m_table != null) { m_table.removeAllChildren(); m_table.remove(); m_dataBody = null; } m_errorDiv = new Div(); m_errorDiv.setCssClass("ui-dt-nores"); m_errorDiv.setText(Msgs.BUNDLE.getString(Msgs.UI_DATATABLE_EMPTY)); add(m_errorDiv); return; } // private void updateResults(int count) throws Exception { // if(count == 0) // setNoResults(); // else // setResults(); /* CODING: Dumbass setters and getters. */ @Override public int getPageSize() { return m_pageSize; } public void setPageSize(int pageSize) { if(m_pageSize == pageSize) return; m_pageSize = pageSize; forceRebuild(); firePageChanged(); } /* CODING: TableModelListener implementation */ /** * Called when there are sweeping changes to the model. It forces a complete re-render of the table. */ public void modelChanged(ITableModel<T> model) { forceRebuild(); } /** * Row add. Determine if the row is within the paged-in indexes. If not we ignore the * request. If it IS within the paged content we insert the new TR. Since this adds a * new row to the visible set we check if the resulting rowset is not bigger than the * page size; if it is we delete the last node. After all this the renderer will render * the correct result. * When called the actual insert has already taken place in the model. * * @see to.etc.domui.component.tbl.ITableModelListener#rowAdded(to.etc.domui.component.tbl.ITableModel, int, java.lang.Object) */ public void rowAdded(ITableModel<T> model, int index, T value) throws Exception { if(!isBuilt()) return; calcIndices(); // Calculate visible nodes if(index < m_six || index >= m_eix) // Outside visible bounds return; //-- What relative row? setResults(); int rrow = index - m_six; // This is the location within the child array ColumnContainer<T> cc = new ColumnContainer<T>(this); TR tr = new TR(); cc.setParent(tr); m_rowRenderer.renderRow(this, cc, index, value); m_dataBody.add(rrow, tr); //-- Is the size not > the page size? if(m_pageSize > 0 && m_dataBody.getChildCount() > m_pageSize) { //-- Delete the last row. m_dataBody.removeChild(m_dataBody.getChildCount() - 1); // Delete last element } } /** * Delete the row specified. If it is not visible we do nothing. If it is visible we * delete the row. This causes one less row to be shown, so we check if we have a pagesize * set; if so we add a new row at the end IF it is available. * * @see to.etc.domui.component.tbl.ITableModelListener#rowDeleted(to.etc.domui.component.tbl.ITableModel, int, java.lang.Object) */ public void rowDeleted(ITableModel<T> model, int index, T value) throws Exception { if(!isBuilt()) return; if(index < m_six || index >= m_eix) // Outside visible bounds return; int rrow = index - m_six; // This is the location within the child array m_dataBody.removeChild(rrow); // Discard this one; if(m_dataBody.getChildCount() == 0) { setNoResults(); return; } //-- One row gone; must we add one at the end? int peix = m_six + m_pageSize - 1; // Index of last element on "page" if(m_pageSize > 0 && peix < m_eix) { ColumnContainer<T> cc = new ColumnContainer<T>(this); TR tr = new TR(); cc.setParent(tr); m_rowRenderer.renderRow(this, cc, peix, getModelItem(peix)); m_dataBody.add(m_pageSize - 1, tr); } } /** * Merely force a full redraw of the appropriate row. * * @see to.etc.domui.component.tbl.ITableModelListener#rowModified(to.etc.domui.component.tbl.ITableModel, int, java.lang.Object) */ public void rowModified(ITableModel<T> model, int index, T value) throws Exception { if(!isBuilt()) return; if(index < m_six || index >= m_eix) // Outside visible bounds return; int rrow = index - m_six; // This is the location within the child array TR tr = (TR) m_dataBody.getChild(rrow); // The visible row there tr.removeAllChildren(); // Discard current contents. ColumnContainer<T> cc = new ColumnContainer<T>(this); m_rowRenderer.renderRow(this, cc, index, value); } public void setTableWidth(String w) { m_table.setTableWidth(w); } }
package jdo.order.model; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.persistence.Entity; import javax.persistence.OneToMany; import javax.persistence.OrderBy; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import jdo.model.BasePersistentModel; import jdo.order.model.adjustment.OrderAdjustment; import jdo.order.model.status.OrderStatus; import jdo.order.model.terms.OrderTerm; /** * @author Jim * @version 1.0 * @created 25-Dec-2007 9:54:32 AM */ @Entity @Table(name = "PurchaseSalesOrders") public class Order extends BasePersistentModel { private static final long serialVersionUID = 1L; @OneToMany(mappedBy = "affectingOrder") private List<OrderAdjustment> affectedBy = new ArrayList<OrderAdjustment>(); @OneToMany(mappedBy = "order") @OrderBy("orderItemSeqId") private List<OrderItem> composedOf = new ArrayList<OrderItem>(); @OneToMany(mappedBy = "order") private List<OrderContactMechanism> contactMechanisms = new ArrayList<OrderContactMechanism>(); @Temporal(TemporalType.DATE) private Date entryDate; @OneToMany(mappedBy = "partOf") private List<OrderRole> involving = new ArrayList<OrderRole>(); @Temporal(TemporalType.DATE) private Date orderDate; @OneToMany(mappedBy = "statusForOrder") private List<OrderStatus> stateOf = new ArrayList<OrderStatus>(); @OneToMany(mappedBy = "conditionForOrder") private List<OrderTerm> subjectTo = new ArrayList<OrderTerm>(); public List<OrderAdjustment> getAffectedBy() { return affectedBy; } public List<OrderItem> getComposedOf() { return composedOf; } public List<OrderContactMechanism> getContactMechanisms() { return contactMechanisms; } public Date getEntryDate() { return entryDate; } public List<OrderRole> getInvolving() { return involving; } public Date getOrderDate() { return orderDate; } public List<OrderStatus> getStateOf() { return stateOf; } public List<OrderTerm> getSubjectTo() { return subjectTo; } public void setAffectedBy(List<OrderAdjustment> affectedBy) { this.affectedBy = affectedBy; } public void setComposedOf(List<OrderItem> composedOf) { this.composedOf = composedOf; } public void setContactMechanisms( List<OrderContactMechanism> contactMechanisms) { this.contactMechanisms = contactMechanisms; } public void setEntryDate(Date entryDate) { this.entryDate = entryDate; } public void setInvolving(List<OrderRole> involving) { this.involving = involving; } public void setOrderDate(Date orderDate) { this.orderDate = orderDate; } public void setStateOf(List<OrderStatus> stateOf) { this.stateOf = stateOf; } public void setSubjectTo(List<OrderTerm> subjectTo) { this.subjectTo = subjectTo; } }
package com.sometrik.framework; import android.content.Context; import android.graphics.Color; import android.graphics.Typeface; import android.view.View; import android.widget.TextView; public class FWTextView extends TextView implements NativeCommandHandler { private FrameWork frame; public FWTextView(FrameWork frame) { super(frame); this.frame = frame; // Color color = new Color(); this.setBackground(null); } @Override public void addChild(View view) { System.out.println("FWTextView couldn't handle command"); } @Override public void addOption(int optionId, String text) { System.out.println("FWTextView couldn't handle command"); } @Override public void setValue(String v) { setText(v); } @Override public void setValue(int v) { System.out.println("FWTextView couldn't handle command"); } @Override public void setViewEnabled(Boolean enabled) { setEnabled(enabled); } @Override public void setStyle(String key, String value) { if (key.equals("font-size")) { if (value.equals("small")) { this.setTextSize(9); } else if (value.equals("medium")) { this.setTextSize(12); } else if (value.equals("large")) { this.setTextSize(15); } } } @Override public void setError(boolean hasError, String errorText) { //TODO System.out.println("FWTextView couldn't handle command"); } @Override public int getElementId() { return getId(); } @Override public void onScreenOrientationChange(boolean isLandscape) { // TODO Auto-generated method stub } @Override public void addData(String text, int row, int column, int sheet) { System.out.println("FWTextView couldn't handle command"); } @Override public void setViewVisibility(boolean visibility) { if (visibility){ this.setVisibility(VISIBLE); } else { this.setVisibility(INVISIBLE); } } @Override public void clear() { System.out.println("couldn't handle command"); } @Override public void flush() { // TODO Auto-generated method stub } @Override public void addColumn(String text, int columnType) { // TODO Auto-generated method stub } @Override public void reshape(int value, int size) { // TODO Auto-generated method stub } @Override public void setImage(byte[] bytes) { // TODO Auto-generated method stub } @Override public void reshape(int size) { // TODO Auto-generated method stub } }
package com.mapswithme.maps; import android.annotation.SuppressLint; import android.app.ActionBar; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.res.Resources; import android.location.Location; import android.os.Bundle; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.util.Log; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.inputmethod.EditorInfo; import android.widget.AbsListView; import android.widget.AbsListView.OnScrollListener; import android.widget.BaseAdapter; import android.widget.EditText; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.RadioGroup; import android.widget.RadioGroup.OnCheckedChangeListener; import android.widget.TextView; import android.widget.TextView.OnEditorActionListener; import com.mapswithme.maps.base.MapsWithMeBaseListActivity; import com.mapswithme.maps.location.LocationService; import com.mapswithme.maps.search.SearchController; import com.mapswithme.util.InputUtils; import com.mapswithme.util.Language; import com.mapswithme.util.UiUtils; import com.mapswithme.util.Utils; import com.mapswithme.util.statistics.Statistics; public class SearchActivity extends MapsWithMeBaseListActivity implements LocationService.Listener { private static String TAG = "SearchActivity"; public static final String SEARCH_RESULT = "search_result"; public static final String EXTRA_SCOPE = "search_scope"; public static final String EXTRA_QUERY = "search_query"; public static void startForSearch(Context context, String query, int scope) { final Intent i = new Intent(context, SearchActivity.class); i.putExtra(EXTRA_SCOPE, scope).putExtra(EXTRA_QUERY, query); context.startActivity(i); } public static void startForSearch(Context context, String query) { final Intent i = new Intent(context, SearchActivity.class); i.putExtra(EXTRA_QUERY, query); context.startActivity(i); } private static class SearchAdapter extends BaseAdapter { private final SearchActivity m_context; private final LayoutInflater m_inflater; private final Resources m_resource; private final String m_packageName; private static final String m_categories[] = { "food", "shop", "hotel", "tourism", "entertainment", "atm", "bank", "transport", "fuel", "parking", "pharmacy", "hospital", "toilet", "post", "police" }; private int m_count = -1; private int m_resultID = 0; public SearchAdapter(SearchActivity context) { m_context = context; m_inflater = (LayoutInflater) m_context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); m_resource = m_context.getResources(); m_packageName = m_context.getApplicationContext().getPackageName(); } private static final int CATEGORY_TYPE = 0; private static final int RESULT_TYPE = 1; private static final int MESSAGE_TYPE = 2; private boolean isShowCategories() { return m_context.isShowCategories(); } private String getWarningForEmptyResults() { // First try to show warning if no country downloaded for viewport. if (m_context.m_searchMode != AROUND_POSITION) { final String name = m_context.getViewportCountryNameIfAbsent(); if (name != null) return String.format(m_context.getString(R.string.download_viewport_country_to_search), name); } // If now position detected or no country downloaded for position. if (m_context.m_searchMode != IN_VIEWPORT) { final Location loc = m_context.m_location.getLastKnown(); if (loc == null) { return m_context.getString(R.string.unknown_current_position); } else { final String name = m_context.getCountryNameIfAbsent(loc.getLatitude(), loc.getLongitude()); if (name != null) return String.format(m_context.getString(R.string.download_location_country), name); } } return null; } @Override public boolean isEnabled(int position) { return (isShowCategories() || m_count > 0); } @Override public int getItemViewType(int position) { if (isShowCategories()) return CATEGORY_TYPE; else return (m_count == 0 ? MESSAGE_TYPE : RESULT_TYPE); } @Override public int getViewTypeCount() { return 3; } @Override public int getCount() { if (isShowCategories()) return m_categories.length; else if (m_count < 0) return 0; else return (m_count == 0 ? 1 : m_count + 1); // first additional item is "Show all result for" } @Override public Object getItem(int position) { return position; } @Override public long getItemId(int position) { return position; } private static class ViewHolder { public TextView m_name = null; public TextView m_countryAndType = null; public TextView m_distance = null; void initFromView(View v, int type) { m_name = (TextView) v.findViewById(R.id.search_item_name); if (type != CATEGORY_TYPE) m_countryAndType = (TextView) v.findViewById(R.id.search_item_place_type); if (type == RESULT_TYPE) m_distance = (TextView) v.findViewById(R.id.search_item_distance); } } /// Created from native code. public static class SearchResult { public String m_name; public String m_country; public String m_amenity; public String m_distance; /// 0 - suggestion result /// 1 - feature result public int m_type; // Called from native code @SuppressWarnings("unused") public SearchResult(String suggestion) { m_name = suggestion; m_type = 0; } // Called from native code @SuppressWarnings("unused") public SearchResult(String name, String country, String amenity, String flag, String distance, double azimut) { m_name = name; m_country = country; m_amenity = amenity; m_distance = distance; m_type = 1; } } private String getCategoryName(String strID) { final int id = m_resource.getIdentifier(strID, "string", m_packageName); if (id > 0) { return m_context.getString(id); } else { Log.e(TAG, "Failed to get resource id from: " + strID); return null; } } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder = null; if (convertView == null) { holder = new ViewHolder(); switch (getItemViewType(position)) { case CATEGORY_TYPE: convertView = m_inflater.inflate(R.layout.search_category_item, null); holder.initFromView(convertView, CATEGORY_TYPE); break; case RESULT_TYPE: convertView = m_inflater.inflate(R.layout.search_item, null); holder.initFromView(convertView, RESULT_TYPE); break; case MESSAGE_TYPE: convertView = m_inflater.inflate(R.layout.search_message_item, null); holder.initFromView(convertView, MESSAGE_TYPE); break; } convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } if (isShowCategories()) { // Show categories list. final String strID = m_categories[position]; UiUtils.setTextAndShow(holder.m_name, getCategoryName(strID)); } else if (m_count == 0) { // Show warning message. UiUtils.setTextAndShow(holder.m_name, m_context.getString(R.string.no_search_results_found)); final String msg = getWarningForEmptyResults(); if (msg != null) UiUtils.setTextAndShow(holder.m_countryAndType, msg); else UiUtils.clearTextAndHide(holder.m_countryAndType); } else { // title item with "Show all" text if (position == 0) { UiUtils.setTextAndShow(holder.m_name, m_context.getString(R.string.search_show_on_map)); UiUtils.clearTextAndHide(holder.m_countryAndType); UiUtils.clearTextAndHide(holder.m_distance); return convertView; } // 0 index is for multiple result // so real result are from 1 --position; // Show search results. final SearchResult r = m_context.getResult(position, m_resultID); if (r != null) { UiUtils.setTextAndShow(holder.m_name, r.m_name); UiUtils.setTextAndShow(holder.m_countryAndType, TextUtils.join(", ", Utils.asObjectArray(r.m_country, r.m_amenity))); UiUtils.setTextAndShow(holder.m_distance, r.m_distance); } } return convertView; } /// Update list data. public void updateData(int count, int resultID) { m_count = count; m_resultID = resultID; notifyDataSetChanged(); } public void updateData() { notifyDataSetChanged(); } public void updateCategories() { m_count = -1; updateData(); } /// Show tapped country or get suggestion or get category to search. /// @return Suggestion string with space in the end (for full match purpose). public String onItemClick(int position) { if (isShowCategories()) { final String category = getCategoryName(m_categories[position]); Statistics.INSTANCE.trackSearchCategoryClicked(m_context, category); return category + ' '; } else { if (m_count > 0) { // Show all items was clicked if (position == 0) { SearchActivity.nativeShowAllSearchResults(); return null; } // Specific result was clicked final int resIndex = position - 1; final SearchResult r = m_context.getResult(resIndex, m_resultID); if (r != null) { if (r.m_type == 1) { // show country and close activity SearchActivity.nativeShowItem(resIndex); return null; } else { // advise suggestion return r.m_name + ' '; } } } } // close activity in case of any error return null; } } private String getSearchString() { return mSearchBox.getText().toString(); } private boolean isShowCategories() { return (getSearchString().length() == 0); } private LocationService m_location; // Search views private EditText mSearchBox; private ProgressBar mSearchProgress; private View mClearQueryBtn; private View mVoiceInput; private View mSearchIcon; private RadioGroup mSearchScopeGroup; @SuppressLint("NewApi") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (Utils.apiEqualOrGreaterThan(11)) { final ActionBar actionBar = getActionBar(); if (actionBar != null) actionBar.hide(); } m_location = ((MWMApplication) getApplication()).getLocationService(); setContentView(R.layout.search_list_view); setUpView(); // Create search list view adapter. setListAdapter(new SearchAdapter(this)); nativeConnect(); //checking search intent final Intent intent = getIntent(); if (intent != null && intent.hasExtra(EXTRA_QUERY)) { mSearchBox.setText(intent.getStringExtra(EXTRA_QUERY)); if (intent.hasExtra(EXTRA_SCOPE)) setSearchGroupSelectionByMode(intent.getIntExtra(EXTRA_SCOPE, 0)); runSearch(); } // Listen for keyboard buttons mSearchBox.setOnEditorActionListener(new OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (isShowCategories()) return false; final boolean isEnterDown = (event != null) && (event.getAction() == KeyEvent.ACTION_DOWN && event.getKeyCode() == KeyEvent.KEYCODE_ENTER); final boolean isActionDone = (actionId == EditorInfo.IME_ACTION_DONE); if (isEnterDown || isActionDone) { if (getSA().getCount() > 1) { getListView().performItemClick(getSA().getView(0, null, null), 0, 0); return true; } } return false; } }); } private void setSearchGroupSelectionByMode(final int savedSearchMode) { switch (savedSearchMode) { case ALL: mSearchScopeGroup.check(R.id.search_scope_everywhere); break; case IN_VIEWPORT: mSearchScopeGroup.check(R.id.search_scope_on_screen); break; default: mSearchScopeGroup.check(R.id.search_scope_near); break; } } @Override protected void onDestroy() { nativeDisconnect(); super.onDestroy(); } private void setUpView() { mVoiceInput = findViewById(R.id.search_voice_input); mSearchIcon = findViewById(R.id.search_icon); mSearchProgress = (ProgressBar) findViewById(R.id.search_progress); mClearQueryBtn = findViewById(R.id.search_image_clear); mClearQueryBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mSearchBox.getText().clear(); } }); // Initialize search edit box processor. mSearchBox = (EditText) findViewById(R.id.search_text_query); mSearchBox.addTextChangedListener(new TextWatcher() { @Override public void afterTextChanged(Editable s) { if (runSearch() == QUERY_EMPTY) showCategories(); if (s.length() == 0) // enable voice input { UiUtils.invisible(mClearQueryBtn); UiUtils.hideIf(!InputUtils.isVoiceInputSupported(SearchActivity.this), mVoiceInput); } else // show clear cross { UiUtils.show(mClearQueryBtn); UiUtils.invisible(mVoiceInput); } } @Override public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { } @Override public void onTextChanged(CharSequence s, int arg1, int arg2, int arg3) { } }); setUpSearchModes(); mVoiceInput.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { final Intent vrIntent = InputUtils.createIntentForVoiceRecognition(getResources().getString(R.string.search_map)); startActivityForResult(vrIntent, RC_VOICE_RECOGNITION); } }); getListView().setOnScrollListener(new OnScrollListener() { @Override public void onScrollStateChanged(AbsListView view, int scrollState) { // Hide keyboard when user starts scroll InputUtils.hideKeyboard(mSearchBox); // Hacky way to remove focus from only edittext at activity mSearchBox.setFocusableInTouchMode(false); mSearchBox.setFocusable(false); mSearchBox.setFocusableInTouchMode(true); mSearchBox.setFocusable(true); } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {} }); } private void setUpSearchModes() { // Initialize search modes group mSearchScopeGroup = (RadioGroup)findViewById(R.id.search_scope); // Default mode is AROUND_POSITION m_searchMode = MWMApplication.get().nativeGetInt(SEARCH_MODE_SETTING, AROUND_POSITION); setSearchGroupSelectionByMode(m_searchMode); mSearchScopeGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { int mode; if (R.id.search_scope_everywhere == checkedId) mode = ALL; else if (R.id.search_scope_near == checkedId) mode = AROUND_POSITION; else if (R.id.search_scope_on_screen == checkedId) mode = IN_VIEWPORT; else throw new IllegalArgumentException("Unknown Id: " + checkedId); getMwmApplication().nativeSetInt(SEARCH_MODE_SETTING, mode); runSearch(mode); } }); } @Override protected void onResume() { super.onResume(); // Reset current mode flag - start first search. m_flags = 0; m_north = -1.0; m_location.startUpdate(this); // do the search immediately after resume Utils.setStringAndCursorToEnd(mSearchBox, getLastQuery()); mSearchBox.requestFocus(); } @Override protected void onPause() { m_location.stopUpdate(this); super.onPause(); } private SearchAdapter getSA() { return (SearchAdapter) getListView().getAdapter(); } @Override protected void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); final String suggestion = getSA().onItemClick(position); if (suggestion == null) { presentResult(v, position); } else { // set suggestion string and run search (this call invokes runSearch) runSearch(suggestion); } } private void presentResult(View v, int position) { // If user searched for something, then // clear API layer SearchController.get().cancelApiCall(); if (MWMApplication.get().isProVersion()) { finish(); final SearchAdapter.ViewHolder vh = (SearchAdapter.ViewHolder) v.getTag(); final String queryTitle = vh.m_name.getText().toString().trim(); final String showOnMapTitle = getString(R.string.search_show_on_map).trim(); if (showOnMapTitle.equalsIgnoreCase(queryTitle)) SearchController.get().setQuery(mSearchBox.getText().toString()); else SearchController.get().setQuery(queryTitle); MWMActivity.startWithSearchResult(this, position != 0); } else { // Should we add something more attractive? Utils.toastShortcut(this, R.string.search_available_in_pro_version); } } @Override public void onBackPressed() { super.onBackPressed(); SearchController.get().cancel(); } /// Current position. private double m_lat; private double m_lon; private double m_north = -1.0; /// @name These constants should be equal with /// Java_com_mapswithme_maps_SearchActivity_nativeRunSearch routine. private static final int NOT_FIRST_QUERY = 1; private static final int HAS_POSITION = 2; private int m_flags = 0; private void updateDistance() { getSA().updateData(); } private void showCategories() { clearLastQuery(); setSearchInProgress(false); getSA().updateCategories(); } @Override public void onLocationUpdated(final Location l) { m_flags |= HAS_POSITION; m_lat = l.getLatitude(); m_lon = l.getLongitude(); if (runSearch() == SEARCH_SKIPPED) updateDistance(); } private final static long COMPAS_DELTA = 300; private long mLastCompasUpdate; @Override public void onCompassUpdated(long time, double magneticNorth, double trueNorth, double accuracy) { if (isShowCategories()) return; // We don't want to update view too often, it is slow // and breaks click listeners if (System.currentTimeMillis() - mLastCompasUpdate < COMPAS_DELTA) return; else mLastCompasUpdate = System.currentTimeMillis(); final double north[] = { magneticNorth, trueNorth }; m_location.correctCompassAngles(getWindowManager().getDefaultDisplay(), north); final double ret = (north[1] >= 0.0 ? north[1] : north[0]); // if difference is more than 1 degree if (m_north == -1 || Math.abs(m_north - ret) > 0.02) { m_north = ret; updateDistance(); } } @Override public void onLocationError(int errorCode) { } private int m_queryID = 0; /// Make 5-step increment to leave space for middle queries. /// This constant should be equal with native SearchAdapter::QUERY_STEP; private final static int QUERY_STEP = 5; private boolean isCurrentResult(int id) { return (id >= m_queryID && id < m_queryID + QUERY_STEP); } public void updateData(final int count, final int resultID) { runOnUiThread(new Runnable() { @Override public void run() { // if this results for the last query - hide progress if (isCurrentResult(resultID)) setSearchInProgress(false); if (!isShowCategories()) { // update list view with results if we are not in categories mode getSA().updateData(count, resultID); // scroll list view to the top setSelection(0); } } }); } private void runSearch(String s) { Utils.setStringAndCursorToEnd(mSearchBox, s); } /// @name These constants should be equal with search_params.hpp private static final int AROUND_POSITION = 1; private static final int IN_VIEWPORT = 2; private static final int SEARCH_WORLD = 4; private static final int ALL = AROUND_POSITION | IN_VIEWPORT | SEARCH_WORLD; private static final String SEARCH_MODE_SETTING = "SearchMode"; private int m_searchMode = AROUND_POSITION; private void runSearch(int mode) { m_searchMode = mode; runSearch(); } private static final int SEARCH_LAUNCHED = 0; private static final int QUERY_EMPTY = 1; private static final int SEARCH_SKIPPED = 2; private int runSearch() { final String s = getSearchString(); if (s.length() == 0) { // do force search next time from categories list m_flags &= (~NOT_FIRST_QUERY); return QUERY_EMPTY; } final String lang = Language.getKeyboardInput(this); final int id = m_queryID + QUERY_STEP; if (nativeRunSearch(s, lang, m_lat, m_lon, m_flags, m_searchMode, id)) { // store current query m_queryID = id; // mark that it's not the first query already - don't do force search m_flags |= NOT_FIRST_QUERY; setSearchInProgress(true); return SEARCH_LAUNCHED; } else return SEARCH_SKIPPED; } private void setSearchInProgress(boolean inProgress) { if (inProgress) { UiUtils.show(mSearchProgress); UiUtils.invisible(mSearchIcon); } else // search is completed { UiUtils.invisible(mSearchProgress); UiUtils.show(mSearchIcon); } } public SearchAdapter.SearchResult getResult(int position, int queryID) { return nativeGetResult(position, queryID, m_lat, m_lon, (m_flags & HAS_POSITION) != 0, m_north); } private native void nativeConnect(); private native void nativeDisconnect(); private static native SearchAdapter.SearchResult nativeGetResult(int position, int queryID, double lat, double lon, boolean mode, double north); private native boolean nativeRunSearch(String s, String lang, double lat, double lon, int flags, int searchMode, int queryID); private static native void nativeShowItem(int position); private static native void nativeShowAllSearchResults(); private native String getCountryNameIfAbsent(double lat, double lon); private native String getViewportCountryNameIfAbsent(); private native String getLastQuery(); private native void clearLastQuery(); // Handle voice recognition here private final static int RC_VOICE_RECOGNITION = 0xCA11; @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if ((requestCode == RC_VOICE_RECOGNITION) && (resultCode == Activity.RESULT_OK)) { final String result = InputUtils.getMostConfidentResult(data); if (result != null) mSearchBox.setText(result); } } }
package tourguide.tourguide; import android.animation.Animator; import android.animation.AnimatorSet; import android.animation.ObjectAnimator; import android.animation.ValueAnimator; import android.app.Activity; import android.graphics.Color; import android.graphics.Point; import android.os.Build; import android.util.Log; import android.view.Display; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.TextView; import net.i2p.android.ext.floatingactionbutton.FloatingActionButton; public class TourGuide { /** * This describes the animation techniques * */ public enum Technique { Click, HorizontalLeft, HorizontalRight, VerticalUpward, VerticalDownward } /** * This describes the allowable motion, for example if you want the users to learn about clicking, but want to stop them from swiping, then use ClickOnly */ public enum MotionType { AllowAll, ClickOnly, SwipeOnly } private Technique mTechnique; private View mHighlightedView; private Activity mActivity; private MotionType mMotionType; private FrameLayoutWithHole mFrameLayout; private View mToolTipViewGroup; public ToolTip mToolTip; public Pointer mPointer; public Overlay mOverlay; private Sequence mSequence; /* Static builder */ public static TourGuide init(Activity activity){ return new TourGuide(activity); } /* Constructor */ public TourGuide(Activity activity){ mActivity = activity; } /** * Setter for the animation to be used * @param technique Animation to be used * @return return TourGuide instance for chaining purpose */ public TourGuide with(Technique technique) { mTechnique = technique; return this; } /** * Sets which motion type is motionType * @param motionType * @return return TourGuide instance for chaining purpose */ public TourGuide motionType(MotionType motionType){ mMotionType = motionType; return this; } /** * Sets the duration * @param view the view in which the tutorial button will be placed on top of * @return return TourGuide instance for chaining purpose */ public TourGuide playOn(View view){ mHighlightedView = view; setupView(); return this; } /** * Sets the overlay * @param overlay this overlay object should contain the attributes of the overlay, such as background color, animation, Style, etc * @return return TourGuide instance for chaining purpose */ public TourGuide setOverlay(Overlay overlay){ mOverlay = overlay; return this; } /** * Set the toolTip * @param toolTip this toolTip object should contain the attributes of the ToolTip, such as, the title text, and the description text, background color, etc * @return return TourGuide instance for chaining purpose */ public TourGuide setToolTip(ToolTip toolTip){ mToolTip = toolTip; return this; } /** * Set the Pointer * @param pointer this pointer object should contain the attributes of the Pointer, such as the pointer color, pointer gravity, etc, refer to @Link{pointer} * @return return TourGuide instance for chaining purpose */ public TourGuide setPointer(Pointer pointer){ mPointer = pointer; return this; } /** * Clean up the tutorial that is added to the activity */ public void cleanUp(){ mFrameLayout.cleanUp(); if (mToolTipViewGroup!=null) { ((ViewGroup) mActivity.getWindow().getDecorView()).removeView(mToolTipViewGroup); } } public TourGuide playLater(View view){ mHighlightedView = view; return this; } public TourGuide playInSequence(Sequence sequence){ setSequence(sequence); next(); return this; } public TourGuide setSequence(Sequence sequence){ mSequence = sequence; mSequence.setParentTourGuide(this); for (TourGuide tourGuide : sequence.mTourGuideArray){ if (tourGuide.mHighlightedView == null) { throw new NullPointerException("Please specify the view using 'playLater' method"); } } return this; } public TourGuide next(){ if (mFrameLayout!=null) { cleanUp(); } if (mSequence.mCurrentSequence < mSequence.mTourGuideArray.length) { setToolTip(mSequence.getToolTip()); setPointer(mSequence.getPointer()); setOverlay(mSequence.getOverlay()); mHighlightedView = mSequence.getNextTourGuide().mHighlightedView; setupView(); mSequence.mCurrentSequence++; } return this; } /** * * @return FrameLayoutWithHole that is used as overlay */ public FrameLayoutWithHole getOverlay(){ return mFrameLayout; } /** * * @return the ToolTip container View */ public View getToolTip(){ return mToolTipViewGroup; } //TODO: move into Pointer private int getXBasedOnGravity(int width){ int [] pos = new int[2]; mHighlightedView.getLocationOnScreen(pos); int x = pos[0]; if((mPointer.mGravity & Gravity.RIGHT) == Gravity.RIGHT){ return x+mHighlightedView.getWidth()-width; } else if ((mPointer.mGravity & Gravity.LEFT) == Gravity.LEFT) { return x; } else { // this is center return x+mHighlightedView.getWidth()/2-width/2; } } //TODO: move into Pointer private int getYBasedOnGravity(int height){ int [] pos = new int[2]; mHighlightedView.getLocationInWindow(pos); int y = pos[1]; if((mPointer.mGravity & Gravity.BOTTOM) == Gravity.BOTTOM){ return y+mHighlightedView.getHeight()-height; } else if ((mPointer.mGravity & Gravity.TOP) == Gravity.TOP) { return y; }else { // this is center return y+mHighlightedView.getHeight()/2-height/2; } } private void setupView(){ // TODO: throw exception if either mActivity, mDuration, mHighlightedView is null checking(); final ViewTreeObserver viewTreeObserver = mHighlightedView.getViewTreeObserver(); viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { // make sure this only run once if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { //noinspection deprecation viewTreeObserver.removeGlobalOnLayoutListener(this); } else { viewTreeObserver.removeOnGlobalLayoutListener(this); } /* Initialize a frame layout with a hole */ mFrameLayout = new FrameLayoutWithHole(mActivity, mHighlightedView, mMotionType, mOverlay); /* handle click disable */ handleDisableClicking(mFrameLayout); /* setup floating action button */ if (mPointer != null) { FloatingActionButton fab = setupAndAddFABToFrameLayout(mFrameLayout); performAnimationOn(fab); } setupFrameLayout(); /* setup tooltip view */ setupToolTip(); } }); } private void checking(){ // There is not check for tooltip because tooltip can be null, it means there no tooltip will be shown } private void handleDisableClicking(FrameLayoutWithHole frameLayoutWithHole){ // 1. if user provides an overlay listener, use that as 1st priority if (mOverlay != null && mOverlay.mOnClickListener!=null) { frameLayoutWithHole.setClickable(true); frameLayoutWithHole.setOnClickListener(mOverlay.mOnClickListener); } // 2. if overlay listener is not provided, check if it's disabled else if (mOverlay != null && mOverlay.mDisableClick) { Log.w("tourguide", "Overlay's default OnClickListener is null, it will proceed to next tourguide when it is clicked"); frameLayoutWithHole.setViewHole(mHighlightedView); frameLayoutWithHole.setSoundEffectsEnabled(false); frameLayoutWithHole.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) {} // do nothing, disabled. }); } } private void setupToolTip(){ final FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT); if (mToolTip != null) { /* inflate and get views */ ViewGroup parent = (ViewGroup) mActivity.getWindow().getDecorView(); LayoutInflater layoutInflater = mActivity.getLayoutInflater(); mToolTipViewGroup = layoutInflater.inflate(R.layout.tooltip, null); View toolTipContainer = mToolTipViewGroup.findViewById(R.id.toolTip_container); TextView toolTipTitleTV = (TextView) mToolTipViewGroup.findViewById(R.id.title); TextView toolTipDescriptionTV = (TextView) mToolTipViewGroup.findViewById(R.id.description); /* set tooltip attributes */ toolTipContainer.setBackgroundColor(mToolTip.mBackgroundColor); if (mToolTip.mTitle == null){ toolTipTitleTV.setVisibility(View.GONE); } else { toolTipTitleTV.setText(mToolTip.mTitle); } if (mToolTip.mDescription == null){ toolTipDescriptionTV.setVisibility(View.GONE); } else { toolTipDescriptionTV.setText(mToolTip.mDescription); } mToolTipViewGroup.startAnimation(mToolTip.mEnterAnimation); /* add setShadow if it's turned on */ if (mToolTip.mShadow) { mToolTipViewGroup.setBackgroundDrawable(mActivity.getResources().getDrawable(R.drawable.drop_shadow)); } /* position and size calculation */ int [] pos = new int[2]; mHighlightedView.getLocationOnScreen(pos); int targetViewX = pos[0]; final int targetViewY = pos[1]; // get measured size of tooltip mToolTipViewGroup.measure(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT); int toolTipMeasuredWidth = mToolTipViewGroup.getMeasuredWidth(); int toolTipMeasuredHeight = mToolTipViewGroup.getMeasuredHeight(); Point resultPoint = new Point(); // this holds the final position of tooltip float density = mActivity.getResources().getDisplayMetrics().density; final float adjustment = 10 * density; //adjustment is that little overlapping area of tooltip and targeted button // calculate x position, based on gravity, tooltipMeasuredWidth, parent max width, x position of target view, adjustment if (toolTipMeasuredWidth > parent.getWidth()){ resultPoint.x = getXForTooTip(mToolTip.mGravity, parent.getWidth(), targetViewX, adjustment); } else { resultPoint.x = getXForTooTip(mToolTip.mGravity, toolTipMeasuredWidth, targetViewX, adjustment); } resultPoint.y = getYForTooTip(mToolTip.mGravity, toolTipMeasuredHeight, targetViewY, adjustment); // add view to parent // ((ViewGroup) mActivity.getWindow().getDecorView().findViewById(android.R.id.content)).addView(mToolTipViewGroup, layoutParams); parent.addView(mToolTipViewGroup, layoutParams); // 1. width < screen check if (toolTipMeasuredWidth > parent.getWidth()){ mToolTipViewGroup.getLayoutParams().width = parent.getWidth(); toolTipMeasuredWidth = parent.getWidth(); } // 2. x left boundary check if (resultPoint.x < 0){ mToolTipViewGroup.getLayoutParams().width = toolTipMeasuredWidth + resultPoint.x; //since point.x is negative, use plus resultPoint.x = 0; } // 3. x right boundary check int tempRightX = resultPoint.x + toolTipMeasuredWidth; if ( tempRightX > parent.getWidth()){ mToolTipViewGroup.getLayoutParams().width = parent.getWidth() - resultPoint.x; //since point.x is negative, use plus } // pass toolTip onClickListener into toolTipViewGroup if (mToolTip.mOnClickListener!=null) { mToolTipViewGroup.setOnClickListener(mToolTip.mOnClickListener); } // TODO: no boundary check for height yet, this is a unlikely case though // height boundary can be fixed by user changing the gravity to the other size, since there are plenty of space vertically compared to horizontally // this needs an viewTreeObserver, that's because TextView measurement of it's vertical height is not accurate (didn't take into account of multiple lines yet) before it's rendered // re-calculate height again once it's rendered final ViewTreeObserver viewTreeObserver = mToolTipViewGroup.getViewTreeObserver(); viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { mToolTipViewGroup.getViewTreeObserver().removeGlobalOnLayoutListener(this);// make sure this only run once int fixedY; int toolTipHeightAfterLayouted = mToolTipViewGroup.getHeight(); fixedY = getYForTooTip(mToolTip.mGravity, toolTipHeightAfterLayouted, targetViewY, adjustment); layoutParams.setMargins((int)mToolTipViewGroup.getX(),fixedY,0,0); } }); // set the position using setMargins on the left and top layoutParams.setMargins(resultPoint.x, resultPoint.y, 0, 0); } } private int getXForTooTip(int gravity, int toolTipMeasuredWidth, int targetViewX, float adjustment){ int x; if ((gravity & Gravity.LEFT) == Gravity.LEFT){ x = targetViewX - toolTipMeasuredWidth + (int)adjustment; } else if ((gravity & Gravity.RIGHT) == Gravity.RIGHT) { x = targetViewX + mHighlightedView.getWidth() - (int)adjustment; } else { x = targetViewX + mHighlightedView.getWidth() / 2 - toolTipMeasuredWidth / 2; } return x; } private int getYForTooTip(int gravity, int toolTipMeasuredHeight, int targetViewY, float adjustment){ int y; if ((gravity & Gravity.TOP) == Gravity.TOP) { if (((gravity & Gravity.LEFT) == Gravity.LEFT) || ((gravity & Gravity.RIGHT) == Gravity.RIGHT)) { y = targetViewY - toolTipMeasuredHeight + (int)adjustment; } else { y = targetViewY - toolTipMeasuredHeight - (int)adjustment; } } else { // this is center if (((gravity & Gravity.LEFT) == Gravity.LEFT) || ((gravity & Gravity.RIGHT) == Gravity.RIGHT)) { y = targetViewY + mHighlightedView.getHeight() - (int) adjustment; } else { y = targetViewY + mHighlightedView.getHeight() + (int) adjustment; } } return y; } private FloatingActionButton setupAndAddFABToFrameLayout(final FrameLayoutWithHole frameLayoutWithHole){ // invisFab is invisible, and it's only used for getting the width and height final FloatingActionButton invisFab = new FloatingActionButton(mActivity); invisFab.setSize(FloatingActionButton.SIZE_MINI); invisFab.setVisibility(View.INVISIBLE); ((ViewGroup)mActivity.getWindow().getDecorView()).addView(invisFab); // fab is the real fab that is going to be added final FloatingActionButton fab = new FloatingActionButton(mActivity); fab.setBackgroundColor(Color.BLUE); fab.setSize(FloatingActionButton.SIZE_MINI); fab.setColorNormal(mPointer.mColor); fab.setStrokeVisible(false); fab.setClickable(false); // When invisFab is layouted, it's width and height can be used to calculate the correct position of fab final ViewTreeObserver viewTreeObserver = invisFab.getViewTreeObserver(); viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { // make sure this only run once invisFab.getViewTreeObserver().removeGlobalOnLayoutListener(this); final FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT); frameLayoutWithHole.addView(fab, params); // measure size of image to be placed params.setMargins(getXBasedOnGravity(invisFab.getWidth()), getYBasedOnGravity(invisFab.getHeight()), 0, 0); } }); return fab; } private void setupFrameLayout(){ FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT); ViewGroup contentArea = (ViewGroup) mActivity.getWindow().getDecorView().findViewById(android.R.id.content); int [] pos = new int[2]; contentArea.getLocationOnScreen(pos); // frameLayoutWithHole's coordinates are calculated taking full screen height into account // but we're adding it to the content area only, so we need to offset it to the same Y value of contentArea layoutParams.setMargins(0,-pos[1],0,0); contentArea.addView(mFrameLayout, layoutParams); } private void performAnimationOn(final View view){ if (mTechnique != null && mTechnique == Technique.HorizontalLeft){ final AnimatorSet animatorSet = new AnimatorSet(); final AnimatorSet animatorSet2 = new AnimatorSet(); Animator.AnimatorListener lis1 = new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animator) {} @Override public void onAnimationCancel(Animator animator) {} @Override public void onAnimationRepeat(Animator animator) {} @Override public void onAnimationEnd(Animator animator) { view.setScaleX(1f); view.setScaleY(1f); view.setTranslationX(0); animatorSet2.start(); } }; Animator.AnimatorListener lis2 = new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animator) {} @Override public void onAnimationCancel(Animator animator) {} @Override public void onAnimationRepeat(Animator animator) {} @Override public void onAnimationEnd(Animator animator) { view.setScaleX(1f); view.setScaleY(1f); view.setTranslationX(0); animatorSet.start(); } }; long fadeInDuration = 800; long scaleDownDuration = 800; long goLeftXDuration = 2000; long fadeOutDuration = goLeftXDuration; float translationX = getScreenWidth()/2; final ValueAnimator fadeInAnim = ObjectAnimator.ofFloat(view, "alpha", 0f, 1f); fadeInAnim.setDuration(fadeInDuration); final ObjectAnimator scaleDownX = ObjectAnimator.ofFloat(view, "scaleX", 1f, 0.85f); scaleDownX.setDuration(scaleDownDuration); final ObjectAnimator scaleDownY = ObjectAnimator.ofFloat(view, "scaleY", 1f, 0.85f); scaleDownY.setDuration(scaleDownDuration); final ObjectAnimator goLeftX = ObjectAnimator.ofFloat(view, "translationX", -translationX); goLeftX.setDuration(goLeftXDuration); final ValueAnimator fadeOutAnim = ObjectAnimator.ofFloat(view, "alpha", 1f, 0f); fadeOutAnim.setDuration(fadeOutDuration); final ValueAnimator fadeInAnim2 = ObjectAnimator.ofFloat(view, "alpha", 0f, 1f); fadeInAnim2.setDuration(fadeInDuration); final ObjectAnimator scaleDownX2 = ObjectAnimator.ofFloat(view, "scaleX", 1f, 0.85f); scaleDownX2.setDuration(scaleDownDuration); final ObjectAnimator scaleDownY2 = ObjectAnimator.ofFloat(view, "scaleY", 1f, 0.85f); scaleDownY2.setDuration(scaleDownDuration); final ObjectAnimator goLeftX2 = ObjectAnimator.ofFloat(view, "translationX", -translationX); goLeftX2.setDuration(goLeftXDuration); final ValueAnimator fadeOutAnim2 = ObjectAnimator.ofFloat(view, "alpha", 1f, 0f); fadeOutAnim2.setDuration(fadeOutDuration); animatorSet.play(fadeInAnim); animatorSet.play(scaleDownX).with(scaleDownY).after(fadeInAnim); animatorSet.play(goLeftX).with(fadeOutAnim).after(scaleDownY); animatorSet2.play(fadeInAnim2); animatorSet2.play(scaleDownX2).with(scaleDownY2).after(fadeInAnim2); animatorSet2.play(goLeftX2).with(fadeOutAnim2).after(scaleDownY2); animatorSet.addListener(lis1); animatorSet2.addListener(lis2); animatorSet.start(); /* these animatorSets are kept track in FrameLayout, so that they can be cleaned up when FrameLayout is detached from window */ mFrameLayout.addAnimatorSet(animatorSet); mFrameLayout.addAnimatorSet(animatorSet2); } else if (mTechnique != null && mTechnique == Technique.HorizontalRight){ } else if (mTechnique != null && mTechnique == Technique.VerticalUpward){ } else if (mTechnique != null && mTechnique == Technique.VerticalDownward){ } else { // do click for default case final AnimatorSet animatorSet = new AnimatorSet(); final AnimatorSet animatorSet2 = new AnimatorSet(); Animator.AnimatorListener lis1 = new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animator) {} @Override public void onAnimationCancel(Animator animator) {} @Override public void onAnimationRepeat(Animator animator) {} @Override public void onAnimationEnd(Animator animator) { view.setScaleX(1f); view.setScaleY(1f); view.setTranslationX(0); animatorSet2.start(); } }; Animator.AnimatorListener lis2 = new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animator) {} @Override public void onAnimationCancel(Animator animator) {} @Override public void onAnimationRepeat(Animator animator) {} @Override public void onAnimationEnd(Animator animator) { view.setScaleX(1f); view.setScaleY(1f); view.setTranslationX(0); animatorSet.start(); } }; long fadeInDuration = 800; long scaleDownDuration = 800; long fadeOutDuration = 800; long delay = 1000; final ValueAnimator delayAnim = ObjectAnimator.ofFloat(view, "translationX", 0); delayAnim.setDuration(delay); final ValueAnimator fadeInAnim = ObjectAnimator.ofFloat(view, "alpha", 0f, 1f); fadeInAnim.setDuration(fadeInDuration); final ObjectAnimator scaleDownX = ObjectAnimator.ofFloat(view, "scaleX", 1f, 0.85f); scaleDownX.setDuration(scaleDownDuration); final ObjectAnimator scaleDownY = ObjectAnimator.ofFloat(view, "scaleY", 1f, 0.85f); scaleDownY.setDuration(scaleDownDuration); final ObjectAnimator scaleUpX = ObjectAnimator.ofFloat(view, "scaleX", 0.85f, 1f); scaleUpX.setDuration(scaleDownDuration); final ObjectAnimator scaleUpY = ObjectAnimator.ofFloat(view, "scaleY", 0.85f, 1f); scaleUpY.setDuration(scaleDownDuration); final ValueAnimator fadeOutAnim = ObjectAnimator.ofFloat(view, "alpha", 1f, 0f); fadeOutAnim.setDuration(fadeOutDuration); final ValueAnimator delayAnim2 = ObjectAnimator.ofFloat(view, "translationX", 0); delayAnim2.setDuration(delay); final ValueAnimator fadeInAnim2 = ObjectAnimator.ofFloat(view, "alpha", 0f, 1f); fadeInAnim2.setDuration(fadeInDuration); final ObjectAnimator scaleDownX2 = ObjectAnimator.ofFloat(view, "scaleX", 1f, 0.85f); scaleDownX2.setDuration(scaleDownDuration); final ObjectAnimator scaleDownY2 = ObjectAnimator.ofFloat(view, "scaleY", 1f, 0.85f); scaleDownY2.setDuration(scaleDownDuration); final ObjectAnimator scaleUpX2 = ObjectAnimator.ofFloat(view, "scaleX", 0.85f, 1f); scaleUpX2.setDuration(scaleDownDuration); final ObjectAnimator scaleUpY2 = ObjectAnimator.ofFloat(view, "scaleY", 0.85f, 1f); scaleUpY2.setDuration(scaleDownDuration); final ValueAnimator fadeOutAnim2 = ObjectAnimator.ofFloat(view, "alpha", 1f, 0f); fadeOutAnim2.setDuration(fadeOutDuration); view.setAlpha(0); animatorSet.setStartDelay(mToolTip != null ? mToolTip.mEnterAnimation.getDuration() : 0); animatorSet.play(fadeInAnim); animatorSet.play(scaleDownX).with(scaleDownY).after(fadeInAnim); animatorSet.play(scaleUpX).with(scaleUpY).with(fadeOutAnim).after(scaleDownY); animatorSet.play(delayAnim).after(scaleUpY); animatorSet2.play(fadeInAnim2); animatorSet2.play(scaleDownX2).with(scaleDownY2).after(fadeInAnim2); animatorSet2.play(scaleUpX2).with(scaleUpY2).with(fadeOutAnim2).after(scaleDownY2); animatorSet2.play(delayAnim2).after(scaleUpY2); animatorSet.addListener(lis1); animatorSet2.addListener(lis2); animatorSet.start(); /* these animatorSets are kept track in FrameLayout, so that they can be cleaned up when FrameLayout is detached from window */ mFrameLayout.addAnimatorSet(animatorSet); mFrameLayout.addAnimatorSet(animatorSet2); } } private int getScreenWidth(){ if (mActivity!=null) { return mActivity.getResources().getDisplayMetrics().widthPixels; } else { return 0; } } }
package com.goree.api.domain; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.goree.api.util.GoreeDateDeserializer; import com.goree.api.util.GoreeDateSerializer; import lombok.Getter; import lombok.Setter; import lombok.ToString; import java.util.Date; @Getter @Setter @ToString public class Meeting { private long id; private String title; private Group group; private Place place; private Member promoter; private Date date; private String description; @JsonSerialize(using= GoreeDateSerializer.class) @JsonDeserialize(using = GoreeDateDeserializer.class) public Date getDate() { return date; } @Override public boolean equals(Object other) { if (!(other instanceof Meeting)) return false; Meeting meeting = (Meeting) other; return meeting.getTitle().equals(title) && meeting.getGroup().getId() == group.getId() && meeting.getGroup().getName().equals(group.getName()) && meeting.getDate().equals(date) && meeting.getPromoter().getId() == promoter.getId() && meeting.getPromoter().getNickname().equals(promoter.getNickname()) && meeting.getPlace().getId() == place.getId(); } }
package org.uddi.api_v3; import java.io.StringReader; import java.io.StringWriter; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import javax.xml.namespace.QName; import javax.xml.transform.stream.StreamSource; import static junit.framework.Assert.fail; import static junit.framework.Assert.assertEquals; import org.junit.Test; import org.uddi.api_v3.AuthToken; import org.uddi.api_v3.ObjectFactory; public class AuthInfoTester { private final static String EXPECTED_XML_FRAGMENT = "<fragment xmlns:ns3=\"urn:uddi-org:api_v3\" xmlns:ns2=\"http://www.w3.org/2000/09/xmldsig +" <ns3:authInfo>AuthInfo String</ns3:authInfo>\n" +"</fragment>"; /** * Testing going from object to XML using JAXB. */ @Test public void marshall() { try { JAXBContext jaxbContext=JAXBContext.newInstance("org.uddi.api_v3"); Marshaller marshaller = jaxbContext.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE); marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8"); ObjectFactory factory = new ObjectFactory(); AuthToken authToken = factory.createAuthToken(); authToken.setAuthInfo("AuthInfo String"); StringWriter writer = new StringWriter(); JAXBElement<AuthToken> element = new JAXBElement<AuthToken>(new QName("","fragment"),AuthToken.class,authToken); marshaller.marshal(element,writer); String actualXml=writer.toString(); assertEquals(EXPECTED_XML_FRAGMENT, actualXml); } catch (JAXBException jaxbe) { fail("No exception should be thrown"); } } @Test public void unmarshall() { try { JAXBContext jaxbContext=JAXBContext.newInstance("org.uddi.api_v3"); Unmarshaller unMarshaller = jaxbContext.createUnmarshaller(); //unMarshaller.setProperty(U, arg1) StringReader reader = new StringReader(EXPECTED_XML_FRAGMENT); JAXBElement<AuthToken> element = unMarshaller.unmarshal(new StreamSource(reader),AuthToken.class); String infoString = element.getValue().getAuthInfo(); assertEquals("AuthInfo String", infoString); } catch (JAXBException jaxbe) { fail("No exception should be thrown"); } } }
package bf.io.openshop.api; import bf.io.openshop.CONST; public class EndPoints { /** * Base server url. */ private static final String API_URL = "http://private-4bdb8-bfashionapibfversion.apiary-mock.com/"; // mock public static final String SHOPS = API_URL.concat(CONST.ORGANIZATION_ID + "/shops"); public static final String SHOPS_SINGLE = API_URL.concat(CONST.ORGANIZATION_ID + "/shops/%d"); public static final String NAVIGATION_DRAWER = API_URL.concat("%d/navigation_drawer"); public static final String BANNERS = API_URL.concat("%d/banners"); public static final String PAGES_SINGLE = API_URL.concat("%d/pages/%d"); public static final String PAGES_TERMS_AND_COND = API_URL.concat("%d/pages/terms"); public static final String PRODUCTS = API_URL.concat("%d/products"); public static final String PRODUCTS_SINGLE = API_URL.concat("%d/products/%d"); public static final String PRODUCTS_SINGLE_RELATED = API_URL.concat("%d/products/%d?include=related"); public static final String USER_REGISTER = API_URL.concat("%d/users/register"); public static final String USER_LOGIN_EMAIL = API_URL.concat("%d/login/email"); public static final String USER_LOGIN_FACEBOOK = API_URL.concat("%d/login/facebook"); public static final String USER_RESET_PASSWORD = API_URL.concat("%d/users/reset-password"); public static final String USER_SINGLE = API_URL.concat("%d/users/%d"); public static final String USER_CHANGE_PASSWORD = API_URL.concat("%d/users/%d/password"); public static final String CART = API_URL.concat("%d/cart"); public static final String CART_INFO = API_URL.concat("%d/cart/info"); public static final String CART_ITEM = API_URL.concat("%d/cart/%d"); public static final String CART_DELIVERY_INFO = API_URL.concat("%d/cart/delivery-info"); public static final String CART_DISCOUNTS = API_URL.concat("%d/cart/discounts"); public static final String CART_DISCOUNTS_SINGLE = API_URL.concat("%d/cart/discounts/%d"); public static final String ORDERS = API_URL.concat("%d/orders"); public static final String ORDERS_SINGLE = API_URL.concat("%d/orders/%d"); public static final String BRANCHES = API_URL.concat("%d/branches"); public static final String WISHLIST = API_URL.concat("%d/wishlist"); public static final String WISHLIST_SINGLE = API_URL.concat("%d/wishlist/%d"); public static final String WISHLIST_IS_IN_WISHLIST = API_URL.concat("%d/wishlist/is-in-wishlist/%d"); public static final String REGISTER_NOTIFICATION = API_URL.concat("%d/devices"); // Notifications parameters public static final String NOTIFICATION_LINK = "link"; public static final String NOTIFICATION_MESSAGE = "message"; public static final String NOTIFICATION_TITLE = "title"; public static final String NOTIFICATION_IMAGE_URL = "image_url"; public static final String NOTIFICATION_SHOP_ID = "shop_id"; public static final String NOTIFICATION_UTM = "utm"; private EndPoints() {} }
package com.supinfo.jva.geocar; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v7.app.ActionBarActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import org.json.JSONException; import org.json.JSONObject; import com.supinfo.jva.geocar.tools.APIRequest; public class Login extends ActionBarActivity { private EditText usernameField = null; private EditText passwordField = null; private final Login context = this; private APIRequest requestStuff = new APIRequest(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); // If we couln't get the informations, we return an empty string. String username = preferences.getString("username", ""); String password = preferences.getString("password", ""); if(username.equals("") && password.equals("")) { setContentView(R.layout.login); usernameField = (EditText) findViewById(R.id.username); passwordField = (EditText) findViewById(R.id.password); Button sendDataButton = (Button) findViewById(R.id.sendButton); sendDataButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { logIn(); } }); } else { goHome(); } } void logIn() { String username = usernameField.getText().toString(); String password = passwordField.getText().toString(); if (username.isEmpty() || password.isEmpty()) { Toast.makeText(this.context, R.string.error_toast, Toast.LENGTH_SHORT).show(); } else { String response = requestStuff.requestAPI(this.context, "login", username, password); Boolean success = false; try { JSONObject json = new JSONObject(response); success = (Boolean) json.get("success"); } catch (JSONException e) { e.printStackTrace(); } if (success) { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this.context); SharedPreferences.Editor editor = preferences.edit(); editor.putString("username", username); editor.putString("password", password); editor.commit(); goHome(); } else { Toast.makeText(this.context, R.string.error_id, Toast.LENGTH_SHORT).show(); } } } void goHome() { Intent home = new Intent(Login.this, Home.class); startActivity(home); } }
package com.tsy.leanote; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.NavigationView; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AlertDialog; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.orhanobut.logger.Logger; import com.tsy.leanote.base.BaseActivity; import com.tsy.leanote.base.NormalInteractorCallback; import com.tsy.leanote.constant.EnvConstant; import com.tsy.leanote.eventbus.SyncEvent; import com.tsy.leanote.feature.note.bean.Note; import com.tsy.leanote.feature.note.bean.Notebook; import com.tsy.leanote.feature.note.contract.NoteContract; import com.tsy.leanote.feature.note.contract.NotebookContract; import com.tsy.leanote.feature.note.interactor.NoteInteractor; import com.tsy.leanote.feature.note.interactor.NotebookInteractor; import com.tsy.leanote.feature.note.view.NoteIndexFragment; import com.tsy.leanote.feature.note.view.NoteViewActivity; import com.tsy.leanote.feature.user.bean.UserInfo; import com.tsy.leanote.feature.user.contract.UserContract; import com.tsy.leanote.feature.user.interactor.UserInteractor; import com.tsy.leanote.feature.user.view.LoginActivity; import com.tsy.leanote.widget.webview.WebviewFragment; import com.tsy.leanote.glide.CropCircleTransformation; import com.tsy.sdk.myutil.ToastUtils; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; public class HomeActivity extends BaseActivity implements NavigationView.OnNavigationItemSelectedListener, Toolbar.OnMenuItemClickListener { @BindView(R.id.toolbar) Toolbar toolbar; @BindView(R.id.drawer_layout) DrawerLayout drawer_layout; @BindView(R.id.nav_view) NavigationView nav_view; @BindView(R.id.fab_add) FloatingActionButton fab_add; ImageView img_avatar; TextView txt_username; TextView txt_email; private UserInfo mUserInfo; private UserContract.Interactor mUserInteractor; private NotebookContract.Interactor mNotebookInteractor; private NoteContract.Interactor mNoteInteractor; private NoteIndexFragment mNoteIndexFragment; private WebviewFragment mBlogWebviewFragment; private WebviewFragment mLeeWebviewFragment; private ProgressDialog mSyncProgressDialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_home); ButterKnife.bind(this); EventBus.getDefault().register(this); mSyncProgressDialog = new ProgressDialog(this); mSyncProgressDialog.setCancelable(false); mSyncProgressDialog.setMessage(getString(R.string.sync_ing)); mUserInteractor = new UserInteractor(this); mUserInfo = mUserInteractor.getCurUser(); MyApplication.getInstance().setUserInfo(mUserInfo); mNotebookInteractor = new NotebookInteractor(this); mNoteInteractor = new NoteInteractor(this); //init toolbar toolbar.setTitle(R.string.toolbar_title_note); setSupportActionBar(toolbar); toolbar.setOnMenuItemClickListener(this); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer_layout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer_layout.addDrawerListener(toggle); toggle.syncState(); //init navigationview nav_view.setNavigationItemSelectedListener(this); View headerView = nav_view.getHeaderView(0); img_avatar = (ImageView) headerView.findViewById(R.id.img_avatar); txt_username = (TextView) headerView.findViewById(R.id.txt_username); txt_email = (TextView) headerView.findViewById(R.id.txt_email); nav_view.getMenu().getItem(0).setChecked(true); //menu Glide.with(this) .load(mUserInfo.getLogo()) .placeholder(R.drawable.default_avatar) .bitmapTransform(new CropCircleTransformation(this)) .into(img_avatar); txt_username.setText(mUserInfo.getUsername()); txt_email.setText(mUserInfo.getEmail()); //Default Switch To Note switchNote(); doSync(); } @Override public void onDestroy() { super.onDestroy(); EventBus.getDefault().unregister(this); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @OnClick(R.id.fab_add) public void addNote() { startActivity(NoteViewActivity.createIntent(this)); } private void switchNote() { toolbar.setTitle(R.string.toolbar_title_note); FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction transaction = fragmentManager.beginTransaction(); if(mNoteIndexFragment == null) { mNoteIndexFragment = new NoteIndexFragment(); transaction.add(R.id.fl_content, mNoteIndexFragment, "NoteIndexFragment"); } if(mBlogWebviewFragment != null) { transaction.hide(mBlogWebviewFragment); } if(mLeeWebviewFragment != null) { transaction.hide(mLeeWebviewFragment); } transaction.show(mNoteIndexFragment); transaction.commit(); } private void switchBlog() { toolbar.setTitle(R.string.toolbar_title_blog); FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction transaction = fragmentManager.beginTransaction(); if(mBlogWebviewFragment == null) { mBlogWebviewFragment = new WebviewFragment(); mBlogWebviewFragment.setArguments(WebviewFragment.createArguments(EnvConstant.HOST + "/blog/" + mUserInfo.getEmail())); transaction.add(R.id.fl_content, mBlogWebviewFragment, "BlogWebviewFragment"); } if(mNoteIndexFragment != null) { transaction.hide(mNoteIndexFragment); } if(mLeeWebviewFragment != null) { transaction.hide(mLeeWebviewFragment); } transaction.show(mBlogWebviewFragment); transaction.commit(); } private void switchLee() { toolbar.setTitle(R.string.toolbar_title_lee); FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction transaction = fragmentManager.beginTransaction(); if(mLeeWebviewFragment == null) { mLeeWebviewFragment = new WebviewFragment(); mLeeWebviewFragment.setArguments(WebviewFragment.createArguments("http://lea.leanote.com/index")); transaction.add(R.id.fl_content, mLeeWebviewFragment, "LeeWebviewFragment"); } if(mNoteIndexFragment != null) { transaction.hide(mNoteIndexFragment); } if(mBlogWebviewFragment != null) { transaction.hide(mBlogWebviewFragment); } transaction.show(mLeeWebviewFragment); transaction.commit(); } @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { switch (item.getItemId()) { case R.id.nav_note: drawer_layout.closeDrawer(GravityCompat.START); switchNote(); showSyncAndNote(true); break; case R.id.nav_blog: drawer_layout.closeDrawer(GravityCompat.START); switchBlog(); showSyncAndNote(false); break; case R.id.nav_lee: drawer_layout.closeDrawer(GravityCompat.START); switchLee(); showSyncAndNote(false); break; case R.id.nav_exit: AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(R.string.user_exit_dialog_title); builder.setNegativeButton(R.string.cancel, null); builder.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { doExit(); } }); builder.show(); break; default: break; } return true; } @Override public boolean onMenuItemClick(MenuItem item) { switch (item.getItemId()) { case R.id.action_sync: doSync(); break; } return true; } @Override public void onBackPressed() { if (drawer_layout.isDrawerOpen(GravityCompat.START)) { drawer_layout.closeDrawer(GravityCompat.START); } else { super.onBackPressed(); } } @Subscribe(threadMode = ThreadMode.MAIN) public void onSyncEvent(SyncEvent event) { switch (event.getMsg()) { case SyncEvent.MSG_SYNC: doSync(); break; } } /** * * @param show */ private void showSyncAndNote(boolean show) { MenuItem syncItem = toolbar.getMenu().findItem(R.id.action_sync); if(show) { syncItem.setVisible(true); fab_add.setVisibility(View.VISIBLE); } else { syncItem.setVisible(false); fab_add.setVisibility(View.GONE); } } private void doSync() { mSyncProgressDialog.show(); mUserInteractor.getSyncState(mUserInfo, new UserContract.GetSyncStateCallback() { @Override public void onSuccess(final int lastSyncUsn) { if(mUserInfo.getLast_usn() >= lastSyncUsn) { mSyncProgressDialog.dismiss(); return; } mNotebookInteractor.sync(mUserInfo, new NotebookContract.GetNotebooksCallback() { @Override public void onSuccess(List<Notebook> notebooks) { mNoteInteractor.sync(mUserInfo, new NoteContract.GetNotesCallback() { @Override public void onSuccess(List<Note> notes) { // lastSyncUsn mUserInteractor.updateLastSyncUsn(mUserInfo, lastSyncUsn); mSyncProgressDialog.dismiss(); Logger.i("Sync Usn %s", lastSyncUsn); EventBus.getDefault().post(new SyncEvent(SyncEvent.MSG_REFRESH)); } @Override public void onFailure(String msg) { mSyncProgressDialog.dismiss(); ToastUtils.showShort(getApplicationContext(), msg); } }); } @Override public void onFailure(String msg) { mSyncProgressDialog.dismiss(); ToastUtils.showShort(getApplicationContext(), msg); } }); } @Override public void onFailure(String msg) { mSyncProgressDialog.dismiss(); ToastUtils.showShort(getApplicationContext(), msg); } }); } private void doExit() { mUserInteractor.logout(mUserInfo, new NormalInteractorCallback() { @Override public void onSuccess() { startActivity(LoginActivity.createIntent(HomeActivity.this)); } @Override public void onFailure(String msg) { ToastUtils.showShort(getApplicationContext(), msg); } }); } public static Intent createIntent(Context context) { Intent intent = new Intent(context, HomeActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); return intent; } }
package com.vaya.voicebox; import android.app.Dialog; import android.content.Context; import android.preference.DialogPreference; import android.util.AttributeSet; import android.view.View; import android.widget.NumberPicker; import android.widget.NumberPicker.OnValueChangeListener; public class NumberPickerPreference extends DialogPreference { /*@Override protected void onBindDialogView(View view) { NumberPicker np = (NumberPicker) view.findViewById(R.id.numberPicker1); np.setMaxValue(100); // max value 100 np.setMinValue(0); // min value 0 np.setWrapSelectorWheel(false); np.setOnValueChangedListener((OnValueChangeListener) this); super.onBindDialogView(view); }*/ public NumberPickerPreference(Context context, AttributeSet attrs) { super(context, attrs); setDialogLayoutResource(R.xml.dialog); setPositiveButtonText(android.R.string.ok); setNegativeButtonText(android.R.string.cancel); setDialogIcon(null); } }
package ti.modules.titanium.xml; import org.appcelerator.kroll.KrollProxy; import org.appcelerator.kroll.annotations.Kroll; import org.appcelerator.titanium.TiContext; import org.w3c.dom.Attr; import org.w3c.dom.CDATASection; import org.w3c.dom.Comment; import org.w3c.dom.DOMException; import org.w3c.dom.Document; import org.w3c.dom.DocumentFragment; import org.w3c.dom.DocumentType; import org.w3c.dom.Element; import org.w3c.dom.Entity; import org.w3c.dom.EntityReference; import org.w3c.dom.Node; import org.w3c.dom.Notation; import org.w3c.dom.ProcessingInstruction; import org.w3c.dom.Text; @Kroll.proxy public class NodeProxy extends KrollProxy { @Kroll.constant public static final int ATTRIBUTE_NODE = Node.ATTRIBUTE_NODE; @Kroll.constant public static final int CDATA_SECTION_NODE = Node.CDATA_SECTION_NODE; @Kroll.constant public static final int COMMENT_NODE = Node.COMMENT_NODE; @Kroll.constant public static final int DOCUMENT_FRAGMENT_NODE = Node.DOCUMENT_FRAGMENT_NODE; @Kroll.constant public static final int DOCUMENT_NODE = Node.DOCUMENT_NODE; @Kroll.constant public static final int DOCUMENT_TYPE_NODE = Node.DOCUMENT_TYPE_NODE; @Kroll.constant public static final int ELEMENT_NODE = Node.ELEMENT_NODE; @Kroll.constant public static final int ENTITY_NODE = Node.ENTITY_NODE; @Kroll.constant public static final int ENTITY_REFERENCE_NODE = Node.ENTITY_REFERENCE_NODE; @Kroll.constant public static final int NOTATION_NODE = Node.NOTATION_NODE; @Kroll.constant public static final int PROCESSING_INSTRUCTION_NODE = Node.PROCESSING_INSTRUCTION_NODE; @Kroll.constant public static final int TEXT_NODE = Node.TEXT_NODE; protected Node node; public NodeProxy(TiContext context, Node node) { super(context); this.node = node; } public Node getNode() { return node; } // We cache node proxies so we're not constructing new ones on every single call // on node finalize we have to go back through and remove each proxy public static NodeProxy getNodeProxy(TiContext context, Node node) { NodeProxy proxy; switch (node.getNodeType()) { case Node.ATTRIBUTE_NODE: proxy = new AttrProxy(context, (Attr)node); break; case Node.CDATA_SECTION_NODE: proxy = new CDATASectionProxy(context, (CDATASection)node); break; case Node.COMMENT_NODE: proxy = new CommentProxy(context, (Comment)node); break; case Node.DOCUMENT_FRAGMENT_NODE: proxy = new DocumentFragmentProxy(context, (DocumentFragment)node); break; case Node.DOCUMENT_NODE: proxy = new DocumentProxy(context, (Document)node); break; case Node.DOCUMENT_TYPE_NODE: proxy = new DocumentTypeProxy(context, (DocumentType)node); break; case Node.ELEMENT_NODE: proxy = new ElementProxy(context, (Element)node); break; case Node.ENTITY_NODE: proxy = new EntityProxy(context, (Entity)node); break; case Node.ENTITY_REFERENCE_NODE: proxy = new EntityReferenceProxy(context, (EntityReference)node); break; case Node.NOTATION_NODE: proxy = new NotationProxy(context, (Notation)node); break; case Node.PROCESSING_INSTRUCTION_NODE: proxy = new ProcessingInstructionProxy(context, (ProcessingInstruction)node); break; case Node.TEXT_NODE: proxy = new TextProxy(context, (Text)node); break; default: proxy = new NodeProxy(context, node); break; } return proxy; } public static NodeProxy removeProxyForNode(TiContext context, Node node) { // if we're here then a proxy was never generated for this node // just return a temporary wrapper in this case return new NodeProxy(context, node); } @SuppressWarnings("unchecked") protected <T extends NodeProxy> T getProxy(Node node) { return (T) getNodeProxy(getTiContext(), node); } @Kroll.method public NodeProxy appendChild(NodeProxy newChild) throws DOMException { return getProxy(node.appendChild(newChild.node)); } @Kroll.method public NodeProxy cloneNode(boolean deep) { return getProxy(node.cloneNode(deep)); } @Kroll.getProperty @Kroll.method public NamedNodeMapProxy getAttributes() { return new NamedNodeMapProxy(getTiContext(), node.getAttributes()); } @Kroll.getProperty @Kroll.method public NodeListProxy getChildNodes() { return new NodeListProxy(getTiContext(), node.getChildNodes()); } @Kroll.getProperty @Kroll.method public NodeProxy getFirstChild() { return getProxy(node.getFirstChild()); } @Kroll.getProperty @Kroll.method public NodeProxy getLastChild() { return getProxy(node.getLastChild()); } @Kroll.getProperty @Kroll.method public String getLocalName() { return node.getLocalName(); } @Kroll.getProperty @Kroll.method public String getNamespaceURI() { return node.getNamespaceURI(); } @Kroll.getProperty @Kroll.method public NodeProxy getNextSibling() { return getProxy(node.getNextSibling()); } @Kroll.getProperty @Kroll.method public String getNodeName() { return node.getNodeName(); } @Kroll.getProperty @Kroll.method public short getNodeType() { return node.getNodeType(); } @Kroll.getProperty @Kroll.method public String getNodeValue() throws DOMException { return node.getNodeValue(); } @Kroll.getProperty @Kroll.method public DocumentProxy getOwnerDocument() { return new DocumentProxy(getTiContext(), node.getOwnerDocument()); } @Kroll.getProperty @Kroll.method public NodeProxy getParentNode() { return getProxy(node.getParentNode()); } @Kroll.getProperty @Kroll.method public String getPrefix() { return node.getPrefix(); } @Kroll.getProperty @Kroll.method public NodeProxy getPreviousSibling() { return getProxy(node.getPreviousSibling()); } @Kroll.method public boolean hasAttributes() { return node.hasAttributes(); } @Kroll.method public boolean hasChildNodes() { return node.hasChildNodes(); } @Kroll.method public NodeProxy insertBefore(NodeProxy newChild, NodeProxy refChild) throws DOMException { return getProxy(node.insertBefore(newChild.node, refChild.node)); } @Kroll.method public boolean isSupported(String feature, String version) { return node.isSupported(feature, version); } @Kroll.method public void normalize() { node.normalize(); } @Kroll.method public NodeProxy removeChild(NodeProxy oldChild) throws DOMException { Node oldNode = node.removeChild(oldChild.node); return removeProxyForNode(getTiContext(), oldNode); } @Kroll.method public NodeProxy replaceChild(NodeProxy newChild, NodeProxy oldChild) throws DOMException { Node oldNode = node.replaceChild(newChild.node, oldChild.node); return removeProxyForNode(getTiContext(), oldNode); } @Kroll.setProperty @Kroll.method public void setNodeValue(String nodeValue) throws DOMException { node.setNodeValue(nodeValue); } @Kroll.setProperty @Kroll.method public void setPrefix(String prefix) throws DOMException { node.setPrefix(prefix); } @Kroll.method public XPathNodeListProxy evaluate(String xpath) { return XPathUtil.evaluate(this, xpath); } @Override public boolean equals(Object o) { if (this.node == null || !(o instanceof NodeProxy)) { return super.equals(o); } return this.node.equals(((NodeProxy) o).node); } @Override public int hashCode() { if (this.node == null) { return super.hashCode(); } return this.node.hashCode(); } }
package com.hairysoft.cockcrow; import android.animation.Animator; import android.animation.ValueAnimator; import android.app.Activity; import android.app.AlarmManager; import android.app.DialogFragment; import android.app.PendingIntent; import android.bluetooth.BluetoothAdapter; // import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.media.RingtoneManager; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Message; import com.hairysoft.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.animation.AccelerateDecelerateInterpolator; import android.widget.AnalogClock; import android.widget.ImageButton; import android.widget.SeekBar; import android.widget.TextView; // import android.widget.Toast; import com.hairysoft.alarm.AlarmActivity; import com.hairysoft.alarm.AlarmReceiver; import com.hairysoft.bt.ConnectThread; import com.hairysoft.bt.Dispatcher; import com.hairysoft.message.BaseMessage; import com.hairysoft.message.ClockMessage; import com.hairysoft.message.DemoSunrise; import com.hairysoft.message.SetAlarm; import com.hairysoft.message.SetBrightness; import com.hairysoft.message.TurnOnOff; import com.hairysoft.util.Constants; import org.json.JSONException; import java.util.Calendar; /** * Main activity for the application */ public class MainActivity extends Activity implements TimePickerFragment.OnAlarmSelectedListener { private final static String TAG = "MainActivity"; // The views used with a global scope private AnalogClock analogClock; private TextView alarmTimeView; private TextView alarmButtonText; private TextView connStatus; // Preferences private String alarmTime; private String notySoundUri; private SharedPreferences prefs; // Bluetooth connection handlers private BluetoothAdapter mBluetoothAdapter; private WakyBluetoothService wakyBluetoothService; // Alarm handlers private AlarmManager mAlarmManager; private Intent mNotificationReceiverIntent; private PendingIntent mNotificationReceiverPendingIntent; private boolean sliderAnimating = false; // Handler to receive notifications from other places within the application, and show/handle them in the UI thread private final Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { // Context c = getApplicationContext(); switch (msg.what) { case Constants.BT_CONNECT_SUCCESS: // Toast.makeText(c, R.string.connect_success, Toast.LENGTH_LONG).show(); connStatus.setText(R.string.connected); break; case Constants.BT_CONNECT_FAILED: // Toast.makeText(c, R.string.connect_failed, Toast.LENGTH_LONG).show(); connStatus.setText(R.string.cant_connect); wakyBluetoothService.discoverWaky(true); break; case Constants.BT_DISCONNECT: connStatus.setText(R.string.disconnected); wakyBluetoothService.discoverWaky(true); break; case Constants.UPDATE_ALARM: if(alarmTime != null && alarmTime.length() > 0) { String[] items = alarmTime.split(":"); int hourOfDay = Integer.parseInt(items[0]); int minute = Integer.parseInt(items[1]); try { Dispatcher.queueMessage(new SetAlarm(hourOfDay, minute).getJSON()); } catch(JSONException ex) { } } break; } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initApp(); initGUI(); // Register the types of messages to be recognized by the application // More information in BaseMessage.java BaseMessage.registerClass(ClockMessage.class, SetBrightness.class, DemoSunrise.class, SetAlarm.class, TurnOnOff.class); mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); wakyBluetoothService = new WakyBluetoothService(this, mHandler); Dispatcher.init(); mAlarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); mNotificationReceiverIntent = new Intent(this, AlarmReceiver.class); mNotificationReceiverPendingIntent = PendingIntent.getBroadcast(this, 0, mNotificationReceiverIntent, 0); } @Override protected void onStart() { super.onStart(); if(!ConnectThread.isConnected()) { if (mBluetoothAdapter == null) { // This should not happen, though mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); } if (!mBluetoothAdapter.isEnabled()) { Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableIntent, Constants.AR_REQUEST_ENABLE_BT); } else { wakyBluetoothService.discoverWaky(); } } else { connStatus.setText(R.string.connected); } } @Override protected void onStop() { super.onStop(); wakyBluetoothService.holdWaky(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case Constants.AR_REQUEST_ENABLE_BT: if(resultCode == Activity.RESULT_OK) { wakyBluetoothService.discoverWaky(); } else { Log.d(TAG, "BT not enabled"); // Toast.makeText(this, R.string.bt_not_enabled, Toast.LENGTH_LONG).show(); } break; case Constants.AR_SELECT_ALARMTONE: Uri uri = data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI); if(uri != null) { String name = RingtoneManager.getRingtone(this, uri).getTitle(this); Log.d(TAG, "Selected sound: " + name + " (" + uri.toString() + ")"); alarmButtonText.setText(name); SharedPreferences.Editor editor = prefs.edit(); editor.putString("noty_sound_uri", uri.toString()); editor.putString("noty_sound_name", name); editor.commit(); } break; } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.action_add_alarm) { Log.d(TAG, "Adding alarm"); DialogFragment timePicker = new TimePickerFragment(); timePicker.show(getFragmentManager(), "timePicker"); return true; } else if(id == R.id.action_search_waky) { Log.d(TAG, "Searching for waky"); if(!ConnectThread.isConnected()) { wakyBluetoothService.discoverWaky(true); } return true; } else if(id == R.id.action_demo) { Log.d(TAG, "Demoing sunrise"); try { Dispatcher.queueMessage(new DemoSunrise().getJSON()); } catch(JSONException ex) { } return true; } else if(id == R.id.action_demo_alarm) { startActivity(new Intent(this, AlarmActivity.class)); } return super.onOptionsItemSelected(item); } @Override public void onAlarmSelected(int hourOfDay, int minute) { String timeString = hourOfDay+":"+(minute < 10 ? "0" : "")+minute; SharedPreferences.Editor editor = prefs.edit(); editor.putString("alarm_time", timeString); editor.commit(); alarmTimeView.setText(timeString); alarmTime = timeString; Calendar c = Calendar.getInstance(); c.set(Calendar.HOUR_OF_DAY, hourOfDay); c.set(Calendar.MINUTE, minute); if(c.getTimeInMillis() < System.currentTimeMillis()) { c.add(Calendar.DATE, 1); } mAlarmManager.setExact(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), mNotificationReceiverPendingIntent); try { Dispatcher.queueMessage(new SetAlarm(hourOfDay, minute).getJSON()); } catch(JSONException ex) { } } private void initApp() { prefs = getSharedPreferences(Constants.PREFS_NAME, MODE_PRIVATE); alarmTime = prefs.getString("alarm_time", null); notySoundUri = prefs.getString("noty_sound_uri", null); } private void initGUI() { /* AnalogClock */ analogClock = (AnalogClock) findViewById(R.id.analogClock); /* SeekBar - Set current brightness */ final SeekBar seekBar = (SeekBar) findViewById(R.id.seekBar); seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int i, boolean b) { // Checking if the progress is changing due to an animation, in order to avoid flooding the bluetooth channel with unnecessary messages if(!sliderAnimating) { Log.d(TAG, "Setting brightness @ " + i); try { Dispatcher.queueMessage(new SetBrightness(i).getJSON()); } catch(JSONException ex) { } } } @Override public void onStartTrackingTouch(SeekBar seekBar) { // Not implemented } @Override public void onStopTrackingTouch(SeekBar seekBar) { // Not implemented } }); /* Value animator end listener */ final Animator.AnimatorListener animatorListener = new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animator) { sliderAnimating = true; } @Override public void onAnimationEnd(Animator animator) { sliderAnimating = false; if(seekBar.getProgress() == 0) { Log.d(TAG, "Leds turned off"); } else if(seekBar.getProgress() == seekBar.getMax()) { Log.d(TAG, "Leds set at full brightness"); } try { Dispatcher.queueMessage(new TurnOnOff(seekBar.getProgress() > seekBar.getMax() - 1).getJSON()); } catch(JSONException ex) { } } @Override public void onAnimationCancel(Animator animator) { // Not implemented } @Override public void onAnimationRepeat(Animator animator) { // Not implemented } }; /* Alarm time view */ alarmTimeView = (TextView) findViewById(R.id.alarmTime); alarmTimeView.setText(alarmTime == null ? "--:--" : alarmTime); alarmTimeView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.d(TAG, "Adding alarm"); DialogFragment timePicker = new TimePickerFragment(); timePicker.show(getFragmentManager(), "timePicker"); } }); /* Power off leds */ ImageButton powerOff = (ImageButton) findViewById(R.id.powerOff); powerOff.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Log.d(TAG, "Powering leds off"); ValueAnimator anim = ValueAnimator.ofInt(seekBar.getProgress(), 0); anim.setDuration(500); anim.addListener(animatorListener); anim.setInterpolator(new AccelerateDecelerateInterpolator()); anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator valueAnimator) { seekBar.setProgress((Integer)valueAnimator.getAnimatedValue()); } }); anim.start(); } }); /* Leds full brightness */ ImageButton powerOn = (ImageButton) findViewById(R.id.powerOn); powerOn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Log.d(TAG, "Settings leds to full brightness"); ValueAnimator anim = ValueAnimator.ofInt(seekBar.getProgress(), seekBar.getMax()); anim.setDuration(500); anim.addListener(animatorListener); anim.setInterpolator(new AccelerateDecelerateInterpolator()); anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator valueAnimator) { seekBar.setProgress((Integer)valueAnimator.getAnimatedValue()); } }); anim.start(); } }); /* Remove alarm */ ImageButton removeAlarm = (ImageButton) findViewById(R.id.deleteAlarm); removeAlarm.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.d(TAG, "Removing alarm"); SharedPreferences.Editor editor = prefs.edit(); editor.remove("alarm_time"); editor.commit(); alarmTimeView.setText(" mAlarmManager.cancel(mNotificationReceiverPendingIntent); try { Dispatcher.queueMessage(new SetAlarm(-1, -1).getJSON()); } catch(JSONException ex) { } } }); /* Connection status */ connStatus = (TextView) findViewById(R.id.connStatus); /* Ringtone selection */ View.OnClickListener selectRingTone = new View.OnClickListener() { @Override public void onClick(View v) { Intent sound = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER); sound.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE, RingtoneManager.TYPE_ALARM); if(notySoundUri != null) { sound.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, Uri.parse(notySoundUri)); } startActivityForResult(sound, Constants.AR_SELECT_ALARMTONE); } }; ImageButton alarmButtonImage = (ImageButton) findViewById(R.id.alarmTone); alarmButtonImage.setOnClickListener(selectRingTone); alarmButtonText = (TextView) findViewById(R.id.alarmRingtone); alarmButtonText.setOnClickListener(selectRingTone); alarmButtonText.setText(prefs.getString("noty_sound_name", "Default ringtone")); } }
package com.oblador.keychain; import android.content.Context; import android.content.SharedPreferences; import android.os.Build; import android.security.KeyPairGeneratorSpec; import android.security.keystore.KeyGenParameterSpec; import android.security.keystore.KeyProperties; import android.support.annotation.NonNull; import android.util.Base64; import android.util.Log; import com.facebook.android.crypto.keychain.AndroidConceal; import com.facebook.android.crypto.keychain.SharedPrefsBackedKeyChain; import com.facebook.crypto.Crypto; import com.facebook.crypto.CryptoConfig; import com.facebook.crypto.Entity; import com.facebook.crypto.keychain.KeyChain; import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.Promise; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; import com.facebook.react.bridge.ReadableMap; import com.facebook.react.bridge.WritableMap; import com.oblador.keychain.exceptions.CryptoFailedException; import com.oblador.keychain.exceptions.EmptyParameterException; import com.oblador.keychain.exceptions.KeyStoreAccessException; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.math.BigInteger; import java.nio.charset.Charset; import java.security.InvalidAlgorithmParameterException; import java.security.KeyPairGenerator; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.UnrecoverableKeyException; import java.security.cert.CertificateException; import java.security.spec.AlgorithmParameterSpec; import java.util.Calendar; import java.util.Date; import javax.crypto.Cipher; import javax.crypto.CipherInputStream; import javax.crypto.CipherOutputStream; import javax.security.auth.x500.X500Principal; public class KeychainModule extends ReactContextBaseJavaModule { public static final String E_EMPTY_PARAMETERS = "E_EMPTY_PARAMETERS"; public static final String E_CRYPTO_FAILED = "E_CRYPTO_FAILED"; public static final String E_UNSUPPORTED_KEYSTORE = "E_UNSUPPORTED_KEYSTORE"; public static final String E_KEYSTORE_ACCESS_ERROR = "E_KEYSTORE_ACCESS_ERROR"; public static final String KEYCHAIN_MODULE = "RNKeychainManager"; public static final String KEYCHAIN_DATA = "RN_KEYCHAIN"; public static final String DEFAULT_ALIAS = "RN_KEYCHAIN_DEFAULT_ALIAS"; public static final int YEARS_TO_LAST = 15; public static final String LEGACY_DELIMITER = ":"; public static final String DELIMITER = "_"; public static final String KEYSTORE_TYPE = "AndroidKeyStore"; public static final String RSA_ALGORITHM = "RSA/ECB/PKCS1Padding"; private final Crypto crypto; private final SharedPreferences prefs; private class ResultSet { final String service; final byte[] decryptedUsername; final byte[] decryptedPassword; public ResultSet(String service, byte[] decryptedUsername, byte[] decryptedPassword) { this.service = service; this.decryptedUsername = decryptedUsername; this.decryptedPassword = decryptedPassword; } } @Override public String getName() { return KEYCHAIN_MODULE; } public KeychainModule(ReactApplicationContext reactContext) { super(reactContext); KeyChain keyChain = new SharedPrefsBackedKeyChain(getReactApplicationContext(), CryptoConfig.KEY_256); crypto = AndroidConceal.get().createDefaultCrypto(keyChain); prefs = this.getReactApplicationContext().getSharedPreferences(KEYCHAIN_DATA, Context.MODE_PRIVATE); } @ReactMethod public void setGenericPasswordForOptions(String service, String username, String password, Promise promise) { try { setGenericPasswordForOptions(service, username, password); // Clean legacy values (if any) resetGenericPasswordForOptionsLegacy(service); promise.resolve("KeychainModule saved the data"); } catch (EmptyParameterException e) { Log.e(KEYCHAIN_MODULE, e.getMessage()); promise.reject(E_EMPTY_PARAMETERS, e); } catch (CryptoFailedException e) { Log.e(KEYCHAIN_MODULE, e.getMessage()); promise.reject(E_CRYPTO_FAILED, e); } catch (KeyStoreException e) { Log.e(KEYCHAIN_MODULE, e.getMessage()); promise.reject(E_UNSUPPORTED_KEYSTORE, e); } catch (KeyStoreAccessException e) { Log.e(KEYCHAIN_MODULE, e.getMessage()); promise.reject(E_KEYSTORE_ACCESS_ERROR, e); } } private void setGenericPasswordForOptions(String service, String username, String password) throws EmptyParameterException, CryptoFailedException, KeyStoreException, KeyStoreAccessException { if (username == null || username.isEmpty() || password == null || password.isEmpty()) { throw new EmptyParameterException("you passed empty or null username/password"); } service = service == null ? DEFAULT_ALIAS : service; KeyStore keyStore = getKeyStoreAndLoad(); try { if (!keyStore.containsAlias(service)) { AlgorithmParameterSpec spec; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { spec = new KeyGenParameterSpec.Builder( service, KeyProperties.PURPOSE_DECRYPT | KeyProperties.PURPOSE_ENCRYPT) .setDigests(KeyProperties.DIGEST_SHA256, KeyProperties.DIGEST_SHA512) .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_PKCS1) .setRandomizedEncryptionRequired(true) //.setUserAuthenticationRequired(true) // Will throw InvalidAlgorithmParameterException if there is no fingerprint enrolled on the device .setKeySize(2048) .build(); } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { Calendar cal = Calendar.getInstance(); Date start = cal.getTime(); cal.add(Calendar.YEAR, YEARS_TO_LAST); Date end = cal.getTime(); spec = new KeyPairGeneratorSpec.Builder(this.getReactApplicationContext()) .setAlias(service) .setSubject(new X500Principal("CN=domain.com, O=security")) .setSerialNumber(BigInteger.ONE) .setStartDate(start) .setEndDate(end) .setKeySize(2048) .build(); } else { throw new CryptoFailedException("Unsupported Android SDK " + Build.VERSION.SDK_INT); } KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", KEYSTORE_TYPE); generator.initialize(spec); generator.generateKeyPair(); } PublicKey publicKey = keyStore.getCertificate(service).getPublicKey(); String encryptedUsername = encryptString(publicKey, service, username); String encryptedPassword = encryptString(publicKey, service, password); SharedPreferences.Editor prefsEditor = prefs.edit(); prefsEditor.putString(service + DELIMITER + "u", encryptedUsername); prefsEditor.putString(service + DELIMITER + "p", encryptedPassword); prefsEditor.apply(); Log.d(KEYCHAIN_MODULE, "saved the data"); } catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException | NoSuchProviderException e) { throw new CryptoFailedException("Could not encrypt data for service " + service, e); } } private String encryptString(PublicKey publicKey, String service, String value) throws CryptoFailedException { try { Cipher cipher = Cipher.getInstance(RSA_ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE, publicKey); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); CipherOutputStream cipherOutputStream = new CipherOutputStream(outputStream, cipher); cipherOutputStream.write(value.getBytes("UTF-8")); cipherOutputStream.close(); byte[] encryptedBytes = outputStream.toByteArray(); return Base64.encodeToString(encryptedBytes, Base64.DEFAULT); } catch (Exception e) { throw new CryptoFailedException("Could not encrypt value for service " + service, e); } } @ReactMethod public void getGenericPasswordForOptions(String service, Promise promise) { service = service == null ? DEFAULT_ALIAS : service; try { byte[] recuser = getBytesFromPrefs(service, DELIMITER + "u"); byte[] recpass = getBytesFromPrefs(service, DELIMITER + "p"); if (recuser == null || recpass == null) { // Check if the values are stored using the LEGACY_DELIMITER and thus encrypted using FaceBook's Conceal ResultSet resultSet = getGenericPasswordForOptionsUsingConceal(service); if (resultSet != null) { // Store the values using the new delimiter and the KeyStore setGenericPasswordForOptions( resultSet.service, new String(resultSet.decryptedUsername, Charset.forName("UTF-8")), new String(resultSet.decryptedUsername, Charset.forName("UTF-8"))); // Remove the legacy value(s) resetGenericPasswordForOptionsLegacy(service); recuser = resultSet.decryptedUsername; recpass = resultSet.decryptedPassword; } else { Log.e(KEYCHAIN_MODULE, "no keychain entry found for service: " + service); promise.resolve(false); return; } } KeyStore keyStore = getKeyStoreAndLoad(); PrivateKey privateKey = (PrivateKey) keyStore.getKey(service, null); byte[] decryptedUsername = decryptBytes(privateKey, recuser); byte[] decryptedPassword = decryptBytes(privateKey, recpass); WritableMap credentials = Arguments.createMap(); credentials.putString("service", service); credentials.putString("username", new String(decryptedUsername, Charset.forName("UTF-8"))); credentials.putString("password", new String(decryptedPassword, Charset.forName("UTF-8"))); promise.resolve(credentials); } catch (KeyStoreException e) { Log.e(KEYCHAIN_MODULE, e.getMessage()); promise.reject(E_UNSUPPORTED_KEYSTORE, e); } catch (KeyStoreAccessException e) { Log.e(KEYCHAIN_MODULE, e.getMessage()); promise.reject(E_KEYSTORE_ACCESS_ERROR, e); } catch (UnrecoverableKeyException | NoSuchAlgorithmException | CryptoFailedException e) { Log.e(KEYCHAIN_MODULE, e.getMessage()); promise.reject(E_CRYPTO_FAILED, e); } catch (EmptyParameterException e) { Log.e(KEYCHAIN_MODULE, e.getMessage()); promise.reject(E_EMPTY_PARAMETERS, e); } } private byte[] decryptBytes(PrivateKey privateKey, byte[] bytes) throws CryptoFailedException { try { Cipher cipher = Cipher.getInstance(RSA_ALGORITHM); cipher.init(Cipher.DECRYPT_MODE, privateKey); CipherInputStream cipherInputStream = new CipherInputStream( new ByteArrayInputStream(bytes), cipher); ByteArrayOutputStream output = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; while (true) { int n = cipherInputStream.read(buffer, 0, buffer.length); if (n <= 0) { break; } output.write(buffer, 0, n); } return output.toByteArray(); } catch (Exception e) { throw new CryptoFailedException("Could not decrypt bytes", e); } } private ResultSet getGenericPasswordForOptionsUsingConceal(String service) throws CryptoFailedException { if (!crypto.isAvailable()) { throw new CryptoFailedException("Crypto is missing"); } service = service == null ? DEFAULT_ALIAS : service; byte[] recuser = getBytesFromPrefs(service, LEGACY_DELIMITER + "u"); byte[] recpass = getBytesFromPrefs(service, LEGACY_DELIMITER + "p"); if (recuser == null || recpass == null) { return null; } Entity userentity = Entity.create(KEYCHAIN_DATA + ":" + service + "user"); Entity pwentity = Entity.create(KEYCHAIN_DATA + ":" + service + "pass"); try { byte[] decryptedUsername = crypto.decrypt(recuser, userentity); byte[] decryptedPassword = crypto.decrypt(recpass, pwentity); return new ResultSet(service, decryptedUsername, decryptedPassword); } catch (Exception e) { throw new CryptoFailedException("Decryption failed for service " + service, e); } } private byte[] getBytesFromPrefs(String service, String prefix) { String key = service + prefix; String value = prefs.getString(service + prefix, null); if (value != null) { return Base64.decode(value, Base64.DEFAULT); } return null; } @ReactMethod public void resetGenericPasswordForOptions(String service, Promise promise) { try { resetGenericPasswordForOptions(service); promise.resolve(true); } catch (KeyStoreException e) { Log.e(KEYCHAIN_MODULE, e.getMessage()); promise.reject(E_UNSUPPORTED_KEYSTORE, e); } catch (KeyStoreAccessException e) { Log.e(KEYCHAIN_MODULE, e.getMessage()); promise.reject(E_KEYSTORE_ACCESS_ERROR, e); } } private void resetGenericPasswordForOptions(String service) throws KeyStoreException, KeyStoreAccessException { service = service == null ? DEFAULT_ALIAS : service; KeyStore keyStore = getKeyStoreAndLoad(); if (keyStore.containsAlias(service)) { keyStore.deleteEntry(service); } SharedPreferences.Editor prefsEditor = prefs.edit(); if (prefs.contains(service + DELIMITER + "u")) { prefsEditor.remove(service + DELIMITER + "u"); prefsEditor.remove(service + DELIMITER + "p"); prefsEditor.apply(); } } private void resetGenericPasswordForOptionsLegacy(String service) throws KeyStoreException, KeyStoreAccessException { service = service == null ? DEFAULT_ALIAS : service; SharedPreferences.Editor prefsEditor = prefs.edit(); if (prefs.contains(service + LEGACY_DELIMITER + "u")) { prefsEditor.remove(service + LEGACY_DELIMITER + "u"); prefsEditor.remove(service + LEGACY_DELIMITER + "p"); prefsEditor.apply(); } } @ReactMethod public void setInternetCredentialsForServer(@NonNull String server, String username, String password, ReadableMap unusedOptions, Promise promise) { setGenericPasswordForOptions(server, username, password, promise); } @ReactMethod public void getInternetCredentialsForServer(@NonNull String server, ReadableMap unusedOptions, Promise promise) { getGenericPasswordForOptions(server, promise); } @ReactMethod public void resetInternetCredentialsForServer(@NonNull String server, ReadableMap unusedOptions, Promise promise) { resetGenericPasswordForOptions(server, promise); } private KeyStore getKeyStore() throws KeyStoreException { return KeyStore.getInstance(KEYSTORE_TYPE); } private KeyStore getKeyStoreAndLoad() throws KeyStoreException, KeyStoreAccessException { try { KeyStore keyStore = getKeyStore(); keyStore.load(null); return keyStore; } catch (NoSuchAlgorithmException | CertificateException | IOException e) { throw new KeyStoreAccessException("Could not access KeyStore", e); } } }
package com.messagebird.objects; import org.jetbrains.annotations.Nullable; import java.io.Serializable; import java.math.BigInteger; import java.util.Date; import java.util.List; import java.util.Map; public class MessageResponse implements MessageResponseBase, Serializable { private static final long serialVersionUID = 6363132950790389653L; private String id; private String href; private String direction; private MsgType type; private String originator; private String body; private String reference; private Integer validity; private Integer gateway; private Map<String, Object> typeDetails; private DataCodingType datacoding = DataCodingType.unicode; private MClassType mclass; private Date scheduledDatetime; private Date createdDatetime; private Recipients recipients; public MessageResponse() { } @Override public String toString() { return "MessageResponse{" + "id='" + id + '\'' + ", href='" + href + '\'' + ", direction='" + direction + '\'' + ", type=" + type + ", originator='" + originator + '\'' + ", body='" + body + '\'' + ", reference='" + reference + '\'' + ", validity=" + validity + ", gateway=" + gateway + ", typeDetails=" + typeDetails + ", datacoding=" + datacoding + ", mclass=" + mclass + ", scheduledDatetime=" + scheduledDatetime + ", createdDatetime=" + createdDatetime + ", recipients=" + recipients + '}'; } @Override public String getId() { return id; } @Override public String getHref() { return href; } /** * Tells you if the message is sent or received. * mt: mobile terminated (sent to mobile) * mo: mobile originated (received from mobile) * * @return String */ public String getDirection() { return direction; } /** * The type of message. Values can be: sms, binary, premium, or flash * * @return MsgType */ public MsgType getType() { return type; } /** * The sender of the message. This can be a telephone number (including country code) or an alphanumeric string. In case of an alphanumeric string, the maximum length is 11 characters. * * @return String */ public String getOriginator() { return originator; } @Override public String getBody() { return body; } @Override public String getReference() { return reference; } /** * Your reference for this message * * @param reference */ public void setReference(String reference) { this.reference = reference; } /** * The amount of seconds that the message is valid. If a message is not delivered within this time, the message will be discarded. * * @return Integer */ public Integer getValidity() { return validity; } /** * The SMS route that is used to send the message. * * @return Integer */ public Integer getGateway() { return gateway; } /** * The datacoding used, can be plain or unicode * * @return DataCodingType */ public DataCodingType getDatacoding() { return datacoding; } /** * Indicated the message type. 1 is a normal message, 0 is a flash message. * * @return MClassType */ public MClassType getMclass() { return mclass; } /** * The scheduled date and time of the message * * @return Date */ public Date getScheduledDatetime() { return scheduledDatetime; } /** * The date and time of the creation of the message * * @return Date */ public Date getCreatedDatetime() { return createdDatetime; } @Override public Recipients getRecipients() { return recipients; } /** * Return type details object * * @return Map<String , Object> */ public Map<String, Object> getTypeDetails() { return typeDetails; } /** * Recipient status */ static public class Recipients implements Serializable { private static final long serialVersionUID = 547164972757802213L; private Integer totalCount; private Integer totalSentCount; private Integer totalDeliveredCount; private Integer totalDeliveryFailedCount; private List<Items> items; public Recipients() { } @Override public String toString() { return "Recipients{" + "totalCount=" + totalCount + ", totalSentCount=" + totalSentCount + ", totalDeliveredCount=" + totalDeliveredCount + ", totalDeliveryFailedCount=" + totalDeliveryFailedCount + ", items=" + items + '}'; } public Integer getTotalCount() { return totalCount; } /** * The count of recipients that have the message pending (status sent, and buffered). * * @return Integer */ public Integer getTotalSentCount() { return totalSentCount; } /** * The count of recipients where the message is delivered (status delivered). * * @return Integer */ public Integer getTotalDeliveredCount() { return totalDeliveredCount; } /** * The count of recipients where the delivery has failed (status delivery_failed). * * @return Integer */ public Integer getTotalDeliveryFailedCount() { return totalDeliveryFailedCount; } /** * An array of recipient hashes * * @return List<Items> */ public List<Items> getItems() { return items; } } /** * Response recipient items */ static public class Items implements Serializable { private static final long serialVersionUID = -4104837036540050532L; private BigInteger recipient; private BigInteger originator; private String status; private Date statusDatetime; private String recipientCountry; private Integer recipientCountryPrefix; private String recipientOperator; private Integer messageLength; private String statusReason; @Nullable private Price price; private String mccmnc; private String mcc; private String mnc; private int messagePartCount; public Items() { } @Override public String toString() { return "Items{" + "recipient=" + recipient + ", originator=" + originator + ", status='" + status + '\'' + ", statusDatetime=" + statusDatetime + ", recipientCountry='" + recipientCountry + '\'' + ", recipientCountryPrefix=" + recipientCountryPrefix + ", recipientOperator='" + recipientOperator + '\'' + ", messageLength=" + messageLength + ", statusReason='" + statusReason + '\'' + ", price=" + price + ", mccmnc='" + mccmnc + '\'' + ", mcc='" + mcc + '\'' + ", mnc='" + mnc + '\'' + ", messagePartCount=" + messagePartCount + '}'; } /** * The msisdn of the recipient * * @return BigInteger */ public BigInteger getRecipient() { return recipient; } /** * The status of the message sent to the recipient. Possible values: scheduled, sent, buffered, delivered, and delivery_failed * * @return String */ public String getStatus() { return status; } /** * The datum time of the last status * * @return Date */ public Date getStatusDatetime() { return statusDatetime; } public Price getPrice() { return price; } public BigInteger getOriginator() { return originator; } public String getRecipientCountry() { return recipientCountry; } public Integer getRecipientCountryPrefix() { return recipientCountryPrefix; } public String getRecipientOperator() { return recipientOperator; } public Integer getMessageLength() { return messageLength; } public String getStatusReason() { return statusReason; } public String getMccmnc() { return mccmnc; } public String getMcc() { return mcc; } public String getMnc() { return mnc; } public int getMessagePartCount() { return messagePartCount; } } /** * Response price of items */ static public class Price implements Serializable { private static final long serialVersionUID = -4104837036540050532L; private float amount; private String currency; public Price() { } @Override public String toString() { return "Price{" + "amount=" + amount + ", currency=" + currency + "}"; } public float getAmount() { return amount; } public String getCurrency() { return currency; } } }
package rtdc.web.server.service; import org.hibernate.Session; import rtdc.core.model.Unit; import rtdc.core.model.User; import rtdc.web.server.config.PersistenceConfig; import rtdc.web.server.model.ServerUnit; import rtdc.web.server.model.ServerUser; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.*; import javax.ws.rs.core.Context; import java.util.List; import static rtdc.core.model.ApplicationPermission.ADMIN; import static rtdc.core.model.ApplicationPermission.USER; @Path("users") public class UserService { @GET @Produces("application/json") public List<User> getUser(@Context HttpServletRequest req){ AuthService.hasRole(req, ADMIN); Session session = PersistenceConfig.getSessionFactory().getCurrentSession(); session.beginTransaction(); List<User> units = (List<User>) session.createCriteria(ServerUser.class).list(); session.getTransaction().commit(); return units; } @POST @Produces("application/json") public boolean updateUser(@Context HttpServletRequest req, ServerUser unit){ AuthService.hasRole(req, ADMIN); Session session = PersistenceConfig.getSessionFactory().getCurrentSession(); session.beginTransaction(); session.saveOrUpdate(unit); session.getTransaction().commit(); return true; } @DELETE @Path("{id}") @Produces("application/json") public boolean deleteUnit(@Context HttpServletRequest req, @PathParam("id") String id){ AuthService.hasRole(req, ADMIN); Session session = PersistenceConfig.getSessionFactory().getCurrentSession(); session.beginTransaction(); ServerUser user = (ServerUser) session.load(ServerUser.class, id); session.delete(user); session.getTransaction().commit(); return true; } }
package org.noear.weed.mongo; import com.mongodb.client.model.IndexOptions; import org.noear.weed.DataItem; import java.util.*; import java.util.function.Consumer; import java.util.regex.Pattern; /** * @author noear 2021/2/5 created */ public class MgTableQuery { private String table; private Map<String, Object> whereMap; private Map<String, Object> orderMap; private Map<String, Object> dataItem; private int limit_size; private int limit_start; private MongoX mongoX; private void initWhereMap() { if (whereMap == null) { whereMap = new LinkedHashMap<>(); } } public MgTableQuery(MongoX mongoX) { this.mongoX = mongoX; } public MgTableQuery table(String table) { this.table = table; return this; } public MgTableQuery whereMap(Map<String, Object> map) { this.whereMap = map; return this; } //SQL where = public MgTableQuery whereTrue() { initWhereMap(); return this; } /** * <p><code> * db.table("user").whereScript("this.age > 20 && this.age <= 40") * </code></p> * SQL where script * */ public MgTableQuery whereScript(String code) { initWhereMap(); String fun = null; if (code.contains("return ")) { fun = "function (){" + code + "};"; } else { fun = "function (){return " + code + "};"; } whereMap.put("$where", fun); return this; } //SQL where = public MgTableQuery whereEq(String col, Object val) { initWhereMap(); whereMap.put(col, val); return this; } //SQL where != public MgTableQuery whereNeq(String col, Object val) { initWhereMap(); Map<String, Object> tmp = new LinkedHashMap<>(); tmp.put("$ne", val); whereMap.put(col, tmp); return this; } //SQL where < public MgTableQuery whereLt(String col, Object val) { initWhereMap(); Map<String, Object> tmp = new LinkedHashMap<>(); tmp.put("$lt", val); whereMap.put(col, tmp); return this; } //SQL where <= public MgTableQuery whereLte(String col, Object val) { initWhereMap(); Map<String, Object> tmp = new LinkedHashMap<>(); tmp.put("$lte", val); whereMap.put(col, tmp); return this; } //SQL where > public MgTableQuery whereGt(String col, Object val) { initWhereMap(); Map<String, Object> tmp = new LinkedHashMap<>(); tmp.put("$gt", val); whereMap.put(col, tmp); return this; } //SQL where >= public MgTableQuery whereGte(String col, Object val) { initWhereMap(); Map<String, Object> tmp = new LinkedHashMap<>(); tmp.put("$gte", val); whereMap.put(col, tmp); return this; } public MgTableQuery whereBtw(String col, Object start, Object end) { initWhereMap(); Map<String, Object> tmp = new LinkedHashMap<>(); tmp.put("$gte", start); tmp.put("$lte", end); whereMap.put(col, tmp); return this; } public MgTableQuery whereExists(String col, boolean exists) { initWhereMap(); Map<String, Object> tmp = new LinkedHashMap<>(); tmp.put("$exists", exists); whereMap.put(col, tmp); return this; } public MgTableQuery whereMod(String col, long base, long result) { initWhereMap(); Map<String, Object> tmp = new LinkedHashMap<>(); tmp.put("$mod", Arrays.asList(base, result)); whereMap.put(col, tmp); return this; } public MgTableQuery whereNmod(String col, long base, long result) { initWhereMap(); Map<String, Object> tmp = new LinkedHashMap<>(); tmp.put("$mod", Arrays.asList(base, result)); Map<String, Object> tmp2 = new LinkedHashMap<>(); tmp2.put("$not", tmp2); whereMap.put(col, tmp2); return this; } public MgTableQuery whereSize(String col, long size) { initWhereMap(); Map<String, Object> tmp = new LinkedHashMap<>(); tmp.put("$size", size); whereMap.put(col, tmp); return this; } public MgTableQuery whereAll(String col, Iterable<Object> ary) { initWhereMap(); Map<String, Object> tmp = new LinkedHashMap<>(); tmp.put("$all", ary); whereMap.put(col, tmp); return this; } public MgTableQuery whereIn(String col, Iterable<Object> ary) { initWhereMap(); Map<String, Object> tmp = new LinkedHashMap<>(); tmp.put("$in", ary); whereMap.put(col, tmp); return this; } public MgTableQuery whereNin(String col, Iterable<Object> ary) { initWhereMap(); Map<String, Object> tmp = new LinkedHashMap<>(); tmp.put("$nin", ary); whereMap.put(col, tmp); return this; } public MgTableQuery whereLk(String col, String regex) { initWhereMap(); Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE); whereMap.put(col, pattern); return this; } public MgTableQuery whereNlk(String col, String regex) { initWhereMap(); Pattern expr = Pattern.compile(regex, Pattern.CASE_INSENSITIVE); Map<String, Object> tmp = new LinkedHashMap<>(); tmp.put("$not", expr); whereMap.put(col, tmp); return this; } // for and //SQL and = public MgTableQuery andEq(String col, Object val) { initWhereMap(); whereMap.put(col, val); return this; } //SQL where != public MgTableQuery andNeq(String col, Object val) { initWhereMap(); Map<String, Object> tmp = new LinkedHashMap<>(); tmp.put("$ne", val); whereMap.put(col, tmp); return this; } //SQL where < public MgTableQuery andLt(String col, Object val) { initWhereMap(); Map<String, Object> tmp = new LinkedHashMap<>(); tmp.put("$lt", val); whereMap.put(col, tmp); return this; } //SQL where <= public MgTableQuery andLte(String col, Object val) { initWhereMap(); Map<String, Object> tmp = new LinkedHashMap<>(); tmp.put("$lte", val); whereMap.put(col, tmp); return this; } //SQL where > public MgTableQuery andGt(String col, Object val) { initWhereMap(); Map<String, Object> tmp = new LinkedHashMap<>(); tmp.put("$gt", val); whereMap.put(col, tmp); return this; } //SQL where >= public MgTableQuery andGte(String col, Object val) { initWhereMap(); Map<String, Object> tmp = new LinkedHashMap<>(); tmp.put("$gte", val); whereMap.put(col, tmp); return this; } public MgTableQuery andBtw(String col, Object start, Object end) { initWhereMap(); Map<String, Object> tmp = new LinkedHashMap<>(); tmp.put("$gte", start); tmp.put("$lte", end); whereMap.put(col, tmp); return this; } public MgTableQuery andExists(String col, boolean exists) { initWhereMap(); Map<String, Object> tmp = new LinkedHashMap<>(); tmp.put("$exists", exists); whereMap.put(col, tmp); return this; } public MgTableQuery andMod(String col, long base, long result) { initWhereMap(); Map<String, Object> tmp = new LinkedHashMap<>(); tmp.put("$mod", Arrays.asList(base, result)); whereMap.put(col, tmp); return this; } public MgTableQuery andNmod(String col, long base, long result) { initWhereMap(); Map<String, Object> tmp = new LinkedHashMap<>(); tmp.put("$mod", Arrays.asList(base, result)); Map<String, Object> tmp2 = new LinkedHashMap<>(); tmp2.put("$not", tmp2); whereMap.put(col, tmp2); return this; } public MgTableQuery andSize(String col, long size) { initWhereMap(); Map<String, Object> tmp = new LinkedHashMap<>(); tmp.put("$size", size); whereMap.put(col, tmp); return this; } public MgTableQuery andAll(String col, Iterable<Object> ary) { initWhereMap(); Map<String, Object> tmp = new LinkedHashMap<>(); tmp.put("$all", ary); whereMap.put(col, tmp); return this; } public MgTableQuery andIn(String col, Iterable<Object> ary) { initWhereMap(); Map<String, Object> tmp = new LinkedHashMap<>(); tmp.put("$in", ary); whereMap.put(col, tmp); return this; } public MgTableQuery andNin(String col, Iterable<Object> ary) { initWhereMap(); Map<String, Object> tmp = new LinkedHashMap<>(); tmp.put("$nin", ary); whereMap.put(col, tmp); return this; } public MgTableQuery andLk(String col, String regex) { initWhereMap(); Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE); whereMap.put(col, pattern); return this; } public MgTableQuery andNlk(String col, String regex) { initWhereMap(); Pattern expr = Pattern.compile(regex, Pattern.CASE_INSENSITIVE); Map<String, Object> tmp = new LinkedHashMap<>(); tmp.put("$not", expr); whereMap.put(col, tmp); return this; } private Map<String, Object> buildFilter(boolean forced) { if (whereMap == null) { throw new IllegalArgumentException("No where condition..."); } if (forced) { if (whereMap.size() == 0) { throw new IllegalArgumentException("No where condition..."); } } return whereMap; } // set public MgTableQuery set(String col, Object val) { if (dataItem == null) { dataItem = new LinkedHashMap<>(); } dataItem.put(col, val); return this; } public MgTableQuery setMap(Map<String, Object> map) { dataItem = map; return this; } public MgTableQuery setEntity(Object bean) { dataItem = new DataItem().setEntity(bean).getMap(); return this; } public void insert() { insert(dataItem); } public void insert(Map<String, Object> data) { if (data == null || data.size() == 0) { throw new IllegalArgumentException("No insert data..."); } mongoX.insertOne(table, data); } public void insertList(List<Map<String, Object>> dataList) { mongoX.insertMany(table, dataList); } public long update() { if (dataItem == null || dataItem.size() == 0) { throw new IllegalArgumentException("No update data..."); } Map<String, Object> filter = buildFilter(true); return mongoX.updateMany(table, filter, dataItem); } public long replace() { Map<String, Object> filter = buildFilter(true); return mongoX.replaceOne(table, filter, dataItem); } public long delete() { Map<String, Object> filter = buildFilter(true); return mongoX.deleteMany(table, filter); } public MgTableQuery limit(int size) { limit_size = size; return this; } public MgTableQuery limit(int start, int size) { limit_size = size; limit_start = start; return this; } public MgTableQuery orderByAsc(String col) { if (orderMap == null) { orderMap = new LinkedHashMap<>(); } orderMap.put(col, 1); return this; } public MgTableQuery orderByDesc(String col) { if (orderMap == null) { orderMap = new LinkedHashMap<>(); } orderMap.put(col, -1); return this; } public MgTableQuery andByAsc(String col) { return orderByAsc(col); } public MgTableQuery andByDesc(String col) { return orderByDesc(col); } public <T> List<T> selectList(Class<T> clz) { List<T> list = new ArrayList<>(); List<Map<String, Object>> listTmp = selectMapList(); for (Map<String, Object> itemTmp : listTmp) { list.add(new DataItem().setMap(itemTmp).toEntity(clz)); } return list; } public <T> T selectItem(Class<T> clz) { Map<String, Object> itemTmp = selectMap(); return new DataItem().setMap(itemTmp).toEntity(clz); } public List<Map<String, Object>> selectMapList() { Map<String, Object> filter = buildFilter(true); if (limit_size > 0) { return mongoX.findPage(table, filter, orderMap, limit_start, limit_size); } else { return mongoX.findMany(table, filter, orderMap); } } public <T> List<T> selectArray(String col) { List<T> list = new ArrayList<>(); List<Map<String, Object>> listTmp = selectMapList(); for (Map<String, Object> map : listTmp) { Object v1 = map.get(col); if (v1 != null) { list.add((T) v1); } } return list; } public Map<String, Object> selectMap() { Map<String, Object> filter = buildFilter(true); return mongoX.findOne(table, filter); } public long selectCount() { Map<String, Object> filter = buildFilter(false); if (filter.size() > 0) { return mongoX.countDocuments(table, filter); } else { return mongoX.count(table); } } public boolean selectExists() { Map map = selectMap(); return (map != null && map.size() > 0); } public String createIndex(boolean background) { return createIndex(new IndexOptions().background(background)); } public String createIndex(IndexOptions options) { if (orderMap == null || orderMap.size() == 0) { throw new IllegalArgumentException("No index keys..."); } if (options == null) { return mongoX.createIndex(table, orderMap); } else { return mongoX.createIndex(table, orderMap, options); } } public MgTableQuery build(Consumer<MgTableQuery> builder){ builder.accept(this); return this; } }
package com.intellij.lexer; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.fileTypes.SyntaxHighlighter; import com.intellij.psi.jsp.el.ELTokenType; import com.intellij.psi.jsp.JspSpiUtil; import com.intellij.psi.tree.IElementType; import com.intellij.psi.xml.XmlTokenType; import com.intellij.util.text.CharArrayCharSequence; public class HtmlHighlightingLexer extends BaseHtmlLexer { private static final Logger LOG = Logger.getInstance("#com.intellij.lexer.HtmlHighlightingLexer"); private static final int EMBEDDED_LEXER_ON = 0x1 << BASE_STATE_SHIFT; private static final int EMBEDDED_LEXER_STATE_SHIFT = BASE_STATE_SHIFT + 1; private Lexer embeddedLexer; private Lexer styleLexer; private Lexer scriptLexer; private Lexer elLexer; private boolean hasNoEmbeddments; private static FileType ourStyleFileType; private static FileType ourScriptFileType; public class XmlEmbeddmentHandler implements TokenHandler { public void handleElement(Lexer lexer) { if (!hasSeenStyle() && !hasSeenScript() || hasNoEmbeddments) return; final IElementType tokenType = lexer.getTokenType(); if ((tokenType==XmlTokenType.XML_ATTRIBUTE_VALUE_TOKEN && hasSeenAttribute()) || (tokenType==XmlTokenType.XML_DATA_CHARACTERS && hasSeenTag()) || tokenType==XmlTokenType.XML_COMMENT_CHARACTERS && hasSeenTag() ) { setEmbeddedLexer(); if (embeddedLexer!=null) { embeddedLexer.start( getBufferSequence(), HtmlHighlightingLexer.super.getTokenStart(), skipToTheEndOfTheEmbeddment(), embeddedLexer instanceof EmbedmentLexer ? ((EmbedmentLexer)embeddedLexer).getEmbeddedInitialState(tokenType) : 0 ); if (embeddedLexer.getTokenType() == null) { // no content for embeddment embeddedLexer = null; } } } } } public class ElEmbeddmentHandler implements TokenHandler { public void handleElement(Lexer lexer) { setEmbeddedLexer(); if (embeddedLexer != null) { embeddedLexer.start(getBufferSequence(),HtmlHighlightingLexer.super.getTokenStart(),HtmlHighlightingLexer.super.getTokenEnd(), 0); } } } public HtmlHighlightingLexer() { this(new MergingLexerAdapter(new FlexAdapter(new _HtmlLexer()),TOKENS_TO_MERGE),true); } protected HtmlHighlightingLexer(Lexer lexer, boolean caseInsensitive) { super(lexer,caseInsensitive); XmlEmbeddmentHandler value = new XmlEmbeddmentHandler(); registerHandler(XmlTokenType.XML_ATTRIBUTE_VALUE_TOKEN,value); registerHandler(XmlTokenType.XML_DATA_CHARACTERS,value); registerHandler(XmlTokenType.XML_COMMENT_CHARACTERS,value); } public void start(char[] buffer, int startOffset, int endOffset, int initialState) { start(new CharArrayCharSequence(buffer),startOffset, endOffset, initialState); } public void start(CharSequence buffer, int startOffset, int endOffset, int initialState) { super.start(buffer, startOffset, endOffset, initialState); if ((initialState & EMBEDDED_LEXER_ON)!=0) { int state = initialState >> EMBEDDED_LEXER_STATE_SHIFT; setEmbeddedLexer(); LOG.assertTrue(embeddedLexer!=null); embeddedLexer.start(buffer,startOffset,skipToTheEndOfTheEmbeddment(),state); } else { embeddedLexer = null; } } private void setEmbeddedLexer() { Lexer newLexer = null; if (hasSeenStyle()) { if (styleLexer==null) { styleLexer = (ourStyleFileType!=null)? SyntaxHighlighter.PROVIDER.create(ourStyleFileType, null, null).getHighlightingLexer():null; } newLexer = styleLexer; } else if (hasSeenScript()) { if (scriptLexer==null) { scriptLexer = (ourScriptFileType!=null)? SyntaxHighlighter.PROVIDER.create(ourScriptFileType, null, null).getHighlightingLexer():null; } newLexer = scriptLexer; } else if (super.getTokenType() == ELTokenType.JSP_EL_CONTENT) { if (elLexer==null) elLexer = JspSpiUtil.createElLexer(); newLexer = elLexer; } if (newLexer!=null) { embeddedLexer = newLexer; } } public void advance() { if (embeddedLexer!=null) { embeddedLexer.advance(); if (embeddedLexer.getTokenType()==null) { embeddedLexer=null; } } if (embeddedLexer==null) { super.advance(); } } protected boolean isValidAttributeValueTokenType(final IElementType tokenType) { return super.isValidAttributeValueTokenType(tokenType) || tokenType == ELTokenType.JSP_EL_CONTENT; } public IElementType getTokenType() { if (embeddedLexer!=null) { return embeddedLexer.getTokenType(); } else { IElementType tokenType = super.getTokenType(); // TODO: fix no DOCTYPE highlighting if (tokenType == null) return tokenType; if (tokenType==XmlTokenType.XML_NAME) { // we need to convert single xml_name for tag name and attribute name into to separate // lex types for the highlighting! final int state = getState() & BASE_STATE_MASK; if (isHtmlTagState(state)) { tokenType = XmlTokenType.XML_TAG_NAME; } } else if (tokenType == XmlTokenType.XML_WHITE_SPACE || tokenType == XmlTokenType.XML_REAL_WHITE_SPACE) { if (hasSeenTag() && (hasSeenStyle() || hasSeenScript())) { tokenType = XmlTokenType.XML_WHITE_SPACE; } else { tokenType = (getState()!=0)?XmlTokenType.TAG_WHITE_SPACE:XmlTokenType.XML_REAL_WHITE_SPACE; } } else if (tokenType == XmlTokenType.XML_CHAR_ENTITY_REF || tokenType == XmlTokenType.XML_ENTITY_REF_TOKEN ) { // we need to convert char entity ref & entity ref in comments as comment chars final int state = getState() & BASE_STATE_MASK; if (state == _HtmlLexer.COMMENT) return XmlTokenType.XML_COMMENT_CHARACTERS; } return tokenType; } } public int getTokenStart() { if (embeddedLexer!=null) { return embeddedLexer.getTokenStart(); } else { return super.getTokenStart(); } } public int getTokenEnd() { if (embeddedLexer!=null) { return embeddedLexer.getTokenEnd(); } else { return super.getTokenEnd(); } } public static final void registerStyleFileType(FileType fileType) { ourStyleFileType = fileType; } public static void registerScriptFileType(FileType _scriptFileType) { ourScriptFileType = _scriptFileType; } public int getState() { int state = super.getState(); state |= ((embeddedLexer!=null)?EMBEDDED_LEXER_ON:0); if (embeddedLexer!=null) state |= (embeddedLexer.getState() << EMBEDDED_LEXER_STATE_SHIFT); return state; } protected boolean isHtmlTagState(int state) { return state == _HtmlLexer.START_TAG_NAME || state == _HtmlLexer.END_TAG_NAME || state == _HtmlLexer.START_TAG_NAME2 || state == _HtmlLexer.END_TAG_NAME2; } public void setHasNoEmbeddments(boolean hasNoEmbeddments) { this.hasNoEmbeddments = hasNoEmbeddments; } }
package io.spine.query; import com.google.common.collect.ImmutableList; import com.google.errorprone.annotations.CanIgnoreReturnValue; import com.google.protobuf.FieldMask; import com.google.protobuf.Message; import io.spine.annotation.Internal; import io.spine.base.Field; import org.checkerframework.checker.nullness.qual.Nullable; import java.util.Optional; /** * A builder for instance of {@link Query}. * * @param <I> * the type of identifiers of the records which are queried * @param <R> * the type of queried records * @param <P> * the type of subject parameters to use when composing the query * @param <B> * the type of the {@code QueryBuilder} implementation * @param <Q> * the type of {@code Query} implementation */ public interface QueryBuilder<I, R extends Message, P extends SubjectParameter<R, ?, ?>, B extends QueryBuilder<I, R, P, B, Q>, Q extends Query<I, R>> { /** * Creates a new instance of the query on top of this builder. */ Q build(); /** * Returns the type of the queried records. */ Class<R> whichRecordType(); /** * Returns the type of the identifiers for the queried records. */ Class<I> whichIdType(); /** * Returns the criterion for the record identifiers. */ IdParameter<I> whichIds(); /** * Returns the predicates for the record fields. */ ImmutableList<QueryPredicate<R>> predicates(); /** * Returns the ordering directives to be applied to the resulting dataset. */ ImmutableList<OrderBy<?, R>> ordering(); /** * Returns the maximum number of records in the resulting dataset. * * <p>Returns {@code null} if the limit is not set. */ @Nullable Integer whichLimit(); /** * Returns the field mask to be applied to each of the resulting records. * * <p>If the mask is not set, returns {@code Optional.empty()}. */ Optional<FieldMask> whichMask(); /** * Adds a predicate to be treated in disjunction with the existing predicates. * * <p>All expressions passed with every {@code Either} parameter are treated with {@code OR} * behavior. * * <p>Example. * * <pre> * ProjectView.newQuery() * .either(builder -> builder.daysSinceStarted() * .isGreaterThan(30), * builder -> builder.status() * .is(DONE)) * .build(); * </pre> * * <p>The {@code ProjectView} query above targets the instances which are either started * more than thirty days ago, or those which are in {@code DONE} status. * * <p>Each {@code Either} is a lambda serving to preserve the current {@code QueryBuilder} with * its API and syntax sugar for creating the new predicates, but in a disjunction context. * * <p>Another example. * * <pre> * {@literal ImmutableList<Project.Status>} statuses = //... * ProjectView.newQuery() * .either((builder) -> { * for (Project.Status status : statuses) { * builder.status().is(status); * } * return builder; * }).build(); * </pre> * * <p>This example creates a query for the {@code ProjectView} instances which have one * of the expected {@code statuses}. Note that {@code either(..)} is passed with a single * argument lambda. Each predicate appended to the builder inside of the passed lambda * is treated as a disjunction predicate. Basically, that is just a short form of * the expression as follows: * * <pre> * {@literal ImmutableList<Project.Status>} statuses = //... * ProjectView.newQuery() * // Performs the same as in the previous example. Much less elegant though. * .either(builder -> builder.status().is(statuses.get(0)), * builder -> builder.status().is(statuses.get(1)), * builder -> builder.status().is(statuses.get(2)), * //... * builder -> builder.status().is(statuses.get(lastOne))) * .build(); * </pre> * * <p>If several {@code Either} lambdas are passed to the {@code either(..)}, all * predicates appended to the builder in them are treated together in an {@code OR} fashion. * * <p>You may extract lambdas into variables to simplify the code even further: * * <pre> * {@literal Either<ProjectView.QueryBuilder>} startedMoreThanMonthAgo = * project -> project.daysSinceStarted() * .isGreaterThan(daysSinceStarted); * {@literal Either<ProjectView.QueryBuilder>} isDone = * project -> project.status() * .is(statusValue); * ProjectView.Query query = * ProjectView.newQuery() * .either(startedMoreThanMonthAgo, isDone) * .build(); * </pre> * * @return this instance of query builder, for chaining */ @SuppressWarnings("unchecked") // See the implementations on the varargs issue. B either(Either<B>... parameters); /** * Sets the maximum number of records in the resulting dataset. * * <p>The expected value must be positive. * * <p>If this method is not called, the limit value remains unset. * * @return this instance of query builder, for chaining */ @CanIgnoreReturnValue B limit(int numberOfRecords); /** * Sets the field mask to be applied to each of the resulting records. * * <p>If the mask is not set, the query results contain the records as-is. * * <p>Any previously set mask values are overridden by this method call. * * @return this instance of query builder, for chaining */ @CanIgnoreReturnValue B withMask(FieldMask mask); /** * Sets the paths for the field mask to apply to each of the resulting records. * * <p>If the mask is not set, the query results contain the records as-is. * * <p>Any previously set mask values are overridden by this method call. * * @return this instance of query builder, for chaining */ @SuppressWarnings("OverloadedVarargsMethod") // Each overload has a different parameter type. B withMask(String ...maskPaths); /** * Sets the fields to apply as a field mask to each of the resulting records. * * <p>If the mask is not set, the query results contain the records as-is. * * <p>Any previously set mask values are overridden by this method call. * * @return this instance of query builder, for chaining */ @SuppressWarnings("OverloadedVarargsMethod") // Each overload has a different parameter type. B withMask(Field...fields); /** * Adds an ordering directive. * * <p>Each call to this method adds another ordering directive. Directives are applied one * after another, each following determining the order of records remained "equal" after * the previous ordering. * * @param column * the field of the message by which the resulting set should be ordered * @param direction * the direction of ordering * @return this instance of query builder, for chaining */ @CanIgnoreReturnValue B orderBy(RecordColumn<R, ?> column, Direction direction); /** * Adds a parameter by which the records are to be queried. * * @return this instance of query builder, for chaining */ @CanIgnoreReturnValue @Internal B addParameter(P parameter); /** * Adds a parameter for the {@link CustomColumn}. * * @return this instance of query builder, for chaining */ @CanIgnoreReturnValue @Internal B addCustomParameter(CustomSubjectParameter<?, ?> parameter); }
package org.yamcs.tctm; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.SocketException; import java.nio.ByteBuffer; import org.yamcs.ConfigurationException; import org.yamcs.TmPacket; import org.yamcs.YConfiguration; /** * Receives telemetry packets via UDP. One UDP datagram = one TM packet. * * Keeps simple statistics about the number of datagram received and the number of too short datagrams * * @author nm * */ public class UdpTmDataLink extends AbstractTmDataLink implements Runnable { private volatile int invalidDatagramCount = 0; private DatagramSocket tmSocket; private int port; final static int MAX_LENGTH = 1500; DatagramPacket datagram; int maxLength; /** * Creates a new UDP TM Data Link * * @throws ConfigurationException * if port is not defined in the configuration */ public void init(String instance, String name, YConfiguration config) throws ConfigurationException { super.init(instance, name, config); port = config.getInt("port"); maxLength = config.getInt("maxLength", MAX_LENGTH); datagram = new DatagramPacket(new byte[maxLength], maxLength); } @Override public void doStart() { if (!isDisabled()) { try { tmSocket = new DatagramSocket(port); new Thread(this).start(); } catch (SocketException e) { notifyFailed(e); } } notifyStarted(); } @Override public void doStop() { if (tmSocket != null) { tmSocket.close(); } notifyStopped(); } @Override public void run() { while (isRunningAndEnabled()) { TmPacket tmpkt = getNextPacket(); if (tmpkt != null) { processPacket(tmpkt); } } } /** * * Called to retrieve the next packet. It blocks in readining on the multicast socket * * @return anything that looks as a valid packet, just the size is taken into account to decide if it's valid or not */ public TmPacket getNextPacket() { ByteBuffer packet = null; while (isRunning()) { try { tmSocket.receive(datagram); updateStats(datagram.getLength()); packet = ByteBuffer.allocate(datagram.getLength()); packet.put(datagram.getData(), datagram.getOffset(), datagram.getLength()); break; } catch (IOException e) { if (!isRunning() || isDisabled()) {// the shutdown or disable will close the socket and that will // generate an exception // which we ignore here return null; } log.warn("exception thrown when reading from the UDP socket at port {}", port, e); } } if (packet != null) { TmPacket tmPacket = new TmPacket(timeService.getMissionTime(), packet.array()); tmPacket.setEarthRceptionTime(timeService.getHresMissionTime()); return packetPreprocessor.process(tmPacket); } else { return null; } } /** * returns statistics with the number of datagram received and the number of invalid datagrams */ @Override public String getDetailedStatus() { if (isDisabled()) { return "DISABLED"; } else { return String.format("OK (%s) %nValid datagrams received: %d%nInvalid datagrams received: %d", port, packetCount.get(), invalidDatagramCount); } } /** * Sets the disabled to true such that getNextPacket ignores the received datagrams */ @Override public void doDisable() { if (tmSocket != null) { tmSocket.close(); tmSocket = null; } } /** * Sets the disabled to false such that getNextPacket does not ignore the received datagrams * * @throws SocketException */ @Override public void doEnable() throws SocketException { tmSocket = new DatagramSocket(port); new Thread(this).start(); } @Override protected Status connectionStatus() { return Status.OK; } }
package org.yamcs.tctm; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.nio.ByteBuffer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.yamcs.ConfigurationException; import org.yamcs.YConfiguration; import org.yamcs.archive.PacketWithTime; /** * Receives telemetry packets via UDP. One UDP datagram = one TM packet. * * Keeps simple statistics about the number of datagram received and the number of too short datagrams * * @author nm * */ public class UdpTmDataLink extends AbstractTmDataLink { private volatile int validDatagramCount = 0; private volatile int invalidDatagramCount = 0; private volatile boolean disabled = false; private DatagramSocket tmSocket; private int port; private TmSink tmSink; private Logger log = LoggerFactory.getLogger(this.getClass().getName()); final static int MAX_LENGTH = 1500; final DatagramPacket datagram; final int maxLength; String packetPreprocessorClassName; Object packetPreprocessorArgs; /** * Creates a new UDP TM Data Link * * @throws ConfigurationException * if port is not defined in the configuration */ public UdpTmDataLink(String instance, String name, YConfiguration config) throws ConfigurationException { super(instance, name, config); port = config.getInt("port"); maxLength = config.getInt("maxLength", MAX_LENGTH); datagram = new DatagramPacket(new byte[maxLength], maxLength); initPreprocessor(instance, config); } @Override public void startUp() throws IOException { tmSocket = new DatagramSocket(port); } @Override public void setTmSink(TmSink tmSink) { this.tmSink = tmSink; } @Override public void run() { while (isRunning()) { PacketWithTime pwrt = getNextPacket(); if(pwrt!=null) { tmSink.processPacket(pwrt); } while (isRunning() && disabled) { try { Thread.sleep(1000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return; } } } } @Override public void triggerShutdown() { tmSocket.close(); } /** * * Called to retrieve the next packet. It blocks in readining on the multicast socket * * @return anything that looks as a valid packet, just the size is taken into account to decide if it's valid or not */ public PacketWithTime getNextPacket() { ByteBuffer packet = null; while (isRunning()) { try { tmSocket.receive(datagram); validDatagramCount++; packet = ByteBuffer.allocate(datagram.getLength()); packet.put(datagram.getData(), datagram.getOffset(), datagram.getLength()); break; } catch (IOException e) { if (!isRunning()) {// the triggerShutdown will close the socket and that will generate an exception // which we ignore here return null; } log.warn("exception thrown when reading from the UDP socket at port {}", port, e); } } if (packet != null) { return packetPreprocessor.process(packet.array()); } else { return null; } } @Override public Status getLinkStatus() { return disabled ? Status.DISABLED : Status.OK; } /** * returns statistics with the number of datagram received and the number of invalid datagrams */ @Override public String getDetailedStatus() { if (disabled) { return "DISABLED"; } else { return String.format("OK (%s) %nValid datagrams received: %d%nInvalid datagrams received: %d", port, validDatagramCount, invalidDatagramCount); } } /** * Sets the disabled to true such that getNextPacket ignores the received datagrams */ @Override public void disable() { disabled = true; } /** * Sets the disabled to false such that getNextPacket does not ignore the received datagrams */ @Override public void enable() { disabled = false; } @Override public boolean isDisabled() { return disabled; } @Override public long getDataInCount() { return validDatagramCount; } @Override public long getDataOutCount() { return 0; } @Override public void resetCounters() { validDatagramCount = 0; } }
package aQute.bnd.differ; import static aQute.bnd.service.diff.Delta.ADDED; import static aQute.bnd.service.diff.Delta.CHANGED; import static aQute.bnd.service.diff.Delta.IGNORED; import static aQute.bnd.service.diff.Delta.MAJOR; import static aQute.bnd.service.diff.Delta.MICRO; import static aQute.bnd.service.diff.Delta.MINOR; import static aQute.bnd.service.diff.Delta.REMOVED; import static aQute.bnd.service.diff.Delta.UNCHANGED; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.EnumSet; import java.util.Formattable; import java.util.FormattableFlags; import java.util.Formatter; import java.util.List; import java.util.Set; import aQute.bnd.service.diff.Delta; import aQute.bnd.service.diff.Diff; import aQute.bnd.service.diff.Tree; import aQute.bnd.service.diff.Type; import aQute.libg.generics.Create; /** * A DiffImpl class compares a newer Element to an older Element. The Element * classes hide all the low level details. A Element class is either either * Structured (has children) or it is a Leaf, it only has a value. The * constructor will first build its children (if any) and then calculate the * delta. Each comparable element is translated to an Element. If necessary the * Element can be sub classed to provide special behavior. */ public class DiffImpl implements Diff, Comparable<DiffImpl>, Formattable { final Tree older; final Tree newer; final Collection<DiffImpl> children; final Delta delta; /** * The transitions table defines how the state is escalated depending on the * children. horizontally is the current delta and this is indexed with the * child delta for each child. This escalates deltas from below up. */ final static Delta[][] TRANSITIONS = { { IGNORED, UNCHANGED, CHANGED, MICRO, MINOR, MAJOR }, // IGNORED { IGNORED, UNCHANGED, CHANGED, MICRO, MINOR, MAJOR }, // UNCHANGED { IGNORED, CHANGED, CHANGED, MICRO, MINOR, MAJOR }, // CHANGED { IGNORED, MICRO, MICRO, MICRO, MINOR, MAJOR }, // MICRO { IGNORED, MINOR, MINOR, MINOR, MINOR, MAJOR }, // MINOR { IGNORED, MAJOR, MAJOR, MAJOR, MAJOR, MAJOR }, // MAJOR { IGNORED, MAJOR, MAJOR, MAJOR, MAJOR, MAJOR }, // REMOVED { IGNORED, MINOR, MINOR, MINOR, MINOR, MAJOR }, // ADDED }; /** * Compares the newer against the older, traversing the children if * necessary. * * @param newer The newer Element * @param older The older Element */ public DiffImpl(Tree newer, Tree older) { assert newer != null || older != null; this.older = older; this.newer = newer; // Either newer or older can be null, indicating remove or add // so we have to be very careful. Tree[] newerChildren = newer == null ? Element.EMPTY : newer.getChildren(); Tree[] olderChildren = older == null ? Element.EMPTY : older.getChildren(); int o = 0; int n = 0; List<DiffImpl> children = new ArrayList<DiffImpl>(); while (true) { Tree nw = n < newerChildren.length ? newerChildren[n] : null; Tree ol = o < olderChildren.length ? olderChildren[o] : null; DiffImpl diff; if (nw == null && ol == null) break; if (nw != null && ol != null) { // we have both sides int result = nw.compareTo(ol); if (result == 0) { // we have two equal named elements // use normal diff diff = new DiffImpl(nw, ol); n++; o++; } else if (result > 0) { // we newer > older, so there is no newer == removed diff = new DiffImpl(null, ol); o++; } else { // we newer < older, so there is no older == added diff = new DiffImpl(nw, null); n++; } } else { // we reached the end of one of the list diff = new DiffImpl(nw, ol); n++; o++; } children.add(diff); } // make sure they're read only this.children = Collections.unmodifiableCollection(children); delta = getDelta(null); } /** * Return the absolute delta. Also see * {@link #getDelta(aQute.bnd.service.diff.Diff.Ignore)} that allows you to * ignore Diff objects on the fly (and calculate their parents accordingly). */ public Delta getDelta() { return delta; } /** * This getDelta calculates the delta but allows the caller to ignore * certain Diff objects by calling back the ignore call back parameter. This * can be useful to ignore warnings/errors. */ public Delta getDelta(Ignore ignore) { // If ignored, we just return ignore. if (ignore != null && ignore.contains(this)) return IGNORED; if (newer == null) { return REMOVED; } else if (older == null) { return ADDED; } else { // now we're sure newer and older are both not null assert newer != null && older != null; assert newer.getClass() == older.getClass(); Delta local = Delta.UNCHANGED; for (DiffImpl child : children) { Delta sub = child.getDelta(ignore); if (sub == REMOVED) sub = child.older.ifRemoved(); else if (sub == ADDED) sub = child.newer.ifAdded(); // The escalate method is used to calculate the default // transition in the // delta based on the children. In general the delta can // only escalate, i.e. // move up in the chain. local = TRANSITIONS[sub.ordinal()][local.ordinal()]; } return local; } } public Type getType() { return (newer == null ? older : newer).getType(); } public String getName() { return (newer == null ? older : newer).getName(); } public Collection< ? extends Diff> getChildren() { return children; } @Override public String toString() { return String.format("%-10s %-10s %s", getDelta(), getType(), getName()); } @Override public boolean equals(Object other) { if (other instanceof DiffImpl) { DiffImpl o = (DiffImpl) other; return getDelta() == o.getDelta() && getType() == o.getType() && getName().equals(o.getName()); } return false; } @Override public int hashCode() { return getDelta().hashCode() ^ getType().hashCode() ^ getName().hashCode(); } public int compareTo(DiffImpl other) { if (getDelta() == other.getDelta()) { if (getType() == other.getType()) { return getName().compareTo(other.getName()); } return getType().compareTo(other.getType()); } return getDelta().compareTo(other.getDelta()); } public Diff get(String name) { for (DiffImpl child : children) { if (child.getName().equals(name)) return child; } return null; } public Tree getOlder() { return older; } public Tree getNewer() { return newer; } public Data serialize() { Data data = new Data(); data.type = getType(); data.delta = delta; data.name = getName(); data.children = new Data[children.size()]; int i = 0; for (Diff d : children) data.children[i++] = d.serialize(); return data; } @Override public void formatTo(Formatter formatter, int flags, int width, int precision) { boolean alternate = (flags & FormattableFlags.ALTERNATE) != 0; if (alternate) { Set<Delta> deltas = EnumSet.allOf(Delta.class); if ((flags & FormattableFlags.UPPERCASE) != 0) { deltas.remove(Delta.UNCHANGED); } int indent = Math.max(width, 0); format(formatter, this, Create.<String> list(), deltas, indent, 0); } else { StringBuilder sb = new StringBuilder(); sb.append('%'); if ((flags & FormattableFlags.LEFT_JUSTIFY) != 0) { sb.append('-'); } if (width != -1) { sb.append(width); } if (precision != -1) { sb.append('.'); sb.append(precision); } if ((flags & FormattableFlags.UPPERCASE) != 0) { sb.append('S'); } else { sb.append('s'); } formatter.format(sb.toString(), toString()); } } private static void format(final Formatter formatter, final Diff diff, final List<String> formats, final Set<Delta> deltas, final int indent, final int depth) { if (depth == formats.size()) { StringBuilder sb = new StringBuilder(); if (depth > 0) { sb.append("%n"); } int width = depth * 2; for (int leading = width + indent; leading > 0; leading sb.append(' '); } sb.append("%-"); sb.append(Math.max(20 - width, 1)); sb.append("s %-10s %s"); formats.add(sb.toString()); } String format = formats.get(depth); formatter.format(format, diff.getDelta(), diff.getType(), diff.getName()); for (Diff childDiff : diff.getChildren()) { if (deltas.contains(childDiff.getDelta())) { format(formatter, childDiff, formats, deltas, indent, depth + 1); } } } }
package edu.umd.cs.findbugs.bluej; import org.apache.bcel.classfile.JavaClass; import edu.umd.cs.findbugs.BugCollection; import edu.umd.cs.findbugs.BugInstance; import edu.umd.cs.findbugs.BugPattern; import edu.umd.cs.findbugs.TextUIBugReporter; public class MyReporter extends TextUIBugReporter { BugCollection bugs; MyReporter(BugCollection bugs) { this.bugs = bugs; } @Override protected void doReportBug(BugInstance bugInstance) { BugPattern bugPattern = bugInstance.getBugPattern(); if (bugPattern.getCategory().equals("CORRECTNESS") && ! bugPattern.getType().startsWith("DE_") && ! bugPattern.getType().startsWith("HE_") && ! bugPattern.getType().startsWith("SE_") ) bugs.add(bugInstance); } public void finish() { // TODO Auto-generated method stub } public void observeClass(JavaClass javaClass) { // TODO Auto-generated method stub } }
package c5db; import com.google.common.collect.Lists; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.NoSuchFileException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; public class NioFileConfigDirectory implements ConfigDirectory { private static final Logger LOG = LoggerFactory.getLogger(NioFileConfigDirectory.class); private static final Charset UTF_8 = Charset.forName("UTF-8"); private final Path baseConfigPath; private final Path nodeIdPath; private final Path clusterNamePath; public NioFileConfigDirectory(Path baseConfigPath) throws IOException { this.baseConfigPath = baseConfigPath; this.nodeIdPath = baseConfigPath.resolve(nodeIdFile); this.clusterNamePath = baseConfigPath.resolve(clusterNameFile); init(); } /** * Verifies that the 'config directory' is actually usable. If it doesn't exist, create it. If it exists, * ensure that it's writable. Ensure that primary configuration files aren't directories. * * @throws IOException */ private void init() throws IOException { if (Files.exists(getBaseConfigPath()) && !Files.isDirectory(getBaseConfigPath())) { throw new IOException("Base config path exists and is not a directory " + getBaseConfigPath()); } if (!Files.exists(getBaseConfigPath())) { Files.createDirectories(getBaseConfigPath()); } if (Files.exists(nodeIdPath) && !Files.isRegularFile(nodeIdPath)) { throw new IOException("NodeId file is not a regular directory!"); } if (Files.exists(clusterNamePath) && !Files.isRegularFile(clusterNamePath)) { throw new IOException("Cluster name is not a regular directory!"); } if (!Files.isWritable(getBaseConfigPath())) { throw new IOException("Can't write to the base configuration path!"); } } /** * Get the contents of the node id config file */ @Override public String getNodeId() throws IOException { return getFirstLineOfFile(nodeIdPath); } @Override public String getClusterName() throws IOException { return getFirstLineOfFile(clusterNamePath); } @Override public void createSubDir(Path dirRelPath) throws IOException { if (dirRelPath.isAbsolute()) { throw new IllegalArgumentException("dirRelPath should a relative path with respect to the base config directory"); } Path dirPath = this.getBaseConfigPath().resolve(dirRelPath); if (Files.isRegularFile(dirPath)) { throw new IOException("dirPath is a regular file! It needs to be a directory: " + dirPath); } // not a regular file. if (Files.isDirectory(dirPath) && !Files.isWritable(dirPath)) { throw new IOException("dirPath is a directory but not writable by me: " + dirPath); } if (Files.isDirectory(dirPath)) { return; } Files.createDirectories(dirPath); } @Override public void writeFile(Path dirRelPath, String fileName, List<String> data) throws IOException { createSubDir(dirRelPath); Path filePath = getBaseConfigPath().resolve(dirRelPath).resolve(fileName); Files.write(filePath, data, UTF_8); } @Override public List<String> readFile(Path dirRelPath, String fileName) throws IOException { Path filePath = getBaseConfigPath().resolve(dirRelPath).resolve(fileName); try { return Files.readAllLines(filePath, UTF_8); } catch (NoSuchFileException ex) { // file doesn't exist, return empty: return new ArrayList<>(); } } private String getFirstLineOfFile(Path path) throws IOException { if (Files.isRegularFile(path)) { List<String> allLines; try { allLines = Files.readAllLines(path, UTF_8); } catch (NoSuchFileException ex) { return null; } if (allLines.isEmpty()) { return null; } return allLines.get(0); } return null; } @Override public void setNodeIdFile(String data) throws IOException { setFile(data, nodeIdPath); } @Override public void setClusterNameFile(String data) throws IOException { setFile(data, clusterNamePath); } private void setFile(String data, Path path) throws IOException { List<String> lines = new ArrayList<>(1); lines.add(data); Files.write(path, lines, UTF_8); } @Override public Path getQuorumRelPath(String quorumId) throws IOException { Path quorumRelPath = Paths.get(quorumsSubDir, quorumId); createSubDir(quorumRelPath); return quorumRelPath; } @Override public List<Long> readPeers(String quorumId) throws IOException { List<String> peersFromFile = readFile(getQuorumRelPath(quorumId), peerIdsFile); try { //noinspection Convert2MethodRef return Lists.transform(peersFromFile, lineOfFile -> Long.parseLong(lineOfFile)); } catch (NumberFormatException e) { // if the file contains garbage, we can't just sub in an empty list. throw new IOException("Unparsable peer file", e); } } @Override public void writePeersToFile(String quorumId, List<Long> peers) throws IOException { //noinspection Convert2MethodRef List<String> peerIdsStrings = Lists.transform(peers, (p) -> p.toString()); writeFile(getQuorumRelPath(quorumId), peerIdsFile, peerIdsStrings); } @Override public void writeBinaryData(String quorumId, String type, byte[] data) throws IOException { Path quorumRelPath = getQuorumRelPath(quorumId); Path filePath = getBaseConfigPath().resolve(quorumRelPath).resolve(type); Files.write(filePath, data); } @Override public byte[] readBinaryData(String quorumId, String type) throws IOException { Path quorumPath = getQuorumRelPath(quorumId); Path binaryDataPath = getBaseConfigPath().resolve(quorumPath).resolve(type); return Files.readAllBytes(binaryDataPath); } @Override public List<String> configuredQuorums() throws IOException { Path quorumsPath = getBaseConfigPath().resolve(quorumsSubDir); List<String> quorumNames = new ArrayList<>(); try (DirectoryStream<Path> allQuorums = Files.newDirectoryStream(quorumsPath)) { for (Path pathQuorum : allQuorums) { if (Files.isDirectory(pathQuorum)) { quorumNames.add(pathQuorum.getFileName().toString()); } } } catch (NoSuchFileException ignored) { } return quorumNames; } @Override public Path getBaseConfigPath() { return baseConfigPath; } }
package ru.job4j.chess; import ru.job4j.chess.exceptions.FigureNotFoundException; import ru.job4j.chess.exceptions.ImpossibleMoveException; import ru.job4j.chess.exceptions.OccupiedWayException; import ru.job4j.chess.figures.*; /** * Playing board. */ public class Board { /** * @param figures - main array of figures on the field; */ Figure[] figures; /** * @param HEIGHT - size of the board; */ public static final int HEIGHT = 8; /** * @param source - source position of figure. * @param dist - desierable position. * @return true if we can move, otherwise false. * @throw exceptions if move cannot be done. */ public boolean move(Cell source, Cell dist) throws ImpossibleMoveException, OccupiedWayException, FigureNotFoundException { Figure src = getFigure(source); if (src == null) { throw new FigureNotFoundException(); } int tmpX = source.getX(); int tmpY = source.getY(); Cell[] route = src.way(dist); int idDist = getFigureId(dist); int idSource = getFigureId(source); if (freeRoute(route, src)) { figures[idSource].position.setX(dist.getX()); figures[idSource].position.setY(dist.getY()); figures[idDist] = new NullFigure(new Cell(tmpX, tmpY), Side.EMPTY); } else { throw new OccupiedWayException(); } return true; } /** * Init method, to fill figures. */ public void init() { figures = new Figure[64]; int id = 0; for (int y = 1; y <= HEIGHT; y++) { for (int x = 1; x <= HEIGHT; x++) { if (y == 1 || y == 8) { if (x == 1 || x == 8) { figures[id++] = new Rook(new Cell(x, y), getSide(y)); } else if (x == 2 || x == 7) { figures[id++] = new Bishop(new Cell(x, y), getSide(y)); } else if (x == 3 || x == 6) { figures[id++] = new Knight(new Cell(x, y), getSide(y)); } else if (x == 4) { figures[id++] = new King(new Cell(x, y), getSide(y)); } else if (x == 5) { figures[id++] = new Queen(new Cell(x, y), getSide(y)); } } else if (y == 2 || y == 7) { figures[id++] = new Pawn(new Cell(x, y), getSide(y)); } else { figures[id++] = new NullFigure(new Cell(x, y), Side.EMPTY); } } } } /** * Method prints board in console. */ public void draw() { System.out.println(" A B C D E F G H"); for (int y = 1; y <= HEIGHT; y++) { System.out.print(y + " "); for (int x = 1; x <= HEIGHT; x++) { for (Figure f : figures) { if (f.position.getX() == x && f.position.getY() == y) { System.out.print(f + " "); } } } System.out.println(); } } /** * @param y - param. */ private Side getSide(int y) { if (y >= 2) { return Side.BLACK; } else { return Side.WHITE; } } /** * Get figure in cell. * * @param source - primary coords of the cell. * @return - figure or null if not found any figure. */ private Figure getFigure(Cell source) { Figure figure = null; for (Figure f : figures) { // search figure in the cell. if (!(f.side == Side.EMPTY) && f.position.getX() == source.getX() && f.position.getY() == source.getY()) { figure = f; break; } } return figure; } /** * * @param source - source cell. * @return - index of the figure in figures. */ private int getFigureId(Cell source) { int result = -1; for (int i = 0; i < figures.length; i++) { Figure f = figures[i]; if (f.position.getX() == source.getX() && f.position.getY() == source.getY()) { result = i; break; } } return result; } /** * Checks if route is free to move. * @param route - possible route. * @param f - figure that want to move. * @return - true if possible, false if not. */ private boolean freeRoute(Cell[] route, Figure f) { boolean result = true; int len = route.length; for (int i = 0; i < len; i++) { Figure figure = getFigure(route[i]); if (figure != null) { if (i == len - 1 && figure.side == f.side) { result = false; } else if (figure.side != Side.EMPTY && i < len - 1) { result = false; break; } } } return result; } }
package net.iaeste.iws.api.dtos.exchange; import net.iaeste.iws.api.constants.IWSConstants; import net.iaeste.iws.api.constants.exchange.IWSExchangeConstants; import net.iaeste.iws.api.enums.Currency; import net.iaeste.iws.api.enums.Language; import net.iaeste.iws.api.enums.exchange.ExchangeType; import net.iaeste.iws.api.enums.exchange.FieldOfStudy; import net.iaeste.iws.api.enums.exchange.LanguageLevel; import net.iaeste.iws.api.enums.exchange.LanguageOperator; import net.iaeste.iws.api.enums.exchange.OfferState; import net.iaeste.iws.api.enums.exchange.OfferType; import net.iaeste.iws.api.enums.exchange.PaymentFrequency; import net.iaeste.iws.api.enums.exchange.StudyLevel; import net.iaeste.iws.api.enums.exchange.TypeOfWork; import net.iaeste.iws.api.util.AbstractVerification; import net.iaeste.iws.api.util.Date; import net.iaeste.iws.api.util.DatePeriod; import net.iaeste.iws.api.util.DateTime; import java.math.BigDecimal; import java.util.EnumSet; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; public final class Offer extends AbstractVerification { /** {@link IWSConstants#SERIAL_VERSION_UID}. */ private static final long serialVersionUID = IWSConstants.SERIAL_VERSION_UID; private String offerId = null; private String refNo = null; private OfferType offerType = OfferType.OPEN; // Defaulting to IW, as COBE is causing problems for Reserved Offers private ExchangeType exchangeType = ExchangeType.IW; private String oldRefNo = null; // General Work Description private Employer employer = null; private String workDescription = null; private TypeOfWork typeOfWork = null; private Float weeklyHours = null; private Float dailyHours = null; private Float weeklyWorkDays = null; private Set<StudyLevel> studyLevels = EnumSet.noneOf(StudyLevel.class); private Set<FieldOfStudy> fieldOfStudies = EnumSet.noneOf(FieldOfStudy.class); private Set<String> specializations = new HashSet<>(1); private Boolean previousTrainingRequired = null; private String otherRequirements = null; // DatePeriod for the Offer private Integer minimumWeeks = null; private Integer maximumWeeks = null; private DatePeriod period1 = null; private DatePeriod period2 = null; private DatePeriod unavailable = null; // Language restrictions private Language language1 = null; private LanguageLevel language1Level = null; private LanguageOperator language1Operator = null; private Language language2 = null; private LanguageLevel language2Level = null; private LanguageOperator language2Operator = null; private Language language3 = null; private LanguageLevel language3Level = null; // Payment & Cost information private BigDecimal payment = null; private PaymentFrequency paymentFrequency = null; /* need big numbers, e.g. 1 EUR = 26.435,00 VND */ private Currency currency = null; private String deduction = null; private BigDecimal livingCost = null; private PaymentFrequency livingCostFrequency = null; private String lodgingBy = null; private BigDecimal lodgingCost = null; private PaymentFrequency lodgingCostFrequency = null; // Other things private Date nominationDeadline = null; private Integer numberOfHardCopies = null; private String additionalInformation = null; private String privateComment = null; private OfferState status = null; private DateTime modified = null; private DateTime created = null; // Additional information private String nsFirstname = null; private String nsLastname = null; private DateTime shared = null; // custom flag used by the FE to hide irrelevant offers private Boolean hidden = false; // Object Constructors /** * Empty Constructor, to use if the setters are invoked. This is required * for WebServices to work properly. */ public Offer() { } /** * Copy constructor. * * @param offer Offer Object to copy */ public Offer(final Offer offer) { if (offer != null) { offerId = offer.offerId; refNo = offer.refNo; offerType = offer.offerType; exchangeType = offer.exchangeType; employer = new Employer(offer.employer); workDescription = offer.workDescription; weeklyHours = offer.weeklyHours; dailyHours = offer.dailyHours; weeklyWorkDays = offer.weeklyWorkDays; typeOfWork = offer.typeOfWork; studyLevels = offer.studyLevels; fieldOfStudies = offer.fieldOfStudies; specializations = offer.specializations; previousTrainingRequired = offer.previousTrainingRequired; otherRequirements = offer.otherRequirements; minimumWeeks = offer.minimumWeeks; maximumWeeks = offer.maximumWeeks; period1 = new DatePeriod(offer.period1); period2 = new DatePeriod(offer.period2); unavailable = new DatePeriod(offer.unavailable); language1 = offer.language1; language1Level = offer.language1Level; language1Operator = offer.language1Operator; language2 = offer.language2; language2Level = offer.language2Level; language2Operator = offer.language2Operator; language3 = offer.language3; language3Level = offer.language3Level; payment = offer.payment; paymentFrequency = offer.paymentFrequency; currency = offer.currency; deduction = offer.deduction; livingCost = offer.livingCost; livingCostFrequency = offer.livingCostFrequency; lodgingBy = offer.lodgingBy; lodgingCost = offer.lodgingCost; lodgingCostFrequency = offer.lodgingCostFrequency; nominationDeadline = offer.nominationDeadline; numberOfHardCopies = offer.numberOfHardCopies; additionalInformation = offer.additionalInformation; privateComment = offer.privateComment; status = offer.status; modified = offer.modified; created = offer.created; nsFirstname = offer.nsFirstname; nsLastname = offer.nsLastname; shared = offer.shared; hidden = offer.hidden; } } // Standard Setters & Getters public void setOfferId(final String offerId) throws IllegalArgumentException { ensureValidId("offerId", offerId); this.offerId = offerId; } public String getOfferId() { return offerId; } public void setRefNo(final String refNo) throws IllegalArgumentException { ensureNotNullAndValidRefno("refNo", refNo); this.refNo = refNo; } public String getRefNo() { return refNo; } /** * Returns the Printable or Displayable version of the Reference Number. This * is the version of the Reference Number together with Type of Offer. * * @return Reference Number + Offer Type */ public String printableRefNo() { return refNo + offerType.getType(); } public void setOfferType(final OfferType offerType) throws IllegalArgumentException { ensureNotNull("offerType", offerType); this.offerType = offerType; } public OfferType getOfferType() { return offerType; } public void setExchangeType(final ExchangeType exchangeType) throws IllegalArgumentException { ensureNotNull("offerType", offerType); ensureNotNullAndContains("exchangeType", exchangeType, offerType.getExchangeTypes()); this.exchangeType = exchangeType; } public ExchangeType getExchangeType() { return exchangeType; } /** * Sets the IW3 Offer refNo. * The oldRefNo once set after migration cannot be changed, * any changes of this field made to DTO will be ignored during * persiting the entity. * * @param oldRefNo old Offer Reference Number */ public void setOldRefNo(final String oldRefNo) { ensureNotTooLong("oldRefNo", oldRefNo, 50); this.oldRefNo = oldRefNo; } public String getOldRefNo() { return oldRefNo; } public void setEmployer(final Employer employer) throws IllegalArgumentException { //ensureNotNullAndVerifiable("employer", employer); ensureNotNull("employer", employer); this.employer = new Employer(employer); } public Employer getEmployer() { return new Employer(employer); } public void setWorkDescription(final String workDescription) throws IllegalArgumentException { ensureNotTooLong("workDescription", workDescription, 3000); this.workDescription = workDescription; } public String getWorkDescription() { return workDescription; } public void setTypeOfWork(final TypeOfWork typeOfWork) { this.typeOfWork = typeOfWork; } public TypeOfWork getTypeOfWork() { return typeOfWork; } public void setWeeklyHours(final Float weeklyHours) { ensureNotNull("weeklyHours", weeklyHours); this.weeklyHours = weeklyHours; } public Float getWeeklyHours() { return weeklyHours; } /** * Sets the Daily Hours expected by the Employer. * * @param dailyHours Offer Daily Hours */ public void setDailyHours(final Float dailyHours) { this.dailyHours = dailyHours; } public Float getDailyHours() { return dailyHours; } /** * Sets the number of work days expected by the Employer. * * @param dailyHours Offer Weekly Work Days */ public void setWeeklyWorkDays(final Float weeklyWorkDays) { this.weeklyWorkDays = weeklyWorkDays; } public Float getWeeklyWorkDays() { return weeklyWorkDays; } public void setStudyLevels(final Set<StudyLevel> studyLevels) throws IllegalArgumentException { ensureNotNull("studyLevels", studyLevels); ensureNotTooLong("studyLevels", studyLevels.toString(), 25); this.studyLevels = studyLevels; } public Set<StudyLevel> getStudyLevels() { return studyLevels; } public void setFieldOfStudies(final Set<FieldOfStudy> fieldOfStudies) throws IllegalArgumentException { ensureNotNullOrTooLong("fieldOfStudies", fieldOfStudies, IWSExchangeConstants.MAX_OFFER_FIELDS_OF_STUDY); this.fieldOfStudies = fieldOfStudies; } public Set<FieldOfStudy> getFieldOfStudies() { return fieldOfStudies; } public void setSpecializations(final Set<String> specializations) throws IllegalArgumentException { ensureNotNullOrTooLong("specializations", specializations, IWSExchangeConstants.MAX_OFFER_SPECIALIZATIONS); this.specializations = specializations; } public Set<String> getSpecializations() { return specializations; } public void setPreviousTrainingRequired(final Boolean previousTrainingRequired) { this.previousTrainingRequired = previousTrainingRequired; } public Boolean getPreviousTrainingRequired() { return previousTrainingRequired; } public void setOtherRequirements(final String otherRequirements) throws IllegalArgumentException { ensureNotTooLong("otherRequirements", otherRequirements, 4000); this.otherRequirements = otherRequirements; } public String getOtherRequirements() { return otherRequirements; } public void setMinimumWeeks(final Integer minimumWeeks) throws IllegalArgumentException { ensureNotNullAndMinimum("minimumWeeks", minimumWeeks, IWSExchangeConstants.MIN_OFFER_MINIMUM_WEEKS); this.minimumWeeks = minimumWeeks; } public Integer getMinimumWeeks() { return minimumWeeks; } public void setMaximumWeeks(final Integer maximumWeeks) throws IllegalArgumentException { ensureNotNullAndMinimum("maximumWeeks", maximumWeeks, IWSExchangeConstants.MIN_OFFER_MINIMUM_WEEKS); this.maximumWeeks = maximumWeeks; } public Integer getMaximumWeeks() { return maximumWeeks; } public void setPeriod1(final DatePeriod period1) throws IllegalArgumentException { ensureNotNull("period1", period1); this.period1 = new DatePeriod(period1); } public DatePeriod getPeriod1() { return new DatePeriod(period1); } public void setPeriod2(final DatePeriod period2) { this.period2 = new DatePeriod(period2); } public DatePeriod getPeriod2() { return new DatePeriod(period2); } public void setUnavailable(final DatePeriod unavailable) { this.unavailable = new DatePeriod(unavailable); } public DatePeriod getUnavailable() { return new DatePeriod(unavailable); } public void setLanguage1(final Language language1) { this.language1 = language1; } public Language getLanguage1() { return language1; } public void setLanguage1Level(final LanguageLevel language1Level) { this.language1Level = language1Level; } public LanguageLevel getLanguage1Level() { return language1Level; } public void setLanguage1Operator(final LanguageOperator language1Operator) { this.language1Operator = language1Operator; } public LanguageOperator getLanguage1Operator() { return language1Operator; } public void setLanguage2(final Language language2) { this.language2 = language2; } public Language getLanguage2() { return language2; } public void setLanguage2Level(final LanguageLevel language2Level) { this.language2Level = language2Level; } public LanguageLevel getLanguage2Level() { return language2Level; } public void setLanguage2Operator(final LanguageOperator language2Operator) { this.language2Operator = language2Operator; } public LanguageOperator getLanguage2Operator() { return language2Operator; } public void setLanguage3(final Language language3) { this.language3 = language3; } public Language getLanguage3() { return language3; } public void setLanguage3Level(final LanguageLevel language3Level) { this.language3Level = language3Level; } public LanguageLevel getLanguage3Level() { return language3Level; } public void setPayment(final BigDecimal payment) { this.payment = payment; } public BigDecimal getPayment() { return payment; } public void setPaymentFrequency(final PaymentFrequency paymentFrequency) { this.paymentFrequency = paymentFrequency; } public PaymentFrequency getPaymentFrequency() { return paymentFrequency; } public void setCurrency(final Currency currency) { this.currency = currency; } public Currency getCurrency() { return currency; } public void setDeduction(final String deduction) { ensureNotTooLong("deduction", deduction, 50); this.deduction = deduction; } public String getDeduction() { return deduction; } public void setLivingCost(final BigDecimal livingCost) { this.livingCost = livingCost; } public BigDecimal getLivingCost() { return livingCost; } public void setLivingCostFrequency(final PaymentFrequency livingCostFrequency) { this.livingCostFrequency = livingCostFrequency; } public PaymentFrequency getLivingCostFrequency() { return livingCostFrequency; } public void setLodgingBy(final String lodgingBy) { ensureNotTooLong("lodgingBy", lodgingBy, 255); this.lodgingBy = lodgingBy; } public String getLodgingBy() { return lodgingBy; } public void setLodgingCost(final BigDecimal lodgingCost) { this.lodgingCost = lodgingCost; } public BigDecimal getLodgingCost() { return lodgingCost; } public void setLodgingCostFrequency(final PaymentFrequency lodgingCostFrequency) { this.lodgingCostFrequency = lodgingCostFrequency; } public PaymentFrequency getLodgingCostFrequency() { return lodgingCostFrequency; } public void setNominationDeadline(final Date nominationDeadline) { this.nominationDeadline = nominationDeadline; } public Date getNominationDeadline() { return nominationDeadline; } public void setNumberOfHardCopies(final Integer numberOfHardCopies) { this.numberOfHardCopies = numberOfHardCopies; } public Integer getNumberOfHardCopies() { return numberOfHardCopies; } public void setAdditionalInformation(final String additionalInformation) throws IllegalArgumentException { ensureNotTooLong("additionalInformation", additionalInformation, 3000); this.additionalInformation = additionalInformation; } public String getAdditionalInformation() { return additionalInformation; } public void setPrivateComment(final String privateComment) throws IllegalArgumentException { ensureNotTooLong("privateComment", privateComment, 1000); this.privateComment = privateComment; } public String getPrivateComment() { return privateComment; } public void setStatus(final OfferState status) { this.status = status; } public OfferState getStatus() { return status; } /** * Sets the Offer latest modification DateTime. Note, this field is * controlled by the IWS, and cannot be altered by users. * * @param modified DateTime of latest modification */ public void setModified(final DateTime modified) { this.modified = modified; } public DateTime getModified() { return modified; } /** * Sets the Offer Creation DateTime. Note, this field is controlled by the * IWS, and cannot be altered by users. * * @param created Offer Creation DateTime */ public void setCreated(final DateTime created) { this.created = created; } public DateTime getCreated() { return created; } /** * Sets the National Secretary for this Offer (from the National Group). * Note, this field is controlled by the IWS and cannot be altered via this * Object. * * @param nsFirstname NS Firstname */ public void setNsFirstname(final String nsFirstname) { this.nsFirstname = nsFirstname; } public String getNsFirstname() { return nsFirstname; } /** * Sets the National Secretary for this Offer (from the National Group). * Note, this field is controlled by the IWS and cannot be altered via this * Object. * * @param nsLastname NS Lastname */ public void setNsLastname(final String nsLastname) { this.nsLastname = nsLastname; } public String getNsLastname() { return nsLastname; } /** * Sets the Offer Sharing DateTime. Note, this field is controlled by the * IWS, and cannot be altered by users. * * @param shared Offer Sharing DateTime */ public void setShared(DateTime shared) { this.shared = shared; } public DateTime getShared() { return shared; } public void setHidden(boolean hidden) { this.hidden = hidden; } public boolean isHidden() { return hidden; } // Standard DTO Methods /** * {@inheritDoc} */ @Override public Map<String, String> validate() { final Map<String, String> validation = new HashMap<>(0); // These checks match those from the Database, remaining are implicit // filled by the IWS Logic as part of the processing of the Offer isNotNull(validation, "refNo", refNo); isNotNull(validation, "offerType", offerType); // The Exchange Type cannot be null and we also need to verify the // content, however as it is dependent on the Offer Type, we must add // a null check here if (offerType != null) { isNotNullAndContains(validation, "exchangeType", exchangeType, offerType.getExchangeTypes()); } else { isNotNull(validation, "exchangeType", exchangeType); } // We need to ensure that the Employer is verifiable also! isNotNullAndVerifiable(validation, "employer", employer); isNotNull(validation, "employer", employer); isNotNull(validation, "weeklyHours", weeklyHours); isNotNull(validation, "workDescription", workDescription); isNotNull(validation, "studyLevels", studyLevels); isNotNull(validation, "fieldOfStudies", fieldOfStudies); isNotNull(validation, "period1", period1); isNotNull(validation, "minimumWeeks", minimumWeeks); isNotNull(validation, "maximumWeeks", maximumWeeks); isNotNull(validation, "language1", language1); isNotNull(validation, "language1Level", language1Level); return validation; } /** * {@inheritDoc} */ @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (!(obj instanceof Offer)) { return false; } final Offer offer = (Offer) obj; if (additionalInformation != null ? !additionalInformation.equals(offer.additionalInformation) : offer.additionalInformation != null) { return false; } if (created != null ? !created.equals(offer.created) : offer.created != null) { return false; } if (currency != offer.currency) { return false; } if (dailyHours != null ? !dailyHours.equals(offer.dailyHours) : offer.dailyHours != null) { return false; } if (deduction != null ? !deduction.equals(offer.deduction) : offer.deduction != null) { return false; } if (employer != null ? !employer.equals(offer.employer) : offer.employer != null) { return false; } if (exchangeType != offer.exchangeType) { return false; } if (fieldOfStudies != null ? !fieldOfStudies.equals(offer.fieldOfStudies) : offer.fieldOfStudies != null) { return false; } if (language1 != offer.language1) { return false; } if (language1Level != offer.language1Level) { return false; } if (language1Operator != offer.language1Operator) { return false; } if (language2 != offer.language2) { return false; } if (language2Level != offer.language2Level) { return false; } if (language2Operator != offer.language2Operator) { return false; } if (language3 != offer.language3) { return false; } if (language3Level != offer.language3Level) { return false; } if (livingCost != null ? !(livingCost.compareTo(offer.livingCost) == 0) : offer.livingCost != null) { return false; } if (livingCostFrequency != offer.livingCostFrequency) { return false; } if (lodgingBy != null ? !lodgingBy.equals(offer.lodgingBy) : offer.lodgingBy != null) { return false; } if (lodgingCost != null ? !(lodgingCost.compareTo(offer.lodgingCost) == 0) : offer.lodgingCost != null) { return false; } if (lodgingCostFrequency != offer.lodgingCostFrequency) { return false; } if (maximumWeeks != null ? !maximumWeeks.equals(offer.maximumWeeks) : offer.maximumWeeks != null) { return false; } if (minimumWeeks != null ? !minimumWeeks.equals(offer.minimumWeeks) : offer.minimumWeeks != null) { return false; } if (modified != null ? !modified.equals(offer.modified) : offer.modified != null) { return false; } if (nominationDeadline != null ? !nominationDeadline.equals(offer.nominationDeadline) : offer.nominationDeadline != null) { return false; } if (nsFirstname != null ? !nsFirstname.equals(offer.nsFirstname) : offer.nsFirstname != null) { return false; } if (nsLastname != null ? !nsLastname.equals(offer.nsLastname) : offer.nsLastname != null) { return false; } if (numberOfHardCopies != null ? !numberOfHardCopies.equals(offer.numberOfHardCopies) : offer.numberOfHardCopies != null) { return false; } if (offerId != null ? !offerId.equals(offer.offerId) : offer.offerId != null) { return false; } if (offerType != offer.offerType) { return false; } if (oldRefNo != null ? !oldRefNo.equals(offer.oldRefNo) : offer.oldRefNo != null) { return false; } if (otherRequirements != null ? !otherRequirements.equals(offer.otherRequirements) : offer.otherRequirements != null) { return false; } if (payment != null ? !(payment.compareTo(offer.payment) == 0) : offer.payment != null) { return false; } if (paymentFrequency != offer.paymentFrequency) { return false; } if (period1 != null ? !period1.equals(offer.period1) : offer.period1 != null) { return false; } if (period2 != null ? !period2.equals(offer.period2) : offer.period2 != null) { return false; } if (previousTrainingRequired != null ? !previousTrainingRequired.equals(offer.previousTrainingRequired) : offer.previousTrainingRequired != null) { return false; } if (privateComment != null ? !privateComment.equals(offer.privateComment) : offer.privateComment != null) { return false; } if (refNo != null ? !refNo.equals(offer.refNo) : offer.refNo != null) { return false; } if (shared != null ? !shared.equals(offer.shared) : offer.shared != null) { return false; } if (specializations != null ? !specializations.equals(offer.specializations) : offer.specializations != null) { return false; } if (status != offer.status) { return false; } if (studyLevels != null ? !studyLevels.equals(offer.studyLevels) : offer.studyLevels != null) { return false; } if (typeOfWork != offer.typeOfWork) { return false; } if (unavailable != null ? !unavailable.equals(offer.unavailable) : offer.unavailable != null) { return false; } if (weeklyHours != null ? !weeklyHours.equals(offer.weeklyHours) : offer.weeklyHours != null) { return false; } if (weeklyWorkDays != null ? !weeklyWorkDays.equals(offer.weeklyWorkDays) : offer.weeklyWorkDays != null) { return false; } return !(workDescription != null ? !workDescription.equals(offer.workDescription) : offer.workDescription != null); } /** * {@inheritDoc} */ @Override public int hashCode() { int result = IWSConstants.HASHCODE_INITIAL_VALUE; result = IWSConstants.HASHCODE_MULTIPLIER * result + ((offerId != null) ? offerId.hashCode() : 0); result = IWSConstants.HASHCODE_MULTIPLIER * result + (refNo != null ? refNo.hashCode() : 0); result = IWSConstants.HASHCODE_MULTIPLIER * result + (offerType != null ? offerType.hashCode() : 0); result = IWSConstants.HASHCODE_MULTIPLIER * result + (exchangeType != null ? exchangeType.hashCode() : 0); result = IWSConstants.HASHCODE_MULTIPLIER * result + (oldRefNo != null ? oldRefNo.hashCode() : 0); result = IWSConstants.HASHCODE_MULTIPLIER * result + (employer != null ? employer.hashCode() : 0); result = IWSConstants.HASHCODE_MULTIPLIER * result + (workDescription != null ? workDescription.hashCode() : 0); result = IWSConstants.HASHCODE_MULTIPLIER * result + (typeOfWork != null ? typeOfWork.hashCode() : 0); result = IWSConstants.HASHCODE_MULTIPLIER * result + (weeklyHours != null ? weeklyHours.hashCode() : 0); result = IWSConstants.HASHCODE_MULTIPLIER * result + (dailyHours != null ? dailyHours.hashCode() : 0); result = IWSConstants.HASHCODE_MULTIPLIER * result + (weeklyWorkDays != null ? weeklyWorkDays.hashCode() : 0); result = IWSConstants.HASHCODE_MULTIPLIER * result + (studyLevels != null ? studyLevels.hashCode() : 0); result = IWSConstants.HASHCODE_MULTIPLIER * result + (fieldOfStudies != null ? fieldOfStudies.hashCode() : 0); result = IWSConstants.HASHCODE_MULTIPLIER * result + (specializations != null ? specializations.hashCode() : 0); result = IWSConstants.HASHCODE_MULTIPLIER * result + (previousTrainingRequired != null ? previousTrainingRequired.hashCode() : 0); result = IWSConstants.HASHCODE_MULTIPLIER * result + (otherRequirements != null ? otherRequirements.hashCode() : 0); result = IWSConstants.HASHCODE_MULTIPLIER * result + (minimumWeeks != null ? minimumWeeks.hashCode() : 0); result = IWSConstants.HASHCODE_MULTIPLIER * result + (maximumWeeks != null ? maximumWeeks.hashCode() : 0); result = IWSConstants.HASHCODE_MULTIPLIER * result + (period1 != null ? period1.hashCode() : 0); result = IWSConstants.HASHCODE_MULTIPLIER * result + (period2 != null ? period2.hashCode() : 0); result = IWSConstants.HASHCODE_MULTIPLIER * result + (unavailable != null ? unavailable.hashCode() : 0); result = IWSConstants.HASHCODE_MULTIPLIER * result + (language1 != null ? language1.hashCode() : 0); result = IWSConstants.HASHCODE_MULTIPLIER * result + (language1Level != null ? language1Level.hashCode() : 0); result = IWSConstants.HASHCODE_MULTIPLIER * result + (language1Operator != null ? language1Operator.hashCode() : 0); result = IWSConstants.HASHCODE_MULTIPLIER * result + (language2 != null ? language2.hashCode() : 0); result = IWSConstants.HASHCODE_MULTIPLIER * result + (language2Level != null ? language2Level.hashCode() : 0); result = IWSConstants.HASHCODE_MULTIPLIER * result + (language2Operator != null ? language2Operator.hashCode() : 0); result = IWSConstants.HASHCODE_MULTIPLIER * result + (language3 != null ? language3.hashCode() : 0); result = IWSConstants.HASHCODE_MULTIPLIER * result + (language3Level != null ? language3Level.hashCode() : 0); result = IWSConstants.HASHCODE_MULTIPLIER * result + (payment != null ? payment.hashCode() : 0); result = IWSConstants.HASHCODE_MULTIPLIER * result + (paymentFrequency != null ? paymentFrequency.hashCode() : 0); result = IWSConstants.HASHCODE_MULTIPLIER * result + (currency != null ? currency.hashCode() : 0); result = IWSConstants.HASHCODE_MULTIPLIER * result + (deduction != null ? deduction.hashCode() : 0); result = IWSConstants.HASHCODE_MULTIPLIER * result + (livingCost != null ? livingCost.hashCode() : 0); result = IWSConstants.HASHCODE_MULTIPLIER * result + (livingCostFrequency != null ? livingCostFrequency.hashCode() : 0); result = IWSConstants.HASHCODE_MULTIPLIER * result + (lodgingBy != null ? lodgingBy.hashCode() : 0); result = IWSConstants.HASHCODE_MULTIPLIER * result + (lodgingCost != null ? lodgingCost.hashCode() : 0); result = IWSConstants.HASHCODE_MULTIPLIER * result + (lodgingCostFrequency != null ? lodgingCostFrequency.hashCode() : 0); result = IWSConstants.HASHCODE_MULTIPLIER * result + (nominationDeadline != null ? nominationDeadline.hashCode() : 0); result = IWSConstants.HASHCODE_MULTIPLIER * result + (numberOfHardCopies != null ? numberOfHardCopies.hashCode() : 0); result = IWSConstants.HASHCODE_MULTIPLIER * result + (additionalInformation != null ? additionalInformation.hashCode() : 0); result = IWSConstants.HASHCODE_MULTIPLIER * result + (privateComment != null ? privateComment.hashCode() : 0); result = IWSConstants.HASHCODE_MULTIPLIER * result + (status != null ? status.hashCode() : 0); result = IWSConstants.HASHCODE_MULTIPLIER * result + (modified != null ? modified.hashCode() : 0); result = IWSConstants.HASHCODE_MULTIPLIER * result + (created != null ? created.hashCode() : 0); result = IWSConstants.HASHCODE_MULTIPLIER * result + (nsFirstname != null ? nsFirstname.hashCode() : 0); result = IWSConstants.HASHCODE_MULTIPLIER * result + (nsLastname != null ? nsLastname.hashCode() : 0); result = IWSConstants.HASHCODE_MULTIPLIER * result + (shared != null ? shared.hashCode() : 0); result = IWSConstants.HASHCODE_MULTIPLIER * result + (hidden != null ? hidden.hashCode() : 0); return result; } /** * {@inheritDoc} */ @Override public String toString() { return "Offer{" + "offerId='" + offerId + '\'' + ", refNo='" + refNo + '\'' + ", offerType='" + offerType + '\'' + ", exchangeType='" + exchangeType + '\'' + ", oldRefNo='" + oldRefNo + '\'' + ", employer=" + employer + ", workDescription='" + workDescription + '\'' + ", typeOfWork=" + typeOfWork + ", weeklyHours=" + weeklyHours + ", dailyHours=" + dailyHours + ", weeklyWorkDays=" + weeklyWorkDays + ", studyLevels=" + studyLevels + ", fieldOfStudies=" + fieldOfStudies + ", specializations=" + specializations + ", previousTrainingRequired=" + previousTrainingRequired + ", otherRequirements='" + otherRequirements + '\'' + ", minimumWeeks=" + minimumWeeks + ", maximumWeeks=" + maximumWeeks + ", period1=" + period1 + ", period2=" + period2 + ", unavailable=" + unavailable + ", language1=" + language1 + ", language1Level=" + language1Level + ", language1Operator=" + language1Operator + ", language2=" + language2 + ", language2Level=" + language2Level + ", language2Operator=" + language2Operator + ", language3=" + language3 + ", language3Level=" + language3Level + ", payment=" + payment + ", paymentFrequency=" + paymentFrequency + ", currency=" + currency + ", deduction='" + deduction + '\'' + ", livingCost=" + livingCost + ", livingCostFrequency=" + livingCostFrequency + ", lodgingBy='" + lodgingBy + '\'' + ", lodgingCost=" + lodgingCost + ", lodgingCostFrequency=" + lodgingCostFrequency + ", nominationDeadline=" + nominationDeadline + ", numberOfHardCopies=" + numberOfHardCopies + ", additionalInformation='" + additionalInformation + '\'' + ", privateComment='" + privateComment + '\'' + ", status=" + status + ", modified=" + modified + ", created=" + created + ", nsFirstname='" + nsFirstname + '\'' + ", nsLastname='" + nsLastname + '\'' + ", shared=" + shared + ", hidden=" + hidden + '}'; } }
package mil.nga.giat.mage.sdk.datastore.observation; import android.net.Uri; import android.support.annotation.NonNull; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.j256.ormlite.field.DataType; import com.j256.ormlite.field.DatabaseField; import com.j256.ormlite.field.ForeignCollectionField; import com.j256.ormlite.table.DatabaseTable; import org.apache.commons.lang3.builder.CompareToBuilder; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.ToStringBuilder; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import mil.nga.giat.mage.sdk.Temporal; import mil.nga.giat.mage.sdk.datastore.user.Event; import mil.nga.giat.mage.sdk.utils.GeometryUtility; import mil.nga.wkb.geom.Geometry; import mil.nga.wkb.geom.Point; import mil.nga.wkb.util.GeometryUtils; @DatabaseTable(tableName = "observations") public class Observation implements Comparable<Observation>, Temporal { // name _id needed for cursor adapters @DatabaseField(generatedId = true) private Long _id; @DatabaseField(unique = true, columnName = "remote_id") private String remoteId; @DatabaseField(unique = true, columnName = "url") private String url; /** * This is really the remote id! */ @DatabaseField(columnName = "user_id", canBeNull = false) private String userId = "-1"; @DatabaseField(columnName = "device_id") private String deviceId; /** * This is the time the server created or updated the observation. It can also be a local time, if no time from the server is given. */ @DatabaseField(canBeNull = false, columnName = "last_modified", dataType = DataType.DATE_LONG) private Date lastModified = null; /** * This is the time the observation was made/reported at. */ @DatabaseField(canBeNull = false, dataType = DataType.DATE_LONG) private Date timestamp = new Date(0); @DatabaseField(canBeNull = false) private boolean dirty = Boolean.TRUE; @DatabaseField(canBeNull = false) private State state = State.ACTIVE; @DatabaseField(columnName = "geometry", canBeNull = false, dataType = DataType.BYTE_ARRAY) private byte[] geometryBytes; @DatabaseField private String provider; @DatabaseField private Float accuracy; @DatabaseField private String locationDelta; @DatabaseField(canBeNull = false, foreign = true, foreignAutoRefresh = true) private Event event; @ForeignCollectionField(eager = true) private Collection<ObservationForm> forms = new ArrayList<>(); @ForeignCollectionField(eager = true) private Collection<Attachment> attachments = new ArrayList<>(); @DatabaseField(canBeNull = true, foreign = true, foreignAutoRefresh = true, foreignAutoCreate = true) private ObservationImportant important; @DatabaseField(persisterClass = ObservationErrorClassPersister.class, columnName = "error") private ObservationError error; @ForeignCollectionField(eager = true) private Collection<ObservationFavorite> favorites = new ArrayList<>(); public Observation() { // ORMLite needs a no-arg constructor } public Observation(Geometry geometry, Collection<ObservationForm> forms, Collection<Attachment> attachments, Date timestamp, Event event) { this(null, null, geometry, forms, attachments, timestamp, event); this.dirty = true; } public Observation(String remoteId, Date lastModified, Geometry geometry, Collection<ObservationForm> forms, Collection<Attachment> attachments, Date timestamp, Event event) { super(); this.remoteId = remoteId; this.lastModified = lastModified; this.geometryBytes = GeometryUtility.toGeometryBytes(geometry); this.forms = forms; this.attachments = attachments; this.dirty = false; this.timestamp = timestamp; this.event = event; } public Long getId() { return _id; } public void setId(Long id) { this._id = id; } public String getRemoteId() { return remoteId; } public void setRemoteId(String remoteId) { this.remoteId = remoteId; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getDeviceId() { return deviceId; } public void setDeviceId(String deviceId) { this.deviceId = deviceId; } public State getState() { return state; } public void setState(State state) { this.state = state; } public byte[] getGeometryBytes() { return geometryBytes; } public void setGeometryBytes(byte[] geometryBytes) { this.geometryBytes = geometryBytes; } public Geometry getGeometry() { return GeometryUtility.toGeometry(getGeometryBytes()); } public void setGeometry(Geometry geometry) { this.geometryBytes = GeometryUtility.toGeometryBytes(geometry); } public String getProvider() { return provider; } public void setProvider(String provider) { this.provider = provider; } public Float getAccuracy() { return accuracy; } public void setAccuracy(Float accuracy) { this.accuracy = accuracy; } public String getLocationDelta() { return locationDelta; } public void setLocationDelta(String locationDelta) { this.locationDelta = locationDelta; } public String getProvider() { return provider; } public void setProvider(String provider) { this.provider = provider; } public Float getAccuracy() { return accuracy; } public void setAccuracy(Float accuracy) { this.accuracy = accuracy; } public String getLocationDelta() { return locationDelta; } public void setLocationDelta(String locationDelta) { this.locationDelta = locationDelta; } public Event getEvent() { return event; } public void setEvent(Event event) { this.event = event; } public ObservationError getError() { return error; } public void setError(ObservationError error) { this.error = error; } public Date getLastModified() { return lastModified; } public void setLastModified(Date lastModified) { this.lastModified = lastModified; } public boolean isDirty() { return dirty; } public void setDirty(boolean dirty) { this.dirty = dirty; } public Collection<ObservationForm> getForms() { return forms; } public void setForms(Collection<ObservationForm> forms) { this.forms = forms; } public void addForms(Collection<ObservationForm> forms) { Map<Long, ObservationForm> newFormsMap = new HashMap<Long, ObservationForm>(); for (ObservationForm form : forms) { form.setObservation(this); newFormsMap.put(form.getFormId(), form); } Map<Long, ObservationForm> oldFormsMap = getFormsMap(); oldFormsMap.putAll(newFormsMap); this.forms = oldFormsMap.values(); } public Collection<Attachment> getAttachments() { return attachments; } public void setAttachments(Collection<Attachment> attachments) { this.attachments = attachments; } public ObservationImportant getImportant() { return important; } public void setImportant(ObservationImportant important) { this.important = important; } public Collection<ObservationFavorite> getFavorites() { return favorites; } public void setFavorites(Collection<ObservationFavorite> favorites) { this.favorites = favorites; } /** * A convenience method used for returning an Observation's properties in a * more useful data-structure. * * @return */ public final Map<Long, ObservationForm> getFormsMap() { Map<Long, ObservationForm> formsMap = new HashMap<>(); for (ObservationForm form : forms) { formsMap.put(form.getFormId(), form); } return formsMap; } /** * A convenience method used for returning an Observation's favorites in a * more useful data-structure. * * Map key is the userId who favorited the observation. * * @return */ public final Map<String, ObservationFavorite> getFavoritesMap() { Map<String, ObservationFavorite> favoritesMap = new HashMap<>(); for (ObservationFavorite favorite : favorites) { favoritesMap.put(favorite.getUserId(), favorite); } return favoritesMap; } public Uri getGoogleMapsUri() { DecimalFormat latLngFormat = new DecimalFormat(" String uriString = "http://maps.google.com/maps"; Geometry geometry = getGeometry(); Point point = GeometryUtils.getCentroid(geometry); uriString += String.format("?daddr=%1$s,%2$s", latLngFormat.format(point.getY()), latLngFormat.format(point.getX())); return Uri.parse(uriString); } @Override public String toString() { return ToStringBuilder.reflectionToString(this); } @Override public int compareTo(@NonNull Observation another) { return new CompareToBuilder().append(this._id, another._id).append(this.remoteId, another.remoteId).toComparison(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((_id == null) ? 0 : _id.hashCode()); result = prime * result + ((remoteId == null) ? 0 : remoteId.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Observation other = (Observation) obj; return new EqualsBuilder().append(_id, other._id).append(remoteId, other.remoteId).isEquals(); } @Override public Date getTimestamp() { return timestamp; } public void setTimestamp(Date timestamp) { this.timestamp = timestamp; } public ObservationProperty getPrimaryField() { return getField("primaryField"); } public ObservationProperty getSecondaryField() { return getField("variantField"); } public ObservationProperty getField(String name) { ObservationProperty field = null; Collection<ObservationForm> forms = getForms(); if (forms != null && forms.size() > 0) { ObservationForm form = forms.iterator().next(); JsonObject eventForm = getEventForm(form.getFormId()); if (eventForm != null) { JsonElement fieldName = eventForm.get(name); if (fieldName != null && !fieldName.isJsonNull()) { field = form.getPropertiesMap().get(fieldName.getAsString()); } } } return field; } public JsonElement getStyle() { JsonElement style = null; Collection<ObservationForm> forms = getForms(); if (forms != null && forms.size() > 0) { ObservationForm form = forms.iterator().next(); JsonObject eventForm = getEventForm(form.getFormId()); if (eventForm != null) { style = eventForm.get("style"); } } return style; } private JsonObject getEventForm(Long formId) { Iterator<JsonElement> iterator = event.getForms().iterator(); while (iterator.hasNext()) { JsonObject formJson = (JsonObject) iterator.next(); Long id = formJson.get("id").getAsLong(); if (id.equals(formId)) { return formJson; } } return null; } }
package net.bull.javamelody; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.fail; import java.io.File; import java.io.IOException; import java.util.Collections; import java.util.Date; import java.util.Locale; import java.util.Random; import java.util.Timer; import net.sf.ehcache.CacheManager; import org.junit.Test; import org.quartz.JobDetail; import org.quartz.Scheduler; import org.quartz.SchedulerException; import org.quartz.SimpleTrigger; import org.quartz.Trigger; import org.quartz.impl.StdSchedulerFactory; /** * Test unitaire de la classe Action. * @author Emeric Vernat */ public class TestAction { /** Test. */ @Test public void testValueOfIgnoreCase() { for (final Action action : Action.values()) { assertSame("same", action, Action.valueOfIgnoreCase(action.toString().toLowerCase( Locale.getDefault()))); } } /** Test. * @throws IOException e * @throws SchedulerException e */ @Test public void testExecute() throws IOException, SchedulerException { final Counter counter = new Counter("test html report", null); counter.addRequest("test1", 0, 1, false, 1000); counter.addRequest("test2", 1000, 900, false, 1000); counter.addRequest("test3", 10000, 1000, true, 10000); final Timer timer = new Timer("test", true); try { final Collector collector = new Collector("test", Collections.singletonList(counter), timer); final String counterName = counter.getName(); final String sessionId = "sessionId"; final String threadId = "threadId"; final String jobId = "jobId"; assertNotNull("message GC", Action.GC.execute(collector, counterName, sessionId, threadId, jobId)); assertNotNull("message CLEAR_COUNTER", Action.CLEAR_COUNTER.execute(collector, counterName, sessionId, threadId, jobId)); assertNotNull("message CLEAR_COUNTER", Action.CLEAR_COUNTER.execute(collector, "all", sessionId, threadId, jobId)); if (CacheManager.getInstance().getCache("test clear") == null) { CacheManager.getInstance().addCache("test clear"); } assertNotNull("message CLEAR_CACHES", Action.CLEAR_CACHES.execute(collector, counterName, sessionId, threadId, jobId)); final String heapDump1 = Action.HEAP_DUMP.execute(collector, counterName, sessionId, threadId, jobId); assertNotNull("message HEAP_DUMP", heapDump1); String heapDump2; do { heapDump2 = Action.HEAP_DUMP.execute(collector, counterName, sessionId, threadId, jobId); assertNotNull("message HEAP_DUMP", heapDump2); } while (heapDump1.equals(heapDump2)); for (final File file : Parameters.TEMPORARY_DIRECTORY.listFiles()) { if (!file.isDirectory() && file.getName().startsWith("heapdump") && !file.delete()) { file.deleteOnExit(); } } assertNotNull("message INVALIDATE_SESSIONS", Action.INVALIDATE_SESSIONS.execute( collector, counterName, sessionId, threadId, jobId)); assertNotNull("message INVALIDATE_SESSION", Action.INVALIDATE_SESSION.execute( collector, counterName, sessionId, threadId, jobId)); killThread(collector, counterName, sessionId, threadId, jobId); jobs(collector, counterName, sessionId, threadId, jobId); } finally { timer.cancel(); } } private void jobs(Collector collector, String counterName, String sessionId, String threadId, String jobId) throws IOException, SchedulerException { try { assertNotNull("message PAUSE_JOB", Action.PAUSE_JOB.execute(collector, counterName, sessionId, threadId, jobId)); } catch (final IllegalArgumentException e) { assertNotNull(e.toString(), e); } try { assertNotNull("message RESUME_JOB", Action.RESUME_JOB.execute(collector, counterName, sessionId, threadId, jobId)); } catch (final IllegalArgumentException e) { assertNotNull(e.toString(), e); } assertNotNull("message PAUSE_JOB", Action.PAUSE_JOB.execute(collector, counterName, sessionId, threadId, "all")); assertNotNull("message RESUME_JOB", Action.RESUME_JOB.execute(collector, counterName, sessionId, threadId, "all")); assertNull("message PAUSE_JOB", Action.PAUSE_JOB.execute(collector, counterName, sessionId, threadId, "nopid_noip_id")); assertNull("message RESUME_JOB", Action.RESUME_JOB.execute(collector, counterName, sessionId, threadId, "nopid_noip_id")); assertNull("message PAUSE_JOB", Action.PAUSE_JOB.execute(collector, counterName, sessionId, threadId, PID.getPID() + "_noip_id")); assertNull("message RESUME_JOB", Action.RESUME_JOB.execute(collector, counterName, sessionId, threadId, PID.getPID() + "_noip_id")); String globalJobId = PID.getPID() + '_' + Parameters.getHostAddress() + '_' + 10000; assertNotNull("message PAUSE_JOB", Action.PAUSE_JOB.execute(collector, counterName, sessionId, threadId, globalJobId)); assertNotNull("message RESUME_JOB", Action.RESUME_JOB.execute(collector, counterName, sessionId, threadId, globalJobId)); //Grab the Scheduler instance from the Factory final Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler(); try { // and start it off scheduler.start(); //Define job instance final Random random = new Random(); final JobDetail job = new JobDetail("job" + random.nextInt(), null, JobTestImpl.class); //Define a Trigger that will fire "now" final Trigger trigger = new SimpleTrigger("trigger" + random.nextInt(), null, new Date( System.currentTimeMillis() + 60000)); //Schedule the job with the trigger scheduler.scheduleJob(job, trigger); globalJobId = PID.getPID() + '_' + Parameters.getHostAddress() + '_' + job.getFullName().hashCode(); assertNotNull("message PAUSE_JOB", Action.PAUSE_JOB.execute(collector, counterName, sessionId, threadId, globalJobId)); assertNotNull("message RESUME_JOB", Action.RESUME_JOB.execute(collector, counterName, sessionId, threadId, globalJobId)); } finally { scheduler.shutdown(); } } private void killThread(Collector collector, String counterName, String sessionId, String threadId, String jobId) throws IOException { try { assertNull("message KILL_THREAD", Action.KILL_THREAD.execute(collector, counterName, sessionId, threadId, jobId)); } catch (final IllegalArgumentException e) { assertNotNull(e.toString(), e); } assertNull("message KILL_THREAD", Action.KILL_THREAD.execute(collector, counterName, sessionId, "nopid_noip_id", jobId)); assertNull("message KILL_THREAD", Action.KILL_THREAD.execute(collector, counterName, sessionId, PID.getPID() + "_noip_id", jobId)); final Thread myThread = new Thread(new Runnable() { /** {@inheritDoc} */ public void run() { try { Thread.sleep(10000); } catch (final InterruptedException e) { throw new RuntimeException(e); } } }); myThread.setName("thread test"); myThread.start(); String globalThreadId = PID.getPID() + '_' + Parameters.getHostAddress() + '_' + myThread.getId(); assertNotNull("message KILL_THREAD", Action.KILL_THREAD.execute(collector, counterName, sessionId, globalThreadId, jobId)); globalThreadId = PID.getPID() + '_' + Parameters.getHostAddress() + '_' + 10000; assertNotNull("message KILL_THREAD", Action.KILL_THREAD.execute(collector, counterName, sessionId, globalThreadId, jobId)); } /** Test. */ @Test public void testCheckSystemActionsEnabled() { System.getProperties().remove( Parameters.PARAMETER_SYSTEM_PREFIX + Parameter.SYSTEM_ACTIONS_ENABLED.getCode()); boolean systemActionsEnabled = true; try { Action.checkSystemActionsEnabled(); } catch (final Exception e) { systemActionsEnabled = false; } if (systemActionsEnabled) { fail("checkSystemActionsEnabled"); } System.setProperty(Parameters.PARAMETER_SYSTEM_PREFIX + Parameter.SYSTEM_ACTIONS_ENABLED.getCode(), "true"); systemActionsEnabled = true; try { Action.checkSystemActionsEnabled(); } catch (final Exception e) { systemActionsEnabled = false; } finally { System.setProperty(Parameters.PARAMETER_SYSTEM_PREFIX + Parameter.SYSTEM_ACTIONS_ENABLED.getCode(), "false"); } if (!systemActionsEnabled) { fail("checkSystemActionsEnabled"); } } }
package io.searchbox.client; import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import io.searchbox.annotations.JestId; import org.junit.Test; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import static junit.framework.Assert.*; /** * @author Dogukan Sonmez */ public class JestResultTest { JestResult result = new JestResult(new Gson()); @Test public void extractGetResource() { String response = "{\n" + " \"_index\" : \"twitter\",\n" + " \"_type\" : \"tweet\",\n" + " \"_id\" : \"1\", \n" + " \"_source\" : {\n" + " \"user\" : \"kimchy\",\n" + " \"postDate\" : \"2009-11-15T14:12:12\",\n" + " \"message\" : \"trying out Elastic Search\"\n" + " }\n" + "}\n"; result.setJsonMap(new Gson().fromJson(response, Map.class)); result.setPathToResult("_source"); Map<String, Object> expectedResultMap = new LinkedHashMap<String, Object>(); expectedResultMap.put("user", "kimchy"); expectedResultMap.put("postDate", "2009-11-15T14:12:12"); expectedResultMap.put("message", "trying out Elastic Search"); JsonObject actualResultMap = result.extractSource().get(0).getAsJsonObject(); assertEquals(expectedResultMap.size(), actualResultMap.entrySet().size()); for (String key : expectedResultMap.keySet()) { assertEquals(expectedResultMap.get(key).toString(), actualResultMap.get(key).getAsString()); } } @Test public void extractGetResourceWithLongId() { Long actualId = Integer.MAX_VALUE + 10l; String response = "{\n" + " \"_index\" : \"blog\",\n" + " \"_type\" : \"comment\",\n" + " \"_id\" : \"" + actualId.toString() +"\", \n" + " \"_source\" : {\n" + " \"someIdName\" : \"" + actualId.toString() + "\"\n," + " \"message\" : \"trying out Elastic Search\"\n" + " }\n" + "}\n"; result.setJsonMap(new Gson().fromJson(response, Map.class)); result.setPathToResult("_source"); Comment actual = result.getSourceAsObject(Comment.class); assertNotNull(actual); assertEquals(new Long(Integer.MAX_VALUE + 10l), actual.getSomeIdName()); } @Test public void extractUnFoundGetResource() { String response = "{\"_index\":\"twitter\",\"_type\":\"tweet\",\"_id\":\"13333\",\"exists\":false}"; result.setJsonMap(new Gson().fromJson(response, Map.class)); result.setPathToResult("_source"); JsonArray resultList = result.extractSource(); assertNotNull(resultList); assertEquals(0, resultList.size()); } @Test public void getGetSourceAsObject() { String response = "{\n" + " \"_index\" : \"twitter\",\n" + " \"_type\" : \"tweet\",\n" + " \"_id\" : \"1\", \n" + " \"_source\" : {\n" + " \"user\" : \"kimchy\",\n" + " \"postDate\" : \"2009-11-15T14:12:12\",\n" + " \"message\" : \"trying out Elastic Search\"\n" + " }\n" + "}\n"; result.setJsonMap(new Gson().fromJson(response, Map.class)); result.setPathToResult("_source"); Twitter twitter = result.getSourceAsObject(Twitter.class); assertNotNull(twitter); assertEquals("kimchy", twitter.getUser()); assertEquals("trying out Elastic Search", twitter.getMessage()); assertEquals("2009-11-15T14:12:12", twitter.getPostDate()); } @Test public void getUnFoundGetResultAsAnObject() { String response = "{\"_index\":\"twitter\",\"_type\":\"tweet\",\"_id\":\"13333\",\"exists\":false}"; result.setJsonMap(new Gson().fromJson(response, Map.class)); result.setPathToResult("_source"); assertNull(result.getSourceAsObject(Twitter.class)); } @Test public void extractUnFoundMultiGetResource() { String response = "{\n" + "\n" + "\"docs\":\n" + "[\n" + "{\"_index\":\"test\",\"_type\":\"type\",\"_id\":\"1\",\"exists\":false},\n" + "{\"_index\":\"test\",\"_type\":\"type\",\"_id\":\"2\",\"exists\":false}\n" + "]\n" + "\n" + "}\n"; result.setJsonMap(new Gson().fromJson(response, Map.class)); result.setPathToResult("docs/_source"); List<Map<String, Object>> expected = new ArrayList<Map<String, Object>>(); JsonArray actual = result.extractSource(); assertEquals(expected.size(), actual.size()); } @Test public void extractMultiGetWithSourcePartlyFound() { String response = "{\"docs\":" + "[" + "{\"_index\":\"test\",\"_type\":\"type\",\"_id\":\"2\",\"exists\":false},\n" + "{\"_index\":\"twitter\",\"_type\":\"tweet\",\"_id\":\"2\",\"_version\":2,\"exists\":true, " + "\"_source\" : {\n" + " \"user\" : \"kimchy\",\n" + " \"post_date\" : \"2009-11-15T14:12:12\",\n" + " \"message\" : \"trying out Elastic Search\"\n" + "}}" + "]}"; result.setJsonMap(new Gson().fromJson(response, Map.class)); result.setPathToResult("docs/_source"); List<Map<String, Object>> expected = new ArrayList<Map<String, Object>>(); Map<String, Object> expectedMap1 = new LinkedHashMap<String, Object>(); expectedMap1.put("user", "kimchy"); expectedMap1.put("post_date", "2009-11-15T14:12:12"); expectedMap1.put("message", "trying out Elastic Search"); expected.add(expectedMap1); JsonArray actual = result.extractSource(); assertEquals(expected.size(), actual.size()); for (int i = 0; i < expected.size(); i++) { Map<String, Object> expectedMap = expected.get(i); JsonObject actualMap = actual.get(i).getAsJsonObject(); for (String key : expectedMap.keySet()) { assertEquals(expectedMap.get(key).toString(), actualMap.get(key).getAsString()); } } } @Test public void extractMultiGetWithSource() { String response = "{\"docs\":" + "[" + "{\"_index\":\"twitter\",\"_type\":\"tweet\",\"_id\":\"1\",\"_version\":9,\"exists\":true, " + "\"_source\" : {\n" + " \"user\" : \"kimchy\",\n" + " \"post_date\" : \"2009-11-15T14:12:12\",\n" + " \"message\" : \"trying out Elastic Search\"\n" + "}}," + "{\"_index\":\"twitter\",\"_type\":\"tweet\",\"_id\":\"2\",\"_version\":2,\"exists\":true, " + "\"_source\" : {\n" + " \"user\" : \"kimchy\",\n" + " \"post_date\" : \"2009-11-15T14:12:12\",\n" + " \"message\" : \"trying out Elastic Search\"\n" + "}}" + "]}"; result.setJsonMap(new Gson().fromJson(response, Map.class)); result.setPathToResult("docs/_source"); List<Map<String, Object>> expected = new ArrayList<Map<String, Object>>(); Map<String, Object> expectedMap1 = new LinkedHashMap<String, Object>(); expectedMap1.put("user", "kimchy"); expectedMap1.put("post_date", "2009-11-15T14:12:12"); expectedMap1.put("message", "trying out Elastic Search"); Map<String, Object> expectedMap2 = new LinkedHashMap<String, Object>(); expectedMap2.put("user", "kimchy"); expectedMap2.put("post_date", "2009-11-15T14:12:12"); expectedMap2.put("message", "trying out Elastic Search"); expected.add(expectedMap1); expected.add(expectedMap2); JsonArray actual = result.extractSource(); for (int i = 0; i < expected.size(); i++) { Map<String, Object> expectedMap = expected.get(i); JsonObject actualMap = actual.get(i).getAsJsonObject(); for (String key : expectedMap.keySet()) { assertEquals(expectedMap.get(key).toString(), actualMap.get(key).getAsString()); } } } @Test public void getMultiGetSourceAsObject() { String response = "{\"docs\":" + "[" + "{\"_index\":\"twitter\",\"_type\":\"tweet\",\"_id\":\"1\",\"_version\":9,\"exists\":true, " + "\"_source\" : {\n" + " \"user\" : \"kimchy\",\n" + " \"postDate\" : \"2009-11-15T14:12:12\",\n" + " \"message\" : \"trying out Elastic Search\"\n" + "}}," + "{\"_index\":\"twitter\",\"_type\":\"tweet\",\"_id\":\"2\",\"_version\":2,\"exists\":true, " + "\"_source\" : {\n" + " \"user\" : \"dogukan\",\n" + " \"postDate\" : \"2012\",\n" + " \"message\" : \"My message\"\n" + "}}" + "]}"; result.setJsonMap(new Gson().fromJson(response, Map.class)); result.setPathToResult("docs/_source"); result.setSucceeded(true); List<Twitter> twitterList = result.getSourceAsObjectList(Twitter.class); assertEquals(2, twitterList.size()); assertEquals("kimchy", twitterList.get(0).getUser()); assertEquals("trying out Elastic Search", twitterList.get(0).getMessage()); assertEquals("2009-11-15T14:12:12", twitterList.get(0).getPostDate()); assertEquals("dogukan", twitterList.get(1).getUser()); assertEquals("My message", twitterList.get(1).getMessage()); assertEquals("2012", twitterList.get(1).getPostDate()); } @Test public void getUnFoundMultiGetSourceAsObject() { String response = "{\n" + "\n" + "\"docs\":\n" + "[\n" + "{\"_index\":\"test\",\"_type\":\"type\",\"_id\":\"1\",\"exists\":false},\n" + "{\"_index\":\"test\",\"_type\":\"type\",\"_id\":\"2\",\"exists\":false}\n" + "]\n" + "\n" + "}\n"; result.setJsonMap(new Gson().fromJson(response, Map.class)); result.setPathToResult("docs/_source"); result.setSucceeded(true); List<Twitter> twitterList = result.getSourceAsObjectList(Twitter.class); assertEquals(0, twitterList.size()); } @Test public void extractEmptySearchSource() { String response = "{\"took\":60,\"timed_out\":false,\"_shards\":{\"total\":1,\"successful\":1," + "\"failed\":0},\"hits\":{\"total\":0,\"max_score\":null,\"hits\":[]}}"; result.setJsonMap(new Gson().fromJson(response, Map.class)); result.setPathToResult("hits/hits/_source"); List<Map<String, Object>> expected = new ArrayList<Map<String, Object>>(); JsonArray actual = result.extractSource(); assertEquals(expected.size(), actual.size()); } @Test public void extractSearchSource() { String response = "{\n" + " \"_shards\":{\n" + " \"total\" : 5,\n" + " \"successful\" : 5,\n" + " \"failed\" : 0\n" + " },\n" + " \"hits\":{\n" + " \"total\" : 1,\n" + " \"hits\" : [\n" + " {\n" + " \"_index\" : \"twitter\",\n" + " \"_type\" : \"tweet\",\n" + " \"_id\" : \"1\", \n" + " \"_source\" : {\n" + " \"user\" : \"kimchy\",\n" + " \"postDate\" : \"2009-11-15T14:12:12\",\n" + " \"message\" : \"trying out Elastic Search\"\n" + " }\n" + " }\n" + " ]\n" + " }\n" + "}"; result.setJsonMap(new Gson().fromJson(response, Map.class)); result.setPathToResult("hits/hits/_source"); Map<String, Object> expectedResultMap = new LinkedHashMap<String, Object>(); expectedResultMap.put("user", "kimchy"); expectedResultMap.put("postDate", "2009-11-15T14:12:12"); expectedResultMap.put("message", "trying out Elastic Search"); JsonObject actualResultMap = result.extractSource().get(0).getAsJsonObject(); assertEquals(expectedResultMap.size() + 1, actualResultMap.entrySet().size()); for (String key : expectedResultMap.keySet()) { assertEquals(expectedResultMap.get(key).toString(), actualResultMap.get(key).getAsString()); } } @Test public void getSearchSourceAsObject() { String response = "{\n" + " \"_shards\":{\n" + " \"total\" : 5,\n" + " \"successful\" : 5,\n" + " \"failed\" : 0\n" + " },\n" + " \"hits\":{\n" + " \"total\" : 1,\n" + " \"hits\" : [\n" + " {\n" + " \"_index\" : \"twitter\",\n" + " \"_type\" : \"tweet\",\n" + " \"_id\" : \"1\", \n" + " \"_source\" : {\n" + " \"user\" : \"kimchy\",\n" + " \"postDate\" : \"2009-11-15T14:12:12\",\n" + " \"message\" : \"trying out Elastic Search\"\n" + " }\n" + " },\n" + " {\n" + " \"_index\" : \"twitter\",\n" + " \"_type\" : \"tweet\",\n" + " \"_id\" : \"1\", \n" + " \"_source\" : {\n" + " \"user\" : \"dogukan\",\n" + " \"postDate\" : \"2012\",\n" + " \"message\" : \"My Search Result\"\n" + " }\n" + " }\n" + " ]\n" + " }\n" + "}"; result.setJsonMap(new Gson().fromJson(response, Map.class)); result.setPathToResult("hits/hits/_source"); result.setSucceeded(true); List<Twitter> twitterList = result.getSourceAsObjectList(Twitter.class); assertEquals(2, twitterList.size()); assertEquals("kimchy", twitterList.get(0).getUser()); assertEquals("trying out Elastic Search", twitterList.get(0).getMessage()); assertEquals("2009-11-15T14:12:12", twitterList.get(0).getPostDate()); assertEquals("dogukan", twitterList.get(1).getUser()); assertEquals("My Search Result", twitterList.get(1).getMessage()); assertEquals("2012", twitterList.get(1).getPostDate()); } @Test public void extractIndexSource() { String response = "{\n" + " \"ok\" : true,\n" + " \"_index\" : \"twitter\",\n" + " \"_type\" : \"tweet\",\n" + " \"_id\" : \"1\"\n" + "}\n"; result.setJsonMap(new Gson().fromJson(response, Map.class)); List<Map<String, Object>> expected = new ArrayList<Map<String, Object>>(); Map<String, Object> expectedMap = new LinkedHashMap<String, Object>(); expectedMap.put("ok", true); expectedMap.put("_index", "twitter"); expectedMap.put("_type", "tweet"); expectedMap.put("_id", "1"); expected.add(expectedMap); JsonArray actual = result.extractSource(); for (int i = 0; i < expected.size(); i++) { Map<String, Object> map = expected.get(i); JsonObject actualMap = actual.get(i).getAsJsonObject(); for (String key : map.keySet()) { assertEquals(map.get(key).toString(), actualMap.get(key).getAsString()); } } } @Test public void extractCountResult() { String response = "{\n" + " \"count\" : 1,\n" + " \"_shards\" : {\n" + " \"total\" : 5,\n" + " \"successful\" : 5,\n" + " \"failed\" : 0\n" + " }\n" + "}\n"; result.setJsonMap(new Gson().fromJson(response, Map.class)); result.setPathToResult("count"); Double actual = result.extractSource().get(0).getAsDouble(); assertEquals(1.0, actual); } @Test public void getCountSourceAsObject() { String response = "{\n" + " \"count\" : 1,\n" + " \"_shards\" : {\n" + " \"total\" : 5,\n" + " \"successful\" : 5,\n" + " \"failed\" : 0\n" + " }\n" + "}\n"; result.setJsonMap(new Gson().fromJson(response, Map.class)); result.setPathToResult("count"); result.setSucceeded(true); Double count = result.getSourceAsObject(Double.class); assertEquals(1.0, count); } @Test public void getKeysWithPathToResult() { result.setPathToResult("_source"); String[] expected = {"_source"}; String[] actual = result.getKeys(); assertEquals(1, actual.length); assertEquals(expected[0], actual[0]); } @Test public void getKeysWithoutPathToResult() { assertNull(result.getKeys()); } class Twitter { String user; String postDate; String message; public String getUser() { return user; } public void setUser(String user) { this.user = user; } public String getPostDate() { return postDate; } public void setPostDate(String postDate) { this.postDate = postDate; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } } class Comment { @JestId Long someIdName; String message; public Long getSomeIdName() { return someIdName; } public void setSomeIdName(Long someIdName) { this.someIdName = someIdName; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } } }
package com.rickenbazolo.carnet.bean; import com.rickenbazolo.carnet.model.Contact; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import javax.inject.Named; /** * * @author Ricken BAZOLO */ @Named @RequestScoped public class AjouterBean extends Contact { @Inject private ContactBean bean; public AjouterBean() { initFields(); } public String ajouter() { Contact contact = new Contact(); contact.setAdresse(adresse); contact.setDatenaiss(datenaiss); contact.setEmail(email); contact.setGenre(genre); contact.setNom(nom); contact.setPrenom(prenom); contact.setSkype(skype); contact.setTelephone(telephone); bean.addContact(contact); initFields(); return (null); } private void initFields() { this.nom = ""; this.prenom = ""; this.datenaiss = ""; this.genre = "Masculin"; this.telephone = ""; this.skype = ""; this.email = ""; this.adresse = ""; } }
package org.jsimpledb.kv; import java.util.ArrayDeque; import java.util.Iterator; import java.util.List; import org.jsimpledb.kv.mvcc.AtomicKVDatabase; import org.jsimpledb.kv.mvcc.AtomicKVStore; import org.jsimpledb.util.ImplementationsReader; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Descriptor for a {@link KVDatabase} implementation. * * <p> * Instances of this class provide information about how to configure and instantiate some * technology-specific implementation of the {@link KVDatabase} and {@link AtomicKVStore} * interfaces. */ public abstract class KVImplementation { /** * Classpath XML file resource describing available {@link KVDatabase} implementations: * {@value #XML_DESCRIPTOR_RESOURCE}. * * <p> * Example: * <blockquote><pre> * &lt;kv-implementations&gt; * &lt;kv-implementation class="com.example.MyKVImplementation"/&gt; * &lt;/kv-implementations&gt; * </pre></blockquote> * * <p> * Instances must have a public default constructor. */ public static final String XML_DESCRIPTOR_RESOURCE = "META-INF/jsimpledb/kv-implementations.xml"; protected final Logger log = LoggerFactory.getLogger(this.getClass()); /** * Get the command line options supported by this implementation, suitable for display in a usage help message. * * <p> * There must be at least one option, to indicate that this implementation is to be used. * * @return array of pairs: { option, description } */ public abstract String[][] getCommandLineOptions(); /** * Get additional usage message text, if any. * * <p> * The implementation in {@link KVImplementation} returns null. * * @return usage text if any, otherwise null */ public String getUsageText() { return null; } public abstract Object parseCommandLineOptions(ArrayDeque<String> options); /** * Subclass support method for parsing out a single command line flag and argument. * If found, the {@code flag} and argument are removed from {@code options}. * * @param options command line options * @param flag command line flag taking an argument * @return flag's argument, or null if flag is not present */ protected String parseCommandLineOption(ArrayDeque<String> options, String flag) { String arg = null; for (Iterator<String> i = options.iterator(); i.hasNext(); ) { final String option = i.next(); if (option.equals(flag)) { i.remove(); if (!i.hasNext()) throw new IllegalArgumentException("`" + flag + "' missing required argument"); arg = i.next(); i.remove(); } } return arg; } /** * Subclass support method for parsing out a boolean command line flag (i.e., a flag without an argument). * If found, all instances of {@code flag} are removed from {@code options}. * * @param options command line options * @param flag command line flag taking an argument * @return whether flag is present */ protected boolean parseCommandLineFlag(ArrayDeque<String> options, String flag) { boolean result = false; for (Iterator<String> i = options.iterator(); i.hasNext(); ) { final String option = i.next(); if (option.equals(flag)) { result = true; i.remove(); } } return result; } /** * Create an {@link KVDatabase} using the specified configuration. * * @param configuration implementation configuration returned by {@link #parseCommandLineOptions parseCommandLineOptions()} * @param kvdb required {@link KVDatabase}; will be null unless {@link #requiresKVDatabase} returned true * @param kvstore required {@link AtomicKVStore}; will be null unless {@link #requiresAtomicKVStore} returned true * @return new {@link KVDatabase} instance */ public abstract KVDatabase createKVDatabase(Object configuration, KVDatabase kvdb, AtomicKVStore kvstore); /** * Create an {@link AtomicKVStore} using the specified configuration. * * <p> * The implementation in {@link KVImplementation} invokes {@link #createKVDatabase createKVDatabase()} and constructs * a {@link AtomicKVDatabase} from the result. Implementations that natively support the {@link AtomicKVDatabase} * interface should override this method. * * @param configuration implementation configuration returned by {@link #parseCommandLineOptions parseCommandLineOptions()} * @return new {@link AtomicKVStore} instance */ public AtomicKVStore createAtomicKVStore(Object configuration) { return new AtomicKVDatabase(this.createKVDatabase(configuration, null, null)); } /** * Determine whether this {@link KVDatabase} implementation requires an underlying {@link AtomicKVStore}. * If so, both implementations must be configured. * * <p> * The implementation in {@link KVImplementation} return false. * * @param configuration implementation configuration returned by {@link #parseCommandLineOptions parseCommandLineOptions()} * @return true if the implementation relies on an underlying {@link AtomicKVStore} */ public boolean requiresAtomicKVStore(Object configuration) { return false; } /** * Determine whether this {@link KVDatabase} implementation requires some other underlying {@link KVDatabase}. * If so, both implementations must be configured. * * <p> * The implementation in {@link KVImplementation} return false. * * @param configuration implementation configuration returned by {@link #parseCommandLineOptions parseCommandLineOptions()} * @return true if the implementation relies on an underlying {@link KVDatabase} */ public boolean requiresKVDatabase(Object configuration) { return false; } /** * Generate a short, human-readable description of the {@link KVDatabase} instance configured as given. * * @param configuration implementation configuration returned by {@link #parseCommandLineOptions parseCommandLineOptions()} * @return human-readable description */ public abstract String getDescription(Object configuration); /** * Find available {@link KVImplementation}s by scanning the classpath. * * <p> * This method searches the classpath for {@link KVImplementation} descriptor files and instantiates * the corresponding {@link KVImplementation}s. Example: * <blockquote><pre> * &lt;kv-implementations&gt; * &lt;kv-implementation class="com.example.MyKVImplementation"/&gt; * &lt;/kv-implementations&gt; * </pre></blockquote> * * @return {@link KVImplementation}s found on the classpath */ public static KVImplementation[] getImplementations() { final List<KVImplementation> kvs = new ImplementationsReader("kv") .findImplementations(KVImplementation.class, XML_DESCRIPTOR_RESOURCE); return kvs.toArray(new KVImplementation[kvs.size()]); } }
package org.jetel.ctl; import static org.jetel.ctl.TransformLangParserTreeConstants.JJTVARIABLEDECLARATION; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.TreeSet; import org.jetel.ctl.ASTnode.CLVFAddNode; import org.jetel.ctl.ASTnode.CLVFAnd; import org.jetel.ctl.ASTnode.CLVFArguments; import org.jetel.ctl.ASTnode.CLVFArrayAccessExpression; import org.jetel.ctl.ASTnode.CLVFAssignment; import org.jetel.ctl.ASTnode.CLVFBlock; import org.jetel.ctl.ASTnode.CLVFBreakStatement; import org.jetel.ctl.ASTnode.CLVFBreakpointNode; import org.jetel.ctl.ASTnode.CLVFCaseStatement; import org.jetel.ctl.ASTnode.CLVFComparison; import org.jetel.ctl.ASTnode.CLVFConditionalExpression; import org.jetel.ctl.ASTnode.CLVFContinueStatement; import org.jetel.ctl.ASTnode.CLVFDateField; import org.jetel.ctl.ASTnode.CLVFDeleteDictNode; import org.jetel.ctl.ASTnode.CLVFDivNode; import org.jetel.ctl.ASTnode.CLVFDoStatement; import org.jetel.ctl.ASTnode.CLVFEvalNode; import org.jetel.ctl.ASTnode.CLVFFieldAccessExpression; import org.jetel.ctl.ASTnode.CLVFForStatement; import org.jetel.ctl.ASTnode.CLVFForeachStatement; import org.jetel.ctl.ASTnode.CLVFFunctionCall; import org.jetel.ctl.ASTnode.CLVFFunctionDeclaration; import org.jetel.ctl.ASTnode.CLVFIIfNode; import org.jetel.ctl.ASTnode.CLVFIdentifier; import org.jetel.ctl.ASTnode.CLVFIfStatement; import org.jetel.ctl.ASTnode.CLVFImportSource; import org.jetel.ctl.ASTnode.CLVFInFunction; import org.jetel.ctl.ASTnode.CLVFIsNullNode; import org.jetel.ctl.ASTnode.CLVFListOfLiterals; import org.jetel.ctl.ASTnode.CLVFLiteral; import org.jetel.ctl.ASTnode.CLVFLogLevel; import org.jetel.ctl.ASTnode.CLVFLookupNode; import org.jetel.ctl.ASTnode.CLVFMemberAccessExpression; import org.jetel.ctl.ASTnode.CLVFModNode; import org.jetel.ctl.ASTnode.CLVFMulNode; import org.jetel.ctl.ASTnode.CLVFNVL2Node; import org.jetel.ctl.ASTnode.CLVFNVLNode; import org.jetel.ctl.ASTnode.CLVFOr; import org.jetel.ctl.ASTnode.CLVFParameters; import org.jetel.ctl.ASTnode.CLVFPostfixExpression; import org.jetel.ctl.ASTnode.CLVFPrintErrNode; import org.jetel.ctl.ASTnode.CLVFPrintLogNode; import org.jetel.ctl.ASTnode.CLVFPrintStackNode; import org.jetel.ctl.ASTnode.CLVFRaiseErrorNode; import org.jetel.ctl.ASTnode.CLVFReadDictNode; import org.jetel.ctl.ASTnode.CLVFReturnStatement; import org.jetel.ctl.ASTnode.CLVFSequenceNode; import org.jetel.ctl.ASTnode.CLVFStart; import org.jetel.ctl.ASTnode.CLVFStartExpression; import org.jetel.ctl.ASTnode.CLVFSubNode; import org.jetel.ctl.ASTnode.CLVFSwitchStatement; import org.jetel.ctl.ASTnode.CLVFType; import org.jetel.ctl.ASTnode.CLVFUnaryExpression; import org.jetel.ctl.ASTnode.CLVFVariableDeclaration; import org.jetel.ctl.ASTnode.CLVFWhileStatement; import org.jetel.ctl.ASTnode.CLVFWriteDictNode; import org.jetel.ctl.ASTnode.CastNode; import org.jetel.ctl.ASTnode.SimpleNode; import org.jetel.ctl.data.TLType; import org.jetel.ctl.data.TLTypePrimitive; import org.jetel.ctl.data.TLType.TLTypeList; import org.jetel.ctl.data.TLType.TLTypeMap; import org.jetel.ctl.data.TLType.TLTypeRecord; import org.jetel.ctl.data.TLType.TLTypeSymbol; import org.jetel.ctl.extensions.TLFunctionCallContext; import org.jetel.ctl.extensions.TLFunctionDescriptor; import org.jetel.metadata.DataFieldMetadata; import org.jetel.metadata.DataRecordMetadata; public class TypeChecker extends NavigatingVisitor { // functions being checked for handling private Map<String,List<CLVFFunctionDeclaration>> declaredFunctions; private TreeSet<String> functionInProgress = new TreeSet<String>(); private ProblemReporter problemReporter; private CLVFFunctionDeclaration activeFunction = null; private Map<String, List<TLFunctionDescriptor>> externalFunctions; private final HashMap<String,TLType> typeVarMapping = new HashMap<String, TLType>(); private ArrayList<TLFunctionCallContext> functionCalls = new ArrayList<TLFunctionCallContext>(); private int functionCallIndex = 0; public TypeChecker(ProblemReporter problemReporter, Map<String, List<CLVFFunctionDeclaration>> declaredFunctions, Map<String, List<TLFunctionDescriptor>> externalFunctions) { this.problemReporter = problemReporter; this.declaredFunctions = declaredFunctions; this.externalFunctions = externalFunctions; this.functionCallIndex = 0; } public void check(CLVFStart ast) { visit(ast, null); } public void check(CLVFStartExpression ast) { visit(ast, null); } @Override public Object visit(CLVFAddNode node, Object data) { super.visit(node, data); // propagate error if (!checkChildren(node)) { return data; } SimpleNode lhs = (SimpleNode) node.jjtGetChild(0); SimpleNode rhs = (SimpleNode) node.jjtGetChild(1); // (mixed) list concatenation if (lhs.getType().isList()) { if (lhs.getType().canAssign(rhs.getType())) { // list + list concatenation node.setType(lhs.getType()); return data; } // invalid concatenation node.setType(TLType.ERROR); error(node,"Operator '+' is not defined for types '" + lhs.getType().name() + "' and '" + rhs.getType().name() + "'"); return data; } // map concatenation if (lhs.getType().isMap()) { if (lhs.getType().canAssign(rhs.getType())) { node.setType(lhs.getType()); return data; } node.setType(TLType.ERROR); return data; } // string concatenation if (lhs.getType().isString() || rhs.getType().isString()) { castIfNeeded(node,0,TLTypePrimitive.STRING); castIfNeeded(node,1,TLTypePrimitive.STRING); node.setType(TLTypePrimitive.STRING); return data; } // general (mixed-type) addition TLType result = checkArithmeticOperator(lhs, rhs); if (result.isError()) { error(node, "Operator '+' is not defined for types: " + "'" + lhs.getType().name() + "' and '" + rhs.getType().name() + "'"); } else { // check if any explicit type-casting is needed castIfNeeded(node,0,result); castIfNeeded(node,1,result); } node.setType(result); return data; } @Override public Object visit(CLVFAnd node, Object data) { super.visit(node, data); TLType lhs = ((SimpleNode) node.jjtGetChild(0)).getType(); TLType rhs = ((SimpleNode) node.jjtGetChild(1)).getType(); if (!checkChildren(node)) { return data; } if (lhs.isBoolean() && rhs.isBoolean()) { node.setType(TLTypePrimitive.BOOLEAN); return data; } // any other configuration is incorrect node.setType(TLType.ERROR); error(node, "Operator '&&' is not defined for types: " + "'" + lhs.name() + "' and '" + rhs.name() + "'"); return data; } @Override public Object visit(CLVFArguments node, Object data) { super.visit(node, data); node.setType(TLType.VOID); checkChildren(node); return data; } @Override public Object visit(CLVFArrayAccessExpression node, Object data) { super.visit(node, data); if (!checkChildren(node)) { return data; } SimpleNode composite = (SimpleNode)node.jjtGetChild(0); if (composite.getType().isList()) { SimpleNode index = (SimpleNode)node.jjtGetChild(1); if (! index.getType().isInteger()) { error(index,"Cannot convert from '" + index.getType().name() + "' to '" + TLTypePrimitive.INTEGER.name() + "'"); node.setType(TLType.ERROR); return data; } node.setType(((TLTypeList)composite.getType()).getElementType()); return data; } if (composite.getType().isMap()) { // map can accept any type as its index TLTypeMap mapComposite = (TLTypeMap)composite.getType(); SimpleNode key = (SimpleNode)node.jjtGetChild(1); if (! mapComposite.getKeyType().canAssign(key.getType())) { error(key,"Cannot convert from '" + key.getType().name() + "' to " + mapComposite.getKeyType().name()); node.setType(TLType.ERROR); return data; } node.setType(mapComposite.getValueType()); return data; } error(node,"Expression is not a composite type but is resolved to '" + composite.getType().name() + "'", "Expression must be a list or map"); node.setType(TLType.ERROR); return data; } @Override public Object visit(CLVFAssignment node, Object data) { super.visit(node, data); if (!checkChildren(node)) { return data; } TLType lhs = ((SimpleNode) node.jjtGetChild(0)).getType(); TLType rhs = ((SimpleNode) node.jjtGetChild(1)).getType(); /* * Resulting type of assignment expression is LHS of assignment * Java example: * int i; * float f; * t = f = 3; // results in type error, value of assignment is the LHS (not RHS) */ if (lhs.canAssign(rhs)) { castIfNeeded(node, 1, lhs); node.setType(lhs); } else { error(node, "Type mismatch: cannot convert from " + "'" + rhs.name() + "' to '" + lhs.name() + "'"); node.setType(TLType.ERROR); } return data; } @Override public Object visit(CLVFBlock node, Object data) { super.visit(node, data); node.setType(TLType.VOID); checkChildren(node); // this will overwrite VOID with ERROR if children have errors return data; } @Override public Object visit(CLVFBreakpointNode node, Object data) { node.setType(TLType.VOID); return data; } @Override public Object visit(CLVFBreakStatement node, Object data) { node.setType(TLType.VOID); return data; } @Override public Object visit(CLVFCaseStatement node, Object data) { super.visit(node, data); node.setType(TLType.VOID); // check children for errors and possibly set error type checkChildren(node); // nothing to check for the 'default' clause if (node.isDefaultCase()) { return data; } // check case condition type if it is valid SimpleNode caseExp = (SimpleNode)node.jjtGetChild(0); if (caseExp.getType().isError()) { return data; } if (!caseExp.getType().isPrimitive()) { error(caseExp, "Illegal type of case expression '" + caseExp.getType().name() + "'"); node.setType(TLType.ERROR); } return data; } @Override public Object visit(CLVFComparison node, Object data) { super.visit(node, data); if (!checkChildren(node)) { return data; } TLType lhs = ((SimpleNode) node.jjtGetChild(0)).getType(); TLType rhs = ((SimpleNode) node.jjtGetChild(1)).getType(); switch (node.getOperator()) { case TransformLangParserConstants.REGEX_CONTAINS: case TransformLangParserConstants.REGEX_EQUAL: // regular expression operators if (lhs.isString()) { if (rhs.isString()) { node.setType(TLTypePrimitive.BOOLEAN); node.setOperationType(TLTypePrimitive.STRING); } } else { node.setType(TLType.ERROR); error(node, "Incompatible types '" + lhs.name() + "' and '" + rhs.name() + "' for regexp operator", "Both expressions must be of type 'string'"); } break; case TransformLangParserConstants.EQUAL: case TransformLangParserConstants.NON_EQUAL: case TransformLangParserConstants.GREATER_THAN: case TransformLangParserConstants.GREATER_THAN_EQUAL: case TransformLangParserConstants.LESS_THAN: case TransformLangParserConstants.LESS_THAN_EQUAL: // arithmetic operators TLType ret = checkLogicalOperator(lhs, rhs); if (ret.isError()) { node.setType(ret); error(node, "Incompatible types '" + lhs.name() + "' and '" + rhs.name() + "' for binary operator"); } else if (ret.isBoolean() && node.getOperator() != TransformLangParserConstants.EQUAL && node.getOperator() != TransformLangParserConstants.NON_EQUAL) { node.setType(TLType.ERROR); error(node, "Operator '" + TLUtils.operatorToString(node.getOperator()) + "' is not defined for types '" + lhs.name() + "' and '" + rhs.name() + "'"); } else { node.setOperationType(ret); node.setType(TLTypePrimitive.BOOLEAN); castIfNeeded(node,0,ret); castIfNeeded(node,1,ret); } break; default: throw new IllegalArgumentException("Unknown operator type: Token kind (" + node.getOperator() + ")"); } return data; } @Override public Object visit(CLVFConditionalExpression node, Object data) { super.visit(node, data); // if condition/expressions in error we propagate error if (!checkChildren(node)) { return data; } // condition must return boolean SimpleNode condition = (SimpleNode) node.jjtGetChild(0); TLType condType = condition.getType(); if (!condType.isBoolean()) { error(condition, "Type mismatch: cannot convert '" + condType.name() + "' to '" + TLTypePrimitive.BOOLEAN.name() +"'"); node.setType(TLType.ERROR); return data; } TLType thenType = ((SimpleNode) node.jjtGetChild(1)).getType(); TLType elseType = ((SimpleNode) node.jjtGetChild(2)).getType(); TLType ret = thenType.promoteWith(elseType); if (ret.isError()) { error(node, "Types of expressions mismatch: '" + thenType.name() + "' and '" + elseType.name() + "'"); } else { castIfNeeded(node,1,ret); castIfNeeded(node,2,ret); } node.setType(ret); return data; } @Override public Object visit(CLVFContinueStatement node, Object data) { node.setType(TLType.VOID); return data; } @Override public Object visit(CLVFDateField node, Object data) { // nothing to do, type calculation done in ASTBuilder return data; } @Override public Object visit(CLVFDivNode node, Object data) { super.visit(node, data); if (!checkChildren(node)) { return data; } SimpleNode lhs = (SimpleNode) node.jjtGetChild(0); SimpleNode rhs = (SimpleNode) node.jjtGetChild(1); TLType result = checkArithmeticOperator(lhs, rhs); if (result.isError()) { error(node, "Operator '/' is not defined for types: " + "'" + lhs.getType().name() + "' and '" + rhs.getType().name() + "'"); } else { castIfNeeded(node,0,result); castIfNeeded(node,1,result); } node.setType(result); return data; } @Override public Object visit(CLVFDoStatement node, Object data) { super.visit(node, data); if (!checkChildren(node)) { return data; } SimpleNode exp = (SimpleNode) node.jjtGetChild(1); if (!exp.getType().isBoolean()) { error(exp, "Cannot convert '" + exp.getType().name() + "' to '" + TLTypePrimitive.BOOLEAN.name() + "'"); node.setType(TLType.ERROR); return data; } node.setType(TLType.VOID); return data; } @Override public Object visit(CLVFFieldAccessExpression node, Object data) { // nothing to do, type calculation done in ASTBuilder return data; } @Override public Object visit(CLVFEvalNode node, Object data) { node.setType(TLType.VOID); return data; } @Override public Object visit(CLVFForStatement node, Object data) { super.visit(node, data); // let's assume the node is valid and only set error if we find one node.setType(TLType.VOID); checkChildren(node); /* * For-loop control expressions are optional so we cannot * use the jjtGetChild() to reliably distinguish between them */ SimpleNode forInit = node.getForInit(); if (forInit != null) { if (!forInit.getType().isError()) { /* * for init can be a variable declaration or an expression * in case the variable is declared, it MUST be initialized * (since there can be tests referencing it) */ if (forInit.getId() == JJTVARIABLEDECLARATION) { if (forInit.jjtGetNumChildren() < 2) { // missing initializer error(forInit,"Loop control variable must be initialized"); node.setType(TLType.ERROR); } } } } // the final-test expression must be obviously of boolean type SimpleNode forFinal = node.getForFinal(); if (forFinal != null) { if (!forFinal.getType().isError()) { if (!forFinal.getType().isBoolean()) { error(forFinal,"Cannot convert '" + forFinal.getType().name() + "' to '" + TLTypePrimitive.BOOLEAN.name() + "'"); node.setType(TLType.ERROR); } } } // node type was set to VOID already return data; } @Override public Object visit(CLVFForeachStatement node, Object data) { super.visit(node, data); // let's presume the node is OK and set the ERROR whenever we hit an error node.setType(TLType.VOID); // will set the ERROR flag if children have errors checkChildren(node); CLVFVariableDeclaration loopVar = (CLVFVariableDeclaration) node.jjtGetChild(0); TLType loopVarType = loopVar.getType(); SimpleNode iterable = (SimpleNode) node.jjtGetChild(1); // we cannot validate anything if variable or expression are in error if (loopVarType.isError() || iterable.getType().isError()) { return data; } if (iterable.getType().isList()) { TLType elemType = ((TLTypeList)iterable.getType()).getElementType(); if (!loopVarType.canAssign(elemType)) { error(iterable,"Cannot convert '" + elemType.name() + "' to '" + loopVarType.name() + "'"); node.setType(TLType.ERROR); } // type-cast will be generated when rewriting to Java code } else if (iterable.getType().isRecord()) { // we need to derive the list of fields that are safe to assign to the loopVar DataRecordMetadata meta = ((TLTypeRecord) iterable.getType()).getMetadata(); LinkedList<Integer> typeSafeFields = new LinkedList<Integer>(); for (int i = 0; i < meta.getNumFields(); i++) { TLType fieldType = TLTypePrimitive.fromCloverType(meta.getField(i)); if (loopVarType.equals(fieldType)) { typeSafeFields.add(i); } } if (typeSafeFields.size() == 0) { warn(iterable,"'" + iterable.getType().name() + "' does not contain any fields of type '" + loopVar.getType().name() + "'"); } int[] fields = new int[typeSafeFields.size()]; int i = 0; for (Integer f : typeSafeFields) { fields[i++] = f; } node.setTypeSafeFields(fields); } else { error(iterable, "Cannot iterate over the expression of type '" + iterable.getType().name() + "'", "Can only iterate over list, map or record"); node.setType(TLType.ERROR); } return data; } @Override public Object visit(CLVFFunctionCall node, Object data) { // infer types of function arguments super.visit(node, null); if (!checkChildren(node)) { return data; } CLVFFunctionDeclaration localCandidate = null; int minResult = Integer.MAX_VALUE; // infer actual parameter types CLVFArguments args = (CLVFArguments) node.jjtGetChild(0); int paramCount = args.jjtGetNumChildren(); TLType[] actual = new TLType[paramCount]; boolean[] isLiteral = new boolean[paramCount]; Object[] paramValues = new Object[paramCount]; for (int i = 0; i < actual.length; i++) { SimpleNode iNode = (SimpleNode) args.jjtGetChild(i); actual[i] = iNode.getType(); isLiteral[i] = (iNode instanceof CLVFLiteral); if (isLiteral[i]) { paramValues[i] = ((CLVFLiteral)iNode).getValue(); } } // scan local function declarations for (best) match final List<CLVFFunctionDeclaration> local = declaredFunctions.get(node.getName()); if (local != null) { // local function with such name exists for (CLVFFunctionDeclaration fd : local) { final int distance = functionDistance(actual, fd.getFormalParameters(), false); if (distance < minResult) { minResult = distance; localCandidate = fd; if (distance == 0) { // best possible match break; } } } } // if minResult==0 and we found a match we have the best possible match // thus we do not need to scan the external functions... if (localCandidate != null && minResult == 0) { node.setCallTarget(localCandidate); node.setType(localCandidate.getType()); return data; } /* * None or not-the-best match with local functions yet - scan external */ final List<TLFunctionDescriptor> external = externalFunctions.get(node.getName()); TLFunctionDescriptor extCandidate = null; if (external != null) { for (TLFunctionDescriptor fd : external) { int distance = functionDistance(actual, fd.getFormalParameters(), fd.isVarArg()); if (distance < minResult) { minResult = distance; extCandidate = fd; if (distance == 0) { // best possible match break; } } } } // if extCandidate != null we found even better match in external functions if (extCandidate != null) { node.setCallTarget(extCandidate); // All library function calls need a context TLFunctionCallContext context = new TLFunctionCallContext(); context.setParams(actual); context.setLiterals(isLiteral); context.setParamValues(paramValues); node.setFunctionCallContext(context); getFunctionCalls().add(context); context.setIndex(functionCallIndex); functionCallIndex++; boolean hasInit = extCandidate.hasInit(); if (hasInit) { context.setHasInit(true); context.setInitMethodName(extCandidate.getName() + "_init"); context.setLibClassName(node.getExternalFunction().getLibrary().getLibraryClassName()); } castIfNeeded(args,extCandidate.getFormalParameters()); if (!extCandidate.isGeneric()) { node.setType(extCandidate.getReturnType()); } else { //infer the real return type (if necessary) by binding the type variables node.setType(bindType(extCandidate.getReturnType())); } return data; } // no better external candidate found, fall back to any local function if (localCandidate != null) { node.setCallTarget(localCandidate); castIfNeeded(args,localCandidate.getFormalParameters()); node.setType(localCandidate.getType()); } else { // no match found - if we have any candidates, report with hints if (local != null && local.size() > 0) { error(node, functionErrorMessage( local.get(0).getName(), local.get(0).getFormalParameters(), actual)); } else if (external != null && external.size() > 0){ error(node, functionErrorMessage( external.get(0).getName(), external.get(0).getFormalParameters(), actual)); } else { error(node, "Function '" + node.getName() + "' is not declared"); } node.setType(TLType.ERROR); } return data; } @Override public Object visit(CLVFFunctionDeclaration node, Object data) { if (functionInProgress.contains(node.getName())) { // we are already resolving this function (inside recursive call) return data; } functionInProgress.add(node.getName()); CLVFFunctionDeclaration prevFunc = activeFunction; activeFunction = node; // we handled return type and arguments in AST builder pass // let's take care of function body now CLVFBlock body = (CLVFBlock) node.jjtGetChild(2); body.jjtAccept(this, data); functionInProgress.remove(node.getName()); activeFunction = prevFunc; return data; } @Override public Object visit(CLVFIdentifier node, Object data) { node.setType(node.getVariable().getType()); return data; } /** * Checks iif(condition,trueExp,falseExp) node the same way * as ternary conditional (?:)expression */ @Override public Object visit(CLVFIIfNode node, Object data) { super.visit(node, data); // if condition/expressions in error we propagate error if (!checkChildren(node)) { return data; } if (!isFunctionNodeValid(node,"iif",new TLType[]{TLTypePrimitive.BOOLEAN,TLType.OBJECT,TLType.OBJECT})) { return data; } TLType thenType = ((SimpleNode) node.jjtGetChild(0).jjtGetChild(1)).getType(); TLType elseType = ((SimpleNode) node.jjtGetChild(0).jjtGetChild(2)).getType(); TLType ret = thenType.promoteWith(elseType); if (ret.isError()) { error(node, "Types of expressions mismatch: '" + thenType.name() + "' and '" + elseType.name() + "'"); node.setType(TLType.ERROR); } // generate type casts if necessary castIfNeeded((SimpleNode)node.jjtGetChild(0),1,ret); castIfNeeded((SimpleNode)node.jjtGetChild(0),2,ret); node.setType(ret); return data; } @Override public Object visit(CLVFIfStatement node, Object data) { super.visit(node, data); node.setType(TLType.VOID); checkChildren(node); SimpleNode expression = (SimpleNode)node.jjtGetChild(0); if (!expression.getType().isError()) { if (!TLTypePrimitive.BOOLEAN.canAssign(expression.getType())) { error(expression,"Cannot convert '" + expression.getType().name() + "' to '" + TLTypePrimitive.BOOLEAN.name() + "'"); node.setType(TLType.ERROR); } } return data; } @Override public Object visit(CLVFImportSource node, Object data) { // store current "import context" so we can restore it after parsing this import String importFileUrl = problemReporter.getImportFileUrl(); ErrorLocation errorLocation = problemReporter.getErrorLocation(); // set new "import context", propagate error location if already defined problemReporter.setImportFileUrl(node.getSourceToImport()); problemReporter.setErrorLocation((errorLocation != null) ? errorLocation : new ErrorLocation(node.getBegin(), node.getEnd())); super.visit(node, data); node.setType(TLType.VOID); checkChildren(node); // restore current "import context" problemReporter.setImportFileUrl(importFileUrl); problemReporter.setErrorLocation(errorLocation); return data; } @Override public Object visit(CLVFInFunction node, Object data) { super.visit(node, data); // if condition/expressions in error we propagate error if (!checkChildren(node)) { return data; } CLVFArguments args = (CLVFArguments)node.jjtGetChild(0); TLType[] actual = new TLType[args.jjtGetNumChildren()]; for (int i=0; i<args.jjtGetNumChildren(); i++) { actual[i] = ((SimpleNode)args.jjtGetChild(i)).getType(); } if (actual.length != 2) { error(node,functionErrorMessage("in", new TLType[]{TLType.OBJECT,TLType.createList(null)},actual)); node.setType(TLType.ERROR); return data; } if (!actual[1].isList() && !actual[1].isMap()) { node.setType(TLType.ERROR); error(node,functionErrorMessage("in", new TLType[]{TLType.OBJECT,TLType.createList(null)},actual)); } TLType elemType = actual[1].isList() ? ((TLTypeList)actual[1]).getElementType() : ((TLTypeMap)actual[1]).getKeyType(); TLType ret = checkLogicalOperator(actual[0], elemType); if (ret.isError()) { node.setType(ret); error(node,functionErrorMessage("in", new TLType[]{TLType.OBJECT,TLType.createList(null)},actual)); } else { /* * in situation like: * int i=3; * double[] l = [ 3.1, 3.0, 4.3 ]; * boolean b = i .in. l; * * we may need to upcast the LHS to type of the list. * We cannot do upcasting of RHS, because List<Integer> is not assignable * to List<Long> although Integer is assignable to Long. */ castIfNeeded(args,0,elemType); node.setType(TLTypePrimitive.BOOLEAN); } return data; } @Override public Object visit(CLVFIsNullNode node, Object data) { super.visit(node, data); if (!checkChildren(node)) { return data; } if (!isFunctionNodeValid(node, "isnull", new TLType[]{TLTypePrimitive.OBJECT})) { return data; } node.setType(TLTypePrimitive.BOOLEAN); return data; } @Override public Object visit(CLVFListOfLiterals node, Object data) { super.visit(node, data); if (!checkChildren(node)) { return data; } /* * We iterate over values and compute the closure of all element types * Later we check this computed type against declared array type. * In case we receive TLType.ERROR as closure the expressions themselves are incompatible */ TLType closure = null; TLType lastClosure = null; for (int i=0; i<node.jjtGetNumChildren(); i++) { SimpleNode child = (SimpleNode)node.jjtGetChild(i); if ( ( closure = checkListElements(lastClosure = closure,child.getType())).isError()) { error(child,"Cannot convert from '" + child.getType().name() + "' to '" + lastClosure.name()); node.setType(TLType.ERROR); return data; } // switch (child.getId()) { // case TransformLangParserTreeConstants.JJTLITERAL: // if ( ( closure = checkListElements(lastClosure = closure,child.getType())).isError()) { // error(child,"Cannot convert from '" + child.getType().name() + "' to '" + lastClosure.name()); // node.setType(TLType.ERROR); // return data; // break; // case TransformLangParserTreeConstants.JJTUNARYEXPRESSION: // if ( ( closure = checkListElements(lastClosure = closure,child.getType())).isError()) { // error(child,"Cannot convert from '" + child.getType().name() + "' to '" + lastClosure.name()); // node.setType(TLType.ERROR); // return data; // CLVFUnaryExpression expr = (CLVFUnaryExpression)child; // if (expr.getOperator() == TransformLangParserConstants.MINUS) { // break; // // no break here on purpose: handles unary expression other than MINUS ! // default: // "Only literals and negative expressions are allowed to be in the list initializer"); // node.setType(TLType.ERROR); // return data; } // the closure is known: generate type-casts to the closure type if necessary for (int i=0; i<node.jjtGetNumChildren(); i++) { castIfNeeded(node, i, closure); } // we were able to compute the closure for all literals within the list // use it as element type for the list node.setType(TLType.createList(closure)); return data; } private TLType checkListElements(TLType closure, TLType elem) { if (closure == null) { return elem; } return closure.promoteWith(elem); } @Override public Object visit(CLVFLiteral node, Object data) { // nothing to do - type set during parsing return data; } @Override public Object visit(CLVFLogLevel node, Object data) { // nothing to do - type set during parsing return data; } @Override public Object visit(CLVFLookupNode node, Object data) { super.visit(node,data); CLVFArguments args = null; TLType[] actual = null; String opName = null; switch (node.getOperation()) { case CLVFLookupNode.OP_COUNT: opName = "count"; // no break here - key validation continues case CLVFLookupNode.OP_GET: opName = opName == null ? "get" : opName; TLType[] formal = node.getFormalParameters(); args = (CLVFArguments)node.jjtGetChild(0); actual = new TLType[args.jjtGetNumChildren()]; for (int i=0; i<actual.length; i++) { actual[i] = ((SimpleNode)args.jjtGetChild(i)).getType(); } if (formal.length != actual.length) { error(node,functionErrorMessage(opName, formal, actual)); node.setType(TLType.ERROR); return data; } for (int i=0; i<formal.length; i++) { if (! formal[i].canAssign(actual[i])) { error(node,functionErrorMessage(opName, formal, actual)); node.setType(TLType.ERROR); return data; } else { castIfNeeded(args, i, formal[i]); } } // return type already set in AST builder break; case CLVFLookupNode.OP_NEXT: opName = "next"; case CLVFLookupNode.OP_INIT: opName = opName == null ? "init" : opName; //can be flow from above case CLVFLookupNode.OP_FREE: opName = opName == null ? "free" : opName; // can be flow from above args = (CLVFArguments)node.jjtGetChild(0); if (args.jjtGetNumChildren()> 0) { actual = new TLType[args.jjtGetNumChildren()]; error(node,functionErrorMessage(opName, new TLType[0], actual)); node.setType(TLType.ERROR); return data; } // return type already set in AST builder break; } return data; } /** * Checks if field exists within metadata */ @Override public Object visit(CLVFMemberAccessExpression node, Object data) { super.visit(node, data); if (!checkChildren(node)) { return data; } TLType compositeType = ((SimpleNode)node.jjtGetChild(0)).getType(); // check if the field exists within record's metadata if (compositeType.isRecord()) { if (node.isWildcard()) { // wildcard access allows manipulation with complete record // and changes type semantics from reference to value final DataRecordMetadata metadata = ((TLTypeRecord)compositeType).getMetadata(); node.setType(TLType.forRecord(metadata,false)); } else { DataRecordMetadata metadata = ((TLTypeRecord)compositeType).getMetadata(); DataFieldMetadata field = metadata.getField(node.getName()); if (field == null) { error(node,"Field '" + node.getName() + "' does not exist in record '" + metadata.getName() + "'"); node.setType(TLType.ERROR); return data; } node.setFieldId(metadata.getFieldPosition(node.getName())); node.setType(TLTypePrimitive.fromCloverType(field)); } return data; } // anything else is an error error(node,"Argument is not a record"); node.setType(TLType.ERROR); return data; } @Override public Object visit(CLVFModNode node, Object data) { super.visit(node, data); if (!checkChildren(node)) { return data; } SimpleNode lhs = (SimpleNode) node.jjtGetChild(0); SimpleNode rhs = (SimpleNode) node.jjtGetChild(1); TLType result = checkArithmeticOperator(lhs, rhs); if (result.isError()) { error(node, "Operator '%' is not defined for types: " + "'" + lhs.getType().name() + "' and '" + rhs.getType().name() + "'"); } else { castIfNeeded(node,0,result); castIfNeeded(node,1,result); } node.setType(result); return data; } @Override public Object visit(CLVFMulNode node, Object data) { super.visit(node, data); if (!checkChildren(node)) { return data; } SimpleNode lhs = (SimpleNode) node.jjtGetChild(0); SimpleNode rhs = (SimpleNode) node.jjtGetChild(1); // general (mixed-type) multiplication TLType result = checkArithmeticOperator(lhs, rhs); if (result.isError()) { error(lhs, "Operator '*' is not defined for types: " + "'" + lhs.getType().name() + "' and '" + rhs.getType().name() + "'"); } else { /* * NOTE: * Decimal-decimal multiplication where operands have different precision/scale * is handled by BigDecimal implementation so no explicit type-casting is needed */ castIfNeeded(node,0,result); castIfNeeded(node,1,result); } node.setType(result); return data; } @Override public Object visit(CLVFNVLNode node, Object data) { super.visit(node, data); // if condition/expressions in error we propagate error if (!checkChildren(node)) { return data; } if (!isFunctionNodeValid(node,"nvl", new TLType[]{TLType.OBJECT,TLType.OBJECT})) { return data; } // argument types must match TLType thenType = ((SimpleNode) node.jjtGetChild(0).jjtGetChild(0)).getType(); TLType elseType = ((SimpleNode) node.jjtGetChild(0).jjtGetChild(1)).getType(); TLType ret = thenType.promoteWith(elseType); if (ret.isError()) { error(node, "Types of expressions mismatch: '" + thenType.name() + "' and '" + elseType.name() + "'"); node.setType(TLType.ERROR); } // generate type casts if necessary castIfNeeded((SimpleNode)node.jjtGetChild(0),0,ret); castIfNeeded((SimpleNode)node.jjtGetChild(0),1,ret); node.setType(ret); return data; } /** * We will check this similarly as for the ternary conditional expression. * Return types from NVL must be consistent */ @Override public Object visit(CLVFNVL2Node node, Object data) { super.visit(node, data); // if condition/expressions in error we propagate error if (!checkChildren(node)) { return data; } if (!isFunctionNodeValid(node,"nvl2",new TLType[]{TLType.OBJECT,TLType.OBJECT,TLType.OBJECT})) { return data; } TLType thenType = ((SimpleNode) node.jjtGetChild(0).jjtGetChild(1)).getType(); TLType elseType = ((SimpleNode) node.jjtGetChild(0).jjtGetChild(2)).getType(); TLType ret = thenType.promoteWith(elseType); if (ret.isError()) { error(node, "Types of expressions mismatch: '" + thenType.name() + "' and '" + elseType.name() + "'"); node.setType(TLType.ERROR); } // generate type casts if necessary castIfNeeded((SimpleNode)node.jjtGetChild(0),1,ret); castIfNeeded((SimpleNode)node.jjtGetChild(0),2,ret); node.setType(ret); return data; } @Override public Object visit(CLVFOr node, Object data) { super.visit(node, data); if (!checkChildren(node)) { return data; } TLType lhs = ((SimpleNode) node.jjtGetChild(0)).getType(); TLType rhs = ((SimpleNode) node.jjtGetChild(1)).getType(); if (lhs.isBoolean() && rhs.isBoolean()) { node.setType(TLTypePrimitive.BOOLEAN); return data; } // any other configuration is incorrect node.setType(TLType.ERROR); error(node, "Operator '||' is not defined for types: " + "'" + lhs.name() + "' and '" + rhs.name() + "'"); return data; } @Override public Object visit(CLVFParameters node, Object data) { super.visit(node, data); node.setType(TLType.VOID); checkChildren(node); return data; } @Override public Object visit(CLVFPostfixExpression node, Object data) { super.visit(node, data); if (!checkChildren(node)) { return data; } SimpleNode operand = (SimpleNode) node.jjtGetChild(0); /* * Postfix (as well as prefix) operator cannot be applied onto * field-access expression as we are not able to determine if it * is an input or output field. Writing (increment) to input field * would be prohibited, while reading (original value) from output * field would be prohibited as well. */ if (operand.getId() != TransformLangParserTreeConstants.JJTIDENTIFIER && operand.getId() != TransformLangParserTreeConstants.JJTMEMBERACCESSEXPRESSION) { error(node, "Illegal argument to ++/-- operator"); node.setType(TLType.ERROR); return data; } if (operand.getType().isNumeric()) { node.setType(operand.getType()); } else { error(node, "Expression does not have a numeric type"); node.setType(TLType.ERROR); } return data; } @Override public Object visit(CLVFDeleteDictNode node, Object data) { super.visit(node, data); if (!checkChildren(node)) { return data; } CLVFArguments args = (CLVFArguments) node.jjtGetChild(0); TLType[] formal = new TLType[] { TLTypePrimitive.STRING }; TLType[] actual = new TLType[args.jjtGetNumChildren()]; for (int i = 0; i < actual.length; i++) { actual[i] = ((SimpleNode) args.jjtGetChild(i)).getType(); } if (actual.length == 1) { if (formal[0].canAssign(actual[0])) { node.setType(TLType.VOID); return data; } } error(node, functionErrorMessage("delete_dict", formal, actual)); node.setType(TLType.ERROR); return data; } @Override public Object visit(CLVFReadDictNode node, Object data) { super.visit(node, data); if (!checkChildren(node)) { return data; } CLVFArguments args = (CLVFArguments) node.jjtGetChild(0); TLType[] formal = new TLType[] { TLTypePrimitive.STRING }; TLType[] actual = new TLType[args.jjtGetNumChildren()]; for (int i = 0; i < actual.length; i++) { actual[i] = ((SimpleNode) args.jjtGetChild(i)).getType(); } if (actual.length == 1) { if (formal[0].canAssign(actual[0])) { node.setType(TLTypePrimitive.STRING); return data; } } error(node, functionErrorMessage("read_dict", formal, actual)); node.setType(TLType.ERROR); return data; } @Override public Object visit(CLVFWriteDictNode node, Object data) { super.visit(node, data); if (!checkChildren(node)) { return data; } CLVFArguments args = (CLVFArguments) node.jjtGetChild(0); TLType[] formal = new TLType[] { TLTypePrimitive.STRING, TLTypePrimitive.STRING }; TLType[] actual = new TLType[args.jjtGetNumChildren()]; for (int i = 0; i < actual.length; i++) { actual[i] = ((SimpleNode) args.jjtGetChild(i)).getType(); } if (actual.length == 2) { if (formal[0].canAssign(actual[0]) && formal[1].canAssign(actual[1])) { node.setType(TLType.VOID); return data; } } error(node, functionErrorMessage("write_dict", formal, actual)); node.setType(TLType.ERROR); return data; } @Override public Object visit(CLVFPrintErrNode node, Object data) { super.visit(node, data); if (!checkChildren(node)) { return data; } CLVFArguments args = (CLVFArguments)node.jjtGetChild(0); TLType[] formal = new TLType[]{TLType.OBJECT,TLTypePrimitive.BOOLEAN}; TLType[] actual = new TLType[args.jjtGetNumChildren()]; for (int i=0; i<actual.length; i++) { actual[i] = ((SimpleNode)args.jjtGetChild(i)).getType(); } if (actual.length >= 1 && actual.length <= 2) { if (formal[0].canAssign(actual[0])) { if (actual.length > 1) { if (formal[1].canAssign(actual[1])) { node.setType(TLType.VOID); return data; } } else { node.setType(TLType.VOID); return data; } } } error(node,functionErrorMessage("print_err", formal, actual)); node.setType(TLType.ERROR); return data; } @Override public Object visit(CLVFPrintLogNode node, Object data) { super.visit(node, data); if (!checkChildren(node)) { return data; } CLVFArguments args = (CLVFArguments)node.jjtGetChild(0); // let's create a dummy log level formal parameter TLType[] formal = new TLType[] { TLType.createTypeSymbol(TransformLangParserConstants.LOGLEVEL_INFO), TLType.OBJECT }; TLType[] actual = new TLType[args.jjtGetNumChildren()]; for (int i=0; i<actual.length; i++) { actual[i] = ((SimpleNode)args.jjtGetChild(i)).getType(); } if (actual.length == 2) { // first parameter must be a log level if (actual[0].isTypeSymbol() && ((TLTypeSymbol)actual[0]).isLogLevel()) { // second parameter can be any object if (formal[1].canAssign(actual[1])) { node.setType(TLType.VOID); return data; } } } else if (actual.length == 1) { if (formal[0].canAssign(actual[0])) { // the argument can be any type node.setType(TLType.VOID); return data; } } error(node,functionErrorMessage("print_log", formal, actual)); node.setType(TLType.ERROR); return data; } @Override public Object visit(CLVFPrintStackNode node, Object data) { super.visit(node, data); // print_stack has no parameters CLVFArguments args = (CLVFArguments)node.jjtGetChild(0); if (args.jjtHasChildren()) { TLType[] actual = new TLType[args.jjtGetNumChildren()]; for (int i=0; i<actual.length; i++) { actual[i] = ((SimpleNode)args.jjtGetChild(i)).getType(); } error(node,functionErrorMessage("print_stack", new TLType[0], actual)); node.setType(TLType.ERROR); return data; } node.setType(TLType.VOID); return data; } @Override public Object visit(CLVFRaiseErrorNode node, Object data) { super.visit(node, data); if (!checkChildren(node)) { return data; } if (!isFunctionNodeValid(node, "raise_error", new TLType[]{TLTypePrimitive.STRING})) { return data; } node.setType(TLType.VOID); return data; } @Override public Object visit(CLVFReturnStatement node, Object data) { super.visit(node, data); if (!checkChildren(node)) { return data; } if (activeFunction == null) { error(node,"Misplaced return statement","Return statement can only appear inside function declaration"); node.setType(TLType.ERROR); return data; } TLType funcType = activeFunction.getType(); if (node.jjtHasChildren()) { // return statement has an expression for return value -> check it TLType retType = ((SimpleNode)node.jjtGetChild(0)).getType(); if (! funcType.canAssign(retType)) { error(node,"Can't convert from '" + retType.name() + "' to '" + funcType.name() + "'"); node.setType(TLType.ERROR); return data; } else { castIfNeeded(node,0,funcType); } node.setType(funcType); } else { // return without expression -> function must return void if (!funcType.isVoid()) { error(node, "Function must return a value of type '" + funcType.name() + "'"); node.setType(TLType.ERROR); return data; } node.setType(TLType.VOID); } return data; } @Override public Object visit(CLVFSequenceNode node, Object data) { // nothing to do return data; } @Override public Object visit(CLVFStart node, Object data) { super.visit(node, data); node.setType(TLType.VOID); checkChildren(node); return data; } @Override public Object visit(CLVFStartExpression node, Object data) { super.visit(node, data); node.setType(((SimpleNode)node.jjtGetChild(0)).getType()); return data; } @Override public Object visit(CLVFSubNode node, Object data) { super.visit(node, data); // propagate error if (!checkChildren(node)) { return data; } SimpleNode lhs = (SimpleNode) node.jjtGetChild(0); SimpleNode rhs = (SimpleNode) node.jjtGetChild(1); // numeric addition TLType result = checkArithmeticOperator(lhs, rhs); if (result.isError()) { error(node, "Operator '-' is not defined for types: " + "'" + lhs.getType().name() + "' and '" + rhs.getType().name() + "'"); } else { castIfNeeded(node,0,result); castIfNeeded(node,1,result); } node.setType(result); return data; } @Override public Object visit(CLVFSwitchStatement node, Object data) { super.visit(node, data); node.setType(TLType.VOID); checkChildren(node); // if the switch expression is in error, we can't check further final TLType switchType = ((SimpleNode)node.jjtGetChild(0)).getType(); if (switchType.isError()) { return data; } if (!switchType.isPrimitive()) { error((SimpleNode)node.jjtGetChild(0),"Illegal type of switch expression '" + switchType.name() + "'"); node.setType(TLType.ERROR); return data; } // we visit each case statement separately and check its expression type for (int i=1; i<node.jjtGetNumChildren(); i++) { SimpleNode child = (SimpleNode)node.jjtGetChild(i); if (child.getId() != TransformLangParserTreeConstants.JJTCASESTATEMENT) { continue; } final CLVFCaseStatement caseStm = (CLVFCaseStatement)child; // nothing to check for 'default' statement if (caseStm.isDefaultCase()) { continue; } // check case expression type if it is not in error TLType caseType = ((SimpleNode)caseStm.jjtGetChild(0)).getType(); if (caseType.isError()) { continue; } if (!switchType.canAssign(caseType)) { error((SimpleNode)caseStm.jjtGetChild(0),"Cannot convert from '" + caseType.name() + "' to '" + switchType.name() + "'"); node.setType(TLType.ERROR); } else { castIfNeeded(caseStm,0,switchType); } } // node type was set to void already (or contains error) return data; } @Override public Object visit(CLVFType node, Object data) { // nothing to do return data; } @Override public Object visit(CLVFWhileStatement node, Object data) { super.visit(node, data); node.setType(TLType.VOID); checkChildren(node); SimpleNode expr = (SimpleNode)node.jjtGetChild(0); if (expr.getType().isError()) { return data; } if (! expr.getType().isBoolean()) { error(expr,"Cannot convert from '" + expr.getType().name() + "' to '" + TLTypePrimitive.BOOLEAN.name() + "'"); } return data; } @Override public Object visit(CLVFUnaryExpression node, Object data) { super.visit(node, data); if (!checkChildren(node)) { return data; } SimpleNode operand = (SimpleNode) node.jjtGetChild(0); switch (node.getOperator()) { case TransformLangParserConstants.INCR: case TransformLangParserConstants.DECR: /* * Postfix (as well as prefix) operator cannot be applied onto * field-access expression as we are not able to determine if it * is an input or output field. Writing (increment) to input field * would be prohibited, while reading (original value) from output * field would be prohibited as well. */ if (operand.getId() != TransformLangParserTreeConstants.JJTIDENTIFIER && operand.getId() != TransformLangParserTreeConstants.JJTMEMBERACCESSEXPRESSION) { error(node, "Illegal argument to ++/-- operator"); node.setType(TLType.ERROR); return data; } case TransformLangParserConstants.MINUS: if (operand.getType().isNumeric()) { node.setType(operand.getType()); } else { error(node, "Expression does not have a numeric type"); node.setType(TLType.ERROR); } break; case TransformLangParserConstants.NOT: if (TLTypePrimitive.BOOLEAN.canAssign(operand.getType())) { node.setType(TLTypePrimitive.BOOLEAN); } else { error(node, "Operator '!' is not defined for type '" + operand.getType().name() + "'"); node.setType(TLType.ERROR); } break; default: error(node, "Unknown prefix operator (" + node.getOperator() + ")"); throw new IllegalArgumentException("Unknown prefix operator (" + node.getOperator() + ")"); } return data; } @Override public Object visit(CLVFVariableDeclaration node, Object data) { super.visit(node, data); if (node.jjtGetNumChildren() < 2) { // no initializer - no work to do return data; } // check if initializer type matches the variable type TLType lhs = node.getType(); TLType rhs = ((SimpleNode) node.jjtGetChild(1)).getType(); // initializer is in error -> can't check anything further if (rhs.isError()) { node.setType(TLType.ERROR); return data; } else { castIfNeeded(node,1,lhs); } // check if initializer return type matches declared variable type if (!lhs.canAssign(rhs)) { error(node, "Type mismatch: cannot convert from " + "'" + rhs.name() + "' to '" + lhs.name() + "'"); } return data; } /** * Generates node representing a type cast operation. * This is only necessary for decimal and string types as Java will handle * primitive type casts for us. * * @param parent parent of the node to wrap into cast node * @param index index of the node to wrap * @param toType target type for cast */ private void castIfNeeded(SimpleNode parent, int index, TLType toType) { final SimpleNode child = (SimpleNode)parent.jjtGetChild(index); // do not generate type case for identical types or null literal if (child.getType().equals(toType) || child.getType().isNull()) { return; } // do not generate type case if the target type is generic record (coming from CTL function) if (toType.isRecord() && ((TLTypeRecord)toType).getMetadata() == null) { return; } final CastNode c = new CastNode(CAST_NODE_ID,child.getType(),toType); c.jjtAddChild(child, 0); c.jjtSetParent(parent); parent.jjtAddChild(c, index); } /** * Specialization of {@link #castIfNeeded(SimpleNode, int, TLType)} for * function call node parameters * @param node * @param formalParameters * @param varArg */ private void castIfNeeded(CLVFArguments node , TLType[] formal) { int i=0; while (i < formal.length) { // do not cast parameterized types or type symbols if (formal[i].isParameterized() || formal[i].isTypeSymbol()) { i++; continue; } castIfNeeded(node,i,formal[i]); i++; } if (formal.length == node.jjtGetNumChildren()) { return; } // process possible variable arguments final TLType varArgType = formal[formal.length-1]; // no need to cast when parameterized if (! varArgType.isParameterized()) { while (i < node.jjtGetNumChildren()) { castIfNeeded(node,i,varArgType); i++; } } } /** * Iterates over children types for errors and propagates the error on node * * @param node * to check * @return true when children are OK, false otherwise */ private boolean checkChildren(SimpleNode node) { for (int i = 0; i < node.jjtGetNumChildren(); i++) { TLType type = ((SimpleNode) node.jjtGetChild(i)).getType(); if (type.isError()) { node.setType(TLType.ERROR); break; } } // the node type can still be null - can't use .isError() return node.getType() != TLType.ERROR; } private TLType checkLogicalOperator(TLType lhs, TLType rhs) { if (lhs.isString()) { if (rhs.isString()) { return TLTypePrimitive.STRING; } return TLType.ERROR; } if (lhs.isDate()) { if (rhs.isDate()) { return TLTypePrimitive.DATETIME; } return TLType.ERROR; } if (lhs.isBoolean()) { if (rhs.isBoolean()) { return TLTypePrimitive.BOOLEAN; } return TLType.ERROR; } if (lhs.isNumeric()) { if (rhs.isNumeric()) { return lhs.promoteWith(rhs); } return TLType.ERROR; } return TLType.ERROR; } private boolean isBindingValid(TLType formal, TLType actual) { if (!formal.isParameterized()) { return true; } if (formal.isTypeVariable()) { TLType bound = typeVarMapping.get(formal.name()); if (bound == null) { // formal is a type variable without binding: bind it to actual typeVarMapping.put(formal.name(),actual); return true; } else if (bound.equals(actual)) { // existing equivalent binding found: ok return true; } } else if (formal.isList()) { return isBindingValid(((TLTypeList)formal).getElementType(), ((TLTypeList)actual).getElementType()); } else if (formal.isMap()) { TLTypeMap f = (TLTypeMap)formal; TLTypeMap a = (TLTypeMap)actual; return isBindingValid(f.getKeyType(), a.getKeyType()) && isBindingValid(f.getValueType(), a.getValueType()); } return false; } private int functionDistance(TLType[] actual, TLType[] formal, boolean allowVarArg) { // get ready to check type variable bindings typeVarMapping.clear(); if (actual.length < formal.length) { // completely incorrect number of parameters return Integer.MAX_VALUE; } if (formal.length == 0) { return actual.length == 0 ? 0 : Integer.MAX_VALUE; } // here: actual.length >= formal.length, both > 0 int result = 0; int sum = 0; int i = 0; while (i < formal.length) { result = TLType.distance(actual[i], formal[i]); if (result == Integer.MAX_VALUE) { return result; } if (!isBindingValid(formal[i], actual[i])) { return Integer.MAX_VALUE; } // valid type conversion and no colliding bindings - let's continue sum += result; i++; } // the same number of arguments and everything was matched if (formal.length == actual.length) { return sum; } // actual.length > formal.length: process with varArgs if (allowVarArg) { // here: process possible varArgs, case: actual.length > formal.length final TLType varArgType = formal[formal.length-1]; // penalize variable argument variants to so that non-vararg are chosen first sum++; while (i < actual.length) { result = TLType.distance(actual[i], varArgType); if (result == Integer.MAX_VALUE) { return result; } // no need to check for binding here, because the var-arg argument can't change // the binding. we would have found it already with the last non-vararg argument sum += result; i++; } return sum; } // actual.length > formal.length, but varArg is false: error return Integer.MAX_VALUE; } private TLType bindType(TLType returnType) { if (! returnType.isParameterized()) { return returnType; } // if the return type is type variable itself - return it's mapping if (returnType.isTypeVariable()) { return typeVarMapping.get(returnType.name()); } if (returnType.isList()) { return TLType.createList(bindType(((TLTypeList)returnType).getElementType())); } // if map or list, return corresponding type with correct binding if (returnType.isMap()) { TLType keyType = bindType(((TLTypeMap)returnType).getKeyType()); TLType valueType = bindType(((TLTypeMap)returnType).getValueType()); return TLType.createMap(keyType,valueType); } throw new IllegalArgumentException("Unreachable code"); } private String functionErrorMessage(String name, TLType[] formal, TLType[] actual) { StringBuffer msg = new StringBuffer("Function ").append(name).append("("); for (int i = 0; i < formal.length; i++) { msg.append(formal[i].name()); if (i < formal.length - 1) { msg.append(','); } } msg.append(") is not applicable for the arguments ("); for (int i = 0; i < actual.length; i++) { msg.append(actual[i].name()); if (i < actual.length - 1) { msg.append(','); } } msg.append(')'); return msg.toString(); } private TLType checkArithmeticOperator(SimpleNode lhs, SimpleNode rhs) { if (lhs.getType().isNumeric()) { if (rhs.getType().isNumeric()) { return lhs.getType().promoteWith(rhs.getType()); } } return TLType.ERROR; } private boolean isFunctionNodeValid(SimpleNode node, String name, TLType[] formal) { SimpleNode args = (SimpleNode)node.jjtGetChild(0); TLType[] actual = new TLType[args.jjtGetNumChildren()]; for (int i = 0; i<args.jjtGetNumChildren(); i++) { actual[i] = ((SimpleNode)args.jjtGetChild(i)).getType(); } if (formal.length != actual.length) { error(node,functionErrorMessage(name, formal, actual)); node.setType(TLType.ERROR); return false; } for (int i=0; i<formal.length; i++) { if (!formal[i].canAssign(actual[i])) { error(node,functionErrorMessage(name, formal,actual)); node.setType(TLType.ERROR); return false; } } return true; } private void error(SimpleNode node, String error) { problemReporter.error(node.getBegin(), node.getEnd(), error, null); } private void error(SimpleNode node, String error, String hint) { problemReporter.error(node.getBegin(), node.getEnd(), error, hint); } private void warn(SimpleNode node, String error) { problemReporter.warn(node.getBegin(), node.getEnd(), error, null); } /** * @return the functionCalls */ public ArrayList<TLFunctionCallContext> getFunctionCalls() { return functionCalls; } }
package org.jetel.ctl.data; import java.io.Serializable; import java.lang.reflect.GenericArrayType; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.math.BigDecimal; import java.util.Date; import java.util.List; import java.util.Map; import org.jetel.ctl.TLUtils; import org.jetel.ctl.TransformLangParserConstants; import org.jetel.data.DataRecord; import org.jetel.metadata.DataRecordMetadata; import org.jetel.util.EqualsUtil; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; @SuppressWarnings("serial") @SuppressFBWarnings("SE_NO_SERIALVERSIONID") public abstract class TLType implements Serializable { public static final TLTypeVoid VOID = new TLTypeVoid(); public static final TLTypeNull NULL = new TLTypeNull(); public static final TLTypeError ERROR = new TLTypeError(); public static final TLTypeByteArray BYTEARRAY = new TLTypeByteArray(); public static final TLTypeRecord RECORD = new TLTypeRecord(null); // special type that can hold any value-type, used only for CTL internal functions and lookup params public static final TLTypeObject OBJECT = new TLTypeObject(); // special type that can hold any value-type, used only for missing metadata definitions public static final TLTypeUnknown UNKNOWN = new TLTypeUnknown(); /** * Human-readable name for this type. Used for error reporting and messages * as opposed to toString(). * @return */ public abstract String name(); /** * Returns 'least common multiple' for this and other types. * @param otherType * @return */ public abstract TLType promoteWith(TLType otherType); public abstract boolean isNumeric(); @Override public String toString() { return name(); } /** * Tests assignment compatibility of this type with the other type. * @param otherType * @return */ public boolean canAssign(TLType otherType) { return otherType == TLType.NULL || otherType == TLType.UNKNOWN || this.promoteWith(otherType).equals(this); } public static final class TLTypeObject extends TLType { TLTypeObject() { // do not instantiate me, use constant above } @Override public TLType promoteWith(TLType otherType) { if (otherType == TLType.ERROR) { return otherType; } if (otherType == TLType.VOID) { return TLType.ERROR; } return this; } @Override public boolean isNumeric() { return false; } @Override public String name() { return "object"; } } public static final class TLTypeUnknown extends TLType { @Override public TLType promoteWith(TLType otherType) { if (otherType == TLType.VOID) { return TLType.ERROR; } return otherType; } @Override public boolean isNumeric() { return true; } @Override public String name() { return "unknown"; } @Override public boolean canAssign(TLType otherType) { return true; } } public static final class TLTypeVoid extends TLType { TLTypeVoid() { // do not instantiate me, use constant above } @Override public String name() { return "void"; } @Override public boolean isNumeric() { return false; } @Override public TLType promoteWith(TLType otherType) { if (otherType == TLType.VOID) { return TLType.VOID; } return TLType.ERROR; } } public static final class TLTypeNull extends TLType { TLTypeNull() { // do not instantiate me, use constant } @Override public String name() { return "null"; } @Override public boolean isNumeric() { return false; } @Override public TLType promoteWith(TLType otherType) { return otherType; } } public static final class TLTypeError extends TLType { private TLTypeError() { // do not instantiate me, use constant } @Override public String name() { return "error"; } @Override public boolean isNumeric() { return false; } @Override public TLType promoteWith(TLType otherType) { return this; } } public static final class TLTypeList extends TLType { private TLType elementType; private TLTypeList(TLType elementType) { this.elementType = elementType; } public TLType getElementType() { return elementType; } @Override public String name() { return (elementType ==null ? "?" : elementType.toString() ) + "[]"; } @Override public boolean isNumeric() { return false; } @Override public boolean isParameterized() { return elementType.isParameterized(); } @Override public TLType promoteWith(TLType otherType) { if (otherType.isList()) { if (this.equals(otherType)) { return this; } } return TLType.ERROR; } @Override public int hashCode() { final int prime = 37; int result = 1; result = prime * result + ((elementType == null) ? 0 : elementType.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof TLTypeList)) return false; final TLTypeList other = (TLTypeList) obj; if (elementType == null) { if (other.elementType != null) return false; } else if (!elementType.equals(other.elementType)) return false; return true; } } public static TLTypeList createList(TLType elemType) { return new TLTypeList(elemType); } public static final class TLTypeRecord extends TLType { private final DataRecordMetadata metadata; private TLTypeRecord(DataRecordMetadata metadata) { this.metadata = metadata; } @Override public String name() { String ret = "record"; return metadata != null ? ret + "(" + metadata.getName() + ")" : ret; } public DataRecordMetadata getMetadata() { return metadata; } @Override public boolean isNumeric() { return false; } @Override public TLType promoteWith(TLType otherType) { return equals(otherType) ? this : TLType.ERROR; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((metadata == null) ? 0 : metadata.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof TLTypeRecord)) { return false; } final TLTypeRecord other = (TLTypeRecord) obj; if (metadata == null) { if (other.metadata != null) { return false; } } else if (!TLUtils.equals(metadata, other.metadata)) { return false; } return true; } } public static final class TLTypeMap extends TLType { private TLType keyType; private TLType valueType; private TLTypeMap(TLType key, TLType value) { this.keyType = key; this.valueType = value; } public TLType getKeyType() { return keyType; } public TLType getValueType() { return valueType; } @Override public String name() { /*System.out.println("zzzzzzzzzzzzzzzzzz"); System.out.println("map["); System.out.println(keyType == null ? "?" : keyType.name()); System.out.println(","); System.out.println(valueType == null ? "?" : valueType.name()); System.out.println("]"); System.out.println("map[" + (keyType == null ? "?" : keyType.name()) + "," + (valueType == null ? "?" : valueType.name()) + "]");*/ return "map[" + (keyType == null ? "?" : keyType.name()) + "," + (valueType == null ? "?" : valueType.name()) + "]"; } @Override public boolean isNumeric() { return false; } @Override public boolean isParameterized() { return keyType.isParameterized() || valueType.isParameterized(); } @Override public TLType promoteWith(TLType otherType) { return this.equals(otherType) ? this : TLType.ERROR; } @Override public int hashCode() { final int prime = 43; int result = 1; result = prime * result + ((keyType == null) ? 0 : keyType.hashCode()); result = prime * result + ((valueType == null) ? 0 : valueType.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof TLTypeMap)) return false; final TLTypeMap other = (TLTypeMap) obj; if (keyType == null) { if (other.keyType != null) return false; } else if (!keyType.equals(other.keyType)) return false; if (valueType == null) { if (other.valueType != null) return false; } else if (!valueType.equals(other.valueType)) return false; return true; } } public static TLTypeMap createMap(TLType key, TLType value) { return new TLTypeMap(key,value); } public static final TLTypeRecord forRecord(DataRecordMetadata meta) { return new TLTypeRecord(meta); } public static final class TLTypeByteArray extends TLType { private TLTypeByteArray() { } @Override public String name() { return "byte"; } @Override public boolean isNumeric() { return false; } @Override public TLType promoteWith(TLType otherType) { if (otherType == TLType.BYTEARRAY) { return this; } if (otherType.isNull()) { return this; } return TLType.ERROR; } } public abstract static class TLTypeSymbol extends TLType { @Override public boolean isNumeric() { return false; } public abstract boolean isLogLevel(); public abstract boolean isDateField(); public abstract Object getSymbol(); @Override public TLType promoteWith(TLType otherType) { return TLType.ERROR; } } public static final class TLDateField extends TLTypeSymbol { private final DateFieldEnum symbol; public TLDateField(DateFieldEnum symbol) { this.symbol = symbol; } @Override public String name() { return "timeunit"; } @Override public Object getSymbol() { return symbol; } @Override public boolean isLogLevel() { return false; } @Override public boolean isDateField() { return true; } @Override public boolean canAssign(TLType otherType) { return otherType instanceof TLDateField; } @Override public int hashCode() { final int prime = 1039; int result = 1; result = prime * result + ((symbol == null) ? 0 : symbol.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof TLDateField)) return false; final TLDateField other = (TLDateField) obj; if (symbol == null) { if (other.symbol != null) return false; } else if (!symbol.equals(other.symbol)) return false; return true; } } public static final class TLLogLevel extends TLTypeSymbol { private LogLevelEnum symbol; public TLLogLevel(LogLevelEnum symbol ) { this.symbol = symbol; } @Override public LogLevelEnum getSymbol() { return symbol; } @Override public String name() { return "loglevel"; } @Override public boolean isLogLevel() { return true; } @Override public boolean isDateField() { return false; } @Override public boolean canAssign(TLType otherType) { return otherType instanceof TLLogLevel; } @Override public int hashCode() { final int prime = 1031; int result = 1; result = prime * result + ((symbol == null) ? 0 : symbol.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof TLLogLevel)) { return false; } final TLLogLevel other = (TLLogLevel) obj; return EqualsUtil.areEqual(symbol, other.symbol); } } public static TLTypeSymbol createTypeSymbol(int symbol) { switch (symbol){ case TransformLangParserConstants.DAY: case TransformLangParserConstants.MONTH: case TransformLangParserConstants.WEEK: case TransformLangParserConstants.YEAR: case TransformLangParserConstants.HOUR: case TransformLangParserConstants.MINUTE: case TransformLangParserConstants.SECOND: case TransformLangParserConstants.MILLISEC: return new TLDateField(DateFieldEnum.fromToken(symbol)); case TransformLangParserConstants.LOGLEVEL_DEBUG: case TransformLangParserConstants.LOGLEVEL_ERROR: case TransformLangParserConstants.LOGLEVEL_FATAL: case TransformLangParserConstants.LOGLEVEL_INFO: case TransformLangParserConstants.LOGLEVEL_WARN: case TransformLangParserConstants.LOGLEVEL_TRACE: return new TLLogLevel(LogLevelEnum.fromToken(symbol)); default: throw new IllegalArgumentException("Illegal type symbol (" + symbol + ")"); } } /** * Type representing Java type variables. * Exists only in types describing external Java functions from CTL libraries. * Is replaced in TypeChecker for actual types in function call. */ public static final class TLTypeVariable extends TLType { private final String name; public TLTypeVariable(String name) { this.name = name; } @Override public boolean isNumeric() { return false; } @Override public String name() { return name; } @Override public TLType promoteWith(TLType otherType) { return TLType.ERROR; } @Override public boolean isParameterized() { return true; } } public static final TLTypeVariable typeVariable(String name) { return new TLTypeVariable(name); } public boolean isDate() { return this == TLTypePrimitive.DATETIME; } public boolean isInteger() { return this == TLTypePrimitive.INTEGER; } public boolean isLong() { return this == TLTypePrimitive.LONG; } public boolean isDouble() { return this == TLTypePrimitive.DOUBLE; } public boolean isDecimal() { return this == TLTypePrimitive.DECIMAL; } public boolean isBoolean() { return this == TLTypePrimitive.BOOLEAN; } public boolean isString() { return this == TLTypePrimitive.STRING; } public boolean isRecord() { return (this instanceof TLTypeRecord); } public boolean isByteArray() { return (this instanceof TLTypeByteArray); } public boolean isPrimitive() { return false; } public boolean isTypeSymbol() { return (this instanceof TLTypeSymbol); } public boolean isMap() { return (this instanceof TLTypeMap); } public boolean isList() { return (this instanceof TLTypeList); } public boolean isIterable() { return isList() || isMap() || isRecord(); } public boolean isValueType() { return this != TLType.VOID && this != TLType.ERROR && !isTypeSymbol(); } public boolean isError() { return (this instanceof TLTypeError); } public boolean isVoid() { return this == TLType.VOID; } public boolean isNull() { return this ==TLType.NULL; } public boolean isObject() { return this == TLType.OBJECT; } public boolean isUnknown() { return this == TLType.UNKNOWN; } public boolean isTypeVariable() { return this instanceof TLTypeVariable; } /** * @return true when type is or contains a TypeVariable as its element type */ public boolean isParameterized() { return false; } public static TLType fromJavaType(Class<?> type) throws IllegalArgumentException { if (byte[].class.equals(type) || byte.class.equals(type) || Byte.class.equals(type)) { return TLTypePrimitive.BYTEARRAY; } if (int.class.equals(type) || Integer.class.equals(type)) { return TLTypePrimitive.INTEGER; } if (long.class.equals(type) || Long.class.equals(type)) { return TLTypePrimitive.LONG; } if (double.class.equals(type) || Double.class.equals(type)) { return TLTypePrimitive.DOUBLE; } if (BigDecimal.class.equals(type)) { return TLTypePrimitive.DECIMAL; } if (boolean.class.equals(type) || Boolean.class.equals(type)) { return TLTypePrimitive.BOOLEAN; } if (Date.class.equals(type)) { return TLTypePrimitive.DATETIME; } if (String.class.equals(type)) { return TLTypePrimitive.STRING; } if (List.class.isAssignableFrom(type)) { throw new IllegalArgumentException("List cannot be created by fromJavaType(Class)"); } if (Map.class.isAssignableFrom(type)) { throw new IllegalArgumentException("Map cannot be created by fromJavaType(Class)"); } if (void.class.equals(type)) { return TLTypePrimitive.VOID; } if (DataRecord.class.isAssignableFrom(type)) { return TLType.RECORD; } throw new IllegalArgumentException("Type is not representable in CTL: " + type.getName() ); } public static final TLType fromJavaType(Type toConvert) { if (toConvert instanceof TypeVariable) { // type variable return TLType.typeVariable(((TypeVariable<?>)toConvert).getName()); } else if (toConvert instanceof ParameterizedType) { // parameterized: list or map ParameterizedType paramType = (ParameterizedType)toConvert; final Type[] params = paramType.getActualTypeArguments(); Class<?> rawType = (Class<?>)paramType.getRawType(); if (List.class.equals(rawType)) { return TLType.createList(fromJavaType(params[0])); } else if (Map.class.equals(rawType)) { // extract key and value types from parameterized map // map must be parameterized. if not, the method should be declared with type variables return TLType.createMap(fromJavaType(params[0]),fromJavaType(params[1])); } else { throw new IllegalArgumentException("Unsupported parameterized type: " + rawType.getName()); } } else if (toConvert instanceof GenericArrayType) { return TLType.fromJavaType(((GenericArrayType)toConvert).getGenericComponentType()); }else if (toConvert instanceof Class) { // non-generic parameter (possibly parameterized) Class<?> rawType = (Class<?>)toConvert; if (rawType.isArray()) { // we will receive this for var-arg functions // so we will convert it into a single paramter of array-element type return TLType.fromJavaType(rawType.getComponentType()); } else if (rawType.isEnum()) { // we will receive this for functions accepting type symbols (date fields, log levels, etc) if (DateFieldEnum.class.equals(rawType)) { // function accepts date field symbols return TLType.createTypeSymbol(TransformLangParserConstants.YEAR); } else if (LogLevelEnum.class.equals(rawType)) { return TLType.createTypeSymbol(TransformLangParserConstants.LOGLEVEL_INFO); } } else if (DataRecord.class.equals(rawType)) { return TLType.RECORD; } else { return TLType.fromJavaType(rawType); } } throw new IllegalArgumentException("Unsupported type to convert: '" + toConvert); } public static TLType[] fromJavaType(Class<?>[] types) { final TLType[] ret = new TLType[types.length]; for (int i=0; i<types.length; i++) { ret[i] = fromJavaType(types[i]); } return ret; } public static TLType[] fromJavaObjects(Object[] objects) { final TLType[] ret = new TLType[objects.length]; for (int i = 0; i < objects.length; i++) { ret[i] = fromJavaType(objects[i].getClass()); } return ret; } public static int distance(TLType from, TLType to) { if (from.isInteger()) { return to.isInteger() ? 0 : to.isLong() ? 1 : to.isDouble() ? 2 : to.isDecimal() ? 3 : to.isTypeVariable() ? 10 : Integer.MAX_VALUE; } if (from.isLong()) { return to.isLong() ? 0 : to.isDouble() ? 1 : to.isDecimal() ? 2 : to.isTypeVariable() ? 10 : Integer.MAX_VALUE; } if (from.isDouble()) { return to.isDouble() ? 0 : to.isDecimal() ? 1 : to.isTypeVariable() ? 10 : Integer.MAX_VALUE; } if (from.isDecimal()) { return to.isDecimal() ? 0 : to.isTypeVariable() ? 10 : Integer.MAX_VALUE; } if (from.isString()) { return to.isString() ? 0 : to.isTypeVariable() ? 10 : Integer.MAX_VALUE; } if (from.isBoolean()) { return to.isBoolean() ? 0 : to.isTypeVariable() ? 10 : Integer.MAX_VALUE; } if (from.isDate()) { return to.isDate() ? 0 : to.isTypeVariable() ? 10 : Integer.MAX_VALUE; } if (from.isRecord()) { if (to.isRecord()) { // this handles built-in functions where arguments have metadata set to null // as they work with *any* record TLTypeRecord toRecord = (TLTypeRecord)to; if (toRecord.getMetadata() == null) { return 1; } else { return from.equals(to) ? 0 : Integer.MAX_VALUE; } } else if (to.isTypeVariable()) { return 10; } return Integer.MAX_VALUE; } if (from.isList()) { if (to.isList()) { // this handles built-in functions handling generic lists (with any element type) TLTypeList toList = (TLTypeList)to; if (toList.getElementType().isTypeVariable()) { return 10; } else { return from.equals(to) ? 0 : Integer.MAX_VALUE; } } return Integer.MAX_VALUE; } if (from.isMap()) { if (to.isMap()) { // this handles built-in functions handling generic maps (having any element type) TLTypeMap toMap = (TLTypeMap)to; if (toMap.getKeyType().isTypeVariable() && toMap.getValueType().isTypeVariable()) { return 10; } else { return from.equals(to) ? 0 : Integer.MAX_VALUE; } } return Integer.MAX_VALUE; } if (from.isNull()) { if (to.isVoid()) { // should not happen return Integer.MAX_VALUE; } return 0; } if (from.isVoid()) { return Integer.MAX_VALUE; } if (from.isTypeSymbol()) { if (from.canAssign(to)) { return 0; } return Integer.MAX_VALUE; } if (from.isByteArray()) { return to.isByteArray() ? 0 : to.isTypeVariable() ? 10 : Integer.MAX_VALUE; } if (from.isUnknown() || to.isUnknown()) { return 0; } throw new IllegalArgumentException(" Unknown types for type-distance calculation: '" + from.name() + "' and '" + to.name() + "'"); } }
// FILE: c:/projects/jetel/org/jetel/data/DataRecord.java package org.jetel.data; import java.io.Serializable; import java.nio.ByteBuffer; import org.jetel.metadata.DataFieldMetadata; import org.jetel.metadata.DataRecordMetadata; public class DataRecord implements Serializable, Comparable { /** * @since */ private transient String codeClassName; /** * @since */ private DataField fields[]; // Associations /** * @since */ private transient DataRecordMetadata metadata; /** * Create new instance of DataRecord based on specified metadata ( * how many fields, what field types, etc.) * * @param _metadata */ public DataRecord(DataRecordMetadata _metadata) { this.metadata = _metadata; fields = new DataField[metadata.getNumFields()]; } /** * Private constructor used when clonning/copying DataRecord objects. * * @param _metadata metadata describing this record * @param numFields number of fields this record should contain */ private DataRecord(DataRecordMetadata _metadata, int numFields){ this.metadata = _metadata; fields = new DataField[numFields]; } /** * Creates deep copy of existing record (field by field). * * @return new DataRecord */ public DataRecord duplicate(){ DataRecord newRec=new DataRecord(metadata,fields.length); for (int i=0;i<fields.length;i++){ newRec.fields[i]=fields[i].duplicate(); } return newRec; } /** * Set fields by copying the fields from the record passed as argument. * Does assume that both records have the same structure - i.e. metadata. * @param fromRecord DataRecord from which to get fields' values */ public void copyFrom(DataRecord fromRecord){ for (int i=0;i<fields.length;i++){ this.fields[i].copyFrom(fromRecord.fields[i]); } } /** * Set fields by copying the fields from the record passed as argument. * Can handle situation when records are not exactly the same. * * @param _record Record from which fields are copied * @since */ public void copyFieldsByPosition(DataRecord _record) { DataRecordMetadata sourceMetadata = _record.getMetadata(); DataField sourceField; DataField targetField; //DataFieldMetadata fieldMetadata; int sourceLength = sourceMetadata.getNumFields(); int targetLength = this.metadata.getNumFields(); int copyLength; if (sourceLength < targetLength) { copyLength = sourceLength; } else { copyLength = targetLength; } for (int i = 0; i < copyLength; i++) { //fieldMetadata = metadata.getField(i); sourceField = _record.getField(i); targetField = this.getField(i); if (sourceField.getType() == targetField.getType()) { targetField.setValue(sourceField.getValue()); } else { targetField.setToDefaultValue(); } } } /** * Deletes/removes specified field. The field's internal reference * is set to NULL, so it can be garbage collected. * * @param _fieldNum Description of Parameter * @since */ public void delField(int _fieldNum) { try { fields[_fieldNum] = null; } catch (IndexOutOfBoundsException e) { } } /** * Refreshes this record's content from ByteBuffer. * * @param buffer ByteBuffer from which this record's fields should be read * @since April 23, 2002 */ public void deserialize(ByteBuffer buffer) { for (int i = 0; i < fields.length; i++) { fields[i].deserialize(buffer); } } /** * Test two DataRecords for equality. Records must have the same metadata (be * created using the same metadata object) and their field values must be equal. * * @param obj DataRecord to compare with * @return True if they equals, false otherwise * @since April 23, 2002 */ public boolean equals(Object obj) { if (this==obj) return true; /* * first test that both records have the same structure i.e. point to * the same metadata */ if (obj instanceof DataRecord) { if (metadata != ((DataRecord) obj).getMetadata()) { return false; } // check field by field that they are the same for (int i = 0; i < fields.length; i++) { if (!fields[i].equals(((DataRecord) obj).getField(i))) { return false; } } return true; }else{ return false; } } /** * Compares two DataRecords. Records must have the same metadata (be * created using the same metadata object). Their field values are compare one by one, * the first non-equal pair of fields denotes the overall comparison result. * * @see java.lang.Comparable#compareTo(java.lang.Object) */ public int compareTo(Object obj){ if (this==obj) return 0; if (obj instanceof DataRecord) { if (metadata != ((DataRecord) obj).getMetadata()) { throw new RuntimeException("Can't compare - records have different metadata objects assigned!"); } int cmp; // check field by field that they are the same for (int i = 0; i < fields.length; i++) { cmp=fields[i].compareTo(((DataRecord) obj).getField(i)); if (cmp!=0) { return cmp; } } return 0; }else{ throw new ClassCastException("Can't compare DataRecord with "+obj.getClass().getName()); } } /** * Gets the codeClassName attribute of the DataRecord object * * @return The codeClassName value */ public String getCodeClassName() { return codeClassName; } /** * An operation that does ... * * @param _fieldNum Description of Parameter * @return The Field value * @since */ public DataField getField(int _fieldNum) { try { return fields[_fieldNum]; } catch (IndexOutOfBoundsException e) { return null; } } /** * An operation that does ... * * @param _name Description of Parameter * @return The Field value * @since */ public DataField getField(String _name) { try { return fields[metadata.getFieldPosition(_name)]; } catch (IndexOutOfBoundsException e) { return null; } } /** * An attribute that represents ... An operation that does ... * * @return The Metadata value * @since */ public DataRecordMetadata getMetadata() { return metadata; } /** * An operation that does ... * * @return The NumFields value * @since */ public int getNumFields() { return metadata.getNumFields(); } /** * Description of the Method * * @since April 5, 2002 */ public void init() { DataFieldMetadata fieldMetadata; // create appropriate data fields based on metadata supplied for (int i = 0; i < metadata.getNumFields(); i++) { fieldMetadata = metadata.getField(i); fields[i] = DataFieldFactory.createDataField( fieldMetadata.getType(), fieldMetadata); } } /** * Serializes this record's content into ByteBuffer. * * @param buffer ByteBuffer into which the individual fields of this record should be put * @since April 23, 2002 */ public void serialize(ByteBuffer buffer) { for (int i = 0; i < fields.length; i++) { fields[i].serialize(buffer); } } /** * Sets the codeClassName attribute of the DataRecord object * * @param codeClassName The new codeClassName value */ public void setCodeClassName(String codeClassName) { this.codeClassName = codeClassName; } /** * Assigns new metadata to this DataRecord. If the new * metadata is not equal to the current metadata, the record's * content is recreated from scratch. After calling this * method, record is uninitialized and init() method should * be called prior any attempt to manipulate this record's content. * * @param metadata The new Metadata value * @since April 5, 2002 */ public void setMetadata(DataRecordMetadata metadata) { if (this.metadata != metadata){ this.metadata=metadata; fields = new DataField[metadata.getNumFields()]; } } /** * An operation that sets value of all data fields to their default value. */ public void setToDefaultValue() { for (int i = 0; i < fields.length; i++) { fields[i].setToDefaultValue(); } } /** * An operation that sets value of the selected data field to its default * value. * * @param _fieldNum Ordinal number of the field which should be set to default */ public void setToDefaultValue(int _fieldNum) { fields[_fieldNum].setToDefaultValue(); } /** * An operation that sets value of all data fields to NULL value. */ public void setToNull(){ for (int i = 0; i < fields.length; i++) { fields[i].setNull(true); } } /** * An operation that sets value of the selected data field to NULL * value. * @param _fieldNum */ public void setToNull(int _fieldNum) { fields[_fieldNum].setNull(true); } /** * Creates textual representation of record's content based on values of individual * fields * * @return Description of the Return Value */ public String toString() { StringBuffer str = new StringBuffer(80); for (int i = 0; i < fields.length; i++) { str.append("#").append(i).append("|"); str.append(fields[i].getMetadata().getName()).append("|"); str.append(fields[i].getType()); str.append("->"); str.append(fields[i].toString()); str.append("\n"); } return str.toString(); } /** * Gets the actual size of record (in bytes).<br> * <i>How many bytes are required for record serialization</i> * * @return The size value */ public int getSizeSerialized() { int size=0; for (int i = 0; i < fields.length; size+=fields[i++].getSizeSerialized()); return size; } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ public int hashCode(){ int hash=17; for (int i=0;i<fields.length;i++){ hash=37*hash+fields[i].hashCode(); } return hash; } /** * Test whether the whole record has NULL value - i.e. * every field it contains has NULL value. * @return true if all fields have NULL value otherwise false */ public boolean isNull(){ for (int i = 0; i < fields.length; i++) { if (!fields[i].isNull()) return false; } return true; } } /* * end class DataRecord */
package mil.nga.giat.mage.sdk.fetch; import android.content.Context; import android.util.Log; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; import mil.nga.giat.mage.sdk.connectivity.ConnectivityUtility; import mil.nga.giat.mage.sdk.datastore.layer.Layer; import mil.nga.giat.mage.sdk.datastore.layer.LayerHelper; import mil.nga.giat.mage.sdk.http.resource.LayerResource; import mil.nga.giat.mage.sdk.datastore.user.Event; import mil.nga.giat.mage.sdk.datastore.user.EventHelper; import mil.nga.giat.mage.sdk.login.LoginTaskFactory; public class ImageryServerFetch extends AbstractServerFetch { private static final String LOG_NAME = ImageryServerFetch.class.getName(); private static final String TYPE = "Imagery"; private AtomicBoolean isCanceled = new AtomicBoolean(false); private final LayerResource layerResource; public ImageryServerFetch(Context context) { super(context); layerResource = new LayerResource(context); } public void fetch(){ Event event = EventHelper.getInstance(mContext).getCurrentEvent(); LayerHelper layerHelper = LayerHelper.getInstance(mContext); // if you are disconnect, skip this if(!ConnectivityUtility.isOnline(mContext) || LoginTaskFactory.getInstance(mContext).isLocalLogin()) { Log.d(LOG_NAME, "Disconnected, not pulling imagery."); return; } try { Collection<Layer> remoteLayers = layerResource.getImageryLayers(event); // get local layers Collection<Layer> localLayers = layerHelper.readAll(TYPE); Map<String, Layer> remoteIdToLayer = new HashMap<>(localLayers.size()); for(Layer layer : localLayers){ remoteIdToLayer.put(layer.getRemoteId(), layer); } for (Layer remoteLayer : remoteLayers) { if (isCanceled.get()) { break; } remoteLayer.setLoaded(true); if (!localLayers.contains(remoteLayer)) { //New layer from remote server layerHelper.create(remoteLayer); } else { Layer localLayer = remoteIdToLayer.get(remoteLayer.getRemoteId()); //Only remove a local layer if the even has changed if(!remoteLayer.getEvent().equals(localLayer.getEvent())) { layerHelper.delete(localLayer.getId()); layerHelper.create(remoteLayer); } } } }catch(Exception e){ Log.w(LOG_NAME, "Error performing imagery layer operations",e); } } public void destroy() { isCanceled.getAndSet(true); } }
package org.xtreemfs.utils; import java.io.FileInputStream; import java.io.IOException; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.xtreemfs.common.uuids.ServiceUUID; import org.xtreemfs.common.uuids.UUIDResolver; import org.xtreemfs.dir.DIRClient; import org.xtreemfs.foundation.SSLOptions; import org.xtreemfs.foundation.TimeSync; import org.xtreemfs.foundation.logging.Logging; import org.xtreemfs.foundation.logging.Logging.Category; import org.xtreemfs.foundation.pbrpc.Schemes; import org.xtreemfs.foundation.pbrpc.client.RPCNIOSocketClient; import org.xtreemfs.foundation.pbrpc.generatedinterfaces.RPC.Auth; import org.xtreemfs.foundation.pbrpc.generatedinterfaces.RPC.AuthPassword; import org.xtreemfs.foundation.pbrpc.generatedinterfaces.RPC.AuthType; import org.xtreemfs.foundation.pbrpc.generatedinterfaces.RPC.UserCredentials; import org.xtreemfs.foundation.util.CLIParser; import org.xtreemfs.foundation.util.CLIParser.CliOption; import org.xtreemfs.foundation.util.ONCRPCServiceURL; import org.xtreemfs.foundation.util.OutputUtils; import org.xtreemfs.osd.drain.OSDDrain; import org.xtreemfs.pbrpc.generatedinterfaces.DIR.ServiceSet; import org.xtreemfs.pbrpc.generatedinterfaces.DIR.ServiceType; import org.xtreemfs.pbrpc.generatedinterfaces.DIRServiceClient; import org.xtreemfs.pbrpc.generatedinterfaces.GlobalTypes.PORTS; import org.xtreemfs.pbrpc.generatedinterfaces.MRCServiceClient; import org.xtreemfs.pbrpc.generatedinterfaces.OSDServiceClient; public class xtfs_remove_osd { private static final String DEFAULT_DIR_CONFIG = "/etc/xos/xtreemfs/default_dir"; private OSDServiceClient osd; private DIRClient dir; private MRCServiceClient mrc; private RPCNIOSocketClient dirClient; private RPCNIOSocketClient osdClient; private RPCNIOSocketClient mrcClient; private InetSocketAddress osdAddr; private InetSocketAddress mrcAddr; private SSLOptions sslOptions; private InetSocketAddress dirAddress; private UUIDResolver resolver; private RPCNIOSocketClient resolverClient; private Auth authHeader; private UserCredentials credentials; private String osdUUIDString; private ServiceUUID osdUUID; public static void main(String[] args) { Map<String, CliOption> options = null; try { // parse the call arguments options = utils.getDefaultAdminToolOptions(true); List<String> arguments = new ArrayList<String>(1); CliOption oDir = new CliOption(CliOption.OPTIONTYPE.URL, "directory service to use (e.g. 'pbrpc://localhost:32638')", "<uri>"); oDir.urlDefaultPort = PORTS.DIR_PBRPC_PORT_DEFAULT.getNumber(); oDir.urlDefaultProtocol = Schemes.SCHEME_PBRPC; options.put("dir", oDir); options.put("s", new CliOption(CliOption.OPTIONTYPE.SWITCH, "shutdown OSD", "")); options.put("d", new CliOption(CliOption.OPTIONTYPE.SWITCH, "enbable debug output", "")); CLIParser.parseCLI(args, options, arguments); // start logging if (options.get("d").switchValue) { Logging.start(Logging.LEVEL_DEBUG); } else { Logging.start(Logging.LEVEL_ERROR); } if (options.get(utils.OPTION_HELP).switchValue || options.get(utils.OPTION_HELP_LONG).switchValue || arguments.size() == 0) { usage(options); return; } if (arguments.size() > 1) { // print error. error("invalid number of arguments", options, true); } ONCRPCServiceURL dirURL = options.get("dir").urlValue; boolean shutdown = options.get("s").switchValue; String password = (options.get(utils.OPTION_ADMIN_PASS).stringValue != null) ? options .get(utils.OPTION_ADMIN_PASS).stringValue : ""; boolean useSSL = false; boolean gridSSL = false; String serviceCredsFile = null; String serviceCredsPass = null; String trustedCAsFile = null; String trustedCAsPass = null; InetSocketAddress dirAddr = null; // read default settings for the OSD String osdUUID = null; if (arguments.get(0).startsWith("uuid:")) { osdUUID = arguments.get(0).substring("uuid:".length()); } else { error("There was no UUID for the OSD given!", options); } // parse security info if protocol is 'https' if (dirURL != null && (Schemes.SCHEME_PBRPCS.equals(dirURL.getProtocol()) || Schemes.SCHEME_PBRPCG .equals(dirURL.getProtocol()))) { useSSL = true; serviceCredsFile = options.get(utils.OPTION_USER_CREDS_FILE).stringValue; serviceCredsPass = options.get(utils.OPTION_USER_CREDS_PASS).stringValue; trustedCAsFile = options.get(utils.OPTION_TRUSTSTORE_FILE).stringValue; trustedCAsPass = options.get(utils.OPTION_TRUSTSTORE_PASS).stringValue; if (Schemes.SCHEME_PBRPCG.equals(dirURL.getProtocol())) { gridSSL = true; } if (serviceCredsFile == null) { System.out.println("SSL requires '-" + utils.OPTION_USER_CREDS_FILE + "' parameter to be specified"); usage(options); System.exit(1); } else if (trustedCAsFile == null) { System.out.println("SSL requires '-" + utils.OPTION_TRUSTSTORE_FILE + "' parameter to be specified"); usage(options); System.exit(1); } } // read default settings if (dirURL == null) { try { DefaultDirConfig cfg = new DefaultDirConfig(DEFAULT_DIR_CONFIG); cfg.read(); dirAddr = cfg.getDirectoryService(); useSSL = cfg.isSslEnabled(); serviceCredsFile = cfg.getServiceCredsFile(); serviceCredsPass = cfg.getServiceCredsPassphrase(); trustedCAsFile = cfg.getTrustedCertsFile(); trustedCAsPass = cfg.getTrustedCertsPassphrase(); } catch (IOException e) { error("No DIR service configuration available. Please use the -dir option.", options); } } else { dirAddr = new InetSocketAddress(dirURL.getHost(), dirURL.getPort()); } // TODO: support custom SSL trust managers SSLOptions sslOptions = useSSL ? new SSLOptions(new FileInputStream(serviceCredsFile), serviceCredsPass, SSLOptions.PKCS12_CONTAINER, new FileInputStream(trustedCAsFile), trustedCAsPass, SSLOptions.JKS_CONTAINER, false, gridSSL, null) : null; xtfs_remove_osd removeOsd = new xtfs_remove_osd(dirAddr, osdUUID, sslOptions, password); removeOsd.initialize(); removeOsd.drainOSD(shutdown); removeOsd.shutdown(); System.exit(0); } catch (Exception e) { error(e.getMessage(), options); } } public xtfs_remove_osd(InetSocketAddress dirAddress, String osdUUIDString, SSLOptions sslOptions, String password) throws Exception { try { this.sslOptions = sslOptions; this.dirAddress = dirAddress; this.osdUUIDString = osdUUIDString; if (password.equals("")) { this.authHeader = Auth.newBuilder().setAuthType(AuthType.AUTH_NONE).build(); } else { this.authHeader = Auth.newBuilder().setAuthType(AuthType.AUTH_PASSWORD) .setAuthPasswd(AuthPassword.newBuilder().setPassword(password).build()).build(); } // TODO: use REAL user credentials (this is a SECURITY HOLE) this.credentials = UserCredentials.newBuilder().setUsername("root").addGroups("root").build(); } catch (Exception e) { shutdown(); throw e; } } public void initialize() throws Exception { TimeSync.initializeLocal(0, 50); // connect to DIR dirClient = new RPCNIOSocketClient(sslOptions, 10000, 5 * 60 * 1000); dirClient.start(); dirClient.waitForStartup(); DIRServiceClient tmp = new DIRServiceClient(dirClient, dirAddress); dir = new DIRClient(tmp, new InetSocketAddress[] { dirAddress }, 100, 15 * 1000); resolverClient = new RPCNIOSocketClient(sslOptions, 10000, 5 * 60 * 1000); resolverClient.start(); resolverClient.waitForStartup(); this.resolver = UUIDResolver.startNonSingelton(dir, 1000, 10 * 10 * 1000); // create OSD client osdUUID = new ServiceUUID(osdUUIDString, resolver); osdUUID.resolve(); osdAddr = osdUUID.getAddress(); osdClient = new RPCNIOSocketClient(sslOptions, 10000, 5 * 60 * 1000); osdClient.start(); osdClient.waitForStartup(); osd = new OSDServiceClient(osdClient, osdAddr); // create MRC client ServiceSet sSet = null; try { sSet = dir.xtreemfs_service_get_by_type(null, authHeader, credentials, ServiceType.SERVICE_TYPE_MRC); } catch (IOException ioe) { Logging.logMessage(Logging.LEVEL_WARN, Category.proc, new Object(), OutputUtils.stackTraceToString(ioe)); throw ioe; } mrcClient = new RPCNIOSocketClient(sslOptions, 100000, 5 * 60 * 10000); mrcClient.start(); mrcClient.waitForStartup(); if (sSet.getServicesCount() == 0) { throw new IOException("No MRC is currently registred at DIR"); } String mrcUUID = sSet.getServices(0).getUuid(); ServiceUUID UUIDService = new ServiceUUID(mrcUUID, resolver); UUIDService.resolve(); mrcAddr = UUIDService.getAddress(); mrc = new MRCServiceClient(mrcClient, mrcAddr); } public void shutdown() { try { UUIDResolver.shutdown(resolver); resolverClient.shutdown(); } catch (Exception e) { e.printStackTrace(); } } /** * Removes (drain) an OSD. * * @throws Exception */ public void drainOSD(boolean shutdown) throws Exception { OSDDrain osdDrain = new OSDDrain(dir, osd, mrc, osdUUID, authHeader, credentials, resolver); osdDrain.drain(shutdown); } /** * Prints the error <code>message</code> and delegates to usage() if "printUsage" is true. * * @param message * The error message * @param options * The CLI Options. * @param printUsage * True if usage should be printed. False otherwise. * */ private static void error(String message, Map<String, CliOption> options, boolean printUsage) { System.err.println(message); if (printUsage) { System.out.println(); usage(options); } System.exit(1); } /** * Prints the error <code>message</code> and delegates to usage(). * * @param message * The error message * @param options * The CLI Options. */ private static void error(String message, Map<String, CliOption> options) { error(message, options, false); } public static void usage(Map<String, CliOption> options) { System.out.println("usage: xtfs_remove_osd [options] uuid:<osd_uuid>\n"); System.out.println(" " + "<osd_uuid> the unique identifier of the OSD to be removed\n"); System.out.println(" " + "options:"); utils.printOptions(options); } }
package org.jbpm; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import junit.framework.TestCase; import org.drools.KnowledgeBase; import org.drools.KnowledgeBaseFactory; import org.drools.audit.WorkingMemoryInMemoryLogger; import org.drools.audit.event.LogEvent; import org.drools.audit.event.RuleFlowNodeLogEvent; import org.drools.builder.KnowledgeBuilder; import org.drools.builder.KnowledgeBuilderFactory; import org.drools.builder.ResourceType; import org.drools.definition.process.Node; import org.drools.io.ResourceFactory; import org.drools.persistence.jpa.JPAKnowledgeService; import org.drools.runtime.Environment; import org.drools.runtime.EnvironmentName; import org.drools.runtime.KnowledgeSessionConfiguration; import org.drools.runtime.StatefulKnowledgeSession; import org.drools.runtime.process.NodeInstance; import org.drools.runtime.process.NodeInstanceContainer; import org.drools.runtime.process.ProcessInstance; import org.drools.runtime.process.WorkItem; import org.drools.runtime.process.WorkItemHandler; import org.drools.runtime.process.WorkItemManager; import org.drools.runtime.process.WorkflowProcessInstance; import org.h2.tools.DeleteDbFiles; import org.h2.tools.Server; import org.jbpm.process.audit.JPAProcessInstanceDbLog; import org.jbpm.process.audit.JPAWorkingMemoryDbLogger; import org.jbpm.process.audit.NodeInstanceLog; import org.jbpm.workflow.instance.impl.WorkflowProcessInstanceImpl; import bitronix.tm.TransactionManagerServices; import bitronix.tm.resource.jdbc.PoolingDataSource; public abstract class JbpmJUnitTestCase extends TestCase { protected final static String EOL = System.getProperty( "line.separator" ); private boolean persistence = false; private PoolingDataSource ds1; private EntityManagerFactory emf; private static Server h2Server; private TestWorkItemHandler workItemHandler = new TestWorkItemHandler(); public StatefulKnowledgeSession ksession; private WorkingMemoryInMemoryLogger logger; private JPAProcessInstanceDbLog log; public JbpmJUnitTestCase() { this(false); } public JbpmJUnitTestCase(boolean persistence) { this.persistence = persistence; if (persistence) { startH2Database(); } } public boolean isPersistence() { return persistence; } protected void setUp() { if (persistence) { ds1 = new PoolingDataSource(); ds1.setClassName("bitronix.tm.resource.jdbc.lrc.LrcXADataSource"); ds1.setUniqueName("jdbc/testDS1"); ds1.setMaxPoolSize(5); ds1.setAllowLocalTransactions(true); ds1.getDriverProperties().setProperty("driverClassName", "org.h2.Driver"); ds1.getDriverProperties().setProperty("url", "jdbc:h2:tcp://localhost/JPADroolsFlow"); ds1.getDriverProperties().setProperty("user", "sa"); ds1.getDriverProperties().setProperty("password", ""); ds1.init(); emf = Persistence.createEntityManagerFactory( "org.jbpm.persistence.jpa" ); } } protected void tearDown() { if (emf != null) { emf.close(); } if (ds1 != null) { ds1.close(); } } public synchronized void startH2Database() { if (h2Server == null) { try { DeleteDbFiles.execute("", "", true); h2Server = Server.createTcpServer(new String[0]); h2Server.start(); } catch (SQLException e) { if (h2Server != null) { h2Server.shutdown(); h2Server = null; } throw new RuntimeException("can't start h2 server db",e); } } } protected KnowledgeBase createKnowledgeBase(String... process) { KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); for (String p: process) { kbuilder.add(ResourceFactory.newClassPathResource(p), ResourceType.BPMN2); } return kbuilder.newKnowledgeBase(); } protected KnowledgeBase createKnowledgeBase(Map<String, ResourceType> resources) throws Exception { KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); for (Map.Entry<String, ResourceType> entry: resources.entrySet()) { kbuilder.add(ResourceFactory.newClassPathResource(entry.getKey()), entry.getValue()); } return kbuilder.newKnowledgeBase(); } protected KnowledgeBase createKnowledgeBaseGuvnor(String... packages) throws Exception { return createKnowledgeBaseGuvnor(false, "http://localhost:8080/drools-guvnor", "admin", "admin", packages); } protected KnowledgeBase createKnowledgeBaseGuvnorAssets(String pkg, String...assets) throws Exception { return createKnowledgeBaseGuvnor(false, "http://localhost:8080/drools-guvnor", "admin", "admin", pkg, assets); } protected KnowledgeBase createKnowledgeBaseGuvnor(boolean dynamic, String url, String username, String password, String pkg, String... assets) throws Exception { KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); String changeSet = "<change-set xmlns='http://drools.org/drools-5.0/change-set'" + EOL + " xmlns:xs='http: " xs:schemaLocation='http: " <add>" + EOL; for(String a : assets) { if(a.indexOf(".bpmn") >= 0) { a = a.substring(0, a.indexOf(".bpmn")); } changeSet += " <resource source='" + url + "/rest/packages/" + pkg + "/assets/" + a + "/binary' type='BPMN2' basicAuthentication=\"enabled\" username=\"" + username + "\" password=\"" + password + "\" />" + EOL; } changeSet += " </add>" + EOL + "</change-set>"; kbuilder.add(ResourceFactory.newByteArrayResource(changeSet.getBytes()), ResourceType.CHANGE_SET); return kbuilder.newKnowledgeBase(); } protected KnowledgeBase createKnowledgeBaseGuvnor(boolean dynamic, String url, String username, String password, String... packages) throws Exception { KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); String changeSet = "<change-set xmlns='http://drools.org/drools-5.0/change-set'" + EOL + " xmlns:xs='http: " xs:schemaLocation='http: " <add>" + EOL; for (String p : packages) { changeSet += " <resource source='" + url + "/rest/packages/" + p + "/binary' type='PKG' basicAuthentication=\"enabled\" username=\"" + username + "\" password=\"" + password + "\" />" + EOL; } changeSet += " </add>" + EOL + "</change-set>"; kbuilder.add(ResourceFactory.newByteArrayResource(changeSet.getBytes()), ResourceType.CHANGE_SET); return kbuilder.newKnowledgeBase(); } protected StatefulKnowledgeSession createKnowledgeSession(KnowledgeBase kbase) { if (persistence) { Environment env = KnowledgeBaseFactory.newEnvironment(); env.set(EnvironmentName.ENTITY_MANAGER_FACTORY, emf); env.set(EnvironmentName.TRANSACTION_MANAGER, TransactionManagerServices.getTransactionManager()); StatefulKnowledgeSession result = JPAKnowledgeService.newStatefulKnowledgeSession(kbase, null, env); new JPAWorkingMemoryDbLogger(result); if (log == null) { log = new JPAProcessInstanceDbLog(); } return result; } else { StatefulKnowledgeSession result = kbase.newStatefulKnowledgeSession(); logger = new WorkingMemoryInMemoryLogger(result); return result; } } protected StatefulKnowledgeSession createKnowledgeSession(String... process) { KnowledgeBase kbase = createKnowledgeBase(process); return createKnowledgeSession(kbase); } protected StatefulKnowledgeSession restoreSession(StatefulKnowledgeSession ksession, boolean noCache) { if (persistence) { int id = ksession.getId(); KnowledgeBase kbase = ksession.getKnowledgeBase(); Environment env = null; if (noCache) { env = KnowledgeBaseFactory.newEnvironment(); emf = Persistence.createEntityManagerFactory( "org.jbpm.persistence.jpa" ); env.set(EnvironmentName.ENTITY_MANAGER_FACTORY, emf); env.set(EnvironmentName.TRANSACTION_MANAGER, TransactionManagerServices.getTransactionManager()); } else { env = ksession.getEnvironment(); } KnowledgeSessionConfiguration config = ksession.getSessionConfiguration(); StatefulKnowledgeSession result = JPAKnowledgeService.loadStatefulKnowledgeSession(id, kbase, config, env); new JPAWorkingMemoryDbLogger(result); return result; } else { return ksession; } } public Object getVariableValue(String name, long processInstanceId, StatefulKnowledgeSession ksession) { return ((WorkflowProcessInstance) ksession.getProcessInstance(processInstanceId)).getVariable(name); } public void assertProcessInstanceCompleted(long processInstanceId, StatefulKnowledgeSession ksession) { assertNull(ksession.getProcessInstance(processInstanceId)); } public void assertProcessInstanceAborted(long processInstanceId, StatefulKnowledgeSession ksession) { assertNull(ksession.getProcessInstance(processInstanceId)); } public void assertProcessInstanceActive(long processInstanceId, StatefulKnowledgeSession ksession) { assertNotNull(ksession.getProcessInstance(processInstanceId)); } public void assertNodeActive(long processInstanceId, StatefulKnowledgeSession ksession, String... name) { List<String> names = new ArrayList<String>(); for (String n: name) { names.add(n); } ProcessInstance processInstance = ksession.getProcessInstance(processInstanceId); if (processInstance instanceof WorkflowProcessInstance) { assertNodeActive((WorkflowProcessInstance) processInstance, names); } if (!names.isEmpty()) { String s = names.get(0); for (int i = 1; i < names.size(); i++) { s += ", " + names.get(i); } fail("Node(s) not active: " + s); } } private void assertNodeActive(NodeInstanceContainer container, List<String> names) { for (NodeInstance nodeInstance: container.getNodeInstances()) { String nodeName = nodeInstance.getNodeName(); if (names.contains(nodeName)) { names.remove(nodeName); } if (nodeInstance instanceof NodeInstanceContainer) { assertNodeActive((NodeInstanceContainer) nodeInstance, names); } } } public void assertNodeTriggered(long processInstanceId, String... nodeNames) { List<String> names = new ArrayList<String>(); for (String nodeName: nodeNames) { names.add(nodeName); } if (persistence) { List<NodeInstanceLog> logs = log.findNodeInstances(processInstanceId); if (logs != null) { for (NodeInstanceLog l: logs) { String nodeName = l.getNodeName(); if (l.getType() == NodeInstanceLog.TYPE_ENTER && names.contains(nodeName)) { names.remove(nodeName); } } } } else { for (LogEvent event: logger.getLogEvents()) { if (event instanceof RuleFlowNodeLogEvent) { String nodeName = ((RuleFlowNodeLogEvent) event).getNodeName(); if (names.contains(nodeName)) { names.remove(nodeName); } } } } if (!names.isEmpty()) { String s = names.get(0); for (int i = 1; i < names.size(); i++) { s += ", " + names.get(i); } fail("Node(s) not executed: " + s); } } protected void clearHistory() { if (persistence) { if (log == null) { log = new JPAProcessInstanceDbLog(); } log.clear(); } else { logger.clear(); } } public TestWorkItemHandler getTestWorkItemHandler() { return workItemHandler; } public static class TestWorkItemHandler implements WorkItemHandler { private List<WorkItem> workItems = new ArrayList<WorkItem>(); public void executeWorkItem(WorkItem workItem, WorkItemManager manager) { workItems.add(workItem); } public void abortWorkItem(WorkItem workItem, WorkItemManager manager) { } public WorkItem getWorkItem() { if (workItems.size() == 0) { return null; } if (workItems.size() == 1) { WorkItem result = workItems.get(0); this.workItems.clear(); return result; } else { throw new IllegalArgumentException("More than one work item active"); } } public List<WorkItem> getWorkItems() { List<WorkItem> result = new ArrayList<WorkItem>(workItems); workItems.clear(); return result; } } public void assertProcessVarExists(ProcessInstance process, String... processVarNames) { WorkflowProcessInstanceImpl instance = (WorkflowProcessInstanceImpl) process; List<String> names = new ArrayList<String>(); for (String nodeName: processVarNames) { names.add(nodeName); } for(String pvar : instance.getVariables().keySet()) { if (names.contains(pvar)) { names.remove(pvar); } } if (!names.isEmpty()) { String s = names.get(0); for (int i = 1; i < names.size(); i++) { s += ", " + names.get(i); } fail("Process Variable(s) do not exist: " + s); } } public void assertNodeExists(ProcessInstance process, String... nodeNames) { WorkflowProcessInstanceImpl instance = (WorkflowProcessInstanceImpl) process; List<String> names = new ArrayList<String>(); for (String nodeName: nodeNames) { names.add(nodeName); } for(Node node : instance.getNodeContainer().getNodes()) { if (names.contains(node.getName())) { names.remove(node.getName()); } } if (!names.isEmpty()) { String s = names.get(0); for (int i = 1; i < names.size(); i++) { s += ", " + names.get(i); } fail("Node(s) do not exist: " + s); } } public void assertNumOfIncommingConnections(ProcessInstance process, String nodeName, int num) { assertNodeExists(process, nodeName); WorkflowProcessInstanceImpl instance = (WorkflowProcessInstanceImpl) process; for(Node node : instance.getNodeContainer().getNodes()) { if(node.getName().equals(nodeName)) { if(node.getIncomingConnections().size() != num) { fail("Expected incomming connections: " + num + " - found " + node.getIncomingConnections().size()); } else { break; } } } } public void assertNumOfOutgoingConnections(ProcessInstance process, String nodeName, int num) { assertNodeExists(process, nodeName); WorkflowProcessInstanceImpl instance = (WorkflowProcessInstanceImpl) process; for(Node node : instance.getNodeContainer().getNodes()) { if(node.getName().equals(nodeName)) { if(node.getOutgoingConnections().size() != num) { fail("Expected outgoing connections: " + num + " - found " + node.getOutgoingConnections().size()); } else { break; } } } } public void assertVersionEquals(ProcessInstance process, String version) { WorkflowProcessInstanceImpl instance = (WorkflowProcessInstanceImpl) process; if(!instance.getWorkflowProcess().getVersion().equals(version)) { fail("Expected version: " + version + " - found " + instance.getWorkflowProcess().getVersion()); } } public void assertProcessNameEquals(ProcessInstance process, String name) { WorkflowProcessInstanceImpl instance = (WorkflowProcessInstanceImpl) process; if(!instance.getWorkflowProcess().getName().equals(name)) { fail("Expected name: " + name + " - found " + instance.getWorkflowProcess().getName()); } } public void assertPackageNameEquals(ProcessInstance process, String packageName) { WorkflowProcessInstanceImpl instance = (WorkflowProcessInstanceImpl) process; if(!instance.getWorkflowProcess().getPackageName().equals(packageName)) { fail("Expected package name: " + packageName + " - found " + instance.getWorkflowProcess().getPackageName()); } } }
package net.minecraftforge.fluids; import java.util.HashMap; import java.util.Map; import net.minecraft.block.Block; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.Event; import com.google.common.collect.BiMap; import com.google.common.collect.HashBiMap; import com.google.common.collect.ImmutableMap; /** * Handles Fluid registrations. Fluids MUST be registered in order to function. * * @author King Lemming, CovertJaguar (LiquidDictionary) * */ public abstract class FluidRegistry { static int maxID = 0; static HashMap<String, Fluid> fluids = new HashMap(); static BiMap<String, Integer> fluidIDs = HashBiMap.create(); static BiMap<Block, Fluid> fluidBlocks; public static final Fluid WATER = new Fluid("water").setBlockID(Block.waterStill.blockID).setUnlocalizedName(Block.waterStill.getUnlocalizedName()); public static final Fluid LAVA = new Fluid("lava").setBlockID(Block.lavaStill.blockID).setLuminosity(15).setDensity(3000).setViscosity(6000).setTemperature(1300).setUnlocalizedName(Block.lavaStill.getUnlocalizedName()); public static int renderIdFluid = -1; static { registerFluid(WATER); registerFluid(LAVA); } private FluidRegistry(){} /** * Called by Forge to prepare the ID map for server -> client sync. */ static void initFluidIDs(BiMap<String, Integer> newfluidIDs) { maxID = newfluidIDs.size(); fluidIDs.clear(); fluidIDs.putAll(newfluidIDs); } /** * Register a new Fluid. If a fluid with the same name already exists, registration is denied. * * @param fluid * The fluid to register. * @return True if the fluid was successfully registered; false if there is a name clash. */ public static boolean registerFluid(Fluid fluid) { if (fluidIDs.containsKey(fluid.getName())) { return false; } fluids.put(fluid.getName(), fluid); fluidIDs.put(fluid.getName(), ++maxID); MinecraftForge.EVENT_BUS.post(new FluidRegisterEvent(fluid.getName(), maxID)); return true; } public static boolean isFluidRegistered(Fluid fluid) { return fluidIDs.containsKey(fluid.getName()); } public static boolean isFluidRegistered(String fluidName) { return fluidIDs.containsKey(fluidName); } public static Fluid getFluid(String fluidName) { return fluids.get(fluidName); } public static Fluid getFluid(int fluidID) { return fluids.get(getFluidName(fluidID)); } public static String getFluidName(int fluidID) { return fluidIDs.inverse().get(fluidID); } public static String getFluidName(FluidStack stack) { return getFluidName(stack.fluidID); } public static int getFluidID(String fluidName) { return fluidIDs.get(fluidName); } public static FluidStack getFluidStack(String fluidName, int amount) { if (!fluidIDs.containsKey(fluidName)) { return null; } return new FluidStack(getFluidID(fluidName), amount); } /** * Returns a read-only map containing Fluid Names and their associated Fluids. */ public static Map<String, Fluid> getRegisteredFluids() { return ImmutableMap.copyOf(fluids); } /** * Returns a read-only map containing Fluid Names and their associated IDs. */ public static Map<String, Integer> getRegisteredFluidIDs() { return ImmutableMap.copyOf(fluidIDs); } public static Fluid lookupFluidForBlock(Block block) { if (fluidBlocks == null) { fluidBlocks = new BiMap<Block, Fluid>(); for (Fluid fluid : fluids.values()) { if (fluid.canBePlacedInWorld() && Block.blocksList[fluid.getBlockID()] != null) { fluidBlocks.put(Block.blocksList[fluid.getBlockID()], fluid); } } } return fluidBlocks.get(block); } public static class FluidRegisterEvent extends Event { public final String fluidName; public final int fluidID; public FluidRegisterEvent(String fluidName, int fluidID) { this.fluidName = fluidName; this.fluidID = fluidID; } } }
package mtr.data; import mtr.block.BlockLiftButtons; import mtr.entity.EntityLift; import net.minecraft.core.BlockPos; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.entity.BlockEntity; import java.util.ArrayList; import java.util.List; import java.util.function.Consumer; public class LiftInstructions { private final List<LiftInstruction> instructions = new ArrayList<>(); private final Consumer<String> callback; public LiftInstructions(Consumer<String> callback) { this.callback = callback; } public void getTargetFloor(Consumer<Integer> callback) { if (hasInstructions()) { callback.accept(instructions.get(0).floor); } } public void arrived() { if (hasInstructions()) { instructions.remove(0); callback.accept(toString()); } } public boolean hasInstructions() { return !instructions.isEmpty(); } public void addInstruction(int currentFloor, boolean currentMovingUp, int floor) { addInstruction(currentFloor, currentMovingUp, floor, false, true, true); } private int addInstruction(int currentFloor, boolean currentMovingUp, int newFloor, boolean newMovingUp, boolean noDirection, boolean shouldAdd) { if (currentFloor == newFloor) { return 0; } final List<LiftInstruction> tempInstructions = new ArrayList<>(instructions); tempInstructions.add(0, new LiftInstruction(currentFloor, currentMovingUp)); int distance = 0; for (int i = 0; i < tempInstructions.size() - 1; i++) { final LiftInstruction previousInstruction = tempInstructions.get(i); final LiftInstruction nextInstruction = tempInstructions.get(i + 1); final boolean newMovingUpTemp = noDirection ? nextInstruction.movingUp : newMovingUp; if (instructions.contains(new LiftInstruction(newFloor, newMovingUpTemp))) { return -1; } if (nextInstruction.canInsert(previousInstruction, newFloor, newMovingUpTemp)) { if (shouldAdd) { instructions.add(i, new LiftInstruction(newFloor, newMovingUpTemp)); callback.accept(toString()); } return distance + Math.abs(newFloor - previousInstruction.floor); } distance += Math.abs(nextInstruction.floor - previousInstruction.floor); } final int lastInstruction = hasInstructions() ? instructions.get(instructions.size() - 1).floor : currentFloor; if (shouldAdd) { instructions.add(new LiftInstruction(newFloor, noDirection ? newFloor > lastInstruction : newMovingUp)); callback.accept(toString()); } return distance + Math.abs(newFloor - lastInstruction); } @Override public String toString() { final StringBuilder stringBuilder = new StringBuilder(); instructions.forEach(liftInstruction -> stringBuilder.append("floor_").append(liftInstruction.floor).append("_").append(liftInstruction.movingUp).append(",")); return stringBuilder.toString(); } public static void addInstruction(Level world, BlockPos pos, boolean topHalfClicked) { final BlockEntity blockEntity = world.getBlockEntity(pos); if (!(blockEntity instanceof BlockLiftButtons.TileEntityLiftButtons)) { return; } final int[] currentWeight = {Integer.MAX_VALUE}; final LiftInstructions[] liftInstructionsToUse = {null}; final int[] liftFloorToUse = {0}; final boolean[] liftMovingUpToUse = {false}; final int[] newLiftFloorToUse = {0}; final boolean[] hasButtonOverall = {false, false}; ((BlockLiftButtons.TileEntityLiftButtons) blockEntity).forEachTrackPosition(world, (trackPosition, trackFloorTileEntity) -> { final EntityLift entityLift = trackFloorTileEntity.getEntityLift(); if (entityLift != null) { final int liftFloor = (int) Math.round(entityLift.getY()); final int newLiftFloor = trackPosition.getY(); final boolean[] hasButton = {false, false}; entityLift.hasButton(newLiftFloor, hasButton); final boolean newMovingUp; if (topHalfClicked) { newMovingUp = hasButton[0]; } else { newMovingUp = !hasButton[1]; } final boolean liftMovingUp = entityLift.getLiftDirection() == EntityLift.LiftDirection.UP; final int weight = entityLift.liftInstructions.addInstruction(liftFloor, liftMovingUp, newLiftFloor, newMovingUp, false, false); if (weight >= 0 && (topHalfClicked == newMovingUp && weight < currentWeight[0] || newMovingUp && !hasButtonOverall[0] || !newMovingUp && !hasButtonOverall[1])) { currentWeight[0] = weight; liftInstructionsToUse[0] = entityLift.liftInstructions; liftFloorToUse[0] = liftFloor; liftMovingUpToUse[0] = liftMovingUp; newLiftFloorToUse[0] = newLiftFloor; } if (hasButton[0]) { hasButtonOverall[0] = true; } if (hasButton[1]) { hasButtonOverall[1] = true; } } }); if (liftInstructionsToUse[0] != null) { final boolean newMovingUp; if (topHalfClicked) { newMovingUp = hasButtonOverall[0]; } else { newMovingUp = !hasButtonOverall[1]; } liftInstructionsToUse[0].addInstruction(liftFloorToUse[0], liftMovingUpToUse[0], newLiftFloorToUse[0], newMovingUp, false, true); } } public static String getStringPart(int floor, boolean movingUp) { return "floor_" + floor + "_" + movingUp; } private static class LiftInstruction { private final int floor; private final boolean movingUp; private LiftInstruction(int floor, boolean movingUp) { this.floor = floor; this.movingUp = movingUp; } private boolean canInsert(LiftInstruction previousInstruction, int newFloor, boolean newMovingUp) { if (RailwayData.isBetween(newFloor, previousInstruction.floor, floor) && newMovingUp == movingUp) { return true; } else { return previousInstruction.movingUp != movingUp && previousInstruction.movingUp == (newFloor > previousInstruction.floor); } } @Override public boolean equals(Object object) { return object instanceof LiftInstruction && floor == ((LiftInstruction) object).floor && movingUp == ((LiftInstruction) object).movingUp; } } }
package com.fsck.k9.view; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import android.content.Context; import android.graphics.Typeface; import android.os.Parcel; import android.os.Parcelable; import android.text.SpannableString; import android.text.SpannableStringBuilder; import android.text.TextUtils; import android.text.format.DateUtils; import android.text.style.StyleSpan; import android.util.AttributeSet; import android.util.Log; import android.view.Gravity; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnLongClickListener; import android.widget.CheckBox; import android.widget.LinearLayout; import android.widget.QuickContactBadge; import android.widget.TextView; import android.widget.Toast; import com.fsck.k9.Account; import com.fsck.k9.FontSizes; import com.fsck.k9.K9; import com.fsck.k9.R; import com.fsck.k9.activity.misc.ContactPictureLoader; import com.fsck.k9.helper.ClipboardManager; import com.fsck.k9.helper.ContactPicture; import com.fsck.k9.helper.Contacts; import com.fsck.k9.helper.MessageHelper; import com.fsck.k9.mail.Address; import com.fsck.k9.mail.Flag; import com.fsck.k9.mail.Message; import com.fsck.k9.mail.MessagingException; import com.fsck.k9.mail.internet.MimeUtility; public class MessageHeader extends LinearLayout implements OnClickListener, OnLongClickListener { private Context mContext; private TextView mFromView; private TextView mDateView; private TextView mToView; private TextView mToLabel; private TextView mCcView; private TextView mCcLabel; private TextView mSubjectView; private View mChip; private CheckBox mFlagged; private int defaultSubjectColor; private TextView mAdditionalHeadersView; private View mAnsweredIcon; private View mForwardedIcon; private Message mMessage; private Account mAccount; private FontSizes mFontSizes = K9.getFontSizes(); private Contacts mContacts; private SavedState mSavedState; private MessageHelper mMessageHelper; private ContactPictureLoader mContactsPictureLoader; private QuickContactBadge mContactBadge; private OnLayoutChangedListener mOnLayoutChangedListener; /** * Pair class is only available since API Level 5, so we need * this helper class unfortunately */ private static class HeaderEntry { public String label; public String value; public HeaderEntry(String label, String value) { this.label = label; this.value = value; } } public MessageHeader(Context context, AttributeSet attrs) { super(context, attrs); mContext = context; mContacts = Contacts.getInstance(mContext); } @Override protected void onFinishInflate() { super.onFinishInflate(); mAnsweredIcon = findViewById(R.id.answered); mForwardedIcon = findViewById(R.id.forwarded); mFromView = (TextView) findViewById(R.id.from); mToView = (TextView) findViewById(R.id.to); mToLabel = (TextView) findViewById(R.id.to_label); mCcView = (TextView) findViewById(R.id.cc); mCcLabel = (TextView) findViewById(R.id.cc_label); mContactBadge = (QuickContactBadge) findViewById(R.id.contact_badge); mSubjectView = (TextView) findViewById(R.id.subject); mAdditionalHeadersView = (TextView) findViewById(R.id.additional_headers_view); mChip = findViewById(R.id.chip); mDateView = (TextView) findViewById(R.id.date); mFlagged = (CheckBox) findViewById(R.id.flagged); defaultSubjectColor = mSubjectView.getCurrentTextColor(); mFontSizes.setViewTextSize(mSubjectView, mFontSizes.getMessageViewSubject()); mFontSizes.setViewTextSize(mDateView, mFontSizes.getMessageViewDate()); mFontSizes.setViewTextSize(mAdditionalHeadersView, mFontSizes.getMessageViewAdditionalHeaders()); mFontSizes.setViewTextSize(mFromView, mFontSizes.getMessageViewSender()); mFontSizes.setViewTextSize(mToView, mFontSizes.getMessageViewTo()); mFontSizes.setViewTextSize(mToLabel, mFontSizes.getMessageViewTo()); mFontSizes.setViewTextSize(mCcView, mFontSizes.getMessageViewCC()); mFontSizes.setViewTextSize(mCcLabel, mFontSizes.getMessageViewCC()); mFromView.setOnClickListener(this); mToView.setOnClickListener(this); mCcView.setOnClickListener(this); mFromView.setOnLongClickListener(this); mToView.setOnLongClickListener(this); mCcView.setOnLongClickListener(this); mMessageHelper = MessageHelper.getInstance(mContext); mSubjectView.setVisibility(VISIBLE); hideAdditionalHeaders(); } @Override public void onClick(View view) { switch (view.getId()) { case R.id.from: { onAddSenderToContacts(); break; } case R.id.to: case R.id.cc: { expand((TextView)view, ((TextView)view).getEllipsize() != null); layoutChanged(); } } } @Override public boolean onLongClick(View view) { switch (view.getId()) { case R.id.from: onAddAddressesToClipboard(mMessage.getFrom()); break; case R.id.to: onAddRecipientsToClipboard(Message.RecipientType.TO); break; case R.id.cc: onAddRecipientsToClipboard(Message.RecipientType.CC); break; } return true; } private void onAddSenderToContacts() { if (mMessage != null) { try { final Address senderEmail = mMessage.getFrom()[0]; mContacts.createContact(senderEmail); } catch (Exception e) { Log.e(K9.LOG_TAG, "Couldn't create contact", e); } } } public String createMessage(int addressesCount) { return mContext.getResources().getQuantityString(R.plurals.copy_address_to_clipboard, addressesCount); } private void onAddAddressesToClipboard(Address[] addresses) { StringBuilder addressesToCopy = new StringBuilder(); for (Address addressTemp : addresses) { addressesToCopy.append(addressTemp.getAddress() + " "); } addressesToCopy = addressesToCopy.deleteCharAt(addressesToCopy.length() - 1); ClipboardManager.getInstance(mContext).setText("addresses", addressesToCopy.toString()); Toast.makeText(mContext, createMessage(addresses.length), Toast.LENGTH_LONG).show(); } private void onAddRecipientsToClipboard(Message.RecipientType recipientType) { try { onAddAddressesToClipboard(mMessage.getRecipients(recipientType)); } catch (MessagingException e) { Log.e(K9.LOG_TAG, "Couldn't get recipients address", e); } } public void setOnFlagListener(OnClickListener listener) { mFlagged.setOnClickListener(listener); } public boolean additionalHeadersVisible() { return (mAdditionalHeadersView != null && mAdditionalHeadersView.getVisibility() == View.VISIBLE); } /** * Clear the text field for the additional headers display if they are * not shown, to save UI resources. */ private void hideAdditionalHeaders() { mAdditionalHeadersView.setVisibility(View.GONE); mAdditionalHeadersView.setText(""); } /** * Set up and then show the additional headers view. Called by * {@link #onShowAdditionalHeaders()} * (when switching between messages). */ private void showAdditionalHeaders() { Integer messageToShow = null; try { // Retrieve additional headers List<HeaderEntry> additionalHeaders = getAdditionalHeaders(mMessage); if (!additionalHeaders.isEmpty()) { // Show the additional headers that we have got. populateAdditionalHeadersView(additionalHeaders); mAdditionalHeadersView.setVisibility(View.VISIBLE); } else { // All headers have been downloaded, but there are no additional headers. messageToShow = R.string.message_no_additional_headers_available; } } catch (Exception e) { messageToShow = R.string.message_additional_headers_retrieval_failed; } // Show a message to the user, if any if (messageToShow != null) { Toast toast = Toast.makeText(mContext, messageToShow, Toast.LENGTH_LONG); toast.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL, 0, 0); toast.show(); } } public void populate(final Message message, final Account account) throws MessagingException { final Contacts contacts = K9.showContactName() ? mContacts : null; final CharSequence from = MessageHelper.toFriendly(message.getFrom(), contacts); final CharSequence to = MessageHelper.toFriendly(message.getRecipients(Message.RecipientType.TO), contacts); final CharSequence cc = MessageHelper.toFriendly(message.getRecipients(Message.RecipientType.CC), contacts); Address[] fromAddrs = message.getFrom(); Address[] toAddrs = message.getRecipients(Message.RecipientType.TO); Address[] ccAddrs = message.getRecipients(Message.RecipientType.CC); boolean fromMe = mMessageHelper.toMe(account, fromAddrs); Address counterpartyAddress = null; if (fromMe) { if (toAddrs.length > 0) { counterpartyAddress = toAddrs[0]; } else if (ccAddrs.length > 0) { counterpartyAddress = ccAddrs[0]; } } else if (fromAddrs.length > 0) { counterpartyAddress = fromAddrs[0]; } /* * Only reset visibility of the subject if populate() was called because a new * message is shown. If it is the same, do not force the subject visible, because * this breaks the MessageTitleView in the action bar, which may hide our subject * if it fits in the action bar but is only called when a new message is shown * or the device is rotated. */ if (mMessage == null || mMessage.getId() != message.getId()) { mSubjectView.setVisibility(VISIBLE); } mMessage = message; mAccount = account; if (K9.showContactPicture()) { mContactBadge.setVisibility(View.VISIBLE); mContactsPictureLoader = ContactPicture.getContactPictureLoader(mContext); } else { mContactBadge.setVisibility(View.GONE); } final String subject = message.getSubject(); if (TextUtils.isEmpty(subject)) { mSubjectView.setText(mContext.getText(R.string.general_no_subject)); } else { mSubjectView.setText(subject); } mSubjectView.setTextColor(0xff000000 | defaultSubjectColor); String dateTime = DateUtils.formatDateTime(mContext, message.getSentDate().getTime(), DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL | DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_YEAR); mDateView.setText(dateTime); if (K9.showContactPicture()) { if (counterpartyAddress != null) { mContactBadge.assignContactFromEmail(counterpartyAddress.getAddress(), true); mContactsPictureLoader.loadContactPicture(counterpartyAddress, mContactBadge); } else { mContactBadge.setImageResource(R.drawable.ic_contact_picture); } } mFromView.setText(from); updateAddressField(mToView, to, mToLabel); updateAddressField(mCcView, cc, mCcLabel); mAnsweredIcon.setVisibility(message.isSet(Flag.ANSWERED) ? View.VISIBLE : View.GONE); mForwardedIcon.setVisibility(message.isSet(Flag.FORWARDED) ? View.VISIBLE : View.GONE); mFlagged.setChecked(message.isSet(Flag.FLAGGED)); mChip.setBackgroundColor(mAccount.getChipColor()); setVisibility(View.VISIBLE); if (mSavedState != null) { if (mSavedState.additionalHeadersVisible) { showAdditionalHeaders(); } mSavedState = null; } else { hideAdditionalHeaders(); } } public void onShowAdditionalHeaders() { int currentVisibility = mAdditionalHeadersView.getVisibility(); if (currentVisibility == View.VISIBLE) { hideAdditionalHeaders(); expand(mToView, false); expand(mCcView, false); } else { showAdditionalHeaders(); expand(mToView, true); expand(mCcView, true); } layoutChanged(); } private void updateAddressField(TextView v, CharSequence text, View label) { boolean hasText = !TextUtils.isEmpty(text); v.setText(text); v.setVisibility(hasText ? View.VISIBLE : View.GONE); label.setVisibility(hasText ? View.VISIBLE : View.GONE); } /** * Expand or collapse a TextView by removing or adding the 2 lines limitation */ private void expand(TextView v, boolean expand) { if (expand) { v.setMaxLines(Integer.MAX_VALUE); v.setEllipsize(null); } else { v.setMaxLines(2); v.setEllipsize(android.text.TextUtils.TruncateAt.END); } } private List<HeaderEntry> getAdditionalHeaders(final Message message) throws MessagingException { List<HeaderEntry> additionalHeaders = new LinkedList<HeaderEntry>(); Set<String> headerNames = new LinkedHashSet<String>(message.getHeaderNames()); for (String headerName : headerNames) { String[] headerValues = message.getHeader(headerName); for (String headerValue : headerValues) { additionalHeaders.add(new HeaderEntry(headerName, headerValue)); } } return additionalHeaders; } /** * Set up the additional headers text view with the supplied header data. * * @param additionalHeaders List of header entries. Each entry consists of a header * name and a header value. Header names may appear multiple * times. * <p/> * This method is always called from within the UI thread by * {@link #showAdditionalHeaders()}. */ private void populateAdditionalHeadersView(final List<HeaderEntry> additionalHeaders) { SpannableStringBuilder sb = new SpannableStringBuilder(); boolean first = true; for (HeaderEntry additionalHeader : additionalHeaders) { if (!first) { sb.append("\n"); } else { first = false; } StyleSpan boldSpan = new StyleSpan(Typeface.BOLD); SpannableString label = new SpannableString(additionalHeader.label + ": "); label.setSpan(boldSpan, 0, label.length(), 0); sb.append(label); sb.append(MimeUtility.unfoldAndDecode(additionalHeader.value)); } mAdditionalHeadersView.setText(sb); } @Override public Parcelable onSaveInstanceState() { Parcelable superState = super.onSaveInstanceState(); SavedState savedState = new SavedState(superState); savedState.additionalHeadersVisible = additionalHeadersVisible(); return savedState; } @Override public void onRestoreInstanceState(Parcelable state) { if(!(state instanceof SavedState)) { super.onRestoreInstanceState(state); return; } SavedState savedState = (SavedState)state; super.onRestoreInstanceState(savedState.getSuperState()); mSavedState = savedState; } static class SavedState extends BaseSavedState { boolean additionalHeadersVisible; public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() { @Override public SavedState createFromParcel(Parcel in) { return new SavedState(in); } @Override public SavedState[] newArray(int size) { return new SavedState[size]; } }; SavedState(Parcelable superState) { super(superState); } private SavedState(Parcel in) { super(in); this.additionalHeadersVisible = (in.readInt() != 0); } @Override public void writeToParcel(Parcel out, int flags) { super.writeToParcel(out, flags); out.writeInt((this.additionalHeadersVisible) ? 1 : 0); } } public interface OnLayoutChangedListener { void onLayoutChanged(); } public void setOnLayoutChangedListener(OnLayoutChangedListener listener) { mOnLayoutChangedListener = listener; } private void layoutChanged() { if (mOnLayoutChangedListener != null) { mOnLayoutChangedListener.onLayoutChanged(); } } public void hideSubjectLine() { mSubjectView.setVisibility(GONE); } }
package com.intellij.lang.pratt; import com.intellij.lang.PsiBuilder; import com.intellij.psi.tree.IElementType; import java.util.LinkedList; /** * @author peter */ public class MutableMarker { enum Mode { READY, DROPPED, COMMITTED, ERROR } private final PsiBuilder.Marker myStartMarker; private IElementType myResultType; private int myInitialPathLength; private LinkedList<IElementType> myPath; private Mode myMode; public MutableMarker(final LinkedList<IElementType> path, final PsiBuilder.Marker startMarker, final int initialPathLength) { myPath = path; myStartMarker = startMarker; myInitialPathLength = initialPathLength; myMode = Mode.READY; } public boolean isCommitted() { return myMode == Mode.COMMITTED; } public boolean isDropped() { return myMode == Mode.DROPPED || myMode == Mode.ERROR; } public MutableMarker setResultType(final IElementType resultType) { myResultType = resultType; return this; } public IElementType getResultType() { return myResultType; } public void finish() { assert myMode == Mode.READY; if (myResultType == null) { myMode = Mode.DROPPED; myStartMarker.drop(); } else { myMode = Mode.COMMITTED; myStartMarker.done(myResultType); restorePath(); myPath.addLast(myResultType); } } private void restorePath() { while (myPath.size() > myInitialPathLength) { myPath.removeLast(); } } public MutableMarker precede() { return new MutableMarker(myPath, myStartMarker.precede(), myInitialPathLength); } public void finish(final IElementType type) { setResultType(type); finish(); } public void drop() { assert myMode == Mode.READY; myMode = Mode.DROPPED; myStartMarker.drop(); } public void rollback() { assert myMode == Mode.READY; myMode = Mode.DROPPED; restorePath(); myStartMarker.rollbackTo(); } public void error(final String message) { assert myMode == Mode.READY; myMode = Mode.ERROR; myStartMarker.error(message); } }
// ClassUtils.java package imagej.util; import java.lang.reflect.Constructor; import java.lang.reflect.Field; /** * Useful methods for working with {@link Class} objects and primitive types. * * @author Curtis Rueden */ public final class ClassUtils { private ClassUtils() { // prevent instantiation of utility class } // -- Type conversion and casting -- /** * Converts the given object to an object of the specified type. The object is * casted directly if possible, or else a new object is created using the * destination type's public constructor that takes the original object as * input (except when converting to {@link String}, which uses the * {@link Object#toString()} method instead). In the case of primitive types, * returns an object of the corresponding wrapped type. If the destination * type does not have an appropriate constructor, returns null. * * @param <T> Type to which the object should be converted. * @param value The object to convert. * @param type Type to which the object should be converted. */ public static <T> T convert(final Object value, final Class<T> type) { if (value == null) return getNullValue(type); // ensure type is well-behaved, rather than a primitive type final Class<T> saneType = getNonprimitiveType(type); // cast the existing object, if possible if (canCast(value, saneType)) return cast(value, saneType); // special cases for strings if (value instanceof String) { // source type is String final String s = (String) value; if (s.isEmpty()) { // TODO - only do this for primitive types? or types w/o string ctor? // return null for empty strings return getNullValue(type); } // use first character when converting to Character if (saneType == Character.class) { final Character c = new Character(s.charAt(0)); @SuppressWarnings("unchecked") final T result = (T) c; return result; } } if (saneType == String.class) { // destination type is String; use Object.toString() method final String sValue = value.toString(); @SuppressWarnings("unchecked") final T result = (T) sValue; return result; } // wrap the original object with one of the new type, using a constructor try { final Constructor<T> ctor = saneType.getConstructor(value.getClass()); return ctor.newInstance(value); } catch (final Exception e) { // NB: Many types of exceptions; simpler to handle them all the same. Log.warn("Cannot convert '" + value + "' to " + type.getName(), e); } return null; } /** * Casts the given object to the specified type, or null if the types are * incompatible. */ public static <T> T cast(final Object obj, final Class<T> type) { if (!canCast(obj, type)) return null; @SuppressWarnings("unchecked") final T result = (T) obj; return result; } /** Checks whether the given object can be cast to the specified type. */ public static boolean canCast(final Object obj, final Class<?> type) { return (type.isAssignableFrom(obj.getClass())); } /** * Returns the non-primitive {@link Class} closest to the given type. * <p> * Specifically, the following type conversions are done: * <ul> * <li>boolean.class becomes Boolean.class</li> * <li>byte.class becomes Byte.class</li> * <li>char.class becomes Character.class</li> * <li>double.class becomes Double.class</li> * <li>float.class becomes Float.class</li> * <li>int.class becomes Integer.class</li> * <li>long.class becomes Long.class</li> * <li>short.class becomes Short.class</li> * </ul> * All other types are unchanged. * </p> */ public static <T> Class<T> getNonprimitiveType(final Class<T> type) { final Class<?> destType; if (type == boolean.class) destType = Boolean.class; else if (type == byte.class) destType = Byte.class; else if (type == char.class) destType = Character.class; else if (type == double.class) destType = Double.class; else if (type == float.class) destType = Float.class; else if (type == int.class) destType = Integer.class; else if (type == long.class) destType = Long.class; else if (type == short.class) destType = Short.class; else destType = type; @SuppressWarnings("unchecked") final Class<T> result = (Class<T>) destType; return result; } /** * Gets the "null" value for the given type. For non-primitives, this will * actually be null. For primitives, it will be zero for numeric types, false * for boolean, and the null character for char. */ public static <T> T getNullValue(final Class<T> type) { final Object defaultValue; if (type == boolean.class) defaultValue = false; else if (type == byte.class) defaultValue = (byte) 0; else if (type == char.class) defaultValue = '\0'; else if (type == double.class) defaultValue = 0.0; else if (type == float.class) defaultValue = 0f; else if (type == int.class) defaultValue = 0; else if (type == long.class) defaultValue = 0L; else if (type == short.class) defaultValue = (short) 0; else defaultValue = null; @SuppressWarnings("unchecked") final T result = (T) defaultValue; return result; } // -- Class loading and reflection -- // TODO - split everything except this section into new TypeUtils class /** Loads the class with the given name, or null if it cannot be loaded. */ public static Class<?> loadClass(final String className) { try { return Class.forName(className); } catch (final ClassNotFoundException e) { Log.error("Could not load class: " + className, e); return null; } } /** * Gets the specified field of the given class, or null if it does not exist. */ public static Field getField(final String className, final String fieldName) { // TODO - use getDeclaredField and recursively search final Class<?> c = loadClass(className); if (c == null) return null; try { return c.getField(fieldName); } catch (final NoSuchFieldException e) { Log.error("No such field: " + fieldName, e); return null; } } // TODO - add getMethod method that recursively searches // use new method in AbstractModuleItem#findCallbackMethod /** * Gets the given field's value of the specified object instance, or null if * the value cannot be obtained. */ public static Object getValue(final Field field, final Object instance) { // TODO - rename to getFieldValue if (instance == null) return null; try { return field.get(instance); } catch (final IllegalArgumentException e) { Log.error(e); return null; } catch (final IllegalAccessException e) { Log.error(e); return null; } } /** * Sets the given field's value of the specified object instance. Does nothing * if the value cannot be set. */ public static void setValue(final Field field, final Object instance, final Object value) { // TODO - rename to setFieldValue if (instance == null) return; try { field.setAccessible(true); field.set(instance, convert(value, field.getType())); } catch (final IllegalArgumentException e) { Log.error(e); assert false; } catch (final IllegalAccessException e) { Log.error(e); assert false; } } // -- Type querying -- public static boolean isBoolean(final Class<?> type) { return type == boolean.class || Boolean.class.isAssignableFrom(type); } public static boolean isByte(final Class<?> type) { return type == byte.class || Byte.class.isAssignableFrom(type); } public static boolean isCharacter(final Class<?> type) { return type == char.class || Character.class.isAssignableFrom(type); } public static boolean isDouble(final Class<?> type) { return type == double.class || Double.class.isAssignableFrom(type); } public static boolean isFloat(final Class<?> type) { return type == float.class || Float.class.isAssignableFrom(type); } public static boolean isInteger(final Class<?> type) { return type == int.class || Integer.class.isAssignableFrom(type); } public static boolean isLong(final Class<?> type) { return type == long.class || Long.class.isAssignableFrom(type); } public static boolean isShort(final Class<?> type) { return type == short.class || Short.class.isAssignableFrom(type); } public static boolean isNumber(final Class<?> type) { return Number.class.isAssignableFrom(type) || type == byte.class || type == double.class || type == float.class || type == int.class || type == long.class || type == short.class; } public static boolean isText(final Class<?> type) { return String.class.isAssignableFrom(type) || isCharacter(type); } }
package backend; import java.util.LinkedList; import java.util.Queue; public class FloatPointUnit { public enum OP { ADDD, SUBD, MULD, DIVD, LD, ST }; public enum UnitType { ADD, MULT, MEM }; public static float memory[] = new float[4096]; OperationUnit addUnit = new OperationUnit(3, UnitType.ADD); OperationUnit multUnit = new OperationUnit(2, UnitType.MULT); OperationUnit memUnit = new OperationUnit(6, UnitType.MEM); // OperationUnit stUnit = new OperationUnit(3, UnitType.STORE); Queue<Instruction> instQueue = new LinkedList<Instruction>(); CDB cdb = CDB.getInstance(); public FloatPointUnit() { cdb.setFPU(this); } RegStates regs = RegStates.getInstance(); public void display() { System.out.println(addUnit); System.out.println(multUnit); System.out.println(memUnit); // System.out.println("\n\n\n"); } public String showReserStations() { return addUnit.showContent() + "\n" + multUnit.showContent() + "\n"+ memUnit.showContent(); } public void update() { issueInstruction(); startNewExec();//added choose instr here execute(); writeBack(); display(); System.out.println("update finished"); } public void setReg(int ind, float v) { regs.setReg(ind, v); } public String getRegInfo() { return regs.toString(); } public void setMem(int ind, float v) { memory[ind] = v; } public float getMem(int ind) { return memory[ind]; } public void reset() { RegStates.getInstance().reset(); memory = new float[4096]; addUnit = new OperationUnit(3, UnitType.ADD); multUnit = new OperationUnit(2, UnitType.MULT); memUnit = new OperationUnit(6, UnitType.MEM); instQueue = new LinkedList<Instruction>(); } public boolean finishExcute() { if(!instQueue.isEmpty()) return false; if(!addUnit.finishExcute()) return false; if(!multUnit.finishExcute()) return false; if(!memUnit.finishExcute()) return false; return true; } public void addInstruction(Instruction instruction) { instQueue.add(instruction); } public void issueInstruction() { //Instruction currentI = instQueue.poll(); Instruction currentI = instQueue.peek(); if(currentI == null) return; boolean issueInResult = false; switch (currentI.op) { case ADDD: case SUBD: issueInResult = addUnit.issueInstruction(currentI); break; case MULD: case DIVD: issueInResult = multUnit.issueInstruction(currentI); break; case LD: case ST: issueInResult = memUnit.issueInstruction(currentI); break; default: System.out.println(currentI.op); break; } //System.out.println(issueInResult); if(issueInResult == true) { instQueue.poll(); } // fixed : } private void startNewExec() { addUnit.startNewExec(); multUnit.startNewExec(); memUnit.startNewExec(); } private void execute() { addUnit.execute(); multUnit.execute(); memUnit.execute(); } private void writeBack() { addUnit.writeBack(); multUnit.writeBack(); memUnit.writeBack(); } }
public interface SortElements { public static final int MAIOR = 1; public static final int MENOR = -1; public static final int IGUAL = 0; public void sortItems(Integer[] elementos); }
package com.intuit.karate.template; import com.intuit.karate.graal.JsEngine; import com.intuit.karate.http.ServerConfig; import com.intuit.karate.resource.ResourceResolver; import org.thymeleaf.context.ITemplateContext; import org.thymeleaf.model.IModel; import org.thymeleaf.model.IModelFactory; import org.thymeleaf.model.IProcessableElementTag; /** * * @author pthomas3 */ public class TemplateUtils { private TemplateUtils() { // only static methods } private static final String HTMX_SCRIPT_TAG = "<script src=\"https://unpkg.com/htmx.org@1.4.0\"></script>"; public static IModel generateHeadScriptTag(ITemplateContext ctx) { IModelFactory modelFactory = ctx.getModelFactory(); return modelFactory.parse(ctx.getTemplateData(), HTMX_SCRIPT_TAG); } public static boolean hasAncestorElement(ITemplateContext ctx, String name) { for (IProcessableElementTag tag : ctx.getElementStack()) { if (tag.getElementCompleteName().equalsIgnoreCase(name)) { return true; } } return false; } public static KarateTemplateEngine forServer(ServerConfig config) { KarateTemplateEngine engine = new KarateTemplateEngine(null, new KarateServerDialect(config)); engine.setTemplateResolver(new ServerHtmlTemplateResolver(config.getResourceResolver())); return engine; } public static KarateTemplateEngine forStrings(JsEngine je, ResourceResolver resourceResolver) { KarateTemplateEngine engine = new KarateTemplateEngine(je, new KarateScriptDialect(resourceResolver)); engine.setTemplateResolver(StringHtmlTemplateResolver.INSTANCE); engine.addTemplateResolver(new ResourceHtmlTemplateResolver(resourceResolver)); return engine; } public static KarateTemplateEngine forResourceResolver(JsEngine je, ResourceResolver resourceResolver) { KarateTemplateEngine engine = new KarateTemplateEngine(je, new KarateScriptDialect(resourceResolver)); engine.setTemplateResolver(new ResourceHtmlTemplateResolver(resourceResolver)); return engine; } public static KarateTemplateEngine forResourceRoot(JsEngine je, String root) { return forResourceResolver(je, new ResourceResolver(root)); } public static String renderResourcePath(String path, JsEngine je, ResourceResolver resourceResolver) { KarateEngineContext old = KarateEngineContext.get(); try { KarateTemplateEngine kte = forResourceResolver(je, resourceResolver); return kte.process(path); } finally { KarateEngineContext.set(old); } } public static String renderHtmlString(String html, JsEngine je, ResourceResolver resourceResolver) { KarateEngineContext old = KarateEngineContext.get(); try { KarateTemplateEngine kte = forStrings(je, resourceResolver); return kte.process(html); } finally { KarateEngineContext.set(old); } } }
package com.iptv.player; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.Set; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.DialogInterface.OnDismissListener; import android.graphics.Bitmap; import android.media.MediaPlayer; import android.media.MediaPlayer.OnErrorListener; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.util.Pair; import android.view.KeyEvent; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.GridView; import android.widget.ImageView; import android.widget.MediaController; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.VideoView; import com.iptv.parser.M3UFile; import com.iptv.parser.M3UItem; import com.iptv.parser.M3UToolSet; import com.iptv.utils.BaseActivity; import com.iptv.utils.FileBrowser; import com.iptv.utils.FileBrowser.OnFileSelectedListener; import com.iptv.utils.Interlude; import com.iptv.utils.Interlude.Callback; import com.iptv.utils.Interlude.Task; import com.iptv.utils.MessageBox; import com.iptv.utils.SystemProperties; import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator; import com.nostra13.universalimageloader.core.DisplayImageOptions; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.ImageLoaderConfiguration; import com.nostra13.universalimageloader.core.assist.QueueProcessingType; import com.nostra13.universalimageloader.core.listener.ImageLoadingProgressListener; import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener; public class Player extends BaseActivity { private static final String TAG = "M3U"; private static final boolean DEBUGON = true; private static final String KEY_PATH = "ro.playlist.default"; private static final String DEFAULT_PATH = "/system/etc/playlist.m3u"; private static final String SP_NAME = "data"; private static final String SP_KEY = "path"; private VideoView mVideoView; private RelativeLayout mMenu; private TextView mGroupTitle; private Button mPrevPage; private Button mNextPage; private GridView mGridView; private Button mBrowse; private Button mReset; private AlertDialog mBrowser = null; private ArrayList<Pair<String, ChannelAdapter>> mCatalogs = new ArrayList<Pair<String,ChannelAdapter>>(); private String[] mGroups = null; private int mPosition = 0; private String mCurrentPath = null; private ImageLoader mImgLoader = ImageLoader.getInstance(); private DisplayImageOptions mOpt; private View.OnClickListener mOnClicklistener = new View.OnClickListener() { @Override public void onClick(View v) { if (v == mPrevPage) { prev(); } else if (v == mNextPage) { next(); } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); initViews(); prepareData(loadPath(SystemProperties.get(KEY_PATH, DEFAULT_PATH))); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_MENU) { if (mMenu.getVisibility() != View.VISIBLE) { mMenu.setVisibility(View.VISIBLE); mMenu.requestLayout(); mMenu.requestFocus(); } else { choose(mPosition); } return true; } else if (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_ESCAPE) { if (mMenu.getVisibility() == View.VISIBLE) { mMenu.setVisibility(View.INVISIBLE); return true; } } return super.onKeyDown(keyCode, event); } private void initViews() { mVideoView = (VideoView) findViewById(R.id.video); mMenu = (RelativeLayout) findViewById(R.id.menu_bg); mGroupTitle = (TextView) findViewById(R.id.group_title); mPrevPage = (Button) findViewById(R.id.prev_page); mNextPage = (Button) findViewById(R.id.next_page); mGridView = (GridView) findViewById(R.id.grid); mBrowse = (Button) findViewById(R.id.browse); mReset = (Button) findViewById(R.id.reset); mPrevPage.setOnClickListener(mOnClicklistener); mNextPage.setOnClickListener(mOnClicklistener); mVideoView.setMediaController(new MediaController(this)); mVideoView.setOnErrorListener(new OnErrorListener() { @Override public boolean onError(MediaPlayer mp, int what, int extra) { new MessageBox(Player.this, getString(R.string.error), getString(R.string.error_cannot_play, what), MessageBox.MB_OK); return true; } }); mGridView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { play((M3UItem) ((ChannelAdapter) parent.getAdapter()).getItem(position)); } }); mBrowse.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { browse(); } }); mReset.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { reset(); } }); mOpt = new DisplayImageOptions.Builder() .showImageOnLoading(R.drawable.default_logo) .showImageForEmptyUri(R.drawable.default_logo) .showImageOnFail(R.drawable.default_logo) .cacheInMemory(true) .cacheOnDisk(true) .considerExifParams(true) .bitmapConfig(Bitmap.Config.RGB_565) .build(); ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this) .threadPriority(Thread.NORM_PRIORITY - 2) .denyCacheImageMultipleSizesInMemory() .diskCacheFileNameGenerator(new Md5FileNameGenerator()) .diskCacheSize(50 * 1024 * 1024) // 50 Mb .tasksProcessingOrder(QueueProcessingType.LIFO) .build(); mImgLoader.init(config); } private void prepareData(final String path) { if (path.equals(mCurrentPath)) { return; } final ArrayList<Pair<String, M3UItem[]>> data = new ArrayList<Pair<String,M3UItem[]>>(); Interlude interlude = new Interlude(this, new Task(false) { final HashMap<String, ArrayList<M3UItem>> map = new HashMap<String, ArrayList<M3UItem>>(); @Override public void execute() { M3UFile m3ufile = M3UToolSet.load(path); if (DEBUGON) { Log.d(TAG, "Load [" + path + "]"); Log.d(TAG, m3ufile.toString()); } if (m3ufile.getItems().isEmpty()) { return; } data.add(new Pair<String, M3UItem[]>( getString(R.string.default_catalog), m3ufile.getItems() .toArray(new M3UItem[0]))); for (M3UItem item : m3ufile.getItems()) { if (item.getGroupTitle() != null) { ArrayList<M3UItem> list = null; if (map.containsKey(item.getGroupTitle())) { list = map.get(item.getGroupTitle()); } else { list = new ArrayList<M3UItem>(); map.put(item.getGroupTitle(), list); } list.add(item); } } Set<String> keyset = map.keySet(); for (Iterator<String> it = keyset.iterator(); it.hasNext();) { String key = it.next(); data.add(new Pair<String, M3UItem[]>(key, map.get(key) .toArray(new M3UItem[0]))); } } }); interlude.setCallback(new Callback() { @Override public void onCompleted() { savePath(mCurrentPath = path); ArrayList<String> groups = new ArrayList<String>(); mCatalogs.clear(); for (Pair<String, M3UItem[]> x : data) { mCatalogs.add(new Pair<String, ChannelAdapter>(x.first, new ChannelAdapter(x.second))); groups.add(x.first); } mGroups = groups.toArray(new String[0]); if (mCatalogs.isEmpty()) { new MessageBox(Player.this, getString(R.string.error), getString(R.string.error_empty_playlist2), MessageBox.MB_YESNO, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { browse(); } }, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { finish(); } }); } else { if (mCatalogs.size() == 1) { mPrevPage.setVisibility(View.INVISIBLE); mNextPage.setVisibility(View.INVISIBLE); } else { mPrevPage.setVisibility(View.VISIBLE); mNextPage.setVisibility(View.VISIBLE); } load(0); } } }); interlude.excute(); } private void load(int position) { if (position < 0 || position >= mCatalogs.size()) { return; } Pair<String,ChannelAdapter> info = mCatalogs.get(position); mPosition = position; mGroupTitle.setText(info.first); mGridView.setAdapter(info.second); mMenu.setVisibility(View.VISIBLE); mGridView.requestFocus(); } private void browse() { if (mBrowser == null) { mBrowser = FileBrowser.createFileBrowser(this, "/", ".m3u", new OnFileSelectedListener() { @Override public void onFileSelected(String path) { prepareData(path); if (mBrowser != null && mBrowser.isShowing()) { mBrowser.dismiss(); } } }); mBrowser.setOnDismissListener(new OnDismissListener() { @Override public void onDismiss(DialogInterface dialog) { mBrowse.requestFocus(); } }); } mBrowser.show(); } private void prev() { mPosition if (mPosition < 0) { mPosition = mCatalogs.size() - 1; } load(mPosition); } private void next() { mPosition++; if (mPosition >= mCatalogs.size()) { mPosition = 0; } load(mPosition); } private void play(final M3UItem item) { if (item.getStreamURL() != null) { Interlude loading = new Interlude(this, new Task(false) { @Override public void execute() { mVideoView.stopPlayback(); } }); loading.setCallback(new Callback() { @Override public void onCompleted() { mVideoView.setVideoURI(Uri.parse(item.getStreamURL())); mVideoView.start(); } }); loading.excute(); } else { new MessageBox(this, getString(R.string.error), getString(R.string.error_invalid_url), MessageBox.MB_OK); } } private void choose(final int defaultPos) { new AlertDialog.Builder(this) .setTitle(R.string.title_choose_group) .setSingleChoiceItems(mGroups, defaultPos, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { if (which != defaultPos) { load(which); } dialog.dismiss(); } }).create().show(); } private void reset() { prepareData(SystemProperties.get(KEY_PATH, DEFAULT_PATH)); } private void savePath(String path) { getSharedPreferences(SP_NAME, Context.MODE_PRIVATE).edit() .putString(SP_KEY, path).commit(); } private String loadPath(String defaultPath) { return getSharedPreferences(SP_NAME, Context.MODE_PRIVATE).getString( SP_KEY, defaultPath); } static class ViewHolder { ImageView mLogo; TextView mName; } public class ChannelAdapter extends BaseAdapter { private final M3UItem[] mItems; public ChannelAdapter(M3UItem[] items) { super(); mItems = items; } @Override public int getCount() { return mItems.length; } @Override public Object getItem(int position) { return mItems[position]; } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { final ViewHolder holder; View view = convertView; if (view == null) { view = getLayoutInflater() .inflate(R.layout.item, parent, false); holder = new ViewHolder(); assert view != null; holder.mLogo = (ImageView) view.findViewById(R.id.logo); holder.mName = (TextView) view.findViewById(R.id.name); view.setTag(holder); } else { holder = (ViewHolder) view.getTag(); } mImgLoader.displayImage(mItems[position].getLogoURL(), holder.mLogo, mOpt, new SimpleImageLoadingListener(), new ImageLoadingProgressListener() { @Override public void onProgressUpdate(String imageUri, View view, int current, int total) { } }); holder.mName.setText(mItems[position].getChannelName()); return view; } } }
package com.jme.scene; import java.io.Serializable; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import java.util.Stack; import java.util.logging.Level; import com.jme.bounding.BoundingVolume; import com.jme.math.Vector2f; import com.jme.math.Vector3f; import com.jme.renderer.ColorRGBA; import com.jme.renderer.Renderer; import com.jme.scene.state.RenderState; import com.jme.system.DisplaySystem; import com.jme.system.JmeException; import com.jme.util.LoggingSystem; import com.jme.math.FastMath; /** * <code>Geometry</code> defines a leaf node of the scene graph. The leaf node * contains the geometric data for rendering objects. It manages all rendering * information such as a collection of states and the data for a model. * Subclasses define what the model data is. * * @author Mark Powell * @version $Id: Geometry.java,v 1.45 2004-05-20 18:29:42 renanse Exp $ */ public abstract class Geometry extends Spatial implements Serializable { protected BoundingVolume bound; //data that specifies how to render this leaf. protected Vector3f[] vertex; protected Vector3f[] normal; protected ColorRGBA[] color; protected Vector2f[][] texture; protected int vertQuantity = -1; //buffers that allow for faster data processing. protected transient FloatBuffer colorBuf; protected transient FloatBuffer normBuf; protected transient FloatBuffer vertBuf; protected transient FloatBuffer[] texBuf; private RenderState[] states = new RenderState[RenderState.RS_MAX_STATE]; private boolean useVBOVertex = false; private boolean useVBOTexture = false; private boolean useVBOColor = false; private boolean useVBONormal = false; private int vboVertexID = -1; private int vboColorID = -1; private int vboNormalID = -1; private int[] vboTextureIDs; /** * Empty Constructor to be used internally only. */ public Geometry() { } /** * Constructor instantiates a new <code>Geometry</code> object. This is * the default object which has an empty vertex array. All other data is * null. * * @param name * the name of the scene element. This is required for * identification and comparision purposes. * */ public Geometry(String name) { super(name); vertex = new Vector3f[0]; int textureUnits = DisplaySystem.getDisplaySystem().getRenderer() .getTextureState().getNumberOfUnits(); texture = new Vector2f[textureUnits][0]; texBuf = new FloatBuffer[textureUnits]; vboTextureIDs = new int[textureUnits]; } /** * Constructor creates a new <code>Geometry</code> object. During * instantiation the geometry is set including vertex, normal, color and * texture information. Any part may be null except for the vertex * information. If this is null, an exception will be thrown. * * @param name * the name of the scene element. This is required for * identification and comparision purposes. * @param vertex * the points that make up the geometry. * @param normal * the normals of the geometry. * @param color * the color of each point of the geometry. * @param texture * the texture coordinates of the geometry. */ public Geometry(String name, Vector3f[] vertex, Vector3f[] normal, ColorRGBA[] color, Vector2f[] texture) { super(name); if (vertex == null) { LoggingSystem.getLogger().log(Level.WARNING, "Geometry must" + " include vertex information."); throw new JmeException("Geometry must include vertex information."); } int textureUnits = DisplaySystem.getDisplaySystem().getRenderer() .getTextureState().getNumberOfUnits(); this.texture = new Vector2f[textureUnits][0]; this.texBuf = new FloatBuffer[textureUnits]; this.vboTextureIDs = new int[textureUnits]; this.vertex = vertex; this.vertQuantity = vertex.length; this.normal = normal; this.color = color; this.texture[0] = texture; updateColorBuffer(); updateNormalBuffer(); updateVertexBuffer(); updateTextureBuffer(); } /** * <code>reconstruct</code> reinitializes the geometry with new data. This * will reuse the geometry object. * * @param vertices * the new vertices to use. * @param normal * the new normals to use. * @param color * the new colors to use. * @param texture * the new texture coordinates to use. */ public void reconstruct(Vector3f[] vertices, Vector3f[] normal, ColorRGBA[] color, Vector2f[] texture) { if (vertex == null) { LoggingSystem.getLogger().log(Level.WARNING, "Geometry must" + " include vertex information."); throw new JmeException("Geometry must include vertex information."); } int textureUnits = DisplaySystem.getDisplaySystem().getRenderer() .getTextureState().getNumberOfUnits(); this.texture = new Vector2f[textureUnits][0]; this.texBuf = new FloatBuffer[textureUnits]; this.vertex = vertices; this.normal = normal; this.color = color; this.texture[0] = texture; updateColorBuffer(); updateNormalBuffer(); updateVertexBuffer(); updateTextureBuffer(); } public boolean isVBOVertexEnabled() { return useVBOVertex; } public boolean isVBOTextureEnabled() { return useVBOTexture; } public boolean isVBONormalEnabled() { return useVBONormal; } public boolean isVBOColorEnabled() { return useVBOColor; } public void setVBOVertexEnabled(boolean enabled) { useVBOVertex = enabled; } public void setVBOTextureEnabled(boolean enabled) { useVBOTexture = enabled; } public void setVBONormalEnabled(boolean enabled) { useVBONormal = enabled; } public void setVBOColorEnabled(boolean enabled) { useVBOColor = enabled; } public int getVBOVertexID() { return vboVertexID; } public int getVBOTextureID(int index) { return vboTextureIDs[index]; } public int getVBONormalID() { return vboNormalID; } public int getVBOColorID() { return vboColorID; } public void setVBOVertexID(int id) { vboVertexID = id; } public void setVBOTextureID(int index, int id) { vboTextureIDs[index] = id; } public void setVBONormalID(int id) { vboNormalID = id; } public void setVBOColorID(int id) { vboColorID = id; } /** * <code>getColors</code> returns the color information of the geometry. * This may be null and should be check for such a case. * * @return the color array. */ public ColorRGBA[] getColors() { return color; } /** * <code>setColors</code> sets the color array of this geometry. * * @param color * the new color array. */ public void setColors(ColorRGBA[] color) { if (this.color != null) { if (this.color.length != color.length) { colorBuf = null; } } this.color = color; updateColorBuffer(); } /** * * <code>setSolidColor</code> sets the color array of this geometry to a * single color. * * @param color * the color to set. */ public void setSolidColor(ColorRGBA color) { ColorRGBA colors[] = new ColorRGBA[vertex.length]; for (int x = 0; x < colors.length; x++) colors[x] = (ColorRGBA) color.clone(); setColors(colors); } /** * <code>getColorAsFloatBuffer</code> retrieves the float buffer that * contains this geometry's color information. * * @return the buffer that contains this geometry's color information. */ public FloatBuffer getColorAsFloatBuffer() { return colorBuf; } /** * <code>getVertices</code> returns the vertex array for this geometry. * * @return the array of vertices for this geometry. */ public Vector3f[] getVertices() { return vertex; } /** * <code>setVertices</code> sets the vertices of this geometry. The * vertices may not be null and will throw an exception if so. * * @param vertex * the new vertices of this geometry. */ public void setVertices(Vector3f[] vertex) { if (vertex == null) { throw new JmeException( "Geometry must include vertex information."); } if (this.vertex.length != vertex.length) { vertBuf = null; } this.vertex = vertex; this.vertQuantity = vertex.length; updateVertexBuffer(); } /** * * <code>setVertex</code> sets a single vertex into the vertex array. The * index to set it is given, and due to speed considerations, no bounds * checking is done. Therefore, if an invalid index is given, an * ArrayIndexOutOfBoundsException will be thrown. * * @param index * the index of the vertex to set. * @param value * the vertex to set. */ public void setVertex(int index, Vector3f value) { vertex[index] = value; vertBuf.put(index * 3, value.x); vertBuf.put(index * 3 + 1, value.y); vertBuf.put(index * 3 + 2, value.z); } /** * * <code>setTextureCoord</code> sets a single coord into the texture * array. The index to set it is given, and due to speed considerations, no * bounds checking is done. Therefore, if an invalid index is given, an * ArrayIndexOutOfBoundsException will be thrown. * * @param textureUnit * the textureUnit to set on. * @param index * the index of the coord to set. * @param value * the vertex to set. */ public void setTextureCoord(int textureUnit, int index, Vector2f value) { this.texture[textureUnit][index] = value; } /** * <code>getVerticeAsFloatBuffer</code> returns the float buffer that * contains this geometry's vertex information. * * @return the float buffer that contains this geometry's vertex * information. */ public FloatBuffer getVerticeAsFloatBuffer() { return vertBuf; } /** * <code>getNormals</code> returns the array that contains this geometry's * normal information. * * @return the normal array for this geometry. */ public Vector3f[] getNormals() { return normal; } /** * <code>setNormals</code> sets this geometry's normals to a new array of * normal values. * * @param normal * the new normal values. */ public void setNormals(Vector3f[] normal) { if (this.normal != null) { if (this.normal.length != normal.length) { normBuf = null; } } this.normal = normal; updateNormalBuffer(); } /** * * <code>setNormal</code> sets a single normal into the normal array. The * index to set it is given, and due to speed considerations, no bounds * checking is done. Therefore, if an invalid index is given, an * ArrayIndexOutOfBoundsException will be thrown. * * @param index * the index of the normal to set. * @param value * the normal to set. */ public void setNormal(int index, Vector3f value) { normal[index] = value; normBuf.put(index * 3, value.x); normBuf.put(index * 3 + 1, value.y); normBuf.put(index * 3 + 2, value.z); } /** * <code>getNormalAsFloatBuffer</code> retrieves this geometry's normal * information as a float buffer. * * @return the float buffer containing the geometry information. */ public FloatBuffer getNormalAsFloatBuffer() { return normBuf; } /** * <code>getTextures</code> retrieves the texture array that contains this * geometry's texture information. The texture coordinates are those of the * first texture unit. * * @return the array that contains the geometry's texture information. */ public Vector2f[] getTextures() { return texture[0]; } /** * * <code>getTextures</code> retrieves the texture array that contains this * geometry's texture information for a given texture unit. If the texture * unit is invalid, or no texture coordinates are set for the texture unit, * null is returned. * * @param textureUnit * the texture unit to retrieve the coordinates for. * @return the texture coordinates of a given texture unit. Null is returned * if the texture unit is not valid, or no coordinates are set for * the given unit. */ public Vector2f[] getTextures(int textureUnit) { if (textureUnit >= 0 && textureUnit < texture.length) { return texture[textureUnit]; } else { return null; } } /** * <code>setTextures</code> sets this geometry's texture array to a new * array. * * @param texture * the new texture information for this geometry. */ public void setTextures(Vector2f[] texture) { if (this.texture != null) { if (this.texture[0].length != texture.length) { texBuf[0] = null; } } this.texture[0] = texture; updateTextureBuffer(); } /** * * <code>setTextures</code> sets the texture coordinates of a given * texture unit. If the texture unit is not valid, then the coordinates are * ignored. * * @param textures * the coordinates to set. * @param textureUnit * the texture unit to set them to. */ public void setTextures(Vector2f[] textures, int textureUnit) { if (textureUnit < 0 || textureUnit >= this.texture.length) { return; } if (this.texture != null) { if (this.texture[textureUnit].length != texture.length) { texBuf[textureUnit] = null; } } this.texture[textureUnit] = textures; updateTextureBuffer(textureUnit); } /** * * <code>setTexture</code> sets a single texture coordinate into the * texture array. The index to set it is given, and due to speed * considerations, no bounds checking is done. Therefore, if an invalid * index is given, an ArrayIndexOutOfBoundsException will be thrown. * * @param index * the index of the texture coordinate to set. * @param value * the texture coordinate to set. */ public void setTexture(int index, Vector2f value) { texture[0][index] = value; texBuf[0].put(index * 2, value.x); texBuf[0].put(index * 2 + 1, value.y); } /** * * <code>setTexture</code> sets a single texture coordinate into the * texture array. The index to set it is given, and due to speed * considerations, no bounds checking is done. Therefore, if an invalid * index is given, an ArrayIndexOutOfBoundsException will be thrown. * * @param index * the index of the texture coordinate to set. * @param value * the texture coordinate to set. * @param textureUnit * the texture unit to alter. */ public void setTexture(int index, Vector2f value, int textureUnit) { texture[textureUnit][index] = value; texBuf[textureUnit].put(index * 2, value.x); texBuf[textureUnit].put(index * 2 + 1, value.y); } /** * * <code>copyTextureCoords</code> copys the texture coordinates of a given * texture unit to another location. If the texture unit is not valid, then * the coordinates are ignored. * * @param fromIndex * the coordinates to copy. * @param toIndex * the texture unit to set them to. */ public void copyTextureCoords(int fromIndex, int toIndex) { if (fromIndex < 0 || fromIndex >= this.texture.length) { return; } if (toIndex < 0 || toIndex >= this.texture.length) { return; } if (this.texture != null) { if (this.texture[fromIndex].length != texture.length) { texBuf[toIndex] = null; } } this.texture[toIndex] = (Vector2f[]) texture[fromIndex].clone(); updateTextureBuffer(toIndex); } /** * <code>getTextureAsFloatBuffer</code> retrieves this geometry's texture * information contained within a float buffer. * * @return the float buffer that contains this geometry's texture * information. */ public FloatBuffer getTextureAsFloatBuffer() { return texBuf[0]; } /** * * <code>getTextureAsFloatBuffer</code> retrieves the texture buffer of a * given texture unit. If the texture unit is not valid, null is returned. * * @param textureUnit * the texture unit to check. * @return the texture coordinates at the given texture unit. */ public FloatBuffer getTextureAsFloatBuffer(int textureUnit) { return texBuf[textureUnit]; } /** * * <code>getNumberOfUnits</code> returns the number of texture units this * geometry supports. * * @return the number of texture units supported by the geometry. */ public int getNumberOfUnits() { return texBuf.length; } public int getVertQuantity() { return vertQuantity; } public void setAllTextures(Vector2f[][] texture) { this.texture = texture; } public Vector2f[][] getAllTextures() { return texture; } public void clearBuffers() { int textureUnits = DisplaySystem.getDisplaySystem().getRenderer() .getTextureState().getNumberOfUnits(); vertBuf = null; normBuf = null; this.texBuf = new FloatBuffer[textureUnits]; colorBuf = null; } /** * <code>updateBound</code> recalculates the bounding object assigned to * the geometry. This resets it parameters to adjust for any changes to the * vertex information. * */ public void updateModelBound() { if (bound != null) { bound.computeFromPoints(vertex); updateWorldBound(); } } /** * * <code>getModelBound</code> retrieves the bounding object that contains * the geometry node's vertices. * * @return the bounding object for this geometry. */ public BoundingVolume getModelBound() { return bound; } /** * * <code>setModelBound</code> sets the bounding object for this geometry. * * @param modelBound * the bounding object for this geometry. */ public void setModelBound(BoundingVolume modelBound) { this.bound = modelBound; } /** * * <code>setStates</code> applies all the render states for this * particular geometry. * */ public void applyStates() { if (parent != null) Spatial.clearCurrentStates(); for (int i = 0; i < states.length; i++) { if (states[i] != currentStates[i]) { states[i].apply(); currentStates[i] = states[i]; } } } /** * <code>draw</code> prepares the geometry for rendering to the display. * The renderstate is set and the subclass is responsible for rendering the * actual data. * * @see com.jme.scene.Spatial#draw(com.jme.renderer.Renderer) * @param r * the renderer that displays to the context. */ public void draw(Renderer r) { applyStates(); } /** * <code>drawBounds</code> calls super to set the render state then passes * itself to the renderer. * * @param r * the renderer to display */ public void drawBounds(Renderer r) { } /** * <code>updateWorldBound</code> updates the bounding volume that contains * this geometry. The location of the geometry is based on the location of * all this node's parents. * * @see com.jme.scene.Spatial#updateWorldBound() */ public void updateWorldBound() { if (bound != null) { worldBound = bound.transform(worldRotation, worldTranslation, worldScale, worldBound); } } /** * <code>applyRenderState</code> determines if a particular render state * is set for this Geometry. If not, the default state will be used. */ protected void applyRenderState(Stack[] states) { for (int x = 0; x < states.length; x++) { if (states[x].size() > 0) { this.states[x] = ((RenderState) states[x].peek()).extract( states[x], this); } else { this.states[x] = (RenderState) defaultStateList[x]; } } } /** * <code>setColorBuffer</code> calculates the <code>FloatBuffer</code> * that contains all the color information of this geometry. * */ public void updateColorBuffer() { if (color == null) { return; } int bufferLength; if (vertQuantity >= 0) bufferLength = vertQuantity * 4; else bufferLength = vertex.length * 4; if (colorBuf == null || colorBuf.capacity() < (4 * bufferLength)) { colorBuf = ByteBuffer.allocateDirect(4 * bufferLength).order( ByteOrder.nativeOrder()).asFloatBuffer(); } colorBuf.clear(); ColorRGBA tempColor; for (int i = 0, max = bufferLength>>2; i < max; i++) { tempColor = color[i]; if (tempColor != null) { colorBuf.put(tempColor.r).put(tempColor.g) .put(tempColor.b).put(tempColor.a); } } colorBuf.flip(); } /** * <code>updateVertexBuffer</code> sets the float buffer that contains * this geometry's vertex information. * */ public void updateVertexBuffer() { if (vertex == null) { return; } int bufferLength; if (vertQuantity >= 0) bufferLength = vertQuantity * 3; else bufferLength = vertex.length * 3; if (vertBuf == null || vertBuf.capacity() < (4 * bufferLength)) { vertBuf = ByteBuffer.allocateDirect(4 * bufferLength).order( ByteOrder.nativeOrder()).asFloatBuffer(); } vertBuf.clear(); Vector3f tempVect; for (int i = 0, endPoint = bufferLength / 3; i < endPoint; i++) { tempVect = vertex[i]; if (tempVect != null) { vertBuf.put(tempVect.x).put(tempVect.y).put(tempVect.z); } } vertBuf.flip(); } /** * <code>updateNormalBuffer</code> sets the float buffer that contains * this geometry's normal information. * */ public void updateNormalBuffer() { if (normal == null) { return; } int bufferLength; if (vertQuantity >= 0) bufferLength = vertQuantity * 3; else bufferLength = vertex.length * 3; if (normBuf == null || normBuf.capacity() < (4 * bufferLength)) { normBuf = ByteBuffer.allocateDirect(4 * bufferLength).order( ByteOrder.nativeOrder()).asFloatBuffer(); } normBuf.clear(); Vector3f tempVect; for (int i = 0, endPoint = bufferLength / 3; i < endPoint; i++) { tempVect = normal[i]; if (tempVect != null) { normBuf.put(tempVect.x).put(tempVect.y).put(tempVect.z); } } normBuf.flip(); } /** * <code>updateTextureBuffer</code> sets the float buffer that contains * this geometry's texture information. Updates textureUnit 0. * */ public void updateTextureBuffer() { updateTextureBuffer(0); } /** * <code>updateTextureBuffer</code> sets the float buffer that contains * this geometry's texture information. * */ public void updateTextureBuffer(int textureUnit) { if (texture == null) { return; } if (texture[textureUnit] == null) { return; } int bufferLength; if (vertQuantity >= 0) bufferLength = vertQuantity * 2; else bufferLength = vertex.length * 2; if (texBuf[textureUnit] == null || texBuf[textureUnit].capacity() < (4 * bufferLength)) { texBuf[textureUnit] = ByteBuffer.allocateDirect(4 * bufferLength) .order(ByteOrder.nativeOrder()).asFloatBuffer(); } texBuf[textureUnit].clear(); Vector2f tempVect; for (int i = 0, max = bufferLength>>1; i < max; i++) { tempVect = texture[textureUnit][i]; if (tempVect != null) { texBuf[textureUnit].put(tempVect.x).put(tempVect.y); } } texBuf[textureUnit].flip(); } /** * <code>randomVertice</code> returns a random vertex from the list of * vertices set to this geometry. If there are no vertices set, null is * returned. * * @return Vector3f a random vertex from the vertex list. Null is returned * if the vertex list is not set. */ public Vector3f randomVertice() { if (vertex == null) return null; int i = (int) (FastMath.nextRandomFloat() * vertQuantity); return worldRotation.mult(vertex[i]).addLocal(worldTranslation); } }
package com.tilegenerator; import java.awt.EventQueue; import java.awt.Font; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import javax.swing.JFileChooser; import javax.swing.UIManager; import javax.swing.GroupLayout; import javax.swing.GroupLayout.Alignment; import javax.swing.JLabel; import javax.swing.LayoutStyle.ComponentPlacement; import javax.swing.JTextField; import javax.swing.JSpinner; import javax.swing.SpinnerNumberModel; import javax.swing.JButton; import com.tilegenerator.Generator; public class Main extends JFrame implements ActionListener{ private JPanel contentPane; private JTextField tTop; private JTextField tBot; private JTextField tLeft; private JTextField tRight; private JSpinner spinner; private String resizedFileLocation=""; private String resultDir=""; private String fileLocation=""; JButton bDo; private final JLabel lbIn; private final JLabel lbOut; public static void main(String[] args) { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Throwable e) { e.printStackTrace(); } EventQueue.invokeLater(new Runnable() { public void run() { try { Main frame = new Main(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } public Main() { final JFrame frame = new JFrame(); setTitle("Map Tile Generator"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 512, 358); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); JLabel lDown = new JLabel("D\u00F3\u0142:"); lDown.setFont(new Font("Tahoma", Font.PLAIN, 15)); tTop = new JTextField(); tTop.setText("0.00"); tTop.setColumns(10); tTop.addActionListener(this); tBot = new JTextField(); tBot.setText("0.00"); tBot.setColumns(10); tBot.addActionListener(this); JLabel lLeft = new JLabel("Lewo:"); lLeft.setFont(new Font("Tahoma", Font.PLAIN, 15)); JLabel lRight = new JLabel("Prawo:"); lRight.setFont(new Font("Tahoma", Font.PLAIN, 15)); tLeft = new JTextField(); tLeft.setText("0.00"); tLeft.setColumns(10); tLeft.addActionListener(this); tRight = new JTextField(); tRight.setText("0.00"); tRight.setColumns(10); JLabel lTop = new JLabel("G\u00F3ra:"); lTop.setFont(new Font("Tahoma", Font.PLAIN, 15)); spinner = new JSpinner(); spinner.setModel(new SpinnerNumberModel(16, 16, 22, 1)); JLabel lAppro = new JLabel("Przyblienie"); lAppro.setFont(new Font("Tahoma", Font.PLAIN, 15)); lbIn = new JLabel("C:\\Test"); lbOut = new JLabel("D:\\Test"); JButton bInput = new JButton("Podaj plik wejciowy"); bInput.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { JFileChooser j = new JFileChooser(); Integer opt = j.showSaveDialog(frame); lbIn.setText(j.getSelectedFile().getAbsolutePath()); } }); JButton bOutput = new JButton("Podaj folder wyjciowy"); bOutput.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { JFileChooser j = new JFileChooser(); j.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); Integer opt = j.showSaveDialog(frame); lbOut.setText(j.getSelectedFile().getAbsolutePath()); } }); bDo = new JButton("Wykonaj"); bDo.addActionListener(this); GroupLayout gl_contentPane = new GroupLayout(contentPane); gl_contentPane.setHorizontalGroup( gl_contentPane.createParallelGroup(Alignment.TRAILING) .addGroup(gl_contentPane.createSequentialGroup() .addGroup(gl_contentPane.createParallelGroup(Alignment.TRAILING) .addGroup(gl_contentPane.createSequentialGroup() .addGap(8) .addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING, false) .addGroup(gl_contentPane.createSequentialGroup() .addComponent(lTop, GroupLayout.PREFERRED_SIZE, 56, GroupLayout.PREFERRED_SIZE) .addPreferredGap(ComponentPlacement.UNRELATED) .addComponent(tTop, 0, 0, Short.MAX_VALUE)) .addGroup(gl_contentPane.createSequentialGroup() .addComponent(lDown, GroupLayout.PREFERRED_SIZE, 61, GroupLayout.PREFERRED_SIZE) .addPreferredGap(ComponentPlacement.RELATED) .addComponent(tBot, GroupLayout.PREFERRED_SIZE, 86, GroupLayout.PREFERRED_SIZE)))) .addGroup(gl_contentPane.createSequentialGroup() .addGap(24) .addGroup(gl_contentPane.createParallelGroup(Alignment.TRAILING) .addComponent(bOutput, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(bInput, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 143, Short.MAX_VALUE)) .addPreferredGap(ComponentPlacement.RELATED))) .addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING) .addGroup(gl_contentPane.createSequentialGroup() .addGap(10) .addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING) .addComponent(lLeft) .addComponent(lRight)) .addGap(4) .addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING) .addGroup(gl_contentPane.createSequentialGroup() .addComponent(tRight, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addGap(18) .addComponent(lAppro)) .addComponent(tLeft, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)) .addGap(18) .addComponent(spinner, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)) .addGroup(gl_contentPane.createSequentialGroup() .addGap(18) .addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING) .addComponent(lbOut, GroupLayout.PREFERRED_SIZE, 215, GroupLayout.PREFERRED_SIZE) .addComponent(lbIn, GroupLayout.DEFAULT_SIZE, 254, Short.MAX_VALUE)))) .addContainerGap()) .addGroup(gl_contentPane.createSequentialGroup() .addContainerGap(101, Short.MAX_VALUE) .addComponent(bDo, GroupLayout.PREFERRED_SIZE, 293, GroupLayout.PREFERRED_SIZE) .addGap(92)) ); gl_contentPane.setVerticalGroup( gl_contentPane.createParallelGroup(Alignment.LEADING) .addGroup(gl_contentPane.createSequentialGroup() .addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING) .addGroup(gl_contentPane.createSequentialGroup() .addGap(26) .addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING) .addComponent(lTop) .addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE) .addComponent(tTop, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(lLeft) .addComponent(tLeft, GroupLayout.PREFERRED_SIZE, 18, GroupLayout.PREFERRED_SIZE))) .addGap(8) .addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE) .addComponent(lDown, GroupLayout.PREFERRED_SIZE, 30, GroupLayout.PREFERRED_SIZE) .addComponent(tBot, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(tRight, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(lRight))) .addGroup(gl_contentPane.createSequentialGroup() .addGap(29) .addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE) .addComponent(lAppro) .addComponent(spinner, GroupLayout.PREFERRED_SIZE, 58, GroupLayout.PREFERRED_SIZE)))) .addGap(38) .addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE) .addComponent(bInput, GroupLayout.PREFERRED_SIZE, 29, GroupLayout.PREFERRED_SIZE) .addComponent(lbIn, GroupLayout.PREFERRED_SIZE, 27, GroupLayout.PREFERRED_SIZE)) .addGap(28) .addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE) .addComponent(bOutput, GroupLayout.PREFERRED_SIZE, 28, GroupLayout.PREFERRED_SIZE) .addComponent(lbOut, GroupLayout.PREFERRED_SIZE, 27, GroupLayout.PREFERRED_SIZE)) .addGap(39) .addComponent(bDo, GroupLayout.PREFERRED_SIZE, 50, GroupLayout.PREFERRED_SIZE) .addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); contentPane.setLayout(gl_contentPane); } public void actionPerformed(ActionEvent e) { Object source = e.getSource(); if(source== bDo){ long start = System.currentTimeMillis(); double topLat = Double.parseDouble(tTop.getText()); double leftLng = Double.parseDouble(tLeft.getText()); double bottomLat = Double.parseDouble(tBot.getText()); double rightLng = Double.parseDouble(tRight.getText()); Integer zoom = (Integer) spinner.getValue(); fileLocation=lbIn.getText(); resizedFileLocation=lbOut.getText()+"\\source-resized.png"; resultDir=lbOut.getText(); Generator generator = new Generator(); generator.setMapImageLocation(fileLocation); generator.setResizedMapImageLocation(resizedFileLocation); generator.setResultDir(resultDir); generator.setLeftTopLat(topLat); generator.setLeftTopLng(leftLng); generator.setRightBottomLat(bottomLat); generator.setRightBottomLng(rightLng); generator.setZoom(zoom); try { generator.generateTiles(); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } System.out.println("Zakoczono.\nCzas trwania: " + (System.currentTimeMillis() - start) + "ms"); } } }
package com.ui; import java.awt.BorderLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JEditorPane; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.SwingUtilities; import javax.swing.UIManager; import main.java.google.pagerank.PageRank; import com.main.ExcelOperator; import com.main.TextOperator; public class FileChooserDemo extends JPanel implements ActionListener { static private final String newline = "\n"; JButton mOpenButton, mCheckButton; JTextArea log; JFileChooser fc; JEditorPane mEditText; public FileChooserDemo() { super(new BorderLayout()); //Create the log first, because the action listeners //need to refer to it. log = new JTextArea(5,20); log.setMargin(new Insets(5,5,5,5)); log.setEditable(false); JScrollPane logScrollPane = new JScrollPane(log); //Create a file chooser fc = new JFileChooser(); //Uncomment one of the following lines to try a different //file selection mode. The first allows just directories //to be selected (and, at least in the Java look and feel, //shown). The second allows both files and directories //to be selected. If you leave these lines commented out, //then the default mode (FILES_ONLY) will be used. //fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); //fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); //Create the open button. We use the image from the JLF //Graphics Repository (but we extracted it from the jar). mOpenButton = new JButton("Open a File..."); mOpenButton.addActionListener(this); mCheckButton = new JButton("Check PR"); mCheckButton.addActionListener(this); //For layout purposes, put the buttons in a separate panel JPanel buttonPanel = new JPanel(); //use FlowLayout mEditText = new JEditorPane(); buttonPanel.add(mEditText); buttonPanel.add(mCheckButton); buttonPanel.add(mOpenButton); //Add the buttons and the log to this panel. add(buttonPanel, BorderLayout.PAGE_START); add(logScrollPane, BorderLayout.CENTER); } public void actionPerformed(ActionEvent e) { //Handle open button action. if (e.getSource() == mOpenButton) { int returnVal = fc.showOpenDialog(FileChooserDemo.this); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); //This is where a real application would open the file. String fileName = file.getName(); log.append("Opening: " + fileName + "." + newline); // only text files or excel files if (fileName.endsWith("txt")) { TextOperator text = new TextOperator(file.toString()); text.getPageRank(); } else if (fileName.endsWith("xlsx")) { ExcelOperator excel = new ExcelOperator(file.toString()); excel.getPageRank(); } else { JOptionPane.showMessageDialog(null, "Not Supported !"); } } else { log.append("Open command cancelled by user." + newline); } log.setCaretPosition(log.getDocument().getLength()); } else if (e.getSource() == mCheckButton) { String url = mEditText.getText(); String tmpURL = url; if (url != null && !url.equals("")) { if (!url.startsWith("http")) { tmpURL = "http://" + url; } int pageRank = PageRank.get(tmpURL); log.append(url + ": PR = " + pageRank + newline); } } } /** Returns an ImageIcon, or null if the path was invalid. */ protected static ImageIcon createImageIcon(String path) { java.net.URL imgURL = FileChooserDemo.class.getResource(path); if (imgURL != null) { return new ImageIcon(imgURL); } else { System.err.println("Couldn't find file: " + path); return null; } } /** * Create the GUI and show it. For thread safety, * this method should be invoked from the * event dispatch thread. */ private static void createAndShowGUI() { //Create and set up the window. JFrame frame = new JFrame("FileChooserDemo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Add content to the window. frame.add(new FileChooserDemo()); //Display the window. frame.pack(); frame.setVisible(true); } public static void main(String[] args) { //Schedule a job for the event dispatch thread: //creating and showing this application's GUI. SwingUtilities.invokeLater(new Runnable() { public void run() { //Turn off metal's use of bold fonts UIManager.put("swing.boldMetal", Boolean.FALSE); createAndShowGUI(); } }); } }
package hm.binkley.util.logging.osi; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.contrib.java.lang.system.ProvideSystemProperty; import org.junit.contrib.java.lang.system.StandardErrorStreamLog; import org.junit.contrib.java.lang.system.StandardOutputStreamLog; import static hm.binkley.util.logging.LoggerUtil.refreshLogback; import static hm.binkley.util.logging.osi.OSI.SystemProperty.LOGBACK_CONFIGURATION_FILE; import static hm.binkley.util.logging.osi.OSI.SystemProperty.LOGBACK_INCLUDED_RESOURCE; import static hm.binkley.util.logging.osi.SupportLoggers.ALERT; import static hm.binkley.util.logging.osi.SupportLoggers.APPLICATION; import static hm.binkley.util.logging.osi.SupportLoggers.AUDIT; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.isEmptyString; import static org.junit.Assert.assertThat; /** * {@code ITSupportLoggers} integration tests {@link SupportLoggers}. * * @author <a href="mailto:binkley@alumni.rice.edu">B. K. Oxley</a> */ public final class ITSupportLoggers { @Rule public final StandardOutputStreamLog sout = new StandardOutputStreamLog(); @Rule public final StandardErrorStreamLog serr = new StandardErrorStreamLog(); @Rule public final ProvideSystemProperty osi = new ProvideSystemProperty( LOGBACK_CONFIGURATION_FILE.key(), "osi-logback.xml"); @Rule public final ProvideSystemProperty included = new ProvideSystemProperty( LOGBACK_INCLUDED_RESOURCE.key(), "osi-support-loggers-included.xml"); @Before public void setUp() { refreshLogback(); } @Test public void applicationShouldLogNormally() { APPLICATION.getLogger("test").error("Ignored"); assertThat(sout.getLog(), containsString("Ignored")); } @Test public void alertShouldSayWarnOnStderr() { ALERT.getLogger("alert").warn("Ignored"); assertThat(serr.getLog(), containsString("ALERT/WARN")); } @Test public void alertShouldIncludeNonAlertLoggerName() { ALERT.getLogger("test").warn("Ignored"); assertThat(serr.getLog(), containsString("ALERT/WARN")); } @Test public void alertShouldDuplicateOnStdout() { ALERT.getLogger("alert").warn("Ignored"); assertThat(sout.getLog(), containsString("ALERT/WARN")); } @Test(expected = IllegalStateException.class) public void alertShouldComplainWithInfo() { ALERT.getLogger("test").info("Ignored"); } @Test public void auditShouldSayInfoOnStdout() { AUDIT.getLogger("audit").info("Ignored"); assertThat(sout.getLog(), containsString("AUDIT/INFO")); } @Test public void auditShouldIncludeNonAuditLoggerName() { AUDIT.getLogger("test").info("Ignored"); assertThat(sout.getLog(), containsString("AUDIT/INFO")); } @Test public void auditShouldSayNothingOnStderr() { AUDIT.getLogger("test").info("Ignored"); assertThat(serr.getLog(), isEmptyString()); } @Test(expected = IllegalStateException.class) public void auditShouldComplainWithDebug() { AUDIT.getLogger("test").debug("Ignored"); } }
package ru.stqa.pft.mantis.appmanager; import org.apache.commons.net.ftp.FTPClient; import java.io.File; import java.io.FileInputStream; import java.io.IOException; public class FtpHelper { private final ApplicationManager app; private FTPClient ftp; public FtpHelper(ApplicationManager app) { this.app = app; ftp = new FTPClient(); } public void upload(File file, String target, String backup) throws IOException { ftp.connect(app.getProperty("ftp.host")); ftp.login(app.getProperty("ftp.login"), app.getProperty("ftp.password")); ftp.deleteFile(backup); ftp.rename(target, backup); ftp.enterLocalPassiveMode(); ftp.storeFile(target, new FileInputStream(file)); ftp.disconnect(); } public void restore(String backup, String target) throws IOException { ftp.connect(app.getProperty("ftp.host")); ftp.login(app.getProperty("ftp.login"), app.getProperty("ftp.password")); ftp.deleteFile(target); ftp.rename(backup, target); ftp.disconnect(); } }
package dae.gui.tools; import com.jme3.asset.AssetManager; import com.jme3.bounding.BoundingBox; import com.jme3.bounding.BoundingVolume; import com.jme3.bounding.BoundingVolume.Type; import com.jme3.collision.CollisionResult; import com.jme3.collision.CollisionResults; import com.jme3.font.BitmapFont; import com.jme3.font.BitmapText; import com.jme3.input.InputManager; import com.jme3.input.event.MouseMotionEvent; import com.jme3.material.Material; import com.jme3.math.ColorRGBA; import com.jme3.math.Matrix4f; import com.jme3.math.Quaternion; import com.jme3.math.Ray; import com.jme3.math.Vector2f; import com.jme3.math.Vector3f; import com.jme3.renderer.Camera; import com.jme3.scene.Geometry; import com.jme3.scene.Node; import com.jme3.scene.debug.WireBox; import dae.GlobalObjects; import dae.components.TransformComponent; import dae.gui.SandboxViewport; import dae.prefabs.Prefab; import dae.prefabs.shapes.LineShape; import dae.prefabs.shapes.QuadShape; import dae.prefabs.ui.events.LevelEvent; import dae.prefabs.ui.events.LevelEvent.EventType; import dae.project.Layer; import dae.project.Level; import dae.project.ProjectTreeNode; /** * * @author Koen Samyn */ public class LinkTool extends ViewportTool { /** * Used for linking objects. */ private Geometry linkGeometry; private LineShape linkShape; private BitmapText linkText; private QuadShape textBackground; private Geometry textBackgroundGeometry; /** * Used to highlight the parent */ private final WireBox wireBoxLinkParent = new WireBox(); private Geometry wireBoxGeometryLinkParent; private Material wireBoxMaterial; /** * Internal link tool state. */ private enum LinkState { LINK, LINKPARENT }; private LinkState linkState = LinkState.LINK; /** * The current child element for linking. */ private Prefab currentChildElement; /** * Creates a new link tool. */ public LinkTool() { super("LinkTool"); } /** * Initializes the link tool. * * @param assetManager the asset manager to load objects from. * @param inputManager the input manager object. */ @Override public void initialize(AssetManager assetManager, InputManager inputManager) { // helper objects for linking linkShape = new LineShape(Vector3f.ZERO, Vector3f.ZERO); linkGeometry = new Geometry("link", linkShape); wireBoxMaterial = assetManager.loadMaterial("Materials/LinkMaterial.j3m"); linkGeometry.setMaterial(wireBoxMaterial); wireBoxGeometryLinkParent = new Geometry("linked parent", wireBoxLinkParent); wireBoxGeometryLinkParent.setMaterial(assetManager.loadMaterial("Materials/LinkParentMaterial.j3m")); BitmapFont guiFont = assetManager.loadFont("Interface/Fonts/Default.fnt"); linkText = new BitmapText(guiFont, false); linkText.setSize(guiFont.getCharSet().getRenderedSize()); //linkText.setAlpha(.5f); //linkText.setMaterial(assetManager.loadMaterial("Materials/LinkParentMaterial.j3m")); linkText.setColor(new ColorRGBA(1, 1, 1, 1)); linkText.setText(""); this.textBackground = new QuadShape(1, 1); this.textBackgroundGeometry = new Geometry("linktext", textBackground); textBackgroundGeometry.setMaterial(assetManager.loadMaterial("Materials/LinkTextBackgroundMaterial.j3m")); //linkText.setQueueBucket(RenderQueue.Bucket.Transparent); //textBackgroundGeometry.setQueueBucket(RenderQueue.Bucket.Transparent); } /** * Activates the tool in the viewport. * * @param viewport the viewport to activate the tool in. */ @Override public void activate(SandboxViewport viewport) { viewport.clearSelection(); linkState = LinkState.LINK; viewport.attachGuiElement(linkText); viewport.attachGuiElement(textBackgroundGeometry); setActive(); viewport.disableFlyCam(); } /** * Deactivate the tool in the viewport. * * @param viewport the viewport to deactivate the tool in. */ @Override public void deactivate(SandboxViewport viewport) { linkText.removeFromParent(); textBackgroundGeometry.removeFromParent(); setInactive(); viewport.enableFlyCam(); } @Override public void onMouseMotionEvent(MouseMotionEvent evt, SandboxViewport viewport) { if (linkState == LinkState.LINKPARENT) { doLink(viewport); } } /** * Called when the mouse button is pressed. * * @param viewport the viewport where the mouse button was released. */ @Override public void onMouseButtonPressed(SandboxViewport viewport) { if (linkState == LinkState.LINK) { this.currentChildElement = viewport.pick(); viewport.addToSelection(currentChildElement); viewport.getRootNode().attachChild(linkGeometry); linkState = LinkState.LINKPARENT; } else if (linkState == LinkState.LINKPARENT) { Prefab p = viewport.pick(); if (p == currentChildElement || p == null) { return; } Vector3f wtrans = currentChildElement.getWorldTranslation().clone(); Quaternion wrot = currentChildElement.getWorldRotation().clone(); Vector3f wscale = currentChildElement.getWorldScale().clone(); // child element is moved from one place to another. ProjectTreeNode previousParent = currentChildElement.getProjectParent(); int previousIndex = previousParent.getIndexOfChild(currentChildElement); p.attachChild(currentChildElement); // it is possible that the attachment process attaches the child somewhere else. // express the world transformation of the child as a local transformation in the parent space. Node pn = currentChildElement.getParent(); if (pn != null) { Matrix4f parentMatrix = new Matrix4f(); parentMatrix.setTranslation(pn.getWorldTranslation()); parentMatrix.setRotationQuaternion(pn.getWorldRotation()); parentMatrix.setScale(pn.getWorldScale()); parentMatrix.invertLocal(); Matrix4f childMatrix = new Matrix4f(); childMatrix.setTranslation(wtrans); childMatrix.setRotationQuaternion(wrot); childMatrix.setScale(wscale); Matrix4f local = parentMatrix.mult(childMatrix); TransformComponent tc = (TransformComponent) currentChildElement.getComponent("TransformComponent"); if (tc != null) { tc.setTranslation(local.toTranslationVector()); tc.setRotation(local.toRotationQuat()); tc.setScale(local.toScaleVector()); } } // remove child from its layer if (previousParent instanceof Layer) { Layer l = (Layer) previousParent; l.removeNode(currentChildElement); } Level level = viewport.getLevel(); LevelEvent le = new LevelEvent(level, EventType.NODEMOVED, currentChildElement, previousParent, previousIndex, currentChildElement.getProjectParent()); GlobalObjects.getInstance().postEvent(le); viewport.activateIdleState(this); linkText.setText(""); textBackground.setDimension(0, 0); textBackgroundGeometry.updateModelBound(); linkGeometry.removeFromParent(); wireBoxGeometryLinkParent.removeFromParent(); currentChildElement = null; linkText.removeFromParent(); textBackgroundGeometry.removeFromParent(); linkState = linkState.LINK; } } /** * Called when the mouse button is released. * * @param viewport the viewport where the mouse button was released. */ @Override public void onMouseButtonReleased(SandboxViewport viewport) { } private Vector3f doLink(SandboxViewport viewport) { CollisionResults results = new CollisionResults(); // Convert screen click to 3d position InputManager inputManager = viewport.getInputManager(); Vector2f click2d = inputManager.getCursorPosition(); Camera cam = viewport.getCamera(); Vector3f click3d = cam.getWorldCoordinates(new Vector2f(click2d.x, click2d.y), 0f).clone(); Vector3f dir = cam.getWorldCoordinates(new Vector2f(click2d.x, click2d.y), 1f).subtractLocal(click3d); // Aim the ray from the clicked spot forwards. Ray ray = new Ray(click3d, dir); // Collect intersections between ray and all nodes in results list. Node sceneElements = viewport.getSceneElements(); sceneElements.collideWith(ray, results); CollisionResult result = results.getClosestCollision(); if (result == null) { return cam.getWorldCoordinates(new Vector2f(click2d.x, click2d.y), 0.5f).clone(); } Geometry g = result.getGeometry(); Prefab prefab = viewport.findPrefabParent(g); if (prefab != null) { prefab.updateModelBound(); BoundingVolume bv = prefab.getWorldBound(); if (bv.getType() == Type.AABB) { BoundingBox bb = (BoundingBox) bv; if (wireBoxGeometryLinkParent != null) { wireBoxGeometryLinkParent.removeFromParent(); } wireBoxGeometryLinkParent = WireBox.makeGeometry(bb); wireBoxGeometryLinkParent.setMaterial(wireBoxMaterial); wireBoxGeometryLinkParent.setLocalTranslation(bb.getCenter().clone()); if (wireBoxGeometryLinkParent.getParent() == null) { viewport.getRootNode().attachChild(wireBoxGeometryLinkParent); } } String sLinkText = currentChildElement.getName() + "->" + prefab.getName(); linkText.setText(sLinkText); linkText.setLocalTranslation(click2d.x, click2d.y, .2f); //linkText.updateModelBound(); //System.out.println("Setting linkText on : " + click2d ); textBackground.setDimension(linkText.getLineWidth() + 2, linkText.getLineHeight() + 4); textBackgroundGeometry.updateModelBound(); textBackgroundGeometry.setLocalTranslation(click2d.x - 1, click2d.y - linkText.getLineHeight() - 2, .1f); return result.getContactPoint(); } else { wireBoxGeometryLinkParent.removeFromParent(); return result.getContactPoint(); } } @Override public void simpleUpdate(float tpf, SandboxViewport viewport) { if (linkState == LinkState.LINKPARENT) { Vector3f from = this.currentChildElement.getWorldTranslation(); Vector3f to = this.doLink(viewport); linkShape.setLine(from, to); } } @Override public void cleanup() { } @Override public void pickGizmo(Ray ray, CollisionResults results) { } @Override public void gizmoPicked(SandboxViewport viewport, Geometry g, Vector3f contactPoint) { } @Override public void selectionChanged(SandboxViewport viewport, Node node) { } @Override public void removeGizmo() { } }
package org.teiid.metadata.index; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; import java.util.Arrays; import java.util.Collection; import javax.xml.stream.XMLStreamException; import org.jboss.vfs.VirtualFile; import org.teiid.adminapi.impl.VDBMetaData; import org.teiid.adminapi.impl.VDBMetadataParser; import org.teiid.core.TeiidRuntimeException; import org.teiid.core.util.FileUtils; import org.teiid.core.util.LRUCache; import org.teiid.metadata.FunctionMethod; import org.teiid.metadata.MetadataStore; import org.teiid.query.function.FunctionTree; import org.teiid.query.function.SystemFunctionManager; import org.teiid.query.function.UDFSource; import org.teiid.query.function.metadata.FunctionMetadataReader; import org.teiid.query.metadata.CompositeMetadataStore; import org.teiid.query.metadata.PureZipFileSystem; import org.teiid.query.metadata.SystemMetadata; import org.teiid.query.metadata.TransformationMetadata; import org.teiid.query.metadata.VDBResources; import org.teiid.query.metadata.VDBResources.Resource; public class VDBMetadataFactory { public static LRUCache<URL, TransformationMetadata> VDB_CACHE = new LRUCache<URL, TransformationMetadata>(10); public static class IndexVDB { public MetadataStore store; public VDBResources resources; } public static TransformationMetadata getVDBMetadata(String vdbFile) { try { File f = new File(vdbFile); return getVDBMetadata(f.getName(), f.toURI().toURL(), null); } catch (IOException e) { throw new TeiidRuntimeException(e); } } public static TransformationMetadata getVDBMetadata(String vdbName, URL vdbURL, URL udfFile) throws IOException { TransformationMetadata vdbmetadata = VDB_CACHE.get(vdbURL); if (vdbmetadata != null) { return vdbmetadata; } try { IndexVDB imf = loadMetadata(vdbName, vdbURL); Resource r = imf.resources.getEntriesPlusVisibilities().get("/META-INF/vdb.xml"); VDBMetaData vdb = null; if (r != null) { vdb = VDBMetadataParser.unmarshell(r.openStream()); } Collection <FunctionMethod> methods = null; Collection<FunctionTree> trees = null; if (udfFile != null) { String schema = FileUtils.getFilenameWithoutExtension(udfFile.getPath()); methods = FunctionMetadataReader.loadFunctionMethods(udfFile.openStream()); trees = Arrays.asList(new FunctionTree(schema, new UDFSource(methods), true)); } SystemFunctionManager sfm = new SystemFunctionManager(); vdbmetadata = new TransformationMetadata(vdb, new CompositeMetadataStore(Arrays.asList(SystemMetadata.getInstance().getSystemStore(), imf.store)), imf.resources.getEntriesPlusVisibilities(), sfm.getSystemFunctions(), trees); VDB_CACHE.put(vdbURL, vdbmetadata); return vdbmetadata; } catch (XMLStreamException e) { throw new IOException(e); } } public static IndexVDB loadMetadata(String vdbName, URL url) throws IOException, MalformedURLException { VirtualFile root; try { root = PureZipFileSystem.mount(url); } catch (URISyntaxException e) { throw new IOException(e); } IndexVDB result = new IndexVDB(); result.resources = new VDBResources(root, null); IndexMetadataRepository store = new IndexMetadataRepository(); result.store = store.load(SystemMetadata.getInstance().getDataTypes(), result.resources); return result; } }
package com.yammer.metrics.core; import com.yammer.metrics.core.Histogram.SampleType; import com.yammer.metrics.util.MetricPredicate; import com.yammer.metrics.util.ThreadPools; import javax.management.MalformedObjectNameException; import java.util.*; import java.util.concurrent.*; /** * A registry of metric instances. */ public class MetricsRegistry { private final ConcurrentMap<MetricName, Metric> metrics = newMetricsMap(); private final ThreadPools threadPools = new ThreadPools(); private final List<MetricsRegistryListener> listeners = new CopyOnWriteArrayList<MetricsRegistryListener>(); /** * Given a new {@link Gauge}, registers it under the given class * and name. * * @param klass the class which owns the metric * @param name the name of the metric * @param metric the metric * @param <T> the type of the value returned by the metric * @return {@code metric} */ public <T> Gauge<T> newGauge(Class<?> klass, String name, Gauge<T> metric) { return newGauge(klass, name, null, metric); } /** * Given a new {@link Gauge}, registers it under the given class * and name. * * @param klass the class which owns the metric * @param name the name of the metric * @param scope the scope of the metric * @param metric the metric * @param <T> the type of the value returned by the metric * @return {@code metric} */ public <T> Gauge<T> newGauge(Class<?> klass, String name, String scope, Gauge<T> metric) { return newGauge(createName(klass, name, scope), metric); } /** * Given a new {@link Gauge}, registers it under the given metric * name. * * @param metricName the name of the metric * @param metric the metric * @param <T> the type of the value returned by the metric * @return {@code metric} */ public <T> Gauge<T> newGauge(MetricName metricName, Gauge<T> metric) { return getOrAdd(metricName, metric); } /** * Given a JMX MBean's object name and an attribute name, registers a gauge for that attribute * under the given class and name. * * @param klass the class which owns the metric * @param name the name of the metric * @param objectName the object name of the MBean * @param attribute the name of the bean's attribute * @return a new {@link JmxGauge} * @throws MalformedObjectNameException if the object name is malformed * @deprecated use {@link #newGauge(Class, String, Gauge)} and {@link JmxGauge} instead */ @Deprecated @SuppressWarnings({"UnusedDeclaration", "deprecation"}) public JmxGauge newJmxGauge(Class<?> klass, String name, String objectName, String attribute) throws MalformedObjectNameException { return newJmxGauge(klass, name, null, objectName, attribute); } /** * Given a JMX MBean's object name and an attribute name, registers a gauge for that attribute * under the given class, name, and scope. * * @param klass the class which owns the metric * @param name the name of the metric * @param scope the scope of the metric * @param objectName the object name of the MBean * @param attribute the name of the bean's attribute * @return a new {@link JmxGauge} * @throws MalformedObjectNameException if the object name is malformed * @deprecated use {@link #newGauge(Class, String, String, Gauge)} and {@link JmxGauge} instead */ @Deprecated @SuppressWarnings("deprecation") public JmxGauge newJmxGauge(Class<?> klass, String name, String scope, String objectName, String attribute) throws MalformedObjectNameException { return newJmxGauge(createName(klass, name, scope), objectName, attribute); } /** * Given a JMX MBean's object name and an attribute name, registers a gauge for that attribute * under the given metric name. * * @param metricName the name of the metric * @param objectName the object name of the MBean * @param attribute the name of the bean's attribute * @return a new {@link JmxGauge} * @throws MalformedObjectNameException if the object name is malformed * @deprecated use {@link #newGauge(MetricName, Gauge)} and {@link JmxGauge} instead */ @Deprecated public JmxGauge newJmxGauge(MetricName metricName, String objectName, String attribute) throws MalformedObjectNameException { return getOrAdd(metricName, new JmxGauge(objectName, attribute)); } /** * Creates a new {@link Counter} and registers it under the given * class and name. * * @param klass the class which owns the metric * @param name the name of the metric * @return a new {@link Counter} */ public Counter newCounter(Class<?> klass, String name) { return newCounter(klass, name, null); } /** * Creates a new {@link Counter} and registers it under the given * class and name. * * @param klass the class which owns the metric * @param name the name of the metric * @param scope the scope of the metric * @return a new {@link Counter} */ public Counter newCounter(Class<?> klass, String name, String scope) { return newCounter(createName(klass, name, scope)); } /** * Creates a new {@link Counter} and registers it under the given * metric name. * * @param metricName the name of the metric * @return a new {@link Counter} */ public Counter newCounter(MetricName metricName) { return getOrAdd(metricName, new Counter()); } /** * Creates a new {@link Histogram} and registers it under the given class and name. * * @param klass the class which owns the metric * @param name the name of the metric * @param biased whether or not the histogram should be biased * @return a new {@link Histogram} */ public Histogram newHistogram(Class<?> klass, String name, boolean biased) { return newHistogram(klass, name, null, biased); } /** * Creates a new {@link Histogram} and registers it under the given class, name, and * scope. * * @param klass the class which owns the metric * @param name the name of the metric * @param scope the scope of the metric * @param biased whether or not the histogram should be biased * @return a new {@link Histogram} */ public Histogram newHistogram(Class<?> klass, String name, String scope, boolean biased) { return newHistogram(createName(klass, name, scope), biased); } /** * Creates a new non-biased {@link Histogram} and registers it under the given class and * name. * * @param klass the class which owns the metric * @param name the name of the metric * @return a new {@link Histogram} */ public Histogram newHistogram(Class<?> klass, String name) { return newHistogram(klass, name, false); } /** * Creates a new non-biased {@link Histogram} and registers it under the given class, * name, and scope. * * @param klass the class which owns the metric * @param name the name of the metric * @param scope the scope of the metric * @return a new {@link Histogram} */ public Histogram newHistogram(Class<?> klass, String name, String scope) { return newHistogram(klass, name, scope, false); } /** * Creates a new {@link Histogram} and registers it under the given metric name. * * @param metricName the name of the metric * @param biased whether or not the histogram should be biased * @return a new {@link Histogram} */ public Histogram newHistogram(MetricName metricName, boolean biased) { return getOrAdd(metricName, new Histogram(biased ? SampleType.BIASED : SampleType.UNIFORM)); } /** * Creates a new {@link Meter} and registers it under the given class and name. * * @param klass the class which owns the metric * @param name the name of the metric * @param eventType the plural name of the type of events the meter is measuring (e.g., {@code * "requests"}) * @param unit the rate unit of the new meter * @return a new {@link Meter} */ public Meter newMeter(Class<?> klass, String name, String eventType, TimeUnit unit) { return newMeter(klass, name, null, eventType, unit); } /** * Creates a new {@link Meter} and registers it under the given class, name, and scope. * * @param klass the class which owns the metric * @param name the name of the metric * @param scope the scope of the metric * @param eventType the plural name of the type of events the meter is measuring (e.g., {@code * "requests"}) * @param unit the rate unit of the new meter * @return a new {@link Meter} */ public Meter newMeter(Class<?> klass, String name, String scope, String eventType, TimeUnit unit) { return newMeter(createName(klass, name, scope), eventType, unit); } /** * Creates a new {@link Meter} and registers it under the given metric name. * * @param metricName the name of the metric * @param eventType the plural name of the type of events the meter is measuring (e.g., {@code * "requests"}) * @param unit the rate unit of the new meter * @return a new {@link Meter} */ public Meter newMeter(MetricName metricName, String eventType, TimeUnit unit) { final Metric existingMetric = metrics.get(metricName); if (existingMetric != null) { return (Meter) existingMetric; } return getOrAdd(metricName, new Meter(newMeterTickThreadPool(), eventType, unit, Clock.DEFAULT)); } /** * Creates a new {@link Timer} and registers it under the given class and name, measuring * elapsed time in milliseconds and invocations per second. * * @param klass the class which owns the metric * @param name the name of the metric * @return a new {@link Timer} */ public Timer newTimer(Class<?> klass, String name) { return newTimer(klass, name, null, TimeUnit.MILLISECONDS, TimeUnit.SECONDS); } /** * Creates a new {@link Timer} and registers it under the given class and name. * * @param klass the class which owns the metric * @param name the name of the metric * @param durationUnit the duration scale unit of the new timer * @param rateUnit the rate scale unit of the new timer * @return a new {@link Timer} */ public Timer newTimer(Class<?> klass, String name, TimeUnit durationUnit, TimeUnit rateUnit) { return newTimer(klass, name, null, durationUnit, rateUnit); } /** * Creates a new {@link Timer} and registers it under the given class, name, and scope, * measuring elapsed time in milliseconds and invocations per second. * * @param klass the class which owns the metric * @param name the name of the metric * @param scope the scope of the metric * @return a new {@link Timer} */ public Timer newTimer(Class<?> klass, String name, String scope) { return newTimer(klass, name, scope, TimeUnit.MILLISECONDS, TimeUnit.SECONDS); } /** * Creates a new {@link Timer} and registers it under the given class, name, and scope. * * @param klass the class which owns the metric * @param name the name of the metric * @param scope the scope of the metric * @param durationUnit the duration scale unit of the new timer * @param rateUnit the rate scale unit of the new timer * @return a new {@link Timer} */ public Timer newTimer(Class<?> klass, String name, String scope, TimeUnit durationUnit, TimeUnit rateUnit) { return newTimer(createName(klass, name, scope), durationUnit, rateUnit); } /** * Creates a new {@link Timer} and registers it under the given metric name. * * @param metricName the name of the metric * @param durationUnit the duration scale unit of the new timer * @param rateUnit the rate scale unit of the new timer * @return a new {@link Timer} */ public Timer newTimer(MetricName metricName, TimeUnit durationUnit, TimeUnit rateUnit) { final Metric existingMetric = metrics.get(metricName); if (existingMetric != null) { return (Timer) existingMetric; } return getOrAdd(metricName, new Timer(newMeterTickThreadPool(), durationUnit, rateUnit)); } /** * Returns an unmodifiable map of all metrics and their names. * * @return an unmodifiable map of all metrics and their names */ public Map<MetricName, Metric> allMetrics() { return Collections.unmodifiableMap(metrics); } /** * Returns a grouped and sorted map of all registered metrics. * * @return all registered metrics, grouped by name and sorted */ public SortedMap<String, SortedMap<MetricName, Metric>> groupedMetrics() { return groupedMetrics(MetricPredicate.ALL); } /** * Returns a grouped and sorted map of all registered metrics which match then given * {@link MetricPredicate}. * * * @param predicate a predicate which metrics have to match to be in the results * @return all registered metrics which match {@code predicate}, sorted by name */ public SortedMap<String, SortedMap<MetricName, Metric>> groupedMetrics(MetricPredicate predicate) { final SortedMap<String, SortedMap<MetricName, Metric>> groups = new TreeMap<String, SortedMap<MetricName, Metric>>(); for (Map.Entry<MetricName, Metric> entry : metrics.entrySet()) { final String qualifiedTypeName = entry.getKey().getGroup() + "." + entry.getKey().getType(); if (predicate.matches(entry.getKey(), entry.getValue())) { final String scopedName; if (entry.getKey().hasScope()) { scopedName = qualifiedTypeName + "." + entry.getKey().getScope(); } else { scopedName = qualifiedTypeName; } SortedMap<MetricName, Metric> group = groups.get(scopedName); if (group == null) { group = new TreeMap<MetricName, Metric>(); groups.put(scopedName, group); } group.put(entry.getKey(), entry.getValue()); } } return groups; } /** * Shut down this registry's thread pools. */ public void shutdown() { threadPools.shutdown(); } /** * Creates a new scheduled thread pool of a given size with the given name, or returns an * existing thread pool if one was already created with the same name. * * @param poolSize the number of threads to create * @param name the name of the pool * @return a new {@link ScheduledExecutorService} */ public ScheduledExecutorService newScheduledThreadPool(int poolSize, String name) { return threadPools.newScheduledThreadPool(poolSize, name); } /** * Removes the metric for the given class with the given name. * * @param klass the klass the metric is associated with * @param name the name of the metric */ public void removeMetric(Class<?> klass, String name) { removeMetric(klass, name, null); } /** * Removes the metric for the given class with the given name and scope. * * @param klass the klass the metric is associated with * @param name the name of the metric * @param scope the scope of the metric */ public void removeMetric(Class<?> klass, String name, String scope) { removeMetric(createName(klass, name, scope)); } /** * Removes the metric with the given name. * * @param name the name of the metric */ public void removeMetric(MetricName name) { final Metric metric = metrics.remove(name); if (metric != null) { if (metric instanceof Stoppable) { ((Stoppable) metric).stop(); } notifyMetricRemoved(name); } } /** * Adds a {@link MetricsRegistryListener} to a collection of listeners that will be notified on * metric creation. Listeners will be notified in the order in which they are added. * <p/> * <b>N.B.:</b> The listener will be notified of all existing metrics when it first registers. * * @param listener the listener that will be notified */ public void addListener(MetricsRegistryListener listener) { listeners.add(listener); for (Map.Entry<MetricName, Metric> entry : metrics.entrySet()) { listener.onMetricAdded(entry.getKey(), entry.getValue()); } } /** * Removes a {@link MetricsRegistryListener} from this registry's collection of listeners. * * @param listener the listener that will be removed */ public void removeListener(MetricsRegistryListener listener) { listeners.remove(listener); } /** * Override to customize how {@link MetricName}s are created. * * @param klass the class which owns the metric * @param name the name of the metric * @param scope the metric's scope * @return the metric's full name */ protected MetricName createName(Class<?> klass, String name, String scope) { return new MetricName(klass, name, scope); } /** * Returns a new {@link ConcurrentMap} implementation. Subclass this to do weird things with * your own {@link MetricsRegistry} implementation. * * @return a new {@link ConcurrentMap} */ protected ConcurrentMap<MetricName, Metric> newMetricsMap() { return new ConcurrentHashMap<MetricName, Metric>(1024); } @SuppressWarnings("unchecked") protected final <T extends Metric> T getOrAdd(MetricName name, T metric) { final Metric existingMetric = metrics.get(name); if (existingMetric == null) { final Metric justAddedMetric = metrics.putIfAbsent(name, metric); if (justAddedMetric == null) { notifyMetricAdded(name, metric); return metric; } if (metric instanceof Stoppable) { ((Stoppable) metric).stop(); } return (T) justAddedMetric; } return (T) existingMetric; } private ScheduledExecutorService newMeterTickThreadPool() { return threadPools.newScheduledThreadPool(2, "meter-tick"); } private void notifyMetricRemoved(MetricName name) { for (MetricsRegistryListener listener : listeners) { listener.onMetricRemoved(name); } } private void notifyMetricAdded(MetricName name, Metric metric) { for (MetricsRegistryListener listener : listeners) { listener.onMetricAdded(name, metric); } } }
package ie.yesequality.yesequality; import android.app.Activity; import android.content.ClipData; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Matrix; import android.graphics.PixelFormat; import android.graphics.drawable.BitmapDrawable; import android.hardware.Camera; import android.net.Uri; import android.os.Bundle; import android.provider.MediaStore; import android.util.Log; import android.view.DragEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.View; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.view.Window; import android.view.WindowManager; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.Toast; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; public class CameraMainActivity extends Activity implements SurfaceHolder.Callback, Camera.ShutterCallback, Camera.PictureCallback { Camera mCamera; SurfaceView surfaceView; SurfaceHolder surfaceHolder; boolean previewing = false; LayoutInflater controlInflater = null; int duration = Toast.LENGTH_SHORT; static int pictureWidth = 0; int bottomPanelSize = 0; int topPanelSize = 0; ImageView selfieButton, retakeButton, shareButtonBot, infoButton, badge; RelativeLayout surfaceLayout; private int[] mVoteBadges = new int[]{R.drawable.ic_vote_for_me, R.drawable.ic_vote_for_me_color, R.drawable.ic_yes_im_voting, R.drawable.ic_yes_im_voting_color, R.drawable.ic_we_voting, R.drawable.ic_we_voting_color, R.drawable.ic_ta, R.drawable.ic_ta_color, R.drawable.ic_yes, R.drawable.ic_yes_color }; private int mSelectedBadge = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.surface_camera_layout); getWindow().setFormat(PixelFormat.UNKNOWN); surfaceView = (SurfaceView) findViewById(R.id.surface_camera); int screenWidth = getWindowManager().getDefaultDisplay().getWidth(); int screenHeight = getWindowManager().getDefaultDisplay().getHeight(); pictureWidth = screenWidth; surfaceLayout = (RelativeLayout) findViewById(R.id.surface_layout); LinearLayout topLayout = (LinearLayout) findViewById(R.id.top_bar); LayoutParams paramsTop = topLayout.getLayoutParams(); topPanelSize = paramsTop.height; Log.e("CameraActivity", "Top bar height is: " + topPanelSize); bottomPanelSize = screenHeight - topPanelSize - screenWidth; Log.e("CameraActivity", "Top bottomsize is: " + bottomPanelSize); LinearLayout bottomLayout = (LinearLayout) findViewById(R.id.bottom_bar); LayoutParams paramsBot = bottomLayout.getLayoutParams(); paramsBot.height = bottomPanelSize; surfaceHolder = surfaceView.getHolder(); surfaceHolder.addCallback(this); surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); controlInflater = LayoutInflater.from(getBaseContext()); selfieButton = (ImageView) findViewById(R.id.selfieButton); selfieButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if (mCamera != null) { mCamera.takePicture(CameraMainActivity.this, null, null, CameraMainActivity.this); } else { Toast.makeText(getBaseContext(), "Can't connect to camera", Toast.LENGTH_SHORT).show(); } } }); retakeButton = (ImageView) findViewById(R.id.retakeButton); retakeButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { retakeLogic(); } }); shareButtonBot = (ImageView) findViewById(R.id.shareButtonBotom); shareButtonBot.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { shareIt(); } }); infoButton = (ImageView) findViewById(R.id.moreInfoButton); infoButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent intent = new Intent(CameraMainActivity.this, MainActivity.class); startActivity(intent); } }); badge = (ImageView) findViewById(R.id.waterMarkPic); ViewGroup.MarginLayoutParams badgeLP = (ViewGroup.MarginLayoutParams) badge.getLayoutParams(); badgeLP.bottomMargin = bottomPanelSize; badge.setLayoutParams(badgeLP); badge.setOnDragListener(new BadgeDragListener()); badge.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { ClipData data = ClipData.newPlainText("", ""); View.DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(v); v.startDrag(data, shadowBuilder, v, 0); v.setVisibility(View.INVISIBLE); return true; } }); badge.setImageResource(mVoteBadges[mSelectedBadge]); badge.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mSelectedBadge >= mVoteBadges.length - 1) { mSelectedBadge = 0; } else { mSelectedBadge++; } badge.setImageResource(mVoteBadges[mSelectedBadge]); } }); surfaceLayout.setOnDragListener(new BadgeDragListener()); } private final class BadgeDragListener implements View.OnDragListener { @Override public boolean onDrag(View v, DragEvent event) { int action = event.getAction(); switch (action) { case DragEvent.ACTION_DROP: View view = (View) event.getLocalState(); view.setX(event.getX() - (view.getWidth() / 2)); view.setY(event.getY() - (view.getHeight() / 2)); view.setVisibility(View.VISIBLE); break; default: break; } return true; } } private void shareIt() { String fname = getPhotoDirectory(CameraMainActivity.this) + "/yesequal.jpg"; Bitmap myfile = BitmapFactory.decodeFile(fname); Intent share = new Intent(Intent.ACTION_SEND); share.setType("image/jpeg"); ContentValues values = new ContentValues(); values.put(MediaStore.Images.Media.TITLE, "title"); values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg"); Uri uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); OutputStream outstream; try { outstream = getContentResolver().openOutputStream(uri); myfile.compress(Bitmap.CompressFormat.JPEG, 100, outstream); outstream.close(); } catch (Exception e) { System.err.println(e.toString()); } share.putExtra(Intent.EXTRA_STREAM, uri); startActivity(Intent.createChooser(share, "Share Image")); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_camera_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { if (mCamera != null) { try { mCamera.setPreviewDisplay(surfaceHolder); mCamera.startPreview(); previewing = true; } catch (Exception e) { e.printStackTrace(); } } } @Override public void surfaceCreated(SurfaceHolder holder) { selfieButton.setVisibility(View.VISIBLE); retakeButton.setVisibility(View.INVISIBLE); shareButtonBot.setVisibility(View.INVISIBLE); if (Camera.getNumberOfCameras() >= 2) { try { mCamera = Camera.open(Camera.CameraInfo.CAMERA_FACING_FRONT); } catch (Exception ex) { Toast.makeText(this, "Fail to connect to camera service", Toast.LENGTH_SHORT).show(); } } else { try { mCamera = Camera.open(); } catch (Exception ex) { Toast.makeText(this, "Fail to connect to camera service", Toast.LENGTH_SHORT).show(); } } if (mCamera != null) { mCamera.setDisplayOrientation(90); } } @Override public void surfaceDestroyed(SurfaceHolder holder) { if (mCamera != null) { mCamera.stopPreview(); mCamera.release(); } mCamera = null; previewing = false; selfieButton.setVisibility(View.VISIBLE); retakeButton.setVisibility(View.INVISIBLE); shareButtonBot.setVisibility(View.INVISIBLE); } private Bitmap overlay(Bitmap bmp1, Bitmap bmp2) { Bitmap bmOverlay = Bitmap.createBitmap(bmp1.getWidth(), bmp1.getHeight(), bmp1.getConfig()); Canvas canvas = new Canvas(bmOverlay); // The badge is 150dp x 150dp Log.e("CameraActivity", "bmp2 height is: " + bmp2.getHeight()); Log.e("CameraActivity", "bmp2 width is: " + bmp2.getWidth()); // A lot of magic numbers in here; trial an error mostly. // There are two sizes of badges (changing in height) // These should be calculated automatically instead of hardcoding them here int widthScale = 150; int heightScale = 129; if(bmp2.getHeight() != 275) { heightScale = 57; } // mirror the camera snapshot to match the camera preview Matrix matrixBmp1 = new Matrix(); matrixBmp1.setScale(-1, 1); matrixBmp1.postTranslate(bmp1.getWidth(), 0); // set the badge position and dimension, to match the one from the camera preview Matrix matrixBmp2 = new Matrix(); if(heightScale == 57) { // I have no idea why this correction is needed for smaller badges Log.e("CameraActivity", "I am correcting the height cause bmp2 height is: " + bmp2.getHeight()); Log.e("CameraActivity", "I am correcting the height cause bmp2 height is: " + bmp2.getHeight()); Log.e("CameraActivity", "old bottomsize is: " + bottomPanelSize); bottomPanelSize -= 26; Log.e("CameraActivity", "new bottomsize is: " + bottomPanelSize); } matrixBmp2.postTranslate(badge.getX(), badge.getY() - bottomPanelSize); // Badge has to be scaled or will be grabbed as is form resources. Bitmap scaledBadge = Bitmap.createScaledBitmap(bmp2, widthScale, heightScale, true); canvas.drawBitmap(bmp1, matrixBmp1, null); canvas.drawBitmap(scaledBadge, matrixBmp2, null); return bmOverlay; } byte[] resizeImageAndWaterMark(byte[] input) { Bitmap original = BitmapFactory.decodeByteArray(input, 0, input.length); Matrix matrix = new Matrix(); matrix.postRotate(-90); Log.d("CameraActivity", " the size of the action bar is: " + topPanelSize); Log.d("CameraActivity", " the original width is " + original.getWidth()); Log.d("CameraActivity", " the original height is " + original.getHeight()); Bitmap scaledBitmap = Bitmap.createBitmap(original, topPanelSize, 0, original.getHeight(), original.getHeight()); //TODO (jos) width and height are the same, this thing does not do anything!??? Bitmap rotatedBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0, scaledBitmap.getWidth(), scaledBitmap.getHeight(), matrix, true); Bitmap waterMark = ((BitmapDrawable) badge.getDrawable()).getBitmap(); rotatedBitmap = overlay(rotatedBitmap, waterMark); ByteArrayOutputStream blob = new ByteArrayOutputStream(); rotatedBitmap.compress(Bitmap.CompressFormat.JPEG, 100, blob); return blob.toByteArray(); } @Override public void onPictureTaken(byte[] data, Camera camera) { data = resizeImageAndWaterMark(data); selfieButton.setVisibility(View.INVISIBLE); retakeButton.setVisibility(View.VISIBLE); shareButtonBot.setVisibility(View.VISIBLE); try { String fname = getPhotoDirectory(CameraMainActivity.this) + "/yesequal.jpg"; File ld = new File(getPhotoDirectory(CameraMainActivity.this)); if (ld.exists()) { if (!ld.isDirectory()) { CameraMainActivity.this.finish(); } } else { ld.mkdir(); } Log.d("YES", "open output stream " + fname + " : " + data.length); OutputStream os = new FileOutputStream(fname); os.write(data, 0, data.length); os.close(); } catch (FileNotFoundException e) { Toast.makeText(CameraMainActivity.this, "FILE NOT FOUND !", duration).show(); e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); Toast.makeText(CameraMainActivity.this, "IO EXCEPTION", duration).show(); } } public void retakeLogic() { selfieButton.setVisibility(View.VISIBLE); retakeButton.setVisibility(View.INVISIBLE); shareButtonBot.setVisibility(View.INVISIBLE); if (mCamera != null) { mCamera.startPreview(); } } public static String getPhotoDirectory(Context context) { return context.getExternalFilesDir(null).getPath(); } @Override public void onShutter() { Toast.makeText(CameraMainActivity.this, "Share your picture!", duration).show(); } }
package org.apache.geronimo.gbean.jmx; import java.lang.reflect.InvocationTargetException; import net.sf.cglib.proxy.Callback; import net.sf.cglib.proxy.Enhancer; import net.sf.cglib.proxy.MethodInterceptor; public class ProxyFactory { private final Class type; private final Enhancer enhancer; public ProxyFactory(Class type) { enhancer = new Enhancer(); enhancer.setSuperclass(type); enhancer.setCallbackType(MethodInterceptor.class); enhancer.setUseFactory(false); this.type = enhancer.createClass(); } public Class getType() { return type; } public Object create(MethodInterceptor methodInterceptor) throws InvocationTargetException { return create(methodInterceptor, new Class[0], new Object[0]); } public synchronized Object create(MethodInterceptor methodInterceptor, Class[] types, Object[] arguments) throws InvocationTargetException { enhancer.setCallbacks(new Callback[]{methodInterceptor}); // @todo trap CodeGenerationException indicating missing no-arg ctr return enhancer.create(types, arguments); } }
package org.geotools.jdbc; import static org.geotools.jdbc.VirtualTable.WHERE_CLAUSE_PLACE_HOLDER; import static org.geotools.jdbc.VirtualTable.WHERE_CLAUSE_PLACE_HOLDER_LENGTH; import static org.geotools.jdbc.VirtualTable.setKeepWhereClausePlaceHolderHint; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.lang.reflect.Method; import java.net.URLDecoder; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.Types; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Objects; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.logging.Level; import javax.sql.DataSource; import org.apache.commons.lang3.ArrayUtils; import org.geotools.data.DataStore; import org.geotools.data.DefaultTransaction; import org.geotools.data.FeatureStore; import org.geotools.data.GmlObjectStore; import org.geotools.data.InProcessLockingManager; import org.geotools.data.Query; import org.geotools.data.Transaction; import org.geotools.data.Transaction.State; import org.geotools.data.jdbc.FilterToSQL; import org.geotools.data.jdbc.FilterToSQLException; import org.geotools.data.jdbc.datasource.ManageableDataSource; import org.geotools.data.simple.SimpleFeatureCollection; import org.geotools.data.simple.SimpleFeatureIterator; import org.geotools.data.store.ContentDataStore; import org.geotools.data.store.ContentEntry; import org.geotools.data.store.ContentFeatureSource; import org.geotools.data.store.ContentState; import org.geotools.feature.NameImpl; import org.geotools.feature.simple.SimpleFeatureBuilder; import org.geotools.feature.visitor.CountVisitor; import org.geotools.feature.visitor.GroupByVisitor; import org.geotools.feature.visitor.LimitingVisitor; import org.geotools.filter.FilterCapabilities; import org.geotools.geometry.jts.ReferencedEnvelope; import org.geotools.jdbc.JoinInfo.JoinPart; import org.geotools.referencing.CRS; import org.geotools.util.Converters; import org.geotools.util.SoftValueHashMap; import org.geotools.util.factory.Hints; import org.locationtech.jts.geom.Envelope; import org.locationtech.jts.geom.Geometry; import org.locationtech.jts.geom.Point; import org.opengis.feature.FeatureVisitor; import org.opengis.feature.simple.SimpleFeature; import org.opengis.feature.simple.SimpleFeatureType; import org.opengis.feature.type.AttributeDescriptor; import org.opengis.feature.type.GeometryDescriptor; import org.opengis.feature.type.Name; import org.opengis.filter.Filter; import org.opengis.filter.Id; import org.opengis.filter.PropertyIsLessThanOrEqualTo; import org.opengis.filter.expression.BinaryExpression; import org.opengis.filter.expression.Expression; import org.opengis.filter.expression.Function; import org.opengis.filter.expression.Literal; import org.opengis.filter.expression.PropertyName; import org.opengis.filter.identity.FeatureId; import org.opengis.filter.identity.GmlObjectId; import org.opengis.filter.sort.SortBy; import org.opengis.filter.sort.SortOrder; import org.opengis.referencing.FactoryException; import org.opengis.referencing.crs.CoordinateReferenceSystem; import org.opengis.referencing.operation.TransformException; /** * Datastore implementation for jdbc based relational databases. * * <p>This class is not intended to be subclassed on a per database basis. Instead the notion of a * "dialect" is used. * * <p> * * <h3>Dialects</h3> * * A dialect ({@link SQLDialect}) encapsulates all the operations that are database specific. * Therefore to implement a jdbc based datastore one must extend SQLDialect. The specific dialect to * use is set using {@link #setSQLDialect(SQLDialect)}. * * <p> * * <h3>Database Connections</h3> * * Connections to the underlying database are obtained through a {@link DataSource}. A datastore * must be specified using {@link #setDataSource(DataSource)}. * * <p> * * <h3>Schemas</h3> * * This datastore supports the notion of database schemas, which is more or less just a grouping of * tables. When a schema is specified, only those tables which are part of the schema are provided * by the datastore. The schema is specified using {@link #setDatabaseSchema(String)}. * * <p> * * <h3>Spatial Functions</h3> * * The set of spatial operations or functions that are supported by the specific database are * reported with a {@link FilterCapabilities} instance. This is specified using {@link * #setFilterCapabilities(FilterCapabilities)}. * * @author Justin Deoliveira, The Open Planning Project */ public final class JDBCDataStore extends ContentDataStore implements GmlObjectStore { /** Caches the "setValue" method in various aggregate visitors */ private static SoftValueHashMap<Class, Method> AGGREGATE_SETVALUE_CACHE = new SoftValueHashMap<>(1000); /** * When true, record a stack trace documenting who disposed the JDBCDataStore. If dispose() is * called a second time we can identify the offending parties. */ protected static final Boolean TRACE_ENABLED = "true".equalsIgnoreCase(System.getProperty("gt2.jdbc.trace")); /** * The native SRID associated to a certain descriptor TODO: qualify this key with * 'org.geotools.jdbc' */ public static final String JDBC_NATIVE_SRID = "nativeSRID"; /** Boolean marker stating whether the feature type is to be considered read only */ public static final String JDBC_READ_ONLY = "org.geotools.jdbc.readOnly"; /** Boolean marker stating whether an attribute is part of the primary key */ public static final String JDBC_PRIMARY_KEY_COLUMN = "org.geotools.jdbc.pk.column"; /** * The key for attribute descriptor user data which specifies the original database column data * type. */ public static final String JDBC_NATIVE_TYPENAME = "org.geotools.jdbc.nativeTypeName"; /** * The key for attribute descriptor user data which specifies the original database column data * type, as a {@link Types} value. */ public static final String JDBC_NATIVE_TYPE = "org.geotools.jdbc.nativeType"; /** Used to specify the column alias to use when encoding a column in a select */ public static final String JDBC_COLUMN_ALIAS = "org.geotools.jdbc.columnAlias"; /** name of table to use to store geometries when {@link #associations} is set. */ protected static final String GEOMETRY_TABLE = "geometry"; /** * name of table to use to store multi geometries made up of non-multi geometries when {@link * #associations} is set. */ protected static final String MULTI_GEOMETRY_TABLE = "multi_geometry"; /** name of table to use to store geometry associations when {@link #associations} is set. */ protected static final String GEOMETRY_ASSOCIATION_TABLE = "geometry_associations"; /** * name of table to use to store feature relationships (information about associations) when * {@link #associations} is set. */ protected static final String FEATURE_RELATIONSHIP_TABLE = "feature_relationships"; /** name of table to use to store feature associations when {@link #associations} is set. */ protected static final String FEATURE_ASSOCIATION_TABLE = "feature_associations"; /** The envelope returned when bounds is called against a geometryless feature type */ protected static final ReferencedEnvelope EMPTY_ENVELOPE = new ReferencedEnvelope(); /** Max number of ids to use for the optimized locks checking filter. */ public static final int MAX_IDS_IN_FILTER = 100; /** data source */ protected DataSource dataSource; /** * Used with TRACE_ENABLED to record the thread responsible for disposing the JDBCDataStore. In * the event dispose() is called a second time this throwable is used to identify the offending * party. */ private Throwable disposedBy = null; /** the dialect of sql */ public SQLDialect dialect; /** The database schema. */ protected String databaseSchema; /** sql type to java class mappings */ protected HashMap<Integer, Class<?>> sqlTypeToClassMappings; /** sql type name to java class mappings */ protected HashMap<String, Class<?>> sqlTypeNameToClassMappings; /** java class to sql type mappings; */ protected HashMap<Class<?>, Integer> classToSqlTypeMappings; /** sql type to sql type name overrides */ protected HashMap<Integer, String> sqlTypeToSqlTypeNameOverrides; /** cache of sqltypes found in database */ protected ConcurrentHashMap<Integer, String> dBsqlTypesCache; /** Feature visitor to aggregate function name */ protected HashMap<Class<? extends FeatureVisitor>, String> aggregateFunctions; /** java supported filter function mappings to dialect name; */ protected HashMap<String, String> supportedFunctions; /** * flag controlling if the datastore is supporting feature and geometry relationships with * associations */ protected boolean associations = false; /** * The fetch size for this datastore, defaulting to 1000. Set to a value less or equal to 0 to * disable fetch size limit and grab all the records in one shot. */ public int fetchSize; /** * The number of features to bufferize while inserting in order to do batch inserts. * * <p>By default 1 to avoid backward compatibility with badly written code that forgets to close * the JDBCInsertFeatureWriter or does it after closing the DB connection. */ protected int batchInsertSize = 1; /** flag controlling whether primary key columns of a table are exposed via the feature type. */ protected boolean exposePrimaryKeyColumns = false; /** * Finds the primary key definitions (instantiated here because the finders might keep state) */ protected PrimaryKeyFinder primaryKeyFinder = new CompositePrimaryKeyFinder( new MetadataTablePrimaryKeyFinder(), new HeuristicPrimaryKeyFinder()); /** Contains the SQL definition of the various virtual tables */ protected Map<String, VirtualTable> virtualTables = new ConcurrentHashMap<String, VirtualTable>(); /** The listeners that are allowed to handle the connection lifecycle */ protected List<ConnectionLifecycleListener> connectionLifecycleListeners = new CopyOnWriteArrayList<ConnectionLifecycleListener>(); protected JDBCCallbackFactory callbackFactory = JDBCCallbackFactory.NULL; private volatile NamePatternEscaping namePatternEscaping; public JDBCDataStore() { super(); } public void setCallbackFactory(JDBCCallbackFactory factory) { this.callbackFactory = factory; } public JDBCCallbackFactory getCallbackFactory() { return callbackFactory; } public JDBCFeatureSource getAbsoluteFeatureSource(String typeName) throws IOException { ContentFeatureSource featureSource = getFeatureSource(typeName); if (featureSource instanceof JDBCFeatureSource) { return (JDBCFeatureSource) featureSource; } return ((JDBCFeatureStore) featureSource).getFeatureSource(); } /** * Adds a virtual table to the data store. If a virtual table with the same name was registered * this method will replace it with the new one. * @param vt * * @throws IOException If the view definition is not valid */ public void createVirtualTable(VirtualTable vtable) throws IOException { try { virtualTables.put(vtable.getName(), new VirtualTable(vtable)); // the new vtable might be overriding a previous definition entries.remove(new NameImpl(namespaceURI, vtable.getName())); getSchema(vtable.getName()); } catch (IOException e) { virtualTables.remove(vtable.getName()); throw e; } } /** * Returns a modifiable list of connection lifecycle listeners * * @return */ public List<ConnectionLifecycleListener> getConnectionLifecycleListeners() { return connectionLifecycleListeners; } /** * Removes and returns the specified virtual table * * @param name * @return */ public VirtualTable dropVirtualTable(String name) { // the new vtable might be overriding a previous definition VirtualTable vt = virtualTables.remove(name); if (vt != null) { entries.remove(new NameImpl(namespaceURI, name)); } return vt; } /** * Returns a live, immutable view of the virtual tables map (from name to definition) * * @return */ public Map<String, VirtualTable> getVirtualTables() { Map<String, VirtualTable> result = new HashMap<String, VirtualTable>(); for (String key : virtualTables.keySet()) { result.put(key, new VirtualTable(virtualTables.get(key))); } return Collections.unmodifiableMap(result); } /** * Returns the finder used to build {@link PrimaryKey} representations * * @return */ public PrimaryKeyFinder getPrimaryKeyFinder() { return primaryKeyFinder; } /** * Sets the finder used to build {@link PrimaryKey} representations * * @param primaryKeyFinder */ public void setPrimaryKeyFinder(PrimaryKeyFinder primaryKeyFinder) { this.primaryKeyFinder = primaryKeyFinder; } /** * The current fetch size. The fetch size influences how many records are read from the dbms at * a time. If set to a value less or equal than zero, all the records will be read in one shot, * severily increasing the memory requirements to read a big number of features. * * @return */ public int getFetchSize() { return fetchSize; } /** * Changes the fetch size. * * @param fetchSize */ public void setFetchSize(int fetchSize) { this.fetchSize = fetchSize; } /** @return the number of features to bufferize while inserting in order to do batch inserts. */ public int getBatchInsertSize() { return batchInsertSize; } /** * Set the number of features to bufferize while inserting in order to do batch inserts. * * <p>Warning: when changing this value from its default of 1, the behavior of the {@link * JDBCInsertFeatureWriter} is changed in non backward compatible ways. If your code closes the * writer before closing the connection, you are fine. Plus, the feature added events will be * delayed until a batch is actually inserted. * * @param batchInsertSize */ public void setBatchInsertSize(int batchInsertSize) { this.batchInsertSize = batchInsertSize; } /** * Determines if the datastore creates feature types which include those columns / attributes * which compose the primary key. */ public boolean isExposePrimaryKeyColumns() { return exposePrimaryKeyColumns; } /** * Sets the flag controlling if the datastore creates feature types which include those columns * / attributes which compose the primary key. */ public void setExposePrimaryKeyColumns(boolean exposePrimaryKeyColumns) { if (this.exposePrimaryKeyColumns != exposePrimaryKeyColumns) { entries.clear(); } this.exposePrimaryKeyColumns = exposePrimaryKeyColumns; } /** * The dialect the datastore uses to generate sql statements in order to communicate with the * underlying database. * * @return The dialect, never <code>null</code>. */ public SQLDialect getSQLDialect() { return dialect; } /** * Sets the dialect the datastore uses to generate sql statements in order to communicate with * the underlying database. * * @param dialect The dialect, never <code>null</code>. */ public void setSQLDialect(SQLDialect dialect) { if (dialect == null) { throw new NullPointerException(); } this.dialect = dialect; } /** * The data source the datastore uses to obtain connections to the underlying database. * * @return The data source, never <code>null</code>. */ public DataSource getDataSource() { if (dataSource == null) { // Should never return null so throw an exception if (TRACE_ENABLED) { // If TRACE_ENABLED disposedBy may have stored an exception if (disposedBy == null) { LOGGER.log(Level.WARNING, "JDBCDataStore was never given a DataSource."); throw new IllegalStateException( "DataSource not available as it was never set."); } else { LOGGER.log( Level.WARNING, "JDBCDataStore was disposed:" + disposedBy, disposedBy); throw new IllegalStateException( "DataSource not available after calling dispose()."); } } else { throw new IllegalStateException( "DataSource not available after calling dispose() or before being set."); } } return dataSource; } /** * Sets the data source the datastore uses to obtain connections to the underlying database. * * @param dataSource The data source, never <code>null</code>. */ public void setDataSource(DataSource dataSource) { if (this.dataSource != null) { LOGGER.log( Level.FINE, "Setting DataSource on JDBCDataStore that already has DataSource set"); } if (dataSource == null) { throw new IllegalArgumentException( "JDBCDataStore's DataSource should not be set to null"); } this.dataSource = dataSource; } /** * The schema from which this datastore is serving tables from. * * @return the schema, or <code>null</code> if non specified. */ public String getDatabaseSchema() { return databaseSchema; } /** * Set the database schema for the datastore. * * <p>When this value is set only those tables which are part of the schema are served through * the datastore. This value can be set to <code>null</code> to specify no particular schema. * * @param databaseSchema The schema, may be <code>null</code>. */ public void setDatabaseSchema(String databaseSchema) { this.databaseSchema = databaseSchema; } /** * The filter capabilities which reports which spatial operations the underlying database can * handle natively. * * @return The filter capabilities, never <code>null</code>. */ public FilterCapabilities getFilterCapabilities() { if (dialect instanceof PreparedStatementSQLDialect) return ((PreparedStatementSQLDialect) dialect) .createPreparedFilterToSQL() .getCapabilities(); else return ((BasicSQLDialect) dialect).createFilterToSQL().getCapabilities(); } /** * Flag controlling if the datastore is supporting feature and geometry relationships with * associations */ public boolean isAssociations() { return associations; } /** * Sets the flag controlling if the datastore is supporting feature and geometry relationships * with associations */ public void setAssociations(boolean foreignKeyGeometries) { this.associations = foreignKeyGeometries; } /** * The sql type to java type mappings that the datastore uses when reading and writing objects * to and from the database. * * <p>These mappings are derived from {@link * SQLDialect#registerSqlTypeToClassMappings(java.util.Map)} * * @return The mappings, never <code>null</code>. */ public Map<Integer, Class<?>> getSqlTypeToClassMappings() { if (sqlTypeToClassMappings == null) { sqlTypeToClassMappings = new HashMap<Integer, Class<?>>(); dialect.registerSqlTypeToClassMappings(sqlTypeToClassMappings); } return sqlTypeToClassMappings; } /** * The sql type name to java type mappings that the dialect uses when * reading and writing objects to and from the database. * <p> * These mappings are derived from {@link SQLDialect#registerSqlTypeNameToClassMappings(Map)} * </p> * * @return The mappings, never <code>null<code>. */ public Map<String, Class<?>> getSqlTypeNameToClassMappings() { if (sqlTypeNameToClassMappings == null) { sqlTypeNameToClassMappings = new HashMap<String, Class<?>>(); dialect.registerSqlTypeNameToClassMappings(sqlTypeNameToClassMappings); } return sqlTypeNameToClassMappings; } /** * The java type to sql type mappings that the datastore uses when reading and writing objects * to and from the database. * * <p>These mappings are derived from {@link SQLDialect#registerClassToSqlMappings(Map)} * * @return The mappings, never <code>null</code>. */ public Map<Class<?>, Integer> getClassToSqlTypeMappings() { if (classToSqlTypeMappings == null) { HashMap<Class<?>, Integer> classToSqlTypeMappings = new HashMap<Class<?>, Integer>(); dialect.registerClassToSqlMappings(classToSqlTypeMappings); this.classToSqlTypeMappings = classToSqlTypeMappings; } return classToSqlTypeMappings; } /** * Returns any ovverides which map integer constants for database types (from {@link Types}) to * database type names. * * <p>This method will return an empty map when there are no overrides. */ public Map<Integer, String> getSqlTypeToSqlTypeNameOverrides() { if (sqlTypeToSqlTypeNameOverrides == null) { sqlTypeToSqlTypeNameOverrides = new HashMap<Integer, String>(); dialect.registerSqlTypeToSqlTypeNameOverrides(sqlTypeToSqlTypeNameOverrides); } return sqlTypeToSqlTypeNameOverrides; } /** * Returns a map integer constants for database types (from {@link Types}) to database type * names. * * <p>This method will return an empty map when there are no overrides. */ public ConcurrentHashMap<Integer, String> getDBsqlTypesCache() { if (dBsqlTypesCache == null) { dBsqlTypesCache = new ConcurrentHashMap<Integer, String>(); } return dBsqlTypesCache; } /** Returns the supported aggregate functions and the visitors they map to. */ public Map<Class<? extends FeatureVisitor>, String> getAggregateFunctions() { if (aggregateFunctions == null) { aggregateFunctions = new HashMap(); dialect.registerAggregateFunctions(aggregateFunctions); } return aggregateFunctions; } /** * Returns the java type mapped to the specified sql type. * * <p>If there is no such type mapped to <tt>sqlType</tt>, <code>null</code> is returned. * * @param sqlType The integer constant for the sql type from {@link Types}. * @return The mapped java class, or <code>null</code>. if no such mapping exists. */ public Class<?> getMapping(int sqlType) { return getSqlTypeToClassMappings().get(Integer.valueOf(sqlType)); } /** * Returns the java type mapped to the specified sql type name. * * <p>If there is no such type mapped to <tt>sqlTypeName</tt>, <code>null</code> is returned. * * @param sqlTypeName The name of the sql type. * @return The mapped java class, or <code>null</code>. if no such mapping exists. */ public Class<?> getMapping(String sqlTypeName) { return getSqlTypeNameToClassMappings().get(sqlTypeName); } /** * Returns the sql type mapped to the specified java type. * * <p>If there is no such type mapped to <tt>clazz</tt>, <code>Types.OTHER</code> is returned. * * @param clazz The java class. * @return The mapped sql type from {@link Types}, Types.OTHER if no such mapping exists. */ public Integer getMapping(Class<?> clazz) { Integer mapping = getClassToSqlTypeMappings().get(clazz); // check for arrays, but don't get fooled by BLOB/CLOB java counterparts if (mapping == null && clazz.isArray()) { mapping = Types.ARRAY; } if (mapping == null) { // no match, try a "fuzzy" match in which we find the super class which matches best List<Map.Entry<Class<?>, Integer>> matches = new ArrayList(); for (Map.Entry<Class<?>, Integer> e : getClassToSqlTypeMappings().entrySet()) { if (e.getKey().isAssignableFrom(clazz)) { matches.add(e); } } if (!matches.isEmpty()) { if (matches.size() == 1) { // single match, great, use it mapping = matches.get(0).getValue(); } else { // sort to match lowest class in type hierarchy, if we end up with a list like: // A, B where B is a super class of A, then chose A since it is the closest // subclass to match Collections.sort( matches, new Comparator<Map.Entry<Class<?>, Integer>>() { public int compare( Entry<Class<?>, Integer> o1, Entry<Class<?>, Integer> o2) { if (o1.getKey().isAssignableFrom(o2.getKey())) { return 1; } if (o2.getKey().isAssignableFrom(o1.getKey())) { return -1; } return 0; } }); if (matches.get(1).getKey().isAssignableFrom(matches.get(0).getKey())) { mapping = matches.get(0).getValue(); } } } } if (mapping == null) { mapping = Types.OTHER; LOGGER.warning("No mapping for " + clazz.getName()); } return mapping; } public void createSchema(final SimpleFeatureType featureType) throws IOException { if (entry(featureType.getName()) != null) { String msg = "Schema '" + featureType.getName() + "' already exists"; throw new IllegalArgumentException(msg); } // execute the create table statement // TODO: create a primary key and a spatial index Connection cx = createConnection(); try { String sql = createTableSQL(featureType, cx); LOGGER.log(Level.FINE, "Create schema: {0}", sql); Statement st = cx.createStatement(); try { st.execute(sql); } finally { closeSafe(st); } dialect.postCreateTable(databaseSchema, featureType, cx); } catch (Exception e) { String msg = "Error occurred creating table"; throw (IOException) new IOException(msg).initCause(e); } finally { closeSafe(cx); } } public void removeSchema(String typeName) throws IOException { removeSchema(name(typeName)); } public void removeSchema(Name typeName) throws IOException { if (entry(typeName) == null) { String msg = "Schema '" + typeName + "' does not exist"; throw new IllegalArgumentException(msg); } // check for virtual table if (virtualTables.containsKey(typeName.getLocalPart())) { dropVirtualTable(typeName.getLocalPart()); return; } SimpleFeatureType featureType = getSchema(typeName); // execute the drop table statement Connection cx = createConnection(); try { // give the dialect a chance to cleanup pre dialect.preDropTable(databaseSchema, featureType, cx); String sql = dropTableSQL(featureType, cx); LOGGER.log(Level.FINE, "Drop schema: {0}", sql); Statement st = cx.createStatement(); try { st.execute(sql); } finally { closeSafe(st); } dialect.postDropTable(databaseSchema, featureType, cx); removeEntry(typeName); } catch (Exception e) { String msg = "Error occurred dropping table"; throw (IOException) new IOException(msg).initCause(e); } finally { closeSafe(cx); } } public Object getGmlObject(GmlObjectId id, Hints hints) throws IOException { // geometry? if (isAssociations()) { Connection cx = createConnection(); try { try { Statement st = null; ResultSet rs = null; if (getSQLDialect() instanceof PreparedStatementSQLDialect) { st = selectGeometrySQLPS(id.getID(), cx); rs = ((PreparedStatement) st).executeQuery(); } else { String sql = selectGeometrySQL(id.getID()); LOGGER.log(Level.FINE, "Get GML object: {0}", sql); st = cx.createStatement(); rs = st.executeQuery(sql); } try { if (rs.next()) { // read the geometry Geometry g = getSQLDialect() .decodeGeometryValue( null, rs, "geometry", getGeometryFactory(), cx, hints); // read the metadata String name = rs.getString("name"); String desc = rs.getString("description"); setGmlProperties(g, id.getID(), name, desc); return g; } } finally { closeSafe(rs); closeSafe(st); } } catch (SQLException e) { throw (IOException) new IOException().initCause(e); } } finally { closeSafe(cx); } } // regular feature, first feature out the feature type int i = id.getID().indexOf('.'); if (i == -1) { LOGGER.info("Unable to determine feature type for GmlObjectId:" + id); return null; } // figure out the type name from the id String featureTypeName = id.getID().substring(0, i); SimpleFeatureType featureType = getSchema(featureTypeName); if (featureType == null) { throw new IllegalArgumentException("No such feature type: " + featureTypeName); } // load the feature Id filter = getFilterFactory().id(Collections.singleton(id)); Query query = new Query(featureTypeName); query.setFilter(filter); query.setHints(hints); SimpleFeatureCollection features = getFeatureSource(featureTypeName).getFeatures(query); if (!features.isEmpty()) { SimpleFeatureIterator fi = features.features(); try { if (fi.hasNext()) { return fi.next(); } } finally { fi.close(); } } return null; } /** * Creates a new instance of {@link JDBCFeatureStore}. * * @see ContentDataStore#createFeatureSource(ContentEntry) */ protected ContentFeatureSource createFeatureSource(ContentEntry entry) throws IOException { // grab the schema, it carries a flag telling us if the feature type is read only SimpleFeatureType schema = entry.getState(Transaction.AUTO_COMMIT).getFeatureType(); if (schema == null) { // if the schema still haven't been computed, force its computation so // that we can decide if the feature type is read only schema = new JDBCFeatureSource(entry, null).buildFeatureType(); entry.getState(Transaction.AUTO_COMMIT).setFeatureType(schema); } Object readOnlyMarker = schema.getUserData().get(JDBC_READ_ONLY); if (Boolean.TRUE.equals(readOnlyMarker)) { return new JDBCFeatureSource(entry, null); } return new JDBCFeatureStore(entry, null); } // /** // * Creates a new instance of {@link JDBCTransactionState}. // */ // protected State createTransactionState(ContentSimpleFeatureSource featureSource) // throws IOException { // return new JDBCTransactionState((JDBCFeatureStore) featureSource); /** * Creates an instanceof {@link JDBCState}. * * @see ContentDataStore#createContentState(ContentEntry) */ protected ContentState createContentState(ContentEntry entry) { JDBCState state = new JDBCState(entry); state.setExposePrimaryKeyColumns(exposePrimaryKeyColumns); return state; } /** * Generates the list of type names provided by the database. * * <p>The list is generated from the underlying database metadata. */ protected List createTypeNames() throws IOException { Connection cx = createConnection(); /* * <LI><B>TABLE_CAT</B> String => table catalog (may be <code>null</code>) * <LI><B>TABLE_SCHEM</B> String => table schema (may be <code>null</code>) * <LI><B>TABLE_NAME</B> String => table name * <LI><B>TABLE_TYPE</B> String => table type. Typical types are "TABLE", * "VIEW", "SYSTEM TABLE", "GLOBAL TEMPORARY", * "LOCAL TEMPORARY", "ALIAS", "SYNONYM". * <LI><B>REMARKS</B> String => explanatory comment on the table * <LI><B>TYPE_CAT</B> String => the types catalog (may be <code>null</code>) * <LI><B>TYPE_SCHEM</B> String => the types schema (may be <code>null</code>) * <LI><B>TYPE_NAME</B> String => type name (may be <code>null</code>) * <LI><B>SELF_REFERENCING_COL_NAME</B> String => name of the designated * "identifier" column of a typed table (may be <code>null</code>) * <LI><B>REF_GENERATION</B> String => specifies how values in * SELF_REFERENCING_COL_NAME are created. Values are * "SYSTEM", "USER", "DERIVED". (may be <code>null</code>) */ List typeNames = new ArrayList(); try { DatabaseMetaData metaData = cx.getMetaData(); Set<String> availableTableTypes = new HashSet<String>(); ResultSet tableTypes = null; try { tableTypes = metaData.getTableTypes(); while (tableTypes.next()) { availableTableTypes.add(tableTypes.getString("TABLE_TYPE")); } } finally { closeSafe(tableTypes); } Set<String> queryTypes = new HashSet<String>(); for (String desiredTableType : dialect.getDesiredTablesType()) { if (availableTableTypes.contains(desiredTableType)) { queryTypes.add(desiredTableType); } } ResultSet tables = metaData.getTables( null, escapeNamePattern(metaData, databaseSchema), "%", queryTypes.toArray(new String[0])); try { if (fetchSize > 1) { tables.setFetchSize(fetchSize); } while (tables.next()) { String schemaName = tables.getString("TABLE_SCHEM"); String tableName = tables.getString("TABLE_NAME"); // use the dialect to filter if (!dialect.includeTable(schemaName, tableName, cx)) { continue; } typeNames.add(new NameImpl(namespaceURI, tableName)); } } finally { closeSafe(tables); } } catch (SQLException e) { throw (IOException) new IOException("Error occurred getting table name list.").initCause(e); } finally { closeSafe(cx); } for (String virtualTable : virtualTables.keySet()) { typeNames.add(new NameImpl(namespaceURI, virtualTable)); } return typeNames; } /** * Returns the primary key object for a particular entry, deriving it from the underlying * database metadata. */ protected PrimaryKey getPrimaryKey(ContentEntry entry) throws IOException { JDBCState state = (JDBCState) entry.getState(Transaction.AUTO_COMMIT); if (state.getPrimaryKey() == null) { synchronized (this) { if (state.getPrimaryKey() == null) { // get metadata from database Connection cx = createConnection(); try { PrimaryKey pkey = null; String tableName = entry.getName().getLocalPart(); if (virtualTables.containsKey(tableName)) { VirtualTable vt = virtualTables.get(tableName); if (vt.getPrimaryKeyColumns().size() == 0) { pkey = new NullPrimaryKey(tableName); } else { List<ColumnMetadata> metas = JDBCFeatureSource.getColumnMetadata(cx, vt, dialect, this); List<PrimaryKeyColumn> kcols = new ArrayList<PrimaryKeyColumn>(); for (String pkName : vt.getPrimaryKeyColumns()) { // look for the pk type Class binding = null; for (ColumnMetadata meta : metas) { if (meta.name.equals(pkName)) { binding = meta.binding; } } // we build a pk without type, the JDBCFeatureStore will do this // for us while building the primary key kcols.add(new NonIncrementingPrimaryKeyColumn(pkName, binding)); } pkey = new PrimaryKey(tableName, kcols); } } else { try { pkey = primaryKeyFinder.getPrimaryKey( this, databaseSchema, tableName, cx); } catch (SQLException e) { LOGGER.log( Level.WARNING, "Failure occurred while looking up the primary key with " + "finder: " + primaryKeyFinder, e); } if (pkey == null) { String msg = "No primary key or unique index found for " + tableName + "."; LOGGER.info(msg); pkey = new NullPrimaryKey(tableName); } } state.setPrimaryKey(pkey); } catch (SQLException e) { String msg = "Error looking up primary key"; throw (IOException) new IOException(msg).initCause(e); } finally { closeSafe(cx); } } } } return state.getPrimaryKey(); } /** Checks whether the tableName corresponds to a view */ boolean isView(DatabaseMetaData metaData, String databaseSchema, String tableName) throws SQLException { ResultSet tables = null; try { tables = metaData.getTables( null, escapeNamePattern(metaData, databaseSchema), escapeNamePattern(metaData, tableName), new String[] {"VIEW"}); return tables.next(); } finally { closeSafe(tables); } } /* * Creates a key from a primary key or unique index. */ PrimaryKey createPrimaryKey( ResultSet index, DatabaseMetaData metaData, String tableName, Connection cx) throws SQLException { ArrayList<PrimaryKeyColumn> cols = new ArrayList(); while (index.next()) { String columnName = index.getString("COLUMN_NAME"); // work around. For some reason the first record returned is always 'empty' // this was tested on Oracle and Postgres databases if (columnName == null) { continue; } // look up the type ( should only be one row ) Class columnType = getColumnType(metaData, databaseSchema, tableName, columnName); // determine which type of primary key we have PrimaryKeyColumn col = null; // 1. Auto Incrementing? Statement st = cx.createStatement(); try { // not actually going to get data st.setFetchSize(1); StringBuffer sql = new StringBuffer(); sql.append("SELECT "); dialect.encodeColumnName(null, columnName, sql); sql.append(" FROM "); encodeTableName(tableName, sql, null); sql.append(" WHERE 0=1"); LOGGER.log(Level.FINE, "Grabbing table pk metadata: {0}", sql); ResultSet rs = st.executeQuery(sql.toString()); try { if (rs.getMetaData().isAutoIncrement(1)) { col = new AutoGeneratedPrimaryKeyColumn(columnName, columnType); } } finally { closeSafe(rs); } } finally { closeSafe(st); } // 2. Has a sequence? if (col == null) { try { String sequenceName = dialect.getSequenceForColumn(databaseSchema, tableName, columnName, cx); if (sequenceName != null) { col = new SequencedPrimaryKeyColumn(columnName, columnType, sequenceName); } } catch (Exception e) { // log the exception , and continue on LOGGER.log( Level.WARNING, "Error occured determining sequence for " + columnName + ", " + tableName, e); } } if (col == null) { col = new NonIncrementingPrimaryKeyColumn(columnName, columnType); } cols.add(col); } if (!cols.isEmpty()) { return new PrimaryKey(tableName, cols); } return null; } /** * Returns the type of the column by inspecting the metadata, with the collaboration of the * dialect */ protected Class getColumnType( DatabaseMetaData metaData, String databaseSchema2, String tableName, String columnName) throws SQLException { ResultSet columns = null; try { columns = metaData.getColumns( null, escapeNamePattern(metaData, databaseSchema), escapeNamePattern(metaData, tableName), escapeNamePattern(metaData, columnName)); if (!columns.next()) { throw new SQLException("Could not find metadata for column"); } int binding = columns.getInt("DATA_TYPE"); Class columnType = getMapping(binding); if (columnType == null) { LOGGER.warning("No class for sql type " + binding); columnType = Object.class; } return columnType; } finally { closeSafe(columns); } } /** * Returns the primary key object for a particular feature type / table, deriving it from the * underlying database metadata. */ public PrimaryKey getPrimaryKey(SimpleFeatureType featureType) throws IOException { return getPrimaryKey(ensureEntry(featureType.getName())); } /** * Returns the expose primary key columns flag for the specified feature type * * @param featureType * @return * @throws IOException */ protected boolean isExposePrimaryKeyColumns(SimpleFeatureType featureType) throws IOException { ContentEntry entry = ensureEntry(featureType.getName()); JDBCState state = (JDBCState) entry.getState(Transaction.AUTO_COMMIT); return state.isExposePrimaryKeyColumns(); } /** * Returns the bounds of the features for a particular feature type / table. * * @param featureType The feature type / table. * @param query Specifies rows to include in bounds calculation, as well as how many features * and the offset if needed */ protected ReferencedEnvelope getBounds( SimpleFeatureType featureType, Query query, Connection cx) throws IOException { // handle geometryless case by returning an emtpy envelope if (featureType.getGeometryDescriptor() == null) return EMPTY_ENVELOPE; Statement st = null; ResultSet rs = null; ReferencedEnvelope bounds = ReferencedEnvelope.create(featureType.getCoordinateReferenceSystem()); try { // try optimized bounds computation only if we're targeting the entire table if (isFullBoundsQuery(query, featureType)) { List<ReferencedEnvelope> result = dialect.getOptimizedBounds(databaseSchema, featureType, cx); if (result != null && !result.isEmpty()) { // merge the envelopes into one for (ReferencedEnvelope envelope : result) { bounds = mergeEnvelope(bounds, envelope); } return bounds; } } // build an aggregate query if (dialect instanceof PreparedStatementSQLDialect) { st = selectBoundsSQLPS(featureType, query, cx); rs = ((PreparedStatement) st).executeQuery(); } else { String sql = selectBoundsSQL(featureType, query); LOGGER.log(Level.FINE, "Retriving bounding box: {0}", sql); st = cx.createStatement(); rs = st.executeQuery(sql); } // scan through all the rows (just in case a non aggregated function was used) // and through all the columns (in case we have multiple geometry columns) CoordinateReferenceSystem flatCRS = CRS.getHorizontalCRS(featureType.getCoordinateReferenceSystem()); final int columns = rs.getMetaData().getColumnCount(); while (rs.next()) { for (int i = 1; i <= columns; i++) { final Envelope envelope = dialect.decodeGeometryEnvelope(rs, i, st.getConnection()); if (envelope != null) { if (envelope instanceof ReferencedEnvelope) { bounds = mergeEnvelope(bounds, (ReferencedEnvelope) envelope); } else { bounds = mergeEnvelope( bounds, new ReferencedEnvelope(envelope, flatCRS)); } } } } } catch (Exception e) { String msg = "Error occured calculating bounds for " + featureType.getTypeName(); throw (IOException) new IOException(msg).initCause(e); } finally { closeSafe(rs); closeSafe(st); } return bounds; } /** * Returns true if the query will hit all the geometry columns with no row filtering (a * condition that allows to use spatial index statistics to compute the table bounds) * * @param query * @param schema * @return */ private boolean isFullBoundsQuery(Query query, SimpleFeatureType schema) { if (query == null) { return true; } if (!Filter.INCLUDE.equals(query.getFilter())) { return false; } if (query.getProperties() == Query.ALL_PROPERTIES) { return true; } List<String> names = Arrays.asList(query.getPropertyNames()); for (AttributeDescriptor ad : schema.getAttributeDescriptors()) { if (ad instanceof GeometryDescriptor) { if (!names.contains(ad.getLocalName())) { return false; } } } return true; } /** * Merges two envelopes handling possibly different CRS * * @param base * @param merge * @return * @throws TransformException * @throws FactoryException */ ReferencedEnvelope mergeEnvelope(ReferencedEnvelope base, ReferencedEnvelope merge) throws TransformException, FactoryException { if (base == null || base.isNull()) { return merge; } else if (merge == null || merge.isNull()) { return base; } else { // reproject and merge final CoordinateReferenceSystem crsBase = base.getCoordinateReferenceSystem(); final CoordinateReferenceSystem crsMerge = merge.getCoordinateReferenceSystem(); if (crsBase == null) { merge.expandToInclude(base); return merge; } else if (crsMerge == null) { base.expandToInclude(base); return base; } else { // both not null, are they equal? if (!CRS.equalsIgnoreMetadata(crsBase, crsMerge)) { merge = merge.transform(crsBase, true); } base.expandToInclude(merge); return base; } } } /** Returns the count of the features for a particular feature type / table. */ protected int getCount(SimpleFeatureType featureType, Query query, Connection cx) throws IOException { CountVisitor v = new CountVisitor(); getAggregateValue(v, featureType, query, cx); return v.getCount(); } /** * Results the value of an aggregate function over a query. * * @return generated result, or null if unsupported */ protected Object getAggregateValue( FeatureVisitor visitor, SimpleFeatureType featureType, Query query, Connection cx) throws IOException { // check if group by is supported by the underlying store if (isGroupByVisitor(visitor) && (!dialect.isGroupBySupported() || !isSupportedGroupBy((GroupByVisitor) visitor))) { return null; } // try to match the visitor with an aggregate function String function = matchAggregateFunction(visitor); if (function == null) { // this visitor is not supported return null; } // try to extract an aggregate attribute from the visitor Expression aggregateExpression = null; if (!isCountVisitor(visitor)) { aggregateExpression = getAggregateExpression(visitor); if (aggregateExpression != null && !fullySupports(aggregateExpression)) { return null; } } // if the visitor is limiting the result to a given start - max, we will // try to apply limits to the aggregate query LimitingVisitor limitingVisitor = null; if (visitor instanceof LimitingVisitor) { limitingVisitor = (LimitingVisitor) visitor; } // if the visitor is a group by visitor we extract the group by attributes List<Expression> groupByExpressions = extractGroupByExpressions(visitor); // result of the function try { Object result = null; List results = new ArrayList(); Statement st = null; ResultSet rs = null; try { if (dialect instanceof PreparedStatementSQLDialect) { st = selectAggregateSQLPS( function, aggregateExpression, groupByExpressions, featureType, query, limitingVisitor, cx); rs = ((PreparedStatement) st).executeQuery(); } else { String sql = selectAggregateSQL( function, aggregateExpression, groupByExpressions, featureType, query, limitingVisitor); LOGGER.fine(sql); st = cx.createStatement(); st.setFetchSize(fetchSize); rs = st.executeQuery(sql); } while (rs.next()) { if (groupByExpressions == null || groupByExpressions.isEmpty()) { Object value = rs.getObject(1); result = value; results.add(value); } else { results.add(extractValuesFromResultSet(rs, groupByExpressions.size())); } } } finally { closeSafe(rs); closeSafe(st); } if (groupByExpressions != null && !groupByExpressions.isEmpty()) { setResult(visitor, results); return results; } else if (setResult(visitor, results.size() > 1 ? results : result)) { return result == null ? results : result; } return null; } catch (SQLException e) { throw (IOException) new IOException().initCause(e); } } /** * Checks if the groupBy is a supported one, that is, if it's possible to turn to SQL the * various {@link Expression} it's using * * @param visitor * @return */ private boolean isSupportedGroupBy(GroupByVisitor visitor) { return visitor.getGroupByAttributes().stream().allMatch(xp -> fullySupports(xp)); } private boolean fullySupports(Expression expression) { if (expression == null) { throw new IllegalArgumentException("Null expression can not be unpacked"); } FilterCapabilities filterCapabilities = getFilterCapabilities(); if (!filterCapabilities.supports(expression.getClass())) { return false; } // check the known composite expressions if (expression instanceof BinaryExpression) { BinaryExpression be = (BinaryExpression) expression; return fullySupports(be.getExpression1()) && fullySupports(be.getExpression2()); } else if (expression instanceof Function) { Function function = (Function) expression; for (Expression fe : function.getParameters()) { if (!fullySupports(fe)) { return false; } } } return true; } // Helper method that checks if the visitor is of type count visitor. protected boolean isCountVisitor(FeatureVisitor visitor) { if (visitor instanceof CountVisitor) { // is count visitor nothing else to test return true; } // the visitor maybe wrapper by a group by visitor return isGroupByVisitor(visitor) && ((GroupByVisitor) visitor).getAggregateVisitor() instanceof CountVisitor; } /** * Helper method the checks if a feature visitor is a group by visitor, * * @param visitor the feature visitor * @return TRUE if the visitor is a group by visitor otherwise FALSE */ protected boolean isGroupByVisitor(FeatureVisitor visitor) { return visitor instanceof GroupByVisitor; } /** * Helper method that will try to match a feature visitor with an aggregate function. If no * aggregate function machs the visitor NULL will be returned. * * @param visitor the feature visitor * @return the match aggregate function name, or NULL if no match */ protected String matchAggregateFunction(FeatureVisitor visitor) { // if is a group by visitor we use use the internal aggregate visitor class otherwise we use // the visitor class Class visitorClass = isGroupByVisitor(visitor) ? ((GroupByVisitor) visitor).getAggregateVisitor().getClass() : visitor.getClass(); String function = null; // try to find a matching aggregate function walking up the hierarchy if necessary while (function == null && visitorClass != null) { function = getAggregateFunctions().get(visitorClass); visitorClass = visitorClass.getSuperclass(); } if (function == null) { // this visitor don't match any aggregate function NULL will be returned LOGGER.info( "Unable to find aggregate function matching visitor: " + visitor.getClass()); } return function; } private Expression getAggregateExpression(FeatureVisitor visitor) { // if is a group by visitor we need to use the internal aggregate visitor FeatureVisitor aggregateVisitor = isGroupByVisitor(visitor) ? ((GroupByVisitor) visitor).getAggregateVisitor() : visitor; Expression expression = getExpression(aggregateVisitor); if (expression == null) { // no aggregate attribute available, NULL will be returned LOGGER.info("Visitor " + visitor.getClass() + " has no aggregate attribute."); return null; } return expression; } /** * Helper method that extracts a list of group by attributes from a group by visitor. If the * visitor is not a group by visitor an empty list will be returned. * * @param visitor the feature visitor * @return the list of the group by attributes or an empty list */ protected List<Expression> extractGroupByExpressions(FeatureVisitor visitor) { // if is a group by visitor we get the list of attributes expressions otherwise we get an // empty list List<Expression> expressions = isGroupByVisitor(visitor) ? ((GroupByVisitor) visitor).getGroupByAttributes() : new ArrayList<>(); return expressions; } /** * Helper method that translate the result set to the appropriate group by visitor result format */ protected GroupByVisitor.GroupByRawResult extractValuesFromResultSet( ResultSet resultSet, int numberOfGroupByAttributes) throws SQLException { List<Object> groupByValues = new ArrayList<>(); for (int i = 0; i < numberOfGroupByAttributes; i++) { groupByValues.add(resultSet.getObject(i + 1)); } return new GroupByVisitor.GroupByRawResult( groupByValues, resultSet.getObject(numberOfGroupByAttributes + 1)); } /** * Helper method for getting the expression from a visitor TODO: Remove this method when there * is an interface for aggregate visitors. See GEOT-2325 for details. */ Expression getExpression(FeatureVisitor visitor) { if (visitor instanceof CountVisitor) { return null; } try { Method g = visitor.getClass().getMethod("getExpression", null); if (g != null) { Object result = g.invoke(visitor, null); if (result instanceof Expression) { return (Expression) result; } } } catch (Exception e) { // ignore for now } return null; } /** * Helper method for setting the result of a aggregate functino on a visitor. TODO: Remove this * method when there is an interface for aggregate visitors. See GEOT-2325 for details. */ boolean setResult(FeatureVisitor visitor, Object result) { try { Method s = null; if (AGGREGATE_SETVALUE_CACHE.containsKey(visitor.getClass())) { s = AGGREGATE_SETVALUE_CACHE.get(visitor.getClass()); } else { try { s = visitor.getClass().getMethod("setValue", result.getClass()); } catch (Exception e) { } if (s == null) { for (Method m : visitor.getClass().getMethods()) { if ("setValue".equals(m.getName())) { s = m; break; } } } AGGREGATE_SETVALUE_CACHE.put(visitor.getClass(), s); } if (s != null) { Class type = s.getParameterTypes()[0]; if (!type.isInstance(result)) { // convert Object converted = Converters.convert(result, type); if (converted != null) { result = converted; } else { // could not set value return false; } } s.invoke(visitor, result); return true; } } catch (Exception e) { // ignore for now } return false; } /** Inserts a new feature into the database for a particular feature type / table. */ protected void insert(SimpleFeature feature, SimpleFeatureType featureType, Connection cx) throws IOException { insert(Collections.singletonList(feature), featureType, cx); } /** * Inserts a collection of new features into the database for a particular feature type / table. */ protected void insert( Collection<? extends SimpleFeature> features, SimpleFeatureType featureType, Connection cx) throws IOException { PrimaryKey key = getPrimaryKey(featureType); // we do this in a synchronized block because we need to do two queries, // first to figure out what the id will be, then the insert statement synchronized (this) { try { if (dialect instanceof PreparedStatementSQLDialect) { Map<InsertionClassifier, Collection<SimpleFeature>> kinds = InsertionClassifier.classify(featureType, features); for (InsertionClassifier kind : kinds.keySet()) { insertPS(kinds.get(kind), kind, featureType, cx, key); } } else { Collection<SimpleFeature> useExistings = new ArrayList<>(); Collection<SimpleFeature> notUseExistings = new ArrayList<>(); for (SimpleFeature cur : features) { (InsertionClassifier.useExisting(cur) ? useExistings : notUseExistings) .add(cur); } insertNonPS(useExistings, featureType, cx, key, true); insertNonPS(notUseExistings, featureType, cx, key, false); } } catch (SQLException e) { String msg = "Error inserting features"; throw (IOException) new IOException(msg).initCause(e); } } } /** Specialized insertion for dialects that are using prepared statements. */ private void insertPS( Collection<SimpleFeature> features, InsertionClassifier kind, SimpleFeatureType featureType, Connection cx, PrimaryKey key) throws IOException, SQLException { final PreparedStatementSQLDialect dialect = (PreparedStatementSQLDialect) getSQLDialect(); final KeysFetcher keysFetcher = KeysFetcher.create(this, cx, kind.useExisting, key); final String sql = buildInsertPS(kind, featureType, keysFetcher, dialect); LOGGER.log(Level.FINE, "Inserting new features with ps: {0}", sql); // create the prepared statement final PreparedStatement ps; if (keysFetcher.isPostInsert()) { // ask the DB to return the values of all the keys after the insertion ps = cx.prepareStatement(sql, keysFetcher.getColumnNames()); } else { ps = cx.prepareStatement(sql); } try { for (SimpleFeature feature : features) { // set the attribute values int i = 1; for (AttributeDescriptor att : featureType.getAttributeDescriptors()) { String colName = att.getLocalName(); // skip the pk columns in case we have exposed them, we grab the // value from the pk itself if (keysFetcher.isKey(colName)) { continue; } Class binding = att.getType().getBinding(); Object value = feature.getAttribute(colName); if (value == null && !att.isNillable()) { throw new IOException( "Cannot set a NULL value on the not null column " + colName); } if (Geometry.class.isAssignableFrom(binding)) { Geometry g = (Geometry) value; int srid = getGeometrySRID(g, att); int dimension = getGeometryDimension(g, att); dialect.setGeometryValue(g, dimension, srid, binding, ps, i); } else if (isArray(att)) { dialect.setArrayValue(value, att, ps, i, cx); } else { dialect.setValue(value, binding, ps, i, cx); } if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine((i) + " = " + value); } i++; } keysFetcher.setKeyValues(dialect, ps, cx, featureType, feature, i); dialect.onInsert(ps, cx, featureType); ps.addBatch(); } int[] inserts = ps.executeBatch(); checkAllInserted(inserts, features.size()); keysFetcher.postInsert(featureType, features, ps); } finally { closeSafe(ps); } } static void checkAllInserted(int[] inserts, int size) throws IOException { int sum = 0; for (int cur : inserts) { if (cur == PreparedStatement.SUCCESS_NO_INFO) { return; // cannot check } else if (cur == PreparedStatement.EXECUTE_FAILED) { throw new IOException("Failed to insert some features"); } sum += cur; } if (sum != size) { throw new IOException("Failed to insert some features"); } } /** Build the insert statement that will be used in a PreparedStatement. */ private String buildInsertPS( InsertionClassifier kind, SimpleFeatureType featureType, KeysFetcher keysFetcher, PreparedStatementSQLDialect dialect) throws SQLException { StringBuffer sql = new StringBuffer(); sql.append("INSERT INTO "); encodeTableName(featureType.getTypeName(), sql, null); // column names sql.append(" ( "); for (int i = 0; i < featureType.getAttributeCount(); i++) { String colName = featureType.getDescriptor(i).getLocalName(); // skip the pk columns in case we have exposed them if (keysFetcher.isKey(colName)) { continue; } dialect.encodeColumnName(null, colName, sql); sql.append(","); } // primary key values keysFetcher.addKeyColumns(sql); sql.setLength(sql.length() - 1); // remove the last coma // values sql.append(" ) VALUES ( "); for (AttributeDescriptor att : featureType.getAttributeDescriptors()) { String colName = att.getLocalName(); // skip the pk columns in case we have exposed them, we grab the // value from the pk itself if (keysFetcher.isKey(colName)) { continue; } // geometries might need special treatment, delegate to the dialect if (att instanceof GeometryDescriptor) { Class<? extends Geometry> geometryClass = kind.geometryTypes.get(att.getName().getLocalPart()); dialect.prepareGeometryValue( geometryClass, getDescriptorDimension(att), getDescriptorSRID(att), att.getType().getBinding(), sql); } else { sql.append("?"); } sql.append(","); } keysFetcher.addKeyBindings(sql); sql.setLength(sql.length() - 1); sql.append(")"); return sql.toString(); } /** Specialized insertion for dialects that are not using prepared statements. */ private void insertNonPS( Collection<? extends SimpleFeature> features, SimpleFeatureType featureType, Connection cx, PrimaryKey key, boolean useExisting) throws IOException, SQLException { if (features.isEmpty()) { return; } final Statement st = cx.createStatement(); final KeysFetcher keysFetcher = KeysFetcher.create(this, cx, useExisting, key); try { for (SimpleFeature feature : features) { String sql = insertSQL(featureType, feature, keysFetcher, cx); ((BasicSQLDialect) dialect).onInsert(st, cx, featureType); LOGGER.log(Level.FINE, "Inserting new feature: {0}", sql); if (keysFetcher.hasAutoGeneratedKeys()) { st.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS); } else { st.executeUpdate(sql); } keysFetcher.postInsert(featureType, feature, cx, st); } } finally { closeSafe(st); } } /** Updates an existing feature(s) in the database for a particular feature type / table. */ protected void update( SimpleFeatureType featureType, List<AttributeDescriptor> attributes, List<Object> values, Filter filter, Connection cx) throws IOException, SQLException { update( featureType, attributes.toArray(new AttributeDescriptor[attributes.size()]), values.toArray(new Object[values.size()]), filter, cx); } /** Updates an existing feature(s) in the database for a particular feature type / table. */ protected void update( SimpleFeatureType featureType, AttributeDescriptor[] attributes, Object[] values, Filter filter, Connection cx) throws IOException, SQLException { if ((attributes == null) || (attributes.length == 0)) { LOGGER.warning("Update called with no attributes, doing nothing."); return; } // grab primary key PrimaryKey key = null; try { key = getPrimaryKey(featureType); } catch (IOException e) { throw new RuntimeException(e); } Set<String> pkColumnNames = getColumnNames(key); // do a check to ensure that the update includes at least one non primary key column boolean nonPkeyColumn = false; for (AttributeDescriptor att : attributes) { if (!pkColumnNames.contains(att.getLocalName())) { nonPkeyColumn = true; } } if (!nonPkeyColumn) { throw new IllegalArgumentException( "Illegal update, must include at least one non primary key column, " + "all primary key columns are ignored."); } if (dialect instanceof PreparedStatementSQLDialect) { try { PreparedStatement ps = updateSQLPS(featureType, attributes, values, filter, pkColumnNames, cx); try { ((PreparedStatementSQLDialect) dialect).onUpdate(ps, cx, featureType); ps.execute(); } finally { closeSafe(ps); } } catch (SQLException e) { throw new RuntimeException(e); } } else { String sql = updateSQL(featureType, attributes, values, filter, pkColumnNames); try { Statement st = cx.createStatement(); try { ((BasicSQLDialect) dialect).onUpdate(st, cx, featureType); LOGGER.log(Level.FINE, "Updating feature: {0}", sql); st.execute(sql); } finally { closeSafe(st); } } catch (SQLException e) { String msg = "Error occured updating features"; throw (IOException) new IOException(msg).initCause(e); } } } /** Deletes an existing feature in the database for a particular feature type / fid. */ protected void delete(SimpleFeatureType featureType, String fid, Connection cx) throws IOException { Filter filter = filterFactory.id(Collections.singleton(filterFactory.featureId(fid))); delete(featureType, filter, cx); } /** Deletes an existing feature(s) in the database for a particular feature type / table. */ protected void delete(SimpleFeatureType featureType, Filter filter, Connection cx) throws IOException { Statement st = null; try { try { if (dialect instanceof PreparedStatementSQLDialect) { st = deleteSQLPS(featureType, filter, cx); PreparedStatement ps = (PreparedStatement) st; ((PreparedStatementSQLDialect) dialect).onDelete(ps, cx, featureType); ps.execute(); } else { String sql = deleteSQL(featureType, filter); st = cx.createStatement(); ((BasicSQLDialect) dialect).onDelete(st, cx, featureType); LOGGER.log(Level.FINE, "Removing feature(s): {0}", sql); st.execute(sql); } } finally { closeSafe(st); } } catch (SQLException e) { String msg = "Error occured during delete"; throw (IOException) new IOException(msg).initCause(e); } } /** * Returns a JDBC Connection to the underlying database for the specified GeoTools {@link * Transaction}. This has two main use cases: * * <ul> * <li>Independently accessing the underlying database directly reusing the connection pool * contained in the {@link JDBCDataStore} * <li>Performing some direct access to the database in the same JDBC transaction as the * Geotools code * </ul> * * The connection shall be used in a different way depending on the use case: * * <ul> * <li>If the transaction is {@link Transaction#AUTO_COMMIT} or if the transaction is not * shared with this data store and originating {@link FeatureStore} objects it is the duty * of the caller to properly close the connection after usage, failure to do so will * result in the connection pool loose one available connection permanently * <li>If the transaction is on the other side a valid transaction is shared with Geotools the * client code should refrain from closing the connection, committing or rolling back, and * use the {@link Transaction} facilities to do so instead * </ul> * * @param t The GeoTools transaction. Can be {@code null}, in that case a new connection will be * returned (as if {@link Transaction#AUTO_COMMIT} was provided) */ public Connection getConnection(Transaction t) throws IOException { // short circuit this state, all auto commit transactions are using the same if (t == Transaction.AUTO_COMMIT) { Connection cx = createConnection(); try { if (!cx.getAutoCommit()) { cx.setAutoCommit(true); } } catch (SQLException e) { throw (IOException) new IOException().initCause(e); } return cx; } JDBCTransactionState tstate = (JDBCTransactionState) t.getState(this); if (tstate != null) { return tstate.cx; } else { Connection cx = createConnection(); try { cx.setAutoCommit(false); } catch (SQLException e) { throw (IOException) new IOException().initCause(e); } tstate = new JDBCTransactionState(cx, this); t.putState(this, tstate); return cx; } } /** Gets a database connection for the specified feature store. */ protected final Connection getConnection(JDBCState state) throws IOException { return getConnection(state.getTransaction()); } /** * Creates a new connection. * * <p>Callers of this method should close the connection when done with it. . */ protected final Connection createConnection() { try { LOGGER.fine("CREATE CONNECTION"); Connection cx = getDataSource().getConnection(); // isolation level is not set in the datastore, see // call dialect callback to initialize the connection dialect.initializeConnection(cx); // if there is any lifecycle listener use it if (connectionLifecycleListeners.size() > 0) { List<ConnectionLifecycleListener> locals = new ArrayList<ConnectionLifecycleListener>(connectionLifecycleListeners); cx = new LifecycleConnection(this, cx, locals); } return cx; } catch (SQLException e) { throw new RuntimeException("Unable to obtain connection: " + e.getMessage(), e); } } /** * Releases an existing connection (paying special attention to {@link Transaction#AUTO_COMMIT}. * * <p>If the state is based off the AUTO_COMMIT transaction - close using {@link * #closeSafe(Connection)}. Otherwise wait until the transaction itself is closed to close the * connection. */ protected final void releaseConnection(Connection cx, JDBCState state) { if (state.getTransaction() == Transaction.AUTO_COMMIT) { closeSafe(cx); } } /** * Calls through to: <code><pre> * encodeFID(pkey, rs, 0); * </pre></code> */ protected String encodeFID(PrimaryKey pkey, ResultSet rs) throws SQLException, IOException { return encodeFID(pkey, rs, 0); } /** * Encodes a feature id from a primary key and result set values. * * <p><tt>offset</tt> specifies where in the result set to start from when reading values for * the primary key. */ protected String encodeFID(PrimaryKey pkey, ResultSet rs, int offset) throws SQLException, IOException { // no pk columns List<PrimaryKeyColumn> columns = pkey.getColumns(); if (columns.isEmpty()) { return SimpleFeatureBuilder.createDefaultFeatureId(); } // just one, no need to build support structures if (columns.size() == 1) { return dialect.getPkColumnValue(rs, columns.get(0), offset + 1); } // more than one List<Object> keyValues = new ArrayList<Object>(); for (int i = 0; i < columns.size(); i++) { String o = dialect.getPkColumnValue(rs, columns.get(0), offset + i + 1); keyValues.add(o); } return encodeFID(keyValues); } protected static String encodeFID(List<Object> keyValues) { StringBuffer fid = new StringBuffer(); for (Object o : keyValues) { fid.append(o).append("."); } fid.setLength(fid.length() - 1); return fid.toString(); } /** * Decodes a fid into its components based on a primary key. * * @param strict If set to true the value of the fid will be validated against the type of the * key columns. If a conversion can not be made, an exception will be thrown. */ public static List<Object> decodeFID(PrimaryKey key, String FID, boolean strict) { // strip off the feature type name if (FID.startsWith(key.getTableName() + ".")) { FID = FID.substring(key.getTableName().length() + 1); } try { FID = URLDecoder.decode(FID, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } // check for case of multi column primary key and try to backwards map using // "." as a seperator of values List values = null; if (key.getColumns().size() > 1) { String[] split = FID.split("\\."); // copy over to avoid array store exception values = new ArrayList(split.length); for (int i = 0; i < split.length; i++) { values.add(split[i]); } } else { // single value case values = new ArrayList(); values.add(FID); } if (values.size() != key.getColumns().size()) { throw new IllegalArgumentException( "Illegal fid: " + FID + ". Expected " + key.getColumns().size() + " values but got " + values.size()); } // convert to the type of the key for (int i = 0; i < values.size(); i++) { Object value = values.get(i); if (value != null) { Class type = key.getColumns().get(i).getType(); Object converted = Converters.convert(value, type); if (converted != null) { values.set(i, converted); } if (strict && !type.isInstance(values.get(i))) { throw new IllegalArgumentException( "Value " + values.get(i) + " illegal for type " + type.getName()); } } } return values; } /** * Determines if a primary key is made up entirely of column which are generated via an * auto-generating column or a sequence. */ protected boolean isGenerated(PrimaryKey pkey) { for (PrimaryKeyColumn col : pkey.getColumns()) { if (!(col instanceof AutoGeneratedPrimaryKeyColumn)) { return false; } } return true; } // SQL generation /** Generates a 'CREATE TABLE' sql statement. */ protected String createTableSQL(SimpleFeatureType featureType, Connection cx) throws Exception { // figure out the names and types of the columns String[] columnNames = new String[featureType.getAttributeCount()]; String[] sqlTypeNames = null; Class[] classes = new Class[featureType.getAttributeCount()]; // figure out which columns can not be null boolean[] nillable = new boolean[featureType.getAttributeCount()]; for (int i = 0; i < featureType.getAttributeCount(); i++) { AttributeDescriptor attributeType = featureType.getDescriptor(i); // column name columnNames[i] = attributeType.getLocalName(); // column type classes[i] = attributeType.getType().getBinding(); // can be null? nillable[i] = attributeType.getMinOccurs() <= 0 || attributeType.isNillable(); } sqlTypeNames = getSQLTypeNames(classes, cx); for (int i = 0; i < sqlTypeNames.length; i++) { if (sqlTypeNames[i] == null) { String msg = "Unable to map " + columnNames[i] + "( " + classes[i].getName() + ")"; throw new RuntimeException(msg); } } return createTableSQL( featureType.getTypeName(), columnNames, sqlTypeNames, nillable, findPrimaryKeyColumnName(featureType), featureType); } /* * search feature type looking for suitable unique column for primary key. */ protected String findPrimaryKeyColumnName(SimpleFeatureType featureType) { String[] suffix = new String[] {"", "_1", "_2"}; String[] base = new String[] {"fid", "id", "gt_id", "ogc_fid"}; for (String b : base) { O: for (String s : suffix) { String name = b + s; for (AttributeDescriptor ad : featureType.getAttributeDescriptors()) { if (ad.getLocalName().equalsIgnoreCase(name)) { continue O; } } return name; } } // practically should never get here, but just fall back and fail later return "fid"; } /** Generates a 'DROP TABLE' sql statement. */ protected String dropTableSQL(SimpleFeatureType featureType, Connection cx) throws Exception { StringBuffer sql = new StringBuffer(); sql.append("DROP TABLE "); encodeTableName(featureType.getTypeName(), sql, null); return sql.toString(); } /** * Ensures that that the specified transaction has access to features specified by a filter. * * <p>If any features matching the filter are locked, and the transaction does not have * authorization with respect to the lock, an exception is thrown. * * @param featureType The feature type / table. * @param filter The filters. * @param tx The transaction. * @param cx The database connection. */ protected void ensureAuthorization( SimpleFeatureType featureType, Filter filter, Transaction tx, Connection cx) throws IOException, SQLException { InProcessLockingManager lm = (InProcessLockingManager) getLockingManager(); // verify if we have any lock to check Map locks = lm.locks(featureType.getTypeName()); if (locks.size() != 0) { // limiting query to only extract locked features if (locks.size() <= MAX_IDS_IN_FILTER) { Set<FeatureId> ids = getLockedIds(locks); Id lockFilter = getFilterFactory().id(ids); // intersect given filter with ids filter filter = getFilterFactory().and(filter, lockFilter); } Query query = new Query(featureType.getTypeName(), filter, Query.NO_NAMES); Statement st = null; try { ResultSet rs = null; if (getSQLDialect() instanceof PreparedStatementSQLDialect) { st = selectSQLPS(featureType, query, cx); PreparedStatement ps = (PreparedStatement) st; ((PreparedStatementSQLDialect) getSQLDialect()).onSelect(ps, cx, featureType); rs = ps.executeQuery(); } else { String sql = selectSQL(featureType, query); st = cx.createStatement(); st.setFetchSize(fetchSize); ((BasicSQLDialect) getSQLDialect()).onSelect(st, cx, featureType); LOGGER.fine(sql); rs = st.executeQuery(sql); } try { PrimaryKey key = getPrimaryKey(featureType); while (rs.next()) { String fid = featureType.getTypeName() + "." + encodeFID(key, rs); lm.assertAccess(featureType.getTypeName(), fid, tx); } } finally { closeSafe(rs); } } finally { closeSafe(st); } } } /** * Extracts a set of FeatureId objects from the locks Map. * * @param locks * @return */ private Set<FeatureId> getLockedIds(Map locks) { Set<FeatureId> ids = new HashSet<FeatureId>(); for (Object lock : locks.keySet()) { ids.add(getFilterFactory().featureId(lock.toString())); } return ids; } /** Helper method for creating geometry association table if it does not exist. */ protected void ensureAssociationTablesExist(Connection cx) throws IOException, SQLException { // look for feature relationship table DatabaseMetaData metadata = cx.getMetaData(); ResultSet tables = metadata.getTables( null, escapeNamePattern(metadata, databaseSchema), escapeNamePattern(metadata, FEATURE_RELATIONSHIP_TABLE), null); try { if (!tables.next()) { // does not exist, create it String sql = createRelationshipTableSQL(cx); LOGGER.log(Level.FINE, "Creating relationship table: {0}", sql); Statement st = cx.createStatement(); try { st.execute(sql); } finally { closeSafe(st); } } } finally { closeSafe(tables); } // look for feature association table tables = metadata.getTables( null, escapeNamePattern(metadata, databaseSchema), escapeNamePattern(metadata, FEATURE_ASSOCIATION_TABLE), null); try { if (!tables.next()) { // does not exist, create it String sql = createAssociationTableSQL(cx); LOGGER.log(Level.FINE, "Creating association table: {0}", sql); Statement st = cx.createStatement(); try { st.execute(sql); } finally { closeSafe(st); } } } finally { closeSafe(tables); } // look up for geometry table tables = metadata.getTables( null, escapeNamePattern(metadata, databaseSchema), escapeNamePattern(metadata, GEOMETRY_TABLE), null); try { if (!tables.next()) { // does not exist, create it String sql = createGeometryTableSQL(cx); LOGGER.log(Level.FINE, "Creating geometry table: {0}", sql); Statement st = cx.createStatement(); try { st.execute(sql); } finally { closeSafe(st); } } } finally { closeSafe(tables); } // look up for multi geometry table tables = metadata.getTables( null, escapeNamePattern(metadata, databaseSchema), escapeNamePattern(metadata, MULTI_GEOMETRY_TABLE), null); try { if (!tables.next()) { // does not exist, create it String sql = createMultiGeometryTableSQL(cx); LOGGER.log(Level.FINE, "Creating multi-geometry table: {0}", sql); Statement st = cx.createStatement(); try { st.execute(sql); } finally { closeSafe(st); } } } finally { closeSafe(tables); } // look up for metadata for geometry association table tables = metadata.getTables( null, escapeNamePattern(metadata, databaseSchema), escapeNamePattern(metadata, GEOMETRY_ASSOCIATION_TABLE), null); try { if (!tables.next()) { // does not exist, create it String sql = createGeometryAssociationTableSQL(cx); LOGGER.log(Level.FINE, "Creating geometry association table: {0}", sql); Statement st = cx.createStatement(); try { st.execute(sql); } finally { closeSafe(st); } } } finally { closeSafe(tables); } } /** * Creates the sql for the relationship table. * * <p>This method is only called when {@link JDBCDataStore#isAssociations()} is true. */ protected String createRelationshipTableSQL(Connection cx) throws SQLException { String[] sqlTypeNames = getSQLTypeNames(new Class[] {String.class, String.class}, cx); String[] columnNames = new String[] {"table", "col"}; return createTableSQL( FEATURE_RELATIONSHIP_TABLE, columnNames, sqlTypeNames, null, null, null); } /** * Creates the sql for the association table. * * <p>This method is only called when {@link JDBCDataStore#isAssociations()} is true. */ protected String createAssociationTableSQL(Connection cx) throws SQLException { String[] sqlTypeNames = getSQLTypeNames( new Class[] {String.class, String.class, String.class, String.class}, cx); String[] columnNames = new String[] {"fid", "rtable", "rcol", "rfid"}; return createTableSQL( FEATURE_ASSOCIATION_TABLE, columnNames, sqlTypeNames, null, null, null); } /** * Creates the sql for the geometry table. * * <p>This method is only called when {@link JDBCDataStore#isAssociations()} is true. */ protected String createGeometryTableSQL(Connection cx) throws SQLException { String[] sqlTypeNames = getSQLTypeNames( new Class[] { String.class, String.class, String.class, String.class, Geometry.class }, cx); String[] columnNames = new String[] {"id", "name", "description", "type", "geometry"}; return createTableSQL(GEOMETRY_TABLE, columnNames, sqlTypeNames, null, null, null); } /** * Creates the sql for the multi_geometry table. * * <p>This method is only called when {@link JDBCDataStore#isAssociations()} is true. */ protected String createMultiGeometryTableSQL(Connection cx) throws SQLException { String[] sqlTypeNames = getSQLTypeNames(new Class[] {String.class, String.class, Boolean.class}, cx); String[] columnNames = new String[] {"id", "mgid", "ref"}; return createTableSQL(MULTI_GEOMETRY_TABLE, columnNames, sqlTypeNames, null, null, null); } /** * Creates the sql for the relationship table. * * <p>This method is only called when {@link JDBCDataStore#isAssociations()} is true. * * @param table The table of the association * @param column The column of the association */ protected String selectRelationshipSQL(String table, String column) throws SQLException { BasicSQLDialect dialect = (BasicSQLDialect) getSQLDialect(); StringBuffer sql = new StringBuffer(); sql.append("SELECT "); dialect.encodeColumnName(null, "table", sql); sql.append(","); dialect.encodeColumnName(null, "col", sql); sql.append(" FROM "); encodeTableName(FEATURE_RELATIONSHIP_TABLE, sql, null); if (table != null) { sql.append(" WHERE "); dialect.encodeColumnName(null, "table", sql); sql.append(" = "); dialect.encodeValue(table, String.class, sql); } if (column != null) { if (table == null) { sql.append(" WHERE "); } else { sql.append(" AND "); } dialect.encodeColumnName(null, "col", sql); sql.append(" = "); dialect.encodeValue(column, String.class, sql); } return sql.toString(); } /** * Creates the prepared statement for a query against the relationship table. * * <p>This method is only called when {@link JDBCDataStore#isAssociations()} is true. * * @param table The table of the association * @param column The column of the association */ protected PreparedStatement selectRelationshipSQLPS(String table, String column, Connection cx) throws SQLException { PreparedStatementSQLDialect dialect = (PreparedStatementSQLDialect) getSQLDialect(); StringBuffer sql = new StringBuffer(); sql.append("SELECT "); dialect.encodeColumnName(null, "table", sql); sql.append(","); dialect.encodeColumnName(null, "col", sql); sql.append(" FROM "); encodeTableName(FEATURE_RELATIONSHIP_TABLE, sql, null); if (table != null) { sql.append(" WHERE "); dialect.encodeColumnName(null, "table", sql); sql.append(" = ? "); } if (column != null) { if (table == null) { sql.append(" WHERE "); } else { sql.append(" AND "); } dialect.encodeColumnName(null, "col", sql); sql.append(" = ? "); } LOGGER.fine(sql.toString()); PreparedStatement ps = cx.prepareStatement(sql.toString()); if (table != null) { ps.setString(1, table); } if (column != null) { ps.setString(table != null ? 2 : 1, column); } return ps; } /** * Creates the sql for the association table. * * <p>This method is only called when {@link JDBCDataStore#isAssociations()} is true. * * @param fid The feature id of the association */ protected String selectAssociationSQL(String fid) throws SQLException { BasicSQLDialect dialect = (BasicSQLDialect) getSQLDialect(); StringBuffer sql = new StringBuffer(); sql.append("SELECT "); dialect.encodeColumnName(null, "fid", sql); sql.append(","); dialect.encodeColumnName(null, "rtable", sql); sql.append(","); dialect.encodeColumnName(null, "rcol", sql); sql.append(", "); dialect.encodeColumnName(null, "rfid", sql); sql.append(" FROM "); encodeTableName(FEATURE_ASSOCIATION_TABLE, sql, null); if (fid != null) { sql.append(" WHERE "); dialect.encodeColumnName(null, "fid", sql); sql.append(" = "); dialect.encodeValue(fid, String.class, sql); } return sql.toString(); } /** * Creates the prepared statement for the association table. * * <p>This method is only called when {@link JDBCDataStore#isAssociations()} is true. * * @param fid The feature id of the association */ protected PreparedStatement selectAssociationSQLPS(String fid, Connection cx) throws SQLException { PreparedStatementSQLDialect dialect = (PreparedStatementSQLDialect) getSQLDialect(); StringBuffer sql = new StringBuffer(); sql.append("SELECT "); dialect.encodeColumnName(null, "fid", sql); sql.append(","); dialect.encodeColumnName(null, "rtable", sql); sql.append(","); dialect.encodeColumnName(null, "rcol", sql); sql.append(", "); dialect.encodeColumnName(null, "rfid", sql); sql.append(" FROM "); encodeTableName(FEATURE_ASSOCIATION_TABLE, sql, null); if (fid != null) { sql.append(" WHERE "); dialect.encodeColumnName(null, "fid", sql); sql.append(" = ?"); } LOGGER.fine(sql.toString()); PreparedStatement ps = cx.prepareStatement(sql.toString()); if (fid != null) { ps.setString(1, fid); } return ps; } /** * Creates the sql for a select from the geometry table. * * <p>This method is only called when {@link JDBCDataStore#isAssociations()} is true. * * @param gid The geometry id to select for, may be <code>null</code> */ protected String selectGeometrySQL(String gid) throws SQLException { BasicSQLDialect dialect = (BasicSQLDialect) getSQLDialect(); StringBuffer sql = new StringBuffer(); sql.append("SELECT "); dialect.encodeColumnName(null, "id", sql); sql.append(","); dialect.encodeColumnName(null, "name", sql); sql.append(","); dialect.encodeColumnName(null, "description", sql); sql.append(","); dialect.encodeColumnName(null, "type", sql); sql.append(","); dialect.encodeColumnName(null, "geometry", sql); sql.append(" FROM "); encodeTableName(GEOMETRY_TABLE, sql, null); if (gid != null) { sql.append(" WHERE "); dialect.encodeColumnName(null, "id", sql); sql.append(" = "); dialect.encodeValue(gid, String.class, sql); } return sql.toString(); } /** * Creates the prepared for a select from the geometry table. * * <p>This method is only called when {@link JDBCDataStore#isAssociations()} is true. * * @param gid The geometry id to select for, may be <code>null</code> */ protected PreparedStatement selectGeometrySQLPS(String gid, Connection cx) throws SQLException { PreparedStatementSQLDialect dialect = (PreparedStatementSQLDialect) getSQLDialect(); StringBuffer sql = new StringBuffer(); sql.append("SELECT "); dialect.encodeColumnName(null, "id", sql); sql.append(","); dialect.encodeColumnName(null, "name", sql); sql.append(","); dialect.encodeColumnName(null, "description", sql); sql.append(","); dialect.encodeColumnName(null, "type", sql); sql.append(","); dialect.encodeColumnName(null, "geometry", sql); sql.append(" FROM "); encodeTableName(GEOMETRY_TABLE, sql, null); if (gid != null) { sql.append(" WHERE "); dialect.encodeColumnName(null, "id", sql); sql.append(" = ?"); } LOGGER.fine(sql.toString()); PreparedStatement ps = cx.prepareStatement(sql.toString()); if (gid != null) { ps.setString(1, gid); } return ps; } /** * Creates the sql for a select from the multi geometry table. * * <p>This method is only called when {@link JDBCDataStore#isAssociations()} is true. * * @param gid The geometry id to select for, may be <code>null</code>. */ protected String selectMultiGeometrySQL(String gid) throws SQLException { BasicSQLDialect dialect = (BasicSQLDialect) getSQLDialect(); StringBuffer sql = new StringBuffer(); sql.append("SELECT "); dialect.encodeColumnName(null, "id", sql); sql.append(","); dialect.encodeColumnName(null, "mgid", sql); sql.append(","); dialect.encodeColumnName(null, "ref", sql); sql.append(" FROM "); encodeTableName(MULTI_GEOMETRY_TABLE, sql, null); if (gid != null) { sql.append(" WHERE "); dialect.encodeColumnName(null, "id", sql); sql.append(" = "); dialect.encodeValue(gid, String.class, sql); } return sql.toString(); } /** * Creates the prepared statement for a select from the multi geometry table. * * <p>This method is only called when {@link JDBCDataStore#isAssociations()} is true. * * @param gid The geometry id to select for, may be <code>null</code>. */ protected PreparedStatement selectMultiGeometrySQLPS(String gid, Connection cx) throws SQLException { PreparedStatementSQLDialect dialect = (PreparedStatementSQLDialect) getSQLDialect(); StringBuffer sql = new StringBuffer(); sql.append("SELECT "); dialect.encodeColumnName(null, "id", sql); sql.append(","); dialect.encodeColumnName(null, "mgid", sql); sql.append(","); dialect.encodeColumnName(null, "ref", sql); sql.append(" FROM "); encodeTableName(MULTI_GEOMETRY_TABLE, sql, null); if (gid != null) { sql.append(" WHERE "); dialect.encodeColumnName(null, "id", sql); sql.append(" = ?"); } LOGGER.fine(sql.toString()); PreparedStatement ps = cx.prepareStatement(sql.toString()); if (gid != null) { ps.setString(1, gid); } return ps; } /** * Creates the sql for the geometry association table. * * <p>This method is only called when {@link JDBCDataStore#isAssociations()} is true. */ protected String createGeometryAssociationTableSQL(Connection cx) throws SQLException { String[] sqlTypeNames = getSQLTypeNames( new Class[] {String.class, String.class, String.class, Boolean.class}, cx); String[] columnNames = new String[] {"fid", "gname", "gid", "ref"}; return createTableSQL( GEOMETRY_ASSOCIATION_TABLE, columnNames, sqlTypeNames, null, null, null); } /** * Creates the sql for a select from the geometry association table. * * <p> * * @param fid The fid to select for, may be <code>null</code> * @param gid The geometry id to select for, may be <code>null</code> * @param gname The geometry name to select for, may be <code>null</code> */ protected String selectGeometryAssociationSQL(String fid, String gid, String gname) throws SQLException { BasicSQLDialect dialect = (BasicSQLDialect) getSQLDialect(); StringBuffer sql = new StringBuffer(); sql.append("SELECT "); dialect.encodeColumnName(null, "fid", sql); sql.append(","); dialect.encodeColumnName(null, "gid", sql); sql.append(","); dialect.encodeColumnName(null, "gname", sql); sql.append(","); dialect.encodeColumnName(null, "ref", sql); sql.append(" FROM "); encodeTableName(GEOMETRY_ASSOCIATION_TABLE, sql, null); if (fid != null) { sql.append(" WHERE "); dialect.encodeColumnName(null, "fid", sql); sql.append(" = "); dialect.encodeValue(fid, String.class, sql); } if (gid != null) { if (fid == null) { sql.append(" WHERE "); } else { sql.append(" AND "); } dialect.encodeColumnName(null, "gid", sql); sql.append(" = "); dialect.encodeValue(gid, String.class, sql); } if (gname != null) { if ((fid == null) && (gid == null)) { sql.append(" WHERE "); } else { sql.append(" AND "); } dialect.encodeColumnName(null, "gname", sql); sql.append(" = "); dialect.encodeValue(gname, String.class, sql); } return sql.toString(); } /** * Creates the prepared statement for a select from the geometry association table. * * <p> * * @param fid The fid to select for, may be <code>null</code> * @param gid The geometry id to select for, may be <code>null</code> * @param gname The geometry name to select for, may be <code>null</code> */ protected PreparedStatement selectGeometryAssociationSQLPS( String fid, String gid, String gname, Connection cx) throws SQLException { PreparedStatementSQLDialect dialect = (PreparedStatementSQLDialect) getSQLDialect(); StringBuffer sql = new StringBuffer(); sql.append("SELECT "); dialect.encodeColumnName(null, "fid", sql); sql.append(","); dialect.encodeColumnName(null, "gid", sql); sql.append(","); dialect.encodeColumnName(null, "gname", sql); sql.append(","); dialect.encodeColumnName(null, "ref", sql); sql.append(" FROM "); encodeTableName(GEOMETRY_ASSOCIATION_TABLE, sql, null); if (fid != null) { sql.append(" WHERE "); dialect.encodeColumnName(null, "fid", sql); sql.append(" = ? "); } if (gid != null) { if (fid == null) { sql.append(" WHERE "); } else { sql.append(" AND "); } dialect.encodeColumnName(null, "gid", sql); sql.append(" = ? "); } if (gname != null) { if ((fid == null) && (gid == null)) { sql.append(" WHERE "); } else { sql.append(" AND "); } dialect.encodeColumnName(null, "gname", sql); sql.append(" = ?"); } LOGGER.fine(sql.toString()); PreparedStatement ps = cx.prepareStatement(sql.toString()); if (fid != null) { ps.setString(1, fid); } if (gid != null) { ps.setString(fid != null ? 2 : 1, gid); } if (gname != null) { ps.setString(fid != null ? (gid != null ? 3 : 2) : (gid != null ? 2 : 1), gname); } return ps; } /** Helper method for building a 'CREATE TABLE' sql statement. */ private String createTableSQL( String tableName, String[] columnNames, String[] sqlTypeNames, boolean[] nillable, String pkeyColumn, SimpleFeatureType featureType) throws SQLException { // build the create table sql StringBuffer sql = new StringBuffer(); dialect.encodeCreateTable(sql); encodeTableName(tableName, sql, null); sql.append(" ( "); // primary key column if (pkeyColumn != null) { dialect.encodePrimaryKey(pkeyColumn, sql); sql.append(", "); } // normal attributes for (int i = 0; i < columnNames.length; i++) { // the column name dialect.encodeColumnName(null, columnNames[i], sql); sql.append(" "); // some sql dialects require varchars to have an // associated size with them int length = -1; if (sqlTypeNames[i].toUpperCase().startsWith("VARCHAR")) { if (featureType != null) { AttributeDescriptor att = featureType.getDescriptor(columnNames[i]); length = findVarcharColumnLength(att); } } // only apply a length if one exists (i.e. to applicable varchars) if (length == -1) { dialect.encodeColumnType(sqlTypeNames[i], sql); } else { dialect.encodeColumnType(sqlTypeNames[i] + "(" + length + ")", sql); } // nullable if (nillable != null && !nillable[i]) { sql.append(" NOT NULL "); } // delegate to dialect to encode column postamble if (featureType != null) { AttributeDescriptor att = featureType.getDescriptor(columnNames[i]); dialect.encodePostColumnCreateTable(att, sql); } // sql.append(sqlTypeNames[i]); if (i < (sqlTypeNames.length - 1)) { sql.append(", "); } } sql.append(" ) "); // encode anything post create table dialect.encodePostCreateTable(tableName, sql); return sql.toString(); } /** * Searches the attribute descriptor restrictions in an attempt to determine the length of the * specified varchar column. */ private Integer findVarcharColumnLength(AttributeDescriptor att) { for (Filter r : att.getType().getRestrictions()) { if (r instanceof PropertyIsLessThanOrEqualTo) { PropertyIsLessThanOrEqualTo c = (PropertyIsLessThanOrEqualTo) r; if (c.getExpression1() instanceof Function && ((Function) c.getExpression1()) .getName() .toLowerCase() .endsWith("length")) { if (c.getExpression2() instanceof Literal) { Integer length = c.getExpression2().evaluate(null, Integer.class); if (length != null) { return length; } } } } } return dialect.getDefaultVarcharSize(); } /** * Helper method for determining what the sql type names are for a set of classes. * * <p>This method uses a combination of dialect mappings and database metadata to determine * which sql types map to the specified classes. */ private String[] getSQLTypeNames(Class[] classes, Connection cx) throws SQLException { // figure out what the sql types are corresponding to the feature type // attributes int[] sqlTypes = new int[classes.length]; String[] sqlTypeNames = new String[sqlTypes.length]; for (int i = 0; i < classes.length; i++) { Class clazz = classes[i]; Integer sqlType = getMapping(clazz); if (sqlType == null) { LOGGER.warning("No sql type mapping for: " + clazz); sqlType = Types.OTHER; } sqlTypes[i] = sqlType; // if this a geometric type, get the name from teh dialect // if ( attributeType instanceof GeometryDescriptor ) { if (Geometry.class.isAssignableFrom(clazz)) { String sqlTypeName = dialect.getGeometryTypeName(sqlType); if (sqlTypeName != null) { sqlTypeNames[i] = sqlTypeName; } } // check types previously read from DB String sqlTypeDBName = getDBsqlTypesCache().get(sqlType); if (sqlTypeDBName != null) { sqlTypeNames[i] = sqlTypeDBName; } } // GEOT-6347 if all sql type names have been found in dialect dont // go to database boolean allTypesFound = !ArrayUtils.contains(sqlTypeNames, null); if (!allTypesFound) { LOGGER.log(Level.WARNING, "Fetching fields from Database"); // figure out the type names that correspond to the sql types from // the database metadata DatabaseMetaData metaData = cx.getMetaData(); /* * <LI><B>TYPE_NAME</B> String => Type name * <LI><B>DATA_TYPE</B> int => SQL data type from java.sql.Types * <LI><B>PRECISION</B> int => maximum precision * <LI><B>LITERAL_PREFIX</B> String => prefix used to quote a literal * (may be <code>null</code>) * <LI><B>LITERAL_SUFFIX</B> String => suffix used to quote a literal (may be <code>null</code>) * <LI><B>CREATE_PARAMS</B> String => parameters used in creating * the type (may be <code>null</code>) * <LI><B>NULLABLE</B> short => can you use NULL for this type. * <UL> * <LI> typeNoNulls - does not allow NULL values * <LI> typeNullable - allows NULL values * <LI> typeNullableUnknown - nullability unknown * </UL> * <LI><B>CASE_SENSITIVE</B> boolean=> is it case sensitive. * <LI><B>SEARCHABLE</B> short => can you use "WHERE" based on this type: * <UL> * <LI> typePredNone - No support * <LI> typePredChar - Only supported with WHERE .. LIKE * <LI> typePredBasic - Supported except for WHERE .. LIKE * <LI> typeSearchable - Supported for all WHERE .. * </UL> * <LI><B>UNSIGNED_ATTRIBUTE</B> boolean => is it unsigned. * <LI><B>FIXED_PREC_SCALE</B> boolean => can it be a money value. * <LI><B>AUTO_INCREMENT</B> boolean => can it be used for an * auto-increment value. * <LI><B>LOCAL_TYPE_NAME</B> String => localized version of type name * (may be <code>null</code>) * <LI><B>MINIMUM_SCALE</B> short => minimum scale supported * <LI><B>MAXIMUM_SCALE</B> short => maximum scale supported * <LI><B>SQL_DATA_TYPE</B> int => unused * <LI><B>SQL_DATETIME_SUB</B> int => unused * <LI><B>NUM_PREC_RADIX</B> int => usually 2 or 10 */ ResultSet types = metaData.getTypeInfo(); try { while (types.next()) { int sqlType = types.getInt("DATA_TYPE"); String sqlTypeName = types.getString("TYPE_NAME"); for (int i = 0; i < sqlTypes.length; i++) { // check if we already have the type name from the dialect if (sqlTypeNames[i] != null) { continue; } if (sqlType == sqlTypes[i]) { sqlTypeNames[i] = sqlTypeName; // GEOT-6347 // cache the sqlType which required going to database for sql types getDBsqlTypesCache().putIfAbsent(sqlType, sqlTypeName); } } } } finally { closeSafe(types); } } // apply the overrides specified by the dialect Map<Integer, String> overrides = getSqlTypeToSqlTypeNameOverrides(); for (int i = 0; i < sqlTypes.length; i++) { String override = overrides.get(sqlTypes[i]); if (override != null) sqlTypeNames[i] = override; } return sqlTypeNames; } /** * Generates a 'SELECT p1, p2, ... FROM ... WHERE ...' statement. * * @param featureType the feature type that the query must return (may contain less attributes * than the native one) * @param query the query to be run. The type name and property will be ignored, as they are * supposed to have been already embedded into the provided feature type */ protected String selectSQL(SimpleFeatureType featureType, Query query) throws IOException, SQLException { StringBuffer sql = new StringBuffer(); sql.append("SELECT "); // column names selectColumns(featureType, null, query, sql); sql.setLength(sql.length() - 1); dialect.encodePostSelect(featureType, sql); // from sql.append(" FROM "); encodeTableName(featureType.getTypeName(), sql, setKeepWhereClausePlaceHolderHint(query)); // filtering Filter filter = query.getFilter(); if (filter != null && !Filter.INCLUDE.equals(filter)) { sql.append(" WHERE "); // encode filter filter(featureType, filter, sql); } // sorting sort(featureType, query.getSortBy(), null, sql); // encode limit/offset, if necessary applyLimitOffset(sql, query.getStartIndex(), query.getMaxFeatures()); // add search hints if the dialect supports them applySearchHints(featureType, query, sql); return sql.toString(); } private void applySearchHints(SimpleFeatureType featureType, Query query, StringBuffer sql) { // we can apply search hints only on real tables if (virtualTables.containsKey(featureType.getTypeName())) { return; } dialect.handleSelectHints(sql, featureType, query); } protected String selectJoinSQL(SimpleFeatureType featureType, JoinInfo join, Query query) throws IOException, SQLException { StringBuffer sql = new StringBuffer(); sql.append("SELECT "); // column names selectColumns(featureType, join.getPrimaryAlias(), query, sql); // joined columns for (JoinPart part : join.getParts()) { selectColumns(part.getQueryFeatureType(), part.getAlias(), query, sql); } sql.setLength(sql.length() - 1); dialect.encodePostSelect(featureType, sql); // from sql.append(" FROM "); // join clauses encodeTableJoin(featureType, join, query, sql); // filtering encodeWhereJoin(featureType, join, sql); // TODO: sorting sort(featureType, query.getSortBy(), join.getPrimaryAlias(), sql); // finally encode limit/offset, if necessary applyLimitOffset(sql, query.getStartIndex(), query.getMaxFeatures()); return sql.toString(); } void selectColumns(SimpleFeatureType featureType, String prefix, Query query, StringBuffer sql) throws IOException { // primary key PrimaryKey key = null; try { key = getPrimaryKey(featureType); } catch (IOException e) { throw new RuntimeException(e); } Set<String> pkColumnNames = getColumnNames(key); // we need to add the primary key columns only if they are not already exposed for (PrimaryKeyColumn col : key.getColumns()) { dialect.encodeColumnName(prefix, col.getName(), sql); if (prefix != null) { // if a prefix is specified means we are joining so use a prefix to avoid clashing // with primary key columsn with the same name from other tables in the join dialect.encodeColumnAlias(prefix + "_" + col.getName(), sql); } sql.append(","); } // other columns for (AttributeDescriptor att : featureType.getAttributeDescriptors()) { String columnName = att.getLocalName(); // skip the eventually exposed pk column values if (pkColumnNames.contains(columnName)) continue; String alias = null; if (att.getUserData().containsKey(JDBC_COLUMN_ALIAS)) { alias = (String) att.getUserData().get(JDBC_COLUMN_ALIAS); } if (att instanceof GeometryDescriptor) { // encode as geometry encodeGeometryColumn((GeometryDescriptor) att, prefix, sql, query.getHints()); if (alias == null) { // alias it to be the name of the original geometry alias = columnName; } } else { dialect.encodeColumnName(prefix, columnName, sql); } if (alias != null) { dialect.encodeColumnAlias(alias, sql); } sql.append(","); } } FilterToSQL filter(SimpleFeatureType featureType, Filter filter, StringBuffer sql) throws IOException { SimpleFeatureType fullSchema = getSchema(featureType.getTypeName()); FilterToSQL toSQL = getFilterToSQL(fullSchema); return filter(featureType, filter, sql, toSQL); } FilterToSQL filter( SimpleFeatureType featureType, Filter filter, StringBuffer sql, FilterToSQL toSQL) throws IOException { try { // grab the full feature type, as we might be encoding a filter // that uses attributes that aren't returned in the results toSQL.setInline(true); String filterSql = toSQL.encodeToString(filter); int whereClauseIndex = sql.indexOf(WHERE_CLAUSE_PLACE_HOLDER); if (whereClauseIndex != -1) { sql.replace( whereClauseIndex, whereClauseIndex + WHERE_CLAUSE_PLACE_HOLDER_LENGTH, "AND " + filterSql); sql.append("1 = 1"); } else { sql.append(filterSql); } return toSQL; } catch (FilterToSQLException e) { throw new RuntimeException(e); } } private FilterToSQL getFilterToSQL(SimpleFeatureType fullSchema) { return dialect instanceof PreparedStatementSQLDialect ? createPreparedFilterToSQL(fullSchema) : createFilterToSQL(fullSchema); } /** * Encodes the sort-by portion of an sql query * * @param featureType * @param sort * @param key * @param sql * @throws IOException */ void sort(SimpleFeatureType featureType, SortBy[] sort, String prefix, StringBuffer sql) throws IOException { if ((sort != null) && (sort.length > 0)) { PrimaryKey key = getPrimaryKey(featureType); sql.append(" ORDER BY "); for (int i = 0; i < sort.length; i++) { String order; if (sort[i].getSortOrder() == SortOrder.DESCENDING) { order = " DESC"; } else { order = " ASC"; } if (SortBy.NATURAL_ORDER.equals(sort[i]) || SortBy.REVERSE_ORDER.equals(sort[i])) { if (key instanceof NullPrimaryKey) throw new IOException( "Cannot do natural order without a primary key, please add it or " + "specify a manual sort over existing attributes"); for (PrimaryKeyColumn col : key.getColumns()) { dialect.encodeColumnName(prefix, col.getName(), sql); sql.append(order); sql.append(","); } } else { dialect.encodeColumnName( prefix, getPropertyName(featureType, sort[i].getPropertyName()), sql); sql.append(order); sql.append(","); } } sql.setLength(sql.length() - 1); } } /** * Generates a 'SELECT p1, p2, ... FROM ... WHERE ...' prepared statement. * * @param featureType the feature type that the query must return (may contain less attributes * than the native one) * @param query the query to be run. The type name and property will be ignored, as they are * supposed to have been already embedded into the provided feature type * @param cx The database connection to be used to create the prepared statement */ protected PreparedStatement selectSQLPS( SimpleFeatureType featureType, Query query, Connection cx) throws SQLException, IOException { StringBuffer sql = new StringBuffer(); sql.append("SELECT "); // column names selectColumns(featureType, null, query, sql); sql.setLength(sql.length() - 1); dialect.encodePostSelect(featureType, sql); sql.append(" FROM "); encodeTableName(featureType.getTypeName(), sql, setKeepWhereClausePlaceHolderHint(query)); // filtering PreparedFilterToSQL toSQL = null; Filter filter = query.getFilter(); if (filter != null && !Filter.INCLUDE.equals(filter)) { sql.append(" WHERE "); // encode filter toSQL = (PreparedFilterToSQL) filter(featureType, filter, sql); } // sorting sort(featureType, query.getSortBy(), null, sql); // finally encode limit/offset, if necessary applyLimitOffset(sql, query.getStartIndex(), query.getMaxFeatures()); // add search hints if the dialect supports them applySearchHints(featureType, query, sql); LOGGER.fine(sql.toString()); PreparedStatement ps = cx.prepareStatement( sql.toString(), ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); ps.setFetchSize(fetchSize); if (toSQL != null) { setPreparedFilterValues(ps, toSQL, 0, cx); } return ps; } protected PreparedStatement selectJoinSQLPS( SimpleFeatureType featureType, JoinInfo join, Query query, Connection cx) throws SQLException, IOException { StringBuffer sql = new StringBuffer(); sql.append("SELECT "); selectColumns(featureType, join.getPrimaryAlias(), query, sql); // joined columns for (JoinPart part : join.getParts()) { selectColumns(part.getQueryFeatureType(), part.getAlias(), query, sql); } sql.setLength(sql.length() - 1); dialect.encodePostSelect(featureType, sql); sql.append(" FROM "); // join clauses encodeTableJoin(featureType, join, query, sql); // filtering List<FilterToSQL> toSQLs = encodeWhereJoin(featureType, join, sql); // sorting sort(featureType, query.getSortBy(), join.getPrimaryAlias(), sql); // finally encode limit/offset, if necessary applyLimitOffset(sql, query.getStartIndex(), query.getMaxFeatures()); LOGGER.fine(sql.toString()); PreparedStatement ps = cx.prepareStatement( sql.toString(), ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); ps.setFetchSize(fetchSize); setPreparedFilterValues(ps, toSQLs, cx); return ps; } /** * Helper method for setting the values of the WHERE class of a prepared statement from a list * of PreparedFilterToSQL. */ protected void setPreparedFilterValues(PreparedStatement ps, List toSQLs, Connection cx) throws SQLException { int offset = 0; for (PreparedFilterToSQL toSQL : (List<PreparedFilterToSQL>) toSQLs) { setPreparedFilterValues(ps, toSQL, offset, cx); offset += toSQL.getLiteralValues().size(); } } /** Helper method for setting the values of the WHERE class of a prepared statement. */ public void setPreparedFilterValues( PreparedStatement ps, PreparedFilterToSQL toSQL, int offset, Connection cx) throws SQLException { PreparedStatementSQLDialect dialect = (PreparedStatementSQLDialect) getSQLDialect(); for (int i = 0; i < toSQL.getLiteralValues().size(); i++) { Object value = toSQL.getLiteralValues().get(i); Class binding = toSQL.getLiteralTypes().get(i); Integer srid = toSQL.getSRIDs().get(i); Integer dimension = toSQL.getDimensions().get(i); AttributeDescriptor ad = toSQL.getDescriptors().get(i); if (srid == null) { srid = -1; } if (dimension == null) { dimension = 2; } if (binding != null && Geometry.class.isAssignableFrom(binding)) { dialect.setGeometryValue( (Geometry) value, dimension, srid, binding, ps, offset + i + 1); } else if (ad != null && isArray(ad)) { dialect.setArrayValue(value, ad, ps, offset + i + 1, cx); } else { dialect.setValue(value, binding, ps, offset + i + 1, cx); } if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine((i + 1) + " = " + value); } } } /** * Returns true if the attribute descriptor matches a native SQL array (as recorded in its user * data via {@link #JDBC_NATIVE_TYPE} * * @return */ private boolean isArray(AttributeDescriptor att) { Integer nativeType = (Integer) att.getUserData().get(JDBC_NATIVE_TYPE); return Objects.equals(Types.ARRAY, nativeType); } /** * Helper method for executing a property name against a feature type. * * <p>This method will fall back on {@link PropertyName#getPropertyName()} if it does not * evaulate against the feature type. */ protected String getPropertyName(SimpleFeatureType featureType, PropertyName propertyName) { AttributeDescriptor att = (AttributeDescriptor) propertyName.evaluate(featureType); if (att != null) { return att.getLocalName(); } return propertyName.getPropertyName(); } /** * Generates a 'SELECT' sql statement which selects bounds. * * @param featureType The feature type / table. * @param query Specifies which features are to be used for the bounds computation (and in * particular uses filter, start index and max features) */ protected String selectBoundsSQL(SimpleFeatureType featureType, Query query) throws SQLException { StringBuffer sql = new StringBuffer(); boolean offsetLimit = checkLimitOffset(query.getStartIndex(), query.getMaxFeatures()); if (offsetLimit) { // envelopes are aggregates, just like count, so we must first isolate // the rows against which the aggregate will work in a subquery sql.append(" SELECT *"); } else { sql.append("SELECT "); buildEnvelopeAggregates(featureType, sql); } sql.append(" FROM "); encodeTableName(featureType.getTypeName(), sql, setKeepWhereClausePlaceHolderHint(query)); Filter filter = query.getFilter(); if (filter != null && !Filter.INCLUDE.equals(filter)) { // encode filter try { FilterToSQL toSQL = createFilterToSQL(featureType); sql.append(" ").append(toSQL.encodeToString(filter)); } catch (FilterToSQLException e) { throw new RuntimeException(e); } } // finally encode limit/offset, if necessary if (offsetLimit) { applyLimitOffset(sql, query.getStartIndex(), query.getMaxFeatures()); // build the prologue StringBuffer sb = new StringBuffer(); sb.append("SELECT "); buildEnvelopeAggregates(featureType, sb); sb.append("FROM ("); // wrap the existing query sql.insert(0, sb.toString()); sql.append(")"); dialect.encodeTableAlias("GT2_BOUNDS_", sql); } // add search hints if the dialect supports them applySearchHints(featureType, query, sql); return sql.toString(); } /** * Generates a 'SELECT' prepared statement which selects bounds. * * @param featureType The feature type / table. * @param query Specifies which features are to be used for the bounds computation (and in * particular uses filter, start index and max features) * @param cx A database connection. */ protected PreparedStatement selectBoundsSQLPS( SimpleFeatureType featureType, Query query, Connection cx) throws SQLException { StringBuffer sql = new StringBuffer(); boolean offsetLimit = checkLimitOffset(query.getStartIndex(), query.getMaxFeatures()); if (offsetLimit) { // envelopes are aggregates, just like count, so we must first isolate // the rows against which the aggregate will work in a subquery sql.append(" SELECT *"); } else { sql.append("SELECT "); buildEnvelopeAggregates(featureType, sql); } sql.append(" FROM "); encodeTableName(featureType.getTypeName(), sql, setKeepWhereClausePlaceHolderHint(query)); // encode the filter PreparedFilterToSQL toSQL = null; Filter filter = query.getFilter(); if (filter != null && !Filter.INCLUDE.equals(filter)) { // encode filter try { toSQL = createPreparedFilterToSQL(featureType); int whereClauseIndex = sql.indexOf(WHERE_CLAUSE_PLACE_HOLDER); if (whereClauseIndex != -1) { toSQL.setInline(true); sql.replace( whereClauseIndex, whereClauseIndex + WHERE_CLAUSE_PLACE_HOLDER_LENGTH, "AND " + toSQL.encodeToString(filter)); toSQL.setInline(false); } else { sql.append(" ").append(toSQL.encodeToString(filter)); } } catch (FilterToSQLException e) { throw new RuntimeException(e); } } // finally encode limit/offset, if necessary if (offsetLimit) { applyLimitOffset(sql, query.getStartIndex(), query.getMaxFeatures()); // build the prologue StringBuffer sb = new StringBuffer(); sb.append("SELECT "); buildEnvelopeAggregates(featureType, sb); sb.append("FROM ("); // wrap the existing query sql.insert(0, sb.toString()); sql.append(")"); dialect.encodeTableAlias("GT2_BOUNDS_", sql); } // add search hints if the dialect supports them applySearchHints(featureType, query, sql); LOGGER.fine(sql.toString()); PreparedStatement ps = cx.prepareStatement(sql.toString()); if (toSQL != null) { setPreparedFilterValues(ps, toSQL, 0, cx); } return ps; } /** * Builds a list of the aggregate function calls necesary to compute each geometry column bounds * * @param featureType * @param sql */ void buildEnvelopeAggregates(SimpleFeatureType featureType, StringBuffer sql) { // walk through all geometry attributes and build the query for (Iterator a = featureType.getAttributeDescriptors().iterator(); a.hasNext(); ) { AttributeDescriptor attribute = (AttributeDescriptor) a.next(); if (attribute instanceof GeometryDescriptor) { String geometryColumn = attribute.getLocalName(); dialect.encodeGeometryEnvelope(featureType.getTypeName(), geometryColumn, sql); sql.append(","); } } sql.setLength(sql.length() - 1); } protected String selectAggregateSQL( String function, Expression att, List<Expression> groupByExpressions, SimpleFeatureType featureType, Query query, LimitingVisitor visitor) throws SQLException, IOException { StringBuffer sql = new StringBuffer(); doSelectAggregateSQL(function, att, groupByExpressions, featureType, query, visitor, sql); return sql.toString(); } protected PreparedStatement selectAggregateSQLPS( String function, Expression att, List<Expression> groupByExpressions, SimpleFeatureType featureType, Query query, LimitingVisitor visitor, Connection cx) throws SQLException, IOException { StringBuffer sql = new StringBuffer(); List<FilterToSQL> toSQL = doSelectAggregateSQL( function, att, groupByExpressions, featureType, query, visitor, sql); LOGGER.fine(sql.toString()); PreparedStatement ps = cx.prepareStatement( sql.toString(), ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); ps.setFetchSize(fetchSize); setPreparedFilterValues(ps, toSQL, cx); return ps; } /** * Helper method to factor out some commonalities between selectAggregateSQL, and * selectAggregateSQLPS */ List<FilterToSQL> doSelectAggregateSQL( String function, Expression expr, List<Expression> groupByExpressions, SimpleFeatureType featureType, Query query, LimitingVisitor visitor, StringBuffer sql) throws SQLException, IOException { JoinInfo join = !query.getJoins().isEmpty() ? JoinInfo.create(query, featureType, this) : null; List<FilterToSQL> toSQL = new ArrayList(); boolean queryLimitOffset = checkLimitOffset(query.getStartIndex(), query.getMaxFeatures()); boolean visitorLimitOffset = visitor == null ? false : visitor.hasLimits() && dialect.isLimitOffsetSupported(); // grouping over expressions is complex, as we need boolean groupByComplexExpressions = hasComplexExpressions(groupByExpressions); if (queryLimitOffset && !visitorLimitOffset && !groupByComplexExpressions) { if (join != null) { // don't select * to avoid ambigous result set sql.append("SELECT "); dialect.encodeColumnName(null, join.getPrimaryAlias(), sql); sql.append(".* FROM "); } else { sql.append("SELECT * FROM "); } } else { sql.append("SELECT "); FilterToSQL filterToSQL = getFilterToSQL(featureType); if (groupByExpressions != null && !groupByExpressions.isEmpty()) { try { // we encode all the group by attributes as columns names int i = 1; for (Expression expression : groupByExpressions) { sql.append(filterToSQL.encodeToString(expression)); // if we are using complex group by, we have to given them an alias if (groupByComplexExpressions) { sql.append(" as ").append(getAggregateExpressionAlias(i++)); } sql.append(", "); } } catch (FilterToSQLException e) { throw new RuntimeException("Failed to encode group by expressions", e); } } if (groupByComplexExpressions) { // if encoding a sub-query, the source of the aggregation function must // also be given an alias (we could use * too, but there is a risk of conflicts) if (expr != null) { try { sql.append(filterToSQL.encodeToString(expr)); sql.append(" as gt_agg_src"); } catch (FilterToSQLException e) { throw new RuntimeException("Failed to encode group by expressions", e); } } else { // remove the last comma and space sql.setLength(sql.length() - 2); } } else { encodeFunction(function, expr, sql, filterToSQL); } toSQL.add(filterToSQL); sql.append(" FROM "); } if (join != null) { encodeTableJoin(featureType, join, query, sql); } else { encodeTableName( featureType.getTypeName(), sql, setKeepWhereClausePlaceHolderHint(query)); } if (join != null) { toSQL.addAll(encodeWhereJoin(featureType, join, sql)); } else { Filter filter = query.getFilter(); if (filter != null && !Filter.INCLUDE.equals(filter)) { sql.append(" WHERE "); toSQL.add(filter(featureType, filter, sql)); } } if (dialect.isAggregatedSortSupported(function)) { sort(featureType, query.getSortBy(), null, sql); } // apply limits if (visitorLimitOffset) { applyLimitOffset(sql, visitor.getStartIndex(), visitor.getMaxFeatures()); } else if (queryLimitOffset) { applyLimitOffset(sql, query.getStartIndex(), query.getMaxFeatures()); } // if the limits were in query or there is a group by with complex expressions // we need to roll what was built so far in a sub-query if (queryLimitOffset || groupByComplexExpressions) { StringBuffer sql2 = new StringBuffer("SELECT "); try { if (groupByExpressions != null && !groupByExpressions.isEmpty()) { FilterToSQL filterToSQL = getFilterToSQL(featureType); int i = 1; for (Expression expression : groupByExpressions) { if (groupByComplexExpressions) { sql2.append(getAggregateExpressionAlias(i++)); } else { sql2.append(filterToSQL.encodeToString(expression)); } sql2.append(","); } toSQL.add(filterToSQL); } } catch (FilterToSQLException e) { throw new RuntimeException("Failed to encode group by expressions", e); } FilterToSQL filterToSQL = getFilterToSQL(featureType); if (groupByComplexExpressions) { if ("count".equals(function)) { sql2.append("count(*)"); } else { sql2.append(function).append("(").append("gt_agg_src").append(")"); } } else { encodeFunction(function, expr, sql2, filterToSQL); } toSQL.add(filterToSQL); sql2.append(" AS gt_result_"); sql2.append(" FROM ("); sql.insert(0, sql2.toString()); sql.append(") gt_limited_"); } FilterToSQL filterToSQL = getFilterToSQL(featureType); encodeGroupByStatement(groupByExpressions, sql, filterToSQL, groupByComplexExpressions); toSQL.add(filterToSQL); // add search hints if the dialect supports them applySearchHints(featureType, query, sql); return toSQL; } private String getAggregateExpressionAlias(int idx) { return "gt_agg_" + idx; } /** * Returns true if the expressions have anything but property names * * @param expressions * @return */ private boolean hasComplexExpressions(List<Expression> expressions) { if (expressions == null || expressions.isEmpty()) { return false; } return expressions.stream().anyMatch(x -> !(x instanceof PropertyName)); } /** * Helper method that adds a group by statement to the SQL query. If the list of group by * attributes is empty or NULL no group by statement is add. * * @param groupByExpressions the group by attributes to be encoded * @param sql the sql query buffer */ protected void encodeGroupByStatement( List<Expression> groupByExpressions, StringBuffer sql, FilterToSQL filterToSQL, boolean aggregateOnExpression) { if (groupByExpressions == null || groupByExpressions.isEmpty()) { // there is not group by attributes to encode so nothing to do return; } sql.append(" GROUP BY "); int i = 1; for (Expression groupByExpression : groupByExpressions) { if (aggregateOnExpression) { sql.append("gt_agg_" + i++); } else { try { sql.append(filterToSQL.encodeToString(groupByExpression)); } catch (FilterToSQLException e) { throw new RuntimeException(e); } } sql.append(", "); } sql.setLength(sql.length() - 2); } protected void encodeFunction( String function, Expression expression, StringBuffer sql, FilterToSQL filterToSQL) { sql.append(function).append("("); if (expression == null) { sql.append("*"); } else { try { sql.append(filterToSQL.encodeToString(expression)); } catch (FilterToSQLException e) { throw new RuntimeException(e); } } sql.append(")"); } /** Generates a 'DELETE FROM' sql statement. */ protected String deleteSQL(SimpleFeatureType featureType, Filter filter) throws SQLException { StringBuffer sql = new StringBuffer(); sql.append("DELETE FROM "); encodeTableName(featureType.getTypeName(), sql, null); if (filter != null && !Filter.INCLUDE.equals(filter)) { // encode filter try { FilterToSQL toSQL = createFilterToSQL(featureType); sql.append(" ").append(toSQL.encodeToString(filter)); } catch (FilterToSQLException e) { throw new RuntimeException(e); } } return sql.toString(); } /** Generates a 'DELETE FROM' prepared statement. */ protected PreparedStatement deleteSQLPS( SimpleFeatureType featureType, Filter filter, Connection cx) throws SQLException { StringBuffer sql = new StringBuffer(); sql.append("DELETE FROM "); encodeTableName(featureType.getTypeName(), sql, null); PreparedFilterToSQL toSQL = null; if (filter != null && !Filter.INCLUDE.equals(filter)) { // encode filter try { toSQL = createPreparedFilterToSQL(featureType); sql.append(" ").append(toSQL.encodeToString(filter)); } catch (FilterToSQLException e) { throw new RuntimeException(e); } } LOGGER.fine(sql.toString()); PreparedStatement ps = cx.prepareStatement(sql.toString()); if (toSQL != null) { setPreparedFilterValues(ps, toSQL, 0, cx); } return ps; } /** * Generates a 'INSERT INFO' sql statement. * * @throws IOException */ protected String insertSQL( SimpleFeatureType featureType, SimpleFeature feature, KeysFetcher keysFetcher, Connection cx) throws SQLException, IOException { BasicSQLDialect dialect = (BasicSQLDialect) getSQLDialect(); StringBuffer sql = new StringBuffer(); sql.append("INSERT INTO "); encodeTableName(featureType.getTypeName(), sql, null); // column names sql.append(" ( "); for (int i = 0; i < featureType.getAttributeCount(); i++) { String colName = featureType.getDescriptor(i).getLocalName(); // skip the pk columns in case we have exposed them if (keysFetcher.isKey(colName)) { continue; } dialect.encodeColumnName(null, colName, sql); sql.append(","); } // primary key values keysFetcher.addKeyColumns(sql); sql.setLength(sql.length() - 1); // values sql.append(" ) VALUES ( "); for (int i = 0; i < featureType.getAttributeCount(); i++) { AttributeDescriptor att = featureType.getDescriptor(i); String colName = att.getLocalName(); // skip the pk columns in case we have exposed them, we grab the // value from the pk itself if (keysFetcher.isKey(colName)) { continue; } Class binding = att.getType().getBinding(); Object value = feature.getAttribute(colName); if (value == null) { if (!att.isNillable()) { throw new IOException( "Cannot set a NULL value on the not null column " + colName); } sql.append("null"); } else { if (Geometry.class.isAssignableFrom(binding)) { try { Geometry g = (Geometry) value; int srid = getGeometrySRID(g, att); int dimension = getGeometryDimension(g, att); dialect.encodeGeometryValue(g, dimension, srid, sql); } catch (IOException e) { throw new RuntimeException(e); } } else { dialect.encodeValue(value, binding, sql); } } sql.append(","); } // handle the primary key keysFetcher.setKeyValues(this, cx, featureType, feature, sql); sql.setLength(sql.length() - 1); // remove last comma sql.append(")"); return sql.toString(); } /** * Returns the set of the primary key column names. The set is guaranteed to have the same * iteration order as the primary key. */ protected static LinkedHashSet<String> getColumnNames(PrimaryKey key) { LinkedHashSet<String> pkColumnNames = new LinkedHashSet<String>(); for (PrimaryKeyColumn pkcol : key.getColumns()) { pkColumnNames.add(pkcol.getName()); } return pkColumnNames; } /** * Looks up the geometry srs by trying a number of heuristics. Returns -1 if all attempts at * guessing the srid failed. */ protected int getGeometrySRID(Geometry g, AttributeDescriptor descriptor) throws IOException { int srid = getDescriptorSRID(descriptor); if (g == null) { return srid; } // check for srid in the jts geometry then if (srid <= 0 && g.getSRID() > 0) { srid = g.getSRID(); } // check if the geometry has anything if (srid <= 0 && g.getUserData() instanceof CoordinateReferenceSystem) { // check for crs object CoordinateReferenceSystem crs = (CoordinateReferenceSystem) g.getUserData(); try { Integer candidate = CRS.lookupEpsgCode(crs, false); if (candidate != null) srid = candidate; } catch (Exception e) { // ok, we tried... } } return srid; } /** * Looks up the geometry dimension by trying a number of heuristics. Returns 2 if all attempts * at guessing the dimension failed. */ protected int getGeometryDimension(Geometry g, AttributeDescriptor descriptor) throws IOException { int dimension = getDescriptorDimension(descriptor); if (g == null || dimension > 0) { return dimension; } // check for dimension in the geometry coordinate sequences CoordinateSequenceDimensionExtractor dex = new CoordinateSequenceDimensionExtractor(); g.apply(dex); return dex.getDimension(); } /** * Extracts the eventual native SRID user property from the descriptor, returns -1 if not found * * @param descriptor */ protected int getDescriptorSRID(AttributeDescriptor descriptor) { int srid = -1; // check if we have stored the native srid in the descriptor (we should) if (descriptor.getUserData().get(JDBCDataStore.JDBC_NATIVE_SRID) != null) srid = (Integer) descriptor.getUserData().get(JDBCDataStore.JDBC_NATIVE_SRID); return srid; } /** * Extracts the eventual native dimension user property from the descriptor, returns -1 if not * found * * @param descriptor */ protected int getDescriptorDimension(AttributeDescriptor descriptor) { int dimension = -1; // check if we have stored the native srid in the descriptor (we should) if (descriptor.getUserData().get(JDBCDataStore.JDBC_NATIVE_SRID) != null) { dimension = (Integer) descriptor.getUserData().get(Hints.COORDINATE_DIMENSION); } return dimension; } /** Generates an 'UPDATE' sql statement. */ protected String updateSQL( SimpleFeatureType featureType, AttributeDescriptor[] attributes, Object[] values, Filter filter, Set<String> pkColumnNames) throws IOException, SQLException { BasicSQLDialect dialect = (BasicSQLDialect) getSQLDialect(); StringBuffer sql = new StringBuffer(); sql.append("UPDATE "); encodeTableName(featureType.getTypeName(), sql, null); sql.append(" SET "); for (int i = 0; i < attributes.length; i++) { // skip exposed pk columns, they are read only AttributeDescriptor att = attributes[i]; String attName = att.getLocalName(); if (pkColumnNames.contains(attName)) { continue; } // build "colName = value" dialect.encodeColumnName(null, attName, sql); sql.append(" = "); if (Geometry.class.isAssignableFrom(att.getType().getBinding())) { try { Geometry g = (Geometry) values[i]; int srid = getGeometrySRID(g, att); int dimension = getGeometryDimension(g, att); dialect.encodeGeometryValue(g, dimension, srid, sql); } catch (IOException e) { throw new RuntimeException(e); } } else { dialect.encodeValue(values[i], att.getType().getBinding(), sql); } sql.append(","); } sql.setLength(sql.length() - 1); sql.append(" "); if (filter != null && !Filter.INCLUDE.equals(filter)) { // encode filter try { FilterToSQL toSQL = createFilterToSQL(featureType); sql.append(" ").append(toSQL.encodeToString(filter)); } catch (FilterToSQLException e) { throw new RuntimeException(e); } } return sql.toString(); } /** Generates an 'UPDATE' prepared statement. */ protected PreparedStatement updateSQLPS( SimpleFeatureType featureType, AttributeDescriptor[] attributes, Object[] values, Filter filter, Set<String> pkColumnNames, Connection cx) throws IOException, SQLException { PreparedStatementSQLDialect dialect = (PreparedStatementSQLDialect) getSQLDialect(); StringBuffer sql = new StringBuffer(); sql.append("UPDATE "); encodeTableName(featureType.getTypeName(), sql, null); sql.append(" SET "); for (int i = 0; i < attributes.length; i++) { // skip exposed primary key values, they are read only AttributeDescriptor att = attributes[i]; String attName = att.getLocalName(); if (pkColumnNames.contains(attName)) { continue; } dialect.encodeColumnName(null, attName, sql); sql.append(" = "); // geometries might need special treatment, delegate to the dialect if (attributes[i] instanceof GeometryDescriptor) { Geometry geometry = (Geometry) values[i]; final Class<?> binding = att.getType().getBinding(); dialect.prepareGeometryValue( geometry, getDescriptorDimension(att), getDescriptorSRID(att), binding, sql); } else { sql.append("?"); } sql.append(","); } sql.setLength(sql.length() - 1); sql.append(" "); PreparedFilterToSQL toSQL = null; if (filter != null && !Filter.INCLUDE.equals(filter)) { // encode filter try { toSQL = createPreparedFilterToSQL(featureType); sql.append(" ").append(toSQL.encodeToString(filter)); } catch (FilterToSQLException e) { throw new RuntimeException(e); } } PreparedStatement ps = cx.prepareStatement(sql.toString()); LOGGER.log(Level.FINE, "Updating features with prepared statement: {0}", sql); int i = 0; int j = 0; for (; i < attributes.length; i++) { // skip exposed primary key columns AttributeDescriptor att = attributes[i]; String attName = att.getLocalName(); if (pkColumnNames.contains(attName)) { continue; } Class binding = att.getType().getBinding(); if (Geometry.class.isAssignableFrom(binding)) { Geometry g = (Geometry) values[i]; dialect.setGeometryValue( g, getDescriptorDimension(att), getDescriptorSRID(att), binding, ps, j + 1); } else { dialect.setValue(values[i], binding, ps, j + 1, cx); } if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine((j + 1) + " = " + values[i]); } // we do this only if we did not skip the exposed pk j++; } if (toSQL != null) { setPreparedFilterValues(ps, toSQL, j, cx); } return ps; } /** * Creates a new instance of a filter to sql encoder. * * <p>The <tt>featureType</tt> may be null but it is not recommended. Such a case where this may * neccessary is when a literal needs to be encoded in isolation. */ public FilterToSQL createFilterToSQL(SimpleFeatureType featureType) { return initializeFilterToSQL(((BasicSQLDialect) dialect).createFilterToSQL(), featureType); } /** Creates a new instance of a filter to sql encoder to be used in a prepared statement. */ public PreparedFilterToSQL createPreparedFilterToSQL(SimpleFeatureType featureType) { return initializeFilterToSQL( ((PreparedStatementSQLDialect) dialect).createPreparedFilterToSQL(), featureType); } /** Helper method to initialize a filter encoder instance. */ protected <F extends FilterToSQL> F initializeFilterToSQL( F toSQL, final SimpleFeatureType featureType) { toSQL.setSqlNameEscape(dialect.getNameEscape()); if (featureType != null) { // set up a fid mapper // TODO: remove this final PrimaryKey key; try { key = getPrimaryKey(featureType); } catch (IOException e) { throw new RuntimeException(e); } toSQL.setFeatureType(featureType); toSQL.setPrimaryKey(key); toSQL.setDatabaseSchema(databaseSchema); } return toSQL; } /** * Helper method to encode table name which checks if a schema is set and prefixes the table * name with it. */ public void encodeTableName(String tableName, StringBuffer sql, Hints hints) throws SQLException { encodeAliasedTableName(tableName, sql, hints, null); } /** * Helper method to encode table name which checks if a schema is set and prefixes the table * name with it, with the addition of an alias to the name */ public void encodeAliasedTableName( String tableName, StringBuffer sql, Hints hints, String alias) throws SQLException { VirtualTable vtDefinition = virtualTables.get(tableName); if (vtDefinition != null) { sql.append("(").append(vtDefinition.expandParameters(hints)).append(")"); if (alias == null) { alias = "vtable"; } dialect.encodeTableAlias(alias, sql); } else { if (databaseSchema != null) { dialect.encodeSchemaName(databaseSchema, sql); sql.append("."); } dialect.encodeTableName(tableName, sql); if (alias != null) { dialect.encodeTableAlias(alias, sql); } } } /** Helper method to encode the join clause(s) of a query. */ protected void encodeTableJoin( SimpleFeatureType featureType, JoinInfo join, Query query, StringBuffer sql) throws SQLException { encodeAliasedTableName( featureType.getTypeName(), sql, query.getHints(), join.getPrimaryAlias()); for (JoinPart part : join.getParts()) { sql.append(" "); dialect.encodeJoin(part.getJoin().getType(), sql); sql.append(" "); encodeAliasedTableName( part.getQueryFeatureType().getTypeName(), sql, setKeepWhereClausePlaceHolderHint(null, true), part.getAlias()); sql.append(" ON "); Filter j = part.getJoinFilter(); FilterToSQL toSQL = getFilterToSQL(null); toSQL.setInline(true); try { sql.append(" ").append(toSQL.encodeToString(j)); } catch (FilterToSQLException e) { throw new RuntimeException(e); } } if (sql.indexOf(WHERE_CLAUSE_PLACE_HOLDER) >= 0) { // this means that one of the joined table provided a placeholder throw new RuntimeException( "Joins between virtual tables that provide a :where_placeholder: are not supported: " + sql); } } protected List<FilterToSQL> encodeWhereJoin( SimpleFeatureType featureType, JoinInfo join, StringBuffer sql) throws IOException { List<FilterToSQL> toSQL = new ArrayList(); boolean whereEncoded = false; Filter filter = join.getFilter(); if (filter != null && !Filter.INCLUDE.equals(filter)) { sql.append(" WHERE "); whereEncoded = true; // encode filter toSQL.add(filter(featureType, filter, sql)); } // filters for joined feature types for (JoinPart part : join.getParts()) { filter = part.getPreFilter(); if (filter == null || Filter.INCLUDE.equals(filter)) continue; if (!whereEncoded) { sql.append(" WHERE "); whereEncoded = true; } else { sql.append(" AND "); } toSQL.add(filter(part.getQueryFeatureType(), filter, sql)); } return toSQL; } /** Helper method for setting the gml:id of a geometry as user data. */ protected void setGmlProperties(Geometry g, String gid, String name, String description) { // set up the user data Map userData = null; if (g.getUserData() != null) { if (g.getUserData() instanceof Map) { userData = (Map) g.getUserData(); } else { userData = new HashMap(); userData.put(g.getUserData().getClass(), g.getUserData()); } } else { userData = new HashMap(); } if (gid != null) { userData.put("gml:id", gid); } if (name != null) { userData.put("gml:name", name); } if (description != null) { userData.put("gml:description", description); } g.setUserData(userData); } /** * Applies the givenb limit/offset elements if the dialect supports them * * @param sql The sql to be modified * @param offset starting index * @param limit max number of features */ void applyLimitOffset(StringBuffer sql, final Integer offset, final int limit) { if (checkLimitOffset(offset, limit)) { dialect.applyLimitOffset(sql, limit, offset != null ? offset : 0); } } /** * Applies the limit/offset elements to the query if they are specified and if the dialect * supports them * * @param sql The sql to be modified * @param query the query that holds the limit and offset parameters */ public void applyLimitOffset(StringBuffer sql, Query query) { applyLimitOffset(sql, query.getStartIndex(), query.getMaxFeatures()); } /** * Checks if the query needs limit/offset treatment * * @param query * @return true if the query needs limit/offset treatment and if the sql dialect can do that * natively */ boolean checkLimitOffset(final Integer offset, final int limit) { // if we cannot, don't bother checking the query if (!dialect.isLimitOffsetSupported()) return false; return limit != Integer.MAX_VALUE || (offset != null && offset > 0); } /** * Utility method for closing a result set. * * <p>This method closed the result set "safely" in that it never throws an exception. Any * exceptions that do occur are logged at {@link Level#FINER}. * * @param rs The result set to close. */ public void closeSafe(ResultSet rs) { if (rs == null) { return; } try { rs.close(); } catch (SQLException e) { String msg = "Error occurred closing result set"; LOGGER.warning(msg); if (LOGGER.isLoggable(Level.FINER)) { LOGGER.log(Level.FINER, msg, e); } } } /** * Utility method for closing a statement. * * <p>This method closed the statement"safely" in that it never throws an exception. Any * exceptions that do occur are logged at {@link Level#FINER}. * * @param st The statement to close. */ public void closeSafe(Statement st) { if (st == null) { return; } try { st.close(); } catch (SQLException e) { String msg = "Error occurred closing statement"; LOGGER.warning(msg); if (LOGGER.isLoggable(Level.FINER)) { LOGGER.log(Level.FINER, msg, e); } } } /** * Utility method for closing a connection. * * <p>This method closed the connection "safely" in that it never throws an exception. Any * exceptions that do occur are logged at {@link Level#FINER}. * * @param cx The connection to close. */ public void closeSafe(Connection cx) { if (cx == null) { return; } try { // System.out.println("Closing connection " + System.identityHashCode(cx)); cx.close(); LOGGER.fine("CLOSE CONNECTION"); } catch (SQLException e) { String msg = "Error occurred closing connection"; LOGGER.warning(msg); if (LOGGER.isLoggable(Level.FINER)) { LOGGER.log(Level.FINER, msg, e); } } } @SuppressWarnings("deprecation") // finalize is deprecated in Java 9 protected void finalize() throws Throwable { if (dataSource != null) { LOGGER.severe( "There's code using JDBC based datastore and " + "not disposing them. This may lead to temporary loss of database connections. " + "Please make sure all data access code calls DataStore.dispose() " + "before freeing all references to it"); dispose(); } } public void dispose() { super.dispose(); if (dataSource != null && dataSource instanceof ManageableDataSource) { try { ManageableDataSource mds = (ManageableDataSource) dataSource; mds.close(); } catch (SQLException e) { // it's ok, we did our best.. LOGGER.log(Level.FINE, "Could not close dataSource", e); } } // Store the exception for logging later if the object is used after disposal if (TRACE_ENABLED) { disposedBy = new RuntimeException( "DataSource disposed by thread " + Thread.currentThread().getName()); } dataSource = null; } /** * Checks if geometry generalization required and makes sense * * @param hints hints hints passed in * @param gatt Geometry attribute descriptor * @return true to indicate generalization */ protected boolean isGeneralizationRequired(Hints hints, GeometryDescriptor gatt) { return isGeometryReduceRequired(hints, gatt, Hints.GEOMETRY_GENERALIZATION); } /** * Checks if geometry simplification required and makes sense * * @param hints hints hints passed in * @param gatt Geometry attribute descriptor * @return true to indicate simplification */ protected boolean isSimplificationRequired(Hints hints, GeometryDescriptor gatt) { return isGeometryReduceRequired(hints, gatt, Hints.GEOMETRY_SIMPLIFICATION); } /** * Checks if reduction required and makes sense * * @param hints hints passed in * @param gatt Geometry attribute descriptor * @param param {@link Hints#GEOMETRY_GENERALIZATION} or {@link Hints#GEOMETRY_SIMPLIFICATION} * @return true to indicate reducing the geometry, false otherwise */ protected boolean isGeometryReduceRequired( Hints hints, GeometryDescriptor gatt, Hints.Key param) { if (hints == null) return false; if (hints.containsKey(param) == false) return false; if (gatt.getType().getBinding() == Point.class && !dialect.canSimplifyPoints()) return false; return true; } /** * Encoding a geometry column with respect to hints Supported Hints are provided by {@link * SQLDialect#addSupportedHints(Set)} * * @param gatt * @param sql * @param hints , may be null */ public void encodeGeometryColumn(GeometryDescriptor gatt, StringBuffer sql, Hints hints) { encodeGeometryColumn(gatt, null, sql, hints); } protected void encodeGeometryColumn( GeometryDescriptor gatt, String prefix, StringBuffer sql, Hints hints) { int srid = getDescriptorSRID(gatt); if (isGeneralizationRequired(hints, gatt) == true) { Double distance = (Double) hints.get(Hints.GEOMETRY_GENERALIZATION); dialect.encodeGeometryColumnGeneralized(gatt, prefix, srid, sql, distance); return; } if (isSimplificationRequired(hints, gatt) == true) { Double distance = (Double) hints.get(Hints.GEOMETRY_SIMPLIFICATION); dialect.encodeGeometryColumnSimplified(gatt, prefix, srid, sql, distance); return; } dialect.encodeGeometryColumn(gatt, prefix, srid, hints, sql); } /** * Builds a transaction object around a user provided connection. The returned transaction * allows the store to work against an externally managed transaction, such as in J2EE * enviroments. It is the duty of the caller to ensure the connection is to the same database * managed by this {@link JDBCDataStore}. * * <p>Calls to {@link Transaction#commit()}, {@link Transaction#rollback()} and {@link * Transaction#close()} will not result in corresponding calls to the provided {@link * Connection} object. * * @param cx The externally managed connection */ public Transaction buildTransaction(Connection cx) { DefaultTransaction tx = new DefaultTransaction(); State state = new JDBCTransactionState(cx, this, true); tx.putState(this, state); return tx; } /** * Creates a new database index * * @param index * @throws IOException */ public void createIndex(Index index) throws IOException { SimpleFeatureType schema = getSchema(index.typeName); Connection cx = null; try { cx = getConnection(Transaction.AUTO_COMMIT); dialect.createIndex(cx, schema, databaseSchema, index); } catch (SQLException e) { throw new IOException("Failed to create index", e); } finally { closeSafe(cx); } } /** * Creates a new database index * * @param index * @throws IOException */ public void dropIndex(String typeName, String indexName) throws IOException { SimpleFeatureType schema = getSchema(typeName); Connection cx = null; try { cx = getConnection(Transaction.AUTO_COMMIT); dialect.dropIndex(cx, schema, databaseSchema, indexName); } catch (SQLException e) { throw new IOException("Failed to create index", e); } finally { closeSafe(cx); } } /** * Lists all indexes associated to the given feature type * * @param typeName Name of the type for which indexes are searched. It's mandatory * @return */ public List<Index> getIndexes(String typeName) throws IOException { // just to ensure we have the type name specified getSchema(typeName); Connection cx = null; try { cx = getConnection(Transaction.AUTO_COMMIT); return dialect.getIndexes(cx, databaseSchema, typeName); } catch (SQLException e) { throw new IOException("Failed to create index", e); } finally { closeSafe(cx); } } /** * Escapes a name pattern used in e.g. {@link java.sql.DatabaseMetaData#getColumns(String, * String, String, String)} when passed in argument is an exact name and not a pattern. * * <p>When a table name or column name contains underscore (or percen, but this is rare) the * underscore is treated as a placeholder and not an actual character. So if our intention is to * match an exact name, we must escape such characters. */ public String escapeNamePattern(DatabaseMetaData metaData, String name) throws SQLException { if (namePatternEscaping == null) { namePatternEscaping = new NamePatternEscaping(metaData.getSearchStringEscape()); } return namePatternEscaping.escape(name); } }
package dynamake.models.factories; import java.util.ArrayList; import java.util.List; import dynamake.commands.CommandState; import dynamake.commands.PendingCommandState; import dynamake.commands.SetPropertyCommand; import dynamake.models.CompositeLocation; import dynamake.models.Location; import dynamake.models.Model; import dynamake.models.PropogationContext; import dynamake.models.RestorableModel; import dynamake.models.RestorableModel_TO_BE_OBSOLETED; import dynamake.models.Model.PendingUndoablePair; import dynamake.numbers.RectangleF; import dynamake.transcription.Collector; import dynamake.transcription.SimpleExPendingCommandFactory2; public class CloneFactory implements ModelFactory { private static final long serialVersionUID = 1L; private RectangleF creationBounds; private Location modelLocation; public CloneFactory(RectangleF creationBounds, Location modelLocation) { this.creationBounds = creationBounds; this.modelLocation = modelLocation; } @Override public ModelCreation create(Model rootModel, PropogationContext propCtx, int propDistance, Collector<Model> collector, Location location) { final Model modelToClone = (Model)CompositeLocation.getChild(rootModel, location, modelLocation); final RestorableModel restorableModelClone = RestorableModel.wrap(modelToClone, true); return new ModelCreation() { @Override public void setup(Model rootModel, final Model createdModel, Location locationOfModelToSetup, PropogationContext propCtx, int propDistance, Collector<Model> collector, Location location) { RestorableModel restorableModelCreation = restorableModelClone.mapToReferenceLocation(modelToClone, createdModel); restorableModelCreation.restoreChangesOnBase(createdModel, propCtx, propDistance, collector); restorableModelCreation.restoreCleanupOnBase(createdModel, propCtx, propDistance, collector); // @SuppressWarnings("unchecked") // List<CommandState<Model>> allCreation = (List<CommandState<Model>>)createdModel.getProperty(RestorableModel.PROPERTY_CREATION); List<CommandState<Model>> newChangesToInheret = new ArrayList<CommandState<Model>>(); newChangesToInheret.add(new PendingCommandState<Model>(new SetPropertyCommand("X", creationBounds.x), new SetPropertyCommand.AfterSetProperty())); newChangesToInheret.add(new PendingCommandState<Model>(new SetPropertyCommand("Y", creationBounds.y), new SetPropertyCommand.AfterSetProperty())); newChangesToInheret.add(new PendingCommandState<Model>(new SetPropertyCommand("Width", creationBounds.width), new SetPropertyCommand.AfterSetProperty())); newChangesToInheret.add(new PendingCommandState<Model>(new SetPropertyCommand("Height", creationBounds.height), new SetPropertyCommand.AfterSetProperty())); // allCreation.addAll(newChangesToInheret); // createdModel.playThenReverse(newChangesToInheret, propCtx, propDistance, collector); collector.execute(new SimpleExPendingCommandFactory2<Model>(createdModel, newChangesToInheret) { @Override public void afterPropogationFinished(List<PendingUndoablePair> changesToInheritPendingUndoablePairs, PropogationContext propCtx, int propDistance, Collector<Model> collector) { @SuppressWarnings("unchecked") List<CommandState<Model>> allCreation = (List<CommandState<Model>>)createdModel.getProperty(RestorableModel.PROPERTY_CREATION); if(allCreation == null) allCreation = new ArrayList<CommandState<Model>>(); allCreation.addAll(changesToInheritPendingUndoablePairs); collector.execute(new SimpleExPendingCommandFactory2<Model>(createdModel, new PendingCommandState<Model>( new SetPropertyCommand(RestorableModel.PROPERTY_CREATION, allCreation), new SetPropertyCommand.AfterSetProperty() ))); } }); } @Override public Model createModel(Model rootModel, PropogationContext propCtx, int propDistance, Collector<Model> collector, Location location) { Model modelBase = restorableModelClone.unwrapBase(propCtx, propDistance, collector); restorableModelClone.restoreOriginsOnBase(modelBase, propCtx, propDistance, collector); return modelBase; } }; } // @Override // public void setup(Model rootModel, Location locationOfModelToSetup, PropogationContext propCtx, int propDistance, Collector<Model> collector, Location location) { } }
package org.micro.neural.config; import com.alibaba.fastjson.JSON; import lombok.Data; import lombok.extern.slf4j.Slf4j; import org.micro.neural.OriginalCall; import java.io.Serializable; import java.util.Calendar; import java.util.Date; import java.util.LinkedHashMap; import java.util.Map; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.LongAccumulator; import static org.micro.neural.common.Constants.*; /** * The Global Statistics. * <p> * TODO: Redis, * * @author lry **/ @Slf4j @Data public class GlobalStatistics implements Serializable { private static final long serialVersionUID = 2972356738274634556L; /** * The total request counter in the current time window: Calculation QPS */ protected final AtomicLong requestCounter = new AtomicLong(0); /** * The total success counter in the current time window: Calculation TPS */ protected final AtomicLong successCounter = new AtomicLong(0); /** * The total failure counter in the current time window */ protected final AtomicLong failureCounter = new AtomicLong(0); /** * The total timeout counter in the current time window */ protected final AtomicLong timeoutCounter = new AtomicLong(0); /** * The total rejection counter in the current time window */ protected final AtomicLong rejectionCounter = new AtomicLong(0); /** * The total elapsed counter in the current time window */ protected final LongAccumulator elapsedAccumulator = new LongAccumulator(Long::sum, 0); /** * The max elapsed counter in the current time window */ protected final LongAccumulator maxElapsedAccumulator = new LongAccumulator(Long::max, 0); /** * The total concurrent exceed counter in the current time window */ protected final AtomicLong concurrentCounter = new AtomicLong(0); /** * The max concurrent counter in the current time window */ protected final LongAccumulator maxConcurrentAccumulator = new LongAccumulator(Long::max, 0); /** * The total rate counter in the current time window */ protected final AtomicLong rateCounter = new AtomicLong(0); /** * The max rate counter in the current time window */ protected final LongAccumulator maxRateAccumulator = new LongAccumulator(Long::max, 0); /** * The total request of statistical traffic */ public void totalRequestTraffic() { try { // increment request times requestCounter.incrementAndGet(); } catch (Exception e) { log.error("The total request traffic is exception", e); } } /** * The wrapper of original call * * @param originalCall The original call interface * @return The original call result * @throws Throwable throw original call exception */ public Object wrapperOriginalCall(OriginalCall originalCall) throws Throwable { long startTime = System.currentTimeMillis(); try { // increment traffic incrementTraffic(); // original call return originalCall.call(); } catch (Throwable t) { // total exception traffic exceptionTraffic(t); throw t; } finally { // decrement traffic decrementTraffic(startTime); System.out.println(JSON.toJSONString(getStatisticsData())); } } /** * The total increment of statistical traffic */ private void incrementTraffic() { try { // increment concurrent times long concurrentNum = concurrentCounter.incrementAndGet(); // total max concurrent times maxConcurrentAccumulator.accumulate(concurrentNum); // increment request rate times long rateNum = rateCounter.incrementAndGet(); // total request max rate times maxRateAccumulator.accumulate(rateNum); } catch (Exception e) { log.error("The increment traffic is exception", e); } } /** * The total exception of statistical traffic * * @param t {@link Throwable} */ private void exceptionTraffic(Throwable t) { try { // total all failure times failureCounter.incrementAndGet(); if (t instanceof TimeoutException) { // total all timeout times timeoutCounter.incrementAndGet(); } else if (t instanceof RejectedExecutionException) { // total all rejection times rejectionCounter.incrementAndGet(); } } catch (Exception e) { log.error("The exception traffic is exception", e); } } /** * The total decrement of statistical traffic * * @param startTime start time */ private void decrementTraffic(long startTime) { try { long elapsed = System.currentTimeMillis() - startTime; // total all elapsed elapsedAccumulator.accumulate(elapsed); // total max elapsed maxElapsedAccumulator.accumulate(elapsed); // total all success times successCounter.incrementAndGet(); // decrement concurrent times concurrentCounter.decrementAndGet(); } catch (Exception e) { log.error("The decrement traffic is exception", e); } } /** * The build statistics time * * @param statisticReportCycle statistic report cycle milliseconds * @return statistics time */ protected long buildStatisticsTime(long statisticReportCycle) { Calendar calendar = Calendar.getInstance(); calendar.setTime(new Date()); int second = (int) statisticReportCycle / 1000; int tempSecond = calendar.get(Calendar.SECOND) % second; second = tempSecond >= second / 2 ? second : 0; calendar.set(Calendar.SECOND, calendar.get(Calendar.SECOND) + second - tempSecond); return calendar.getTimeInMillis(); } /** * The get statistics and reset * * @return statistics data map */ protected Map<String, Long> getAndReset() { Map<String, Long> map = new LinkedHashMap<>(); // statistics trade long totalRequest = requestCounter.getAndSet(0); if (totalRequest < 1) { return map; } // statistics trade map.put(REQUEST_KEY, totalRequest); map.put(SUCCESS_KEY, successCounter.getAndSet(0)); map.put(FAILURE_KEY, failureCounter.getAndSet(0)); // timeout/rejection map.put(TIMEOUT_KEY, timeoutCounter.getAndSet(0)); map.put(REJECTION_KEY, rejectionCounter.getAndSet(0)); // statistics elapsed map.put(ELAPSED_KEY, elapsedAccumulator.getThenReset()); map.put(MAX_ELAPSED_KEY, maxElapsedAccumulator.getThenReset()); // statistics concurrent map.put(CONCURRENT_KEY, concurrentCounter.getAndSet(0)); map.put(MAX_CONCURRENT_KEY, maxConcurrentAccumulator.getThenReset()); // statistics concurrent map.put(RATE_KEY, rateCounter.getAndSet(0)); map.put(MAX_RATE_KEY, maxRateAccumulator.getThenReset()); return map; } /** * The get statistics data * * @return statistics data map */ public Map<String, Long> getStatisticsData() { Map<String, Long> map = new LinkedHashMap<>(); // statistics trade map.put(REQUEST_KEY, requestCounter.get()); map.put(SUCCESS_KEY, successCounter.get()); map.put(FAILURE_KEY, failureCounter.get()); // timeout/rejection map.put(TIMEOUT_KEY, timeoutCounter.get()); map.put(REJECTION_KEY, rejectionCounter.get()); // statistics elapsed map.put(ELAPSED_KEY, elapsedAccumulator.get()); map.put(MAX_ELAPSED_KEY, maxElapsedAccumulator.get()); // statistics concurrent map.put(CONCURRENT_KEY, concurrentCounter.get()); map.put(MAX_CONCURRENT_KEY, maxConcurrentAccumulator.get()); // statistics rate map.put(RATE_KEY, rateCounter.get()); map.put(MAX_RATE_KEY, maxRateAccumulator.get()); return map; } }
package org.opennms.netmgt.scriptd; import java.lang.reflect.UndeclaredThrowableException; import java.util.List; import java.util.Map; import java.util.Set; import java.util.StringTokenizer; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArraySet; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.apache.bsf.BSFException; import org.apache.bsf.BSFManager; import org.opennms.core.concurrent.LogPreservingThreadFactory; import org.opennms.netmgt.config.ScriptdConfigFactory; import org.opennms.netmgt.config.scriptd.Engine; import org.opennms.netmgt.config.scriptd.EventScript; import org.opennms.netmgt.config.scriptd.ReloadScript; import org.opennms.netmgt.config.scriptd.StartScript; import org.opennms.netmgt.config.scriptd.StopScript; import org.opennms.netmgt.config.scriptd.Uei; import org.opennms.netmgt.dao.api.NodeDao; import org.opennms.netmgt.events.api.EventConstants; import org.opennms.netmgt.model.OnmsNode; import org.opennms.netmgt.xml.event.Event; import org.opennms.netmgt.xml.event.Parm; import org.opennms.netmgt.xml.event.Script; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Executor { private static final Logger LOG = LoggerFactory.getLogger(Executor.class); /** * The configured scripts (no UEI specified). */ private final Set<EventScript> m_eventScripts = new CopyOnWriteArraySet<>(); /** * The configured scripts (UEI specified). */ private final Map<String,Set<EventScript>> m_eventScriptMap = new ConcurrentHashMap<>(); /** * The DAO object for fetching nodes */ private final NodeDao m_nodeDao; /** * The BSF manager */ private BSFManager m_scriptManager = null; /** * The {@link ExecutorService} that will execute tasks for each * event. */ private ExecutorService m_executorService; /** * The broadcast event receiver. */ private BroadcastEventProcessor m_broadcastEventProcessor; /** * The configuration. */ private ScriptdConfigFactory m_config; /** * @param config * The <em>Scriptd</em> configuration. * @param nodeDao * The <em>DAO</em> for fetching node information */ Executor(ScriptdConfigFactory config, NodeDao nodeDao) { m_config = config; m_nodeDao = nodeDao; loadConfig(); } /** * Load the m_scripts and m_scriptMap data structures from the * configuration. * * TODO: If we ever make Scriptd multithreaded then we will need * to handle synchronization for m_eventScripts and m_eventScriptMap * correctly. */ private void loadConfig() { m_eventScripts.clear(); m_eventScriptMap.clear(); for (EventScript script : m_config.getEventScripts()) { Uei[] ueis = script.getUei(); if (ueis.length == 0) { m_eventScripts.add(script); } else { for (Uei uei : ueis) { String ueiName = uei.getName(); Set<EventScript> list = m_eventScriptMap.get(ueiName); if (list == null) { list = new CopyOnWriteArraySet<>(); list.add(script); m_eventScriptMap.put(ueiName, list); } else { list.add(script); } } } } } public void addTask(Event event) { m_executorService.execute(new ScriptdRunnable(event)); } private class ScriptdRunnable implements Runnable { private final Event m_event; public ScriptdRunnable(Event event) { m_event = event; } /** * The main worker of the fiber. This method is executed by the encapsulated * thread to read events from the execution queue and to execute any * configured scripts, allowing these scripts to react to the received * event. If the thread is interrupted then the method will return as quickly as * possible. */ @Override public void run() { // check for reload event if (isReloadConfigEvent(m_event)) { try { ScriptdConfigFactory.reload(); m_config = ScriptdConfigFactory.getInstance(); loadConfig(); ReloadScript[] reloadScripts = m_config.getReloadScripts(); for (ReloadScript script : reloadScripts) { try { m_scriptManager.exec(script.getLanguage(), "", 0, 0, script.getContent()); } catch (BSFException e) { LOG.error("Reload script[{}] failed.", script, e); } } LOG.debug("Scriptd configuration reloaded"); } catch (Throwable e) { LOG.error("Unable to reload Scriptd configuration: ", e); } } Script[] attachedScripts = m_event.getScript(); Set<EventScript> mapScripts = null; try { mapScripts = m_eventScriptMap.get(m_event.getUei()); } catch (Throwable e) { LOG.warn("Unexpected exception: " + e.getMessage(), e); } if (attachedScripts.length > 0 || mapScripts != null || m_eventScripts.size() > 0) { LOG.debug("Executing scripts for: {}", m_event.getUei()); m_scriptManager.registerBean("event", m_event); // And the event's node to the script context OnmsNode node = null; if (m_event.hasNodeid()) { Long nodeLong = m_event.getNodeid(); Integer nodeInt = Integer.valueOf(nodeLong.intValue()); // NMS-8294: Initialize the entire node hierarchy so that // BSF scripts can execute outside of a transaction node = m_nodeDao.getHierarchy(nodeInt); m_scriptManager.registerBean("node", node); } // execute the scripts attached to the event LOG.debug("Executing attached scripts"); if (attachedScripts.length > 0) { for (Script script : attachedScripts) { try { m_scriptManager.exec(script.getLanguage(), "", 0, 0, script.getContent()); } catch (BSFException e) { LOG.error("Attached script [{}] execution failed", script, e); } } } // execute the scripts mapped to the UEI LOG.debug("Executing mapped scripts"); if (mapScripts != null) { for (EventScript script : mapScripts) { try { m_scriptManager.exec(script.getLanguage(), "", 0, 0, script.getContent()); } catch (BSFException e) { LOG.error("UEI-specific event handler script execution failed: {}", m_event.getUei(), e); } } } // execute the scripts that are not mapped to any UEI LOG.debug("Executing global scripts"); for (EventScript script : m_eventScripts) { try { m_scriptManager.exec(script.getLanguage(), "", 0, 0, script.getContent()); } catch (BSFException e) { LOG.error("Non-UEI-specific event handler script execution failed : " + script, e); } } if (node != null) { m_scriptManager.unregisterBean("node"); } m_scriptManager.unregisterBean("event"); LOG.debug("Finished executing scripts for: {}", m_event.getUei()); } } // end run } private static boolean isReloadConfigEvent(Event event) { boolean isTarget = false; if (EventConstants.RELOAD_DAEMON_CONFIG_UEI.equals(event.getUei())) { List<Parm> parmCollection = event.getParmCollection(); for (Parm parm : parmCollection) { if (EventConstants.PARM_DAEMON_NAME.equals(parm.getParmName()) && "Scriptd".equalsIgnoreCase(parm.getValue().getContent())) { isTarget = true; break; } } } else if ("uei.opennms.org/internal/reloadScriptConfig".equals(event.getUei())) { // Deprecating this one... isTarget = true; } return isTarget; } public synchronized void start() { for (Engine engine : m_config.getEngines()) { LOG.debug("Registering engine: {}", engine.getLanguage()); String[] extensions = null; String extensionList = engine.getExtensions(); if (extensionList != null) { StringTokenizer st = new StringTokenizer(extensionList); extensions = new String[st.countTokens()]; int j = 0; while (st.hasMoreTokens()) { extensions[j++] = st.nextToken(); } } BSFManager.registerScriptingEngine(engine.getLanguage(), engine.getClassName(), extensions); } m_scriptManager = new BSFManager(); m_scriptManager.registerBean("log", LOG); // Run all start scripts for (StartScript startScript : m_config.getStartScripts()) { try { m_scriptManager.exec(startScript.getLanguage(), "", 0, 0, startScript.getContent()); } catch (BSFException e) { LOG.error("Start script failed: " + startScript, e); } } // Start the thread pool m_executorService = Executors.newFixedThreadPool(1, new LogPreservingThreadFactory("Scriptd-Executor", 1)); // Register the event listener after the thread pool has been // started try { m_broadcastEventProcessor = new BroadcastEventProcessor(this); } catch (Throwable e) { LOG.error("Failed to setup event reader", e); throw new UndeclaredThrowableException(e); } LOG.debug("Scriptd executor started"); } public synchronized void stop() { // Shut down the event listener if (m_broadcastEventProcessor != null) { m_broadcastEventProcessor.close(); } m_broadcastEventProcessor = null; // Shut down the thread pool m_executorService.shutdown(); // Run all stop scripts for (StopScript stopScript : m_config.getStopScripts()) { try { m_scriptManager.exec(stopScript.getLanguage(), "", 0, 0, stopScript.getContent()); } catch (BSFException e) { LOG.error("Stop script failed: " + stopScript, e); } } LOG.debug("Scriptd executor stopped"); } }
package org.javarosa.demo.shell; import java.util.Hashtable; import java.util.Random; import java.util.Timer; import java.util.TimerTask; import java.util.Vector; import javax.microedition.lcdui.Command; import javax.microedition.lcdui.Displayable; import javax.microedition.midlet.MIDlet; import org.javarosa.activity.splashscreen.SplashScreenActivity; import org.javarosa.communication.http.HttpTransportMethod; import org.javarosa.communication.http.HttpTransportProperties; import org.javarosa.core.Context; import org.javarosa.core.JavaRosaServiceProvider; import org.javarosa.core.api.Constants; import org.javarosa.core.api.IActivity; import org.javarosa.core.api.IShell; import org.javarosa.core.model.FormDef; import org.javarosa.core.model.instance.DataModelTree; import org.javarosa.core.model.storage.DataModelTreeRMSUtility; import org.javarosa.core.model.storage.FormDefRMSUtility; import org.javarosa.core.services.properties.JavaRosaPropertyRules; import org.javarosa.core.util.WorkflowStack; import org.javarosa.formmanager.activity.FormEntryActivity; import org.javarosa.formmanager.activity.FormEntryContext; import org.javarosa.formmanager.activity.FormListActivity; import org.javarosa.formmanager.activity.FormTransportActivity; import org.javarosa.formmanager.activity.MemoryCheckActivity; import org.javarosa.formmanager.activity.ModelListActivity; import org.javarosa.formmanager.properties.FormManagerProperties; import org.javarosa.formmanager.utility.FormDefSerializer; import org.javarosa.formmanager.utility.TransportContext; import org.javarosa.formmanager.view.Commands; import org.javarosa.model.xform.XFormSerializingVisitor; import org.javarosa.model.xform.XPathReference; import org.javarosa.services.properties.activity.PropertyScreenActivity; import org.javarosa.user.activity.AddUserActivity; import org.javarosa.user.activity.LoginActivity; import org.javarosa.user.model.User; import org.javarosa.xform.util.XFormUtils; /** * This is the shell for the JavaRosa demo that handles switching all of the views * @author Brian DeRenzi * */ public class JavaRosaDemoShell implements IShell { // List of views that are used by this shell MIDlet midlet; WorkflowStack stack; Context context; IActivity currentActivity; IActivity mostRecentListActivity; //should never be accessed, only checked for type public JavaRosaDemoShell() { stack = new WorkflowStack(); context = new Context(); } public void exitShell() { midlet.notifyDestroyed(); } public void run() { init(); workflow(null, null, null); } private void startGCThread () { final int GC_INTERVAL = 1000; Timer timer = new Timer(); timer.schedule(new TimerTask () { public void run () { System.gc(); // System.out.print("gc attempted:: "); // System.out.println(Runtime.getRuntime().freeMemory()); } }, GC_INTERVAL, GC_INTERVAL); } private void init() { loadProperties(); startGCThread(); JavaRosaServiceProvider.instance().getTransportManager().registerTransportMethod(new HttpTransportMethod()); DataModelTreeRMSUtility dataModel = new DataModelTreeRMSUtility(DataModelTreeRMSUtility.getUtilityName()); FormDefRMSUtility formDef = new FormDefRMSUtility(FormDefRMSUtility.getUtilityName()); formDef.addModelPrototype(new DataModelTree()); formDef.addReferencePrototype(new XPathReference()); JavaRosaServiceProvider.instance().getStorageManager().getRMSStorageProvider().registerRMSUtility(dataModel); JavaRosaServiceProvider.instance().getStorageManager().getRMSStorageProvider().registerRMSUtility(formDef); boolean readSerialized = false; boolean genSerialized = false; if (genSerialized) { generateSerializedForms("/CHMTTL_Help.xhtml"); // generateSerializedForms("/MobileSurvey.xhtml"); } System.out.println("TOTAL MEM AVAIL: "+java.lang.Runtime.getRuntime().totalMemory()); System.out.println("PRE LOAD FORM MEM: "+java.lang.Runtime.getRuntime().freeMemory()); // For now let's add the dummy form. if (formDef.getNumberOfRecords() == 0) { if (readSerialized ) { //load from serialized form. FormDef form = new FormDef(); form = XFormUtils.getFormFromSerializedResource("/CHMTTL.xhtml.serialized"); //#if debug.output==verbose System.out.println("SERIALIZE TEST:"); System.out.println(form.getName()); //#endif formDef.writeToRMS(form); //load from serialized form. /*form = new FormDef(); form = XFormUtils .getFormFromSerializedResource("/MobileSurvey.xhtml.serialized"); //#if debug.output==verbose System.out.println("SERIALIZE TEST:"); System.out.println(form.getName()); //#endif formDef.writeToRMS(form);*/ }else{ formDef.writeToRMS(XFormUtils.getFormFromResource("/CHMTTL_Help.xhtml")); // formDef.writeToRMS(XFormUtils.getFormFromResource("/CHMTOpenDay2.xhtml")); // formDef.writeToRMS(XFormUtils.getFormFromResource("/CHMTTLT2.xhtml")); // formDef.writeToRMS(XFormUtils.getFormFromResource("/hmis-a_draft.xhtml")); // formDef.writeToRMS(XFormUtils.getFormFromResource("/MobileSurvey.xhtml")); } } System.out.println("POST LOAD FORM MEM: "+java.lang.Runtime.getRuntime().freeMemory()); } private void generateSerializedForms(String originalResource) { FormDef a = XFormUtils.getFormFromResource(originalResource); FormDefSerializer fds = new FormDefSerializer(); fds.setForm(a); fds.setFname(originalResource+".serialized"); new Thread(fds).start(); } private void workflow(IActivity lastActivity, String returnCode, Hashtable returnVals) { if (returnVals == null) returnVals = new Hashtable(); //for easier processing if (lastActivity != currentActivity) { System.out.println("Received 'return' event from activity other than the current activity" + " (such as a background process). Can't handle this yet"); return; } if (returnCode == Constants.ACTIVITY_SUSPEND || returnCode == Constants.ACTIVITY_NEEDS_RESOLUTION) { stack.push(lastActivity); workflowLaunch(lastActivity, returnCode, returnVals); } else { if (stack.size() > 0) { workflowResume(stack.pop(), lastActivity, returnCode, returnVals); } else { workflowLaunch(lastActivity, returnCode, returnVals); if (lastActivity != null) lastActivity.destroy(); } } } private void workflowLaunch (IActivity returningActivity, String returnCode, Hashtable returnVals) { if (returningActivity == null) { /* launchActivity(new SplashScreenActivity(this, "/splash.gif"), context); } else if (returningActivity instanceof SplashScreenActivity) { */ returningActivity = null; //#if javarosa.dev.shortcuts launchActivity(new FormListActivity(this, "Forms List"), context); //#else String passwordVAR = midlet.getAppProperty("username"); String usernameVAR = midlet.getAppProperty("password"); if ((usernameVAR == null) || (passwordVAR == null)) { context.setElement("username","admin"); context.setElement("password","adat"); } else{ context.setElement("username",usernameVAR); context.setElement("password",passwordVAR); } context.setElement("authorization", "admin"); launchActivity(new LoginActivity(this, "Login"), context); //#endif } else if (returningActivity instanceof LoginActivity) { Object returnVal = returnVals.get(LoginActivity.COMMAND_KEY); if (returnVal == "USER_VALIDATED") { User user = (User)returnVals.get(LoginActivity.USER); MemoryCheckActivity memCheck = new MemoryCheckActivity(this); if (user != null){ context.setCurrentUser(user.getUsername()); context.setElement("USER", user); } launchActivity(memCheck, context); } else if (returnVal == "USER_CANCELLED") { exitShell(); } }else if (returningActivity instanceof MemoryCheckActivity) { launchActivity(new FormListActivity(this, "Forms List"), context); } else if (returningActivity instanceof FormListActivity) { String returnVal = (String)returnVals.get(FormListActivity.COMMAND_KEY); if (returnVal == Commands.CMD_SETTINGS) { launchActivity(new PropertyScreenActivity(this), context); } else if (returnVal == Commands.CMD_VIEW_DATA) { launchActivity(new ModelListActivity(this), context); } else if (returnVal == Commands.CMD_SELECT_XFORM) { launchFormEntryActivity(context, ((Integer)returnVals.get(FormListActivity.FORM_ID_KEY)).intValue(), -1); } else if (returnVal == Commands.CMD_EXIT) { exitShell(); } else if (returnVal == Commands.CMD_ADD_USER) launchActivity( new AddUserActivity(this),context); } else if (returningActivity instanceof ModelListActivity) { Object returnVal = returnVals.get(ModelListActivity.returnKey); if (returnVal == ModelListActivity.CMD_MSGS) { launchFormTransportActivity(context, TransportContext.MESSAGE_VIEW, null); } else if (returnVal == ModelListActivity.CMD_EDIT) { launchFormEntryActivity(context, ((FormDef)returnVals.get("form")).getID(), ((DataModelTree)returnVals.get("data")).getId()); } else if (returnVal == ModelListActivity.CMD_SEND) { launchFormTransportActivity(context, TransportContext.SEND_DATA, (DataModelTree)returnVals.get("data")); } else if (returnVal == ModelListActivity.CMD_BACK) { launchActivity(new FormListActivity(this, "Forms List"), context); } } else if (returningActivity instanceof FormEntryActivity) { if (((Boolean)returnVals.get("FORM_COMPLETE")).booleanValue()) { launchFormTransportActivity(context, TransportContext.SEND_DATA, (DataModelTree)returnVals.get("DATA_MODEL")); } else { relaunchListActivity(); } } else if (returningActivity instanceof FormTransportActivity) { relaunchListActivity(); //what is this for? /*if (returnCode == Constants.ACTIVITY_NEEDS_RESOLUTION) { String returnVal = (String)returnVals.get(FormTransportActivity.RETURN_KEY); if(returnVal == FormTransportActivity.VIEW_MODELS) { currentActivity = this.modelActivity; this.modelActivity.start(context); } }*/ } else if (returningActivity instanceof AddUserActivity) launchActivity(new FormListActivity(this, "Forms List"), context); } private void workflowResume (IActivity suspendedActivity, IActivity completingActivity, String returnCode, Hashtable returnVals) { //default action resumeActivity(suspendedActivity, context); } private void launchActivity (IActivity activity, Context context) { if (activity instanceof FormListActivity || activity instanceof ModelListActivity) mostRecentListActivity = activity; currentActivity = activity; activity.start(context); } private void resumeActivity (IActivity activity, Context context) { currentActivity = activity; activity.resume(context); } private void launchFormEntryActivity (Context context, int formID, int instanceID) { FormEntryActivity entryActivity = new FormEntryActivity(this, new FormEntryViewFactory()); FormEntryContext formEntryContext = new FormEntryContext(context); formEntryContext.setFormID(formID); if (instanceID != -1) formEntryContext.setInstanceID(instanceID); launchActivity(entryActivity, formEntryContext); } private void launchFormTransportActivity (Context context, String task, DataModelTree data) { FormTransportActivity formTransport = new FormTransportActivity(this); formTransport.setDataModelSerializer(new XFormSerializingVisitor()); formTransport.setData(data); //why isn't this going in the context? TransportContext msgContext = new TransportContext(context); msgContext.setRequestedTask(task); launchActivity(formTransport, msgContext); } private void relaunchListActivity () { if (mostRecentListActivity instanceof FormListActivity) { launchActivity(new FormListActivity(this, "Forms List"), context); } else if (mostRecentListActivity instanceof ModelListActivity) { launchActivity(new ModelListActivity(this), context); } else { throw new IllegalStateException("Trying to resume list activity when no most recent set"); } } /* (non-Javadoc) * @see org.javarosa.shell.IShell#activityCompeleted(org.javarosa.activity.IActivity) */ public void returnFromActivity(IActivity activity, String returnCode, Hashtable returnVals) { //activity.halt(); //i don't think this belongs here? the contract reserves halt for unexpected halts; //an activity calling returnFromActivity isn't halting unexpectedly workflow(activity, returnCode, returnVals); } public boolean setDisplay(IActivity callingActivity, Displayable display) { if(callingActivity == currentActivity) { JavaRosaServiceProvider.instance().getDisplay().setCurrent(display); return true; } else { //#if debug.output==verbose System.out.println("Activity: " + callingActivity + " attempted, but failed, to set the display"); //#endif return false; } } public void setMIDlet(MIDlet midlet) { this.midlet = midlet; } //need 'addpropery' too. private String initProperty(String propName, String defaultValue) { Vector propVal = JavaRosaServiceProvider.instance().getPropertyManager().getProperty(propName); if (propVal == null || propVal.size() == 0) { propVal = new Vector(); propVal.addElement(defaultValue); JavaRosaServiceProvider.instance().getPropertyManager().setProperty(propName, propVal); //#if debug.output==verbose System.out.println("No default value for [" + propName + "]; setting to [" + defaultValue + "]"); // debug //#endif return defaultValue; }/*else { propVal.addElement(defaultValue); JavaRosaServiceProvider.instance().getPropertyManager().setProperty(propName, propVal); //#if debug.output==verbose System.out.println("added value for [" + propName + "]; setting to [" + defaultValue + "]"); // debug //#endif return defaultValue; }*/ return (String) propVal.elementAt(0); } private void loadProperties() { JavaRosaServiceProvider.instance().getPropertyManager().addRules(new JavaRosaPropertyRules()); JavaRosaServiceProvider.instance().getPropertyManager().addRules(new HttpTransportProperties()); JavaRosaServiceProvider.instance().getPropertyManager().addRules(new FormManagerProperties()); initProperty("DeviceID", genGUID(25)); initProperty(FormManagerProperties.VIEW_TYPE_PROPERTY, FormManagerProperties.VIEW_CLFORMS); initProperty(HttpTransportProperties.POST_URL_LIST_PROPERTY, "http://survey.cell-life.org/admin/post2limeNew.php"); Vector v = JavaRosaServiceProvider.instance().getPropertyManager().getProperty(HttpTransportProperties.POST_URL_LIST_PROPERTY); v.addElement("http://dev.cell-life.org/javarosa/web/limesurvey/admin/post2lime.php"); JavaRosaServiceProvider.instance().getPropertyManager().setProperty(HttpTransportProperties.POST_URL_LIST_PROPERTY, v); initProperty(HttpTransportProperties.POST_URL_PROPERTY, "http://survey.cell-life.org/admin/post2limeNew.php"); // initProperty(FormManagerProperties.VIEW_TYPE_PROPERTY, FormManagerProperties.VIEW_CLFORMS); } //TODO: Put this in a utility method public static String genGUID(int len) { String guid = ""; Random r = new Random(); for (int i = 0; i < 25; i++) { // 25 == 128 bits of entropy guid += Integer.toString(r.nextInt(36), 36); } return guid.toUpperCase(); } }
package MWC.TacticalData; /** somebody who provides a rolling sequence of narrative entries * * @author ian.mayo * */ public interface IRollingNarrativeProvider { /** somebody who wants to listen to all entries * */ public final String ALL_CATS = "ALL"; /** how many entries do we have? * * @return */ public int size(); /** add a narrative listener * * @param categories * @param listener */ public void addNarrativeListener(String category, INarrativeListener listener); /** remove a narrative listener * * @param categories * @param listener */ public void removeNarrativeListener(String category, INarrativeListener listener); /** get the narrative history * * @param categories the categories of narrative we're interested in * @return */ public NarrativeEntry[] getNarrativeHistory(String[] categories); /** and somebody who listens out for new narrative entries * * @author ian.mayo * */ public static interface INarrativeListener { /** a new narrative item has been produced * * @param entry */ public void newEntry(NarrativeEntry entry); /** a narrative entry has been removed */ public void entryRemoved(NarrativeEntry entry); } }
package org.spoofax.jsglr.client; import java.util.ArrayList; import org.spoofax.jsglr.shared.ArrayDeque; public class FineGrainedOnRegion { private static final int MAX_RECOVERIES_PER_LINE = 3; private static final int MAX_NR_OF_LINES = 25; private int acceptRecoveryPosition; private int regionEndPosition; private ArrayList<BacktrackPosition> choicePoints; private SGLR mySGLR; private int maxPerLine; private ParserHistory getHistory() { return mySGLR.getHistory(); } public void setInfoFGOnly(){ regionEndPosition=mySGLR.tokensSeen+5; acceptRecoveryPosition=regionEndPosition+10; int lastIndex=getHistory().getIndexLastLine(); for (int i = 0; i < lastIndex; i++) { IndentInfo line= getHistory().getLine(i); if(line.getStackNodes()!=null && line.getStackNodes().size()>0){ BacktrackPosition btPoint=new BacktrackPosition(line.getStackNodes(), line.getTokensSeen()); btPoint.setIndexHistory(i); choicePoints.add(btPoint); } } maxPerLine=MAX_RECOVERIES_PER_LINE; } public void setRegionInfo(StructureSkipSuggestion erroneousRegion, int acceptPosition){ regionEndPosition=erroneousRegion.getEndSkip().getTokensSeen(); acceptRecoveryPosition=acceptPosition; int lastIndex=Math.min(erroneousRegion.getIndexHistoryEnd(), getHistory().getIndexLastLine()); if(lastIndex<0 || erroneousRegion.getIndexHistoryStart()<0 || erroneousRegion.getIndexHistoryStart()>erroneousRegion.getIndexHistoryEnd()){ System.err.println("Something went wrong with the region index"); return; } for (int i = erroneousRegion.getIndexHistoryStart(); i < lastIndex; i++) { IndentInfo line= getHistory().getLine(i); if(line.getStackNodes()!=null && line.getStackNodes().size()>0){ BacktrackPosition btPoint=new BacktrackPosition(line.getStackNodes(), line.getTokensSeen()); btPoint.setIndexHistory(i); choicePoints.add(btPoint); } } maxPerLine=MAX_RECOVERIES_PER_LINE; if(erroneousRegion.getIndexHistoryEnd()-erroneousRegion.getIndexHistoryStart()==1){ maxPerLine=2; } } public boolean recover() { // System.out.println("FINE GRAINED RECOVERY STARTED"); mySGLR.setFineGrainedOnRegion(true); boolean succeeded=recoverFrom(choicePoints.size()-1, new ArrayList<RecoverNode>()); mySGLR.setFineGrainedOnRegion(false); return succeeded; } private boolean recoverFrom(int indexCP, ArrayList<RecoverNode> candidates) { int loops=choicePoints.size()-1-indexCP; if(indexCP<-1*maxPerLine)//first line 3 times explored return false; if(loops>MAX_NR_OF_LINES)//max nr of lines explored in backtracking return false; int indexChoichePoints=Math.max(0, indexCP); if (indexChoichePoints >= choicePoints.size()) return false; BacktrackPosition btPosition=choicePoints.get(indexChoichePoints); mySGLR.activeStacks.clear(true); mySGLR.activeStacks.addAll(btPosition.recoverStacks); getHistory().deleteLinesFrom(btPosition.getIndexHistory()); getHistory().setTokenIndex(btPosition.tokensSeen); int endPos=regionEndPosition; if(indexChoichePoints<choicePoints.size()-maxPerLine) endPos=choicePoints.get(indexChoichePoints+maxPerLine).tokensSeen; ArrayList<RecoverNode> newCandidates=recoverParse(candidates, endPos, true); if(mySGLR.activeStacks.size()>0 || mySGLR.acceptingStack!=null){ //if (loops<=MAX_RECOVERIES_PER_LINE) { //*/
package etomica.virial.simulations; import java.awt.Color; import java.util.HashMap; import java.util.Map; import java.util.Set; import javax.swing.JLabel; import javax.swing.JPanel; import etomica.action.AtomActionTranslateBy; import etomica.action.IAction; import etomica.action.MoleculeChildAtomAction; import etomica.api.IAtomType; import etomica.api.IIntegratorEvent; import etomica.api.IIntegratorListener; import etomica.api.IMoleculeList; import etomica.api.ISpecies; import etomica.api.IVectorMutable; import etomica.atom.AtomTypeLeaf; import etomica.atom.DiameterHashByType; import etomica.atom.iterator.ANIntergroupCoupled; import etomica.atom.iterator.ApiIndexList; import etomica.atom.iterator.ApiIntergroupCoupled; import etomica.chem.elements.ElementChemical; import etomica.config.ConformationLinear; import etomica.data.AccumulatorAverage; import etomica.data.AccumulatorAverageCovariance; import etomica.data.AccumulatorAverageFixed; import etomica.data.AccumulatorRatioAverageCovariance; import etomica.data.DataPumpListener; import etomica.data.IData; import etomica.data.IEtomicaDataInfo; import etomica.data.types.DataDouble; import etomica.data.types.DataGroup; import etomica.graph.model.Graph; import etomica.graphics.ColorSchemeRandomByMolecule; import etomica.graphics.DisplayBox; import etomica.graphics.DisplayBoxCanvasG3DSys; import etomica.graphics.DisplayTextBox; import etomica.graphics.SimulationGraphic; import etomica.graphics.SimulationPanel; import etomica.listener.IntegratorListenerAction; import etomica.potential.P2EffectiveFeynmanHibbs; import etomica.potential.P2Harmonic; import etomica.potential.P2HePCKLJS; import etomica.potential.P3CPSNonAdditiveHe; import etomica.potential.Potential2SoftSpherical; import etomica.potential.PotentialGroup; import etomica.space.IVectorRandom; import etomica.space.Space; import etomica.space3d.Space3D; import etomica.species.SpeciesSpheres; import etomica.units.CompoundDimension; import etomica.units.CompoundUnit; import etomica.units.Dimension; import etomica.units.DimensionRatio; import etomica.units.Kelvin; import etomica.units.Liter; import etomica.units.Mole; import etomica.units.Pixel; import etomica.units.Quantity; import etomica.units.Unit; import etomica.units.UnitRatio; import etomica.units.Volume; import etomica.util.Constants; import etomica.util.Constants.CompassDirection; import etomica.util.DoubleRange; import etomica.util.HistogramNotSoSimple; import etomica.util.ParameterBase; import etomica.util.ParseArgs; import etomica.virial.ClusterAbstract; import etomica.virial.ClusterBonds; import etomica.virial.ClusterDifference; import etomica.virial.ClusterSum; import etomica.virial.ClusterSumMultibody; import etomica.virial.ClusterSumShell; import etomica.virial.ClusterWeight; import etomica.virial.ClusterWeightAbs; import etomica.virial.MCMoveClusterMoleculeMulti; import etomica.virial.MCMoveClusterRingRegrow; import etomica.virial.MayerEHardSphere; import etomica.virial.MayerFunction; import etomica.virial.MayerFunctionMolecularThreeBody; import etomica.virial.MayerFunctionNonAdditive; import etomica.virial.MayerFunctionSphericalThreeBody; import etomica.virial.MayerFunctionThreeBody; import etomica.virial.MayerGeneral; import etomica.virial.MayerGeneralSpherical; import etomica.virial.MayerHardSphere; import etomica.virial.MeterVirial; import etomica.virial.PotentialGroup3PI; import etomica.virial.PotentialGroup3PI.PotentialGroup3PISkip; import etomica.virial.PotentialGroupPI; import etomica.virial.PotentialGroupPI.PotentialGroupPISkip; import etomica.virial.cluster.Standard; import etomica.virial.cluster.VirialDiagrams; /** * Mayer sampling simulation */ public class VirialHePI { public static void main(String[] args) { VirialHePIParam params = new VirialHePIParam(); boolean isCommandline = args.length > 0; if (isCommandline) { ParseArgs parseArgs = new ParseArgs(params); parseArgs.parseArgs(args, true); } final int nPoints = params.nPoints; final double temperatureK = params.temperature; long steps = params.numSteps; final boolean pairOnly = params.nPoints == 2 || params.pairOnly; double refFreq = params.refFrac; boolean subtractHalf = params.subtractHalf; final double sigmaHSRef = params.sigmaHSRef; final int startBeadHalfs = params.startBeadHalfs; final int beadFac = subtractHalf ? params.beadFac : 1; final int finalNumBeads = params.finalNumBeads; final double[] HSB = new double[8]; if (params.nBeads>-1) System.out.println("nSpheres set explicitly"); int nb = (params.nBeads > -1) ? params.nBeads : ((int)(1200/temperatureK) + 7); final boolean doDiff = params.doDiff; final boolean semiClassical = params.semiClassical; int origNB = nb; if (subtractHalf) { int totalHalfs = (int)Math.ceil(Math.log((nb+finalNumBeads-1)/finalNumBeads)/Math.log(beadFac)); int totalFac = (int)Math.round(Math.pow(beadFac, totalHalfs)); int endBeads = (nb + totalFac -1) / totalFac; nb = endBeads * totalFac; origNB = nb; System.out.println("He Path Integral ("+origNB+"-mer chains) B"+nPoints+" at "+temperatureK+"K"); nb /= (int)Math.round(Math.pow(beadFac,startBeadHalfs)); if (nb*beadFac <= finalNumBeads) { throw new RuntimeException("it is unnecessary to half "+(startBeadHalfs)+" times"); } if (nb <= finalNumBeads) { if (doDiff) { if (semiClassical) { System.out.println("Calculating difference between "+nb+" beads and semiclassical"); } else { System.out.println("Calculating difference between "+nb+" beads and classical"); } } else { System.out.println("Perturbing from "+nb+" beads to hard spheres"); } subtractHalf = false; } else { System.out.println("Calculating difference between "+nb/beadFac+" and "+nb+" beads"); } } else { System.out.println("He Path Integral ("+nb+"-mer chains) B"+nPoints+" at "+temperatureK+"K"); if (doDiff) { if (semiClassical) { System.out.println("computing difference from semiclassical"); } else { System.out.println("computing difference from classical"); } } } if (pairOnly) { System.out.println("computing pairwise contribution"); } else { System.out.println("computing non-additive contribution"); } final int nBeads = nb; HSB[2] = Standard.B2HS(sigmaHSRef); HSB[3] = Standard.B3HS(sigmaHSRef); HSB[4] = Standard.B4HS(sigmaHSRef); HSB[5] = Standard.B5HS(sigmaHSRef); HSB[6] = Standard.B6HS(sigmaHSRef); HSB[7] = Standard.B7HS(sigmaHSRef); Space space = Space3D.getInstance(); double heMass = 4.002602; final double temperature = Kelvin.UNIT.toSim(temperatureK); MayerHardSphere fRef = new MayerHardSphere(sigmaHSRef); MayerEHardSphere eRef = new MayerEHardSphere(sigmaHSRef); final Potential2SoftSpherical p2 = new P2HePCKLJS(space); PotentialGroupPI pTargetGroup = new PotentialGroupPI(beadFac); pTargetGroup.addPotential(p2, new ApiIntergroupCoupled()); PotentialGroupPISkip[] pTargetSkip = new PotentialGroupPISkip[beadFac]; for (int i=0; i<beadFac; i++) { pTargetSkip[i] = pTargetGroup.new PotentialGroupPISkip(i); } final P3CPSNonAdditiveHe p3 = new P3CPSNonAdditiveHe(space); PotentialGroup3PI p3TargetGroup = new PotentialGroup3PI(beadFac); p3TargetGroup.addPotential(p3, new ANIntergroupCoupled(3)); PotentialGroup3PISkip[] p3TargetSkip = new PotentialGroup3PISkip[beadFac]; for (int i=0; i<beadFac; i++) { p3TargetSkip[i] = p3TargetGroup.new PotentialGroup3PISkip(i); } final MayerGeneralSpherical fTargetClassical = new MayerGeneralSpherical(p2); P2EffectiveFeynmanHibbs p2SemiClassical = new P2EffectiveFeynmanHibbs(space, p2); p2SemiClassical.setMass(heMass); p2SemiClassical.setTemperature(temperature); final MayerGeneralSpherical fTargetSemiClassical = new MayerGeneralSpherical(p2SemiClassical); MayerGeneral[] fTargetSkip = new MayerGeneral[beadFac]; for (int i=0; i<beadFac; i++) { fTargetSkip[i] = new MayerGeneral(pTargetSkip[i]) { public double f(IMoleculeList pair, double r2, double beta) { return super.f(pair, r2, beta/(nBeads/beadFac)); } }; } MayerGeneral fTarget = new MayerGeneral(pTargetGroup) { public double f(IMoleculeList pair, double r2, double beta) { return super.f(pair, r2, beta/nBeads); } }; final MayerFunctionSphericalThreeBody f3TargetClassical = new MayerFunctionSphericalThreeBody(p3); MayerFunctionThreeBody[] f3TargetSkip = new MayerFunctionThreeBody[beadFac]; for (int i=0; i<beadFac; i++) { f3TargetSkip[i] = new MayerFunctionMolecularThreeBody(p3TargetSkip[i]) { public double f(IMoleculeList pair, double[] r2, double beta) { return super.f(pair, r2, beta/(nBeads/beadFac)); } }; } MayerFunctionThreeBody f3Target = new MayerFunctionMolecularThreeBody(p3TargetGroup) { public double f(IMoleculeList molecules, double[] r2, double beta) { return super.f(molecules, r2, beta/nBeads); } }; boolean doFlex = nPoints > 2 && pairOnly; VirialDiagrams flexDiagrams = new VirialDiagrams(nPoints, true, doFlex); flexDiagrams.setDoMinimalMulti(true); ClusterAbstract targetCluster = flexDiagrams.makeVirialCluster(fTarget, null, pairOnly ? null : f3Target); VirialDiagrams rigidDiagrams = new VirialDiagrams(nPoints, false, false); rigidDiagrams.setDoReeHoover(false); ClusterSum refCluster = rigidDiagrams.makeVirialCluster(fRef, eRef); final ClusterSum[] targetSubtract = new ClusterSum[subtractHalf ? beadFac : 1]; final ClusterSum fullTargetCluster; ClusterAbstract[] targetDiagrams = new ClusterAbstract[0]; int[] targetDiagramNumbers = new int[0]; if (doDiff || subtractHalf) { fullTargetCluster = (ClusterSum)targetCluster; ClusterBonds[] minusBonds = fullTargetCluster.getClusters(); double[] wMinus = fullTargetCluster.getWeights(); for (int i=0; i<targetSubtract.length; i++) { if (pairOnly) { targetSubtract[i] = new ClusterSum(minusBonds, wMinus, new MayerFunction[]{subtractHalf ? fTargetSkip[i] : (semiClassical ? fTargetSemiClassical : fTargetClassical)}); } else { targetSubtract[i] = new ClusterSumMultibody(minusBonds, wMinus, new MayerFunction[]{subtractHalf ? fTargetSkip[i] : (semiClassical ? fTargetSemiClassical : fTargetClassical)}, new MayerFunctionNonAdditive[]{subtractHalf ? f3TargetSkip[i] : f3TargetClassical}); } } targetCluster = new ClusterDifference(fullTargetCluster, targetSubtract); ClusterSumShell[] targetDiagramsPlus = new ClusterSumShell[0]; targetDiagramsPlus = flexDiagrams.makeSingleVirialClusters(fullTargetCluster, null, fTarget); ClusterSumShell[][] targetDiagramsMinus = new ClusterSumShell[targetDiagramsPlus.length][0]; for (int j=0; j<targetDiagramsMinus.length; j++) { targetDiagramsMinus[j] = new ClusterSumShell[targetSubtract.length]; } for (int i=0; i<targetSubtract.length; i++) { ClusterSumShell[] foo = flexDiagrams.makeSingleVirialClusters(targetSubtract[i], null, fTarget); for (int j=0; j<foo.length; j++) { targetDiagramsMinus[j][i] = foo[j]; } } if (pairOnly) { targetDiagrams = new ClusterDifference[targetDiagramsPlus.length]; for (int j=0; j<targetDiagramsPlus.length; j++) { targetDiagrams[j] = new ClusterDifference(targetDiagramsPlus[j], targetDiagramsMinus[j]); } } } else { if (pairOnly) { targetDiagrams = flexDiagrams.makeSingleVirialClusters((ClusterSum)targetCluster, null, fTarget); } } if (pairOnly) { targetDiagramNumbers = new int[targetDiagrams.length]; System.out.println("individual clusters:"); Set<Graph> singleGraphs = flexDiagrams.getMSMCGraphs(true, !pairOnly); Map<Graph,Graph> cancelMap = flexDiagrams.getCancelMap(); int iGraph = 0; for (Graph g : singleGraphs) { if (VirialDiagrams.graphHasEdgeColor(g, flexDiagrams.mBond)) continue; System.out.print(" ("+g.coefficient()+") "+g.getStore().toNumberString()); targetDiagramNumbers[iGraph] = Integer.parseInt(g.getStore().toNumberString()); Graph cancelGraph = cancelMap.get(g); if (cancelGraph != null) { System.out.print(" - "+cancelGraph.getStore().toNumberString()); } System.out.println(); iGraph++; } System.out.println(); Set<Graph> disconnectedGraphs = flexDiagrams.getExtraDisconnectedVirialGraphs(); if (disconnectedGraphs.size() > 0) { System.out.println("extra clusters:"); HashMap<Graph,Set<Graph>> splitMap = flexDiagrams.getSplitDisconnectedVirialGraphs(disconnectedGraphs); for (Graph g : disconnectedGraphs) { Set<Graph> gSplit = splitMap.get(g); System.out.print(g.coefficient()+" "); for (Graph gs : gSplit) { if (VirialDiagrams.graphHasEdgeColor(gs, flexDiagrams.MBond)) { System.out.print(" "+gs.nodeCount()+"b"); } else { System.out.print(" "+gs.getStore().toNumberString()); } } System.out.println(); } System.out.println(); } } for (int i=0; i<targetDiagrams.length; i++) { targetDiagrams[i].setTemperature(temperature); } double refIntegral = HSB[nPoints]; // the cluster's temperature determines the factor multiplied in the exponential (f=e-1) // we want 1/(P*kT) targetCluster.setTemperature(temperature); refCluster.setTemperature(temperature); ClusterWeight targetSampleCluster = ClusterWeightAbs.makeWeightCluster(targetCluster); ClusterWeight refSampleCluster = ClusterWeightAbs.makeWeightCluster(refCluster); System.out.println("sigmaHSRef: "+sigmaHSRef); // overerr expects this string, BnHS System.out.println("B"+nPoints+"HS: "+refIntegral); if (steps%1000 != 0) { throw new RuntimeException("steps should be a multiple of 1000"); } System.out.println(steps+" steps (1000 blocks of "+steps/1000+")"); SpeciesSpheres species = new SpeciesSpheres(space, nBeads, new AtomTypeLeaf(new ElementChemical("He", heMass, 2)), new ConformationLinear(space, 0)); final SimulationVirialOverlap2 sim = new SimulationVirialOverlap2(space, new ISpecies[]{species}, new int[]{nPoints+(doFlex?1:0)}, temperature, new ClusterAbstract[]{refCluster, targetCluster}, new ClusterWeight[]{refSampleCluster,targetSampleCluster}, false); // we'll use substeps=1000 initially (to allow for better initialization) // and then later switch to 1000 overlap steps sim.integratorOS.setNumSubSteps(1000); steps /= 1000; if (doFlex) { // fix the last molecule at the origin int[] constraintMap = new int[nPoints+1]; for (int i=0; i<nPoints; i++) { constraintMap[i] = i; } constraintMap[nPoints] = 0; ((MCMoveClusterMoleculeMulti)sim.mcMoveTranslate[0]).setConstraintMap(constraintMap); ((MCMoveClusterMoleculeMulti)sim.mcMoveTranslate[1]).setConstraintMap(constraintMap); } // rotation is a bit pointless when we can regrow the chain completely sim.integrators[0].getMoveManager().removeMCMove(sim.mcMoveRotate[0]); sim.integrators[1].getMoveManager().removeMCMove(sim.mcMoveRotate[1]); System.out.println("regrow full ring"); MCMoveClusterRingRegrow ring0 = new MCMoveClusterRingRegrow(sim.getRandom(), space); double lambda = Constants.PLANCK_H/Math.sqrt(2*Math.PI*heMass*temperature); ring0.setEnergyFactor(nBeads*Math.PI/(lambda*lambda)); MCMoveClusterRingRegrow ring1 = new MCMoveClusterRingRegrow(sim.getRandom(), space); ring1.setEnergyFactor(nBeads*Math.PI/(lambda*lambda)); sim.integrators[0].getMoveManager().addMCMove(ring0); sim.integrators[1].getMoveManager().addMCMove(ring1); if (refFreq >= 0) { sim.integratorOS.setAdjustStepFraction(false); sim.integratorOS.setRefStepFraction(refFreq); } if (doDiff || subtractHalf || !pairOnly) { AtomActionTranslateBy translator = new AtomActionTranslateBy(space); IVectorRandom groupTranslationVector = (IVectorRandom)translator.getTranslationVector(); MoleculeChildAtomAction moveMoleculeAction = new MoleculeChildAtomAction(translator); IMoleculeList molecules = sim.box[1].getMoleculeList(); double r = 4; // put the molecules in a ring around the origin, with one atom // from each scaled in toward the origin for (int i=1; i<nPoints; i++) { groupTranslationVector.setX(0, r*Math.cos(2*(i-1)*Math.PI/(nPoints-1))); groupTranslationVector.setX(1, r*Math.sin(2*(i-1)*Math.PI/(nPoints-1))); moveMoleculeAction.actionPerformed(molecules.getMolecule(i)); if (nBeads>1) { IVectorMutable v = molecules.getMolecule(i).getChildList().getAtom(1).getPosition(); v.TE(0.95); } } sim.box[1].trialNotify(); double pi = sim.box[1].getSampleCluster().value(sim.box[1]); if (pi == 0) throw new RuntimeException("initialization failed"); sim.box[1].acceptNotify(); } if (false) { // unnecessary because our MC move regrows the chain using the // probability distribution appropriate for the harmonic bonds // create the intramolecular potential here, add to it and add it to // the potential master if needed PotentialGroup pIntra = sim.integrators[1].getPotentialMaster().makePotentialGroup(1); // we want exp[-(pi*P/lambda^2) * sum(x^2)] // we set the integrator temperature=1 above, so when it does // exp[-beta * U] = exp[-U] // so just make the spring constant whatever we need to get the above expression P2Harmonic p2Bond = new P2Harmonic(space, 2*Math.PI*nBeads/(lambda*lambda)*temperature); int[][] pairs = new int[nBeads][2]; for (int i=0; i<nBeads-1; i++) { pairs[i][0] = i; pairs[i][1] = i+1; } pairs[nBeads-1][0] = nBeads-1; pairs[nBeads-1][1] = 0; pIntra.addPotential(p2Bond, new ApiIndexList(pairs)); // integrators share a common potentialMaster. so just add to one sim.integrators[1].getPotentialMaster().addPotential(pIntra,new ISpecies[]{sim.getSpecies(0)}); } if (false) { double vSize = 5; sim.box[0].getBoundary().setBoxSize(space.makeVector(new double[]{vSize,vSize,vSize})); sim.box[1].getBoundary().setBoxSize(space.makeVector(new double[]{vSize,vSize,vSize})); SimulationGraphic simGraphic = new SimulationGraphic(sim, SimulationGraphic.TABBED_PANE, space, sim.getController()); DisplayBox displayBox0 = simGraphic.getDisplayBox(sim.box[0]); DisplayBox displayBox1 = simGraphic.getDisplayBox(sim.box[1]); displayBox0.setPixelUnit(new Pixel(300.0/vSize)); displayBox1.setPixelUnit(new Pixel(300.0/vSize)); displayBox0.setShowBoundary(false); displayBox1.setShowBoundary(false); ((DisplayBoxCanvasG3DSys)displayBox0.canvas).setBackgroundColor(Color.WHITE); ((DisplayBoxCanvasG3DSys)displayBox1.canvas).setBackgroundColor(Color.WHITE); IAtomType type = species.getLeafType(); DiameterHashByType diameterManager = (DiameterHashByType)displayBox0.getDiameterHash(); diameterManager.setDiameter(type, 0.02+1.0/nBeads); displayBox1.setDiameterHash(diameterManager); ColorSchemeRandomByMolecule colorScheme = new ColorSchemeRandomByMolecule(sim, sim.box[0], sim.getRandom()); displayBox0.setColorScheme(colorScheme); colorScheme = new ColorSchemeRandomByMolecule(sim, sim.box[1], sim.getRandom()); displayBox1.setColorScheme(colorScheme); simGraphic.makeAndDisplayFrame(); sim.integratorOS.setNumSubSteps(1000); sim.setAccumulatorBlockSize(1000); // if running interactively, set filename to null so that it doens't read // (or write) to a refpref file // sim.getController().removeAction(sim.ai); // sim.getController().addAction(new IAction() { // public void actionPerformed() { // sim.initRefPref(null, 10); // sim.equilibrate(null, 20); // sim.ai.setMaxSteps(Long.MAX_VALUE); // sim.getController().addAction(sim.ai); if ((Double.isNaN(sim.refPref) || Double.isInfinite(sim.refPref) || sim.refPref == 0)) { throw new RuntimeException("Oops"); } final DisplayTextBox averageBox = new DisplayTextBox(); averageBox.setLabel("Average"); final DisplayTextBox errorBox = new DisplayTextBox(); errorBox.setLabel("Error"); JLabel jLabelPanelParentGroup = new JLabel("B"+nPoints+" (L/mol)^"+(nPoints-1)); final JPanel panelParentGroup = new JPanel(new java.awt.BorderLayout()); panelParentGroup.add(jLabelPanelParentGroup,CompassDirection.NORTH.toString()); panelParentGroup.add(averageBox.graphic(), java.awt.BorderLayout.WEST); panelParentGroup.add(errorBox.graphic(), java.awt.BorderLayout.EAST); simGraphic.getPanel().controlPanel.add(panelParentGroup, SimulationPanel.getVertGBC()); IAction pushAnswer = new IAction() { public void actionPerformed() { double[] ratioAndError = sim.dsvo.getOverlapAverageAndError(); double ratio = ratioAndError[0]; double error = ratioAndError[1]; data.x = ratio; averageBox.putData(data); data.x = error; errorBox.putData(data); } DataDouble data = new DataDouble(); }; IEtomicaDataInfo dataInfo = new DataDouble.DataInfoDouble("B"+nPoints, new CompoundDimension(new Dimension[]{new DimensionRatio(Volume.DIMENSION, Quantity.DIMENSION)}, new double[]{nPoints-1})); Unit unit = new CompoundUnit(new Unit[]{new UnitRatio(Liter.UNIT, Mole.UNIT)}, new double[]{nPoints-1}); averageBox.putDataInfo(dataInfo); averageBox.setLabel("average"); averageBox.setUnit(unit); errorBox.putDataInfo(dataInfo); errorBox.setLabel("error"); errorBox.setPrecision(2); errorBox.setUnit(unit); sim.integratorOS.getEventManager().addListener(new IntegratorListenerAction(pushAnswer)); return; } // if running interactively, don't use the file String refFileName = null; if (isCommandline) { String tempString = ""+temperatureK; if (temperatureK == (int)temperatureK) { // temperature is an integer, use "200" instead of "200.0" tempString = ""+(int)temperatureK; } refFileName = "refpref"+nPoints+"_"+tempString+"_"+nBeads; if (subtractHalf) { refFileName += "_sh"; } else if (doDiff) { if (semiClassical) { refFileName += "_sc"; } else { refFileName += "_c"; } } } long t1 = System.currentTimeMillis(); // this will either read the refpref in from a file or run a short simulation to find it sim.initRefPref(refFileName, steps/40); // this can't be done after equilibration. ClusterSumShell needs at least // one accepted move before it can collect real data. we'll reset below MeterVirial meterDiagrams = new MeterVirial(targetDiagrams); meterDiagrams.setBox(sim.box[1]); AccumulatorAverage accumulatorDiagrams = null; if (targetDiagrams.length > 0) { if (targetDiagrams.length > 1) { accumulatorDiagrams = new AccumulatorAverageCovariance(steps); } else { accumulatorDiagrams = new AccumulatorAverageFixed(steps); } DataPumpListener pumpDiagrams = new DataPumpListener(meterDiagrams, accumulatorDiagrams); sim.integrators[1].getEventManager().addListener(pumpDiagrams); } // run another short simulation to find MC move step sizes and maybe narrow in more on the best ref pref // if it does continue looking for a pref, it will write the value to the file sim.equilibrate(refFileName, steps/20); if (accumulatorDiagrams != null) { accumulatorDiagrams.reset(); } // make the accumulator block size equal to the # of steps performed for each overlap step. // make the integratorOS aggressive so that it runs either reference or target // then, we'll have some number of complete blocks in the accumulator sim.setAccumulatorBlockSize(steps); sim.integratorOS.setNumSubSteps((int)steps); sim.integratorOS.setAgressiveAdjustStepFraction(true); System.out.println("equilibration finished"); System.out.println("MC Move step sizes (ref) "+sim.mcMoveTranslate[0].getStepSize()); System.out.println("MC Move step sizes (target) "+sim.mcMoveTranslate[1].getStepSize()); final HistogramNotSoSimple hist = new HistogramNotSoSimple(100, new DoubleRange(0, sigmaHSRef)); final ClusterAbstract finalTargetCluster = targetCluster.makeCopy(); IIntegratorListener histListener = new IIntegratorListener() { public void integratorStepStarted(IIntegratorEvent e) {} public void integratorStepFinished(IIntegratorEvent e) { double v = finalTargetCluster.value(sim.box[0]); double r = Math.sqrt(sim.box[0].getCPairSet().getr2(0, 1)); hist.addValue(r, v); if (nPoints > 2) { r = Math.sqrt(sim.box[0].getCPairSet().getr2(0, 2)); hist.addValue(r, v); r = Math.sqrt(sim.box[0].getCPairSet().getr2(1, 2)); hist.addValue(r, v); } } public void integratorInitialized(IIntegratorEvent e) { } }; if (!isCommandline) { // if interactive, print intermediate results final double refIntegralF = refIntegral; IIntegratorListener progressReport = new IIntegratorListener() { public void integratorInitialized(IIntegratorEvent e) {} public void integratorStepStarted(IIntegratorEvent e) {} public void integratorStepFinished(IIntegratorEvent e) { if ((sim.integratorOS.getStepCount()*10) % sim.ai.getMaxSteps() != 0) return; System.out.print(sim.integratorOS.getStepCount()+" steps: "); double[] ratioAndError = sim.dsvo.getOverlapAverageAndError(); double ratio = ratioAndError[0]; double error = ratioAndError[1]; System.out.println("abs average: "+ratio*refIntegralF+" error: "+error*refIntegralF); if (ratio == 0 || Double.isNaN(ratio)) { throw new RuntimeException("oops"); } } }; sim.integratorOS.getEventManager().addListener(progressReport); if (refFreq > 0.5) { IIntegratorListener histReport = new IIntegratorListener() { public void integratorInitialized(IIntegratorEvent e) {} public void integratorStepStarted(IIntegratorEvent e) {} public void integratorStepFinished(IIntegratorEvent e) { if ((sim.integratorOS.getStepCount()*10) % sim.ai.getMaxSteps() != 0) return; double[] xValues = hist.xValues(); double[] h = hist.getHistogram(); for (int i=0; i<xValues.length; i++) { if (!Double.isNaN(h[i])) { System.out.println(xValues[i]+" "+h[i]); } } } }; sim.integratorOS.getEventManager().addListener(histReport); } } if (refFreq > 0.5) { // only collect the histogram if we're forcing it to run the reference system sim.integrators[0].getEventManager().addListener(histListener); } sim.ai.setMaxSteps(1000); sim.getController().actionPerformed(); long t2 = System.currentTimeMillis(); if (refFreq > 0.5) { double[] xValues = hist.xValues(); double[] h = hist.getHistogram(); for (int i=0; i<xValues.length; i++) { if (!Double.isNaN(h[i])) { System.out.println(xValues[i]+" "+(-2*h[i]+1)); } } } System.out.println("final reference step fraction "+sim.integratorOS.getIdealRefStepFraction()); System.out.println("actual reference step fraction "+sim.integratorOS.getRefStepFraction()); System.out.println("Ring acceptance "+ring0.getTracker().acceptanceRatio()+" "+ring1.getTracker().acceptanceRatio()); double[] ratioAndError = sim.dsvo.getOverlapAverageAndError(); double ratio = ratioAndError[0]; double error = ratioAndError[1]; System.out.println("ratio average: "+ratio+" error: "+error); System.out.println("abs average: "+ratio*refIntegral+" error: "+error*refIntegral); double conv = Mole.UNIT.toSim(1e-24); System.out.println(" (cm^3/mol)^"+(nPoints-1)+" "+ratio*refIntegral*Math.pow(conv, nPoints-1)+" "+error*refIntegral*Math.pow(conv, nPoints-1)); DataGroup allYourBase = (DataGroup)sim.accumulators[0].getData(); IData ratioData = allYourBase.getData(AccumulatorRatioAverageCovariance.StatType.RATIO.index); IData ratioErrorData = allYourBase.getData(AccumulatorRatioAverageCovariance.StatType.RATIO_ERROR.index); IData averageData = allYourBase.getData(AccumulatorRatioAverageCovariance.StatType.AVERAGE.index); IData stdevData = allYourBase.getData(AccumulatorRatioAverageCovariance.StatType.STANDARD_DEVIATION.index); IData errorData = allYourBase.getData(AccumulatorRatioAverageCovariance.StatType.ERROR.index); IData correlationData = allYourBase.getData(AccumulatorRatioAverageCovariance.StatType.BLOCK_CORRELATION.index); IData covarianceData = allYourBase.getData(AccumulatorRatioAverageCovariance.StatType.BLOCK_COVARIANCE.index); double correlationCoef = covarianceData.getValue(1)/(stdevData.getValue(0)*stdevData.getValue(1)); correlationCoef = (Double.isNaN(correlationCoef) || Double.isInfinite(correlationCoef)) ? 0 : correlationCoef; System.out.print(String.format("reference ratio average: %20.15e error: %10.5e cor: %9.3e\n", ratioData.getValue(1), ratioErrorData.getValue(1), correlationCoef)); System.out.print(String.format("reference average: %20.15e stdev: %9.3e error: %9.3e cor: %6.4f\n", averageData.getValue(0), stdevData.getValue(0), errorData.getValue(0), correlationData.getValue(0))); System.out.print(String.format("reference overlap average: %20.15e stdev: %9.3e error: %9.3e cor: %6.4f\n", averageData.getValue(1), stdevData.getValue(1), errorData.getValue(1), correlationData.getValue(1))); allYourBase = (DataGroup)sim.accumulators[1].getData(); ratioData = allYourBase.getData(AccumulatorRatioAverageCovariance.StatType.RATIO.index); ratioErrorData = allYourBase.getData(AccumulatorRatioAverageCovariance.StatType.RATIO_ERROR.index); averageData = allYourBase.getData(AccumulatorRatioAverageCovariance.StatType.AVERAGE.index); stdevData = allYourBase.getData(AccumulatorRatioAverageCovariance.StatType.STANDARD_DEVIATION.index); errorData = allYourBase.getData(AccumulatorRatioAverageCovariance.StatType.ERROR.index); correlationData = allYourBase.getData(AccumulatorRatioAverageCovariance.StatType.BLOCK_CORRELATION.index); covarianceData = allYourBase.getData(AccumulatorRatioAverageCovariance.StatType.BLOCK_COVARIANCE.index); correlationCoef = covarianceData.getValue(1)/(stdevData.getValue(0)*stdevData.getValue(1)); correlationCoef = (Double.isNaN(correlationCoef) || Double.isInfinite(correlationCoef)) ? 0 : correlationCoef; System.out.print(String.format("target ratio average: %20.15e error: %10.5e cor: %9.3e\n", ratioData.getValue(1), ratioErrorData.getValue(1), correlationCoef)); System.out.print(String.format("target average: %20.15e stdev: %9.3e error: %9.3e cor: %6.4f\n", averageData.getValue(0), stdevData.getValue(0), errorData.getValue(0), correlationData.getValue(0))); System.out.print(String.format("target overlap average: %20.15e stdev: %9.3e error: %9.3e cor: %6.4f\n", averageData.getValue(1), stdevData.getValue(1), errorData.getValue(1), correlationData.getValue(1))); for (int i=0; i<targetDiagrams.length; i++) { DataGroup allData = (DataGroup)accumulatorDiagrams.getData(); IData dataAvg = allData.getData(AccumulatorAverageCovariance.StatType.AVERAGE.index); IData dataErr = allData.getData(AccumulatorAverageCovariance.StatType.ERROR.index); System.out.print("diagram "+targetDiagramNumbers[i]+" "); System.out.print("average: "+dataAvg.getValue(i)+" error: "+dataErr.getValue(i)); if (targetDiagrams.length > 1) { System.out.print(" cov:"); IData dataCov = allData.getData(AccumulatorAverageCovariance.StatType.BLOCK_COVARIANCE.index); double ivar = dataCov.getValue(i*targetDiagrams.length+i); for (int j=0; j<targetDiagrams.length; j++) { if (i==j) continue; double jvar = dataCov.getValue(j*targetDiagrams.length+j); System.out.print(" "+dataCov.getValue(i*targetDiagrams.length+j)/Math.sqrt(ivar*jvar)); } } System.out.println(); } System.out.println("time: "+(t2-t1)/1000.0); } public static ClusterBonds[] append(ClusterBonds[] inArray, ClusterBonds[] newBonds) { ClusterBonds[] outArray = new ClusterBonds[inArray.length + newBonds.length]; System.arraycopy(inArray, 0, outArray, 0, inArray.length); System.arraycopy(newBonds, 0, outArray, inArray.length, newBonds.length); return outArray; } public static double[] append(double[] inArray, double[] newWeights) { double[] outArray = new double[inArray.length + newWeights.length]; System.arraycopy(inArray, 0, outArray, 0, inArray.length); System.arraycopy(newWeights, 0, outArray, inArray.length, newWeights.length); return outArray; } /** * Inner class for parameters */ public static class VirialHePIParam extends ParameterBase { public int nPoints = 2; public int nBeads = 4; public double temperature = 100; // Kelvin public long numSteps = 1000000; public double refFrac = -1; public double sigmaHSRef = 5; public boolean doDiff = true; public boolean semiClassical = false; public boolean subtractHalf = false; public int startBeadHalfs = 0; public int beadFac = 2; public int finalNumBeads = 2; public boolean pairOnly = true; } }
package lt.markmerkk.utils; import java.io.File; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Stream; import javafx.scene.control.TextArea; import lt.markmerkk.Main; import org.apache.commons.io.input.ReversedLinesFileReader; import org.joda.time.DurationFieldType; import org.joda.time.Period; import org.joda.time.PeriodType; public class Utils { /** * Checks if string is empty or null * @param string provided string to check * @return empty flag */ public static boolean isEmpty(String string) { return !(string != null && string.length() > 0); } /** * Checks if array is empty or null * @param array provided array to check * @return empty flag */ public static boolean isArrayEmpty(ArrayList<String> array) { if (array == null) return true; if (array.size() == 0) return true; return false; } /** * Formats duration time into pretty string format * @param durationMillis provided duration to format * @return formatted duration */ public static String formatDuration(long durationMillis) { if (durationMillis < 1000) return "0s"; StringBuilder builder = new StringBuilder(); PeriodType type = PeriodType.forFields(new DurationFieldType[]{ DurationFieldType.hours(), DurationFieldType.minutes(), DurationFieldType.seconds() }); Period period = new Period(durationMillis, type); if (period.getDays() != 0) builder.append(period.getDays()).append("d").append(" "); if (period.getHours() != 0) builder.append(period.getHours()).append("h").append(" "); if (period.getMinutes() != 0) builder.append(period.getMinutes()).append("m").append(" "); if (period.getSeconds() != 0) builder.append(period.getSeconds()).append("s").append(" "); if ((builder.length() > 0) && builder.charAt(builder.length()-1) == " ".charAt(0)) builder.deleteCharAt(builder.length()-1); return builder.toString(); } /** * Formats duration time into pretty and short string format * @param durationMillis provided duration to format * @return formatted duration */ // fixme : needs tests, as this code was copied from earlier project public static String formatShortDuration(long durationMillis) { if (durationMillis < (1000*60)) return "0m"; StringBuilder builder = new StringBuilder(); PeriodType type = PeriodType.forFields(new DurationFieldType[]{ DurationFieldType.hours(), DurationFieldType.minutes() }); Period period = new Period(durationMillis, type); if (period.getDays() != 0) builder.append(period.getDays()).append("d").append(" "); if (period.getHours() != 0) builder.append(period.getHours()).append("h").append(" "); if (period.getMinutes() != 0) builder.append(period.getMinutes()).append("m").append(" "); if ((builder.length() > 0) && builder.charAt(builder.length()-1) == " ".charAt(0)) builder.deleteCharAt(builder.length()-1); return builder.toString(); } public static final String SEPERATOR = "-"; /** * Inspects id for a valid type * @param message */ public static String validateTaskTitle(String message) { if (Utils.isEmpty(message)) return ""; message = message.replaceAll("\\n", ""); Pattern pattern = Pattern.compile("[a-zA-Z]+(-)?[0-9]+"); Matcher matcher = pattern.matcher(message.trim()); if (matcher.find()) { String found = matcher.group(); found = found.toUpperCase(); found = found.trim(); if (!found.contains(SEPERATOR)) found = insertTaskSeperator(found); if (found.length() == 0) return null; return found; } return ""; } /** * Insers a missing seperator if it is missing. * @param message message that should be altered * @return altered message with seperator attached to its proper spot. */ public static String insertTaskSeperator(String message) { if (message == null) return null; Pattern pattern = Pattern.compile("[a-zA-Z]+[^0-9]"); Matcher matcher = pattern.matcher(message.trim()); if (matcher.find()) { message = message.substring(0, matcher.end()) +SEPERATOR +message.substring(matcher.end(), message.length()); } return message; } /** * Splits task title into */ public static String splitTaskTitle(String message) { if (Utils.isEmpty(message)) return null; message = message.replaceAll("\\n", ""); Pattern pattern = Pattern.compile("[a-zA-Z]+"); Matcher matcher = pattern.matcher(message.trim()); if (matcher.find()) { String found = matcher.group(); found = found.toUpperCase(); found = found.trim(); if (found.length() == 0) return null; return found; } return null; } /** * Fills provided text area with an old log * @param textArea */ public static void fillAllLog(TextArea textArea) { if (textArea == null) return; textArea.clear(); try (Stream<String> stream = Files.lines(Paths.get("checkLog.log"), Charset.defaultCharset())) { stream.forEach(textArea::appendText); } catch (IOException ex) { } } /** * Returns last logged output */ public static String lastLog() { StringBuilder output = new StringBuilder(); try { int maxLines = 150; int lineCount = 0; File file = new File(Main.CFG_PATH + "info.log"); ReversedLinesFileReader object = new ReversedLinesFileReader(file); while (lineCount < maxLines) { String line = object.readLine(); //if (line == null) return ""; output.insert(0, line + "\n"); lineCount++; } } catch (IOException e) { } catch (NullPointerException e) { } return output.toString(); } }
package pt.passarola.model; import com.google.gson.annotations.SerializedName; public class Place { private String id; private String name; @SerializedName("full_address") private String fullAddress; private String location; private String council; private String country; private String lat; private String lng; private String type; private String facebook; private String gmaps; private String tripadvisor; private String website; private String email; private String telephone; private String active; private String updated; public String getId() { return id; } public String getName() { return name; } public String getFullAddress() { return fullAddress; } public String getLocation() { return location; } public String getCouncil() { return council; } public String getCountry() { return country; } public String getLat() { return lat; } public String getLng() { return lng; } public String getType() { return type; } public String getFacebook() { return facebook; } public String getGmaps() { return gmaps; } public String getTripadvisor() { return tripadvisor; } public String getWebsite() { return website; } public String getEmail() { return email; } public String getTelephone() { return telephone; } public String getActive() { return active; } public String getUpdated() { return updated; } public boolean isValid(){ return lat != null && !lat.isEmpty() && lng != null && !lng.isEmpty(); } }
package org.commcare.adapters; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Color; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import org.commcare.dalvik.R; import org.commcare.utils.MediaUtil; import org.commcare.utils.StringUtils; public class ImageAdapter extends BaseAdapter { private final String[] choices; private final ImageView[] imageViews; private final Context context; public ImageAdapter(Context context, String[] choices, ImageView[] imageViews) { this.choices = choices; this.context = context; this.imageViews = imageViews; } @Override public int getCount() { return choices.length; } @Override public Object getItem(int position) { return null; } @Override public long getItemId(int position) { return 0; } // create a new ImageView for each item referenced by the Adapter @Override public View getView(int position, View convertView, ViewGroup parent) { String imageURI = choices[position]; // It is possible that an imageview already exists and has been updated // by updateViewAfterAnswer ImageView mImageView = null; if (imageViews[position] != null) { mImageView = imageViews[position]; } TextView mMissingImage = null; if (imageURI != null) { Bitmap b = MediaUtil.inflateDisplayImage(context, imageURI); if (b != null) { if (mImageView == null) { mImageView = new ImageView(context); mImageView.setBackgroundColor(Color.WHITE); } mImageView.setPadding(3, 3, 3, 3); mImageView.setImageBitmap(b); imageViews[position] = mImageView; } else { String errorMsg = StringUtils.getStringRobust(context, R.string.file_invalid, imageURI); Log.e("GridWidget", errorMsg); mMissingImage = new TextView(context); mMissingImage.setText(errorMsg); mMissingImage.setPadding(10, 10, 10, 10); } } if (mImageView != null) { mImageView.setScaleType(ImageView.ScaleType.FIT_XY); return mImageView; } else { return mMissingImage; } } }
package net.bytebuddy.asm; import net.bytebuddy.ClassFileVersion; import net.bytebuddy.description.annotation.AnnotationDescription; import net.bytebuddy.description.field.FieldDescription; import net.bytebuddy.description.method.MethodDescription; import net.bytebuddy.description.method.MethodList; import net.bytebuddy.description.method.ParameterDescription; import net.bytebuddy.description.method.ParameterList; import net.bytebuddy.description.type.TypeDefinition; import net.bytebuddy.description.type.TypeDescription; import net.bytebuddy.description.type.TypeList; import net.bytebuddy.dynamic.ClassFileLocator; import net.bytebuddy.dynamic.scaffold.FieldLocator; import net.bytebuddy.implementation.bytecode.StackSize; import net.bytebuddy.matcher.ElementMatcher; import net.bytebuddy.utility.CompoundList; import net.bytebuddy.utility.ExceptionTableSensitiveMethodVisitor; import org.objectweb.asm.*; import java.io.*; import java.lang.annotation.*; import java.util.*; import static net.bytebuddy.matcher.ElementMatchers.named; public class Advice implements AsmVisitorWrapper.ForDeclaredMethods.MethodVisitorWrapper { /** * Indicates that no class reader is available to an adice method. */ private static final ClassReader UNDEFINED = null; /** * A reference to the {@link OnMethodEnter#inline()} method. */ private static final MethodDescription.InDefinedShape INLINE_ENTER; /** * A reference to the {@link OnMethodEnter#suppress()} method. */ private static final MethodDescription.InDefinedShape SUPPRESS_ENTER; /** * A reference to the {@link OnMethodEnter#skipIfTrue()} method. */ private static final MethodDescription.InDefinedShape SKIP_IF_TRUE; /** * A reference to the {@link OnMethodExit#inline()} method. */ private static final MethodDescription.InDefinedShape INLINE_EXIT; /** * A reference to the {@link OnMethodExit#suppress()} method. */ private static final MethodDescription.InDefinedShape SUPPRESS_EXIT; /** * A reference to the {@link OnMethodExit#onThrowable()} method. */ private static final MethodDescription.InDefinedShape ON_THROWABLE; /* * Extracts the annotation values for the enter and exit advice annotations. */ static { MethodList<MethodDescription.InDefinedShape> enter = new TypeDescription.ForLoadedType(OnMethodEnter.class).getDeclaredMethods(); INLINE_ENTER = enter.filter(named("inline")).getOnly(); SUPPRESS_ENTER = enter.filter(named("suppress")).getOnly(); SKIP_IF_TRUE = enter.filter(named("skipIfTrue")).getOnly(); MethodList<MethodDescription.InDefinedShape> exit = new TypeDescription.ForLoadedType(OnMethodExit.class).getDeclaredMethods(); INLINE_EXIT = exit.filter(named("inline")).getOnly(); SUPPRESS_EXIT = exit.filter(named("suppress")).getOnly(); ON_THROWABLE = exit.filter(named("onThrowable")).getOnly(); } /** * The dispatcher for instrumenting the instrumented method upon entering. */ private final Dispatcher.Resolved.ForMethodEnter methodEnter; /** * The dispatcher for instrumenting the instrumented method upon exiting. */ private final Dispatcher.Resolved.ForMethodExit methodExit; /** * Creates a new advice. * * @param methodEnter The dispatcher for instrumenting the instrumented method upon entering. * @param methodExit The dispatcher for instrumenting the instrumented method upon exiting. */ protected Advice(Dispatcher.Resolved.ForMethodEnter methodEnter, Dispatcher.Resolved.ForMethodExit methodExit) { this.methodEnter = methodEnter; this.methodExit = methodExit; } /** * Implements advice where every matched method is advised by the given type's advisory methods. The advices binary representation is * accessed by querying the class loader of the supplied class for a class file. * * @param type The type declaring the advice. * @return A method visitor wrapper representing the supplied advice. */ public static Advice to(Class<?> type) { return to(type, ClassFileLocator.ForClassLoader.of(type.getClassLoader())); } /** * Implements advice where every matched method is advised by the given type's advisory methods. * * @param type The type declaring the advice. * @param classFileLocator The class file locator for locating the advisory class's class file. * @return A method visitor wrapper representing the supplied advice. */ public static Advice to(Class<?> type, ClassFileLocator classFileLocator) { return to(new TypeDescription.ForLoadedType(type), classFileLocator); } /** * Implements advice where every matched method is advised by the given type's advisory methods. Using this method, a non-operational * class file locator is specified for the advice target. This implies that only advice targets with the <i>inline</i> target set * to {@code false} are resolvable by the returned instance. * * @param typeDescription The type declaring the advice. * @return A method visitor wrapper representing the supplied advice. */ public static Advice to(TypeDescription typeDescription) { return to(typeDescription, ClassFileLocator.NoOp.INSTANCE); } /** * Implements advice where every matched method is advised by the given type's advisory methods. * * @param typeDescription A description of the type declaring the advice. * @param classFileLocator The class file locator for locating the advisory class's class file. * @return A method visitor wrapper representing the supplied advice. */ public static Advice to(TypeDescription typeDescription, ClassFileLocator classFileLocator) { return to(typeDescription, classFileLocator, Collections.<Dispatcher.OffsetMapping.Factory>emptyList()); } /** * Creates a new advice. * * @param typeDescription A description of the type declaring the advice. * @param classFileLocator The class file locator for locating the advisory class's class file. * @param userFactories A list of custom factories for user generated offset mappings. * @return A method visitor wrapper representing the supplied advice. */ protected static Advice to(TypeDescription typeDescription, ClassFileLocator classFileLocator, List<? extends Dispatcher.OffsetMapping.Factory> userFactories) { try { Dispatcher.Unresolved methodEnter = Dispatcher.Inactive.INSTANCE, methodExit = Dispatcher.Inactive.INSTANCE; for (MethodDescription.InDefinedShape methodDescription : typeDescription.getDeclaredMethods()) { methodEnter = locate(OnMethodEnter.class, INLINE_ENTER, methodEnter, methodDescription); methodExit = locate(OnMethodExit.class, INLINE_EXIT, methodExit, methodDescription); } if (!methodEnter.isAlive() && !methodExit.isAlive()) { throw new IllegalArgumentException("No advice defined by " + typeDescription); } ClassReader classReader = methodEnter.isBinary() || methodExit.isBinary() ? new ClassReader(classFileLocator.locate(typeDescription.getName()).resolve()) : UNDEFINED; Dispatcher.Resolved.ForMethodEnter resolved = methodEnter.asMethodEnter(userFactories, classReader); return new Advice(resolved, methodExit.asMethodExitTo(userFactories, classReader, resolved)); } catch (IOException exception) { throw new IllegalStateException("Error reading class file of " + typeDescription, exception); } } /** * Locates a dispatcher for the method if available. * * @param type The annotation type that indicates a given form of advice that is currently resolved. * @param property An annotation property that indicates if the advice method should be inlined. * @param dispatcher Any previous dispatcher that was discovered or {@code null} if no such dispatcher was yet found. * @param methodDescription The method description that is considered as an advice method. * @return A resolved dispatcher or {@code null} if no dispatcher was resolved. */ private static Dispatcher.Unresolved locate(Class<? extends Annotation> type, MethodDescription.InDefinedShape property, Dispatcher.Unresolved dispatcher, MethodDescription.InDefinedShape methodDescription) { AnnotationDescription annotation = methodDescription.getDeclaredAnnotations().ofType(type); if (annotation == null) { return dispatcher; } else if (dispatcher.isAlive()) { throw new IllegalStateException("Duplicate advice for " + dispatcher + " and " + methodDescription); } else if (!methodDescription.isStatic()) { throw new IllegalStateException("Advice for " + methodDescription + " is not static"); } else { return annotation.getValue(property, Boolean.class) ? new Dispatcher.Inlining(methodDescription) : new Dispatcher.Delegating(methodDescription); } } /** * Allows for the configuration of custom annotations that are then bound to a dynamically computed, constant value. * * @return A builder for an {@link Advice} instrumentation with custom values. * @see DynamicValue */ public static WithCustomMapping withCustomMapping() { return new WithCustomMapping(); } /** * Returns an ASM visitor wrapper that matches the given matcher and applies this advice to the matched methods. * * @param matcher The matcher identifying methods to apply the advice to. * @return A suitable ASM visitor wrapper with the <i>compute frames</i> option enabled. */ public AsmVisitorWrapper.ForDeclaredMethods on(ElementMatcher<? super MethodDescription.InDefinedShape> matcher) { return new AsmVisitorWrapper.ForDeclaredMethods().method(matcher, this); } @Override public MethodVisitor wrap(TypeDescription instrumentedType, MethodDescription.InDefinedShape methodDescription, MethodVisitor methodVisitor, ClassFileVersion classFileVersion, int writerFlags, int readerFlags) { if (methodDescription.isAbstract() || methodDescription.isNative()) { return methodVisitor; } else if (!methodExit.isAlive()) { return new AdviceVisitor.WithoutExitAdvice(methodVisitor, methodDescription, methodEnter, classFileVersion, writerFlags, readerFlags); } else if (methodExit.getTriggeringThrowable().represents(NoExceptionHandler.class)) { return new AdviceVisitor.WithExitAdvice.WithoutExceptionHandling(methodVisitor, methodDescription, methodEnter, methodExit, classFileVersion, writerFlags, readerFlags); } else if (methodDescription.isConstructor()) { throw new IllegalStateException("Cannot catch exception during constructor call for " + methodDescription); } else { return new AdviceVisitor.WithExitAdvice.WithExceptionHandling(methodVisitor, methodDescription, methodEnter, methodExit, classFileVersion, writerFlags, readerFlags, methodExit.getTriggeringThrowable()); } } @Override public boolean equals(Object other) { if (this == other) return true; if (other == null || getClass() != other.getClass()) return false; Advice advice = (Advice) other; return methodEnter.equals(advice.methodEnter) && methodExit.equals(advice.methodExit); } @Override public int hashCode() { int result = methodEnter.hashCode(); result = 31 * result + methodExit.hashCode(); return result; } @Override public String toString() { return "Advice{" + "methodEnter=" + methodEnter + ", methodExit=" + methodExit + '}'; } /** * A handler for computing the instrumented method's size. */ protected interface MethodSizeHandler { /** * Indicates that a size is not computed but handled directly by ASM. */ int UNDEFINED_SIZE = Short.MAX_VALUE; /** * Binds a method size handler for the entry advice. * * @param adviceMethod The method representing the entry advice. * @return A method size handler for the entry advice. */ ForAdvice bindEntry(MethodDescription.InDefinedShape adviceMethod); /** * Binds the method size handler for the exit advice. * * @param adviceMethod The method representing the exit advice. * @param skipThrowable {@code true} if the exit advice is not invoked on an exception. * @return A method size handler for the exit advice. */ ForAdvice bindExit(MethodDescription.InDefinedShape adviceMethod, boolean skipThrowable); /** * Computes a compound stack size for the advice and the translated instrumented method. * * @param stackSize The required stack size of the instrumented method before translation. * @return The stack size required by the instrumented method and its advice methods. */ int compoundStackSize(int stackSize); /** * Computes a compound local variable array length for the advice and the translated instrumented method. * * @param localVariableLength The required local variable array length of the instrumented method before translation. * @return The local variable length required by the instrumented method and its advice methods. */ int compoundLocalVariableLength(int localVariableLength); /** * A method size handler for an advice method. */ interface ForAdvice { /** * Records a minimum stack size required by the represented advice method. * * @param stackSize The minimum size required by the represented advice method. */ void recordMinimum(int stackSize); /** * Records the maximum values for stack size and local variable array which are required by the advice method * for its individual execution without translation. * * @param stackSize The minimum required stack size. * @param localVariableLength The minimum required length of the local variable array. */ void recordMaxima(int stackSize, int localVariableLength); /** * Records a minimum padding additionally to the computed stack size that is required for implementing this advice method. * * @param padding The minimum required padding. */ void recordPadding(int padding); } /** * A non-operational method size handler. */ enum NoOp implements MethodSizeHandler, ForAdvice { /** * The singleton instance. */ INSTANCE; @Override public ForAdvice bindEntry(MethodDescription.InDefinedShape adviceMethod) { return this; } @Override public ForAdvice bindExit(MethodDescription.InDefinedShape adviceMethod, boolean skipThrowable) { return this; } @Override public int compoundStackSize(int stackSize) { return UNDEFINED_SIZE; } @Override public int compoundLocalVariableLength(int localVariableLength) { return UNDEFINED_SIZE; } @Override public void recordMinimum(int stackSize) { /* do nothing */ } @Override public void recordMaxima(int stackSize, int localVariableLength) { /* do nothing */ } @Override public void recordPadding(int padding) { /* do nothing */ } @Override public String toString() { return "Advice.MethodSizeHandler.NoOp." + name(); } } /** * A default implementation for a method size handler. */ class Default implements MethodSizeHandler { /** * The instrumented method. */ private final MethodDescription.InDefinedShape instrumentedMethod; /** * The list of types that the instrumented method requires in addition to the method parameters. */ private final TypeList requiredTypes; /** * A list of types that are yielded by the instrumented method and available to the exit advice. */ private final TypeList yieldedTypes; /** * The maximum stack size required by a visited advice method. */ private int stackSize; /** * The maximum length of the local variable array required by a visited advice method. */ private int localVariableLength; /** * Creates a new default meta data handler that recomputes the space requirements of an instrumented method. * * @param instrumentedMethod The instrumented method. * @param requiredTypes The types this meta data handler expects to be available additionally to the instrumented method's parameters. * @param yieldedTypes The types that are expected to be added after the instrumented method returns. */ protected Default(MethodDescription.InDefinedShape instrumentedMethod, TypeList requiredTypes, TypeList yieldedTypes) { this.instrumentedMethod = instrumentedMethod; this.requiredTypes = requiredTypes; this.yieldedTypes = yieldedTypes; } /** * Creates a method size handler applicable for the given instrumented method. * * @param instrumentedMethod The instrumented method. * @param requiredTypes The list of types that the instrumented method requires in addition to the method parameters. * @param yieldedTypes A list of types that are yielded by the instrumented method and available to the exit advice. * @param writerFlags The flags supplied to the ASM class writer. * @return An appropriate method size handler. */ protected static MethodSizeHandler of(MethodDescription.InDefinedShape instrumentedMethod, List<? extends TypeDescription> requiredTypes, List<? extends TypeDescription> yieldedTypes, int writerFlags) { return (writerFlags & (ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES)) != 0 ? NoOp.INSTANCE : new Default(instrumentedMethod, new TypeList.Explicit(requiredTypes), new TypeList.Explicit(yieldedTypes)); } @Override public MethodSizeHandler.ForAdvice bindEntry(MethodDescription.InDefinedShape adviceMethod) { stackSize = Math.max(stackSize, adviceMethod.getReturnType().getStackSize().getSize()); return new ForAdvice(adviceMethod, new TypeList.Empty(), new TypeList.Explicit(requiredTypes)); } @Override public MethodSizeHandler.ForAdvice bindExit(MethodDescription.InDefinedShape adviceMethod, boolean skipThrowable) { stackSize = Math.max(stackSize, adviceMethod.getReturnType().getStackSize().maximum(skipThrowable ? StackSize.ZERO : StackSize.SINGLE).getSize()); return new ForAdvice(adviceMethod, new TypeList.Explicit(CompoundList.of(requiredTypes, yieldedTypes)), new TypeList.Empty()); } @Override public int compoundStackSize(int stackSize) { return Math.max(this.stackSize, stackSize); } @Override public int compoundLocalVariableLength(int localVariableLength) { return Math.max(this.localVariableLength, localVariableLength + requiredTypes.getStackSize() + yieldedTypes.getStackSize()); } @Override public String toString() { return "Advice.MethodSizeHandler.Default{" + "instrumentedMethod=" + instrumentedMethod + ", requiredTypes=" + requiredTypes + ", yieldedTypes=" + yieldedTypes + ", stackSize=" + stackSize + ", localVariableLength=" + localVariableLength + '}'; } /** * A method size handler for an advice method. */ protected class ForAdvice implements MethodSizeHandler.ForAdvice { /** * The advice method. */ private final MethodDescription.InDefinedShape adviceMethod; /** * A list of types required by this advice method. */ private final TypeList requiredTypes; /** * A list of types yielded by this advice method. */ private final TypeList yieldedTypes; /** * The padding that this advice method requires additionally to its computed size. */ private int padding; /** * Creates a new method size handler for an advice method. * * @param adviceMethod The advice method. * @param requiredTypes A list of types required by this advice method. * @param yieldedTypes A list of types yielded by this advice method. */ protected ForAdvice(MethodDescription.InDefinedShape adviceMethod, TypeList requiredTypes, TypeList yieldedTypes) { this.adviceMethod = adviceMethod; this.requiredTypes = requiredTypes; this.yieldedTypes = yieldedTypes; stackSize = Math.max(stackSize, adviceMethod.getReturnType().getStackSize().getSize()); } @Override public void recordMinimum(int stackSize) { Default.this.stackSize = Math.max(Default.this.stackSize, stackSize); } @Override public void recordMaxima(int stackSize, int localVariableLength) { Default.this.stackSize = Math.max(Default.this.stackSize, stackSize) + padding; Default.this.localVariableLength = Math.max(Default.this.localVariableLength, localVariableLength - adviceMethod.getStackSize() + instrumentedMethod.getStackSize() + requiredTypes.getStackSize() + yieldedTypes.getStackSize()); } @Override public void recordPadding(int padding) { this.padding = Math.max(this.padding, padding); } @Override public String toString() { return "Advice.MethodSizeHandler.Default.ForAdvice{" + "adviceMethod=" + adviceMethod + ", requiredTypes=" + requiredTypes + ", yieldedTypes=" + yieldedTypes + ", padding=" + padding + '}'; } } } } /** * A handler for computing and translating stack map frames. */ protected interface StackMapFrameHandler { /** * Translates a frame. * * @param methodVisitor The method visitor to write the frame to. * @param frameType The frame's type. * @param localVariableLength The local variable length. * @param localVariable An array containing the types of the current local variables. * @param stackSize The size of the operand stack. * @param stack An array containing the types of the current operand stack. */ void translateFrame(MethodVisitor methodVisitor, int frameType, int localVariableLength, Object[] localVariable, int stackSize, Object[] stack); /** * Injects a frame indicating the beginning of a return value handler for the currently handled method. * * @param methodVisitor The method visitor onto which to apply the stack map frame. */ void injectReturnFrame(MethodVisitor methodVisitor); /** * Injects a frame indicating the beginning of an exception handler for the currently handled method. * * @param methodVisitor The method visitor onto which to apply the stack map frame. */ void injectExceptionFrame(MethodVisitor methodVisitor); /** * Injects a frame indicating the completion of the currently handled method, i.e. all yielded types were added. * * @param methodVisitor The method visitor onto which to apply the stack map frame. * @param secondary {@code true} if another completion frame for this method was written previously. */ void injectCompletionFrame(MethodVisitor methodVisitor, boolean secondary); /** * A stack map frame handler for an instrumented method. */ interface ForInstrumentedMethod extends StackMapFrameHandler { /** * Binds this meta data handler for the entry advice. * * @param adviceMethod The entry advice method. * @return An appropriate meta data handler for the enter method. */ ForAdvice bindEntry(MethodDescription.InDefinedShape adviceMethod); /** * Binds this meta data handler for the exit advice. * * @param adviceMethod The exit advice method. * @return An appropriate meta data handler for the enter method. */ ForAdvice bindExit(MethodDescription.InDefinedShape adviceMethod); /** * Returns a hint to supply to a {@link ClassReader} when parsing an advice method. * * @return The reader hint to supply to an ASM class reader. */ int getReaderHint(); } /** * A stack map frame handler for an advice method. */ interface ForAdvice extends StackMapFrameHandler { /* marker interface */ } /** * A non-operational stack map frame handler. */ enum NoOp implements ForInstrumentedMethod, ForAdvice { /** * The singleton instance. */ INSTANCE; @Override public StackMapFrameHandler.ForAdvice bindEntry(MethodDescription.InDefinedShape adviceMethod) { return this; } @Override public StackMapFrameHandler.ForAdvice bindExit(MethodDescription.InDefinedShape adviceMethod) { return this; } @Override public int getReaderHint() { return ClassReader.SKIP_FRAMES; } @Override public void translateFrame(MethodVisitor methodVisitor, int frameType, int localVariableLength, Object[] localVariable, int stackSize, Object[] stack) { /* do nothing */ } @Override public void injectReturnFrame(MethodVisitor methodVisitor) { /* do nothing */ } @Override public void injectExceptionFrame(MethodVisitor methodVisitor) { /* do nothing */ } @Override public void injectCompletionFrame(MethodVisitor methodVisitor, boolean secondary) { /* do nothing */ } @Override public String toString() { return "Advice.StackMapFrameHandler.NoOp." + name(); } } /** * A default implementation of a stack map frame handler for an instrumented method. */ class Default implements ForInstrumentedMethod { /** * An empty array indicating an empty frame. */ private static final Object[] EMPTY = new Object[0]; /** * The instrumented method. */ protected final MethodDescription.InDefinedShape instrumentedMethod; /** * A list of intermediate types to be considered as part of the instrumented method's steady signature. */ protected final TypeList requiredTypes; /** * The types that are expected to be added after the instrumented method returns. */ protected final TypeList yieldedTypes; /** * {@code true} if the meta data handler is expected to expand its frames. */ private final boolean expandFrames; /** * The current frame's size divergence from the original local variable array. */ private int currentFrameDivergence; /** * Creates a new default meta data handler. * * @param instrumentedMethod The instrumented method. * @param requiredTypes A list of intermediate types to be considered as part of the instrumented method's steady signature. * @param yieldedTypes The types that are expected to be added after the instrumented method returns. * @param expandFrames {@code true} if the meta data handler is expected to expand its frames. */ protected Default(MethodDescription.InDefinedShape instrumentedMethod, TypeList requiredTypes, TypeList yieldedTypes, boolean expandFrames) { this.instrumentedMethod = instrumentedMethod; this.requiredTypes = requiredTypes; this.yieldedTypes = yieldedTypes; this.expandFrames = expandFrames; } /** * Creates an appropriate stack map frame handler for an instrumented method. * * @param instrumentedMethod The instrumented method. * @param requiredTypes A list of intermediate types to be considered as part of the instrumented method's steady signature. * @param yieldedTypes The types that are expected to be added after the instrumented method returns. * @param classFileVersion The instrumented type's class file version. * @param writerFlags The flags supplied to the ASM writier. * @param readerFlags The reader flags supplied to the ASM reader. * @return An approrpiate stack map frame handler for an instrumented method. */ protected static ForInstrumentedMethod of(MethodDescription.InDefinedShape instrumentedMethod, List<? extends TypeDescription> requiredTypes, List<? extends TypeDescription> yieldedTypes, ClassFileVersion classFileVersion, int writerFlags, int readerFlags) { return (writerFlags & ClassWriter.COMPUTE_FRAMES) != 0 || classFileVersion.isLessThan(ClassFileVersion.JAVA_V6) ? NoOp.INSTANCE : new Default(instrumentedMethod, new TypeList.Explicit(requiredTypes), new TypeList.Explicit(yieldedTypes), (readerFlags & ClassReader.EXPAND_FRAMES) != 0); } /** * Translates a type into a representation of its form inside a stack map frame. * * @param typeDescription The type to translate. * @return A stack entry representation of the supplied type. */ protected static Object toFrame(TypeDescription typeDescription) { if (typeDescription.represents(boolean.class) || typeDescription.represents(byte.class) || typeDescription.represents(short.class) || typeDescription.represents(char.class) || typeDescription.represents(int.class)) { return Opcodes.INTEGER; } else if (typeDescription.represents(long.class)) { return Opcodes.LONG; } else if (typeDescription.represents(float.class)) { return Opcodes.FLOAT; } else if (typeDescription.represents(double.class)) { return Opcodes.DOUBLE; } else { return typeDescription.getInternalName(); } } @Override public StackMapFrameHandler.ForAdvice bindEntry(MethodDescription.InDefinedShape adviceMethod) { return new ForAdvice(adviceMethod, new TypeList.Empty(), requiredTypes, TranslationMode.ENTRY); } @Override public StackMapFrameHandler.ForAdvice bindExit(MethodDescription.InDefinedShape adviceMethod) { return new ForAdvice(adviceMethod, new TypeList.Explicit(CompoundList.of(requiredTypes, yieldedTypes)), new TypeList.Empty(), TranslationMode.EXIT); } @Override public int getReaderHint() { return expandFrames ? ClassReader.EXPAND_FRAMES : AsmVisitorWrapper.NO_FLAGS; } @Override public void translateFrame(MethodVisitor methodVisitor, int type, int localVariableLength, Object[] localVariable, int stackSize, Object[] stack) { translateFrame(methodVisitor, TranslationMode.COPY, instrumentedMethod, requiredTypes, type, localVariableLength, localVariable, stackSize, stack); } /** * Translates a frame. * * @param methodVisitor The method visitor to write the frame to. * @param translationMode The translation mode to apply. * @param methodDescription The method description for which the frame is written. * @param additionalTypes The additional types to consider part of the instrumented method's parameters. * @param frameType The frame's type. * @param localVariableLength The local variable length. * @param localVariable An array containing the types of the current local variables. * @param stackSize The size of the operand stack. * @param stack An array containing the types of the current operand stack. */ protected void translateFrame(MethodVisitor methodVisitor, TranslationMode translationMode, MethodDescription.InDefinedShape methodDescription, TypeList additionalTypes, int frameType, int localVariableLength, Object[] localVariable, int stackSize, Object[] stack) { switch (frameType) { case Opcodes.F_SAME: case Opcodes.F_SAME1: break; case Opcodes.F_APPEND: currentFrameDivergence += localVariableLength; break; case Opcodes.F_CHOP: currentFrameDivergence -= localVariableLength; break; case Opcodes.F_FULL: case Opcodes.F_NEW: Object[] translated = new Object[localVariableLength - methodDescription.getParameters().size() - (methodDescription.isStatic() ? 0 : 1) + instrumentedMethod.getParameters().size() + (instrumentedMethod.isStatic() ? 0 : 1) + additionalTypes.size()]; int index = translationMode.copy(instrumentedMethod, methodDescription, localVariable, translated); for (TypeDescription typeDescription : additionalTypes) { translated[index++] = toFrame(typeDescription); } System.arraycopy(localVariable, methodDescription.getParameters().size() + (methodDescription.isStatic() ? 0 : 1), translated, index, translated.length - index); localVariableLength = translated.length; localVariable = translated; currentFrameDivergence = translated.length - index; break; default: throw new IllegalArgumentException("Unexpected frame frameType: " + frameType); } methodVisitor.visitFrame(frameType, localVariableLength, localVariable, stackSize, stack); } @Override public void injectReturnFrame(MethodVisitor methodVisitor) { if (!expandFrames && currentFrameDivergence == 0 && !instrumentedMethod.isConstructor()) { if (instrumentedMethod.getReturnType().represents(void.class)) { methodVisitor.visitFrame(Opcodes.F_SAME, 0, EMPTY, 0, EMPTY); } else { methodVisitor.visitFrame(Opcodes.F_SAME1, 0, EMPTY, 1, new Object[]{toFrame(instrumentedMethod.getReturnType().asErasure())}); } } else { injectFullFrame(methodVisitor, requiredTypes, instrumentedMethod.getReturnType().represents(void.class) ? Collections.<TypeDescription>emptyList() : Collections.singletonList(instrumentedMethod.getReturnType().asErasure())); } } @Override public void injectExceptionFrame(MethodVisitor methodVisitor) { if (!expandFrames && currentFrameDivergence == 0) { methodVisitor.visitFrame(Opcodes.F_SAME1, 0, EMPTY, 1, new Object[]{Type.getInternalName(Throwable.class)}); } else { injectFullFrame(methodVisitor, requiredTypes, Collections.singletonList(TypeDescription.THROWABLE)); } } @Override public void injectCompletionFrame(MethodVisitor methodVisitor, boolean secondary) { if (!expandFrames && currentFrameDivergence == 0 && (secondary || !instrumentedMethod.isConstructor())) { if (secondary) { methodVisitor.visitFrame(Opcodes.F_SAME, 0, EMPTY, 0, EMPTY); } else { Object[] local = new Object[yieldedTypes.size()]; int index = 0; for (TypeDescription typeDescription : yieldedTypes) { local[index++] = toFrame(typeDescription); } methodVisitor.visitFrame(Opcodes.F_APPEND, local.length, local, 0, EMPTY); } } else { injectFullFrame(methodVisitor, CompoundList.of(requiredTypes, yieldedTypes), Collections.<TypeDescription>emptyList()); } } /** * Injects a full stack map frame. * * @param methodVisitor The method visitor onto which to write the stack map frame. * @param typesInArray The types that were added to the local variable array additionally to the values of the instrumented method. * @param typesOnStack The types currently on the operand stack. */ protected void injectFullFrame(MethodVisitor methodVisitor, List<? extends TypeDescription> typesInArray, List<? extends TypeDescription> typesOnStack) { Object[] localVariable = new Object[instrumentedMethod.getParameters().size() + (instrumentedMethod.isStatic() ? 0 : 1) + typesInArray.size()]; int index = 0; if (!instrumentedMethod.isStatic()) { localVariable[index++] = toFrame(instrumentedMethod.getDeclaringType()); } for (TypeDescription typeDescription : instrumentedMethod.getParameters().asTypeList().asErasures()) { localVariable[index++] = toFrame(typeDescription); } for (TypeDescription typeDescription : typesInArray) { localVariable[index++] = toFrame(typeDescription); } index = 0; Object[] stackType = new Object[typesOnStack.size()]; for (TypeDescription typeDescription : typesOnStack) { stackType[index++] = toFrame(typeDescription); } methodVisitor.visitFrame(expandFrames ? Opcodes.F_NEW : Opcodes.F_FULL, localVariable.length, localVariable, stackType.length, stackType); currentFrameDivergence = 0; } @Override public String toString() { return "Advice.StackMapFrameHandler.Default{" + "instrumentedMethod=" + instrumentedMethod + ", requiredTypes=" + requiredTypes + ", yieldedTypes=" + yieldedTypes + ", expandFrames=" + expandFrames + ", currentFrameDivergence=" + currentFrameDivergence + '}'; } /** * A translation mode that determines how the fixed frames of the instrumented method are written. */ protected enum TranslationMode { /** * A translation mode that simply copies the original frames which are available when translating frames of the instrumented method. */ COPY { @Override protected int copy(MethodDescription.InDefinedShape instrumentedMethod, MethodDescription.InDefinedShape methodDescription, Object[] localVariable, Object[] translated) { int length = instrumentedMethod.getParameters().size() + (instrumentedMethod.isStatic() ? 0 : 1); System.arraycopy(localVariable, 0, translated, 0, length); return length; } }, /** * A translation mode for the entry advice that considers that the {@code this} reference might not be initialized for a constructor. */ ENTRY { @Override protected int copy(MethodDescription.InDefinedShape instrumentedMethod, MethodDescription.InDefinedShape methodDescription, Object[] localVariable, Object[] translated) { int index = 0; if (!instrumentedMethod.isStatic()) { translated[index++] = instrumentedMethod.isConstructor() ? Opcodes.UNINITIALIZED_THIS : toFrame(instrumentedMethod.getDeclaringType()); } for (TypeDescription typeDescription : instrumentedMethod.getParameters().asTypeList().asErasures()) { translated[index++] = toFrame(typeDescription); } return index; } }, /** * A translation mode for an exit advice where the {@code this} reference is always initialized. */ EXIT { @Override protected int copy(MethodDescription.InDefinedShape instrumentedMethod, MethodDescription.InDefinedShape methodDescription, Object[] localVariable, Object[] translated) { int index = 0; if (!instrumentedMethod.isStatic()) { translated[index++] = toFrame(instrumentedMethod.getDeclaringType()); } for (TypeDescription typeDescription : instrumentedMethod.getParameters().asTypeList().asErasures()) { translated[index++] = toFrame(typeDescription); } return index; } }; /** * Copies the fixed parameters of the instrumented method onto the operand stack. * * @param instrumentedMethod The instrumented method. * @param methodDescription The method for which a frame is created. * @param localVariable The original local variable array. * @param translated The array containing the translated frames. * @return The amount of frames added to the translated frame array. */ protected abstract int copy(MethodDescription.InDefinedShape instrumentedMethod, MethodDescription.InDefinedShape methodDescription, Object[] localVariable, Object[] translated); @Override public String toString() { return "Advice.StackMapFrameHandler.Default.TranslationMode." + name(); } } /** * A stack map frame handler for an advice method. */ protected class ForAdvice implements StackMapFrameHandler.ForAdvice { /** * The method description for which frames are translated. */ protected final MethodDescription.InDefinedShape adviceMethod; /** * A list of intermediate types to be considered as part of the instrumented method's steady signature. */ protected final TypeList requiredTypes; /** * The types that this method yields as a result. */ private final TypeList yieldedTypes; /** * The translation mode to apply for this advice method. Should be either {@link TranslationMode#ENTRY} or {@link TranslationMode#EXIT}. */ protected final TranslationMode translationMode; /** * Creates a new meta data handler for an advice method. * * @param adviceMethod The method description for which frames are translated. * @param requiredTypes A list of expected types to be considered as part of the instrumented method's steady signature. * @param yieldedTypes The types that this method yields as a result. * @param translationMode The translation mode to apply for this advice method. Should be * either {@link TranslationMode#ENTRY} or {@link TranslationMode#EXIT}. */ protected ForAdvice(MethodDescription.InDefinedShape adviceMethod, TypeList requiredTypes, TypeList yieldedTypes, TranslationMode translationMode) { this.adviceMethod = adviceMethod; this.requiredTypes = requiredTypes; this.yieldedTypes = yieldedTypes; this.translationMode = translationMode; } @Override public void translateFrame(MethodVisitor methodVisitor, int type, int localVariableLength, Object[] localVariable, int stackSize, Object[] stack) { Default.this.translateFrame(methodVisitor, translationMode, adviceMethod, requiredTypes, type, localVariableLength, localVariable, stackSize, stack); } @Override public void injectReturnFrame(MethodVisitor methodVisitor) { if (!expandFrames && currentFrameDivergence == 0) { if (yieldedTypes.isEmpty() || adviceMethod.getReturnType().represents(void.class)) { methodVisitor.visitFrame(Opcodes.F_SAME, 0, EMPTY, 0, EMPTY); } else { methodVisitor.visitFrame(Opcodes.F_SAME1, 0, EMPTY, 1, new Object[]{toFrame(adviceMethod.getReturnType().asErasure())}); } } else { injectFullFrame(methodVisitor, requiredTypes, yieldedTypes.isEmpty() || adviceMethod.getReturnType().represents(void.class) ? Collections.<TypeDescription>emptyList() : Collections.singletonList(adviceMethod.getReturnType().asErasure())); } } @Override public void injectExceptionFrame(MethodVisitor methodVisitor) { if (!expandFrames && currentFrameDivergence == 0) { methodVisitor.visitFrame(Opcodes.F_SAME1, 0, EMPTY, 1, new Object[]{Type.getInternalName(Throwable.class)}); } else { injectFullFrame(methodVisitor, requiredTypes, Collections.singletonList(TypeDescription.THROWABLE)); } } @Override public void injectCompletionFrame(MethodVisitor methodVisitor, boolean secondary) { if ((!expandFrames && currentFrameDivergence == 0 && yieldedTypes.size() < 4)) { if (secondary || yieldedTypes.isEmpty()) { methodVisitor.visitFrame(Opcodes.F_SAME, 0, EMPTY, 0, EMPTY); } else { Object[] local = new Object[yieldedTypes.size()]; int index = 0; for (TypeDescription typeDescription : yieldedTypes) { local[index++] = toFrame(typeDescription); } methodVisitor.visitFrame(Opcodes.F_APPEND, local.length, local, 0, EMPTY); } } else { injectFullFrame(methodVisitor, CompoundList.of(requiredTypes, yieldedTypes), Collections.<TypeDescription>emptyList()); } } @Override public String toString() { return "Advice.StackMapFrameHandler.Default.ForAdvice{" + "adviceMethod=" + adviceMethod + ", requiredTypes=" + requiredTypes + ", yieldedTypes=" + yieldedTypes + ", translationMode=" + translationMode + '}'; } } } } /** * A method visitor that weaves the advice methods' byte codes. */ protected abstract static class AdviceVisitor extends ExceptionTableSensitiveMethodVisitor implements Dispatcher.Bound.SkipHandler { /** * Indicates a zero offset. */ private static final int NO_OFFSET = 0; /** * A description of the instrumented method. */ protected final MethodDescription.InDefinedShape instrumentedMethod; /** * The required padding before using local variables after the instrumented method's arguments. */ private final int padding; /** * The dispatcher to be used for method entry. */ private final Dispatcher.Bound.ForMethodEnter methodEnter; /** * The dispatcher to be used for method exit. */ protected final Dispatcher.Bound.ForMethodExit methodExit; /** * A handler for computing the method size requirements. */ protected final MethodSizeHandler methodSizeHandler; /** * A handler for translating and injecting stack map frames. */ protected final StackMapFrameHandler.ForInstrumentedMethod stackMapFrameHandler; /** * Creates a new advice visitor. * * @param methodVisitor The method visitor to which all instructions are written. * @param instrumentedMethod The instrumented method. * @param methodEnter The method enter advice. * @param methodExit The method exit advice. * @param yieldedTypes The types that are expected to be added after the instrumented method returns. * @param classFileVersion The instrumented type's class file version. * @param writerFlags The ASM writer flags that were set. * @param readerFlags The ASM reader flags that were set. */ protected AdviceVisitor(MethodVisitor methodVisitor, MethodDescription.InDefinedShape instrumentedMethod, Dispatcher.Resolved.ForMethodEnter methodEnter, Dispatcher.Resolved.ForMethodExit methodExit, List<? extends TypeDescription> yieldedTypes, ClassFileVersion classFileVersion, int writerFlags, int readerFlags) { super(Opcodes.ASM5, methodVisitor); this.instrumentedMethod = instrumentedMethod; padding = methodEnter.getEnterType().getStackSize().getSize(); List<TypeDescription> requiredTypes = methodEnter.getEnterType().represents(void.class) ? Collections.<TypeDescription>emptyList() : Collections.singletonList(methodEnter.getEnterType()); methodSizeHandler = MethodSizeHandler.Default.of(instrumentedMethod, requiredTypes, yieldedTypes, writerFlags); stackMapFrameHandler = StackMapFrameHandler.Default.of(instrumentedMethod, requiredTypes, yieldedTypes, classFileVersion, writerFlags, readerFlags); this.methodEnter = methodEnter.bind(instrumentedMethod, methodVisitor, methodSizeHandler, stackMapFrameHandler); this.methodExit = methodExit.bind(instrumentedMethod, methodVisitor, methodSizeHandler, stackMapFrameHandler); } @Override protected void onAfterExceptionTable() { methodEnter.prepare(); onUserPrepare(); methodExit.prepare(); methodEnter.apply(this); onUserStart(); } /** * Invoked when the user method's exception handler (if any) is supposed to be prepared. */ protected abstract void onUserPrepare(); /** * Writes the advice for entering the instrumented method. */ protected abstract void onUserStart(); @Override protected void onVisitVarInsn(int opcode, int offset) { mv.visitVarInsn(opcode, offset < instrumentedMethod.getStackSize() ? offset : padding + offset); } @Override protected void onVisitIincInsn(int offset, int increment) { mv.visitIincInsn(offset < instrumentedMethod.getStackSize() ? offset : padding + offset, increment); } /** * Access the first variable after the instrumented variables and return type are stored. * * @param opcode The opcode for accessing the variable. */ protected void variable(int opcode) { variable(opcode, NO_OFFSET); } /** * Access the first variable after the instrumented variables and return type are stored. * * @param opcode The opcode for accessing the variable. * @param offset The additional offset of the variable. */ protected void variable(int opcode, int offset) { mv.visitVarInsn(opcode, instrumentedMethod.getStackSize() + padding + offset); } @Override public void visitFrame(int frameType, int localVariableLength, Object[] localVariable, int stackSize, Object[] stack) { stackMapFrameHandler.translateFrame(mv, frameType, localVariableLength, localVariable, stackSize, stack); } @Override public void visitMaxs(int stackSize, int localVariableLength) { onUserEnd(); mv.visitMaxs(methodSizeHandler.compoundStackSize(stackSize), methodSizeHandler.compoundLocalVariableLength(localVariableLength)); } /** * Writes the advice for completing the instrumented method. */ protected abstract void onUserEnd(); /** * An advice visitor that does not apply exit advice. */ protected static class WithoutExitAdvice extends AdviceVisitor { /** * Creates an advice visitor that does not apply exit advice. * * @param methodVisitor The method visitor for the instrumented method. * @param instrumentedMethod A description of the instrumented method. * @param methodEnter The dispatcher to be used for method entry. * @param classFileVersion The instrumented type's class file version. * @param writerFlags The ASM writer flags that were set. * @param readerFlags The ASM reader flags that were set. */ protected WithoutExitAdvice(MethodVisitor methodVisitor, MethodDescription.InDefinedShape instrumentedMethod, Dispatcher.Resolved.ForMethodEnter methodEnter, ClassFileVersion classFileVersion, int writerFlags, int readerFlags) { super(methodVisitor, instrumentedMethod, methodEnter, Dispatcher.Inactive.INSTANCE, Collections.<TypeDescription>emptyList(), classFileVersion, writerFlags, readerFlags); } @Override protected void onUserPrepare() { /* do nothing */ } @Override protected void onUserStart() { /* do nothing */ } @Override protected void onUserEnd() { /* do nothing */ } @Override public void apply(MethodVisitor methodVisitor) { if (instrumentedMethod.getReturnType().represents(boolean.class) || instrumentedMethod.getReturnType().represents(byte.class) || instrumentedMethod.getReturnType().represents(short.class) || instrumentedMethod.getReturnType().represents(char.class) || instrumentedMethod.getReturnType().represents(int.class)) { mv.visitInsn(Opcodes.ICONST_0); methodVisitor.visitInsn(Opcodes.IRETURN); } else if (instrumentedMethod.getReturnType().represents(long.class)) { mv.visitInsn(Opcodes.LCONST_0); methodVisitor.visitInsn(Opcodes.LRETURN); } else if (instrumentedMethod.getReturnType().represents(float.class)) { mv.visitInsn(Opcodes.FCONST_0); methodVisitor.visitInsn(Opcodes.FRETURN); } else if (instrumentedMethod.getReturnType().represents(double.class)) { mv.visitInsn(Opcodes.DCONST_0); methodVisitor.visitInsn(Opcodes.DRETURN); } else if (instrumentedMethod.getReturnType().represents(void.class)) { methodVisitor.visitInsn(Opcodes.RETURN); } else { mv.visitInsn(Opcodes.ACONST_NULL); methodVisitor.visitInsn(Opcodes.ARETURN); } } @Override public String toString() { return "Advice.AdviceVisitor.WithoutExitAdvice{" + ", instrumentedMethod=" + instrumentedMethod + "}"; } } /** * An advice visitor that applies exit advice. */ protected abstract static class WithExitAdvice extends AdviceVisitor { /** * Indicates the handler for the value returned by the advice method. */ protected final Label returnHandler; /** * Creates an advice visitor that applies exit advice. * * @param methodVisitor The method visitor for the instrumented method. * @param instrumentedMethod A description of the instrumented method. * @param methodEnter The dispatcher to be used for method entry. * @param methodExit The dispatcher to be used for method exit. * @param yieldedTypes The types that are expected to be added after the instrumented method returns. * @param classFileVersion The instrumented type's class file version. * @param writerFlags The ASM writer flags that were set. * @param readerFlags The ASM reader flags that were set. */ protected WithExitAdvice(MethodVisitor methodVisitor, MethodDescription.InDefinedShape instrumentedMethod, Dispatcher.Resolved.ForMethodEnter methodEnter, Dispatcher.Resolved.ForMethodExit methodExit, List<? extends TypeDescription> yieldedTypes, ClassFileVersion classFileVersion, int writerFlags, int readerFlags) { super(methodVisitor, instrumentedMethod, methodEnter, methodExit, yieldedTypes, classFileVersion, writerFlags, readerFlags); returnHandler = new Label(); } @Override public void apply(MethodVisitor methodVisitor) { if (instrumentedMethod.getReturnType().represents(boolean.class) || instrumentedMethod.getReturnType().represents(byte.class) || instrumentedMethod.getReturnType().represents(short.class) || instrumentedMethod.getReturnType().represents(char.class) || instrumentedMethod.getReturnType().represents(int.class)) { mv.visitInsn(Opcodes.ICONST_0); } else if (instrumentedMethod.getReturnType().represents(long.class)) { mv.visitInsn(Opcodes.LCONST_0); } else if (instrumentedMethod.getReturnType().represents(float.class)) { mv.visitInsn(Opcodes.FCONST_0); } else if (instrumentedMethod.getReturnType().represents(double.class)) { mv.visitInsn(Opcodes.DCONST_0); } else if (!instrumentedMethod.getReturnType().represents(void.class)) { mv.visitInsn(Opcodes.ACONST_NULL); } methodVisitor.visitJumpInsn(Opcodes.GOTO, returnHandler); } @Override protected void onVisitInsn(int opcode) { switch (opcode) { case Opcodes.RETURN: case Opcodes.IRETURN: case Opcodes.FRETURN: case Opcodes.DRETURN: case Opcodes.LRETURN: case Opcodes.ARETURN: mv.visitJumpInsn(Opcodes.GOTO, returnHandler); break; default: mv.visitInsn(opcode); } } @Override protected void onUserEnd() { mv.visitLabel(returnHandler); stackMapFrameHandler.injectReturnFrame(mv); Type returnType = Type.getType(instrumentedMethod.getReturnType().asErasure().getDescriptor()); if (!returnType.equals(Type.VOID_TYPE)) { variable(returnType.getOpcode(Opcodes.ISTORE)); } onUserReturn(); methodExit.apply(); onExitAdviceReturn(); if (returnType.equals(Type.VOID_TYPE)) { mv.visitInsn(Opcodes.RETURN); } else { variable(returnType.getOpcode(Opcodes.ILOAD)); mv.visitInsn(returnType.getOpcode(Opcodes.IRETURN)); } } /** * Invoked after the user method has returned. */ protected abstract void onUserReturn(); /** * Invoked after the exit advice method has returned. */ protected abstract void onExitAdviceReturn(); /** * An advice visitor that does not capture exceptions. */ protected static class WithoutExceptionHandling extends WithExitAdvice { /** * Creates a new advice visitor that does not capture exceptions. * * @param methodVisitor The method visitor for the instrumented method. * @param instrumentedMethod A description of the instrumented method. * @param methodEnter The dispatcher to be used for method entry. * @param methodExit The dispatcher to be used for method exit. * @param classFileVersion The instrumented type's class file version. * @param writerFlags The ASM writer flags that were set. * @param readerFlags The ASM reader flags that were set. */ protected WithoutExceptionHandling(MethodVisitor methodVisitor, MethodDescription.InDefinedShape instrumentedMethod, Dispatcher.Resolved.ForMethodEnter methodEnter, Dispatcher.Resolved.ForMethodExit methodExit, ClassFileVersion classFileVersion, int writerFlags, int readerFlags) { super(methodVisitor, instrumentedMethod, methodEnter, methodExit, instrumentedMethod.getReturnType().represents(void.class) ? Collections.<TypeDescription>emptyList() : Collections.singletonList(instrumentedMethod.getReturnType().asErasure()), classFileVersion, writerFlags, readerFlags); } @Override protected void onUserPrepare() { /* empty */ } @Override protected void onUserStart() { /* empty */ } @Override protected void onUserReturn() { if (!instrumentedMethod.getReturnType().represents(void.class)) { stackMapFrameHandler.injectCompletionFrame(mv, false); } } @Override protected void onExitAdviceReturn() { /* empty */ } @Override public String toString() { return "Advice.AdviceVisitor.WithExitAdvice.WithoutExceptionHandling{" + "instrumentedMethod=" + instrumentedMethod + "}"; } } /** * An advice visitor that captures exceptions by weaving try-catch blocks around user code. */ protected static class WithExceptionHandling extends WithExitAdvice { /** * The type of the handled throwable type for which this advice is invoked. */ private final TypeDescription triggeringThrowable; /** * Indicates the start of the user method. */ private final Label userStart; /** * Indicates the exception handler. */ private final Label exceptionHandler; /** * Creates a new advice visitor that captures exception by weaving try-catch blocks around user code. * * @param methodVisitor The method visitor for the instrumented method. * @param instrumentedMethod A description of the instrumented method. * @param methodEnter The dispatcher to be used for method entry. * @param methodExit The dispatcher to be used for method exit. * @param classFileVersion The instrumented type's class file version. * @param writerFlags The ASM writer flags that were set. * @param readerFlags The ASM reader flags that were set. * @param triggeringThrowable The type of the handled throwable type for which this advice is invoked. */ protected WithExceptionHandling(MethodVisitor methodVisitor, MethodDescription.InDefinedShape instrumentedMethod, Dispatcher.Resolved.ForMethodEnter methodEnter, Dispatcher.Resolved.ForMethodExit methodExit, ClassFileVersion classFileVersion, int writerFlags, int readerFlags, TypeDescription triggeringThrowable) { super(methodVisitor, instrumentedMethod, methodEnter, methodExit, instrumentedMethod.getReturnType().represents(void.class) ? Collections.singletonList(TypeDescription.THROWABLE) : Arrays.asList(instrumentedMethod.getReturnType().asErasure(), TypeDescription.THROWABLE), classFileVersion, writerFlags, readerFlags); this.triggeringThrowable = triggeringThrowable; userStart = new Label(); exceptionHandler = new Label(); } @Override protected void onUserPrepare() { mv.visitTryCatchBlock(userStart, returnHandler, exceptionHandler, triggeringThrowable.getInternalName()); } @Override protected void onUserStart() { mv.visitLabel(userStart); } @Override protected void onUserReturn() { mv.visitInsn(Opcodes.ACONST_NULL); variable(Opcodes.ASTORE, instrumentedMethod.getReturnType().getStackSize().getSize()); Label endOfHandler = new Label(); mv.visitJumpInsn(Opcodes.GOTO, endOfHandler); mv.visitLabel(exceptionHandler); stackMapFrameHandler.injectExceptionFrame(mv); variable(Opcodes.ASTORE, instrumentedMethod.getReturnType().getStackSize().getSize()); storeDefaultReturn(); mv.visitLabel(endOfHandler); stackMapFrameHandler.injectCompletionFrame(mv, false); } @Override protected void onExitAdviceReturn() { variable(Opcodes.ALOAD, instrumentedMethod.getReturnType().getStackSize().getSize()); Label endOfHandler = new Label(); mv.visitJumpInsn(Opcodes.IFNULL, endOfHandler); variable(Opcodes.ALOAD, instrumentedMethod.getReturnType().getStackSize().getSize()); mv.visitInsn(Opcodes.ATHROW); mv.visitLabel(endOfHandler); stackMapFrameHandler.injectCompletionFrame(mv, true); } /** * Stores a default return value in the designated slot of the local variable array. */ private void storeDefaultReturn() { if (instrumentedMethod.getReturnType().represents(boolean.class) || instrumentedMethod.getReturnType().represents(byte.class) || instrumentedMethod.getReturnType().represents(short.class) || instrumentedMethod.getReturnType().represents(char.class) || instrumentedMethod.getReturnType().represents(int.class)) { mv.visitInsn(Opcodes.ICONST_0); variable(Opcodes.ISTORE); } else if (instrumentedMethod.getReturnType().represents(long.class)) { mv.visitInsn(Opcodes.LCONST_0); variable(Opcodes.LSTORE); } else if (instrumentedMethod.getReturnType().represents(float.class)) { mv.visitInsn(Opcodes.FCONST_0); variable(Opcodes.FSTORE); } else if (instrumentedMethod.getReturnType().represents(double.class)) { mv.visitInsn(Opcodes.DCONST_0); variable(Opcodes.DSTORE); } else if (!instrumentedMethod.getReturnType().represents(void.class)) { mv.visitInsn(Opcodes.ACONST_NULL); variable(Opcodes.ASTORE); } } @Override public String toString() { return "Advice.AdviceVisitor.WithExitAdvice.WithExceptionHandling{" + "instrumentedMethod=" + instrumentedMethod + ", triggeringThrowable=" + triggeringThrowable + "}"; } } } } /** * A dispatcher for implementing advice. */ protected interface Dispatcher { /** * Indicates that a method does not represent advice and does not need to be visited. */ MethodVisitor IGNORE_METHOD = null; /** * Expresses that an annotation should not be visited. */ AnnotationVisitor IGNORE_ANNOTATION = null; /** * Returns {@code true} if this dispatcher is alive. * * @return {@code true} if this dispatcher is alive. */ boolean isAlive(); /** * A dispatcher that is not yet resolved. */ interface Unresolved extends Dispatcher { /** * Indicates that this dispatcher requires access to the class file declaring the advice method. * * @return {@code true} if this dispatcher requires access to the advice method's class file. */ boolean isBinary(); /** * Resolves this dispatcher as a dispatcher for entering a method. * * @param userFactories A list of custom factories for binding parameters of an advice method. * @param classReader A class reader to query for a class file which might be {@code null} if this dispatcher is not binary. * @return This dispatcher as a dispatcher for entering a method. */ Resolved.ForMethodEnter asMethodEnter(List<? extends OffsetMapping.Factory> userFactories, ClassReader classReader); /** * Resolves this dispatcher as a dispatcher for exiting a method. * * @param userFactories A list of custom factories for binding parameters of an advice method. * @param classReader A class reader to query for a class file which might be {@code null} if this dispatcher is not binary. * @param dispatcher The dispatcher for entering a method. * @return This dispatcher as a dispatcher for exiting a method. */ Resolved.ForMethodExit asMethodExitTo(List<? extends OffsetMapping.Factory> userFactories, ClassReader classReader, Resolved.ForMethodEnter dispatcher); } /** * Represents an offset mapping for an advice method to an alternative offset. */ interface OffsetMapping { /** * Resolves an offset mapping to a given target offset. * * @param instrumentedMethod The instrumented method for which the mapping is to be resolved. * @param context The context in which the offset mapping is applied. * @return A suitable target mapping. */ Target resolve(MethodDescription.InDefinedShape instrumentedMethod, Context context); /** * A context for applying an {@link OffsetMapping}. */ interface Context { /** * Returns {@code true} if the advice is applied on a fully initialized instance, i.e. describes if the {@code this} * instance is available or still uninitialized during calling the advice. * * @return {@code true} if the advice is applied onto a fully initialized method. */ boolean isInitialized(); /** * Returns the padding before writing additional values that this context applies. * * @return The required padding for this context. */ int getPadding(); /** * A context for an offset mapping describing a method entry. */ enum ForMethodEntry implements Context { /** * Describes a context for a method entry that is not a constructor. */ INITIALIZED(true), /** * Describes a context for a method entry that is a constructor. */ NON_INITIALIZED(false); /** * Resolves an appropriate method entry context for the supplied instrumented method. * * @param instrumentedMethod The instrumented method. * @return An appropriate context. */ protected static Context of(MethodDescription.InDefinedShape instrumentedMethod) { return instrumentedMethod.isConstructor() ? NON_INITIALIZED : INITIALIZED; } /** * {@code true} if the method is no constructor, i.e. is invoked for an initialized instance upon entry. */ private final boolean initialized; /** * Creates a new context for a method entry. * * @param initialized {@code true} if the method is no constructor, i.e. is invoked for an initialized instance upon entry. */ ForMethodEntry(boolean initialized) { this.initialized = initialized; } @Override public boolean isInitialized() { return initialized; } @Override public int getPadding() { return StackSize.ZERO.getSize(); } @Override public String toString() { return "Advice.Dispatcher.OffsetMapping.Context.ForMethodEntry." + name(); } } /** * A context for an offset mapping describing a method exit. */ enum ForMethodExit implements Context { /** * A method exit with a zero sized padding. */ ZERO(StackSize.ZERO), /** * A method exit with a single slot padding. */ SINGLE(StackSize.SINGLE), /** * A method exit with a double slot padding. */ DOUBLE(StackSize.DOUBLE); /** * The padding implied by this method exit. */ private final StackSize stackSize; /** * Creates a new context for a method exit. * * @param stackSize The padding implied by this method exit. */ ForMethodExit(StackSize stackSize) { this.stackSize = stackSize; } /** * Resolves an appropriate method exit context for the supplied entry method type. * * @param typeDescription The type that is returned by the enter method. * @return An appropriate context for the supplied entry method type. */ protected static Context of(TypeDescription typeDescription) { switch (typeDescription.getStackSize()) { case ZERO: return ZERO; case SINGLE: return SINGLE; case DOUBLE: return DOUBLE; default: throw new IllegalStateException("Unknown stack size: " + typeDescription); } } @Override public boolean isInitialized() { return true; } @Override public int getPadding() { return stackSize.getSize(); } @Override public String toString() { return "Advice.Dispatcher.OffsetMapping.Context.ForMethodExit." + name(); } } } /** * A target offset of an offset mapping. */ interface Target { /** * Indicates that applying this target does not require any additional padding. */ int NO_PADDING = 0; /** * Applies this offset mapping for a {@link MethodVisitor#visitVarInsn(int, int)} instruction. * * @param methodVisitor The method visitor onto which this offset mapping is to be applied. * @param opcode The opcode of the original instruction. * @return The required padding to the advice's total stack size. */ int resolveAccess(MethodVisitor methodVisitor, int opcode); /** * Applies this offset mapping for a {@link MethodVisitor#visitIincInsn(int, int)} instruction. * * @param methodVisitor The method visitor onto which this offset mapping is to be applied. * @param increment The value with which to increment the targeted value. * @return The required padding to the advice's total stack size. */ int resolveIncrement(MethodVisitor methodVisitor, int increment); /** * Loads a default value onto the stack or pops the accessed value off it. */ enum ForDefaultValue implements Target { /** * The singleton instance. */ INSTANCE; @Override public int resolveAccess(MethodVisitor methodVisitor, int opcode) { switch (opcode) { case Opcodes.ALOAD: methodVisitor.visitInsn(Opcodes.ACONST_NULL); break; case Opcodes.ILOAD: methodVisitor.visitInsn(Opcodes.ICONST_0); break; case Opcodes.LLOAD: methodVisitor.visitInsn(Opcodes.LCONST_0); break; case Opcodes.FLOAD: methodVisitor.visitInsn(Opcodes.FCONST_0); break; case Opcodes.DLOAD: methodVisitor.visitInsn(Opcodes.DCONST_0); break; case Opcodes.ISTORE: case Opcodes.FSTORE: case Opcodes.ASTORE: methodVisitor.visitInsn(Opcodes.POP); break; case Opcodes.LSTORE: case Opcodes.DSTORE: methodVisitor.visitInsn(Opcodes.POP2); break; default: throw new IllegalStateException("Unexpected opcode: " + opcode); } return NO_PADDING; } @Override public int resolveIncrement(MethodVisitor methodVisitor, int increment) { return NO_PADDING; } @Override public String toString() { return "Advice.Dispatcher.OffsetMapping.Target.ForDefaultValue." + name(); } } /** * A read-only target mapping. */ abstract class ForParameter implements Target { /** * The mapped offset. */ protected final int offset; /** * Creates a new read-only target mapping. * * @param offset The mapped offset. */ protected ForParameter(int offset) { this.offset = offset; } @Override public int resolveAccess(MethodVisitor methodVisitor, int opcode) { switch (opcode) { case Opcodes.ISTORE: case Opcodes.LSTORE: case Opcodes.FSTORE: case Opcodes.DSTORE: case Opcodes.ASTORE: onWrite(methodVisitor, opcode); break; case Opcodes.ILOAD: case Opcodes.LLOAD: case Opcodes.FLOAD: case Opcodes.DLOAD: case Opcodes.ALOAD: methodVisitor.visitVarInsn(opcode, offset); break; default: throw new IllegalArgumentException("Did not expect opcode: " + opcode); } return NO_PADDING; } /** * Invoked upon attempting to write to a parameter. * * @param methodVisitor The method visitor onto which this offset mapping is to be applied. * @param opcode The applied opcode. */ protected abstract void onWrite(MethodVisitor methodVisitor, int opcode); @Override public boolean equals(Object object) { if (this == object) return true; if (object == null || getClass() != object.getClass()) return false; ForParameter forParameter = (ForParameter) object; return offset == forParameter.offset; } @Override public int hashCode() { return offset; } /** * A read-only parameter mapping. */ protected static class ReadOnly extends ForParameter { /** * Creates a new parameter mapping that is only readable. * * @param offset The mapped offset. */ protected ReadOnly(int offset) { super(offset); } @Override protected void onWrite(MethodVisitor methodVisitor, int opcode) { throw new IllegalStateException("Cannot write to read-only value"); } @Override public int resolveIncrement(MethodVisitor methodVisitor, int increment) { throw new IllegalStateException("Cannot write to read-only parameter at offset " + offset); } @Override public String toString() { return "Advice.Dispatcher.OffsetMapping.Target.ForParameter.ReadOnly{" + "offset=" + offset + "}"; } } /** * A parameter mapping that is both readable and writable. */ protected static class ReadWrite extends ForParameter { /** * Creates a new parameter mapping that is both readable and writable. * * @param offset The mapped offset. */ protected ReadWrite(int offset) { super(offset); } @Override protected void onWrite(MethodVisitor methodVisitor, int opcode) { methodVisitor.visitVarInsn(opcode, offset); } /** * Resolves a parameter mapping where the value is casted to the given type prior to assignment. * * @param targetType The type to which the target value is cased. * @return An appropriate target mapping. */ protected Target casted(TypeDescription targetType) { return targetType.represents(Object.class) ? this : new WithCasting(offset, targetType); } @Override public int resolveIncrement(MethodVisitor methodVisitor, int increment) { methodVisitor.visitIincInsn(offset, increment); return NO_PADDING; } @Override public String toString() { return "Advice.Dispatcher.OffsetMapping.Target.ForParameter.ReadWrite{" + "offset=" + offset + "}"; } /** * A readable and writable parameter mapping where the assigned value is casted to another type prior to assignment. */ protected static class WithCasting extends ReadWrite { /** * The type to which the written value is casted prior to assignment. */ private final TypeDescription targetType; /** * Creates a new parameter mapping with casting prior to assignment. * * @param offset The mapped offset. * @param targetType The type to which the written value is casted prior to assignment. */ protected WithCasting(int offset, TypeDescription targetType) { super(offset); this.targetType = targetType; } @Override protected void onWrite(MethodVisitor methodVisitor, int opcode) { methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, targetType.getInternalName()); super.onWrite(methodVisitor, opcode); } @Override public boolean equals(Object object) { if (this == object) return true; if (object == null || getClass() != object.getClass()) return false; if (!super.equals(object)) return false; WithCasting that = (WithCasting) object; return targetType.equals(that.targetType); } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + targetType.hashCode(); return result; } @Override public String toString() { return "Advice.Dispatcher.OffsetMapping.Target.ForParameter.ReadWrite.WithCasting{" + "offset=" + offset + ", targetType=" + targetType + "}"; } } } } /** * An offset mapping for a field. */ abstract class ForField implements Target { /** * The field being read. */ protected final FieldDescription.InDefinedShape fieldDescription; /** * Creates a new offset mapping for a field. * * @param fieldDescription The field being read. */ protected ForField(FieldDescription.InDefinedShape fieldDescription) { this.fieldDescription = fieldDescription; } @Override public int resolveAccess(MethodVisitor methodVisitor, int opcode) { switch (opcode) { case Opcodes.ISTORE: case Opcodes.ASTORE: case Opcodes.FSTORE: return onWriteSingle(methodVisitor); case Opcodes.LSTORE: case Opcodes.DSTORE: return onWriteDouble(methodVisitor); case Opcodes.ILOAD: case Opcodes.FLOAD: case Opcodes.ALOAD: case Opcodes.LLOAD: case Opcodes.DLOAD: if (fieldDescription.isStatic()) { accessField(methodVisitor, Opcodes.GETSTATIC); } else { methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); accessField(methodVisitor, Opcodes.GETFIELD); } return NO_PADDING; default: throw new IllegalArgumentException("Did not expect opcode: " + opcode); } } /** * Writes a value to a field which type occupies a single slot on the operand stack. * * @param methodVisitor The method visitor onto which this offset mapping is to be applied. * @return The required padding to the advice's total stack size. */ protected abstract int onWriteSingle(MethodVisitor methodVisitor); /** * Writes a value to a field which type occupies two slots on the operand stack. * * @param methodVisitor The method visitor onto which this offset mapping is to be applied. * @return The required padding to the advice's total stack size. */ protected abstract int onWriteDouble(MethodVisitor methodVisitor); /** * Accesses a field. * * @param methodVisitor The method visitor for which to access the field. * @param opcode The opcode for accessing the field. */ protected void accessField(MethodVisitor methodVisitor, int opcode) { methodVisitor.visitFieldInsn(opcode, fieldDescription.getDeclaringType().asErasure().getInternalName(), fieldDescription.getInternalName(), fieldDescription.getDescriptor()); } @Override public boolean equals(Object object) { if (this == object) return true; if (object == null || getClass() != object.getClass()) return false; ForField forField = (ForField) object; return fieldDescription.equals(forField.fieldDescription); } @Override public int hashCode() { return fieldDescription.hashCode(); } /** * A target mapping for a field that is only readable. */ protected static class ReadOnly extends ForField { /** * Creates a new field mapping for a field that is only readable. * * @param fieldDescription The field which is mapped by this target mapping. */ protected ReadOnly(FieldDescription.InDefinedShape fieldDescription) { super(fieldDescription); } @Override protected int onWriteSingle(MethodVisitor methodVisitor) { throw new IllegalStateException("Cannot write to read-only field " + fieldDescription); } @Override protected int onWriteDouble(MethodVisitor methodVisitor) { throw new IllegalStateException("Cannot write to read-only field " + fieldDescription); } @Override public int resolveIncrement(MethodVisitor methodVisitor, int increment) { throw new IllegalStateException("Cannot write to read-only field " + fieldDescription); } @Override public String toString() { return "Advice.Dispatcher.OffsetMapping.Target.ForField.ReadOnly{" + "fieldDescription=" + fieldDescription + "}"; } } /** * A target mapping for a field that is both readable and writable. */ protected static class ReadWrite extends ForField { /** * Creates a new field mapping for a field that is readable and writable. * * @param fieldDescription The field which is mapped by this target mapping. */ protected ReadWrite(FieldDescription.InDefinedShape fieldDescription) { super(fieldDescription); } @Override protected int onWriteSingle(MethodVisitor methodVisitor) { if (!fieldDescription.isStatic()) { methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitInsn(Opcodes.DUP_X1); methodVisitor.visitInsn(Opcodes.POP); accessField(methodVisitor, Opcodes.PUTFIELD); return 2; } else { accessField(methodVisitor, Opcodes.PUTSTATIC); return NO_PADDING; } } @Override protected int onWriteDouble(MethodVisitor methodVisitor) { if (!fieldDescription.isStatic()) { methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitInsn(Opcodes.DUP_X2); methodVisitor.visitInsn(Opcodes.POP); accessField(methodVisitor, Opcodes.PUTFIELD); return 2; } else { accessField(methodVisitor, Opcodes.PUTSTATIC); return NO_PADDING; } } @Override public int resolveIncrement(MethodVisitor methodVisitor, int increment) { if (fieldDescription.isStatic()) { accessField(methodVisitor, Opcodes.GETSTATIC); methodVisitor.visitInsn(Opcodes.ICONST_1); methodVisitor.visitInsn(Opcodes.IADD); accessField(methodVisitor, Opcodes.PUTSTATIC); return NO_PADDING; } else { methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitInsn(Opcodes.DUP); accessField(methodVisitor, Opcodes.GETFIELD); methodVisitor.visitInsn(Opcodes.ICONST_1); methodVisitor.visitInsn(Opcodes.IADD); accessField(methodVisitor, Opcodes.PUTFIELD); return 2; } } @Override public String toString() { return "Advice.Dispatcher.OffsetMapping.Target.ForField.ReadWrite{" + "fieldDescription=" + fieldDescription + "}"; } } } /** * An offset mapping for a constant pool value. */ class ForConstantPoolValue implements Target { /** * The constant pool value. */ private final Object value; /** * Creates a mapping for a constant pool value. * * @param value The constant pool value. */ protected ForConstantPoolValue(Object value) { this.value = value; } @Override public int resolveAccess(MethodVisitor methodVisitor, int opcode) { switch (opcode) { case Opcodes.ISTORE: case Opcodes.ASTORE: case Opcodes.FSTORE: case Opcodes.LSTORE: case Opcodes.DSTORE: throw new IllegalStateException("Cannot write to fixed value: " + value); case Opcodes.ILOAD: case Opcodes.FLOAD: case Opcodes.ALOAD: case Opcodes.LLOAD: case Opcodes.DLOAD: methodVisitor.visitLdcInsn(value); return NO_PADDING; default: throw new IllegalArgumentException("Did not expect opcode: " + opcode); } } @Override public int resolveIncrement(MethodVisitor methodVisitor, int increment) { throw new IllegalStateException("Cannot write to fixed value: " + value); } @Override public boolean equals(Object object) { if (this == object) return true; if (object == null || getClass() != object.getClass()) return false; ForConstantPoolValue that = (ForConstantPoolValue) object; return value.equals(that.value); } @Override public int hashCode() { return value.hashCode(); } @Override public String toString() { return "Advice.Dispatcher.OffsetMapping.Target.ForConstantPoolValue{" + "value=" + value + '}'; } } /** * A target for an offset mapping that boxes a primitive parameter value. */ abstract class ForBoxedParameter implements Target { /** * The parameters offset. */ protected final int offset; /** * A dispatcher for boxing the primitive value. */ protected final BoxingDispatcher boxingDispatcher; /** * Creates a new offset mapping for boxing a primitive parameter value. * * @param offset The parameters offset. * @param boxingDispatcher A dispatcher for boxing the primitive value. */ protected ForBoxedParameter(int offset, BoxingDispatcher boxingDispatcher) { this.offset = offset; this.boxingDispatcher = boxingDispatcher; } @Override public int resolveAccess(MethodVisitor methodVisitor, int opcode) { switch (opcode) { case Opcodes.ALOAD: boxingDispatcher.loadBoxed(methodVisitor, offset); return boxingDispatcher.getStackSize().getSize() - 1; case Opcodes.ASTORE: onStore(methodVisitor); return NO_PADDING; default: throw new IllegalStateException("Unexpected opcode: " + opcode); } } /** * Handles writing the boxed value if applicable. * * @param methodVisitor The method visitor for which to apply the writing. */ protected abstract void onStore(MethodVisitor methodVisitor); @Override public int resolveIncrement(MethodVisitor methodVisitor, int increment) { throw new IllegalStateException("Cannot increment a boxed parameter"); } @Override public boolean equals(Object object) { if (this == object) return true; if (object == null || getClass() != object.getClass()) return false; ForBoxedParameter that = (ForBoxedParameter) object; return offset == that.offset && boxingDispatcher == that.boxingDispatcher; } @Override public int hashCode() { int result = offset; result = 31 * result + boxingDispatcher.hashCode(); return result; } /** * A target mapping for a boxed parameter that only allows reading the boxed value. */ protected static class ReadOnly extends ForBoxedParameter { /** * Creates a new read-only target offset mapping for a boxed parameter. * * @param offset The parameters offset. * @param boxingDispatcher A dispatcher for boxing the primitive value. */ protected ReadOnly(int offset, BoxingDispatcher boxingDispatcher) { super(offset, boxingDispatcher); } /** * Creates an appropriate target mapping. * * @param offset The parameters offset. * @param type The primitive type that is boxed or unboxed. * @return An appropriate target mapping. */ protected static Target of(int offset, TypeDefinition type) { return new ReadOnly(offset, BoxingDispatcher.of(type)); } @Override protected void onStore(MethodVisitor methodVisitor) { throw new IllegalStateException("Cannot write to read-only boxed parameter"); } @Override public String toString() { return "Advice.Dispatcher.OffsetMapping.Target.ForBoxedParameter.ReadOnly{" + "offset=" + offset + ", boxingDispatcher=" + boxingDispatcher + '}'; } } /** * A target mapping for a boxed parameter that allows reading and writing the boxed value. */ protected static class ReadWrite extends ForBoxedParameter { /** * Creates a new read-write target offset mapping for a boxed parameter. * * @param offset The parameters offset. * @param boxingDispatcher A dispatcher for boxing the primitive value. */ protected ReadWrite(int offset, BoxingDispatcher boxingDispatcher) { super(offset, boxingDispatcher); } /** * Creates an appropriate target mapping. * * @param offset The parameters offset. * @param type The primitive type that is boxed or unboxed. * @return An appropriate target mapping. */ protected static Target of(int offset, TypeDefinition type) { return new ReadWrite(offset, BoxingDispatcher.of(type)); } @Override protected void onStore(MethodVisitor methodVisitor) { boxingDispatcher.storeUnboxed(methodVisitor, offset); } @Override public String toString() { return "Advice.Dispatcher.OffsetMapping.Target.ForBoxedParameter.ReadWrite{" + "offset=" + offset + ", boxingDispatcher=" + boxingDispatcher + '}'; } } /** * A dispatcher for boxing a primitive value. */ protected enum BoxingDispatcher { /** * A boxing dispatcher for the {@code boolean} type. */ BOOLEAN(Opcodes.ILOAD, Opcodes.ISTORE, Boolean.class, boolean.class, "booleanValue"), /** * A boxing dispatcher for the {@code byte} type. */ BYTE(Opcodes.ILOAD, Opcodes.ISTORE, Byte.class, byte.class, "byteValue"), /** * A boxing dispatcher for the {@code short} type. */ SHORT(Opcodes.ILOAD, Opcodes.ISTORE, Short.class, short.class, "shortValue"), /** * A boxing dispatcher for the {@code char} type. */ CHARACTER(Opcodes.ILOAD, Opcodes.ISTORE, Character.class, char.class, "charValue"), /** * A boxing dispatcher for the {@code int} type. */ INTEGER(Opcodes.ILOAD, Opcodes.ISTORE, Integer.class, int.class, "intValue"), /** * A boxing dispatcher for the {@code long} type. */ LONG(Opcodes.LLOAD, Opcodes.LSTORE, Long.class, long.class, "longValue"), /** * A boxing dispatcher for the {@code float} type. */ FLOAT(Opcodes.FLOAD, Opcodes.FSTORE, Float.class, float.class, "floatValue"), /** * A boxing dispatcher for the {@code double} type. */ DOUBLE(Opcodes.DLOAD, Opcodes.DSTORE, Double.class, double.class, "doubleValue"); /** * The name of the boxing method of a wrapper type. */ private static final String VALUE_OF = "valueOf"; /** * The opcode to use for loading a value of this type. */ private final int load; /** * The opcode to use for loading a value of this type. */ private final int store; /** * The name of the method used for unboxing a primitive type. */ private final String unboxingMethod; /** * The name of the wrapper type. */ private final String owner; /** * The descriptor of the boxing method. */ private final String boxingDescriptor; /** * The descriptor of the unboxing method. */ private final String unboxingDescriptor; /** * The required stack size of the unboxed value. */ private final StackSize stackSize; /** * Creates a new boxing dispatcher. * * @param load The opcode to use for loading a value of this type. * @param store The opcode to use for storing a value of this type. * @param wrapperType The represented wrapper type. * @param primitiveType The represented primitive type. * @param unboxingMethod The name of the method used for unboxing a primitive type. */ BoxingDispatcher(int load, int store, Class<?> wrapperType, Class<?> primitiveType, String unboxingMethod) { this.load = load; this.store = store; this.unboxingMethod = unboxingMethod; owner = Type.getInternalName(wrapperType); boxingDescriptor = Type.getMethodDescriptor(Type.getType(wrapperType), Type.getType(primitiveType)); unboxingDescriptor = Type.getMethodDescriptor(Type.getType(primitiveType)); stackSize = StackSize.of(primitiveType); } /** * Resolves a boxing dispatcher for the supplied primitive type. * * @param typeDefinition A description of a primitive type. * @return An appropriate boxing dispatcher. */ protected static BoxingDispatcher of(TypeDefinition typeDefinition) { if (typeDefinition.represents(boolean.class)) { return BOOLEAN; } else if (typeDefinition.represents(byte.class)) { return BYTE; } else if (typeDefinition.represents(short.class)) { return SHORT; } else if (typeDefinition.represents(char.class)) { return CHARACTER; } else if (typeDefinition.represents(int.class)) { return INTEGER; } else if (typeDefinition.represents(long.class)) { return LONG; } else if (typeDefinition.represents(float.class)) { return FLOAT; } else if (typeDefinition.represents(double.class)) { return DOUBLE; } else { throw new IllegalArgumentException("Cannot box: " + typeDefinition); } } /** * Loads the value as a boxed version onto the stack. * * @param methodVisitor the method visitor for which to load the value. * @param offset The offset of the primitive value. */ protected void loadBoxed(MethodVisitor methodVisitor, int offset) { methodVisitor.visitVarInsn(load, offset); methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, owner, VALUE_OF, boxingDescriptor, false); } /** * Stores the value as a unboxed version onto the stack. * * @param methodVisitor the method visitor for which to store the value. * @param offset The offset of the primitive value. */ protected void storeUnboxed(MethodVisitor methodVisitor, int offset) { methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, owner); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, owner, unboxingMethod, unboxingDescriptor, false); methodVisitor.visitVarInsn(store, offset); } /** * Returns the stack size of the primitive value. * * @return The stack size of the primitive value. */ protected StackSize getStackSize() { return stackSize; } @Override public String toString() { return "Advice.Dispatcher.OffsetMapping.Target.ForBoxedParameter.BoxingDispatcher." + name(); } } } /** * A target for an offset mapping of an array containing all (boxed) arguments of the instrumented method. */ class ForBoxedArguments implements Target { /** * The parameters of the instrumented method. */ private final List<ParameterDescription.InDefinedShape> parameters; /** * Creates a mapping for a boxed array containing all arguments of the instrumented method. * * @param parameters The parameters of the instrumented method. */ protected ForBoxedArguments(List<ParameterDescription.InDefinedShape> parameters) { this.parameters = parameters; } @Override public int resolveAccess(MethodVisitor methodVisitor, int opcode) { switch (opcode) { case Opcodes.ALOAD: loadInteger(methodVisitor, parameters.size()); methodVisitor.visitTypeInsn(Opcodes.ANEWARRAY, TypeDescription.OBJECT.getInternalName()); StackSize stackSize = StackSize.ZERO; for (ParameterDescription parameter : parameters) { methodVisitor.visitInsn(Opcodes.DUP); loadInteger(methodVisitor, parameter.getIndex()); if (parameter.getType().isPrimitive()) { ForBoxedParameter.BoxingDispatcher.of(parameter.getType()).loadBoxed(methodVisitor, parameter.getOffset()); } else { methodVisitor.visitVarInsn(Opcodes.ALOAD, parameter.getOffset()); } methodVisitor.visitInsn(Opcodes.AASTORE); stackSize = stackSize.maximum(parameter.getType().getStackSize()); } return stackSize.getSize() + 2; default: throw new IllegalStateException("Unexpected opcode: " + opcode); } } /** * Loads an integer onto the operand stack. * * @param methodVisitor The method visitor for which the integer is loaded. * @param value The integer value to load onto the stack. */ private static void loadInteger(MethodVisitor methodVisitor, int value) { switch (value) { case 0: methodVisitor.visitInsn(Opcodes.ICONST_0); break; case 1: methodVisitor.visitInsn(Opcodes.ICONST_1); break; case 2: methodVisitor.visitInsn(Opcodes.ICONST_2); break; case 3: methodVisitor.visitInsn(Opcodes.ICONST_3); break; case 4: methodVisitor.visitInsn(Opcodes.ICONST_4); break; case 5: methodVisitor.visitInsn(Opcodes.ICONST_5); break; default: if (value < Byte.MAX_VALUE) { methodVisitor.visitIntInsn(Opcodes.BIPUSH, value); } else if (value < Short.MAX_VALUE) { methodVisitor.visitIntInsn(Opcodes.SIPUSH, value); } else { methodVisitor.visitLdcInsn(value); } } } @Override public int resolveIncrement(MethodVisitor methodVisitor, int increment) { throw new IllegalStateException("Cannot increment a boxed argument"); } @Override public boolean equals(Object object) { if (this == object) return true; if (object == null || getClass() != object.getClass()) return false; ForBoxedArguments that = (ForBoxedArguments) object; return parameters.equals(that.parameters); } @Override public int hashCode() { return parameters.hashCode(); } @Override public String toString() { return "Advice.Dispatcher.OffsetMapping.Target.ForBoxedArguments{" + "parameters=" + parameters + '}'; } } /** * Binds a null constant to the target parameter. */ enum ForNullConstant implements Target { /** * A null constant that can only be put onto the stack. */ READ_ONLY { @Override protected void onWrite(MethodVisitor methodVisitor) { throw new IllegalStateException("Cannot write to read-only value"); } }, /** * A null constant that also allows virtual writes where the result is simply popped. */ READ_WRITE { @Override protected void onWrite(MethodVisitor methodVisitor) { methodVisitor.visitInsn(Opcodes.POP); } }; @Override public int resolveAccess(MethodVisitor methodVisitor, int opcode) { switch (opcode) { case Opcodes.ALOAD: methodVisitor.visitInsn(Opcodes.ACONST_NULL); break; case Opcodes.ASTORE: onWrite(methodVisitor); break; default: throw new IllegalStateException("Unexpected opcode: " + opcode); } return NO_PADDING; } /** * Determines the behavior when writing to the target. * * @param methodVisitor The method visitor to which to write the result of the mapping. */ protected abstract void onWrite(MethodVisitor methodVisitor); @Override public int resolveIncrement(MethodVisitor methodVisitor, int increment) { throw new IllegalStateException("Cannot increment a null constant"); } @Override public String toString() { return "Advice.Dispatcher.OffsetMapping.Target.ForNullConstant." + name(); } } /** * Creates a target that represents a value in form of a serialized field. */ class ForSerializedObject implements Target { /** * A charset that does not change the supplied byte array upon encoding or decoding. */ private static final String CHARSET = "ISO-8859-1"; /** * The target type. */ private final TypeDescription target; /** * The serialized form of the supplied form encoded as a string to be stored in the constant pool. */ private final String serialized; /** * Creates a target for an offset mapping that references a serialized value. * * @param target The target type. * @param serialized The serialized form of the supplied form encoded as a string to be stored in the constant pool. */ protected ForSerializedObject(TypeDescription target, String serialized) { this.target = target; this.serialized = serialized; } /** * Resolves a serializable value to a target that reads a value from reconstructing a serializable string representation. * * @param target The target type of the serializable value. * @param value The value that the mapped field should represent. * @return A target for deserializing the supplied value on access. */ protected static Target of(TypeDescription target, Serializable value) { try { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); try { objectOutputStream.writeObject(value); } finally { objectOutputStream.close(); } return new ForSerializedObject(target, byteArrayOutputStream.toString(CHARSET)); } catch (IOException exception) { throw new IllegalStateException("Cannot serialize " + value, exception); } } @Override public int resolveAccess(MethodVisitor methodVisitor, int opcode) { switch (opcode) { case Opcodes.ALOAD: methodVisitor.visitTypeInsn(Opcodes.NEW, Type.getInternalName(ObjectInputStream.class)); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitTypeInsn(Opcodes.NEW, Type.getInternalName(ByteArrayInputStream.class)); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitLdcInsn(serialized); methodVisitor.visitLdcInsn(CHARSET); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(String.class), "getBytes", Type.getMethodType(Type.getType(byte[].class), Type.getType(String.class)).toString(), false); methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(ByteArrayInputStream.class), MethodDescription.CONSTRUCTOR_INTERNAL_NAME, Type.getMethodType(Type.VOID_TYPE, Type.getType(byte[].class)).toString(), false); methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(ObjectInputStream.class), MethodDescription.CONSTRUCTOR_INTERNAL_NAME, Type.getMethodType(Type.VOID_TYPE, Type.getType(InputStream.class)).toString(), false); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(ObjectInputStream.class), "readObject", Type.getMethodType(Type.getType(Object.class)).toString(), false); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, target.getInternalName()); return 5; default: throw new IllegalStateException("Unexpected opcode: " + opcode); } } @Override public int resolveIncrement(MethodVisitor methodVisitor, int increment) { throw new IllegalStateException("Cannot increment serialized object"); } @Override public boolean equals(Object object) { if (this == object) return true; if (object == null || getClass() != object.getClass()) return false; ForSerializedObject that = (ForSerializedObject) object; return target.equals(that.target) && serialized.equals(that.serialized); } @Override public int hashCode() { int result = target.hashCode(); result = 31 * result + serialized.hashCode(); return result; } @Override public String toString() { return "Advice.Dispatcher.OffsetMapping.Target.ForSerializedObject{" + "target=" + target + ", serialized='" + serialized + '\'' + '}'; } } } /** * Represents a factory for creating a {@link OffsetMapping} for a given parameter. */ interface Factory { /** * Indicates that an offset mapping is undefined. */ OffsetMapping UNDEFINED = null; /** * Creates a new offset mapping for the supplied parameter if possible. * * @param parameterDescription The parameter description for which to resolve an offset mapping. * @return A resolved offset mapping or {@code null} if no mapping can be resolved for this parameter. */ OffsetMapping make(ParameterDescription.InDefinedShape parameterDescription); } /** * An offset mapping for a given parameter of the instrumented method. */ class ForParameter implements OffsetMapping { /** * The index of the parameter. */ private final int index; /** * Determines if the parameter is to be treated as read-only. */ private final boolean readOnly; /** * The type expected by the advice method. */ private final TypeDescription targetType; /** * Creates a new offset mapping for a parameter. * * @param argument The annotation for which the mapping is to be created. * @param targetType Determines if the parameter is to be treated as read-only. */ protected ForParameter(Argument argument, TypeDescription targetType) { this(argument.value(), argument.readOnly(), targetType); } /** * Creates a new offset mapping for a parameter of the instrumented method. * * @param index The index of the parameter. * @param readOnly Determines if the parameter is to be treated as read-only. * @param targetType The type expected by the advice method. */ protected ForParameter(int index, boolean readOnly, TypeDescription targetType) { this.index = index; this.readOnly = readOnly; this.targetType = targetType; } @Override public Target resolve(MethodDescription.InDefinedShape instrumentedMethod, Context context) { ParameterList<?> parameters = instrumentedMethod.getParameters(); if (parameters.size() <= index) { throw new IllegalStateException(instrumentedMethod + " does not define an index " + index); } else if (!readOnly && !parameters.get(index).getType().asErasure().equals(targetType)) { throw new IllegalStateException("read-only " + targetType + " is not equal to type of " + parameters.get(index)); } else if (readOnly && !parameters.get(index).getType().asErasure().isAssignableTo(targetType)) { throw new IllegalStateException(targetType + " is not assignable to " + parameters.get(index)); } return readOnly ? new Target.ForParameter.ReadOnly(parameters.get(index).getOffset()) : new Target.ForParameter.ReadWrite(parameters.get(index).getOffset()); } @Override public boolean equals(Object object) { if (this == object) return true; if (object == null || getClass() != object.getClass()) return false; ForParameter that = (ForParameter) object; return index == that.index && readOnly == that.readOnly && targetType.equals(that.targetType); } @Override public int hashCode() { int result = index; result = 31 * result + (readOnly ? 1 : 0); result = 31 * result + targetType.hashCode(); return result; } @Override public String toString() { return "Advice.Dispatcher.OffsetMapping.ForParameter{" + "index=" + index + ", readOnly=" + readOnly + ", targetType=" + targetType + '}'; } /** * A factory for creating a {@link ForParameter} offset mapping. */ protected enum Factory implements OffsetMapping.Factory { /** * A factory that does not allow writing to the mapped parameter. */ READ_ONLY(true), /** * A factory that allows writing to the mapped parameter. */ READ_WRITE(false); /** * {@code true} if the parameter is read-only. */ private final boolean readOnly; /** * Creates a new factory. * * @param readOnly {@code true} if the parameter is read-only. */ Factory(boolean readOnly) { this.readOnly = readOnly; } @Override public OffsetMapping make(ParameterDescription.InDefinedShape parameterDescription) { AnnotationDescription.Loadable<Argument> annotation = parameterDescription.getDeclaredAnnotations().ofType(Argument.class); if (annotation == null) { return UNDEFINED; } else if (readOnly && !annotation.loadSilent().readOnly()) { throw new IllegalStateException("Cannot define writable field access for " + parameterDescription); } else { return new ForParameter(annotation.loadSilent(), parameterDescription.getType().asErasure()); } } @Override public String toString() { return "Advice.Dispatcher.OffsetMapping.ForParameter.Factory." + name(); } } } /** * An offset mapping that provides access to the {@code this} reference of the instrumented method. */ class ForThisReference implements OffsetMapping { /** * The offset of the this reference in a Java method. */ private static final int THIS_REFERENCE = 0; /** * Determines if the parameter is to be treated as read-only. */ private final boolean readOnly; /** * {@code true} if the parameter should be bound to {@code null} if the instrumented method is static. */ private final boolean optional; /** * The type that the advice method expects for the {@code this} reference. */ private final TypeDescription targetType; /** * Creates a new offset mapping for a {@code this} reference. * * @param readOnly Determines if the parameter is to be treated as read-only. * @param optional {@code true} if the parameter should be bound to {@code null} if the instrumented method is static. * @param targetType The type that the advice method expects for the {@code this} reference. */ protected ForThisReference(boolean readOnly, boolean optional, TypeDescription targetType) { this.readOnly = readOnly; this.optional = optional; this.targetType = targetType; } @Override public Target resolve(MethodDescription.InDefinedShape instrumentedMethod, Context context) { if (!readOnly && !instrumentedMethod.getDeclaringType().equals(targetType)) { throw new IllegalStateException("Declaring type of " + instrumentedMethod + " is not equal to read-only " + targetType); } else if (readOnly && !instrumentedMethod.getDeclaringType().isAssignableTo(targetType)) { throw new IllegalStateException("Declaring type of " + instrumentedMethod + " is not assignable to " + targetType); } else if (instrumentedMethod.isStatic() && optional) { return readOnly ? Target.ForNullConstant.READ_ONLY : Target.ForNullConstant.READ_WRITE; } else if (instrumentedMethod.isStatic() && !optional) { throw new IllegalStateException("Cannot map this reference for static method " + instrumentedMethod); } else if (!context.isInitialized()) { throw new IllegalStateException("Cannot access this reference before calling constructor: " + instrumentedMethod); } return readOnly ? new Target.ForParameter.ReadOnly(THIS_REFERENCE) : new Target.ForParameter.ReadWrite(THIS_REFERENCE); } @Override public boolean equals(Object object) { if (this == object) return true; if (object == null || getClass() != object.getClass()) return false; ForThisReference that = (ForThisReference) object; return readOnly == that.readOnly && optional == that.optional && targetType.equals(that.targetType); } @Override public int hashCode() { int result = (readOnly ? 1 : 0); result = 31 * result + (readOnly ? 1 : 0); result = 31 * result + targetType.hashCode(); return result; } @Override public String toString() { return "Advice.Dispatcher.OffsetMapping.ForThisReference{" + "readOnly=" + readOnly + ", optional=" + optional + ", targetType=" + targetType + '}'; } /** * A factory for creating a {@link ForThisReference} offset mapping. */ protected enum Factory implements OffsetMapping.Factory { /** * A factory that does not allow writing to the mapped parameter. */ READ_ONLY(true), /** * A factory that allows writing to the mapped parameter. */ READ_WRITE(false); /** * {@code true} if the parameter is read-only. */ private final boolean readOnly; /** * Creates a new factory. * * @param readOnly {@code true} if the parameter is read-only. */ Factory(boolean readOnly) { this.readOnly = readOnly; } @Override public OffsetMapping make(ParameterDescription.InDefinedShape parameterDescription) { AnnotationDescription.Loadable<This> annotation = parameterDescription.getDeclaredAnnotations().ofType(This.class); if (annotation == null) { return UNDEFINED; } else if (readOnly && !annotation.loadSilent().readOnly()) { throw new IllegalStateException("Cannot write to this reference for " + parameterDescription + " in read-only context"); } else { return new ForThisReference(annotation.loadSilent().readOnly(), annotation.loadSilent().optional(), parameterDescription.getType().asErasure()); } } @Override public String toString() { return "Advice.Dispatcher.OffsetMapping.ForThisReference.Factory." + name(); } } } /** * Maps the declaring type of the instrumented method. */ enum ForInstrumentedType implements OffsetMapping { /** * The singleton instance. */ INSTANCE; @Override public Target resolve(MethodDescription.InDefinedShape instrumentedMethod, Context context) { return new Target.ForConstantPoolValue(Type.getType(instrumentedMethod.getDeclaringType().getDescriptor())); } @Override public String toString() { return "Advice.Dispatcher.OffsetMapping.ForInstrumentedType." + name(); } } /** * An offset mapping for a field. */ abstract class ForField implements OffsetMapping { /** * The {@link FieldValue#value()} method. */ private static final MethodDescription.InDefinedShape VALUE; /** * The {@link FieldValue#declaringType()}} method. */ private static final MethodDescription.InDefinedShape DECLARING_TYPE; /** * The {@link FieldValue#readOnly()}} method. */ private static final MethodDescription.InDefinedShape READ_ONLY; static { MethodList<MethodDescription.InDefinedShape> methods = new TypeDescription.ForLoadedType(FieldValue.class).getDeclaredMethods(); VALUE = methods.filter(named("value")).getOnly(); DECLARING_TYPE = methods.filter(named("declaringType")).getOnly(); READ_ONLY = methods.filter(named("readOnly")).getOnly(); } /** * The name of the field. */ protected final String name; /** * The expected type that the field can be assigned to. */ protected final TypeDescription targetType; /** * {@code true} if this mapping is read-only. */ protected final boolean readOnly; /** * Creates an offset mapping for a field. * * @param name The name of the field. * @param targetType The expected type that the field can be assigned to. * @param readOnly {@code true} if this mapping is read-only. */ protected ForField(String name, TypeDescription targetType, boolean readOnly) { this.name = name; this.targetType = targetType; this.readOnly = readOnly; } @Override public Target resolve(MethodDescription.InDefinedShape instrumentedMethod, Context context) { FieldLocator.Resolution resolution = fieldLocator(instrumentedMethod.getDeclaringType()).locate(name); if (!resolution.isResolved()) { throw new IllegalStateException("Cannot locate field named " + name + " for " + instrumentedMethod); } else if (readOnly && !resolution.getField().asDefined().getType().asErasure().isAssignableTo(targetType)) { throw new IllegalStateException("Cannot assign type of read-only field " + resolution.getField() + " to " + targetType); } else if (!readOnly && !resolution.getField().asDefined().getType().asErasure().equals(targetType)) { throw new IllegalStateException("Type of field " + resolution.getField() + " is not equal to " + targetType); } else if (!resolution.getField().isStatic() && instrumentedMethod.isStatic()) { throw new IllegalStateException("Cannot read non-static field " + resolution.getField() + " from static method " + instrumentedMethod); } else if (!context.isInitialized() && !resolution.getField().isStatic()) { throw new IllegalStateException("Cannot access non-static field before calling constructor: " + instrumentedMethod); } return readOnly ? new Target.ForField.ReadOnly(resolution.getField().asDefined()) : new Target.ForField.ReadWrite(resolution.getField().asDefined()); } @Override public boolean equals(Object object) { if (this == object) return true; if (object == null || getClass() != object.getClass()) return false; ForField forField = (ForField) object; return name.equals(forField.name) && targetType.equals(forField.targetType) && readOnly == forField.readOnly; } @Override public int hashCode() { int result = name.hashCode(); result = 31 * result + targetType.hashCode(); result = 31 * result + (readOnly ? 1 : 0); return result; } /** * Returns a field locator for this instance. * * @param instrumentedType The instrumented type. * @return An appropriate field locator. */ protected abstract FieldLocator fieldLocator(TypeDescription instrumentedType); /** * An offset mapping for a field with an implicit declaring type. */ protected static class WithImplicitType extends ForField { /** * Creates an offset mapping for a field with an implicit declaring type. * * @param name The name of the field. * @param targetType The expected type that the field can be assigned to. * @param readOnly {@code true} if the field is read-only. */ protected WithImplicitType(String name, TypeDescription targetType, boolean readOnly) { super(name, targetType, readOnly); } @Override protected FieldLocator fieldLocator(TypeDescription instrumentedType) { return new FieldLocator.ForClassHierarchy(instrumentedType); } @Override public String toString() { return "Advice.Dispatcher.OffsetMapping.ForField.WithImplicitType{" + "name=" + name + ", targetType=" + targetType + '}'; } } /** * An offset mapping for a field with an explicit declaring type. */ protected static class WithExplicitType extends ForField { /** * The type declaring the field. */ private final TypeDescription explicitType; /** * Creates an offset mapping for a field with an explicit declaring type. * * @param name The name of the field. * @param targetType The expected type that the field can be assigned to. * @param locatedType The type declaring the field. * @param readOnly {@code true} if the field is read-only. */ protected WithExplicitType(String name, TypeDescription targetType, TypeDescription locatedType, boolean readOnly) { super(name, targetType, readOnly); this.explicitType = locatedType; } @Override protected FieldLocator fieldLocator(TypeDescription instrumentedType) { if (!instrumentedType.isAssignableTo(explicitType)) { throw new IllegalStateException(explicitType + " is no super type of " + instrumentedType); } return new FieldLocator.ForExactType(explicitType); } @Override public boolean equals(Object object) { if (this == object) return true; if (object == null || getClass() != object.getClass()) return false; if (!super.equals(object)) return false; WithExplicitType that = (WithExplicitType) object; return explicitType.equals(that.explicitType); } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + explicitType.hashCode(); return result; } @Override public String toString() { return "Advice.Dispatcher.OffsetMapping.ForField.WithExplicitType{" + "name=" + name + ", targetType=" + targetType + ", explicitType=" + explicitType + '}'; } } /** * A factory for a {@link ForField} offset mapping. */ protected enum Factory implements OffsetMapping.Factory { /** * A factory that does not allow writing to the mapped parameter. */ READ_ONLY(true), /** * A factory that allows writing to the mapped parameter. */ READ_WRITE(false); /** * {@code true} if the parameter is read-only. */ private final boolean readOnly; /** * Creates a new factory. * * @param readOnly {@code true} if the parameter is read-only. */ Factory(boolean readOnly) { this.readOnly = readOnly; } @Override public OffsetMapping make(ParameterDescription.InDefinedShape parameterDescription) { AnnotationDescription annotation = parameterDescription.getDeclaredAnnotations().ofType(FieldValue.class); if (annotation == null) { return UNDEFINED; } else if (readOnly && !annotation.getValue(ForField.READ_ONLY, Boolean.class)) { throw new IllegalStateException("Cannot write to field for " + parameterDescription + " in read-only context"); } else { TypeDescription declaringType = annotation.getValue(DECLARING_TYPE, TypeDescription.class); String name = annotation.getValue(VALUE, String.class); TypeDescription targetType = parameterDescription.getType().asErasure(); return declaringType.represents(void.class) ? new WithImplicitType(name, targetType, annotation.getValue(ForField.READ_ONLY, Boolean.class)) : new WithExplicitType(name, targetType, declaringType, annotation.getValue(ForField.READ_ONLY, Boolean.class)); } } @Override public String toString() { return "Advice.Dispatcher.OffsetMapping.ForField.Factory." + name(); } } } /** * An offset mapping for the {@link Advice.Origin} annotation. */ class ForOrigin implements OffsetMapping { /** * The delimiter character. */ private static final char DELIMITER = ' /** * The escape character. */ private static final char ESCAPE = '\\'; /** * The renderers to apply. */ private final List<Renderer> renderers; /** * Creates a new offset mapping for an origin value. * * @param renderers The renderers to apply. */ protected ForOrigin(List<Renderer> renderers) { this.renderers = renderers; } /** * Parses a pattern of an origin annotation. * * @param pattern The supplied pattern. * @return An appropriate offset mapping. */ protected static OffsetMapping parse(String pattern) { if (pattern.equals(Origin.DEFAULT)) { return new ForOrigin(Collections.<Renderer>singletonList(Renderer.ForStringRepresentation.INSTANCE)); } else { List<Renderer> renderers = new ArrayList<Renderer>(pattern.length()); int from = 0; for (int to = pattern.indexOf(DELIMITER); to != -1; to = pattern.indexOf(DELIMITER, from)) { if (to != 0 && pattern.charAt(to - 1) == ESCAPE && (to == 1 || pattern.charAt(to - 2) != ESCAPE)) { renderers.add(new Renderer.ForConstantValue(pattern.substring(from, Math.max(0, to - 1)) + DELIMITER)); from = to + 1; continue; } else if (pattern.length() == to + 1) { throw new IllegalStateException("Missing sort descriptor for " + pattern + " at index " + to); } renderers.add(new Renderer.ForConstantValue(pattern.substring(from, to).replace("" + ESCAPE + ESCAPE, "" + ESCAPE))); switch (pattern.charAt(to + 1)) { case Renderer.ForMethodName.SYMBOL: renderers.add(Renderer.ForMethodName.INSTANCE); break; case Renderer.ForTypeName.SYMBOL: renderers.add(Renderer.ForTypeName.INSTANCE); break; case Renderer.ForDescriptor.SYMBOL: renderers.add(Renderer.ForDescriptor.INSTANCE); break; case Renderer.ForReturnTypeName.SYMBOL: renderers.add(Renderer.ForReturnTypeName.INSTANCE); break; case Renderer.ForJavaSignature.SYMBOL: renderers.add(Renderer.ForJavaSignature.INSTANCE); break; default: throw new IllegalStateException("Illegal sort descriptor " + pattern.charAt(to + 1) + " for " + pattern); } from = to + 2; } renderers.add(new Renderer.ForConstantValue(pattern.substring(from))); return new ForOrigin(renderers); } } @Override public Target resolve(MethodDescription.InDefinedShape instrumentedMethod, Context context) { StringBuilder stringBuilder = new StringBuilder(); for (Renderer renderer : renderers) { stringBuilder.append(renderer.apply(instrumentedMethod)); } return new Target.ForConstantPoolValue(stringBuilder.toString()); } @Override public boolean equals(Object object) { if (this == object) return true; if (object == null || getClass() != object.getClass()) return false; ForOrigin forOrigin = (ForOrigin) object; return renderers.equals(forOrigin.renderers); } @Override public int hashCode() { return renderers.hashCode(); } @Override public String toString() { return "Advice.Dispatcher.OffsetMapping.ForOrigin{" + "renderers=" + renderers + '}'; } /** * A renderer for an origin pattern element. */ protected interface Renderer { /** * Returns a string representation for this renderer. * * @param instrumentedMethod The method being rendered. * @return The string representation. */ String apply(MethodDescription.InDefinedShape instrumentedMethod); /** * A renderer for a method's internal name. */ enum ForMethodName implements Renderer { /** * The singleton instance. */ INSTANCE; /** * The method name symbol. */ public static final char SYMBOL = 'm'; @Override public String apply(MethodDescription.InDefinedShape instrumentedMethod) { return instrumentedMethod.getInternalName(); } @Override public String toString() { return "Advice.Dispatcher.OffsetMapping.ForOrigin.Renderer.ForMethodName." + name(); } } /** * A renderer for a method declaring type's binary name. */ enum ForTypeName implements Renderer { /** * The singleton instance. */ INSTANCE; /** * The type name symbol. */ public static final char SYMBOL = 't'; @Override public String apply(MethodDescription.InDefinedShape instrumentedMethod) { return instrumentedMethod.getDeclaringType().getName(); } @Override public String toString() { return "Advice.Dispatcher.OffsetMapping.ForOrigin.Renderer.ForTypeName." + name(); } } /** * A renderer for a method descriptor. */ enum ForDescriptor implements Renderer { /** * The singleton instance. */ INSTANCE; /** * The descriptor symbol. */ public static final char SYMBOL = 'd'; @Override public String apply(MethodDescription.InDefinedShape instrumentedMethod) { return instrumentedMethod.getDescriptor(); } @Override public String toString() { return "Advice.Dispatcher.OffsetMapping.ForOrigin.Renderer.ForDescriptor." + name(); } } /** * A renderer for a method's Java signature in binary form. */ enum ForJavaSignature implements Renderer { /** * The singleton instance. */ INSTANCE; /** * The signature symbol. */ public static final char SYMBOL = 's'; @Override public String apply(MethodDescription.InDefinedShape instrumentedMethod) { StringBuilder stringBuilder = new StringBuilder("("); boolean comma = false; for (TypeDescription typeDescription : instrumentedMethod.getParameters().asTypeList().asErasures()) { if (comma) { stringBuilder.append(','); } else { comma = true; } stringBuilder.append(typeDescription.getName()); } return stringBuilder.append(')').toString(); } @Override public String toString() { return "Advice.Dispatcher.OffsetMapping.ForOrigin.Renderer.ForJavaSignature." + name(); } } /** * A renderer for a method's return type in binary form. */ enum ForReturnTypeName implements Renderer { /** * The singleton instance. */ INSTANCE; /** * The return type symbol. */ public static final char SYMBOL = 'r'; @Override public String apply(MethodDescription.InDefinedShape instrumentedMethod) { return instrumentedMethod.getReturnType().asErasure().getName(); } @Override public String toString() { return "Advice.Dispatcher.OffsetMapping.ForOrigin.Renderer.ForReturnTypeName." + name(); } } /** * A renderer for a method's {@link Object#toString()} representation. */ enum ForStringRepresentation implements Renderer { /** * The singleton instance. */ INSTANCE; @Override public String apply(MethodDescription.InDefinedShape instrumentedMethod) { return instrumentedMethod.toString(); } @Override public String toString() { return "Advice.Dispatcher.OffsetMapping.ForOrigin.Renderer.ForStringRepresentation." + name(); } } /** * A renderer for a constant value. */ class ForConstantValue implements Renderer { /** * The constant value. */ private final String value; /** * Creates a new renderer for a constant value. * * @param value The constant value. */ protected ForConstantValue(String value) { this.value = value; } @Override public String apply(MethodDescription.InDefinedShape instrumentedMethod) { return value; } @Override public boolean equals(Object object) { if (this == object) return true; if (object == null || getClass() != object.getClass()) return false; ForConstantValue that = (ForConstantValue) object; return value.equals(that.value); } @Override public int hashCode() { return value.hashCode(); } @Override public String toString() { return "Advice.Dispatcher.OffsetMapping.ForOrigin.Renderer.ForConstantValue{" + "value='" + value + '\'' + '}'; } } } /** * A factory for a method origin. */ protected enum Factory implements OffsetMapping.Factory { /** * The singleton instance. */ INSTANCE; @Override public OffsetMapping make(ParameterDescription.InDefinedShape parameterDescription) { AnnotationDescription.Loadable<Origin> origin = parameterDescription.getDeclaredAnnotations().ofType(Origin.class); if (origin == null) { return UNDEFINED; } else if (parameterDescription.getType().asErasure().represents(Class.class)) { return OffsetMapping.ForInstrumentedType.INSTANCE; } else if (parameterDescription.getType().asErasure().isAssignableFrom(String.class)) { return ForOrigin.parse(origin.loadSilent().value()); } else { throw new IllegalStateException("Non-String type " + parameterDescription + " for origin annotation"); } } @Override public String toString() { return "Advice.Dispatcher.OffsetMapping.ForOrigin.Factory." + name(); } } } /** * An offset mapping for a parameter where assignments are fully ignored and that always return the parameter type's default value. */ enum ForIgnored implements OffsetMapping, Factory { /** * The singleton instance. */ INSTANCE; @Override public Target resolve(MethodDescription.InDefinedShape instrumentedMethod, Context context) { return Target.ForDefaultValue.INSTANCE; } @Override public OffsetMapping make(ParameterDescription.InDefinedShape parameterDescription) { return parameterDescription.getDeclaredAnnotations().isAnnotationPresent(Ignored.class) ? this : UNDEFINED; } @Override public String toString() { return "Advice.Dispatcher.OffsetMapping.ForIgnored." + name(); } } /** * An offset mapping that provides access to the value that is returned by the enter advice. */ enum ForEnterValue implements OffsetMapping { /** * Enables writing to the mapped offset. */ WRITABLE(false), /** * Only allows for reading the mapped offset. */ READ_ONLY(true); /** * Determines if the parameter is to be treated as read-only. */ private final boolean readOnly; /** * Creates a new offset mapping for an enter value. * * @param readOnly Determines if the parameter is to be treated as read-only. */ ForEnterValue(boolean readOnly) { this.readOnly = readOnly; } /** * Resolves an offset mapping for an enter value. * * @param readOnly {@code true} if the value is to be treated as read-only. * @return An appropriate offset mapping. */ public static OffsetMapping of(boolean readOnly) { return readOnly ? READ_ONLY : WRITABLE; } @Override public Target resolve(MethodDescription.InDefinedShape instrumentedMethod, Context context) { return readOnly ? new Target.ForParameter.ReadOnly(instrumentedMethod.getStackSize()) : new Target.ForParameter.ReadWrite(instrumentedMethod.getStackSize()); } @Override public String toString() { return "Advice.Dispatcher.OffsetMapping.ForEnterValue." + name(); } /** * A factory for creating a {@link ForEnterValue} offset mapping. */ protected static class Factory implements OffsetMapping.Factory { /** * The supplied type of the enter method. */ private final TypeDescription enterType; /** * Indicates that the mapped parameter is read-only. */ private final boolean readOnly; /** * Creates a new factory for creating a {@link ForEnterValue} offset mapping. * * @param enterType The supplied type of the enter method. * @param readOnly Indicates that the mapped parameter is read-only. */ protected Factory(TypeDescription enterType, boolean readOnly) { this.enterType = enterType; this.readOnly = readOnly; } @Override public OffsetMapping make(ParameterDescription.InDefinedShape parameterDescription) { AnnotationDescription.Loadable<Enter> annotation = parameterDescription.getDeclaredAnnotations().ofType(Enter.class); if (annotation != null) { boolean readOnly = annotation.loadSilent().readOnly(); if (!readOnly && !enterType.equals(parameterDescription.getType().asErasure())) { throw new IllegalStateException("read-only type of " + parameterDescription + " does not equal " + enterType); } else if (readOnly && !enterType.isAssignableTo(parameterDescription.getType().asErasure())) { throw new IllegalStateException("Cannot assign the type of " + parameterDescription + " to supplied type " + enterType); } else if (this.readOnly && !readOnly) { throw new IllegalStateException("Cannot write to enter value field for " + parameterDescription + " in read only context"); } return ForEnterValue.of(readOnly); } else { return UNDEFINED; } } @Override public boolean equals(Object object) { if (this == object) return true; if (object == null || getClass() != object.getClass()) return false; Factory factory = (Factory) object; return readOnly == factory.readOnly && enterType.equals(factory.enterType); } @Override public int hashCode() { int result = enterType.hashCode(); result = 31 * result + (readOnly ? 1 : 0); return result; } @Override public String toString() { return "Advice.Dispatcher.OffsetMapping.ForEnterValue.Factory{" + "enterType=" + enterType + "m readOnly=" + readOnly + '}'; } } } /** * An offset mapping that provides access to the value that is returned by the instrumented method. */ class ForReturnValue implements OffsetMapping { /** * Determines if the parameter is to be treated as read-only. */ private final boolean readOnly; /** * The type that the advice method expects for the {@code this} reference. */ private final TypeDescription targetType; /** * Creates an offset mapping for accessing the return type of the instrumented method. * * @param readOnly Determines if the parameter is to be treated as read-only. * @param targetType The expected target type of the return type. */ protected ForReturnValue(boolean readOnly, TypeDescription targetType) { this.readOnly = readOnly; this.targetType = targetType; } @Override public Target resolve(MethodDescription.InDefinedShape instrumentedMethod, Context context) { if (!readOnly && !instrumentedMethod.getReturnType().asErasure().equals(targetType)) { throw new IllegalStateException("read-only return type of " + instrumentedMethod + " is not equal to " + targetType); } else if (readOnly && !instrumentedMethod.getReturnType().asErasure().isAssignableTo(targetType)) { throw new IllegalStateException("Cannot assign return type of " + instrumentedMethod + " to " + targetType); } return readOnly ? new Target.ForParameter.ReadOnly(instrumentedMethod.getStackSize() + context.getPadding()) : new Target.ForParameter.ReadWrite(instrumentedMethod.getStackSize() + context.getPadding()); } @Override public boolean equals(Object other) { if (this == other) return true; if (other == null || getClass() != other.getClass()) return false; ForReturnValue that = (ForReturnValue) other; return readOnly == that.readOnly && targetType.equals(that.targetType); } @Override public int hashCode() { return (readOnly ? 1 : 0) + 31 * targetType.hashCode(); } @Override public String toString() { return "Advice.Dispatcher.OffsetMapping.ForReturnValue{" + "readOnly=" + readOnly + ", targetType=" + targetType + '}'; } /** * A factory for creating a {@link ForReturnValue} offset mapping. */ protected enum Factory implements OffsetMapping.Factory { /** * A factory that does not allow writing to the mapped parameter. */ READ_ONLY(true), /** * A factory that allows writing to the mapped parameter. */ READ_WRITE(false); /** * {@code true} if the parameter is read-only. */ private final boolean readOnly; /** * Creates a new factory. * * @param readOnly {@code true} if the parameter is read-only. */ Factory(boolean readOnly) { this.readOnly = readOnly; } @Override public OffsetMapping make(ParameterDescription.InDefinedShape parameterDescription) { AnnotationDescription.Loadable<Return> annotation = parameterDescription.getDeclaredAnnotations().ofType(Return.class); if (annotation == null) { return UNDEFINED; } else if (readOnly && !annotation.loadSilent().readOnly()) { throw new IllegalStateException("Cannot write return value for " + parameterDescription + " in read-only context"); } else { return new ForReturnValue(annotation.loadSilent().readOnly(), parameterDescription.getType().asErasure()); } } @Override public String toString() { return "Advice.Dispatcher.OffsetMapping.ForReturnValue.Factory." + name(); } } } /** * An offset mapping for the method's (boxed) return value. */ enum ForBoxedReturnValue implements OffsetMapping { READ_ONLY(true), /** * A mapping that also allows writing to the boxed return value via a type casting and potential unboxing. */ READ_WRITE(false); /** * {@code true} if the factory is read-only. */ private final boolean readOnly; /** * Creates a new offset mapping. * * @param readOnly {@code true} if the mapping is read-only. */ ForBoxedReturnValue(boolean readOnly) { this.readOnly = readOnly; } @Override public Target resolve(MethodDescription.InDefinedShape instrumentedMethod, Context context) { if (instrumentedMethod.getReturnType().represents(void.class)) { return readOnly ? Target.ForNullConstant.READ_ONLY : Target.ForNullConstant.READ_WRITE; } else if (instrumentedMethod.getReturnType().isPrimitive()) { return readOnly ? Target.ForBoxedParameter.ReadOnly.of(instrumentedMethod.getStackSize() + context.getPadding(), instrumentedMethod.getReturnType()) : Target.ForBoxedParameter.ReadWrite.of(instrumentedMethod.getStackSize() + context.getPadding(), instrumentedMethod.getReturnType()); } else { return readOnly ? new Target.ForParameter.ReadOnly(instrumentedMethod.getStackSize() + context.getPadding()) : new Target.ForParameter.ReadWrite(instrumentedMethod.getStackSize() + context.getPadding()).casted(instrumentedMethod.getReturnType().asErasure()); } } @Override public String toString() { return "Advice.Dispatcher.OffsetMapping.ForBoxedReturnValue." + name(); } /** * A factory for an offset mapping the method's (boxed) return value. */ protected enum Factory implements OffsetMapping.Factory { READ_ONLY(true), /** * A factory that also allows writing to the boxed return value via a type casting and potential unboxing. */ READ_WRITE(false); /** * {@code true} if the factory is read-only. */ private final boolean readOnly; /** * Creates a new factory. * * @param readOnly {@code true} if the factory is read-only. */ Factory(boolean readOnly) { this.readOnly = readOnly; } @Override public OffsetMapping make(ParameterDescription.InDefinedShape parameterDescription) { AnnotationDescription.Loadable<BoxedReturn> annotation = parameterDescription.getDeclaredAnnotations().ofType(BoxedReturn.class); if (annotation == null) { return UNDEFINED; } else if (readOnly && !annotation.loadSilent().readOnly()) { throw new IllegalStateException("Cannot write return value from a non-writable context for " + parameterDescription); } else if (parameterDescription.getType().represents(Object.class)) { return annotation.loadSilent().readOnly() ? ForBoxedReturnValue.READ_ONLY : ForBoxedReturnValue.READ_WRITE; } else { throw new IllegalStateException("Can only assign a boxed return value to an Object type for " + parameterDescription); } } @Override public String toString() { return "Advice.Dispatcher.OffsetMapping.ForBoxedReturnValue.Factory." + name(); } } } /** * An offset mapping for an array containing the (boxed) method arguments. */ enum ForBoxedArguments implements OffsetMapping, Factory { /** * The singleton instance. */ INSTANCE; @Override public Target resolve(MethodDescription.InDefinedShape instrumentedMethod, Context context) { return new Target.ForBoxedArguments(instrumentedMethod.getParameters()); } @Override public OffsetMapping make(ParameterDescription.InDefinedShape parameterDescription) { if (!parameterDescription.getDeclaredAnnotations().isAnnotationPresent(BoxedArguments.class)) { return UNDEFINED; } else if (parameterDescription.getType().represents(Object[].class)) { return this; } else { throw new IllegalStateException("Can only assign an array of boxed arguments to an Object[] array"); } } @Override public String toString() { return "Advice.Dispatcher.OffsetMapping.ForBoxedArguments." + name(); } } /** * An offset mapping for accessing a {@link Throwable} of the instrumented method. */ class ForThrowable implements OffsetMapping { /** * The type of parameter that is being accessed. */ private final TypeDescription targetType; /** * The type of the {@link Throwable} being catched if thrown from the instrumented method. */ private final TypeDescription triggeringThrowable; /** * {@code true} if the parameter is read-only. */ private final boolean readOnly; /** * Creates a new offset mapping for access of the exception that is thrown by the instrumented method.. * * @param targetType The type of parameter that is being accessed. * @param triggeringThrowable The type of the {@link Throwable} being catched if thrown from the instrumented method. * @param readOnly {@code true} if the parameter is read-only. */ protected ForThrowable(TypeDescription targetType, TypeDescription triggeringThrowable, boolean readOnly) { this.targetType = targetType; this.triggeringThrowable = triggeringThrowable; this.readOnly = readOnly; } @Override public Target resolve(MethodDescription.InDefinedShape instrumentedMethod, Context context) { int offset = instrumentedMethod.getStackSize() + context.getPadding() + instrumentedMethod.getReturnType().getStackSize().getSize(); return readOnly ? new Target.ForParameter.ReadOnly(offset) : new Target.ForParameter.ReadWrite(offset); } @Override public boolean equals(Object object) { if (this == object) return true; if (object == null || getClass() != object.getClass()) return false; ForThrowable forThrowable = (ForThrowable) object; return readOnly == forThrowable.readOnly && targetType.equals(forThrowable.targetType) && triggeringThrowable.equals(forThrowable.triggeringThrowable); } @Override public int hashCode() { int result = triggeringThrowable.hashCode(); result = 31 * result + targetType.hashCode(); result = 31 * result + (readOnly ? 1 : 0); return result; } @Override public String toString() { return "Advice.Dispatcher.OffsetMapping.ForThrowable{" + "targetType=" + targetType + ", triggeringThrowable=" + triggeringThrowable + ", readOnly=" + readOnly + '}'; } /** * A factory for accessing an exception that was thrown by the instrumented method. */ protected static class Factory implements OffsetMapping.Factory { /** * The type of the {@link Throwable} being catched if thrown from the instrumented method. */ private final TypeDescription triggeringThrowable; /** * {@code true} if the parameter is read-only. */ private final boolean readOnly; /** * Creates a new factory for access of the exception that is thrown by the instrumented method.. * * @param triggeringThrowable The type of the {@link Throwable} being catched if thrown from the instrumented method. * @param readOnly {@code true} if the parameter is read-only. */ protected Factory(TypeDescription triggeringThrowable, boolean readOnly) { this.triggeringThrowable = triggeringThrowable; this.readOnly = readOnly; } /** * Resolves an appropriate offset mapping factory for the {@link Thrown} parameter annotation. * * @param adviceMethod The exit advice method, annotated with {@link OnMethodExit}. * @param readOnly {@code true} if the parameter is read-only. * @return An appropriate offset mapping factory. */ @SuppressWarnings("all") // In absence of @SafeVarargs for Java 6 protected static OffsetMapping.Factory of(MethodDescription.InDefinedShape adviceMethod, boolean readOnly) { TypeDescription triggeringThrowable = adviceMethod.getDeclaredAnnotations() .ofType(OnMethodExit.class) .getValue(ON_THROWABLE, TypeDescription.class); return triggeringThrowable.represents(NoExceptionHandler.class) ? new OffsetMapping.Illegal(Thrown.class) : new Factory(triggeringThrowable, readOnly); } @Override public OffsetMapping make(ParameterDescription.InDefinedShape parameterDescription) { AnnotationDescription.Loadable<Thrown> annotation = parameterDescription.getDeclaredAnnotations().ofType(Thrown.class); if (annotation == null) { return UNDEFINED; } else if (!parameterDescription.getType().represents(Throwable.class)) { throw new IllegalStateException("Parameter must be a throwable type for " + parameterDescription); } else if (readOnly && !annotation.loadSilent().readOnly()) { throw new IllegalStateException("Cannot write exception value for " + parameterDescription + " in read-only context"); } else { return new ForThrowable(parameterDescription.getType().asErasure(), triggeringThrowable, annotation.loadSilent().readOnly()); } } @Override public boolean equals(Object object) { if (this == object) return true; if (object == null || getClass() != object.getClass()) return false; Factory factory = (Factory) object; return readOnly == factory.readOnly && triggeringThrowable.equals(factory.triggeringThrowable); } @Override public int hashCode() { int result = triggeringThrowable.hashCode(); result = 31 * result + (readOnly ? 1 : 0); return result; } @Override public String toString() { return "Advice.Dispatcher.OffsetMapping.ForThrowable.Factory{" + "triggeringThrowable=" + triggeringThrowable + ", readOnly=" + readOnly + '}'; } } } /** * Represents an offset mapping for a user-defined value. * * @param <T> The mapped annotation type. */ class ForUserValue<T extends Annotation> implements OffsetMapping { /** * The target parameter that is bound. */ private final ParameterDescription.InDefinedShape target; /** * The annotation value that triggered the binding. */ private final AnnotationDescription.Loadable<T> annotation; /** * The dynamic value that is bound. */ private final DynamicValue<T> dynamicValue; /** * Creates a new offset mapping for a user-defined value. * * @param target The target parameter that is bound. * @param annotation The annotation value that triggered the binding. * @param dynamicValue The dynamic value that is bound. */ protected ForUserValue(ParameterDescription.InDefinedShape target, AnnotationDescription.Loadable<T> annotation, DynamicValue<T> dynamicValue) { this.target = target; this.annotation = annotation; this.dynamicValue = dynamicValue; } @Override public Target resolve(MethodDescription.InDefinedShape instrumentedMethod, Context context) { Object value = dynamicValue.resolve(instrumentedMethod, target, annotation, context.isInitialized()); if (value == null) { if (target.getType().isPrimitive()) { throw new IllegalStateException("Cannot map null to primitive type of " + target); } return Target.ForNullConstant.READ_ONLY; } else if ((target.getType().asErasure().isAssignableFrom(String.class) && value instanceof String) || (target.getType().isPrimitive() && target.getType().asErasure().isInstanceOrWrapper(value))) { if (value instanceof Boolean) { value = (Boolean) value ? 1 : 0; } else if (value instanceof Byte) { value = ((Byte) value).intValue(); } else if (value instanceof Short) { value = ((Short) value).intValue(); } else if (value instanceof Character) { value = (int) ((Character) value).charValue(); } return new Target.ForConstantPoolValue(value); } else if (target.getType().asErasure().isAssignableFrom(Class.class) && value instanceof Class) { return new Target.ForConstantPoolValue(Type.getType((Class<?>) value)); } else if (target.getType().asErasure().isAssignableFrom(Class.class) && value instanceof TypeDescription) { return new Target.ForConstantPoolValue(Type.getType(((TypeDescription) value).getDescriptor())); } else if (!target.getType().isPrimitive() && !target.getType().isArray() && value instanceof Serializable && target.getType().asErasure().isInstance(value)) { return Target.ForSerializedObject.of(target.getType().asErasure(), (Serializable) value); } else { throw new IllegalStateException("Cannot map " + value + " as constant value of " + target.getType()); } } @Override public boolean equals(Object object) { if (this == object) return true; if (object == null || getClass() != object.getClass()) return false; ForUserValue that = (ForUserValue) object; return target.equals(that.target) && annotation.equals(that.annotation) && dynamicValue.equals(that.dynamicValue); } @Override public int hashCode() { int result = target.hashCode(); result = 31 * result + annotation.hashCode(); result = 31 * result + dynamicValue.hashCode(); return result; } @Override public String toString() { return "Advice.Dispatcher.OffsetMapping.ForUserValue{" + "target=" + target + ", annotation=" + annotation + ", dynamicValue=" + dynamicValue + '}'; } /** * A factory for mapping a user-defined dynamic value. * * @param <S> The mapped annotation type. */ protected static class Factory<S extends Annotation> implements OffsetMapping.Factory { /** * The mapped annotation type. */ private final Class<S> type; /** * The dynamic value instance used for resolving a binding. */ private final DynamicValue<S> dynamicValue; /** * Creates a new factory for a user-defined dynamic value. * * @param type The mapped annotation type. * @param dynamicValue The dynamic value instance used for resolving a binding. */ protected Factory(Class<S> type, DynamicValue<S> dynamicValue) { this.type = type; this.dynamicValue = dynamicValue; } /** * Creates a new factory for mapping a user value. * * @param type The mapped annotation type. * @param dynamicValue The dynamic value instance used for resolving a binding. * @return An appropriate factory for such a offset mapping. */ @SuppressWarnings("unchecked") protected static OffsetMapping.Factory of(Class<? extends Annotation> type, DynamicValue<?> dynamicValue) { return new Factory(type, dynamicValue); } @Override public OffsetMapping make(ParameterDescription.InDefinedShape parameterDescription) { AnnotationDescription.Loadable<S> annotation = parameterDescription.getDeclaredAnnotations().ofType(type); return annotation == null ? UNDEFINED : new ForUserValue<S>(parameterDescription, annotation, dynamicValue); } @Override public boolean equals(Object object) { if (this == object) return true; if (object == null || getClass() != object.getClass()) return false; Factory factory = (Factory) object; return type.equals(factory.type) && dynamicValue.equals(factory.dynamicValue); } @Override public int hashCode() { int result = type.hashCode(); result = 31 * result + dynamicValue.hashCode(); return result; } @Override public String toString() { return "Advice.Dispatcher.OffsetMapping.ForUserValue.Factory{" + "type=" + type + ", dynamicValue=" + dynamicValue + '}'; } } } class Illegal implements Factory { private final List<? extends Class<? extends Annotation>> annotations; //@SafeVarargs protected Illegal(Class<? extends Annotation>... annotation) { this(Arrays.asList(annotation)); } protected Illegal(List<? extends Class<? extends Annotation>> annotations) { this.annotations = annotations; } @Override public OffsetMapping make(ParameterDescription.InDefinedShape parameterDescription) { for (Class<? extends Annotation> annotation : annotations) { if (parameterDescription.getDeclaredAnnotations().isAnnotationPresent(annotation)) { throw new IllegalStateException("Illegal annotation " + annotation + " for " + parameterDescription); } } return UNDEFINED; } @Override public boolean equals(Object other) { if (this == other) return true; if (other == null || getClass() != other.getClass()) return false; Illegal illegal = (Illegal) other; return annotations.equals(illegal.annotations); } @Override public int hashCode() { return annotations.hashCode(); } @Override public String toString() { return "Advice.Dispatcher.OffsetMapping.Illegal{" + "annotations=" + annotations + '}'; } } } /** * A suppression handler for optionally suppressing exceptions. */ interface SuppressionHandler { /** * Binds the suppression handler for instrumenting a specific method. * * @return A bound version of the suppression handler. */ Bound bind(); /** * A producer for a default return value if this is applicable. */ interface ReturnValueProducer { /** * Instructs this return value producer to assure the production of a default value for the return type of the currently handled method. */ void onDefaultValue(); } /** * A bound version of a suppression handler that must not be reused. */ interface Bound { /** * Invoked to prepare the suppression handler, i.e. to write an exception handler entry if appropriate. * * @param methodVisitor The method visitor to apply the preparation to. */ void onPrepare(MethodVisitor methodVisitor); /** * Invoked at the start of a method. * * @param methodVisitor The method visitor of the instrumented method. * @param methodSizeHandler A handler for computing the method size requirements. */ void onStart(MethodVisitor methodVisitor, MethodSizeHandler.ForAdvice methodSizeHandler); /** * Invoked at the end of a method. * * @param methodVisitor The method visitor of the instrumented method. * @param stackMapFrameHandler A handler for translating and injecting stack map frames. * @param returnValueProducer A producer for defining a default return value of the advised method. */ void onEnd(MethodVisitor methodVisitor, StackMapFrameHandler.ForAdvice stackMapFrameHandler, ReturnValueProducer returnValueProducer); /** * Invoked at the end of a method. Additionally indicates that the handler block should be surrounding by a skipping instruction. This method * is always followed by a stack map frame (if it is required for the class level and class writer setting). * * @param methodVisitor The method visitor of the instrumented method. * @param stackMapFrameHandler A handler for translating and injecting stack map frames. * @param returnValueProducer A producer for defining a default return value of the advised method. */ void onEndSkipped(MethodVisitor methodVisitor, StackMapFrameHandler.ForAdvice stackMapFrameHandler, ReturnValueProducer returnValueProducer); } /** * A non-operational suppression handler that does not suppress any method. */ enum NoOp implements SuppressionHandler, Bound { /** * The singleton instance. */ INSTANCE; @Override public Bound bind() { return this; } @Override public void onPrepare(MethodVisitor methodVisitor) { /* do nothing */ } @Override public void onStart(MethodVisitor methodVisitor, MethodSizeHandler.ForAdvice methodSizeHandler) { /* do nothing */ } @Override public void onEnd(MethodVisitor methodVisitor, StackMapFrameHandler.ForAdvice stackMapFrameHandler, ReturnValueProducer returnValueProducer) { /* do nothing */ } @Override public void onEndSkipped(MethodVisitor methodVisitor, StackMapFrameHandler.ForAdvice stackMapFrameHandler, ReturnValueProducer returnValueProducer) { /* do nothing */ } @Override public String toString() { return "Advice.Dispatcher.SuppressionHandler.NoOp." + name(); } } /** * A suppression handler that suppresses a given throwable type. */ class Suppressing implements SuppressionHandler { /** * The suppressed throwable type. */ private final TypeDescription suppressedType; /** * Creates a new suppressing suppression handler. * * @param suppressedType The suppressed throwable type. */ protected Suppressing(TypeDescription suppressedType) { this.suppressedType = suppressedType; } /** * Resolves an appropriate suppression handler. * * @param suppressedType The suppressed type or {@link NoExceptionHandler} if no type should be suppressed. * @return An appropriate suppression handler. */ protected static SuppressionHandler of(TypeDescription suppressedType) { return suppressedType.represents(NoExceptionHandler.class) ? NoOp.INSTANCE : new Suppressing(suppressedType); } @Override public SuppressionHandler.Bound bind() { return new Bound(suppressedType); } @Override public boolean equals(Object object) { if (this == object) return true; if (object == null || getClass() != object.getClass()) return false; Suppressing that = (Suppressing) object; return suppressedType.equals(that.suppressedType); } @Override public int hashCode() { return suppressedType.hashCode(); } @Override public String toString() { return "Advice.Dispatcher.SuppressionHandler.Suppressing{" + "suppressedType=" + suppressedType + '}'; } /** * An active, bound suppression handler. */ protected static class Bound implements SuppressionHandler.Bound { /** * The suppressed throwable type. */ private final TypeDescription suppressedType; /** * A label indicating the start of the method. */ private final Label startOfMethod; /** * A label indicating the end of the method. */ private final Label endOfMethod; /** * Creates a new active, bound suppression handler. * * @param suppressedType The suppressed throwable type. */ protected Bound(TypeDescription suppressedType) { this.suppressedType = suppressedType; startOfMethod = new Label(); endOfMethod = new Label(); } @Override public void onPrepare(MethodVisitor methodVisitor) { methodVisitor.visitTryCatchBlock(startOfMethod, endOfMethod, endOfMethod, suppressedType.getInternalName()); } @Override public void onStart(MethodVisitor methodVisitor, MethodSizeHandler.ForAdvice methodSizeHandler) { methodVisitor.visitLabel(startOfMethod); methodSizeHandler.recordMinimum(StackSize.SINGLE.getSize()); } @Override public void onEnd(MethodVisitor methodVisitor, StackMapFrameHandler.ForAdvice stackMapFrameHandler, ReturnValueProducer returnValueProducer) { methodVisitor.visitLabel(endOfMethod); stackMapFrameHandler.injectExceptionFrame(methodVisitor); methodVisitor.visitInsn(Opcodes.POP); returnValueProducer.onDefaultValue(); } @Override public void onEndSkipped(MethodVisitor methodVisitor, StackMapFrameHandler.ForAdvice stackMapFrameHandler, ReturnValueProducer returnValueProducer) { Label endOfHandler = new Label(); methodVisitor.visitJumpInsn(Opcodes.GOTO, endOfHandler); onEnd(methodVisitor, stackMapFrameHandler, returnValueProducer); methodVisitor.visitLabel(endOfHandler); } @Override public String toString() { return "Advice.Dispatcher.SuppressionHandler.Suppressing.Bound{" + "suppressedType=" + suppressedType + ", startOfMethod=" + startOfMethod + ", endOfMethod=" + endOfMethod + '}'; } } } } /** * Represents a resolved dispatcher. */ interface Resolved extends Dispatcher { /** * Binds this dispatcher for resolution to a specific method. * * @param instrumentedMethod The instrumented method. * @param methodVisitor The method visitor for writing the instrumented method. * @param methodSizeHandler A handler for computing the method size requirements. * @param stackMapFrameHandler A handler for translating and injecting stack map frames. * @return A dispatcher that is bound to the instrumented method. */ Bound bind(MethodDescription.InDefinedShape instrumentedMethod, MethodVisitor methodVisitor, MethodSizeHandler methodSizeHandler, StackMapFrameHandler.ForInstrumentedMethod stackMapFrameHandler); /** * Represents a resolved dispatcher for entering a method. */ interface ForMethodEnter extends Resolved { /** * Returns the type that this dispatcher supplies as a result of its advice or a description of {@code void} if * no type is supplied as a result of the enter advice. * * @return The type that this dispatcher supplies as a result of its advice or a description of {@code void}. */ TypeDescription getEnterType(); @Override Bound.ForMethodEnter bind(MethodDescription.InDefinedShape instrumentedMethod, MethodVisitor methodVisitor, MethodSizeHandler methodSizeHandler, StackMapFrameHandler.ForInstrumentedMethod stackMapFrameHandler); /** * A skip dispatcher is responsible for skipping the instrumented method depending on the return value of the * enter advice method. */ enum SkipDispatcher { /** * A enabled skip dispatcher that skips the instrumented method. */ ENABLED { @Override protected void apply(MethodVisitor methodVisitor, StackMapFrameHandler.ForAdvice stackMapFrameHandler, MethodDescription.InDefinedShape instrumentedMethod, Bound.SkipHandler skipHandler) { methodVisitor.visitVarInsn(Opcodes.ILOAD, instrumentedMethod.getStackSize()); Label noSkip = new Label(); methodVisitor.visitJumpInsn(Opcodes.IFEQ, noSkip); skipHandler.apply(methodVisitor); methodVisitor.visitLabel(noSkip); stackMapFrameHandler.injectCompletionFrame(methodVisitor, true); } }, /** * A disabled skip dispatcher that does not allow for skipping the instrumented method. */ DISABLED { @Override protected void apply(MethodVisitor methodVisitor, StackMapFrameHandler.ForAdvice stackMapFrameHandler, MethodDescription.InDefinedShape instrumentedMethod, Bound.SkipHandler skipHandler) { /* do nothing */ } }; /** * Resolves a skip dispatcher for an advice method that is annotated with {@link OnMethodEnter}. * * @param adviceMethod The advice method for which to resolve a skip dispatcher. * @return A suitable skip dispatcher for the supplied method. */ protected static SkipDispatcher of(MethodDescription.InDefinedShape adviceMethod) { boolean enabled = adviceMethod.getDeclaredAnnotations().ofType(OnMethodEnter.class).getValue(SKIP_IF_TRUE, Boolean.class); if (enabled && !adviceMethod.getReturnType().represents(boolean.class)) { throw new IllegalStateException(adviceMethod + " does not return boolean as it is required for enabling 'skipIfTrue'"); } return enabled ? ENABLED : DISABLED; } /** * Applies this skip dispatcher. * * @param methodVisitor The method visitor to write to. * @param stackMapFrameHandler The stack map frame handler of the advice method to use. * @param instrumentedMethod The instrumented method. * @param skipHandler The skip handler to use. */ protected abstract void apply(MethodVisitor methodVisitor, StackMapFrameHandler.ForAdvice stackMapFrameHandler, MethodDescription.InDefinedShape instrumentedMethod, Bound.SkipHandler skipHandler); @Override public String toString() { return "Advice.Dispatcher.Resolved.ForMethodEnter.SkipDispatcher." + name(); } } } /** * Represents a resolved dispatcher for exiting a method. */ interface ForMethodExit extends Resolved { /** * Returns the type of throwable for which this exit advice is supposed to be invoked. * * @return The {@link Throwable} type for which to invoke this exit advice or a description of {@link NoExceptionHandler} * if this exit advice does not expect to be invoked upon any throwable. */ TypeDescription getTriggeringThrowable(); @Override Bound.ForMethodExit bind(MethodDescription.InDefinedShape instrumentedMethod, MethodVisitor methodVisitor, MethodSizeHandler methodSizeHandler, StackMapFrameHandler.ForInstrumentedMethod stackMapFrameHandler); } } /** * A bound resolution of an advice method. */ interface Bound { /** * Prepares the advice method's exception handlers. */ void prepare(); /** * A skip handler is responsible for writing code that skips the invocation of the original code * within the instrumented method. */ interface SkipHandler { /** * Applies this skip handler. * * @param methodVisitor The method visitor to write the code to. */ void apply(MethodVisitor methodVisitor); } /** * A bound dispatcher for a method enter. */ interface ForMethodEnter extends Bound { /** * Applies this dispatcher. * * @param skipHandler The skip handler to use. */ void apply(SkipHandler skipHandler); } /** * A bound dispatcher for a method exit. */ interface ForMethodExit extends Bound { /** * Applies this dispatcher. */ void apply(); } } /** * An implementation for inactive devise that does not write any byte code. */ enum Inactive implements Dispatcher.Unresolved, Resolved.ForMethodEnter, Resolved.ForMethodExit, Bound.ForMethodEnter, Bound.ForMethodExit { /** * The singleton instance. */ INSTANCE; @Override public boolean isAlive() { return false; } @Override public boolean isBinary() { return false; } @Override public TypeDescription getTriggeringThrowable() { return NoExceptionHandler.DESCRIPTION; } @Override public TypeDescription getEnterType() { return TypeDescription.VOID; } @Override public Resolved.ForMethodEnter asMethodEnter(List<? extends OffsetMapping.Factory> userFactories, ClassReader classReader) { return this; } @Override public Resolved.ForMethodExit asMethodExitTo(List<? extends OffsetMapping.Factory> userFactories, ClassReader classReader, Resolved.ForMethodEnter dispatcher) { return this; } @Override public void prepare() { /* do nothing */ } @Override public void apply() { /* do nothing */ } @Override public void apply(SkipHandler skipHandler) { /* do nothing */ } @Override public Inactive bind(MethodDescription.InDefinedShape instrumentedMethod, MethodVisitor methodVisitor, MethodSizeHandler methodSizeHandler, StackMapFrameHandler.ForInstrumentedMethod stackMapFrameHandler) { return this; } @Override public String toString() { return "Advice.Dispatcher.Inactive." + name(); } } /** * A dispatcher for an advice method that is being inlined into the instrumented method. */ class Inlining implements Unresolved { /** * The advice method. */ protected final MethodDescription.InDefinedShape adviceMethod; /** * Creates a dispatcher for inlined advice method. * * @param adviceMethod The advice method. */ protected Inlining(MethodDescription.InDefinedShape adviceMethod) { this.adviceMethod = adviceMethod; } @Override public boolean isAlive() { return true; } @Override public boolean isBinary() { return true; } @Override public Dispatcher.Resolved.ForMethodEnter asMethodEnter(List<? extends OffsetMapping.Factory> userFactories, ClassReader classReader) { return new Resolved.ForMethodEnter(adviceMethod, userFactories, classReader); } @Override public Dispatcher.Resolved.ForMethodExit asMethodExitTo(List<? extends OffsetMapping.Factory> userFactories, ClassReader classReader, Dispatcher.Resolved.ForMethodEnter dispatcher) { return Resolved.ForMethodExit.of(adviceMethod, userFactories, classReader, dispatcher.getEnterType()); } @Override public boolean equals(Object other) { return this == other || !(other == null || getClass() != other.getClass()) && adviceMethod.equals(((Inlining) other).adviceMethod); } @Override public int hashCode() { return adviceMethod.hashCode(); } @Override public String toString() { return "Advice.Dispatcher.Inlining{" + "adviceMethod=" + adviceMethod + '}'; } /** * A resolved version of a dispatcher. */ protected abstract static class Resolved implements Dispatcher.Resolved { /** * Indicates a read-only mapping for an offset. */ private static final boolean READ_ONLY = true; /** * The represented advice method. */ protected final MethodDescription.InDefinedShape adviceMethod; /** * A class reader to query for the class file of the advice method. */ protected final ClassReader classReader; /** * An unresolved mapping of offsets of the advice method based on the annotations discovered on each method parameter. */ protected final Map<Integer, OffsetMapping> offsetMappings; /** * The suppression handler to use. */ protected final SuppressionHandler suppressionHandler; /** * Creates a new resolved version of a dispatcher. * * @param adviceMethod The represented advice method. * @param factories A list of factories to resolve for the parameters of the advice method. * @param classReader A class reader to query for the class file of the advice method. * @param throwableType The type to handle by a suppression handler or {@link NoExceptionHandler} to not handle any exceptions. */ protected Resolved(MethodDescription.InDefinedShape adviceMethod, List<OffsetMapping.Factory> factories, ClassReader classReader, TypeDescription throwableType) { this.adviceMethod = adviceMethod; offsetMappings = new HashMap<Integer, OffsetMapping>(); for (ParameterDescription.InDefinedShape parameterDescription : adviceMethod.getParameters()) { OffsetMapping offsetMapping = OffsetMapping.Factory.UNDEFINED; for (OffsetMapping.Factory factory : factories) { OffsetMapping possible = factory.make(parameterDescription); if (possible != null) { if (offsetMapping == null) { offsetMapping = possible; } else { throw new IllegalStateException(parameterDescription + " is bound to both " + possible + " and " + offsetMapping); } } } offsetMappings.put(parameterDescription.getOffset(), offsetMapping == null ? new OffsetMapping.ForParameter(parameterDescription.getIndex(), READ_ONLY, parameterDescription.getType().asErasure()) : offsetMapping); } this.classReader = classReader; suppressionHandler = SuppressionHandler.Suppressing.of(throwableType); } @Override public boolean isAlive() { return true; } /** * Applies a resolution for a given instrumented method. * * @param methodVisitor A method visitor for writing byte code to the instrumented method. * @param methodSizeHandler A handler for computing the method size requirements. * @param stackMapFrameHandler A handler for translating and injecting stack map frames. * @param instrumentedMethod A description of the instrumented method. * @param suppressionHandler The bound suppression handler that is used for suppressing exceptions of this advice method. * @return A method visitor for visiting the advice method's byte code. */ protected abstract MethodVisitor apply(MethodVisitor methodVisitor, MethodSizeHandler methodSizeHandler, StackMapFrameHandler.ForInstrumentedMethod stackMapFrameHandler, MethodDescription.InDefinedShape instrumentedMethod, SuppressionHandler.Bound suppressionHandler); @Override public boolean equals(Object other) { if (this == other) return true; if (other == null || getClass() != other.getClass()) return false; Inlining.Resolved resolved = (Inlining.Resolved) other; return adviceMethod.equals(resolved.adviceMethod) && offsetMappings.equals(resolved.offsetMappings); } @Override public int hashCode() { int result = adviceMethod.hashCode(); result = 31 * result + offsetMappings.hashCode(); return result; } /** * A bound advice method that copies the code by first extracting the exception table and later appending the * code of the method without copying any meta data. */ protected abstract class AdviceMethodInliner extends ClassVisitor implements Bound { /** * The instrumented method. */ protected final MethodDescription.InDefinedShape instrumentedMethod; /** * The method visitor for writing the instrumented method. */ protected final MethodVisitor methodVisitor; /** * A handler for computing the method size requirements. */ protected final MethodSizeHandler methodSizeHandler; /** * A handler for translating and injecting stack map frames. */ protected final StackMapFrameHandler.ForInstrumentedMethod stackMapFrameHandler; /** * A bound suppression handler that is used for suppressing exceptions of this advice method. */ protected final SuppressionHandler.Bound suppressionHandler; /** * A class reader for parsing the class file containing the represented advice method. */ protected final ClassReader classReader; /** * The labels that were found during parsing the method's exception handler in the order of their discovery. */ protected List<Label> labels; /** * Creates a new advice method inliner. * * @param instrumentedMethod The instrumented method. * @param methodVisitor The method visitor for writing the instrumented method. * @param methodSizeHandler A handler for computing the method size requirements. * @param stackMapFrameHandler A handler for translating and injecting stack map frames. * @param suppressionHandler A bound suppression handler that is used for suppressing exceptions of this advice method. * @param classReader A class reader for parsing the class file containing the represented advice method. */ protected AdviceMethodInliner(MethodDescription.InDefinedShape instrumentedMethod, MethodVisitor methodVisitor, MethodSizeHandler methodSizeHandler, StackMapFrameHandler.ForInstrumentedMethod stackMapFrameHandler, SuppressionHandler.Bound suppressionHandler, ClassReader classReader) { super(Opcodes.ASM5); this.instrumentedMethod = instrumentedMethod; this.methodVisitor = methodVisitor; this.methodSizeHandler = methodSizeHandler; this.stackMapFrameHandler = stackMapFrameHandler; this.suppressionHandler = suppressionHandler; this.classReader = classReader; labels = new ArrayList<Label>(); } @Override public void prepare() { classReader.accept(new ExceptionTableExtractor(), ClassReader.SKIP_FRAMES | ClassReader.SKIP_DEBUG); suppressionHandler.onPrepare(methodVisitor); } /** * Inlines the advice method. */ protected void doApply() { classReader.accept(this, ClassReader.SKIP_DEBUG | stackMapFrameHandler.getReaderHint()); } @Override public MethodVisitor visitMethod(int modifiers, String internalName, String descriptor, String signature, String[] exception) { return adviceMethod.getInternalName().equals(internalName) && adviceMethod.getDescriptor().equals(descriptor) ? new ExceptionTableSubstitutor(Inlining.Resolved.this.apply(methodVisitor, methodSizeHandler, stackMapFrameHandler, instrumentedMethod, suppressionHandler)) : IGNORE_METHOD; } /** * A class visitor that extracts the exception tables of the advice method. */ protected class ExceptionTableExtractor extends ClassVisitor { /** * Creates a new exception table extractor. */ protected ExceptionTableExtractor() { super(Opcodes.ASM5); } @Override public MethodVisitor visitMethod(int modifiers, String internalName, String descriptor, String signature, String[] exception) { return adviceMethod.getInternalName().equals(internalName) && adviceMethod.getDescriptor().equals(descriptor) ? new ExceptionTableCollector(methodVisitor) : IGNORE_METHOD; } @Override public String toString() { return "Advice.Dispatcher.Inlining.Resolved.AdviceMethodInliner.ExceptionTableExtractor{" + "methodVisitor=" + methodVisitor + '}'; } } /** * A visitor that only writes try-catch-finally blocks to the supplied method visitor. All labels of these tables are collected * for substitution when revisiting the reminder of the method. */ protected class ExceptionTableCollector extends MethodVisitor { /** * The method visitor for which the try-catch-finally blocks should be written. */ private final MethodVisitor methodVisitor; /** * Creates a new exception table collector. * * @param methodVisitor The method visitor for which the try-catch-finally blocks should be written. */ protected ExceptionTableCollector(MethodVisitor methodVisitor) { super(Opcodes.ASM5); this.methodVisitor = methodVisitor; } @Override public void visitTryCatchBlock(Label start, Label end, Label handler, String type) { methodVisitor.visitTryCatchBlock(start, end, handler, type); labels.addAll(Arrays.asList(start, end, handler)); } @Override public AnnotationVisitor visitTryCatchAnnotation(int typeReference, TypePath typePath, String descriptor, boolean visible) { return methodVisitor.visitTryCatchAnnotation(typeReference, typePath, descriptor, visible); } @Override public String toString() { return "Advice.Dispatcher.Inlining.Resolved.AdviceMethodInliner.ExceptionTableCollector{" + "methodVisitor=" + methodVisitor + '}'; } } /** * A label substitutor allows to visit an advice method a second time after the exception handlers were already written. * Doing so, this visitor substitutes all labels that were already created during the first visit to keep the mapping * consistent. */ protected class ExceptionTableSubstitutor extends MethodVisitor { /** * A map containing resolved substitutions. */ private final Map<Label, Label> substitutions; /** * The current index of the visited labels that are used for try-catch-finally blocks. */ private int index; /** * Creates a label substitor. * * @param methodVisitor The method visitor for which to substitute labels. */ protected ExceptionTableSubstitutor(MethodVisitor methodVisitor) { super(Opcodes.ASM5, methodVisitor); substitutions = new IdentityHashMap<Label, Label>(); } @Override public void visitTryCatchBlock(Label start, Label end, Label handler, String type) { substitutions.put(start, labels.get(index++)); substitutions.put(end, labels.get(index++)); substitutions.put(handler, labels.get(index++)); } @Override public AnnotationVisitor visitTryCatchAnnotation(int typeRef, TypePath typePath, String desc, boolean visible) { return IGNORE_ANNOTATION; } @Override public void visitLabel(Label label) { super.visitLabel(resolve(label)); } @Override public void visitJumpInsn(int opcode, Label label) { super.visitJumpInsn(opcode, resolve(label)); } @Override public void visitTableSwitchInsn(int min, int max, Label dflt, Label... labels) { super.visitTableSwitchInsn(min, max, dflt, resolve(labels)); } @Override public void visitLookupSwitchInsn(Label dflt, int[] keys, Label[] labels) { super.visitLookupSwitchInsn(resolve(dflt), keys, resolve(labels)); } /** * Resolves an array of labels. * * @param label The labels to resolved. * @return An array containing the resolved arrays. */ private Label[] resolve(Label[] label) { Label[] resolved = new Label[label.length]; int index = 0; for (Label aLabel : label) { resolved[index++] = resolve(aLabel); } return resolved; } /** * Resolves a single label if mapped or returns the original label. * * @param label The label to resolve. * @return The resolved label. */ private Label resolve(Label label) { Label substitution = substitutions.get(label); return substitution == null ? label : substitution; } @Override public String toString() { return "Advice.Dispatcher.Inlining.Resolved.AdviceMethodInliner.ExceptionTableSubstitutor{" + "methodVisitor=" + methodVisitor + ", substitutions=" + substitutions + ", index=" + index + '}'; } } } /** * A resolved dispatcher for implementing method enter advice. */ protected static class ForMethodEnter extends Inlining.Resolved implements Dispatcher.Resolved.ForMethodEnter { /** * The skip dispatcher to use. */ private final SkipDispatcher skipDispatcher; /** * Creates a new resolved dispatcher for implementing method enter advice. * * @param adviceMethod The represented advice method. * @param userFactories A list of user-defined factories for offset mappings. * @param classReader A class reader to query for the class file of the advice method. */ @SuppressWarnings("all") // In absence of @SafeVarargs for Java 6 protected ForMethodEnter(MethodDescription.InDefinedShape adviceMethod, List<? extends OffsetMapping.Factory> userFactories, ClassReader classReader) { super(adviceMethod, CompoundList.of(Arrays.asList(OffsetMapping.ForParameter.Factory.READ_WRITE, OffsetMapping.ForBoxedArguments.INSTANCE, OffsetMapping.ForThisReference.Factory.READ_WRITE, OffsetMapping.ForField.Factory.READ_WRITE, OffsetMapping.ForOrigin.Factory.INSTANCE, OffsetMapping.ForIgnored.INSTANCE, new OffsetMapping.Illegal(Thrown.class, Enter.class, Return.class, BoxedReturn.class)), userFactories), classReader, adviceMethod.getDeclaredAnnotations().ofType(OnMethodEnter.class).getValue(SUPPRESS_ENTER, TypeDescription.class)); skipDispatcher = SkipDispatcher.of(adviceMethod); } @Override public Bound.ForMethodEnter bind(MethodDescription.InDefinedShape instrumentedMethod, MethodVisitor methodVisitor, MethodSizeHandler methodSizeHandler, StackMapFrameHandler.ForInstrumentedMethod stackMapFrameHandler) { return new AdviceMethodInliner(instrumentedMethod, methodVisitor, methodSizeHandler, stackMapFrameHandler, suppressionHandler.bind(), classReader, skipDispatcher); } @Override public TypeDescription getEnterType() { return adviceMethod.getReturnType().asErasure(); } @Override protected MethodVisitor apply(MethodVisitor methodVisitor, MethodSizeHandler methodSizeHandler, StackMapFrameHandler.ForInstrumentedMethod stackMapFrameHandler, MethodDescription.InDefinedShape instrumentedMethod, SuppressionHandler.Bound suppressionHandler) { Map<Integer, OffsetMapping.Target> offsetMappings = new HashMap<Integer, OffsetMapping.Target>(); for (Map.Entry<Integer, OffsetMapping> entry : this.offsetMappings.entrySet()) { offsetMappings.put(entry.getKey(), entry.getValue().resolve(instrumentedMethod, OffsetMapping.Context.ForMethodEntry.of(instrumentedMethod))); } return new CodeTranslationVisitor.ForMethodEnter(methodVisitor, methodSizeHandler.bindEntry(adviceMethod), stackMapFrameHandler.bindEntry(adviceMethod), instrumentedMethod, adviceMethod, offsetMappings, suppressionHandler); } @Override public boolean equals(Object object) { if (this == object) return true; if (object == null || getClass() != object.getClass()) return false; if (!super.equals(object)) return false; Inlining.Resolved.ForMethodEnter that = (Inlining.Resolved.ForMethodEnter) object; return skipDispatcher == that.skipDispatcher; } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + skipDispatcher.hashCode(); return result; } @Override public String toString() { return "Advice.Dispatcher.Inlining.Resolved.ForMethodEnter{" + "adviceMethod=" + adviceMethod + ", offsetMappings=" + offsetMappings + ", skipDispatcher=" + skipDispatcher + '}'; } /** * An advice method inliner for a method enter. */ protected class AdviceMethodInliner extends Inlining.Resolved.AdviceMethodInliner implements Bound.ForMethodEnter { /** * The skip dispatcher to use. */ private final SkipDispatcher skipDispatcher; /** * Creates a new advice method inliner for a method enter. * * @param instrumentedMethod The instrumented method. * @param methodVisitor The method visitor for writing the instrumented method. * @param methodSizeHandler A handler for computing the method size requirements. * @param stackMapFrameHandler A handler for translating and injecting stack map frames. * @param suppressionHandler A bound suppression handler that is used for suppressing exceptions of this advice method. * @param classReader A class reader for parsing the class file containing the represented advice method. * @param skipDispatcher The skip dispatcher to use. */ public AdviceMethodInliner(MethodDescription.InDefinedShape instrumentedMethod, MethodVisitor methodVisitor, MethodSizeHandler methodSizeHandler, StackMapFrameHandler.ForInstrumentedMethod stackMapFrameHandler, SuppressionHandler.Bound suppressionHandler, ClassReader classReader, SkipDispatcher skipDispatcher) { super(instrumentedMethod, methodVisitor, methodSizeHandler, stackMapFrameHandler, suppressionHandler, classReader); this.skipDispatcher = skipDispatcher; } @Override public void apply(SkipHandler skipHandler) { doApply(); skipDispatcher.apply(methodVisitor, stackMapFrameHandler.bindEntry(adviceMethod), instrumentedMethod, skipHandler); } @Override public String toString() { return "Advice.Dispatcher.Inlining.Resolved.ForMethodEnter.AdviceMethodInliner{" + "instrumentedMethod=" + instrumentedMethod + ", methodVisitor=" + methodVisitor + ", methodSizeHandler=" + methodSizeHandler + ", stackMapFrameHandler=" + stackMapFrameHandler + ", suppressionHandler=" + suppressionHandler + ", classReader=" + classReader + ", labels=" + labels + ", skipDispatcher=" + skipDispatcher + '}'; } } } /** * A resolved dispatcher for implementing method exit advice. */ protected abstract static class ForMethodExit extends Inlining.Resolved implements Dispatcher.Resolved.ForMethodExit { /** * The additional stack size to consider when accessing the local variable array. */ private final TypeDescription enterType; /** * Creates a new resolved dispatcher for implementing method exit advice. * * @param adviceMethod The represented advice method. * @param userFactories A list of user-defined factories for offset mappings. * @param classReader The class reader for parsing the advice method's class file. * @param enterType The type of the value supplied by the enter advice method or * a description of {@code void} if no such value exists. */ protected ForMethodExit(MethodDescription.InDefinedShape adviceMethod, List<? extends OffsetMapping.Factory> userFactories, ClassReader classReader, TypeDescription enterType) { super(adviceMethod, CompoundList.of(Arrays.asList( OffsetMapping.ForParameter.Factory.READ_WRITE, OffsetMapping.ForBoxedArguments.INSTANCE, OffsetMapping.ForThisReference.Factory.READ_WRITE, OffsetMapping.ForField.Factory.READ_WRITE, OffsetMapping.ForOrigin.Factory.INSTANCE, OffsetMapping.ForIgnored.INSTANCE, new OffsetMapping.ForEnterValue.Factory(enterType, false), OffsetMapping.ForReturnValue.Factory.READ_WRITE, OffsetMapping.ForBoxedReturnValue.Factory.READ_WRITE, OffsetMapping.ForThrowable.Factory.of(adviceMethod, false) ), userFactories), classReader, adviceMethod.getDeclaredAnnotations().ofType(OnMethodExit.class).getValue(SUPPRESS_EXIT, TypeDescription.class)); this.enterType = enterType; } /** * Resolves exit advice that handles exceptions depending on the specification of the exit advice. * * @param adviceMethod The advice method. * @param userFactories A list of user-defined factories for offset mappings. * @param classReader The class reader for parsing the advice method's class file. * @param enterType The type of the value supplied by the enter advice method or * a description of {@code void} if no such value exists. * @return An appropriate exit handler. */ protected static Resolved.ForMethodExit of(MethodDescription.InDefinedShape adviceMethod, List<? extends OffsetMapping.Factory> userFactories, ClassReader classReader, TypeDescription enterType) { TypeDescription triggeringThrowable = adviceMethod.getDeclaredAnnotations() .ofType(OnMethodExit.class) .getValue(ON_THROWABLE, TypeDescription.class); return triggeringThrowable.represents(NoExceptionHandler.class) ? new WithoutExceptionHandler(adviceMethod, userFactories, classReader, enterType) : new WithExceptionHandler(adviceMethod, userFactories, classReader, enterType, triggeringThrowable); } @Override protected MethodVisitor apply(MethodVisitor methodVisitor, MethodSizeHandler methodSizeHandler, StackMapFrameHandler.ForInstrumentedMethod stackMapFrameHandler, MethodDescription.InDefinedShape instrumentedMethod, SuppressionHandler.Bound suppressionHandler) { Map<Integer, OffsetMapping.Target> offsetMappings = new HashMap<Integer, OffsetMapping.Target>(); for (Map.Entry<Integer, OffsetMapping> entry : this.offsetMappings.entrySet()) { offsetMappings.put(entry.getKey(), entry.getValue().resolve(instrumentedMethod, OffsetMapping.Context.ForMethodExit.of(enterType))); } return new CodeTranslationVisitor.ForMethodExit(methodVisitor, methodSizeHandler.bindExit(adviceMethod, getTriggeringThrowable().represents(NoExceptionHandler.class)), stackMapFrameHandler.bindExit(adviceMethod), instrumentedMethod, adviceMethod, offsetMappings, suppressionHandler, enterType.getStackSize().getSize() + getPadding().getSize()); } @Override public Bound.ForMethodExit bind(MethodDescription.InDefinedShape instrumentedMethod, MethodVisitor methodVisitor, MethodSizeHandler methodSizeHandler, StackMapFrameHandler.ForInstrumentedMethod stackMapFrameHandler) { return new AdviceMethodInliner(instrumentedMethod, methodVisitor, methodSizeHandler, stackMapFrameHandler, suppressionHandler.bind(), classReader); } /** * Returns the additional padding this exit advice implies. * * @return The additional padding this exit advice implies. */ protected abstract StackSize getPadding(); @Override public boolean equals(Object other) { return this == other || !(other == null || getClass() != other.getClass()) && super.equals(other) && enterType == ((Inlining.Resolved.ForMethodExit) other).enterType; } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + enterType.hashCode(); return result; } /** * An advice method inliner for a method exit. */ protected class AdviceMethodInliner extends Inlining.Resolved.AdviceMethodInliner implements Bound.ForMethodExit { /** * Creates a new advice method inliner for a method exit. * * @param instrumentedMethod The instrumented method. * @param methodVisitor The method visitor for writing the instrumented method. * @param methodSizeHandler A handler for computing the method size requirements. * @param stackMapFrameHandler A handler for translating and injecting stack map frames. * @param suppressionHandler A bound suppression handler that is used for suppressing exceptions of this advice method. * @param classReader A class reader for parsing the class file containing the represented advice method. */ public AdviceMethodInliner(MethodDescription.InDefinedShape instrumentedMethod, MethodVisitor methodVisitor, MethodSizeHandler methodSizeHandler, StackMapFrameHandler.ForInstrumentedMethod stackMapFrameHandler, SuppressionHandler.Bound suppressionHandler, ClassReader classReader) { super(instrumentedMethod, methodVisitor, methodSizeHandler, stackMapFrameHandler, suppressionHandler, classReader); } @Override public void apply() { doApply(); } @Override public String toString() { return "Advice.Dispatcher.Inlining.Resolved.ForMethodExit.AdviceMethodInliner{" + "instrumentedMethod=" + instrumentedMethod + ", methodVisitor=" + methodVisitor + ", methodSizeHandler=" + methodSizeHandler + ", stackMapFrameHandler=" + stackMapFrameHandler + ", suppressionHandler=" + suppressionHandler + ", classReader=" + classReader + ", labels=" + labels + '}'; } } /** * Implementation of exit advice that handles exceptions. */ protected static class WithExceptionHandler extends Inlining.Resolved.ForMethodExit { /** * The type of the handled throwable type for which this advice is invoked. */ private final TypeDescription triggeringThrowable; /** * Creates a new resolved dispatcher for implementing method exit advice that handles exceptions. * * @param adviceMethod The represented advice method. * @param userFactories A list of user-defined factories for offset mappings. * @param classReader The class reader for parsing the advice method's class file. * @param enterType The type of the value supplied by the enter advice method or * a description of {@code void} if no such value exists. * @param triggeringThrowable The type of the handled throwable type for which this advice is invoked. */ protected WithExceptionHandler(MethodDescription.InDefinedShape adviceMethod, List<? extends OffsetMapping.Factory> userFactories, ClassReader classReader, TypeDescription enterType, TypeDescription triggeringThrowable) { super(adviceMethod, userFactories, classReader, enterType); this.triggeringThrowable = triggeringThrowable; } @Override protected StackSize getPadding() { return triggeringThrowable.getStackSize(); } @Override public TypeDescription getTriggeringThrowable() { return triggeringThrowable; } @Override public String toString() { return "Advice.Dispatcher.Inlining.Resolved.ForMethodExit.WithExceptionHandler{" + "adviceMethod=" + adviceMethod + ", offsetMappings=" + offsetMappings + ", triggeringThrowable=" + triggeringThrowable + '}'; } } /** * Implementation of exit advice that ignores exceptions. */ protected static class WithoutExceptionHandler extends Inlining.Resolved.ForMethodExit { /** * Creates a new resolved dispatcher for implementing method exit advice that does not handle exceptions. * * @param adviceMethod The represented advice method. * @param userFactories A list of user-defined factories for offset mappings. * @param classReader A class reader to query for the class file of the advice method. * @param enterType The type of the value supplied by the enter advice method or * a description of {@code void} if no such value exists. */ protected WithoutExceptionHandler(MethodDescription.InDefinedShape adviceMethod, List<? extends OffsetMapping.Factory> userFactories, ClassReader classReader, TypeDescription enterType) { super(adviceMethod, userFactories, classReader, enterType); } @Override protected StackSize getPadding() { return StackSize.ZERO; } @Override public TypeDescription getTriggeringThrowable() { return NoExceptionHandler.DESCRIPTION; } @Override public String toString() { return "Advice.Dispatcher.Inlining.Resolved.ForMethodExit.WithoutExceptionHandler{" + "adviceMethod=" + adviceMethod + ", offsetMappings=" + offsetMappings + '}'; } } } } /** * A visitor for translating an advice method's byte code for inlining into the instrumented method. */ protected abstract static class CodeTranslationVisitor extends MethodVisitor implements SuppressionHandler.ReturnValueProducer { /** * A handler for computing the method size requirements. */ private final MethodSizeHandler.ForAdvice methodSizeHandler; /** * A handler for translating and injecting stack map frames. */ protected final StackMapFrameHandler.ForAdvice stackMapFrameHandler; /** * The instrumented method. */ protected final MethodDescription.InDefinedShape instrumentedMethod; /** * The advice method. */ protected final MethodDescription.InDefinedShape adviceMethod; /** * A mapping of offsets to resolved target offsets in the instrumented method. */ private final Map<Integer, Resolved.OffsetMapping.Target> offsetMappings; /** * A handler for optionally suppressing exceptions. */ private final SuppressionHandler.Bound suppressionHandler; /** * A label indicating the end of the advice byte code. */ protected final Label endOfMethod; /** * Creates a new code translation visitor. * * @param methodVisitor A method visitor for writing the instrumented method's byte code. * @param methodSizeHandler A handler for computing the method size requirements. * @param stackMapFrameHandler A handler for translating and injecting stack map frames. * @param instrumentedMethod The instrumented method. * @param adviceMethod The advice method. * @param offsetMappings A mapping of offsets to resolved target offsets in the instrumented method. * @param suppressionHandler The suppression handler to use. */ protected CodeTranslationVisitor(MethodVisitor methodVisitor, MethodSizeHandler.ForAdvice methodSizeHandler, StackMapFrameHandler.ForAdvice stackMapFrameHandler, MethodDescription.InDefinedShape instrumentedMethod, MethodDescription.InDefinedShape adviceMethod, Map<Integer, Resolved.OffsetMapping.Target> offsetMappings, SuppressionHandler.Bound suppressionHandler) { super(Opcodes.ASM5, methodVisitor); this.methodSizeHandler = methodSizeHandler; this.stackMapFrameHandler = stackMapFrameHandler; this.instrumentedMethod = instrumentedMethod; this.adviceMethod = adviceMethod; this.offsetMappings = offsetMappings; this.suppressionHandler = suppressionHandler; endOfMethod = new Label(); } @Override public void visitParameter(String name, int modifiers) { /* do nothing */ } @Override public AnnotationVisitor visitAnnotationDefault() { return IGNORE_ANNOTATION; } @Override public AnnotationVisitor visitAnnotation(String descriptor, boolean visible) { return IGNORE_ANNOTATION; } @Override public AnnotationVisitor visitTypeAnnotation(int typeReference, TypePath typePath, String descriptor, boolean visible) { return IGNORE_ANNOTATION; } @Override public AnnotationVisitor visitParameterAnnotation(int index, String descriptor, boolean visible) { return IGNORE_ANNOTATION; } @Override public void visitAttribute(Attribute attribute) { /* do nothing */ } @Override public void visitCode() { suppressionHandler.onStart(mv, methodSizeHandler); } @Override public void visitFrame(int frameType, int localVariableLength, Object[] localVariable, int stackSize, Object[] stack) { stackMapFrameHandler.translateFrame(mv, frameType, localVariableLength, localVariable, stackSize, stack); } @Override public void visitEnd() { suppressionHandler.onEnd(mv, stackMapFrameHandler, this); mv.visitLabel(endOfMethod); onMethodReturn(); stackMapFrameHandler.injectCompletionFrame(mv, false); } @Override public void visitMaxs(int stackSize, int localVariableLength) { methodSizeHandler.recordMaxima(stackSize, localVariableLength); } @Override public void visitVarInsn(int opcode, int offset) { Resolved.OffsetMapping.Target target = offsetMappings.get(offset); if (target != null) { methodSizeHandler.recordPadding(target.resolveAccess(mv, opcode)); } else { mv.visitVarInsn(opcode, adjust(offset + instrumentedMethod.getStackSize() - adviceMethod.getStackSize())); } } @Override public void visitIincInsn(int offset, int increment) { Resolved.OffsetMapping.Target target = offsetMappings.get(offset); if (target != null) { methodSizeHandler.recordPadding(target.resolveIncrement(mv, increment)); } else { mv.visitIincInsn(adjust(offset + instrumentedMethod.getStackSize() - adviceMethod.getStackSize()), increment); } } /** * Adjusts the offset of a variable instruction within the advice method such that no arguments to * the instrumented method are overridden. * * @param offset The original offset. * @return The adjusted offset. */ protected abstract int adjust(int offset); @Override public abstract void visitInsn(int opcode); /** * Invoked after returning from the advice method. */ protected abstract void onMethodReturn(); /** * A code translation visitor that retains the return value of the represented advice method. */ protected static class ForMethodEnter extends CodeTranslationVisitor { /** * Creates a code translation visitor for translating exit advice. * * @param methodVisitor A method visitor for writing the instrumented method's byte code. * @param methodSizeHandler A handler for computing the method size requirements. * @param stackMapFrameHandler A handler for translating and injecting stack map frames. * @param instrumentedMethod The instrumented method. * @param adviceMethod The advice method. * @param offsetMappings A mapping of offsets to resolved target offsets in the instrumented method. * @param suppressionHandler The suppression handler to use. */ protected ForMethodEnter(MethodVisitor methodVisitor, MethodSizeHandler.ForAdvice methodSizeHandler, StackMapFrameHandler.ForAdvice stackMapFrameHandler, MethodDescription.InDefinedShape instrumentedMethod, MethodDescription.InDefinedShape adviceMethod, Map<Integer, Resolved.OffsetMapping.Target> offsetMappings, SuppressionHandler.Bound suppressionHandler) { super(methodVisitor, methodSizeHandler, stackMapFrameHandler, instrumentedMethod, adviceMethod, offsetMappings, suppressionHandler); } @Override public void visitInsn(int opcode) { switch (opcode) { case Opcodes.RETURN: case Opcodes.IRETURN: case Opcodes.LRETURN: case Opcodes.ARETURN: case Opcodes.FRETURN: case Opcodes.DRETURN: mv.visitJumpInsn(Opcodes.GOTO, endOfMethod); break; default: mv.visitInsn(opcode); } } @Override protected int adjust(int offset) { return offset; } @Override public void onDefaultValue() { if (adviceMethod.getReturnType().represents(boolean.class) || adviceMethod.getReturnType().represents(byte.class) || adviceMethod.getReturnType().represents(short.class) || adviceMethod.getReturnType().represents(char.class) || adviceMethod.getReturnType().represents(int.class)) { mv.visitInsn(Opcodes.ICONST_0); } else if (adviceMethod.getReturnType().represents(long.class)) { mv.visitInsn(Opcodes.LCONST_0); } else if (adviceMethod.getReturnType().represents(float.class)) { mv.visitInsn(Opcodes.FCONST_0); } else if (adviceMethod.getReturnType().represents(double.class)) { mv.visitInsn(Opcodes.DCONST_0); } else if (!adviceMethod.getReturnType().represents(void.class)) { mv.visitInsn(Opcodes.ACONST_NULL); } } @Override protected void onMethodReturn() { Type returnType = Type.getType(adviceMethod.getReturnType().asErasure().getDescriptor()); if (!returnType.equals(Type.VOID_TYPE)) { stackMapFrameHandler.injectReturnFrame(mv); mv.visitVarInsn(returnType.getOpcode(Opcodes.ISTORE), instrumentedMethod.getStackSize()); } } @Override public String toString() { return "Advice.Dispatcher.Inlining.CodeTranslationVisitor.ForMethodEnter{" + "instrumentedMethod=" + instrumentedMethod + ", adviceMethod=" + adviceMethod + '}'; } } /** * A code translation visitor that discards the return value of the represented advice method. */ protected static class ForMethodExit extends CodeTranslationVisitor { /** * The padding after the instrumented method's arguments in the local variable array. */ private final int padding; /** * Creates a code translation visitor for translating exit advice. * * @param methodVisitor A method visitor for writing the instrumented method's byte code. * @param methodSizeHandler A handler for computing the method size requirements. * @param stackMapFrameHandler A handler for translating and injecting stack map frames. * @param instrumentedMethod The instrumented method. * @param adviceMethod The advice method. * @param offsetMappings A mapping of offsets to resolved target offsets in the instrumented method. * @param suppressionHandler The suppression handler to use. * @param padding The padding after the instrumented method's arguments in the local variable array. */ protected ForMethodExit(MethodVisitor methodVisitor, MethodSizeHandler.ForAdvice methodSizeHandler, StackMapFrameHandler.ForAdvice stackMapFrameHandler, MethodDescription.InDefinedShape instrumentedMethod, MethodDescription.InDefinedShape adviceMethod, Map<Integer, Resolved.OffsetMapping.Target> offsetMappings, SuppressionHandler.Bound suppressionHandler, int padding) { super(methodVisitor, methodSizeHandler, stackMapFrameHandler, instrumentedMethod, adviceMethod, offsetMappings, suppressionHandler); this.padding = padding; } @Override public void visitInsn(int opcode) { switch (opcode) { case Opcodes.RETURN: break; case Opcodes.IRETURN: case Opcodes.ARETURN: case Opcodes.FRETURN: mv.visitInsn(Opcodes.POP); break; case Opcodes.LRETURN: case Opcodes.DRETURN: mv.visitInsn(Opcodes.POP2); break; default: mv.visitInsn(opcode); return; } mv.visitJumpInsn(Opcodes.GOTO, endOfMethod); } @Override protected int adjust(int offset) { return instrumentedMethod.getReturnType().getStackSize().getSize() + padding + offset; } @Override public void onDefaultValue() { /* do nothing */ } @Override protected void onMethodReturn() { /* do nothing */ } @Override public String toString() { return "Advice.Dispatcher.Inlining.CodeTranslationVisitor.ForMethodExit{" + "instrumentedMethod=" + instrumentedMethod + ", adviceMethod=" + adviceMethod + ", padding=" + padding + '}'; } } } } /** * A dispatcher for an advice method that is being invoked from the instrumented method. */ class Delegating implements Unresolved { /** * The advice method. */ protected final MethodDescription.InDefinedShape adviceMethod; /** * Creates a new delegating advice dispatcher. * * @param adviceMethod The advice method. */ protected Delegating(MethodDescription.InDefinedShape adviceMethod) { this.adviceMethod = adviceMethod; } @Override public boolean isAlive() { return true; } @Override public boolean isBinary() { return false; } @Override public Dispatcher.Resolved.ForMethodEnter asMethodEnter(List<? extends OffsetMapping.Factory> userFactories, ClassReader classReader) { return new Resolved.ForMethodEnter(adviceMethod, userFactories); } @Override public Dispatcher.Resolved.ForMethodExit asMethodExitTo(List<? extends OffsetMapping.Factory> userFactories, ClassReader classReader, Dispatcher.Resolved.ForMethodEnter dispatcher) { return Resolved.ForMethodExit.of(adviceMethod, userFactories, dispatcher.getEnterType()); } @Override public boolean equals(Object other) { return this == other || !(other == null || getClass() != other.getClass()) && adviceMethod.equals(((Delegating) other).adviceMethod); } @Override public int hashCode() { return adviceMethod.hashCode(); } @Override public String toString() { return "Advice.Dispatcher.Delegating{" + "adviceMethod=" + adviceMethod + '}'; } /** * A resolved version of a dispatcher. * * @param <T> The type of advice dispatcher that is bound. */ protected abstract static class Resolved<T extends Bound> implements Dispatcher.Resolved { /** * Indicates a read-only mapping for an offset. */ private static final boolean READ_ONLY = true; /** * The represented advice method. */ protected final MethodDescription.InDefinedShape adviceMethod; /** * An unresolved mapping of offsets of the advice method based on the annotations discovered on each method parameter. */ protected final List<OffsetMapping> offsetMappings; /** * The suppression handler to use. */ protected final SuppressionHandler suppressionHandler; /** * Creates a new resolved version of a dispatcher. * * @param adviceMethod The represented advice method. * @param factories A list of factories to resolve for the parameters of the advice method. * @param throwableType The type to handle by a suppression handler or {@link NoExceptionHandler} to not handle any exceptions. */ protected Resolved(MethodDescription.InDefinedShape adviceMethod, List<OffsetMapping.Factory> factories, TypeDescription throwableType) { this.adviceMethod = adviceMethod; offsetMappings = new ArrayList<OffsetMapping>(adviceMethod.getParameters().size()); for (ParameterDescription.InDefinedShape parameterDescription : adviceMethod.getParameters()) { OffsetMapping offsetMapping = OffsetMapping.Factory.UNDEFINED; for (OffsetMapping.Factory factory : factories) { OffsetMapping possible = factory.make(parameterDescription); if (possible != null) { if (offsetMapping == null) { offsetMapping = possible; } else { throw new IllegalStateException(parameterDescription + " is bound to both " + possible + " and " + offsetMapping); } } } offsetMappings.add(offsetMapping == null ? new OffsetMapping.ForParameter(parameterDescription.getIndex(), READ_ONLY, parameterDescription.getType().asErasure()) : offsetMapping); } suppressionHandler = SuppressionHandler.Suppressing.of(throwableType); } @Override public boolean isAlive() { return true; } @Override public T bind(MethodDescription.InDefinedShape instrumentedMethod, MethodVisitor methodVisitor, MethodSizeHandler methodSizeHandler, StackMapFrameHandler.ForInstrumentedMethod stackMapFrameHandler) { if (!adviceMethod.isVisibleTo(instrumentedMethod.getDeclaringType())) { throw new IllegalStateException(adviceMethod + " is not visible to " + instrumentedMethod.getDeclaringType()); } return resolve(instrumentedMethod, methodVisitor, methodSizeHandler, stackMapFrameHandler); } /** * Binds this dispatcher for resolution to a specific method. * * @param instrumentedMethod The instrumented method that is being bound. * @param methodVisitor The method visitor for writing to the instrumented method. * @param methodSizeHandler A handler for computing the method size requirements. * @param stackMapFrameHandler A handler for translating and injecting stack map frames. * @return An appropriate bound advice dispatcher. */ protected abstract T resolve(MethodDescription.InDefinedShape instrumentedMethod, MethodVisitor methodVisitor, MethodSizeHandler methodSizeHandler, StackMapFrameHandler.ForInstrumentedMethod stackMapFrameHandler); @Override public boolean equals(Object other) { if (this == other) return true; if (other == null || getClass() != other.getClass()) return false; Delegating.Resolved resolved = (Delegating.Resolved) other; return adviceMethod.equals(resolved.adviceMethod) && offsetMappings.equals(resolved.offsetMappings); } @Override public int hashCode() { int result = adviceMethod.hashCode(); result = 31 * result + offsetMappings.hashCode(); return result; } /** * A bound advice method that copies the code by first extracting the exception table and later appending the * code of the method without copying any meta data. */ protected abstract static class AdviceMethodWriter implements Bound, SuppressionHandler.ReturnValueProducer { /** * Indicates an empty local variable array which is not required for calling a method. */ private static final int EMPTY = 0; /** * The advice method. */ protected final MethodDescription.InDefinedShape adviceMethod; /** * The instrumented method. */ protected final MethodDescription.InDefinedShape instrumentedMethod; /** * The offset mappings available to this advice. */ private final List<OffsetMapping.Target> offsetMappings; /** * The method visitor for writing the instrumented method. */ protected final MethodVisitor methodVisitor; /** * A handler for computing the method size requirements. */ private final MethodSizeHandler.ForAdvice methodSizeHandler; /** * A handler for translating and injecting stack map frmes. */ protected final StackMapFrameHandler.ForAdvice stackMapFrameHandler; /** * A bound suppression handler that is used for suppressing exceptions of this advice method. */ private final SuppressionHandler.Bound suppressionHandler; /** * Creates a new advice method writer. * * @param adviceMethod The advice method. * @param instrumentedMethod The instrumented method. * @param offsetMappings The offset mappings available to this advice. * @param methodVisitor The method visitor for writing the instrumented method. * @param methodSizeHandler A handler for computing the method size requirements. * @param stackMapFrameHandler A handler for translating and injecting stack map frames. * @param suppressionHandler A bound suppression handler that is used for suppressing exceptions of this advice method. */ protected AdviceMethodWriter(MethodDescription.InDefinedShape adviceMethod, MethodDescription.InDefinedShape instrumentedMethod, List<OffsetMapping.Target> offsetMappings, MethodVisitor methodVisitor, MethodSizeHandler.ForAdvice methodSizeHandler, StackMapFrameHandler.ForAdvice stackMapFrameHandler, SuppressionHandler.Bound suppressionHandler) { this.adviceMethod = adviceMethod; this.instrumentedMethod = instrumentedMethod; this.offsetMappings = offsetMappings; this.methodVisitor = methodVisitor; this.methodSizeHandler = methodSizeHandler; this.stackMapFrameHandler = stackMapFrameHandler; this.suppressionHandler = suppressionHandler; } @Override public void prepare() { suppressionHandler.onPrepare(methodVisitor); } /** * Writes the advice method invocation. */ protected void doApply() { suppressionHandler.onStart(methodVisitor, methodSizeHandler); int index = 0, currentStackSize = 0, maximumStackSize = 0; for (OffsetMapping.Target offsetMapping : offsetMappings) { Type type = Type.getType(adviceMethod.getParameters().get(index++).getType().asErasure().getDescriptor()); currentStackSize += type.getSize(); maximumStackSize = Math.max(maximumStackSize, currentStackSize + offsetMapping.resolveAccess(methodVisitor, type.getOpcode(Opcodes.ILOAD))); } methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, adviceMethod.getDeclaringType().getInternalName(), adviceMethod.getInternalName(), adviceMethod.getDescriptor(), false); onMethodReturn(); suppressionHandler.onEndSkipped(methodVisitor, stackMapFrameHandler, this); stackMapFrameHandler.injectCompletionFrame(methodVisitor, false); methodSizeHandler.recordMaxima(Math.max(maximumStackSize, adviceMethod.getReturnType().getStackSize().getSize()), EMPTY); } /** * Invoked directly after the advice method was called. */ protected abstract void onMethodReturn(); @Override public String toString() { return "Advice.Dispatcher.Delegating.Resolved.AdviceMethodWriter{" + "instrumentedMethod=" + instrumentedMethod + ", methodVisitor=" + methodVisitor + ", methodSizeHandler=" + methodSizeHandler + ", stackMapFrameHandler=" + stackMapFrameHandler + ", suppressionHandler=" + suppressionHandler + '}'; } /** * An advice method writer for a method entry. */ protected static class ForMethodEnter extends AdviceMethodWriter implements Bound.ForMethodEnter { /** * The skip dispatcher to use. */ private final Resolved.ForMethodEnter.SkipDispatcher skipDispatcher; /** * Creates a new advice method writer. * * @param adviceMethod The advice method. * @param instrumentedMethod The instrumented method. * @param offsetMappings The offset mappings available to this advice. * @param methodVisitor The method visitor for writing the instrumented method. * @param methodSizeHandler A handler for computing the method size requirements. * @param stackMapFrameHandler A handler for translating and injecting stack map frames. * @param suppressionHandler A bound suppression handler that is used for suppressing exceptions of this advice method. * @param skipDispatcher The skip dispatcher to use. */ protected ForMethodEnter(MethodDescription.InDefinedShape adviceMethod, MethodDescription.InDefinedShape instrumentedMethod, List<OffsetMapping.Target> offsetMappings, MethodVisitor methodVisitor, MethodSizeHandler.ForAdvice methodSizeHandler, StackMapFrameHandler.ForAdvice stackMapFrameHandler, SuppressionHandler.Bound suppressionHandler, Resolved.ForMethodEnter.SkipDispatcher skipDispatcher) { super(adviceMethod, instrumentedMethod, offsetMappings, methodVisitor, methodSizeHandler, stackMapFrameHandler, suppressionHandler); this.skipDispatcher = skipDispatcher; } @Override protected void onMethodReturn() { if (adviceMethod.getReturnType().represents(boolean.class) || adviceMethod.getReturnType().represents(byte.class) || adviceMethod.getReturnType().represents(short.class) || adviceMethod.getReturnType().represents(char.class) || adviceMethod.getReturnType().represents(int.class)) { methodVisitor.visitVarInsn(Opcodes.ISTORE, instrumentedMethod.getStackSize()); } else if (adviceMethod.getReturnType().represents(long.class)) { methodVisitor.visitVarInsn(Opcodes.LSTORE, instrumentedMethod.getStackSize()); } else if (adviceMethod.getReturnType().represents(float.class)) { methodVisitor.visitVarInsn(Opcodes.FSTORE, instrumentedMethod.getStackSize()); } else if (adviceMethod.getReturnType().represents(double.class)) { methodVisitor.visitVarInsn(Opcodes.DSTORE, instrumentedMethod.getStackSize()); } else if (!adviceMethod.getReturnType().represents(void.class)) { methodVisitor.visitVarInsn(Opcodes.ASTORE, instrumentedMethod.getStackSize()); } } @Override public void apply(SkipHandler skipHandler) { doApply(); skipDispatcher.apply(methodVisitor, stackMapFrameHandler, instrumentedMethod, skipHandler); } @Override public void onDefaultValue() { if (adviceMethod.getReturnType().represents(boolean.class) || adviceMethod.getReturnType().represents(byte.class) || adviceMethod.getReturnType().represents(short.class) || adviceMethod.getReturnType().represents(char.class) || adviceMethod.getReturnType().represents(int.class)) { methodVisitor.visitInsn(Opcodes.ICONST_0); methodVisitor.visitVarInsn(Opcodes.ISTORE, instrumentedMethod.getStackSize()); } else if (adviceMethod.getReturnType().represents(long.class)) { methodVisitor.visitInsn(Opcodes.LCONST_0); methodVisitor.visitVarInsn(Opcodes.LSTORE, instrumentedMethod.getStackSize()); } else if (adviceMethod.getReturnType().represents(float.class)) { methodVisitor.visitInsn(Opcodes.FCONST_0); methodVisitor.visitVarInsn(Opcodes.FSTORE, instrumentedMethod.getStackSize()); } else if (adviceMethod.getReturnType().represents(double.class)) { methodVisitor.visitInsn(Opcodes.DCONST_0); methodVisitor.visitVarInsn(Opcodes.DSTORE, instrumentedMethod.getStackSize()); } else if (!adviceMethod.getReturnType().represents(void.class)) { methodVisitor.visitInsn(Opcodes.ACONST_NULL); methodVisitor.visitVarInsn(Opcodes.ASTORE, instrumentedMethod.getStackSize()); } } @Override public String toString() { return "Advice.Dispatcher.Delegating.Resolved.AdviceMethodWriter.ForMethodEnter{" + "instrumentedMethod=" + instrumentedMethod + ", adviceMethod=" + adviceMethod + "}"; } } /** * An advice method writer for a method exit. */ protected static class ForMethodExit extends AdviceMethodWriter implements Bound.ForMethodExit { /** * Creates a new advice method writer. * * @param adviceMethod The advice method. * @param instrumentedMethod The instrumented method. * @param offsetMappings The offset mappings available to this advice. * @param methodVisitor The method visitor for writing the instrumented method. * @param methodSizeHandler A handler for computing the method size requirements. * @param stackMapFrameHandler A handler for translating and injecting stack map frames. * @param suppressionHandler A bound suppression handler that is used for suppressing exceptions of this advice method. */ protected ForMethodExit(MethodDescription.InDefinedShape adviceMethod, MethodDescription.InDefinedShape instrumentedMethod, List<OffsetMapping.Target> offsetMappings, MethodVisitor methodVisitor, MethodSizeHandler.ForAdvice methodSizeHandler, StackMapFrameHandler.ForAdvice stackMapFrameHandler, SuppressionHandler.Bound suppressionHandler) { super(adviceMethod, instrumentedMethod, offsetMappings, methodVisitor, methodSizeHandler, stackMapFrameHandler, suppressionHandler); } @Override public void apply() { doApply(); } @Override protected void onMethodReturn() { switch (adviceMethod.getReturnType().getStackSize()) { case ZERO: return; case SINGLE: methodVisitor.visitInsn(Opcodes.POP); return; case DOUBLE: methodVisitor.visitInsn(Opcodes.POP2); return; default: throw new IllegalStateException("Unexpected size: " + adviceMethod.getReturnType().getStackSize()); } } @Override public void onDefaultValue() { /* do nothing */ } @Override public String toString() { return "Advice.Dispatcher.Delegating.Resolved.AdviceMethodWriter.ForMethodExit{" + "instrumentedMethod=" + instrumentedMethod + ", adviceMethod=" + adviceMethod + "}"; } } } /** * A resolved dispatcher for implementing method enter advice. */ protected static class ForMethodEnter extends Delegating.Resolved<Bound.ForMethodEnter> implements Dispatcher.Resolved.ForMethodEnter { /** * The skip dispatcher to use. */ private final SkipDispatcher skipDispatcher; /** * Creates a new resolved dispatcher for implementing method enter advice. * * @param adviceMethod The represented advice method. * @param userFactories A list of user-defined factories for offset mappings. */ @SuppressWarnings("all") // In absence of @SafeVarargs for Java 6 protected ForMethodEnter(MethodDescription.InDefinedShape adviceMethod, List<? extends OffsetMapping.Factory> userFactories) { super(adviceMethod, CompoundList.of(Arrays.asList(OffsetMapping.ForParameter.Factory.READ_ONLY, OffsetMapping.ForBoxedArguments.INSTANCE, OffsetMapping.ForThisReference.Factory.READ_ONLY, OffsetMapping.ForField.Factory.READ_ONLY, OffsetMapping.ForOrigin.Factory.INSTANCE, OffsetMapping.ForIgnored.INSTANCE, new OffsetMapping.Illegal(Thrown.class, Enter.class, Return.class, BoxedReturn.class)), userFactories), adviceMethod.getDeclaredAnnotations().ofType(OnMethodEnter.class).getValue(SUPPRESS_ENTER, TypeDescription.class)); skipDispatcher = SkipDispatcher.of(adviceMethod); } @Override public TypeDescription getEnterType() { return adviceMethod.getReturnType().asErasure(); } @Override protected Bound.ForMethodEnter resolve(MethodDescription.InDefinedShape instrumentedMethod, MethodVisitor methodVisitor, MethodSizeHandler methodSizeHandler, StackMapFrameHandler.ForInstrumentedMethod stackMapFrameHandler) { List<OffsetMapping.Target> offsetMappings = new ArrayList<OffsetMapping.Target>(this.offsetMappings.size()); for (OffsetMapping offsetMapping : this.offsetMappings) { offsetMappings.add(offsetMapping.resolve(instrumentedMethod, OffsetMapping.Context.ForMethodEntry.of(instrumentedMethod))); } return new AdviceMethodWriter.ForMethodEnter(adviceMethod, instrumentedMethod, offsetMappings, methodVisitor, methodSizeHandler.bindEntry(adviceMethod), stackMapFrameHandler.bindEntry(adviceMethod), suppressionHandler.bind(), skipDispatcher); } @Override public boolean equals(Object object) { if (this == object) return true; if (object == null || getClass() != object.getClass()) return false; if (!super.equals(object)) return false; Delegating.Resolved.ForMethodEnter that = (Delegating.Resolved.ForMethodEnter) object; return skipDispatcher == that.skipDispatcher; } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + skipDispatcher.hashCode(); return result; } @Override public String toString() { return "Advice.Dispatcher.Delegating.Resolved.ForMethodEnter{" + "adviceMethod=" + adviceMethod + ", offsetMappings=" + offsetMappings + ", skipDispatcher=" + skipDispatcher + '}'; } } /** * A resolved dispatcher for implementing method exit advice. */ protected abstract static class ForMethodExit extends Delegating.Resolved<Bound.ForMethodExit> implements Dispatcher.Resolved.ForMethodExit { /** * The additional stack size to consider when accessing the local variable array. */ private final TypeDescription enterType; /** * Creates a new resolved dispatcher for implementing method exit advice. * * @param adviceMethod The represented advice method. * @param userFactories A list of user-defined factories for offset mappings. * @param enterType The type of the value supplied by the enter advice method or * a description of {@code void} if no such value exists. */ protected ForMethodExit(MethodDescription.InDefinedShape adviceMethod, List<? extends OffsetMapping.Factory> userFactories, TypeDescription enterType) { super(adviceMethod, CompoundList.of(Arrays.asList( OffsetMapping.ForParameter.Factory.READ_ONLY, OffsetMapping.ForBoxedArguments.INSTANCE, OffsetMapping.ForThisReference.Factory.READ_ONLY, OffsetMapping.ForField.Factory.READ_ONLY, OffsetMapping.ForOrigin.Factory.INSTANCE, OffsetMapping.ForIgnored.INSTANCE, new OffsetMapping.ForEnterValue.Factory(enterType, true), OffsetMapping.ForReturnValue.Factory.READ_ONLY, OffsetMapping.ForBoxedReturnValue.Factory.READ_ONLY, OffsetMapping.ForThrowable.Factory.of(adviceMethod, true) ), userFactories), adviceMethod.getDeclaredAnnotations().ofType(OnMethodExit.class).getValue(SUPPRESS_EXIT, TypeDescription.class)); this.enterType = enterType; } /** * Resolves exit advice that handles exceptions depending on the specification of the exit advice. * * @param adviceMethod The advice method. * @param userFactories A list of user-defined factories for offset mappings. * @param enterType The type of the value supplied by the enter advice method or * a description of {@code void} if no such value exists. * @return An appropriate exit handler. */ protected static Resolved.ForMethodExit of(MethodDescription.InDefinedShape adviceMethod, List<? extends OffsetMapping.Factory> userFactories, TypeDescription enterType) { TypeDescription triggeringThrowable = adviceMethod.getDeclaredAnnotations() .ofType(OnMethodExit.class) .getValue(ON_THROWABLE, TypeDescription.class); return triggeringThrowable.represents(NoExceptionHandler.class) ? new WithoutExceptionHandler(adviceMethod, userFactories, enterType) : new WithExceptionHandler(adviceMethod, userFactories, enterType, triggeringThrowable); } @Override protected Bound.ForMethodExit resolve(MethodDescription.InDefinedShape instrumentedMethod, MethodVisitor methodVisitor, MethodSizeHandler methodSizeHandler, StackMapFrameHandler.ForInstrumentedMethod stackMapFrameHandler) { List<OffsetMapping.Target> offsetMappings = new ArrayList<OffsetMapping.Target>(this.offsetMappings.size()); for (OffsetMapping offsetMapping : this.offsetMappings) { offsetMappings.add(offsetMapping.resolve(instrumentedMethod, OffsetMapping.Context.ForMethodExit.of(enterType))); } return new AdviceMethodWriter.ForMethodExit(adviceMethod, instrumentedMethod, offsetMappings, methodVisitor, methodSizeHandler.bindExit(adviceMethod, getTriggeringThrowable().represents(NoExceptionHandler.class)), stackMapFrameHandler.bindExit(adviceMethod), suppressionHandler.bind()); } @Override public boolean equals(Object other) { return this == other || !(other == null || getClass() != other.getClass()) && super.equals(other) && enterType == ((Delegating.Resolved.ForMethodExit) other).enterType; } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + enterType.hashCode(); return result; } /** * Implementation of exit advice that handles exceptions. */ protected static class WithExceptionHandler extends Delegating.Resolved.ForMethodExit { /** * The type of the handled throwable type for which this advice is invoked. */ private final TypeDescription triggeringThrowable; /** * Creates a new resolved dispatcher for implementing method exit advice that handles exceptions. * * @param adviceMethod The represented advice method. * @param userFactories A list of user-defined factories for offset mappings. * @param enterType The type of the value supplied by the enter advice method or * a description of {@code void} if no such value exists. * @param triggeringThrowable The type of the handled throwable type for which this advice is invoked. */ protected WithExceptionHandler(MethodDescription.InDefinedShape adviceMethod, List<? extends OffsetMapping.Factory> userFactories, TypeDescription enterType, TypeDescription triggeringThrowable) { super(adviceMethod, userFactories, enterType); this.triggeringThrowable = triggeringThrowable; } @Override public TypeDescription getTriggeringThrowable() { return triggeringThrowable; } @Override public String toString() { return "Advice.Dispatcher.Delegating.Resolved.ForMethodExit.WithExceptionHandler{" + "adviceMethod=" + adviceMethod + ", offsetMappings=" + offsetMappings + ", triggeringThrowable=" + triggeringThrowable + '}'; } } /** * Implementation of exit advice that ignores exceptions. */ protected static class WithoutExceptionHandler extends Delegating.Resolved.ForMethodExit { /** * Creates a new resolved dispatcher for implementing method exit advice that does not handle exceptions. * * @param adviceMethod The represented advice method. * @param userFactories A list of user-defined factories for offset mappings. * @param enterType The type of the value supplied by the enter advice method or * a description of {@code void} if no such value exists. */ protected WithoutExceptionHandler(MethodDescription.InDefinedShape adviceMethod, List<? extends OffsetMapping.Factory> userFactories, TypeDescription enterType) { super(adviceMethod, userFactories, enterType); } @Override public TypeDescription getTriggeringThrowable() { return NoExceptionHandler.DESCRIPTION; } @Override public String toString() { return "Advice.Dispatcher.Delegating.Resolved.ForMethodExit.WithoutExceptionHandler{" + "adviceMethod=" + adviceMethod + ", offsetMappings=" + offsetMappings + '}'; } } } } } } /** * <p> * Indicates that this method should be inlined before the matched method is invoked. Any class must declare * at most one method with this annotation. The annotated method must be static. When instrumenting constructors, * the {@code this} values can only be accessed for writing fields but not for reading fields or invoking methods. * </p> * <p> * The annotated method can return a value that is made accessible to another method annotated by {@link OnMethodExit}. * </p> * * @see Advice * @see Argument * @see This */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface OnMethodEnter { /** * Determines if the annotated method should be inlined into the instrumented method or invoked from it. When a method * is inlined, its byte code is copied into the body of the target method. this makes it is possible to execute code * with the visibility privileges of the instrumented method while loosing the privileges of the declared method methods. * When a method is not inlined, it is invoked similarly to a common Java method call. Note that it is not possible to * set breakpoints within a method when it is inlined as no debugging information is copied from the advice method into * the instrumented method. * * @return {@code true} if the annotated method should be inlined into the instrumented method. */ boolean inline() default true; /** * Indicates that this advice should suppress any {@link Throwable} type being thrown during the advice's execution. * * @return The type of {@link Throwable} to suppress. */ Class<? extends Throwable> suppress() default NoExceptionHandler.class; /** * If set to {@code true}, the instrumented method is skipped if the annotated advice method returns {@code true}. For this, * the annotated method must declare a return type {@code boolean}. If this is not the case, an exception is thrown during * construction of an {@link Advice}. * * @return {@code true} if the instrumented method should be skipped if this advice method returns {@code true}. */ boolean skipIfTrue() default false; } /** * <p> * Indicates that this method should be executed before exiting the instrumented method. Any class must declare * at most one method with this annotation. The annotated method must be static. * </p> * <p> * By default, the annotated method is not invoked if the instrumented method terminates exceptionally. This behavior * can be changed by setting the {@link OnMethodExit#onThrowable()} property to an exception type for which this advice * method should be invoked. By setting the value to {@link Throwable}, the advice method is always invoked. * </p> * * @see Advice * @see Argument * @see This * @see Enter * @see Return * @see Thrown */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface OnMethodExit { /** * Determines if the annotated method should be inlined into the instrumented method or invoked from it. When a method * is inlined, its byte code is copied into the body of the target method. this makes it is possible to execute code * with the visibility privileges of the instrumented method while loosing the privileges of the declared method methods. * When a method is not inlined, it is invoked similarly to a common Java method call. Note that it is not possible to * set breakpoints within a method when it is inlined as no debugging information is copied from the advice method into * the instrumented method. * * @return {@code true} if the annotated method should be inlined into the instrumented method. */ boolean inline() default true; /** * Indicates that this advice should suppress any {@link Throwable} type being thrown during the advice's execution. * * @return The type of {@link Throwable} to suppress. */ Class<? extends Throwable> suppress() default NoExceptionHandler.class; /** * Indicates a {@link Throwable} super type for which this exit advice is invoked if it was thrown from the instrumented method. * If an exception is thrown, it is available via the {@link Thrown} parameter annotation. If a method returns exceptionally, * any parameter annotated with {@link Return} is assigned the parameter type's default value. * * @return The type of {@link Throwable} for which this exit advice handler is invoked. */ Class<? extends Throwable> onThrowable() default NoExceptionHandler.class; } /** * Indicates that the annotated parameter should be mapped to the parameter with index {@link Argument#value()} of * the instrumented method. * * @see Advice * @see OnMethodEnter * @see OnMethodExit */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.PARAMETER) public @interface Argument { /** * Returns the index of the mapped parameter. * * @return The index of the mapped parameter. */ int value(); /** * Indicates if it is possible to write to this parameter. If this property is set to {@code false}, the annotated * type must be equal to the parameter of the instrumented method. If this property is set to {@code true}, the * annotated parameter can be any super type of the instrumented methods parameter. * * @return {@code true} if this parameter is read-only. */ boolean readOnly() default true; } /** * <p> * Indicates that the annotated parameter should be mapped to the {@code this} reference of the instrumented method. * </p> * <p> * <b>Important</b>: Parameters with this option must not be used when from a constructor in combination with * {@link OnMethodEnter} where the {@code this} reference is not available. * </p> * * @see Advice * @see OnMethodEnter * @see OnMethodExit */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.PARAMETER) public @interface This { /** * Indicates if it is possible to write to this parameter. If this property is set to {@code false}, the annotated * type must be equal to the type declaring the instrumented method. If this property is set to {@code true}, the * annotated parameter can be any super type of the instrumented method's declaring type. * * @return {@code true} if this parameter is read-only. */ boolean readOnly() default true; /** * Determines if the parameter should be assigned {@code null} if the instrumented method is static. * * @return {@code true} if the value assignment is optional. */ boolean optional() default false; } /** * <p> * Indicates that the annotated parameter should be mapped to a field in the scope of the instrumented method. * </p> * <p> * <b>Important</b>: Parameters with this option must not be used when from a constructor in combination with * {@link OnMethodEnter} and a non-static field where the {@code this} reference is not available. * </p> * <p> * <b>Note</b>: As the mapping is virtual, Byte Buddy might be required to reserve more space on the operand stack than the * optimal value when accessing this parameter. This does not normally matter as the additional space requirement is minimal. * However, if the runtime performance of class creation is secondary, one can require ASM to recompute the optimal frames by * setting {@link ClassWriter#COMPUTE_MAXS}. This is however only relevant when writing to a non-static field. * </p> * * @see Advice * @see OnMethodEnter * @see OnMethodExit */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.PARAMETER) public @interface FieldValue { /** * Returns the name of the field. * * @return The name of the field. */ String value(); /** * Returns the type that declares the field that should be mapped to the annotated parameter. If this property * is set to {@code void}, the field is looked up implicitly within the instrumented class's class hierarchy. * * @return The type that declares the field or {@code void} if this type should be determined implicitly. */ Class<?> declaringType() default void.class; /** * Indicates if it is possible to write to this parameter. If this property is set to {@code false}, the annotated * type must be equal to the mapped field type. If this property is set to {@code true}, the annotated parameter * can be any super type of the field type. * * @return {@code true} if this parameter is read-only. */ boolean readOnly() default true; } /** * Indicates that the annotated parameter should be mapped to a string representation of the instrumented method or * to a constant representing the {@link Class} declaring the method. * * @see Advice * @see OnMethodEnter * @see OnMethodExit */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.PARAMETER) public @interface Origin { /** * Indicates that the origin string should be indicated by the {@link Object#toString()} representation of the instrumented method. */ String DEFAULT = ""; /** * Returns the pattern the annotated parameter should be assigned. By default, the {@link Origin#toString()} representation * of the method is assigned. Alternatively, a pattern can be assigned where: * <ul> * <li>{@code #t} inserts the method's declaring type.</li> * <li>{@code #m} inserts the name of the method ({@code <init>} for constructors and {@code <clinit>} for static initializers).</li> * <li>{@code #d} for the method's descriptor.</li> * <li>{@code #s} for the method's signature.</li> * <li>{@code #r} for the method's return type.</li> * </ul> * Any other {@code #} character must be escaped by {@code \} which can be escaped by itself. This property is ignored if the annotated * parameter is of type {@link Class}. * * @return The pattern the annotated parameter should be assigned. */ String value() default DEFAULT; } /** * Indicates that the annotated parameter should always return a default value (i.e. {@code 0} for numeric values, {@code false} * for {@code boolean} types and {@code null} for reference types). * * @see Advice * @see OnMethodEnter * @see OnMethodExit */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.PARAMETER) public @interface Ignored { /* empty */ } /** * Indicates that the annotated parameter should be mapped to the value that is returned by the advice method that is annotated * by {@link OnMethodEnter}. * * @see Advice * @see OnMethodExit */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.PARAMETER) public @interface Enter { /** * Indicates if it is possible to write to this parameter. If this property is set to {@code false}, the annotated * type must be equal to the parameter of the instrumented method. If this property is set to {@code true}, the * annotated parameter can be any super type of the instrumented methods parameter. * * @return {@code true} if this parameter is read-only. */ boolean readOnly() default true; } /** * Indicates that the annotated parameter should be mapped to the return value of the instrumented method. If the instrumented * method terminates exceptionally, the type's default value is assigned to the parameter, i.e. {@code 0} for numeric types * and {@code null} for reference types. * * @see Advice * @see OnMethodExit */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.PARAMETER) public @interface Return { /** * Indicates if it is possible to write to this parameter. If this property is set to {@code false}, the annotated * type must be equal to the parameter of the instrumented method. If this property is set to {@code true}, the * annotated parameter can be any super type of the instrumented methods parameter. * * @return {@code true} if this parameter is read-only. */ boolean readOnly() default true; } @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.PARAMETER) public @interface BoxedReturn { /** * Determines if it should be possible to write to the boxed return value. When writing to the return value, the assigned type * is casted to the instrumented method's return type. If the method's return type is primitive, the value is unboxed from the * primitive return type's wrapper type after casting to the latter type. If the method is {@code void}, the assigned value is * simply dropped. * * @return {@code true} if it should be possible to write to the annotated parameter. */ boolean readOnly() default true; } @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.PARAMETER) public @interface BoxedArguments { /* boxed */ } /** * Indicates that the annotated parameter should be mapped to the return value of the instrumented method. For this to be valid, * the parameter must be of type {@link Throwable}. If the instrumented method terminates regularly, {@code null} is assigned to * the annotated parameter. * * @see Advice * @see OnMethodExit */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.PARAMETER) public @interface Thrown { boolean readOnly() default true; } /** * <p> * A dynamic value allows to bind parameters of an {@link Advice} method to a custom, constant value. * </p> * <p>The mapped value must be a constant value that can be embedded into a Java class file. This holds for all primitive types, * instances of {@link String} and for {@link Class} instances as well as their unloaded {@link TypeDescription} representations. * </p> * * @param <T> The type of the annotation this dynamic value requires to provide a mapping. * @see WithCustomMapping */ public interface DynamicValue<T extends Annotation> { /** * Resolves a constant value that is mapped to a parameter that is annotated with a custom bound annotation. * * @param instrumentedMethod The instrumented method onto which this advice is applied. * @param target The target parameter that is bound. * @param annotation The annotation that triggered this binding. * @param initialized {@code true} if the method is initialized when the value is bound, i.e. that the value is not * supplied to a constructor before the super constructor was invoked. * @return The constant pool value that is bound to the supplied parameter or {@code null} to assign this value. */ Object resolve(MethodDescription.InDefinedShape instrumentedMethod, ParameterDescription.InDefinedShape target, AnnotationDescription.Loadable<T> annotation, boolean initialized); /** * <p> * A {@link DynamicValue} implementation that always binds a fixed value. * </p> * <p> * The mapped value must be a constant value that can be embedded into a Java class file. This holds for all primitive types, * instances of {@link String} and for {@link Class} instances as well as their unloaded {@link TypeDescription} representations. * </p> */ class ForFixedValue implements DynamicValue<Annotation> { /** * The fixed value to bind to the corresponding annotation. */ private final Object value; /** * Creates a dynamic value for a fixed value. * * @param value The fixed value to bind to the corresponding annotation. */ public ForFixedValue(Object value) { this.value = value; } @Override public Object resolve(MethodDescription.InDefinedShape instrumentedMethod, ParameterDescription.InDefinedShape target, AnnotationDescription.Loadable<Annotation> annotation, boolean initialized) { return value; } @Override public boolean equals(Object object) { if (this == object) return true; if (object == null || getClass() != object.getClass()) return false; ForFixedValue that = (ForFixedValue) object; return value != null ? value.equals(that.value) : that.value == null; } @Override public int hashCode() { return value != null ? value.hashCode() : 0; } @Override public String toString() { return "Advice.DynamicValue.ForFixedValue{" + "value=" + value + '}'; } } } /** * A builder step for creating an {@link Advice} that uses custom mappings of annotations to constant pool values. */ public static class WithCustomMapping { /** * A map containing dynamically computed constant pool values that are mapped by their triggering annotation type. */ private final Map<Class<? extends Annotation>, DynamicValue<?>> dynamicValues; /** * Creates a new custom mapping builder step without including any custom mappings. */ protected WithCustomMapping() { this(Collections.<Class<? extends Annotation>, DynamicValue<?>>emptyMap()); } /** * Creates a new custom mapping builder step with the given custom mappings. * * @param dynamicValues A map containing dynamically computed constant pool values that are mapped by their triggering annotation type. */ protected WithCustomMapping(Map<Class<? extends Annotation>, DynamicValue<?>> dynamicValues) { this.dynamicValues = dynamicValues; } /** * Binds an annotation type to dynamically computed value. Whenever the {@link Advice} component discovers the given annotation on * a parameter of an advice method, the dynamic value is asked to provide a value that is then assigned to the parameter in question. * * @param type The annotation type that triggers the mapping. * @param dynamicValue The dynamic value that is computed for binding the parameter to a value. * @param <T> The annotation type. * @return A new builder for an advice that considers the supplied annotation type during binding. */ public <T extends Annotation> WithCustomMapping bind(Class<? extends T> type, DynamicValue<T> dynamicValue) { Map<Class<? extends Annotation>, DynamicValue<?>> dynamicValues = new HashMap<Class<? extends Annotation>, Advice.DynamicValue<?>>(this.dynamicValues); if (!type.isAnnotation()) { throw new IllegalArgumentException("Not an annotation type: " + type); } else if (dynamicValues.put(type, dynamicValue) != null) { throw new IllegalArgumentException("Annotation-type already mapped: " + type); } return new WithCustomMapping(dynamicValues); } /** * Implements advice where every matched method is advised by the given type's advisory methods. The advices binary representation is * accessed by querying the class loader of the supplied class for a class file. * * @param type The type declaring the advice. * @return A method visitor wrapper representing the supplied advice. */ public Advice to(Class<?> type) { return to(type, ClassFileLocator.ForClassLoader.of(type.getClassLoader())); } /** * Implements advice where every matched method is advised by the given type's advisory methods. * * @param type The type declaring the advice. * @param classFileLocator The class file locator for locating the advisory class's class file. * @return A method visitor wrapper representing the supplied advice. */ public Advice to(Class<?> type, ClassFileLocator classFileLocator) { return to(new TypeDescription.ForLoadedType(type), classFileLocator); } /** * Implements advice where every matched method is advised by the given type's advisory methods. * * @param typeDescription A description of the type declaring the advice. * @param classFileLocator The class file locator for locating the advisory class's class file. * @return A method visitor wrapper representing the supplied advice. */ public Advice to(TypeDescription typeDescription, ClassFileLocator classFileLocator) { List<Dispatcher.OffsetMapping.Factory> userFactories = new ArrayList<Dispatcher.OffsetMapping.Factory>(dynamicValues.size()); for (Map.Entry<Class<? extends Annotation>, DynamicValue<?>> entry : dynamicValues.entrySet()) { userFactories.add(Dispatcher.OffsetMapping.ForUserValue.Factory.of(entry.getKey(), entry.getValue())); } return Advice.to(typeDescription, classFileLocator, userFactories); } @Override public boolean equals(Object object) { if (this == object) return true; if (object == null || getClass() != object.getClass()) return false; WithCustomMapping that = (WithCustomMapping) object; return dynamicValues.equals(that.dynamicValues); } @Override public int hashCode() { return dynamicValues.hashCode(); } @Override public String toString() { return "Advice.WithCustomMapping{" + "dynamicValues=" + dynamicValues + '}'; } } /** * A marker class that indicates that an advice method does not suppress any {@link Throwable}. */ private static class NoExceptionHandler extends Throwable { /** * A description of the {@link NoExceptionHandler} type. */ private static final TypeDescription DESCRIPTION = new TypeDescription.ForLoadedType(NoExceptionHandler.class); /** * A private constructor as this class is not supposed to be invoked. */ private NoExceptionHandler() { throw new UnsupportedOperationException("This marker class is not supposed to be instantiated"); } } }