This repository has been archived by the owner on Nov 9, 2017. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 57
/
CopyTransServiceImplPerformanceTest.java
375 lines (323 loc) · 13.7 KB
/
CopyTransServiceImplPerformanceTest.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
package org.zanata.service.impl;
import static com.github.huangp.entityunit.entity.EntityCleaner.deleteAll;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.Hashtable;
import java.util.Map;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.spi.InitialContextFactory;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import liquibase.Liquibase;
import liquibase.database.Database;
import liquibase.database.DatabaseFactory;
import liquibase.database.jvm.JdbcConnection;
import liquibase.resource.ClassLoaderResourceAccessor;
import lombok.extern.slf4j.Slf4j;
import org.apache.log4j.Level;
import org.apache.log4j.LogManager;
import org.assertj.core.api.Assertions;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Environment;
import org.hibernate.dialect.MySQL5Dialect;
import org.hibernate.search.impl.FullTextSessionImpl;
import org.hibernate.search.jpa.Search;
import org.jboss.seam.security.management.JpaIdentityStore;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExternalResource;
import org.junit.rules.TestRule;
import org.zanata.PerformanceProfiling;
import org.zanata.SlowTest;
import org.zanata.common.ContentState;
import org.zanata.common.LocaleId;
import org.zanata.dao.AccountDAO;
import org.zanata.model.HCopyTransOptions;
import org.zanata.model.HDocument;
import org.zanata.model.HLocale;
import org.zanata.model.HProject;
import org.zanata.model.HTextFlowBuilder;
import org.zanata.seam.AutowireTransaction;
import org.zanata.seam.SeamAutowire;
import org.zanata.service.CopyTransService;
import org.zanata.service.SearchIndexManager;
import org.zanata.util.ZanataEntities;
import com.github.huangp.entityunit.entity.EntityMakerBuilder;
import com.github.huangp.entityunit.maker.FixedValueMaker;
import com.google.common.collect.ImmutableMap;
/**
* This is a JUnit test that will setup large data and test the performance of
* copyTrans. JUnit will NOT be executed by maven at the moment (only testNg)
* which is desirable right now, as we don't have a benchmark and do not want to
* slow down our build.
*
* @author Patrick Huang <a
* href="mailto:pahuang@redhat.com">pahuang@redhat.com</a>
*/
@Slf4j
public class CopyTransServiceImplPerformanceTest {
private static final String PERSIST_NAME = "zanataTestDatasourcePU";
private static final String MYSQL_TEST_DB_URL =
"jdbc:log4jdbc:mysql://localhost:3306/zanata_unit_test?characterEncoding=UTF-8";
private static final String MYSQL_DIALECT =
MySQL5Dialect.class.getCanonicalName();
protected static boolean useMysql = true;
// NOTE: if you use mysql and you have the schema created, just change it to
// update will speed up subsequent test run
// private static String hbm2ddl = "create";
protected static String hbm2ddl = "update";
// protected static String hbm2ddl = "validate";
private static final Map<String, String> MySQLProps =
ImmutableMap
.<String, String> builder()
.put(Environment.URL, MYSQL_TEST_DB_URL)
.put(Environment.USER, "root")
.put(Environment.PASS, "root")
.put(Environment.HBM2DDL_AUTO, "")
// .put(Environment.USE_DIRECT_REFERENCE_CACHE_ENTRIES,
// "true")
// .put(Environment.DEFAULT_BATCH_FETCH_SIZE, "50")
// .put(Environment.STATEMENT_BATCH_SIZE, "50")
// .put(Environment.USE_SECOND_LEVEL_CACHE, "false")
// .put(Environment.USE_QUERY_CACHE, "false")
.put(Environment.DIALECT, MYSQL_DIALECT).build();
@ClassRule
public static TestRule entityManagerFactoryRule = new ExternalResource() {
@Override
protected void before() throws Throwable {
log.debug("Initializing EMF");
emf =
Persistence.createEntityManagerFactory(PERSIST_NAME,
useMysql ? MySQLProps : null);
}
@Override
protected void after() {
log.debug("Shutting down EMF");
emf.close();
emf = null;
}
};
@Rule
public TestRule emRule = new ExternalResource() {
@Override
protected void before() throws Throwable {
log.debug("Setting up EM");
em = emf.createEntityManager();
em.getTransaction().begin();
}
@Override
protected void after() {
log.debug("Shutting down EM");
clearHibernateSecondLevelCache();
em.getTransaction().commit();
if (em.isOpen()) {
em.close();
}
em = null;
}
/**
* Clears the Hibernate Second Level cache.
*/
private void clearHibernateSecondLevelCache() {
SessionFactory sessionFactory =
((Session) em.getDelegate()).getSessionFactory();
try {
sessionFactory.getCache().evictEntityRegions();
sessionFactory.getCache().evictCollectionRegions();
} catch (Exception e) {
System.out.println(" *** Cache Exception " + e.getMessage());
}
}
};
private static final Context jndiContext = mock(Context.class);
@ClassRule
public static MockInitialContextRule initialContextRule =
new MockInitialContextRule(
jndiContext);
private static EntityManagerFactory emf;
protected EntityManager em;
private int numOfTextFlows;
private CopyTransService copyTransService;
private HDocument copyTransTargetDoc;
private static SeamAutowire seam = SeamAutowire.instance();
protected EntityManager getEm() {
return em;
}
protected EntityManagerFactory getEmf() {
return emf;
}
protected Session getSession() {
return (Session) em.getDelegate();
}
@Before
public void setUp() throws Exception {
// runLiquibase();
seam.reset()
.use("entityManager", Search.getFullTextEntityManager(getEm()))
.use("entityManagerFactory", getEmf())
.use("session", new FullTextSessionImpl(getSession()))
.use(JpaIdentityStore.AUTHENTICATED_USER,
seam.autowire(AccountDAO.class).getByUsername("demo"))
.useImpl(LocaleServiceImpl.class)
.useImpl(TranslationMemoryServiceImpl.class)
.useImpl(VersionStateCacheImpl.class)
.useImpl(ValidationServiceImpl.class).ignoreNonResolvable();
seam.autowire(SearchIndexManager.class).reindex(true, true, false);
AutowireTransaction.instance().rollback();
copyTransService = seam.autowire(CopyTransServiceImpl.class);
deleteAll(getEm(), ZanataEntities.entitiesForRemoval());
HLocale enUS = makeLocale(LocaleId.EN_US);
HLocale de = makeLocale(LocaleId.DE);
makeLocale(LocaleId.FR);
makeLocale(LocaleId.ES);
// makeLocale(new LocaleId("zh"));
// makeLocale(new LocaleId("ja"));
// makeLocale(new LocaleId("pl"));
HDocument oldDoc =
getEntityMakerBuilder()
.reuseEntity(enUS).build()
.makeAndPersist(getEm(), HDocument.class);
HProject theProject = oldDoc.getProjectIteration().getProject();
copyTransTargetDoc = getEntityMakerBuilder().reuseEntities(theProject,
enUS).build()
.makeAndPersist(getEm(), HDocument.class);
// ensure two documents are from different version but same project
// Assertions.assertThat(oldDoc.getProjectIteration().getId())
// .isNotEqualTo(copyTransTargetDoc.getProjectIteration().getId());
// Assertions
// .assertThat(oldDoc.getProjectIteration().getProject().getId())
// .isEqualTo(
// copyTransTargetDoc.getProjectIteration().getProject()
// .getId());
HTextFlowBuilder textFlowBuilderForOldDoc =
new HTextFlowBuilder().withDocument(oldDoc)
.withTargetLocale(enUS);
// make many text flows all with translations in DE
numOfTextFlows = 5000;
for (int i = 0; i < numOfTextFlows; i++) {
textFlowBuilderForOldDoc.withResId("res" + i)
.withSourceContent("source " + i)
.withTargetContent("target " + i)
.withTargetLocale(de)
.withTargetState(ContentState.Translated).build();
}
HTextFlowBuilder textFlowBuilderForNewDoc =
new HTextFlowBuilder().withDocument(copyTransTargetDoc)
.withTargetLocale(enUS);
for (int i = 0; i < numOfTextFlows; i++) {
textFlowBuilderForNewDoc.withResId("res" + i)
.withSourceContent("source " + i).build();
}
getEm().flush();
getEm().clear();
// Long totalTextFlows =
// getEm().createQuery("select count(*) from HTextFlow",
// Long.class).getSingleResult();
//
// Assertions.assertThat(totalTextFlows).isEqualTo(numOfTextFlows * 2);
// Long totalTranslation =
// getEm().createQuery("select count(*) from HTextFlowTarget",
// Long.class).getSingleResult();
// Assertions.assertThat(totalTranslation).isEqualTo(numOfTextFlows);
// enable logging
LogManager.getLogger(CopyTransServiceImpl.class.getPackage().getName())
.setLevel(Level.DEBUG);
}
// This method will ensure database schema is up to date
private static void runLiquibase() throws Exception {
when(
jndiContext
.lookup("java:global/zanata/files/document-storage-directory"))
.thenReturn("/tmp/doc");
Connection conn = DriverManager
.getConnection(MYSQL_TEST_DB_URL, "root", "root");
Statement statement = conn.createStatement();
statement.executeUpdate("drop schema zanata_unit_test");
statement.executeUpdate("create schema zanata_unit_test");
statement.executeUpdate("use zanata_unit_test");
Database database = DatabaseFactory.getInstance()
.findCorrectDatabaseImplementation(new JdbcConnection(conn));
Liquibase liquibase = new Liquibase("db/db.changelog.xml",
new ClassLoaderResourceAccessor(), database);
liquibase.update("");
}
private HLocale makeLocale(LocaleId localeId) {
HLocale hLocale = new HLocale(localeId);
hLocale.setActive(true);
hLocale.setEnabledByDefault(true);
getEm().persist(hLocale);
return hLocale;
}
private static EntityMakerBuilder getEntityMakerBuilder() {
return EntityMakerBuilder
.builder()
.addFieldOrPropertyMaker(HProject.class,
"sourceViewURL",
FixedValueMaker.EMPTY_STRING_MAKER)
.addConstructorParameterMaker(HDocument.class, 0,
FixedValueMaker.fix("doc1"))
.addConstructorParameterMaker(HDocument.class, 1,
FixedValueMaker.fix("doc1"))
.addConstructorParameterMaker(HDocument.class, 2,
FixedValueMaker.EMPTY_STRING_MAKER);
}
@Test
@Ignore
@SlowTest
@PerformanceProfiling
public void testCopyTransForDocument() throws Exception {
HCopyTransOptions options =
new HCopyTransOptions(
HCopyTransOptions.ConditionRuleAction.DOWNGRADE_TO_FUZZY,
HCopyTransOptions.ConditionRuleAction.DOWNGRADE_TO_FUZZY,
HCopyTransOptions.ConditionRuleAction.DOWNGRADE_TO_FUZZY);
copyTransService
.copyTransForDocument(copyTransTargetDoc, options, null);
Long totalTranslation =
getEm().createQuery("select count(*) from HTextFlowTarget",
Long.class).getSingleResult();
Assertions.assertThat(totalTranslation).isEqualTo(numOfTextFlows * 2);
}
public static class MockInitialContextFactory implements
InitialContextFactory {
private static final ThreadLocal<Context> currentContext =
new ThreadLocal<Context>();
@Override
public Context getInitialContext(Hashtable<?, ?> environment) throws
NamingException {
return currentContext.get();
}
public static void setCurrentContext(Context context) {
currentContext.set(context);
}
public static void clearCurrentContext() {
currentContext.remove();
}
}
public static class MockInitialContextRule extends ExternalResource {
private final Context context;
private MockInitialContextRule(Context context) {
this.context = context;
}
@Override
protected void before() throws Throwable {
System.setProperty(Context.INITIAL_CONTEXT_FACTORY,
MockInitialContextFactory.class.getName());
MockInitialContextFactory.setCurrentContext(context);
}
@Override
protected void after() {
System.clearProperty(Context.INITIAL_CONTEXT_FACTORY);
MockInitialContextFactory.clearCurrentContext();
}
}
}