Author: gk
Date: Fri Dec 14 15:27:05 2018
New Revision: 1848953
URL: http://svn.apache.org/viewvc?rev=1848953&view=rev
Log:
- update formatted concurrent test class
- add Java8 concurrent test class
Added:
turbine/fulcrum/trunk/json/jackson2/src/test/org/apache/fulcrum/json/jackson/concurrent/JSONConcurrentJunit5Test.java
(with props)
Modified:
turbine/fulcrum/trunk/json/jackson2/src/test/org/apache/fulcrum/json/jackson/concurrent/JSONConcurrentTest.java
Added:
turbine/fulcrum/trunk/json/jackson2/src/test/org/apache/fulcrum/json/jackson/concurrent/JSONConcurrentJunit5Test.java
URL:
http://svn.apache.org/viewvc/turbine/fulcrum/trunk/json/jackson2/src/test/org/apache/fulcrum/json/jackson/concurrent/JSONConcurrentJunit5Test.java?rev=1848953&view=auto
==============================================================================
---
turbine/fulcrum/trunk/json/jackson2/src/test/org/apache/fulcrum/json/jackson/concurrent/JSONConcurrentJunit5Test.java
(added)
+++
turbine/fulcrum/trunk/json/jackson2/src/test/org/apache/fulcrum/json/jackson/concurrent/JSONConcurrentJunit5Test.java
Fri Dec 14 15:27:05 2018
@@ -0,0 +1,282 @@
+package org.apache.fulcrum.json.jackson.concurrent;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.CoreMatchers.not;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
+import static
org.junit.platform.engine.discovery.DiscoverySelectors.selectClass;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+import java.util.Random;
+import java.util.stream.IntStream;
+
+import org.apache.avalon.framework.component.ComponentException;
+import org.apache.fulcrum.json.JsonService;
+import org.apache.fulcrum.json.jackson.Jackson2MapperService;
+import org.apache.fulcrum.json.jackson.SimpleNameIntrospector;
+import org.apache.fulcrum.json.jackson.example.Bean;
+import org.apache.fulcrum.testcontainer.BaseUnit5Test;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.RepeatedTest;
+import org.junit.jupiter.api.TestInstance;
+import org.junit.jupiter.api.TestInstance.Lifecycle;
+import org.junit.jupiter.api.TestReporter;
+import org.junit.jupiter.api.extension.ExtensionContext;
+import org.junit.jupiter.api.extension.TestExecutionExceptionHandler;
+import org.junit.jupiter.api.parallel.Execution;
+import org.junit.jupiter.api.parallel.ExecutionMode;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.junit.platform.launcher.Launcher;
+import org.junit.platform.launcher.LauncherDiscoveryRequest;
+import org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder;
+import org.junit.platform.launcher.core.LauncherFactory;
+import org.junit.platform.launcher.listeners.SummaryGeneratingListener;
+import org.junit.platform.launcher.listeners.TestExecutionSummary;
+import org.junit.platform.launcher.listeners.TestExecutionSummary.Failure;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.AnnotationIntrospector;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.ObjectMapper.DefaultTyping;
+import com.fasterxml.jackson.databind.introspect.AnnotationIntrospectorPair;
+import com.fasterxml.jackson.databind.ser.PropertyFilter;
+import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter;
+import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;
+
+@TestInstance(Lifecycle.PER_CLASS)
+public class JSONConcurrentJunit5Test extends BaseUnit5Test {
+
+ private static volatile Thread fOne = null;
+ private static volatile Thread fTwo = null;
+ private static volatile Thread fThree = null;
+ private static JsonService jsonService = null;
+
+//
+ public JSONConcurrentJunit5Test() throws Exception {
+ }
+
+ @BeforeAll
+ public static void setUp() throws Exception {
+
+ }
+
+ @BeforeEach
+ public void init() throws ComponentException {
+ fOne = null;
+ fTwo = null;
+ fThree = null;
+ jsonService = (JsonService) this.lookup(JsonService.ROLE);
+ }
+
+ // @TestInstance(Lifecycle.PER_CLASS)
+ @Execution(ExecutionMode.CONCURRENT)
+ public static class JSONBeansTests extends BaseUnit5Test implements
TestExecutionExceptionHandler {
+
+ @BeforeEach
+ public void init() throws ComponentException {
+
+ }
+
+ @ParameterizedTest
+ @MethodSource("multipleRandStream")
+ public void one(int randStreamInt) throws InterruptedException {
+ String result = doJob(randStreamInt, "name");
+
assertTrue(!result.contains("org.apache.fulcrum.json.jackson.example.Bean"),
"Result does contain type");
+ assertTrue(!result.contains("java.util.ArrayList"), "Result does
contain type");
+ fOne = Thread.currentThread();
+ }
+
+ @ParameterizedTest
+ @MethodSource("multipleRandStream")
+ public void two(int randStreamInt) throws InterruptedException {
+ String result = doJob(randStreamInt, "name", "age");
+
assertTrue(!result.contains("org.apache.fulcrum.json.jackson.example.Bean"),
"Result does contain type");
+ assertTrue(!result.contains("java.util.ArrayList"), "Result does
contain type");
+ fTwo = Thread.currentThread();
+ }
+
+ @ParameterizedTest
+ @MethodSource("multipleRandStream")
+ public void three(int randStreamInt) throws InterruptedException,
JsonProcessingException {
+ ObjectMapper mapper = customMapper(true);
+ // ((Jackson2MapperService) jsonService).setMapper(mapper);
+ // String result = doTaskJob("name", "age","profession");
+ String result = doFilteredJob(mapper, randStreamInt, new String[]
{ "age", "profession" });
+
assertTrue(result.contains("org.apache.fulcrum.json.jackson.example.Bean"),
+ "Result does not contain type, but it shouldn't");
+ assertTrue(result.contains("java.util.ArrayList"), "Result does
not contain type, but it shouldn't");
+ assertTrue(!result.contains("\"name\""), "Result should not
contain attribute name");
+ fThree = Thread.currentThread();
+ }
+
+ private String doJob(int randStreamInt, String... filtereIds) {
+ List<Bean> tasks = getBeans(randStreamInt);
+ String result = getJson(tasks, Bean.class, true, filtereIds);
+ System.out.println("ser result (id=" + Thread.currentThread() +
"):" + result);
+
+ List<String> fidsArr = Arrays.asList(filtereIds);
+ fidsArr.forEach(fidId -> {
+ assertTrue(result.contains("\"" + fidId + "\""), "Result does
not contain (" + fidId + ")");
+ assertTrue(result.contains(randStreamInt + ""), result + "
does not contain " + randStreamInt + ")");
+ });
+ return result;
+ }
+
+ private String doFilteredJob(ObjectMapper mapper, int randStreamInt,
String... filtereIds)
+ throws JsonProcessingException {
+ List<Bean> tasks = getBeans(randStreamInt);
+ String result = serFiltered(tasks, Bean.class, mapper, filtereIds);
+ System.out.println("ser result (id=" + Thread.currentThread() +
"):" + result);
+ List<String> fidsArr = Arrays.asList(filtereIds);
+ fidsArr.forEach(fidId -> {
+ assertTrue(result.contains("\"" + fidId + "\""), "Result does
not contain (" + fidId + ")");
+ assertTrue(result.contains(randStreamInt + ""), result + "
does not contain " + randStreamInt + ")");
+ });
+ return result;
+ }
+
+ private String serFiltered(List<?> list, Class<?> filterClass,
ObjectMapper mapper, String[] filterAttr)
+ throws JsonProcessingException {
+ Collection<AnnotationIntrospector> ais =
((AnnotationIntrospectorPair) mapper.getSerializationConfig()
+ .getAnnotationIntrospector()).allIntrospectors();
+ // activate filtering
+ ais.stream().filter(ai -> ai instanceof SimpleNameIntrospector)
+ .forEach(ai -> ((SimpleNameIntrospector)
ai).setFilteredClasses(filterClass));
+ PropertyFilter pf =
SimpleBeanPropertyFilter.filterOutAllExcept(filterAttr);
+ SimpleFilterProvider filter = new SimpleFilterProvider();
+ filter.setDefaultFilter(pf);
+ return mapper.writer(filter).writeValueAsString(list);
+ }
+
+ private ObjectMapper customMapper(boolean withType) {
+ ObjectMapper objectMapper = null;
+ if (withType) {
+ // without copy tests will fail in testsRunInParallel
+ objectMapper = ((Jackson2MapperService)
jsonService).getMapper().copy();
+
objectMapper.enableDefaultTypingAsProperty(DefaultTyping.NON_FINAL, "type");
+ AnnotationIntrospector ai =
objectMapper.getSerializationConfig().getAnnotationIntrospector();
+ AnnotationIntrospector siai = new SimpleNameIntrospector();
+ AnnotationIntrospector pair = new
AnnotationIntrospectorPair(siai, ai);
+ objectMapper.setAnnotationIntrospector(pair);
+ } else {
+ objectMapper = ((Jackson2MapperService)
jsonService).getMapper();
+ }
+ return objectMapper;
+ }
+
+ // randNum is in any property -> unconditionally checkable
+ private List<Bean> getBeans(int randNum) {
+ List<Bean> beans = new ArrayList<Bean>();
+ IntStream.of(50).forEach(i -> {
+ Bean dct = new Bean();
+ dct.setName("title" + i + "_" + randNum);
+ dct.setAge(randNum);
+ dct.profession = "prof" + i + "_" + randNum;
+ beans.add(dct);
+ });
+ return beans;
+ }
+
+ private String getJson(List<?> list, Class clazz, Boolean refresh,
String... props) {
+ try {
+ return jsonService.serializeOnlyFilter(list, clazz, refresh,
props);
+ } catch (Exception e) {
+ System.out.println(e.getMessage());
+ fail();
+ }
+ return null;
+ }
+
+ public static IntStream multipleRandStream() {
+ return new Random().ints(5, 1, 1001);
+ }
+
+ @Override
+ public void handleTestExecutionException(ExtensionContext context,
Throwable throwable) throws Throwable {
+ throw throwable;
+ }
+ }
+
+ @RepeatedTest(10)
+ public void testsRunInParallel(TestReporter testReporter) {
+ // Parallel among methods in a class in one thread pool
+ final LauncherDiscoveryRequest request =
LauncherDiscoveryRequestBuilder.request()
+ .selectors(selectClass(JSONBeansTests.class))
+ // does not matter:
+ // if JSONBeansTests is set to per_class
+ // (junit.jupiter.testinstance.lifecycle.default) test methods
may reuse threads
+ // or
+ // if it is default per_method.
+ //
.configurationParameter("junit.jupiter.testinstance.lifecycle.default",
+ // "per_class")
+
.configurationParameter("junit.jupiter.execution.parallel.enabled",
"true").build();
+ TestExecutionSummary summary = defaultExecute(request);
+ defaultAsserts(testReporter, summary);
+
+ // this method may be executed multiple times, any method may get a
reused thread at the end, no assert
+// assertThat(fOne, is(not(fTwo)));
+// assertThat(fTwo, is(not(fThree)));
+// assertThat(fOne, is(not(fThree)));
+ }
+
+ @RepeatedTest(3)
+ public void testsRunInSameThread(TestReporter testReporter) {
+ // Parallel among methods in a class in one thread pool
+ final LauncherDiscoveryRequest request =
LauncherDiscoveryRequestBuilder.request()
+ .selectors(selectClass(JSONBeansTests.class))
+ //
.configurationParameter("junit.jupiter.testinstance.lifecycle.default",
+ // "per_class")
+ .build();
+ TestExecutionSummary summary = defaultExecute(request);
+ defaultAsserts(testReporter, summary);
+ assertThat(fOne, is(fTwo));
+ assertThat(fTwo, is(fThree));
+ assertThat(fOne, is(fThree));
+ }
+
+ private TestExecutionSummary defaultExecute(final LauncherDiscoveryRequest
request) {
+ final Launcher launcher = LauncherFactory.create();
+ final SummaryGeneratingListener listener = new
SummaryGeneratingListener();
+
+ launcher.registerTestExecutionListeners(listener);
+ launcher.execute(request);
+
+ return listener.getSummary();
+ }
+
+ private void defaultAsserts(TestReporter testReporter,
TestExecutionSummary summary) {
+ List<Failure> failures = summary.getFailures();
+ assertNotNull(summary.getTestsFoundCount() > 0, "No Tests found");
+
+ testReporter.publishEntry("summary getTestsStartedCount:" +
summary.getTestsStartedCount());
+ testReporter.publishEntry("summary getTestsSucceededCount:" +
summary.getTestsSucceededCount());
+ testReporter.publishEntry("fOne:" + fOne);
+ testReporter.publishEntry("fTwo:" + fTwo);
+ testReporter.publishEntry("fThree:" + fThree);
+
+ failures.forEach(failure -> {
+ testReporter.publishEntry("failure - " + failure.getException());
+ testReporter.publishEntry("failure at - " +
failure.getTestIdentifier());
+ });
+ long testFoundCount = summary.getTestsFoundCount();
+
+ assertNotNull(fOne);
+ assertNotNull(fTwo);
+ assertNotNull(fThree);
+
+ assertEquals(testFoundCount, summary.getTestsSucceededCount(),
+ "Not exactly " + testFoundCount + " Tests succeessfull");
+ assertEquals(0, summary.getTestsFailedCount(), "No failed tests");
+ assertTrue(failures.isEmpty(), "Parallel Test failures not empty");
+ }
+
+}
Propchange:
turbine/fulcrum/trunk/json/jackson2/src/test/org/apache/fulcrum/json/jackson/concurrent/JSONConcurrentJunit5Test.java
------------------------------------------------------------------------------
svn:eol-style = native
Modified:
turbine/fulcrum/trunk/json/jackson2/src/test/org/apache/fulcrum/json/jackson/concurrent/JSONConcurrentTest.java
URL:
http://svn.apache.org/viewvc/turbine/fulcrum/trunk/json/jackson2/src/test/org/apache/fulcrum/json/jackson/concurrent/JSONConcurrentTest.java?rev=1848953&r1=1848952&r2=1848953&view=diff
==============================================================================
---
turbine/fulcrum/trunk/json/jackson2/src/test/org/apache/fulcrum/json/jackson/concurrent/JSONConcurrentTest.java
(original)
+++
turbine/fulcrum/trunk/json/jackson2/src/test/org/apache/fulcrum/json/jackson/concurrent/JSONConcurrentTest.java
Fri Dec 14 15:27:05 2018
@@ -44,11 +44,13 @@ import org.junit.Test;
import org.junit.experimental.ParallelComputer;
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
+import org.junit.runner.RunWith;
import org.junit.runner.notification.Failure;
+import org.junit.runners.Parameterized;
+import org.junit.runners.Parameterized.Parameters;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.AnnotationIntrospector;
-import com.fasterxml.jackson.databind.MappingJsonFactory;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectMapper.DefaultTyping;
import com.fasterxml.jackson.databind.introspect.AnnotationIntrospectorPair;
@@ -56,204 +58,214 @@ import com.fasterxml.jackson.databind.se
import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter;
import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;
-public class JSONConcurrentTest extends BaseUnit4Test
-{
+@RunWith(Parameterized.class)
+public class JSONConcurrentTest extends BaseUnit4Test {
- private static final long TIMEOUT = 20;
- private static volatile Thread fOne = null;
- private static volatile Thread fTwo = null;
- private static volatile Thread fThree = null;
- private static JsonService jsonService = null;
-
-//
- public JSONConcurrentTest( )
- throws Exception {}
+ private static volatile Thread fOne = null;
+ private static volatile Thread fTwo = null;
+ private static volatile Thread fThree = null;
+ private static JsonService jsonService = null;
+
+ @Parameters(name = "test run {index}")
+ public static Object[][] multiple() {
+ return new Object[10][]; // { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }
}; // new Object[100][0];
+ }
+
+ public JSONConcurrentTest(Object val1) {
+ }
@BeforeClass
- public static void setUp() throws Exception
- {
-
+ public static void setUp() throws Exception {
+
}
-
+
@Before
public void init() throws ComponentException {
- fOne = null;
- fTwo = null;
- fThree = null;
- jsonService = (JsonService) this.lookup(JsonService.ROLE);
- }
-
+ fOne = null;
+ fTwo = null;
+ fThree = null;
+ jsonService = (JsonService) this.lookup(JsonService.ROLE);
+ }
+
+ // seems to have no effect
+ // @RunWith(Parameterized.class)
public static class JSONBeansTests extends BaseUnit4Test {
-
+
private volatile CountDownLatch fSynchronizer;
static int N = 3;// number of concurrent test methods = methods
-
- @Before
- public void init() throws ComponentException {
- fSynchronizer = new CountDownLatch(N);
- }
- @Test
- public void one() throws InterruptedException {
- String result = doJob("name");
- assertTrue("Result does contain type", !result.contains(
"org.apache.fulcrum.json.jackson.example.Bean" ) );
- assertTrue("Result does contain type", !result.contains(
"java.util.ArrayList" ) );
- fSynchronizer.countDown();
- //assertTrue("waiting failed", fSynchronizer.await(TIMEOUT,
TimeUnit.SECONDS));
- fOne = Thread.currentThread();
- }
-
- @Test
- public void two() throws InterruptedException {
- String result = doJob( "name", "age");
-
- assertTrue("Result does contain type", !result.contains(
"org.apache.fulcrum.json.jackson.example.Bean" ) );
- assertTrue("Result does contain type", !result.contains(
"java.util.ArrayList" ) );
- fSynchronizer.countDown();
- //assertTrue("waiting failed", fSynchronizer.await(TIMEOUT,
TimeUnit.SECONDS));
- fTwo = Thread.currentThread();
- }
-
- @Test
- public void three() throws InterruptedException,
JsonProcessingException {
- ObjectMapper mapper = customMapper(true);
- //((Jackson2MapperService) jsonService).setMapper(mapper);
- //String result = doTaskJob("name", "age","profession");
- String result = doFilteredJob(mapper, new
String[]{"age","profession"});
- assertTrue("Result does not contain type, which it should",
result.contains( "org.apache"
- + ".fulcrum.json.jackson.example.Bean" ) );
- assertTrue("Result does not contain type, which it should",
result.contains( "java.util.ArrayList" ) );
- assertTrue("Result should not contain attribute name",
!result.contains( "\"name\"" ) );
- fSynchronizer.countDown();
- //assertTrue("waiting failed", fSynchronizer.await(TIMEOUT,
TimeUnit.SECONDS));
- fThree = Thread.currentThread();
- }
-
- private String doJob(String... filtereIds) {
- final int randInt = randInt(999, 1001);
- List<Bean> tasks = getBeans(randInt);
- String result = getJson(tasks, Bean.class, true,
- filtereIds);
- System.out.println("ser result
(id="+Thread.currentThread()+"):"+ result);
- for ( int i = 0; i < filtereIds.length; i++ )
- {
- assertTrue("Result does not contain ("+ filtereIds[i]
+")", result.contains( "\""+filtereIds[i]+"\"" ) );
- }
- return result;
- }
-
- private String doFilteredJob(ObjectMapper mapper, String...
filtereIds) throws JsonProcessingException {
- final int randInt = randInt(999, 1001);
- List<Bean> tasks = getBeans(randInt);
- String result = serFiltered(tasks,Bean.class, mapper,
- filtereIds);
- System.out.println("ser result
(id="+Thread.currentThread()+"):"+ result);
- for ( int i = 0; i < filtereIds.length; i++ )
- {
- assertTrue("Result does not contain ("+ filtereIds[i] +")",
result.contains( "\""+filtereIds[i]+"\"" ) );
- }
- return result;
- }
-
- private String serFiltered(List<?> list, Class<?> filterClass,
- ObjectMapper mapper, String[] filterAttr)
- throws JsonProcessingException {
- Collection<AnnotationIntrospector> ais =
((AnnotationIntrospectorPair)mapper.getSerializationConfig().getAnnotationIntrospector()).allIntrospectors();
- for (AnnotationIntrospector ai : ais) {
- if (ai instanceof SimpleNameIntrospector) {
- //activate filtering
- ((SimpleNameIntrospector)
ai).setFilteredClasses(filterClass);
- }
- }
- PropertyFilter pf =
SimpleBeanPropertyFilter.filterOutAllExcept(filterAttr);
- SimpleFilterProvider filter = new SimpleFilterProvider();
- filter.setDefaultFilter(pf);
- return mapper.writer(filter).writeValueAsString(list);
- }
-
- private ObjectMapper customMapper(boolean withType) {
- ObjectMapper objectMapper = new ObjectMapper(
- new MappingJsonFactory(((Jackson2MapperService)
jsonService).getMapper()));
- if (withType) objectMapper.enableDefaultTypingAsProperty(
- DefaultTyping.NON_FINAL, "type");
- AnnotationIntrospector ai =
objectMapper.getSerializationConfig().getAnnotationIntrospector();
- AnnotationIntrospector siai = new SimpleNameIntrospector();
- AnnotationIntrospector pair = new
AnnotationIntrospectorPair(siai,ai);
- objectMapper.setAnnotationIntrospector(pair);
- return objectMapper;
- }
-
- private List<Bean> getBeans(int randNum) {
- List<Bean> beans = new ArrayList<Bean>();
- for ( int i = 0; i < 50; i++ )
- {
- Bean dct = new Bean();
- dct.setName( "title" +i );
- dct.setAge(randNum + i);
- dct.profession = "prof" +i;
- beans.add( dct );
- }
- return beans;
- }
-
- private String getJson( List<?> list , Class clazz, Boolean refresh,
String... props)
- {
- String result ="";
- try
- {
- result = jsonService.serializeOnlyFilter(list, clazz,
refresh, props);
- }
- catch ( Exception e )
- {
- System.out.println(e.getMessage());
- fail();
- }
- return result;
- }
+ @Before
+ public void init() throws ComponentException {
+ fSynchronizer = new CountDownLatch(N);
+ }
+
+ @Test
+ public void one() throws InterruptedException {
+ String result = doJob("name");
+ assertTrue("Result does contain type",
!result.contains("org.apache.fulcrum.json.jackson.example.Bean"));
+ assertTrue("Result does contain type",
!result.contains("java.util.ArrayList"));
+ fSynchronizer.countDown();
+ // assertTrue("waiting failed", fSynchronizer.await(TIMEOUT,
TimeUnit.SECONDS));
+ fOne = Thread.currentThread();
+ System.out.println(fThree + " count:" + fSynchronizer.getCount());
+ }
+
+ @Test
+ public void two() throws InterruptedException {
+ String result = doJob("name", "age");
+
+ assertTrue("Result does contain type",
!result.contains("org.apache.fulcrum.json.jackson.example.Bean"));
+ assertTrue("Result does contain type",
!result.contains("java.util.ArrayList"));
+ fSynchronizer.countDown();
+ // assertTrue("waiting failed", fSynchronizer.await(TIMEOUT,
TimeUnit.SECONDS));
+ fTwo = Thread.currentThread();
+ System.out.println(fThree + " count:" + fSynchronizer.getCount());
+ }
+
+ @Test
+ public void three() throws InterruptedException,
JsonProcessingException {
+ ObjectMapper mapper = customMapper(true);
+ // ((Jackson2MapperService) jsonService).setMapper(mapper);
+ // String result = doTaskJob("name", "age","profession");
+ String result = doFilteredJob(mapper, new String[] { "age",
"profession" });
+ assertTrue("Result does not contain type, which it should",
+ result.contains("org.apache" +
".fulcrum.json.jackson.example.Bean"));
+ assertTrue("Result does not contain type, which it should",
result.contains("java.util.ArrayList"));
+ assertTrue("Result should not contain attribute name",
!result.contains("\"name\""));
+ fSynchronizer.countDown();
+ // assertTrue("waiting failed", fSynchronizer.await(TIMEOUT,
TimeUnit.SECONDS));
+ fThree = Thread.currentThread();
+ System.out.println(fThree + " count:" + fSynchronizer.getCount());
+ }
+
+ private String doJob(String... filtereIds) {
+ final int randInt = randInt(999, 1001);
+ List<Bean> tasks = getBeans(randInt);
+ String result = getJson(tasks, Bean.class, true, filtereIds);
+ System.out.println("ser result (id=" + Thread.currentThread() +
"):" + result);
+ for (int i = 0; i < filtereIds.length; i++) {
+ assertTrue("Result does not contain (" + filtereIds[i] + ")",
+ result.contains("\"" + filtereIds[i] + "\""));
+ }
+ return result;
+ }
+
+ private String doFilteredJob(ObjectMapper mapper, String...
filtereIds) throws JsonProcessingException {
+ final int randInt = randInt(999, 1001);
+ List<Bean> tasks = getBeans(randInt);
+ String result = serFiltered(tasks, Bean.class, mapper, filtereIds);
+ System.out.println("ser result (id=" + Thread.currentThread() +
"):" + result);
+ for (int i = 0; i < filtereIds.length; i++) {
+ assertTrue("Result does not contain (" + filtereIds[i] + ")",
+ result.contains("\"" + filtereIds[i] + "\""));
+ }
+ return result;
+ }
+
+ private String serFiltered(List<?> list, Class<?> filterClass,
ObjectMapper mapper, String[] filterAttr)
+ throws JsonProcessingException {
+ Collection<AnnotationIntrospector> ais =
((AnnotationIntrospectorPair) mapper.getSerializationConfig()
+ .getAnnotationIntrospector()).allIntrospectors();
+ for (AnnotationIntrospector ai : ais) {
+ if (ai instanceof SimpleNameIntrospector) {
+ // activate filtering
+ ((SimpleNameIntrospector)
ai).setFilteredClasses(filterClass);
+ }
+ }
+ PropertyFilter pf =
SimpleBeanPropertyFilter.filterOutAllExcept(filterAttr);
+ SimpleFilterProvider filter = new SimpleFilterProvider();
+ filter.setDefaultFilter(pf);
+ return mapper.writer(filter).writeValueAsString(list);
+ }
+
+ private ObjectMapper customMapper(boolean withType) {
+ // without copy test fails probably in testsRunInParallel
+ ObjectMapper objectMapper = null;
+ if (withType) {
+ // without copy tests will fail in testsRunInParallel
+ objectMapper = ((Jackson2MapperService)
jsonService).getMapper().copy();
+
objectMapper.enableDefaultTypingAsProperty(DefaultTyping.NON_FINAL, "type");
+ AnnotationIntrospector ai =
objectMapper.getSerializationConfig().getAnnotationIntrospector();
+ AnnotationIntrospector siai = new SimpleNameIntrospector();
+ AnnotationIntrospector pair = new
AnnotationIntrospectorPair(siai, ai);
+ objectMapper.setAnnotationIntrospector(pair);
+ } else {
+ objectMapper = ((Jackson2MapperService)
jsonService).getMapper();
+ }
+ return objectMapper;
+ }
+
+ private List<Bean> getBeans(int randNum) {
+ List<Bean> beans = new ArrayList<Bean>();
+ for (int i = 0; i < 50; i++) {
+ Bean dct = new Bean();
+ dct.setName("title" + i);
+ dct.setAge(randNum + i);
+ dct.profession = "prof" + i;
+ beans.add(dct);
+ }
+ return beans;
+ }
+
+ private String getJson(List<?> list, Class clazz, Boolean refresh,
String... props) {
+ String result = "";
+ try {
+ result = jsonService.serializeOnlyFilter(list, clazz, refresh,
props);
+ } catch (Exception e) {
+ System.out.println(e.getMessage());
+ fail();
+ }
+ return result;
+ }
}
-
+
@Test
public void testsRunInParallel() {
- //Parallel among methods in a class in one thread pool
- Result result = JUnitCore.runClasses(ParallelComputer.methods(),
JSONBeansTests.class);
-
- assertNotNull("Parallel Init exist"+getFailures(result) ,
result.getFailureCount() ==0);
- assertTrue("Parallel Init"+getTrace(result), result.wasSuccessful());
- assertNotNull(fOne);
- assertNotNull(fTwo);
- assertNotNull(fThree);
- assertThat(fOne, is(not(fTwo)));
- assertThat(fTwo, is(not(fThree)));
- assertThat(fOne, is(not(fThree)));
+ // Parallel among methods in a class in one thread pool
+ Result result = JUnitCore.runClasses(ParallelComputer.methods(),
JSONBeansTests.class);
+ System.out.println("fOne:" + fOne);
+ System.out.println("fTwo:" + fTwo);
+ System.out.println("fThree:" + fThree);
+ assertNotNull("Parallel Init exist" + getFailures(result),
result.getFailureCount() == 0);
+ assertTrue("Parallel Init" + getTrace(result), result.wasSuccessful());
+
+ assertNotNull(fOne);
+ assertNotNull(fTwo);
+ assertNotNull(fThree);
+
+ // if multiple where > 1 sometimes the following statements would fail
with high
+ // confidence
+ //
+// assertThat(fOne, is(not(fTwo)));
+// assertThat(fTwo, is(not(fThree)));
+// assertThat(fOne, is(not(fThree)));
}
-
+
public static String getFailures(Result result) {
- List<Failure> failures = result.getFailures() ;
+ List<Failure> failures = result.getFailures();
StringBuffer sb = new StringBuffer();
for (Failure failure : failures) {
- sb.append(failure.getMessage());
- //System.out.println(failure.getMessage());
+ sb.append(failure.getMessage());
+ // System.out.println(failure.getMessage());
}
return sb.toString();
}
-
-
+
public static String getTrace(Result result) {
- List<Failure> failures = result.getFailures() ;
+ List<Failure> failures = result.getFailures();
StringBuffer sb = new StringBuffer();
for (Failure failure : failures) {
failure.getException().printStackTrace();
- if (failure.getException().getCause() != null)
+ if (failure.getException().getCause() != null)
failure.getException().getCause().printStackTrace();
- sb.append(failure.getTrace());
+ sb.append(failure.getTrace());
}
return sb.toString();
}
-
+
public static int randInt(int min, int max) {
Random rand = new Random();
return rand.nextInt((max - min) + 1) + min;
}
-
}