@Test public void testPOJO() throws Exception { log.info("*** testPOJO ***"); for (int i = 0; i < 10; i++) { Person person = makePerson(); person.setLastName("smith" + i); registrar.createPerson(person); } // the objects returned will be fully loaded, but... Collection<Person> people = registrar.getPeopleByNameHydrated("joe", "%"); assertEquals("unexpected number of managed people", 10, people.size()); // the collection class requires hibernate to be in the path Class<?> clazz = people.iterator().next().getAddresses().getClass(); log.debug("collection class=" + clazz); assertTrue("unexpected collection class", clazz.getPackage().getName().contains("hibernate")); // now get a graph of objects that contain pure POJO classes. The // server will create fresh POJOs for DTOs and pass information from // the business object POJO to the data transfer object POJO. people = registrar.getPeopleByNameCleaned("joe", "%"); assertEquals("unexpected number of clean people", 10, people.size()); for (Person p : people) { p.getAddresses().iterator().next().getZip(); } // the POJOs are cleansed of their hibernate types clazz = people.iterator().next().getAddresses().getClass(); log.debug("collection class=" + clazz); assertFalse("unexpected collection class", clazz.getPackage().getName().contains("hibernate")); }
private Bench runBenchmark(Class<? extends Lookup> cls, int count) throws Exception { System.err.println("* Running " + count + " iterations for " + cls.getSimpleName() + " ..."); System.err.println(" - warm-up 10 iterations..."); for (int i = 0; i < 10; i++) { System.runFinalization(); System.gc(); Lookup lookup = cls.newInstance(); _benchmark(lookup, null, false, null); lookup = null; } Bench b = new Bench(); System.err.print(" - main iterations:"); System.err.flush(); for (int i = 0; i < count; i++) { System.runFinalization(); System.gc(); Lookup lookup = cls.newInstance(); _benchmark(lookup, null, false, b); lookup = null; if (i > 0 && (i % 10 == 0)) { System.err.print(" " + i); System.err.flush(); } } System.err.println(); return b; }
public <T extends AbstractTask> T createTask(Class<T> type, Project project, String name) { Task task = TASK_FACTORY.createTask( (ProjectInternal) project, GUtil.map(Task.TASK_TYPE, type, Task.TASK_NAME, name)); assertTrue(type.isAssignableFrom(task.getClass())); return type.cast(task); }
@Test public void selfRefUsedInAPropertyIsReadSuccessfully() throws NoSuchMethodException { Class<?> aClass = selfRefsClass.getMethod("getChildOfSelf").getReturnType(); assertThat(aClass.getName(), is("com.example.SelfRefs")); }
private final void validateTwoAnnotations(final PackageInfoModifier.Modification mod) throws Exception { assertNotNull(mod); final byte[] newClass = mod.toByteArray(); assertNotNull(newClass); assertTrue(newClass.length > 0); final Class<?> c = new ClassDefiner().define(mod.getPackageName(), newClass); assertNotNull(c); final Annotation[] annotations = c.getAnnotations(); assertNotNull(annotations); assertTrue(annotations.length == 2); Annotation a = annotations[0]; assertNotNull(a); if (a instanceof Deprecated) { a = annotations[1]; assertNotNull(a); } assertTrue(a instanceof XmlJavaTypeAdapters); final XmlJavaTypeAdapters adaptersAnnotation = (XmlJavaTypeAdapters) a; final XmlJavaTypeAdapter[] adapters = adaptersAnnotation.value(); assertNotNull(adapters); assertEquals(1, adapters.length); final XmlJavaTypeAdapter adapter = adapters[0]; assertNotNull(adapter); assertEquals(Person.class, adapter.type()); assertEquals(AnyTypeAdapter.class, adapter.value()); }
@Test public void refToFragmentOfAnotherSchemaIsReadSuccessfully() throws NoSuchMethodException { Class<?> aClass = fragmentRefsClass.getMethod("getFragmentOfA").getReturnType(); assertThat(aClass.getName(), is("com.example.AdditionalPropertyValue")); }
@Test public void testLoadFromJar() throws Exception { File jar = Files.createTempFile("battlecode-test", ".jar").toFile(); jar.deleteOnExit(); ZipOutputStream z = new ZipOutputStream(new FileOutputStream(jar)); ZipEntry classEntry = new ZipEntry("instrumentertest/Nothing.class"); z.putNextEntry(classEntry); IOUtils.copy( getClass().getClassLoader().getResourceAsStream("instrumentertest/Nothing.class"), z); z.closeEntry(); z.close(); IndividualClassLoader jarLoader = new IndividualClassLoader( "instrumentertest", new IndividualClassLoader.Cache(jar.toURI().toURL())); Class<?> jarClass = jarLoader.loadClass("instrumentertest.Nothing"); URL jarClassLocation = jarClass.getResource("Nothing.class"); // EXTREMELY scientific assertTrue(jarClassLocation.toString().startsWith("jar:")); assertTrue(jarClassLocation.toString().contains(jar.toURI().toURL().toString())); }
@Test @SuppressWarnings("rawtypes") public void wordDelimitersCausesCamelCase() throws ClassNotFoundException, IntrospectionException, InstantiationException, IllegalAccessException, InvocationTargetException { ClassLoader resultsClassLoader = generateAndCompile( "/schema/properties/propertiesWithWordDelimiters.json", "com.example", config("usePrimitives", true, "propertyWordDelimiters", "_ -")); Class generatedType = resultsClassLoader.loadClass("com.example.WordDelimit"); Object instance = generatedType.newInstance(); new PropertyDescriptor("propertyWithUnderscores", generatedType) .getWriteMethod() .invoke(instance, "a_b_c"); new PropertyDescriptor("propertyWithHyphens", generatedType) .getWriteMethod() .invoke(instance, "a-b-c"); new PropertyDescriptor("propertyWithMixedDelimiters", generatedType) .getWriteMethod() .invoke(instance, "a b_c-d"); JsonNode jsonified = mapper.valueToTree(instance); assertThat(jsonified.has("property_with_underscores"), is(true)); assertThat(jsonified.has("property-with-hyphens"), is(true)); assertThat(jsonified.has("property_with mixed-delimiters"), is(true)); }
private List<String> dependenciesOf(Package source) { List<String> result = new ArrayList<>(); if (source.isAnnotationPresent(DependsUpon.class)) for (Class<?> target : source.getAnnotation(DependsUpon.class).packagesOf()) result.add(target.getPackage().getName()); return result; }
@Test public void acceptedCommandsCanBeSerializedTest() throws Exception { Field commandsField = JaxbCommandsRequest.class.getDeclaredField("commands"); XmlElements xmlElemsAnno = (XmlElements) commandsField.getAnnotations()[0]; XmlElement[] xmlElems = xmlElemsAnno.value(); Set<Class> cmdSet = new HashSet<Class>(AcceptedCommands.getSet()); assertEquals(cmdSet.size(), xmlElems.length); Set<String> xmlElemNameSet = new HashSet<String>(); for (XmlElement xmlElemAnno : xmlElems) { Class cmdClass = xmlElemAnno.type(); String name = xmlElemAnno.name(); assertTrue(name + " is used twice as a name.", xmlElemNameSet.add(name)); assertTrue( cmdClass.getSimpleName() + " is present in " + JaxbCommandsRequest.class.getSimpleName() + " but not in " + AcceptedCommands.class.getSimpleName(), cmdSet.remove(cmdClass)); } for (Class cmdClass : cmdSet) { System.out.println("Missing: " + cmdClass.getSimpleName()); } assertTrue( "See output for classes in " + AcceptedCommands.class.getSimpleName() + " that are not in " + JaxbCommandsRequest.class.getSimpleName(), cmdSet.size() == 0); }
@Test public void testSetAmount2() throws Exception { System.out.println("setAmount2"); /* Set up a new loan */ Loan target = new Loan(); /* get the setAmount method details */ Method method = Loan.class.getDeclaredMethod("setAmount", double.class); /* make the field assessible */ method.setAccessible(true); /* invoke the method setAmount with the value 3000.0 */ method.invoke(target, 3000.0); /*access the field loanAmount and check its value is set the 3000.0*/ Class secretClass = target.getClass(); Field f = secretClass.getDeclaredField("loanAmount"); f.setAccessible(true); double result = f.getDouble(target); assertEquals("The amounts should be equal", 3000.00, result, 0.0); }
public void assertTestsStarted(Class<?>... classes) { List<String> testNames = newArrayList(); for (Class<?> each : classes) { testNames.add(each.getName()); } assertTestsStarted(toArray(testNames, String.class)); }
@Test public void detectsFindAllWithSortParameterOnSortingRepository() throws Exception { Class<RepositoryWithCustomSortingFindAll> type = RepositoryWithCustomSortingFindAll.class; assertFindAllMethodOn(type, type.getMethod("findAll", Sort.class)); assertSaveMethodPresent(type, false); }
@Test public void refToFragmentOfSelfIsReadSuccessfully() throws NoSuchMethodException { Class<?> aClass = fragmentRefsClass.getMethod("getFragmentOfSelf").getReturnType(); assertThat(aClass.getName(), is("com.example.A")); assertThat(aClass.getMethods(), hasItemInArray(hasProperty("name", equalTo("getPropertyOfA")))); }
/* * (non-Javadoc) * @see org.mockito.stubbing.Answer#answer(org.mockito.invocation.InvocationOnMock) */ @Override public Object answer(InvocationOnMock invocation) throws Throwable { Class<?> returnType = invocation.getMethod().getReturnType(); return returnType.equals(Boolean.class) || returnType.equals(boolean.class) ? true : DEFAULT.answer(invocation); }
@Test public void testConstructor() throws Exception { Class<HMAC> c = HMAC.class; assertEquals(1, c.getDeclaredConstructors().length); Constructor<HMAC> constructor = c.getDeclaredConstructor(); assertTrue(Modifier.isPrivate(constructor.getModifiers())); constructor.setAccessible(true); constructor.newInstance(); }
@Test public void selfRefUsedAsArrayItemsIsReadSuccessfully() throws NoSuchMethodException { Type listOfAType = selfRefsClass.getMethod("getArrayOfSelf").getGenericReturnType(); Class<?> listEntryClass = (Class<?>) ((ParameterizedType) listOfAType).getActualTypeArguments()[0]; assertThat(listEntryClass.getName(), is("com.example.SelfRefs")); }
protected void invokeKey(String name) throws Exception { if (!needsKey) return; BehaviorSkinBase skin = (BehaviorSkinBase) getView().getSkin(); BehaviorBase behavior = skin.getBehavior(); Class<? extends BehaviorBase> behaviorClass = behavior.getClass(); Field field = behaviorClass.getDeclaredField(name); field.setAccessible(true); field.set(behavior, true); }
/** * Refectively invokes action method on behavior * * <p>NOTE to self: boolean.class != Boolean.class - getDeclaredMethod doesn't do any * primitve/Object type conversion. * * @param name method name * @param param boolean parameter * @throws NoSuchMethodException * @throws IllegalAccessException * @throws InvocationTargetException */ protected void invokeBehavior(String name, boolean param) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { BehaviorSkinBase skin = (BehaviorSkinBase) getView().getSkin(); BehaviorBase behavior = skin.getBehavior(); Class<? extends BehaviorBase> behaviorClass = behavior.getClass(); Method method = behaviorClass.getDeclaredMethod(name, boolean.class); method.setAccessible(true); method.invoke(behavior, param); }
/** @see DATACMNS-393 */ @Test public void detectsOverloadedMethodsCorrectly() throws Exception { Class<RepositoryWithAllCrudMethodOverloaded> type = RepositoryWithAllCrudMethodOverloaded.class; assertFindOneMethodOn(type, type.getDeclaredMethod("findOne", Long.class)); assertDeleteMethodOn(type, type.getDeclaredMethod("delete", Long.class)); assertSaveMethodOn(type, type.getDeclaredMethod("save", Domain.class)); assertFindAllMethodOn(type, type.getDeclaredMethod("findAll")); }
@Test public void detectsMethodsOnPagingAndSortingRepository() throws Exception { Class<DomainPagingAndSortingRepository> type = DomainPagingAndSortingRepository.class; assertFindAllMethodOn(type, type.getMethod("findAll", Pageable.class)); assertDeleteMethodOn(type, type.getMethod("delete", Serializable.class)); assertSaveMethodPresent(type, true); }
@Test public void testBeforeAddInterceptor() throws Exception { final TestClassLoader loader = getTestClassLoader(); final String javassistClassName = "com.navercorp.pinpoint.profiler.interceptor.bci.TestObject"; loader.addTransformer( javassistClassName, new TransformCallback() { @Override public byte[] doInTransform( Instrumentor instrumentContext, ClassLoader classLoader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws InstrumentException { try { logger.info("modify className:{} cl:{}", className, classLoader); InstrumentClass aClass = instrumentContext.getInstrumentClass( classLoader, javassistClassName, classfileBuffer); String methodName = "callA"; aClass .getDeclaredMethod(methodName) .addInterceptor( "com.navercorp.pinpoint.profiler.interceptor.TestBeforeInterceptor"); return aClass.toBytecode(); } catch (InstrumentException e) { e.printStackTrace(); throw new RuntimeException(e.getMessage(), e); } } }); loader.initialize(); Class<?> testObjectClazz = loader.loadClass(javassistClassName); final String methodName = "callA"; logger.info("class:{}", testObjectClazz.toString()); final Object testObject = testObjectClazz.newInstance(); Method callA = testObjectClazz.getMethod(methodName); callA.invoke(testObject); Interceptor interceptor = getInterceptor(loader, 0); assertEqualsIntField(interceptor, "call", 1); assertEqualsObjectField( interceptor, "className", "com.navercorp.pinpoint.profiler.interceptor.bci.TestObject"); assertEqualsObjectField(interceptor, "methodName", methodName); assertEqualsObjectField(interceptor, "args", null); assertEqualsObjectField(interceptor, "target", testObject); }
/** * input/output simple records. * * @throws Exception if test was failed */ @SuppressWarnings("unchecked") @Test public void simple_record() throws Exception { ModelLoader loader = generate(); Class<?> type = loader.modelType("Simple"); assertThat(type.isAnnotationPresent(ModelInputLocation.class), is(true)); assertThat(type.isAnnotationPresent(ModelOutputLocation.class), is(true)); ModelWrapper object = loader.newModel("Simple"); DataOutputBuffer output = new DataOutputBuffer(); ModelOutput<Object> modelOut = (ModelOutput<Object>) type.getAnnotation(ModelOutputLocation.class) .value() .getDeclaredConstructor(RecordEmitter.class) .newInstance(new TsvEmitter(new OutputStreamWriter(output, "UTF-8"))); object.set("sid", 1L); object.set("value", new Text("hello")); modelOut.write(object.unwrap()); object.set("sid", 2L); object.set("value", new Text("world")); modelOut.write(object.unwrap()); object.set("sid", 3L); object.set("value", null); modelOut.write(object.unwrap()); modelOut.close(); DataInputBuffer input = new DataInputBuffer(); input.reset(output.getData(), output.getLength()); ModelInput<Object> modelIn = (ModelInput<Object>) type.getAnnotation(ModelInputLocation.class) .value() .getDeclaredConstructor(RecordParser.class) .newInstance(new TsvParser(new InputStreamReader(input, "UTF-8"))); ModelWrapper copy = loader.newModel("Simple"); modelIn.readTo(copy.unwrap()); assertThat(copy.get("sid"), is((Object) 1L)); assertThat(copy.get("value"), is((Object) new Text("hello"))); modelIn.readTo(copy.unwrap()); assertThat(copy.get("sid"), is((Object) 2L)); assertThat(copy.get("value"), is((Object) new Text("world"))); modelIn.readTo(copy.unwrap()); assertThat(copy.get("sid"), is((Object) 3L)); assertThat(copy.getOption("value").isNull(), is(true)); assertThat(input.read(), is(-1)); modelIn.close(); }
/** @see DATACMNS-393 */ @Test public void selectsFindAllWithSortParameterOnRepositoryAmongUnsuitableAlternatives() throws Exception { Class<RepositoryWithInvalidPagingFallbackToSortFindAll> type = RepositoryWithInvalidPagingFallbackToSortFindAll.class; assertFindAllMethodOn(type, type.getMethod("findAll", Sort.class)); assertSaveMethodPresent(type, false); }
@Test public void detectsMethodsOnCustomRepository() throws Exception { Class<RepositoryWithCustomSortingAndPagingFindAll> type = RepositoryWithCustomSortingAndPagingFindAll.class; assertFindAllMethodOn(type, type.getMethod("findAll", Pageable.class)); Class<RepositoryWithIterableDeleteOnly> type1 = RepositoryWithIterableDeleteOnly.class; assertDeleteMethodOn(type1, type1.getMethod("delete", Iterable.class)); }
@Test public void testSetClassName() throws Exception { Intent intent = new Intent(); Class<? extends IntentTest> thisClass = getClass(); intent.setClassName("package.name", thisClass.getName()); assertSame(thisClass.getName(), intent.getComponent().getClassName()); assertEquals("package.name", intent.getComponent().getPackageName()); ShadowIntent si = shadowOf(intent); assertSame(si.getIntentClass(), thisClass); }
@Test public void selfRefUsedForAdditionalPropertiesIsReadSuccessfully() throws NoSuchMethodException { Type additionalPropertiesType = selfRefsClass.getMethod("getAdditionalProperties").getGenericReturnType(); Class<?> mapEntryClass = (Class<?>) ((ParameterizedType) additionalPropertiesType).getActualTypeArguments()[1]; assertThat(mapEntryClass.getName(), is("com.example.SelfRefs")); }
@Test public void nestedSelfRefsInStringContentWithoutParentFile() throws NoSuchMethodException, ClassNotFoundException, IOException { String schemaContents = IOUtils.toString( CodeGenerationHelper.class.getResource("/schema/ref/nestedSelfRefsReadAsString.json")); JCodeModel codeModel = new JCodeModel(); new SchemaMapper().generate(codeModel, "NestedSelfRefsInString", "com.example", schemaContents); codeModel.build(schemaRule.getGenerateDir()); ClassLoader classLoader = schemaRule.compile(); Class<?> nestedSelfRefs = classLoader.loadClass("com.example.NestedSelfRefsInString"); assertThat( nestedSelfRefs.getMethod("getThings").getReturnType().getSimpleName(), equalTo("List")); Class<?> listEntryType = (Class<?>) ((ParameterizedType) nestedSelfRefs.getMethod("getThings").getGenericReturnType()) .getActualTypeArguments()[0]; assertThat(listEntryType.getName(), equalTo("com.example.Thing")); Class<?> thingClass = classLoader.loadClass("com.example.Thing"); assertThat( thingClass.getMethod("getNamespace").getReturnType().getSimpleName(), equalTo("String")); assertThat(thingClass.getMethod("getName").getReturnType().getSimpleName(), equalTo("String")); assertThat( thingClass.getMethod("getVersion").getReturnType().getSimpleName(), equalTo("String")); }
@Test public void shouldFindPathAnnotatedClassesInPackage() { ClassPathScanner scanner = new ClassPathScanner(PACKAGE_ORG_CAMUNDA_BPM_ENGINE_REST); Set<Class<?>> classes = scanner.getClassesWithAnnotation(Path.class); assertEquals(16, classes.size()); for (Class<?> clazz : classes) { Path annotation = clazz.getAnnotation(Path.class); System.out.println(clazz + " path: " + annotation.value()); } }
@Test public void shouldFindApplicationPathAnnotatedClassInPackage() { ClassPathScanner scanner = new ClassPathScanner(PACKAGE_RESTAPIDOC_TEST); Set<Class<?>> classes = scanner.getClassesWithAnnotation(ApplicationPath.class); assertEquals(1, classes.size()); for (Class<?> clazz : classes) { ApplicationPath annotation = clazz.getAnnotation(ApplicationPath.class); System.out.println(clazz + " path: " + annotation.value()); } }