repo
stringlengths 1
191
⌀ | file
stringlengths 23
351
| code
stringlengths 0
5.32M
| file_length
int64 0
5.32M
| avg_line_length
float64 0
2.9k
| max_line_length
int64 0
288k
| extension_type
stringclasses 1
value |
---|---|---|---|---|---|---|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/hibernate/search/coordination/SearchBean.java
|
/*
*
* * JBoss, Home of Professional Open Source.
* * Copyright $year Red Hat, Inc., and individual contributors
* * as indicated by the @author tags.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
*
*/
package org.jboss.as.test.integration.hibernate.search.coordination;
import java.util.List;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import jakarta.transaction.Transactional;
import org.hibernate.search.mapper.orm.Search;
@ApplicationScoped
@Transactional
public class SearchBean {
@PersistenceContext
EntityManager em;
@SuppressWarnings("unchecked")
public List<String> findAgentNames() {
return em.createNativeQuery("select name from HSEARCH_AGENT")
.getResultList();
}
public void create(String text) {
IndexedEntity entity = new IndexedEntity();
entity.text = text;
em.persist(entity);
}
public List<IndexedEntity> search(String keyword) {
return Search.session(em).search(IndexedEntity.class)
.where(f -> f.match().field("text").matching(keyword))
.fetchAllHits();
}
}
| 1,766 | 30.553571 | 78 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/hibernate/search/coordination/IndexedEntity.java
|
/*
*
* * JBoss, Home of Professional Open Source.
* * Copyright $year Red Hat, Inc., and individual contributors
* * as indicated by the @author tags.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
*
*/
package org.jboss.as.test.integration.hibernate.search.coordination;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import org.hibernate.search.mapper.pojo.mapping.definition.annotation.FullTextField;
import org.hibernate.search.mapper.pojo.mapping.definition.annotation.Indexed;
@Entity
@Indexed
public class IndexedEntity {
@Id
@GeneratedValue
Long id;
@FullTextField
String text;
}
| 1,232 | 29.073171 | 84 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/hibernate/search/backend/lucene/extension/HibernateSearchLuceneDependencyTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.hibernate.search.backend.lucene.extension;
import jakarta.enterprise.context.ApplicationScoped;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.TermQuery;
import org.hibernate.search.backend.lucene.LuceneExtension;
import org.hibernate.search.mapper.orm.Search;
import org.hibernate.search.mapper.pojo.mapping.definition.annotation.FullTextField;
import org.hibernate.search.mapper.pojo.mapping.definition.annotation.Indexed;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.as.test.shared.util.AssumeTestGroupUtil;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.Asset;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.jboss.shrinkwrap.descriptor.api.Descriptors;
import org.jboss.shrinkwrap.descriptor.api.persistence20.PersistenceDescriptor;
import org.jboss.shrinkwrap.descriptor.api.spec.se.manifest.ManifestDescriptor;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import jakarta.inject.Inject;
import jakarta.persistence.Entity;
import jakarta.persistence.EntityManager;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import jakarta.persistence.PersistenceContext;
import jakarta.transaction.Transactional;
import java.util.List;
import static org.junit.Assert.assertEquals;
/**
* Test the ability for applications to use native Lucene classes,
* provided they add a dependency to the Lucene module.
* <p>
* That's necessary because that module, while public, may be unsupported by product vendors
* (because its APIs could change without prior notice).
*/
@RunWith(Arquillian.class)
public class HibernateSearchLuceneDependencyTestCase {
@BeforeClass
public static void securityManagerNotSupportedInHibernateSearch() {
AssumeTestGroupUtil.assumeSecurityManagerDisabled();
}
@Deployment
public static Archive<?> createTestArchive() {
return ShrinkWrap.create(WebArchive.class, HibernateSearchLuceneDependencyTestCase.class.getSimpleName() + ".war")
.addClass(HibernateSearchLuceneDependencyTestCase.class)
.addClasses(SearchBean.class, IndexedEntity.class)
.addAsResource(manifest(), "META-INF/MANIFEST.MF")
.addAsResource(persistenceXml(), "META-INF/persistence.xml")
.addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml");
}
private static Asset manifest() {
String manifest = Descriptors.create(ManifestDescriptor.class)
// This import is absolutely required, that's on purpose:
// Lucene is normally an internal module, which can be used at your own risk.
.attribute("Dependencies", "org.apache.lucene")
.exportAsString();
return new StringAsset(manifest);
}
private static Asset persistenceXml() {
String persistenceXml = Descriptors.create(PersistenceDescriptor.class)
.version("2.0")
.createPersistenceUnit()
.name("primary")
.jtaDataSource("java:jboss/datasources/ExampleDS")
.getOrCreateProperties()
.createProperty().name("hibernate.hbm2ddl.auto").value("create-drop").up()
.createProperty().name("hibernate.search.schema_management.strategy").value("drop-and-create-and-drop").up()
.createProperty().name("hibernate.search.backend.type").value("lucene").up()
.createProperty().name("hibernate.search.backend.lucene_version").value("LUCENE_CURRENT").up()
.createProperty().name("hibernate.search.backend.directory.type").value("local-heap").up()
.up().up()
.exportAsString();
return new StringAsset(persistenceXml);
}
@Inject
private SearchBean searchBean;
@Test
public void test() {
assertEquals(0, searchBean.searchWithNativeQuery("mytoken").size());
searchBean.create("This is MYToken");
assertEquals(1, searchBean.searchWithNativeQuery("mytoken").size());
}
@ApplicationScoped
@Transactional
public static class SearchBean {
@PersistenceContext
EntityManager em;
public void create(String text) {
IndexedEntity entity = new IndexedEntity();
entity.text = text;
em.persist(entity);
}
public List<IndexedEntity> searchWithNativeQuery(String keyword) {
return Search.session(em).search(IndexedEntity.class)
.extension(LuceneExtension.get())
.where(f -> f.fromLuceneQuery(new TermQuery(new Term("text", keyword))))
.fetchAllHits();
}
}
@Entity
@Indexed
public static class IndexedEntity {
@Id
@GeneratedValue
Long id;
@FullTextField
String text;
}
}
| 6,197 | 39.246753 | 124 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/hibernate/search/backend/lucene/simple/HibernateSearchLuceneSimpleTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2014, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.hibernate.search.backend.lucene.simple;
import static org.junit.Assert.assertEquals;
import jakarta.inject.Inject;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.as.test.shared.util.AssumeTestGroupUtil;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Verify deployed applications can use the default Hibernate Search module via Jakarta Persistence APIs.
*
* @author Sanne Grinovero <[email protected]> (C) 2014 Red Hat Inc.
*/
@RunWith(Arquillian.class)
public class HibernateSearchLuceneSimpleTestCase {
private static final String NAME = HibernateSearchLuceneSimpleTestCase.class.getSimpleName();
private static final String JAR_ARCHIVE_NAME = NAME + ".jar";
@BeforeClass
public static void securityManagerNotSupportedInHibernateSearch() {
AssumeTestGroupUtil.assumeSecurityManagerDisabled();
}
@Inject
private SearchBean searchBean;
@Before
@After
public void cleanupDatabase() {
searchBean.deleteAll();
}
@Test
public void testFullTextQuery() {
searchBean.storeNewBook("Hello");
searchBean.storeNewBook("Hello world");
searchBean.storeNewBook("Hello planet Mars");
assertEquals(3, searchBean.findByKeyword("hello").size());
assertEquals(1, searchBean.findByKeyword("mars").size());
// Search should be case-insensitive thanks to the default analyzer
assertEquals(3, searchBean.findByKeyword("HELLO").size());
}
@Test
public void testAnalysisConfiguration() {
searchBean.storeNewBook("Hello");
searchBean.storeNewBook("Hello world");
searchBean.storeNewBook("Hello planet Mars");
// This search relies on a custom analyzer configured in AnalysisConfigurationProvider;
// if it works, then our custom analysis configuration was taken into account.
assertEquals(3, searchBean.findAutocomplete("he").size());
assertEquals(1, searchBean.findAutocomplete("he wo").size());
assertEquals(1, searchBean.findAutocomplete("he pl").size());
}
@Deployment
public static Archive<?> deploy() throws Exception {
// TODO maybe just use managed=false and deploy in the @BeforeClass / undeploy in an @AfterClass
if (AssumeTestGroupUtil.isSecurityManagerEnabled()) {
return AssumeTestGroupUtil.emptyJar(JAR_ARCHIVE_NAME);
}
JavaArchive jar = ShrinkWrap.create(JavaArchive.class, JAR_ARCHIVE_NAME);
// add Jakarta Persistence configuration
jar.addAsManifestResource(HibernateSearchLuceneSimpleTestCase.class.getPackage(), "persistence.xml", "persistence.xml");
// add testing Bean and entities
jar.addClasses(SearchBean.class, Book.class, HibernateSearchLuceneSimpleTestCase.class, AnalysisConfigurer.class);
return jar;
}
}
| 4,193 | 38.566038 | 128 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/hibernate/search/backend/lucene/simple/SearchBean.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2018, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.hibernate.search.backend.lucene.simple;
import jakarta.enterprise.context.ApplicationScoped;
import org.hibernate.search.engine.search.common.BooleanOperator;
import org.hibernate.search.mapper.orm.Search;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import jakarta.persistence.criteria.CriteriaDelete;
import jakarta.transaction.Transactional;
import java.util.List;
@ApplicationScoped
@Transactional
public class SearchBean {
@PersistenceContext
EntityManager em;
public void storeNewBook(String title) {
Book book = new Book();
book.title = title;
em.persist(book);
}
public void deleteAll() {
CriteriaDelete<Book> delete = em.getCriteriaBuilder()
.createCriteriaDelete(Book.class);
delete.from(Book.class);
em.createQuery(delete).executeUpdate();
Search.session(em).workspace(Book.class).purge();
}
public List<Book> findByKeyword(String keyword) {
return Search.session(em).search(Book.class)
.where(f -> f.match().field("title").matching(keyword))
.fetchAllHits();
}
public List<Book> findAutocomplete(String term) {
return Search.session(em).search(Book.class)
.where(f -> f.simpleQueryString().field("title_autocomplete")
.matching(term)
.defaultOperator(BooleanOperator.AND))
.fetchAllHits();
}
}
| 2,560 | 35.585714 | 77 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/hibernate/search/backend/lucene/simple/Book.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2018, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.hibernate.search.backend.lucene.simple;
import org.hibernate.search.mapper.pojo.mapping.definition.annotation.FullTextField;
import org.hibernate.search.mapper.pojo.mapping.definition.annotation.Indexed;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
@Entity
@Indexed
public class Book {
@Id
@GeneratedValue
Long id;
@FullTextField
@FullTextField(name = "title_autocomplete",
analyzer = AnalysisConfigurer.AUTOCOMPLETE,
searchAnalyzer = AnalysisConfigurer.AUTOCOMPLETE_QUERY)
String title;
}
| 1,669 | 35.304348 | 84 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/hibernate/search/backend/lucene/simple/AnalysisConfigurer.java
|
package org.jboss.as.test.integration.hibernate.search.backend.lucene.simple;
import org.hibernate.search.backend.lucene.analysis.LuceneAnalysisConfigurationContext;
import org.hibernate.search.backend.lucene.analysis.LuceneAnalysisConfigurer;
public class AnalysisConfigurer
implements LuceneAnalysisConfigurer {
public static final String AUTOCOMPLETE = "autocomplete";
public static final String AUTOCOMPLETE_QUERY = "autocomplete-query";
@Override
public void configure(LuceneAnalysisConfigurationContext context) {
context.analyzer(AUTOCOMPLETE).custom()
.tokenizer("whitespace")
.tokenFilter("lowercase")
.tokenFilter("asciiFolding")
.tokenFilter("edgeNGram")
.param("minGramSize", "1")
.param("maxGramSize", "10");
context.analyzer(AUTOCOMPLETE_QUERY).custom()
.tokenizer("whitespace")
.tokenFilter("lowercase")
.tokenFilter("asciiFolding");
}
}
| 1,060 | 39.807692 | 87 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/hibernate/search/backend/lucene/massindexer/HibernateSearchLuceneEarMassIndexerTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.hibernate.search.backend.lucene.massindexer;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.as.test.shared.util.AssumeTestGroupUtil;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.Asset;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.EnterpriseArchive;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.jboss.shrinkwrap.descriptor.api.Descriptors;
import org.jboss.shrinkwrap.descriptor.api.application6.ApplicationDescriptor;
import org.jboss.shrinkwrap.descriptor.api.persistence20.PersistenceDescriptor;
import org.jboss.shrinkwrap.descriptor.api.spec.se.manifest.ManifestDescriptor;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import jakarta.inject.Inject;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
/**
* @author Hardy Ferentschik
*/
@RunWith(Arquillian.class)
public class HibernateSearchLuceneEarMassIndexerTestCase {
private static final String NAME = HibernateSearchLuceneEarMassIndexerTestCase.class.getSimpleName();
private static final String EAR_ARCHIVE_NAME = NAME + ".ear";
private static final String WAR_ARCHIVE_NAME = NAME + ".war";
private static final String EJB_ARCHIVE_NAME = NAME + ".jar";
@BeforeClass
public static void securityManagerNotSupportedInHibernateSearch() {
AssumeTestGroupUtil.assumeSecurityManagerDisabled();
}
@Deployment
public static EnterpriseArchive createTestEAR() {
JavaArchive ejb = ShrinkWrap
.create(JavaArchive.class, EJB_ARCHIVE_NAME)
.addAsResource(ejbManifest(), "META-INF/MANIFEST.MF")
.addClasses(Singer.class, SingersSingleton.class);
WebArchive war = ShrinkWrap
.create(WebArchive.class, WAR_ARCHIVE_NAME)
.addClasses(HibernateSearchLuceneEarMassIndexerTestCase.class)
.addAsResource(warManifest(), "META-INF/MANIFEST.MF")
.addAsResource(persistenceXml(), "META-INF/persistence.xml")
.addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml");
return ShrinkWrap.create(EnterpriseArchive.class, EAR_ARCHIVE_NAME)
.addAsModules(ejb)
.addAsModule(war)
.setApplicationXML(applicationXml());
}
private static Asset ejbManifest() {
String manifest = Descriptors.create(ManifestDescriptor.class)
.attribute("Dependencies", "org.hibernate.search.mapper.orm services,org.hibernate.search.backend.lucene services")
.exportAsString();
return new StringAsset(manifest);
}
private static Asset persistenceXml() {
String persistenceXml = Descriptors.create(PersistenceDescriptor.class)
.version("2.0")
.createPersistenceUnit()
.name("cmt-test")
.jtaDataSource("java:jboss/datasources/ExampleDS")
.clazz(Singer.class.getName())
.getOrCreateProperties()
.createProperty().name("hibernate.hbm2ddl.auto").value("create").up()
.createProperty().name("hibernate.search.schema_management.strategy").value("drop-and-create-and-drop").up()
.createProperty().name("hibernate.search.backend.type").value("lucene").up()
.createProperty().name("hibernate.search.backend.lucene_version").value("LUCENE_CURRENT").up()
.createProperty().name("hibernate.search.backend.directory.type").value("local-heap").up()
.createProperty().name("hibernate.search.automatic_indexing.enabled").value("false").up()
.up().up()
.exportAsString();
return new StringAsset(persistenceXml);
}
private static Asset applicationXml() {
String applicationXml = Descriptors.create(ApplicationDescriptor.class)
.applicationName(NAME)
.createModule()
.ejb(EJB_ARCHIVE_NAME)
.getOrCreateWeb()
.webUri(WAR_ARCHIVE_NAME)
.contextRoot("test")
.up().up()
.exportAsString();
return new StringAsset(applicationXml);
}
private static Asset warManifest() {
String manifest = Descriptors.create(ManifestDescriptor.class)
.addToClassPath(EJB_ARCHIVE_NAME)
.exportAsString();
return new StringAsset(manifest);
}
@Inject
private SingersSingleton singersEjb;
@Test
public void testMassIndexerWorks() throws Exception {
assertNotNull(singersEjb);
singersEjb.insertContact("John", "Lennon");
singersEjb.insertContact("Paul", "McCartney");
singersEjb.insertContact("George", "Harrison");
singersEjb.insertContact("Ringo", "Starr");
assertEquals("Don't you know the Beatles?", 4, singersEjb.listAllContacts().size());
assertEquals("Beatles should not yet be indexed", 0, singersEjb.searchAllContacts().size());
assertTrue("Indexing the Beatles failed.", singersEjb.rebuildIndex());
assertEquals("Now the Beatles should be indexed", 4, singersEjb.searchAllContacts().size());
}
}
| 6,581 | 43.472973 | 131 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/hibernate/search/backend/lucene/massindexer/SingersSingleton.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.hibernate.search.backend.lucene.massindexer;
import org.hibernate.CacheMode;
import org.hibernate.search.mapper.orm.Search;
import jakarta.ejb.Singleton;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.PersistenceContext;
import jakarta.persistence.PersistenceUnit;
import jakarta.persistence.Query;
import java.util.List;
/**
* A singleton session bean.
*
* @author Hardy Ferentschik
*/
@Singleton
public class SingersSingleton {
@PersistenceUnit(name = "cmt-test")
private EntityManagerFactory entityManagerFactory;
@PersistenceContext(unitName = "cmt-test")
private EntityManager entityManager;
public void insertContact(String firstName, String lastName) {
Singer singer = new Singer();
singer.setFirstName(firstName);
singer.setLastName(lastName);
entityManager.persist(singer);
}
public boolean rebuildIndex() {
try {
Search.mapping(entityManagerFactory).scope(Object.class).massIndexer()
.batchSizeToLoadObjects(30)
.threadsToLoadObjects(4)
.cacheMode(CacheMode.NORMAL)
.startAndWait();
} catch (Exception e) {
return false;
}
return true;
}
public List<?> listAllContacts() {
Query query = entityManager.createQuery("select s from Singer s");
return query.getResultList();
}
public List<?> searchAllContacts() {
return Search.session(entityManager).search(Singer.class)
.where(f -> f.matchAll())
.fetchAllHits();
}
}
| 2,741 | 33.275 | 82 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/hibernate/search/backend/lucene/massindexer/Singer.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.hibernate.search.backend.lucene.massindexer;
import org.hibernate.search.mapper.pojo.mapping.definition.annotation.FullTextField;
import org.hibernate.search.mapper.pojo.mapping.definition.annotation.Indexed;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import java.io.Serializable;
@Entity
@Indexed
public class Singer implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@FullTextField
private String firstName;
@FullTextField
private String lastName;
public long getId() {
return this.id;
}
public void setId(long id) {
this.id = id;
}
public String getFirstName() {
return this.firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return this.lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
@Override
public String toString() {
return "[#" + id + "] " + lastName + ", " + firstName;
}
}
| 2,318 | 27.9875 | 84 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/hibernate/search/backend/lucene/projectionconstructor/SearchBean.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2023, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.hibernate.search.backend.lucene.projectionconstructor;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import jakarta.persistence.criteria.CriteriaDelete;
import jakarta.transaction.Transactional;
import org.hibernate.search.mapper.orm.Search;
import java.util.List;
@ApplicationScoped
@Transactional
public class SearchBean {
@PersistenceContext
EntityManager em;
public void storeNewBook(BookDTO bookDTO) {
Book book = new Book();
book.setId(bookDTO.id);
book.setTitle(bookDTO.title);
for (AuthorDTO authorDTO : bookDTO.authors) {
Author author = new Author();
author.setFirstName(authorDTO.firstName);
author.setLastName(authorDTO.lastName);
author.getBooks().add(book);
book.getAuthors().add(author);
em.persist(author);
}
em.persist(book);
}
public void deleteAll() {
CriteriaDelete<Book> deleteBooks = em.getCriteriaBuilder()
.createCriteriaDelete(Book.class);
deleteBooks.from(Book.class);
em.createQuery(deleteBooks).executeUpdate();
CriteriaDelete<Author> deleteAuthors = em.getCriteriaBuilder()
.createCriteriaDelete(Author.class);
deleteAuthors.from(Author.class);
em.createQuery(deleteAuthors).executeUpdate();
Search.session(em).workspace(Book.class).purge();
}
public List<BookDTO> findByKeyword(String keyword) {
return Search.session(em).search(Book.class)
.select(BookDTO.class)
.where(f -> f.match().field("title").matching(keyword))
.fetchAllHits();
}
}
| 2,834 | 35.818182 | 92 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/hibernate/search/backend/lucene/projectionconstructor/BookDTO.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2023, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.hibernate.search.backend.lucene.projectionconstructor;
import org.hibernate.search.mapper.pojo.mapping.definition.annotation.FieldProjection;
import org.hibernate.search.mapper.pojo.mapping.definition.annotation.IdProjection;
import org.hibernate.search.mapper.pojo.mapping.definition.annotation.ObjectProjection;
import org.hibernate.search.mapper.pojo.mapping.definition.annotation.ProjectionConstructor;
import java.util.List;
public class BookDTO {
public final long id;
public final String title;
public final List<AuthorDTO> authors;
@ProjectionConstructor
public BookDTO(@IdProjection long id,
// This @FieldProjection annotations and @ObjectProjection.path wouldn't be necessary
// with a record or a class compiled with -parameters
@FieldProjection(path = "title") String title,
@ObjectProjection(path = "authors", includeDepth = 1) List<AuthorDTO> authors) {
this.id = id;
this.title = title;
this.authors = authors;
}
}
| 2,120 | 44.12766 | 104 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/hibernate/search/backend/lucene/projectionconstructor/Author.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2023, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.hibernate.search.backend.lucene.projectionconstructor;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import jakarta.persistence.ManyToMany;
import org.hibernate.search.engine.backend.types.Projectable;
import org.hibernate.search.mapper.pojo.mapping.definition.annotation.FullTextField;
import java.util.ArrayList;
import java.util.List;
@Entity
public class Author {
@Id
@GeneratedValue
private Long id;
@FullTextField(projectable = Projectable.YES)
private String firstName;
@FullTextField(projectable = Projectable.YES)
private String lastName;
@ManyToMany(mappedBy = "authors")
private List<Book> books = new ArrayList<>();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public List<Book> getBooks() {
return books;
}
public void setBooks(List<Book> books) {
this.books = books;
}
}
| 2,369 | 27.902439 | 92 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/hibernate/search/backend/lucene/projectionconstructor/Book.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2023, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.hibernate.search.backend.lucene.projectionconstructor;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.ManyToMany;
import jakarta.persistence.OrderColumn;
import org.hibernate.search.engine.backend.types.ObjectStructure;
import org.hibernate.search.engine.backend.types.Projectable;
import org.hibernate.search.mapper.pojo.mapping.definition.annotation.FullTextField;
import org.hibernate.search.mapper.pojo.mapping.definition.annotation.Indexed;
import org.hibernate.search.mapper.pojo.mapping.definition.annotation.IndexedEmbedded;
import java.util.ArrayList;
import java.util.List;
@Entity
@Indexed
public class Book {
@Id
private Long id;
@FullTextField(projectable = Projectable.YES)
private String title;
@IndexedEmbedded(includeDepth = 1, structure = ObjectStructure.NESTED)
@ManyToMany
@OrderColumn
private List<Author> authors = new ArrayList<>();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public List<Author> getAuthors() {
return authors;
}
public void setAuthors(List<Author> authors) {
this.authors = authors;
}
}
| 2,413 | 30.763158 | 92 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/hibernate/search/backend/lucene/projectionconstructor/AuthorDTO.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2023, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.hibernate.search.backend.lucene.projectionconstructor;
import org.hibernate.search.mapper.pojo.mapping.definition.annotation.FieldProjection;
import org.hibernate.search.mapper.pojo.mapping.definition.annotation.ObjectProjection;
import org.hibernate.search.mapper.pojo.mapping.definition.annotation.ProjectionConstructor;
import java.util.Collections;
import java.util.List;
public class AuthorDTO {
public final String firstName;
public final String lastName;
public final List<BookDTO> books;
public AuthorDTO(String firstName, String lastName) {
this(firstName, lastName, Collections.emptyList());
}
@ProjectionConstructor
public AuthorDTO(// These @FieldProjection annotations and @ObjectProjection.path wouldn't be necessary
// with a record or a class compiled with -parameters
@FieldProjection(path = "firstName") String firstName,
@FieldProjection(path = "lastName") String lastName,
@ObjectProjection(path = "books", includeDepth = 1) List<BookDTO> books) {
this.firstName = firstName;
this.lastName = lastName;
this.books = books;
}
}
| 2,260 | 43.333333 | 107 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/hibernate/search/backend/lucene/projectionconstructor/HibernateSearchLuceneProjectionConstructorTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2023, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.hibernate.search.backend.lucene.projectionconstructor;
import jakarta.inject.Inject;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.as.test.shared.util.AssumeTestGroupUtil;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.assertEquals;
/**
* Verify deployed applications can use Hibernate Search's @ProjectionConstructor with Lucene.
*/
@RunWith(Arquillian.class)
public class HibernateSearchLuceneProjectionConstructorTestCase {
private static final String NAME = HibernateSearchLuceneProjectionConstructorTestCase.class.getSimpleName();
private static final String JAR_ARCHIVE_NAME = NAME + ".jar";
@BeforeClass
public static void securityManagerNotSupportedInHibernateSearch() {
AssumeTestGroupUtil.assumeSecurityManagerDisabled();
}
@Inject
private SearchBean searchBean;
@Before
@After
public void cleanupDatabase() {
searchBean.deleteAll();
}
@Test
public void testProjection() {
BookDTO book1 = new BookDTO(1, "Hello world",
Arrays.asList(new AuthorDTO("John", "Smith")));
searchBean.storeNewBook(book1);
BookDTO book2 = new BookDTO(2, "Hello planet Mars",
Arrays.asList(new AuthorDTO("Jane", "Green"),
new AuthorDTO("John", "Doe")));
searchBean.storeNewBook(book2);
List<BookDTO> hits = searchBean.findByKeyword("world");
assertEquals(1, hits.size());
assertSearchHit(book1, hits.get(0));
hits = searchBean.findByKeyword("mars");
assertEquals(1, hits.size());
assertSearchHit(book2, hits.get(0));
}
private static void assertSearchHit(BookDTO expected, BookDTO hit) {
assertEquals(expected.id, hit.id);
assertEquals(expected.title, hit.title);
assertEquals(expected.authors.size(), hit.authors.size());
for (int i = 0; i < expected.authors.size(); i++) {
AuthorDTO expectedAuthor = expected.authors.get(i);
AuthorDTO hitAuthor = hit.authors.get(i);
assertEquals(expectedAuthor.firstName, hitAuthor.firstName);
assertEquals(expectedAuthor.lastName, hitAuthor.lastName);
// We use includeDepth = 1 on BookDTO#authors, so book.authors.books should be empty
assertEquals(0, hitAuthor.books.size());
}
}
@Deployment
public static Archive<?> deploy() throws Exception {
// TODO maybe just use managed=false and deploy in the @BeforeClass / undeploy in an @AfterClass
// see HibernateSearchLuceneSimpleTestCase
if (AssumeTestGroupUtil.isSecurityManagerEnabled()) {
return AssumeTestGroupUtil.emptyJar(JAR_ARCHIVE_NAME);
}
JavaArchive jar = ShrinkWrap.create(JavaArchive.class, JAR_ARCHIVE_NAME);
// add Jakarta Persistence configuration
jar.addAsManifestResource(HibernateSearchLuceneProjectionConstructorTestCase.class.getPackage(),
"persistence.xml", "persistence.xml");
// add testing Bean and entities
jar.addClasses(SearchBean.class, Book.class, Author.class, BookDTO.class, AuthorDTO.class,
HibernateSearchLuceneProjectionConstructorTestCase.class);
return jar;
}
}
| 4,694 | 38.453782 | 112 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/hibernate/search/backend/elasticsearch/extension/HibernateSearchElasticsearchGsonDependencyTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.hibernate.search.backend.elasticsearch.extension;
import com.google.gson.JsonObject;
import jakarta.enterprise.context.ApplicationScoped;
import org.hibernate.search.backend.elasticsearch.ElasticsearchExtension;
import org.hibernate.search.mapper.orm.Search;
import org.hibernate.search.mapper.pojo.mapping.definition.annotation.FullTextField;
import org.hibernate.search.mapper.pojo.mapping.definition.annotation.Indexed;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.core.api.annotation.Observer;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.as.test.integration.hibernate.search.backend.elasticsearch.util.ElasticsearchServerSetupObserver;
import org.jboss.as.test.shared.util.AssumeTestGroupUtil;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.Asset;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.jboss.shrinkwrap.descriptor.api.Descriptors;
import org.jboss.shrinkwrap.descriptor.api.persistence20.PersistenceDescriptor;
import org.jboss.shrinkwrap.descriptor.api.spec.se.manifest.ManifestDescriptor;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import jakarta.inject.Inject;
import jakarta.persistence.Entity;
import jakarta.persistence.EntityManager;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import jakarta.persistence.PersistenceContext;
import jakarta.transaction.Transactional;
import java.util.List;
import static org.junit.Assert.assertEquals;
/**
* Test the ability for applications to use native Gson classes,
* provided they add a dependency to the Gson module.
* <p>
* That's necessary because that module, while public, may be unsupported by product vendors
* (because its APIs could change without prior notice).
*/
@RunWith(Arquillian.class)
@Observer(ElasticsearchServerSetupObserver.class)
public class HibernateSearchElasticsearchGsonDependencyTestCase {
@BeforeClass
public static void testRequiresDocker() {
AssumeTestGroupUtil.assumeDockerAvailable();
}
@BeforeClass
public static void securityManagerNotSupportedInHibernateSearch() {
AssumeTestGroupUtil.assumeSecurityManagerDisabled();
}
@Deployment
public static Archive<?> createTestArchive() throws Exception {
if (!AssumeTestGroupUtil.isDockerAvailable() || !AssumeTestGroupUtil.isSecurityManagerDisabled()) {
return AssumeTestGroupUtil.emptyWar(HibernateSearchElasticsearchGsonDependencyTestCase.class.getSimpleName());
}
return ShrinkWrap.create(WebArchive.class, HibernateSearchElasticsearchGsonDependencyTestCase.class.getSimpleName() + ".war")
.addClass(HibernateSearchElasticsearchGsonDependencyTestCase.class)
.addClasses(SearchBean.class, IndexedEntity.class, AssumeTestGroupUtil.class)
.addAsResource(manifest(), "META-INF/MANIFEST.MF")
.addAsResource(persistenceXml(), "META-INF/persistence.xml")
.addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml");
}
private static Asset manifest() {
String manifest = Descriptors.create(ManifestDescriptor.class)
.attribute("Dependencies", "com.google.code.gson")
.exportAsString();
return new StringAsset(manifest);
}
private static Asset persistenceXml() {
String persistenceXml = Descriptors.create(PersistenceDescriptor.class)
.version("2.0")
.createPersistenceUnit()
.name("primary")
.jtaDataSource("java:jboss/datasources/ExampleDS")
.getOrCreateProperties()
.createProperty().name("hibernate.hbm2ddl.auto").value("create-drop").up()
.createProperty().name("hibernate.search.schema_management.strategy").value("drop-and-create-and-drop").up()
.createProperty().name("hibernate.search.automatic_indexing.synchronization.strategy").value("sync").up()
.createProperty().name("hibernate.search.backend.type").value("elasticsearch").up()
.createProperty().name("hibernate.search.backend.hosts").value(ElasticsearchServerSetupObserver.getHttpHostAddress()).up()
.up().up()
.exportAsString();
return new StringAsset(persistenceXml);
}
@Inject
private SearchBean searchBean;
@Test
public void test() {
assertEquals(0, searchBean.searchWithNativeQuery("mytoken").size());
searchBean.create("This is MYToken");
assertEquals(1, searchBean.searchWithNativeQuery("mytoken").size());
}
@ApplicationScoped
@Transactional
public static class SearchBean {
@PersistenceContext
EntityManager em;
public void create(String text) {
IndexedEntity entity = new IndexedEntity();
entity.text = text;
em.persist(entity);
}
public List<IndexedEntity> searchWithNativeQuery(String keyword) {
return Search.session(em).search(IndexedEntity.class)
.extension(ElasticsearchExtension.get())
.where(f -> {
JsonObject outer = new JsonObject();
JsonObject term = new JsonObject();
outer.add("term", term);
JsonObject inner = new JsonObject();
term.add("text", inner);
inner.addProperty("value", keyword);
return f.fromJson(outer);
})
.fetchAllHits();
}
}
@Entity
@Indexed
public static class IndexedEntity {
@Id
@GeneratedValue
Long id;
@FullTextField
String text;
}
}
| 7,082 | 40.180233 | 138 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/hibernate/search/backend/elasticsearch/simple/SearchBean.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2018, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.hibernate.search.backend.elasticsearch.simple;
import jakarta.enterprise.context.ApplicationScoped;
import org.hibernate.search.engine.search.common.BooleanOperator;
import org.hibernate.search.mapper.orm.Search;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import jakarta.persistence.criteria.CriteriaDelete;
import jakarta.transaction.Transactional;
import java.util.List;
@ApplicationScoped
@Transactional
public class SearchBean {
@PersistenceContext
EntityManager em;
public void storeNewBook(String title) {
Book book = new Book();
book.title = title;
em.persist(book);
}
public void deleteAll() {
CriteriaDelete<Book> delete = em.getCriteriaBuilder()
.createCriteriaDelete(Book.class);
delete.from(Book.class);
em.createQuery(delete).executeUpdate();
Search.session(em).workspace(Book.class).purge();
}
public List<Book> findByKeyword(String keyword) {
return Search.session(em).search(Book.class)
.where(f -> f.match().field("title").matching(keyword))
.fetchAllHits();
}
public List<Book> findAutocomplete(String term) {
return Search.session(em).search(Book.class)
.where(f -> f.simpleQueryString().field("title_autocomplete")
.matching(term)
.defaultOperator(BooleanOperator.AND))
.fetchAllHits();
}
}
| 2,567 | 35.685714 | 84 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/hibernate/search/backend/elasticsearch/simple/Book.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2018, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.hibernate.search.backend.elasticsearch.simple;
import org.hibernate.search.mapper.pojo.mapping.definition.annotation.FullTextField;
import org.hibernate.search.mapper.pojo.mapping.definition.annotation.Indexed;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
@Entity
@Indexed
public class Book {
@Id
@GeneratedValue
Long id;
@FullTextField
@FullTextField(name = "title_autocomplete",
analyzer = AnalysisConfigurer.AUTOCOMPLETE,
searchAnalyzer = AnalysisConfigurer.AUTOCOMPLETE_QUERY)
String title;
}
| 1,676 | 35.456522 | 84 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/hibernate/search/backend/elasticsearch/simple/AnalysisConfigurer.java
|
package org.jboss.as.test.integration.hibernate.search.backend.elasticsearch.simple;
import org.hibernate.search.backend.elasticsearch.analysis.ElasticsearchAnalysisConfigurationContext;
import org.hibernate.search.backend.elasticsearch.analysis.ElasticsearchAnalysisConfigurer;
public class AnalysisConfigurer
implements ElasticsearchAnalysisConfigurer {
public static final String AUTOCOMPLETE = "autocomplete";
public static final String AUTOCOMPLETE_QUERY = "autocomplete-query";
@Override
public void configure(ElasticsearchAnalysisConfigurationContext context) {
context.analyzer(AUTOCOMPLETE).custom()
.tokenizer("whitespace")
.tokenFilters("lowercase", "asciifolding", "my-edge-ngram");
context.tokenFilter("my-edge-ngram").type("edge_ngram")
.param("min_gram", 1)
.param("max_gram", 10);
context.analyzer(AUTOCOMPLETE_QUERY).custom()
.tokenizer("whitespace")
.tokenFilters("lowercase", "asciifolding");
}
}
| 1,068 | 41.76 | 101 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/hibernate/search/backend/elasticsearch/simple/HibernateSearchElasticsearchSimpleTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2014, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.hibernate.search.backend.elasticsearch.simple;
import jakarta.inject.Inject;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.core.api.annotation.Observer;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.as.test.integration.hibernate.search.backend.elasticsearch.massindexer.Singer;
import org.jboss.as.test.integration.hibernate.search.backend.elasticsearch.util.ElasticsearchServerSetupObserver;
import org.jboss.as.test.shared.util.AssumeTestGroupUtil;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.Asset;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.jboss.shrinkwrap.descriptor.api.Descriptors;
import org.jboss.shrinkwrap.descriptor.api.persistence20.PersistenceDescriptor;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.assertEquals;
/**
* Verify deployed applications can use the default Hibernate Search module via Jakarta Persistence APIs.
*
* @author Sanne Grinovero <[email protected]> (C) 2014 Red Hat Inc.
*/
@RunWith(Arquillian.class)
@Observer(ElasticsearchServerSetupObserver.class)
public class HibernateSearchElasticsearchSimpleTestCase {
private static final String NAME = HibernateSearchElasticsearchSimpleTestCase.class.getSimpleName();
private static final String WAR_ARCHIVE_NAME = NAME + ".war";
@BeforeClass
public static void testRequiresDocker() {
AssumeTestGroupUtil.assumeDockerAvailable();
}
@BeforeClass
public static void securityManagerNotSupportedInHibernateSearch() {
AssumeTestGroupUtil.assumeSecurityManagerDisabled();
}
@Deployment
public static WebArchive createArchive() {
// TODO maybe just use managed=false and deploy in the @BeforeClass / undeploy in an @AfterClass
if (!AssumeTestGroupUtil.isDockerAvailable() || AssumeTestGroupUtil.isSecurityManagerEnabled()) {
return AssumeTestGroupUtil.emptyWar(WAR_ARCHIVE_NAME);
}
return ShrinkWrap
.create(WebArchive.class, WAR_ARCHIVE_NAME)
.addClasses(HibernateSearchElasticsearchSimpleTestCase.class,
SearchBean.class, Book.class, HibernateSearchElasticsearchSimpleTestCase.class,
AnalysisConfigurer.class, AssumeTestGroupUtil.class)
.addAsResource(persistenceXml(), "META-INF/persistence.xml")
.addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml");
}
private static Asset persistenceXml() {
String persistenceXml = Descriptors.create(PersistenceDescriptor.class)
.version("2.0")
.createPersistenceUnit()
.name("jpa-search-test-pu")
.jtaDataSource("java:jboss/datasources/ExampleDS")
.clazz(Singer.class.getName())
.getOrCreateProperties()
.createProperty().name("hibernate.hbm2ddl.auto").value("create-drop").up()
.createProperty().name("hibernate.search.schema_management.strategy").value("drop-and-create-and-drop").up()
.createProperty().name("hibernate.search.automatic_indexing.synchronization.strategy").value("sync").up()
.createProperty().name("hibernate.search.backend.type").value("elasticsearch").up()
.createProperty().name("hibernate.search.backend.hosts").value(ElasticsearchServerSetupObserver.getHttpHostAddress()).up()
.createProperty().name("hibernate.search.backend.analysis.configurer").value(AnalysisConfigurer.class.getName()).up()
.up().up()
.exportAsString();
return new StringAsset(persistenceXml);
}
@Inject
private SearchBean searchBean;
@Before
@After
public void cleanupDatabase() {
searchBean.deleteAll();
}
@Test
public void testFullTextQuery() {
searchBean.storeNewBook("Hello");
searchBean.storeNewBook("Hello world");
searchBean.storeNewBook("Hello planet Mars");
assertEquals(3, searchBean.findByKeyword("hello").size());
assertEquals(1, searchBean.findByKeyword("mars").size());
// Search should be case-insensitive thanks to the default analyzer
assertEquals(3, searchBean.findByKeyword("HELLO").size());
}
@Test
public void testAnalysisConfiguration() {
searchBean.storeNewBook("Hello");
searchBean.storeNewBook("Hello world");
searchBean.storeNewBook("Hello planet Mars");
// This search relies on a custom analyzer configured in AnalysisConfigurationProvider;
// if it works, then our custom analysis configuration was taken into account.
assertEquals(3, searchBean.findAutocomplete("he").size());
assertEquals(1, searchBean.findAutocomplete("he wo").size());
assertEquals(1, searchBean.findAutocomplete("he pl").size());
}
}
| 6,202 | 44.277372 | 138 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/hibernate/search/backend/elasticsearch/util/ElasticsearchServerSetupObserver.java
|
package org.jboss.as.test.integration.hibernate.search.backend.elasticsearch.util;
import org.jboss.arquillian.container.spi.event.StartClassContainers;
import org.jboss.arquillian.container.spi.event.StopClassContainers;
import org.jboss.arquillian.core.api.annotation.Observes;
import org.jboss.as.test.shared.util.AssumeTestGroupUtil;
import org.testcontainers.elasticsearch.ElasticsearchContainer;
import java.util.concurrent.atomic.AtomicReference;
public class ElasticsearchServerSetupObserver {
private static final String ELASTICSEARCH_IMAGE = "docker.elastic.co/elasticsearch/elasticsearch:8.8.2";
private static final AtomicReference<String> httpHostAddress = new AtomicReference<>();
public static String getHttpHostAddress() {
String address = httpHostAddress.get();
if (address == null) {
throw new IllegalStateException(ElasticsearchServerSetupObserver.class + " wasn't notified of the StartClassContainers event");
}
return address;
}
private final Object elasticsearchContainer;
public ElasticsearchServerSetupObserver() {
// This observer can be invoked by Arquillian in environments where Docker is not available,
// even though the test itself is disabled, e.g. with an org.junit.Assume in a @BeforeClass method.
// Hence this hack: if Docker is not available,
// we simply don't create a container and the observer acts as a no-op.
if (!AssumeTestGroupUtil.isDockerAvailable()) {
this.elasticsearchContainer = null;
return;
}
try {
// Unfortunately the observer is automatically installed on the server side too,
// where it simply cannot work due to testcontainers not being available.
// Hence this hack: if testcontainers is not available,
// we simply don't create a container and the observer acts as a no-op.
Class.forName( "org.testcontainers.elasticsearch.ElasticsearchContainer" );
} catch (ClassNotFoundException e) {
this.elasticsearchContainer = null;
return;
}
this.elasticsearchContainer = new ElasticsearchContainer(ELASTICSEARCH_IMAGE)
// Limit the RAM usage.
// Recent versions of ES limit themselves to 50% of the total available RAM,
// but on CI this can be too much, as we also have the Maven JVM
// and the JVMs that runs tests taking up a significant amount of RAM.
.withEnv("ES_JAVA_OPTS", "-Xms1g -Xmx1g")
.withEnv("xpack.security.enabled", "false")
.withEnv("cluster.routing.allocation.disk.threshold_enabled", "false");
}
public void startElasticsearch(@Observes StartClassContainers event) {
ElasticsearchContainer theContainer = (ElasticsearchContainer) elasticsearchContainer;
if (theContainer != null) {
theContainer.start();
if (!httpHostAddress.compareAndSet(null, theContainer.getHttpHostAddress())) {
throw new IllegalStateException("Cannot run two Elasticsearch-based tests in parallel");
}
}
}
public void stopElasticsearch(@Observes StopClassContainers event) {
httpHostAddress.set(null);
ElasticsearchContainer theContainer = (ElasticsearchContainer) elasticsearchContainer;
if (theContainer != null && theContainer.isRunning()) {
theContainer.stop();
}
}
}
| 3,536 | 46.16 | 139 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/hibernate/search/backend/elasticsearch/massindexer/HibernateSearchElasticsearchMassIndexerTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.hibernate.search.backend.elasticsearch.massindexer;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.core.api.annotation.Observer;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.as.test.integration.hibernate.search.backend.elasticsearch.util.ElasticsearchServerSetupObserver;
import org.jboss.as.test.shared.util.AssumeTestGroupUtil;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.Asset;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.jboss.shrinkwrap.descriptor.api.Descriptors;
import org.jboss.shrinkwrap.descriptor.api.persistence20.PersistenceDescriptor;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import jakarta.inject.Inject;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
/**
* @author Hardy Ferentschik
*/
@RunWith(Arquillian.class)
@Observer(ElasticsearchServerSetupObserver.class)
public class HibernateSearchElasticsearchMassIndexerTestCase {
private static final String NAME = HibernateSearchElasticsearchMassIndexerTestCase.class.getSimpleName();
private static final String WAR_ARCHIVE_NAME = NAME + ".war";
@BeforeClass
public static void testRequiresDocker() {
AssumeTestGroupUtil.assumeDockerAvailable();
}
@BeforeClass
public static void securityManagerNotSupportedInHibernateSearch() {
AssumeTestGroupUtil.assumeSecurityManagerDisabled();
}
@Deployment
public static WebArchive createArchive() {
if (!AssumeTestGroupUtil.isDockerAvailable() || !AssumeTestGroupUtil.isSecurityManagerDisabled()) {
return AssumeTestGroupUtil.emptyWar(WAR_ARCHIVE_NAME);
}
return ShrinkWrap
.create(WebArchive.class, WAR_ARCHIVE_NAME)
.addClasses(HibernateSearchElasticsearchMassIndexerTestCase.class,
Singer.class, SingersSingleton.class, AssumeTestGroupUtil.class)
.addAsResource(persistenceXml(), "META-INF/persistence.xml")
.addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml");
}
private static Asset persistenceXml() {
String persistenceXml = Descriptors.create(PersistenceDescriptor.class)
.version("2.0")
.createPersistenceUnit()
.name("cmt-test")
.jtaDataSource("java:jboss/datasources/ExampleDS")
.clazz(Singer.class.getName())
.getOrCreateProperties()
.createProperty().name("hibernate.hbm2ddl.auto").value("create-drop").up()
.createProperty().name("hibernate.search.schema_management.strategy").value("drop-and-create-and-drop").up()
.createProperty().name("hibernate.search.automatic_indexing.enabled").value("false").up()
.createProperty().name("hibernate.search.backend.type").value("elasticsearch").up()
.createProperty().name("hibernate.search.backend.hosts").value(ElasticsearchServerSetupObserver.getHttpHostAddress()).up()
.up().up()
.exportAsString();
return new StringAsset(persistenceXml);
}
@Inject
private SingersSingleton singersEjb;
@Test
public void testMassIndexerWorks() throws Exception {
assertNotNull(singersEjb);
singersEjb.insertContact("John", "Lennon");
singersEjb.insertContact("Paul", "McCartney");
singersEjb.insertContact("George", "Harrison");
singersEjb.insertContact("Ringo", "Starr");
assertEquals("Don't you know the Beatles?", 4, singersEjb.listAllContacts().size());
assertEquals("Beatles should not yet be indexed", 0, singersEjb.searchAllContacts().size());
assertTrue("Indexing the Beatles failed.", singersEjb.rebuildIndex());
assertEquals("Now the Beatles should be indexed", 4, singersEjb.searchAllContacts().size());
}
}
| 5,197 | 43.42735 | 138 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/hibernate/search/backend/elasticsearch/massindexer/SingersSingleton.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.hibernate.search.backend.elasticsearch.massindexer;
import org.hibernate.CacheMode;
import org.hibernate.search.mapper.orm.Search;
import jakarta.ejb.Singleton;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.PersistenceContext;
import jakarta.persistence.PersistenceUnit;
import jakarta.persistence.Query;
import java.util.List;
/**
* A singleton session bean.
*
* @author Hardy Ferentschik
*/
@Singleton
public class SingersSingleton {
@PersistenceUnit(name = "cmt-test")
private EntityManagerFactory entityManagerFactory;
@PersistenceContext(unitName = "cmt-test")
private EntityManager entityManager;
public void insertContact(String firstName, String lastName) {
Singer singer = new Singer();
singer.setFirstName(firstName);
singer.setLastName(lastName);
entityManager.persist(singer);
}
public boolean rebuildIndex() {
try {
Search.mapping(entityManagerFactory).scope(Object.class).massIndexer()
.batchSizeToLoadObjects(30)
.threadsToLoadObjects(4)
.cacheMode(CacheMode.NORMAL)
.startAndWait();
} catch (Exception e) {
return false;
}
return true;
}
public List<?> listAllContacts() {
Query query = entityManager.createQuery("select s from Singer s");
return query.getResultList();
}
public List<?> searchAllContacts() {
return Search.session(entityManager).search(Singer.class)
.where(f -> f.matchAll())
.fetchAllHits();
}
}
| 2,748 | 33.3625 | 89 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/hibernate/search/backend/elasticsearch/massindexer/Singer.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.hibernate.search.backend.elasticsearch.massindexer;
import org.hibernate.search.mapper.pojo.mapping.definition.annotation.FullTextField;
import org.hibernate.search.mapper.pojo.mapping.definition.annotation.Indexed;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import java.io.Serializable;
@Entity
@Indexed
public class Singer implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@FullTextField
private String firstName;
@FullTextField
private String lastName;
public long getId() {
return this.id;
}
public void setId(long id) {
this.id = id;
}
public String getFirstName() {
return this.firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return this.lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
@Override
public String toString() {
return "[#" + id + "] " + lastName + ", " + firstName;
}
}
| 2,325 | 28.075 | 89 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/hibernate/search/backend/elasticsearch/projectionconstructor/SearchBean.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2023, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.hibernate.search.backend.elasticsearch.projectionconstructor;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import jakarta.persistence.criteria.CriteriaDelete;
import jakarta.transaction.Transactional;
import org.hibernate.search.mapper.orm.Search;
import java.util.List;
@ApplicationScoped
@Transactional
public class SearchBean {
@PersistenceContext
EntityManager em;
public void storeNewBook(BookDTO bookDTO) {
Book book = new Book();
book.setId(bookDTO.id);
book.setTitle(bookDTO.title);
for (AuthorDTO authorDTO : bookDTO.authors) {
Author author = new Author();
author.setFirstName(authorDTO.firstName);
author.setLastName(authorDTO.lastName);
author.getBooks().add(book);
book.getAuthors().add(author);
em.persist(author);
}
em.persist(book);
}
public void deleteAll() {
CriteriaDelete<Book> deleteBooks = em.getCriteriaBuilder()
.createCriteriaDelete(Book.class);
deleteBooks.from(Book.class);
em.createQuery(deleteBooks).executeUpdate();
CriteriaDelete<Author> deleteAuthors = em.getCriteriaBuilder()
.createCriteriaDelete(Author.class);
deleteAuthors.from(Author.class);
em.createQuery(deleteAuthors).executeUpdate();
Search.session(em).workspace(Book.class).purge();
}
public List<BookDTO> findByKeyword(String keyword) {
return Search.session(em).search(Book.class)
.select(BookDTO.class)
.where(f -> f.match().field("title").matching(keyword))
.fetchAllHits();
}
}
| 2,841 | 35.909091 | 99 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/hibernate/search/backend/elasticsearch/projectionconstructor/BookDTO.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2023, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.hibernate.search.backend.elasticsearch.projectionconstructor;
import org.hibernate.search.mapper.pojo.mapping.definition.annotation.FieldProjection;
import org.hibernate.search.mapper.pojo.mapping.definition.annotation.IdProjection;
import org.hibernate.search.mapper.pojo.mapping.definition.annotation.ObjectProjection;
import org.hibernate.search.mapper.pojo.mapping.definition.annotation.ProjectionConstructor;
import java.util.List;
public class BookDTO {
public final long id;
public final String title;
public final List<AuthorDTO> authors;
@ProjectionConstructor
public BookDTO(@IdProjection long id,
// This @FieldProjection and @ObjectProjection.path wouldn't be necessary
// with a record or a class compiled with -parameters
@FieldProjection(path = "title") String title,
@ObjectProjection(path = "authors", includeDepth = 1) List<AuthorDTO> authors) {
this.id = id;
this.title = title;
this.authors = authors;
}
}
| 2,115 | 44.021277 | 99 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/hibernate/search/backend/elasticsearch/projectionconstructor/Author.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2023, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.hibernate.search.backend.elasticsearch.projectionconstructor;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import jakarta.persistence.ManyToMany;
import org.hibernate.search.mapper.pojo.mapping.definition.annotation.FullTextField;
import java.util.ArrayList;
import java.util.List;
@Entity
public class Author {
@Id
@GeneratedValue
private Long id;
@FullTextField
private String firstName;
@FullTextField
private String lastName;
@ManyToMany(mappedBy = "authors")
private List<Book> books = new ArrayList<>();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public List<Book> getBooks() {
return books;
}
public void setBooks(List<Book> books) {
this.books = books;
}
}
| 2,252 | 26.814815 | 99 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/hibernate/search/backend/elasticsearch/projectionconstructor/HibernateSearchElasticsearchProjectionConstructorTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2023, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.hibernate.search.backend.elasticsearch.projectionconstructor;
import jakarta.inject.Inject;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.core.api.annotation.Observer;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.as.test.integration.hibernate.search.backend.elasticsearch.util.ElasticsearchServerSetupObserver;
import org.jboss.as.test.shared.util.AssumeTestGroupUtil;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.Asset;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.jboss.shrinkwrap.descriptor.api.Descriptors;
import org.jboss.shrinkwrap.descriptor.api.persistence20.PersistenceDescriptor;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.assertEquals;
/**
* Verify deployed applications can use Hibernate Search's @ProjectionConstructor with Lucene.
*/
@RunWith(Arquillian.class)
@Observer(ElasticsearchServerSetupObserver.class)
public class HibernateSearchElasticsearchProjectionConstructorTestCase {
private static final String NAME = HibernateSearchElasticsearchProjectionConstructorTestCase.class.getSimpleName();
private static final String WAR_ARCHIVE_NAME = NAME + ".war";
@BeforeClass
public static void testRequiresDocker() {
AssumeTestGroupUtil.assumeDockerAvailable();
}
@BeforeClass
public static void securityManagerNotSupportedInHibernateSearch() {
AssumeTestGroupUtil.assumeSecurityManagerDisabled();
}
@Deployment
public static WebArchive createArchive() {
// TODO maybe just use managed=false and deploy in the @BeforeClass / undeploy in an @AfterClass
if (!AssumeTestGroupUtil.isDockerAvailable() || AssumeTestGroupUtil.isSecurityManagerEnabled()) {
return AssumeTestGroupUtil.emptyWar(WAR_ARCHIVE_NAME);
}
return ShrinkWrap
.create(WebArchive.class, WAR_ARCHIVE_NAME)
.addClasses(HibernateSearchElasticsearchProjectionConstructorTestCase.class,
SearchBean.class, Book.class, Author.class, BookDTO.class, AuthorDTO.class,
AssumeTestGroupUtil.class)
.addAsResource(persistenceXml(), "META-INF/persistence.xml")
.addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml");
}
private static Asset persistenceXml() {
String persistenceXml = Descriptors.create(PersistenceDescriptor.class)
.version("2.0")
.createPersistenceUnit()
.name("jpa-search-test-pu")
.jtaDataSource("java:jboss/datasources/ExampleDS")
.clazz(Book.class.getName())
.clazz(Author.class.getName())
.getOrCreateProperties()
.createProperty().name("hibernate.hbm2ddl.auto").value("create-drop").up()
.createProperty().name("hibernate.search.schema_management.strategy").value("drop-and-create-and-drop").up()
.createProperty().name("hibernate.search.automatic_indexing.synchronization.strategy").value("sync").up()
.createProperty().name("hibernate.search.backend.type").value("elasticsearch").up()
.createProperty().name("hibernate.search.backend.hosts").value(ElasticsearchServerSetupObserver.getHttpHostAddress()).up()
.up().up()
.exportAsString();
return new StringAsset(persistenceXml);
}
@Inject
private SearchBean searchBean;
@Before
@After
public void cleanupDatabase() {
searchBean.deleteAll();
}
@Test
public void testProjection() {
BookDTO book1 = new BookDTO(1, "Hello world",
Arrays.asList(new AuthorDTO("John", "Smith")));
searchBean.storeNewBook(book1);
BookDTO book2 = new BookDTO(2, "Hello planet Mars",
Arrays.asList(new AuthorDTO("Jane", "Green"),
new AuthorDTO("John", "Doe")));
searchBean.storeNewBook(book2);
List<BookDTO> hits = searchBean.findByKeyword("world");
assertEquals(1, hits.size());
assertSearchHit(book1, hits.get(0));
hits = searchBean.findByKeyword("mars");
assertEquals(1, hits.size());
assertSearchHit(book2, hits.get(0));
}
private static void assertSearchHit(BookDTO expected, BookDTO hit) {
assertEquals(expected.id, hit.id);
assertEquals(expected.title, hit.title);
assertEquals(expected.authors.size(), hit.authors.size());
for (int i = 0; i < expected.authors.size(); i++) {
AuthorDTO expectedAuthor = expected.authors.get(i);
AuthorDTO hitAuthor = hit.authors.get(i);
assertEquals(expectedAuthor.firstName, hitAuthor.firstName);
assertEquals(expectedAuthor.lastName, hitAuthor.lastName);
// We use includeDepth = 1 on BookDTO#authors, so book.authors.books should be empty
assertEquals(0, hitAuthor.books.size());
}
}
}
| 6,369 | 42.333333 | 138 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/hibernate/search/backend/elasticsearch/projectionconstructor/Book.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2023, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.hibernate.search.backend.elasticsearch.projectionconstructor;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.ManyToMany;
import jakarta.persistence.OrderColumn;
import org.hibernate.search.mapper.pojo.mapping.definition.annotation.FullTextField;
import org.hibernate.search.mapper.pojo.mapping.definition.annotation.Indexed;
import org.hibernate.search.mapper.pojo.mapping.definition.annotation.IndexedEmbedded;
import java.util.ArrayList;
import java.util.List;
@Entity
@Indexed
public class Book {
@Id
private Long id;
@FullTextField
private String title;
@IndexedEmbedded(includeDepth = 1)
@ManyToMany
@OrderColumn
private List<Author> authors = new ArrayList<>();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public List<Author> getAuthors() {
return authors;
}
public void setAuthors(List<Author> authors) {
this.authors = authors;
}
}
| 2,225 | 29.081081 | 99 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/hibernate/search/backend/elasticsearch/projectionconstructor/AuthorDTO.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2023, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.hibernate.search.backend.elasticsearch.projectionconstructor;
import org.hibernate.search.mapper.pojo.mapping.definition.annotation.FieldProjection;
import org.hibernate.search.mapper.pojo.mapping.definition.annotation.ObjectProjection;
import org.hibernate.search.mapper.pojo.mapping.definition.annotation.ProjectionConstructor;
import java.util.Collections;
import java.util.List;
public class AuthorDTO {
public final String firstName;
public final String lastName;
public final List<BookDTO> books;
public AuthorDTO(String firstName, String lastName) {
this(firstName, lastName, Collections.emptyList());
}
@ProjectionConstructor
public AuthorDTO(// These @FieldProjection annotations and @ObjectProjection.path wouldn't be necessary
// with a record or a class compiled with -parameters
@FieldProjection(path = "firstName") String firstName,
@FieldProjection(path = "lastName") String lastName,
@ObjectProjection(path = "books", includeDepth = 1) List<BookDTO> books) {
this.firstName = firstName;
this.lastName = lastName;
this.books = books;
}
}
| 2,267 | 43.470588 | 107 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/hibernate/search/cdi/HibernateSearchCDIInjectionTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.hibernate.search.cdi;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.as.test.integration.hibernate.search.cdi.beans.CDIBeansPackage;
import org.jboss.as.test.integration.hibernate.search.cdi.beans.i18n.InternationalizedValue;
import org.jboss.as.test.integration.hibernate.search.cdi.beans.model.EntityWithCDIAwareBridges;
import org.jboss.as.test.integration.hibernate.search.cdi.beans.model.EntityWithCDIAwareBridgesDao;
import org.jboss.as.test.shared.util.AssumeTestGroupUtil;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.Asset;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.jboss.shrinkwrap.descriptor.api.Descriptors;
import org.jboss.shrinkwrap.descriptor.api.persistence20.PersistenceDescriptor;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import jakarta.inject.Inject;
import static org.hamcrest.CoreMatchers.hasItems;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals;
@RunWith(Arquillian.class)
public class HibernateSearchCDIInjectionTestCase {
@BeforeClass
public static void securityManagerNotSupportedInHibernateSearch() {
AssumeTestGroupUtil.assumeSecurityManagerDisabled();
}
@Deployment
public static Archive<?> createTestArchive() throws Exception {
return ShrinkWrap.create(WebArchive.class, HibernateSearchCDIInjectionTestCase.class.getSimpleName() + ".war")
.addClass(HibernateSearchCDIInjectionTestCase.class)
.addPackages(true /* recursive */, CDIBeansPackage.class.getPackage())
.addAsResource(persistenceXml(), "META-INF/persistence.xml")
.addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml");
}
private static Asset persistenceXml() {
String persistenceXml = Descriptors.create(PersistenceDescriptor.class)
.version("2.0")
.createPersistenceUnit()
.name("primary")
.jtaDataSource("java:jboss/datasources/ExampleDS")
.getOrCreateProperties()
.createProperty().name("hibernate.hbm2ddl.auto").value("create-drop").up()
.createProperty().name("hibernate.search.schema_management.strategy").value("drop-and-create-and-drop").up()
.createProperty().name("hibernate.search.backend.type").value("lucene").up()
.createProperty().name("hibernate.search.backend.lucene_version").value("LUCENE_CURRENT").up()
.createProperty().name("hibernate.search.backend.directory.type").value("local-heap").up()
.up().up()
.exportAsString();
return new StringAsset(persistenceXml);
}
@Inject
private EntityWithCDIAwareBridgesDao dao;
@Before
@After
public void cleanupDatabase() {
dao.deleteAll();
}
@Test
public void injectedFieldBridge() {
assertEquals(0, dao.searchValueBridge("bonjour").size());
assertEquals(0, dao.searchValueBridge("hello").size());
assertEquals(0, dao.searchValueBridge("hallo").size());
assertEquals(0, dao.searchValueBridge("au revoir").size());
EntityWithCDIAwareBridges entity = new EntityWithCDIAwareBridges();
entity.setInternationalizedValue(InternationalizedValue.HELLO);
dao.create(entity);
assertThat(dao.searchValueBridge("bonjour"), hasItems(entity.getId()));
assertThat(dao.searchValueBridge("hello"), hasItems(entity.getId()));
assertThat(dao.searchValueBridge("hallo"), hasItems(entity.getId()));
assertEquals(0, dao.searchValueBridge("au revoir").size());
EntityWithCDIAwareBridges entity2 = new EntityWithCDIAwareBridges();
entity2.setInternationalizedValue(InternationalizedValue.GOODBYE);
dao.create(entity2);
assertThat(dao.searchValueBridge("bonjour"), hasItems(entity.getId()));
assertThat(dao.searchValueBridge("hello"), hasItems(entity.getId()));
assertThat(dao.searchValueBridge("hallo"), hasItems(entity.getId()));
assertThat(dao.searchValueBridge("au revoir"), hasItems(entity2.getId()));
dao.delete(entity);
assertEquals(0, dao.searchValueBridge("bonjour").size());
assertEquals(0, dao.searchValueBridge("hello").size());
assertEquals(0, dao.searchValueBridge("hallo").size());
assertThat(dao.searchValueBridge("au revoir"), hasItems(entity2.getId()));
}
@Test
public void injectedClassBridge() {
assertEquals(0, dao.searchTypeBridge("bonjour").size());
assertEquals(0, dao.searchTypeBridge("hello").size());
assertEquals(0, dao.searchTypeBridge("hallo").size());
assertEquals(0, dao.searchTypeBridge("au revoir").size());
EntityWithCDIAwareBridges entity = new EntityWithCDIAwareBridges();
entity.setInternationalizedValue(InternationalizedValue.HELLO);
dao.create(entity);
assertThat(dao.searchTypeBridge("bonjour"), hasItems(entity.getId()));
assertThat(dao.searchTypeBridge("hello"), hasItems(entity.getId()));
assertThat(dao.searchTypeBridge("hallo"), hasItems(entity.getId()));
assertEquals(0, dao.searchTypeBridge("au revoir").size());
EntityWithCDIAwareBridges entity2 = new EntityWithCDIAwareBridges();
entity2.setInternationalizedValue(InternationalizedValue.GOODBYE);
dao.create(entity2);
assertThat(dao.searchTypeBridge("bonjour"), hasItems(entity.getId()));
assertThat(dao.searchTypeBridge("hello"), hasItems(entity.getId()));
assertThat(dao.searchTypeBridge("hallo"), hasItems(entity.getId()));
assertThat(dao.searchTypeBridge("au revoir"), hasItems(entity2.getId()));
dao.delete(entity);
assertEquals(0, dao.searchTypeBridge("bonjour").size());
assertEquals(0, dao.searchTypeBridge("hello").size());
assertEquals(0, dao.searchTypeBridge("hallo").size());
assertThat(dao.searchTypeBridge("au revoir"), hasItems(entity2.getId()));
}
}
| 7,432 | 47.266234 | 124 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/hibernate/search/cdi/beans/CDIBeansPackage.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.hibernate.search.cdi.beans;
public final class CDIBeansPackage {
private CDIBeansPackage() {
// Private constructor
}
}
| 1,198 | 40.344828 | 70 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/hibernate/search/cdi/beans/bridge/InternationalizedValueBinder.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.hibernate.search.cdi.beans.bridge;
import org.hibernate.search.mapper.pojo.bridge.mapping.programmatic.ValueBinder;
public interface InternationalizedValueBinder extends ValueBinder {
}
| 1,249 | 43.642857 | 80 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/hibernate/search/cdi/beans/bridge/InternationalizedValueBridgeImpl.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.hibernate.search.cdi.beans.bridge;
import org.hibernate.search.mapper.pojo.bridge.ValueBridge;
import org.hibernate.search.mapper.pojo.bridge.binding.ValueBindingContext;
import org.hibernate.search.mapper.pojo.bridge.runtime.ValueBridgeToIndexedValueContext;
import org.jboss.as.test.integration.hibernate.search.cdi.beans.i18n.InternationalizedValue;
import org.jboss.as.test.integration.hibernate.search.cdi.beans.i18n.Language;
import org.jboss.as.test.integration.hibernate.search.cdi.beans.i18n.LocalizationService;
import jakarta.enterprise.context.Dependent;
import jakarta.inject.Inject;
@Dependent
public class InternationalizedValueBridgeImpl implements InternationalizedValueBinder {
@Inject
private LocalizationService localizationService;
@Override
public void bind(ValueBindingContext<?> context) {
Language targetLanguage = Language.valueOf((String) context.param("language"));
context.bridge(InternationalizedValue.class, new Bridge(localizationService, targetLanguage));
}
private static class Bridge implements ValueBridge<InternationalizedValue, String> {
private final LocalizationService localizationService;
private final Language targetLanguage;
private Bridge(LocalizationService localizationService, Language targetLanguage) {
this.localizationService = localizationService;
this.targetLanguage = targetLanguage;
}
@Override
public String toIndexedValue(InternationalizedValue value, ValueBridgeToIndexedValueContext context) {
return localizationService.localize(value, targetLanguage);
}
}
}
| 2,725 | 43.688525 | 110 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/hibernate/search/cdi/beans/bridge/InternationalizedValueTypeBinder.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.hibernate.search.cdi.beans.bridge;
import org.hibernate.search.mapper.pojo.bridge.mapping.programmatic.TypeBinder;
public interface InternationalizedValueTypeBinder extends TypeBinder {
}
| 1,251 | 43.714286 | 79 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/hibernate/search/cdi/beans/bridge/InternationalizedValueTypeBinderImpl.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.hibernate.search.cdi.beans.bridge;
import org.hibernate.search.engine.backend.document.DocumentElement;
import org.hibernate.search.engine.backend.document.IndexFieldReference;
import org.hibernate.search.mapper.pojo.bridge.TypeBridge;
import org.hibernate.search.mapper.pojo.bridge.binding.TypeBindingContext;
import org.hibernate.search.mapper.pojo.bridge.runtime.TypeBridgeWriteContext;
import org.jboss.as.test.integration.hibernate.search.cdi.beans.i18n.InternationalizedValue;
import org.jboss.as.test.integration.hibernate.search.cdi.beans.i18n.Language;
import org.jboss.as.test.integration.hibernate.search.cdi.beans.i18n.LocalizationService;
import org.jboss.as.test.integration.hibernate.search.cdi.beans.model.EntityWithCDIAwareBridges;
import jakarta.enterprise.context.Dependent;
import jakarta.inject.Inject;
@Dependent
public class InternationalizedValueTypeBinderImpl implements InternationalizedValueTypeBinder {
@Inject
private LocalizationService localizationService;
@Override
public void bind(TypeBindingContext context) {
context.dependencies().useRootOnly();
String fieldName = (String) context.param("fieldName");
IndexFieldReference<String> fieldRef = context.indexSchemaElement()
.field(fieldName, f -> f.asString())
.multiValued()
.toReference();
context.bridge( EntityWithCDIAwareBridges.class, new Bridge( localizationService, fieldRef ) );
}
private static class Bridge implements TypeBridge<EntityWithCDIAwareBridges> {
private final LocalizationService localizationService;
private final IndexFieldReference<String> fieldRef;
private Bridge(LocalizationService localizationService, IndexFieldReference<String> fieldRef) {
this.localizationService = localizationService;
this.fieldRef = fieldRef;
}
@Override
public void write(DocumentElement target, EntityWithCDIAwareBridges source, TypeBridgeWriteContext context) {
InternationalizedValue internationalizedValue = source.getInternationalizedValue();
for (Language language : Language.values()) {
String localizedValue = localizationService.localize(internationalizedValue, language);
target.addValue(fieldRef, localizedValue);
}
}
}
}
| 3,447 | 44.973333 | 117 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/hibernate/search/cdi/beans/model/EntityWithCDIAwareBridgesDao.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.hibernate.search.cdi.beans.model;
import jakarta.enterprise.context.ApplicationScoped;
import org.hibernate.search.engine.search.common.ValueConvert;
import org.hibernate.search.mapper.orm.Search;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import jakarta.persistence.criteria.CriteriaDelete;
import jakarta.transaction.Transactional;
import java.util.List;
@ApplicationScoped
public class EntityWithCDIAwareBridgesDao {
@PersistenceContext
private EntityManager entityManager;
@Transactional
public void create(EntityWithCDIAwareBridges entity) {
entityManager.persist(entity);
}
@Transactional
public void update(EntityWithCDIAwareBridges entity) {
entityManager.merge(entity);
}
@Transactional
public void delete(EntityWithCDIAwareBridges entity) {
entity = entityManager.merge(entity);
entityManager.remove(entity);
}
@Transactional
public void deleteAll() {
CriteriaDelete<EntityWithCDIAwareBridges> delete = entityManager.getCriteriaBuilder()
.createCriteriaDelete(EntityWithCDIAwareBridges.class);
delete.from(EntityWithCDIAwareBridges.class);
entityManager.createQuery(delete).executeUpdate();
Search.session(entityManager).workspace(EntityWithCDIAwareBridges.class).purge();
}
@Transactional
public List<Long> searchValueBridge(String terms) {
return Search.session(entityManager).search(EntityWithCDIAwareBridges.class)
.select(f -> f.id(Long.class))
.where(f -> f.match().fields("value_fr", "value_en", "value_de")
.matching(terms, ValueConvert.NO))
.fetchAllHits();
}
@Transactional
public List<Long> searchTypeBridge(String terms) {
return Search.session(entityManager).search(EntityWithCDIAwareBridges.class)
.select(f -> f.id(Long.class))
.where(f -> f.match().field(EntityWithCDIAwareBridges.TYPE_BRIDGE_FIELD_NAME)
.matching(terms, ValueConvert.NO))
.fetchAllHits();
}
}
| 3,222 | 38.790123 | 93 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/hibernate/search/cdi/beans/model/EntityWithCDIAwareBridges.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.hibernate.search.cdi.beans.model;
import org.hibernate.search.mapper.pojo.bridge.mapping.annotation.TypeBinderRef;
import org.hibernate.search.mapper.pojo.bridge.mapping.annotation.ValueBinderRef;
import org.hibernate.search.mapper.pojo.common.annotation.Param;
import org.hibernate.search.mapper.pojo.mapping.definition.annotation.FullTextField;
import org.hibernate.search.mapper.pojo.mapping.definition.annotation.Indexed;
import org.hibernate.search.mapper.pojo.mapping.definition.annotation.TypeBinding;
import org.jboss.as.test.integration.hibernate.search.cdi.beans.bridge.InternationalizedValueBinder;
import org.jboss.as.test.integration.hibernate.search.cdi.beans.bridge.InternationalizedValueTypeBinder;
import org.jboss.as.test.integration.hibernate.search.cdi.beans.i18n.InternationalizedValue;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
@Entity
@Indexed
@TypeBinding(binder = @TypeBinderRef(type = InternationalizedValueTypeBinder.class,
params = @Param(name = "fieldName", value = EntityWithCDIAwareBridges.TYPE_BRIDGE_FIELD_NAME)))
public class EntityWithCDIAwareBridges {
public static final String TYPE_BRIDGE_FIELD_NAME = "typeBridge_internationalizedValue";
@Id
@GeneratedValue
private Long id;
@FullTextField(name = "value_fr", valueBinder = @ValueBinderRef(type = InternationalizedValueBinder.class,
params = @Param(name = "language", value = "FRENCH")))
@FullTextField(name = "value_de", valueBinder = @ValueBinderRef(type = InternationalizedValueBinder.class,
params = @Param(name = "language", value = "GERMAN")))
@FullTextField(name = "value_en", valueBinder = @ValueBinderRef(type = InternationalizedValueBinder.class,
params = @Param(name = "language", value = "ENGLISH")))
private InternationalizedValue internationalizedValue;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public InternationalizedValue getInternationalizedValue() {
return internationalizedValue;
}
public void setInternationalizedValue(InternationalizedValue internationalizedValue) {
this.internationalizedValue = internationalizedValue;
}
}
| 3,353 | 43.72 | 110 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/hibernate/search/cdi/beans/i18n/Language.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.hibernate.search.cdi.beans.i18n;
public enum Language {
ENGLISH,
GERMAN,
FRENCH
}
| 1,155 | 40.285714 | 70 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/hibernate/search/cdi/beans/i18n/LocalizationService.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.hibernate.search.cdi.beans.i18n;
import jakarta.enterprise.context.ApplicationScoped;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
@ApplicationScoped
public class LocalizationService {
private final Map<Pair<InternationalizedValue, Language>, String> localizationMap = new HashMap<>();
public LocalizationService() {
register(InternationalizedValue.HELLO, Language.ENGLISH, "hello");
register(InternationalizedValue.GOODBYE, Language.ENGLISH, "goodbye");
register(InternationalizedValue.HELLO, Language.GERMAN, "hallo");
register(InternationalizedValue.GOODBYE, Language.GERMAN, "auf wiedersehen");
register(InternationalizedValue.HELLO, Language.FRENCH, "bonjour");
register(InternationalizedValue.GOODBYE, Language.FRENCH, "au revoir");
}
private void register(InternationalizedValue value, Language language, String translation) {
localizationMap.put(new Pair<>(value, language), translation);
}
public String localize(InternationalizedValue value, Language language) {
return localizationMap.get(new Pair<>(value, language));
}
private static class Pair<L, R> {
private final L left;
private final R right;
public Pair(L left, R right) {
super();
this.left = left;
this.right = right;
}
@Override
public boolean equals(Object obj) {
if (obj != null && obj.getClass() == getClass()) {
Pair<?, ?> other = (Pair<?, ?>) obj;
return Objects.equals(left, other.left)
&& Objects.equals(right, other.right);
}
return false;
}
@Override
public int hashCode() {
return Objects.hash(left, right);
}
}
}
| 2,917 | 36.410256 | 104 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/hibernate/search/cdi/beans/i18n/InternationalizedValue.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.hibernate.search.cdi.beans.i18n;
public enum InternationalizedValue {
HELLO,
GOODBYE
}
| 1,156 | 41.851852 | 70 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/hibernate/search/v5migrationhelper/simple/SearchBean.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2018, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.hibernate.search.v5migrationhelper.simple;
import org.apache.lucene.search.Query;
import org.hibernate.search.jpa.FullTextEntityManager;
import org.hibernate.search.jpa.FullTextQuery;
import org.hibernate.search.jpa.Search;
import org.hibernate.search.query.dsl.QueryBuilder;
import jakarta.ejb.Stateful;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import jakarta.persistence.criteria.CriteriaDelete;
import java.util.List;
@Stateful
// We know the migration helper is deprecated; we want to test it anyway.
@SuppressWarnings("deprecation")
public class SearchBean {
@PersistenceContext
EntityManager em;
public void storeNewBook(String title) {
Book book = new Book();
book.title = title;
em.persist(book);
}
public void deleteAll() {
CriteriaDelete<Book> delete = em.getCriteriaBuilder()
.createCriteriaDelete(Book.class);
delete.from(Book.class);
em.createQuery(delete).executeUpdate();
Search.getFullTextEntityManager(em).purgeAll(Book.class);
}
@SuppressWarnings("unchecked")
public List<Book> findByKeyword(String keyword) {
FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(em);
QueryBuilder qb = fullTextEntityManager.getSearchFactory().buildQueryBuilder().forEntity(Book.class).get();
Query query = qb.keyword().onField("title").matching(keyword).createQuery();
FullTextQuery fullTextQuery = fullTextEntityManager.createFullTextQuery(query, Book.class);
return fullTextQuery.getResultList();
}
@SuppressWarnings("unchecked")
public List<Book> findAutocomplete(String term) {
FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(em);
QueryBuilder qb = fullTextEntityManager.getSearchFactory().buildQueryBuilder().forEntity(Book.class)
.overridesForField("title_autocomplete", AnalysisConfigurer.AUTOCOMPLETE_QUERY)
.get();
Query query = qb.simpleQueryString().onField("title_autocomplete")
.withAndAsDefaultOperator().matching(term).createQuery();
FullTextQuery fullTextQuery = fullTextEntityManager.createFullTextQuery(query, Book.class);
return fullTextQuery.getResultList();
}
}
| 3,407 | 41.074074 | 115 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/hibernate/search/v5migrationhelper/simple/HibernateSearchV5MigrationHelperTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2014, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.hibernate.search.v5migrationhelper.simple;
import jakarta.inject.Inject;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.as.test.integration.hibernate.search.backend.lucene.simple.HibernateSearchLuceneSimpleTestCase;
import org.jboss.as.test.shared.util.AssumeTestGroupUtil;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.Asset;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.jboss.shrinkwrap.descriptor.api.Descriptors;
import org.jboss.shrinkwrap.descriptor.api.persistence20.PersistenceDescriptor;
import org.jboss.shrinkwrap.descriptor.api.spec.se.manifest.ManifestDescriptor;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.io.File;
import static org.junit.Assert.assertEquals;
/**
* Verify deployed applications can use the default Hibernate Search module via Jakarta Persistence APIs
* and through the V5 migration helper provided as an application library.
* <p>
* This test is similar to {@link HibernateSearchLuceneSimpleTestCase},
* but uses old APIs thanks to the V5 migration helper JARs that are packaged with the application.
* Those are not provided as WildFly modules because they shouldn't be used in production.
*/
@RunWith(Arquillian.class)
public class HibernateSearchV5MigrationHelperTestCase {
private static final String NAME = HibernateSearchV5MigrationHelperTestCase.class.getSimpleName();
private static final String WAR_ARCHIVE_NAME = NAME + ".war";
@BeforeClass
public static void securityManagerNotSupportedInHibernateSearch() {
AssumeTestGroupUtil.assumeSecurityManagerDisabled();
}
@Deployment
public static WebArchive createArchive() {
// TODO maybe just use managed=false and deploy in the @BeforeClass / undeploy in an @AfterClass
if (AssumeTestGroupUtil.isSecurityManagerEnabled()) {
return AssumeTestGroupUtil.emptyWar(WAR_ARCHIVE_NAME);
}
return ShrinkWrap
.create(WebArchive.class, WAR_ARCHIVE_NAME)
.addClasses(HibernateSearchV5MigrationHelperTestCase.class,
SearchBean.class, Book.class, AnalysisConfigurer.class)
.addAsResource(warManifest(), "META-INF/MANIFEST.MF")
.addAsResource(persistenceXml(), "META-INF/persistence.xml")
.addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml")
// These JARs are copied to target/ using the maven-dependency-plugin; see pom.xml.
.addAsLibraries(new File("target/testlib/hibernate-search-v5migrationhelper-engine.jar"),
new File("target/testlib/hibernate-search-v5migrationhelper-orm.jar"));
}
private static Asset warManifest() {
String manifest = Descriptors.create(ManifestDescriptor.class)
// We're not using Hibernate Search 6 @Indexed annotations,
// so we need to depend on org.hibernate.search.orm and to import services.
// The V5 migration helper leaks Lucene APIs, so we need a dependency to org.apache.lucene.
.attribute("Dependencies", "org.hibernate.search.orm services,org.apache.lucene")
.exportAsString();
return new StringAsset(manifest);
}
private static Asset persistenceXml() {
String persistenceXml = Descriptors.create(PersistenceDescriptor.class)
.version("2.0")
.createPersistenceUnit()
.name("jpa-search-test-pu")
.jtaDataSource("java:jboss/datasources/ExampleDS")
.clazz(Book.class.getName())
// Configuration properties need to be those of Hibernate Search 6;
// the migration helper doesn't change that.
.getOrCreateProperties()
.createProperty().name("hibernate.hbm2ddl.auto").value("create-drop").up()
.createProperty().name("hibernate.search.schema_management.strategy").value("drop-and-create-and-drop").up()
.createProperty().name("hibernate.search.backend.type").value("lucene").up()
.createProperty().name("hibernate.search.backend.lucene_version").value("LUCENE_CURRENT").up()
.createProperty().name("hibernate.search.backend.directory.type").value("local-heap").up()
.createProperty().name("hibernate.search.backend.analysis.configurer").value(AnalysisConfigurer.class.getName()).up()
.up().up()
.exportAsString();
return new StringAsset(persistenceXml);
}
@Inject
private SearchBean searchBean;
@Before
@After
public void cleanupDatabase() {
searchBean.deleteAll();
}
@Test
public void testFullTextQuery() {
searchBean.storeNewBook("Hello");
searchBean.storeNewBook("Hello world");
searchBean.storeNewBook("Hello planet Mars");
assertEquals(3, searchBean.findByKeyword("hello").size());
assertEquals(1, searchBean.findByKeyword("mars").size());
// Search should be case-insensitive thanks to the default analyzer
assertEquals(3, searchBean.findByKeyword("HELLO").size());
}
@Test
public void testAnalysisConfiguration() {
searchBean.storeNewBook("Hello");
searchBean.storeNewBook("Hello world");
searchBean.storeNewBook("Hello planet Mars");
// This search relies on a custom analyzer configured in AnalysisConfigurationProvider;
// if it works, then our custom analysis configuration was taken into account.
assertEquals(3, searchBean.findAutocomplete("he").size());
assertEquals(1, searchBean.findAutocomplete("he wo").size());
assertEquals(1, searchBean.findAutocomplete("he pl").size());
}
}
| 7,123 | 46.812081 | 133 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/hibernate/search/v5migrationhelper/simple/Book.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2018, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.hibernate.search.v5migrationhelper.simple;
import org.hibernate.search.annotations.Analyzer;
import org.hibernate.search.annotations.Field;
import org.hibernate.search.annotations.Indexed;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
@Entity
@Indexed
// We know the migration helper is deprecated; we want to test it anyway.
@SuppressWarnings("deprecation")
public class Book {
@Id
@GeneratedValue
Long id;
@Field
@Field(name = "title_autocomplete",
analyzer = @Analyzer(definition = AnalysisConfigurer.AUTOCOMPLETE))
String title;
}
| 1,701 | 34.458333 | 80 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/hibernate/search/v5migrationhelper/simple/AnalysisConfigurer.java
|
package org.jboss.as.test.integration.hibernate.search.v5migrationhelper.simple;
import org.hibernate.search.backend.lucene.analysis.LuceneAnalysisConfigurationContext;
import org.hibernate.search.backend.lucene.analysis.LuceneAnalysisConfigurer;
public class AnalysisConfigurer
implements LuceneAnalysisConfigurer {
public static final String AUTOCOMPLETE = "autocomplete";
public static final String AUTOCOMPLETE_QUERY = "autocomplete-query";
@Override
public void configure(LuceneAnalysisConfigurationContext context) {
context.analyzer(AUTOCOMPLETE).custom()
.tokenizer("whitespace")
.tokenFilter("lowercase")
.tokenFilter("asciiFolding")
.tokenFilter("edgeNGram")
.param("minGramSize", "1")
.param("maxGramSize", "10");
context.analyzer(AUTOCOMPLETE_QUERY).custom()
.tokenizer("whitespace")
.tokenFilter("lowercase")
.tokenFilter("asciiFolding");
}
}
| 1,063 | 39.923077 | 87 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/hibernate/search/v5migrationhelper/massindexer/HibernateSearchV5MigrationHelperMassIndexerTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.hibernate.search.v5migrationhelper.massindexer;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.as.test.integration.hibernate.search.backend.lucene.massindexer.HibernateSearchLuceneEarMassIndexerTestCase;
import org.jboss.as.test.shared.util.AssumeTestGroupUtil;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.Asset;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.jboss.shrinkwrap.descriptor.api.Descriptors;
import org.jboss.shrinkwrap.descriptor.api.persistence20.PersistenceDescriptor;
import org.jboss.shrinkwrap.descriptor.api.spec.se.manifest.ManifestDescriptor;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import jakarta.inject.Inject;
import java.io.File;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
/**
* Verify deployed applications can use the mass indexer of the default Hibernate Search module
* through the V5 migration helper provided as an application library.
* <p>
* This test is similar to {@link HibernateSearchLuceneEarMassIndexerTestCase},
* but uses old APIs thanks to the V5 migration helper JARs that are packaged with the application.
* Those are not provided as WildFly modules because they shouldn't be used in production.
*/
@RunWith(Arquillian.class)
public class HibernateSearchV5MigrationHelperMassIndexerTestCase {
private static final String NAME = HibernateSearchV5MigrationHelperMassIndexerTestCase.class.getSimpleName();
private static final String WAR_ARCHIVE_NAME = NAME + ".war";
@BeforeClass
public static void securityManagerNotSupportedInHibernateSearch() {
AssumeTestGroupUtil.assumeSecurityManagerDisabled();
}
@Deployment
public static WebArchive createArchive() {
// TODO maybe just use managed=false and deploy in the @BeforeClass / undeploy in an @AfterClass
if (AssumeTestGroupUtil.isSecurityManagerEnabled()) {
return AssumeTestGroupUtil.emptyWar(WAR_ARCHIVE_NAME);
}
return ShrinkWrap
.create(WebArchive.class, WAR_ARCHIVE_NAME)
.addClasses(HibernateSearchV5MigrationHelperMassIndexerTestCase.class,
Singer.class, SingersSingleton.class)
.addAsResource(warManifest(), "META-INF/MANIFEST.MF")
.addAsResource(persistenceXml(), "META-INF/persistence.xml")
.addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml")
// These JARs are copied to target/ using the maven-dependency-plugin; see pom.xml.
.addAsLibraries(new File("target/testlib/hibernate-search-v5migrationhelper-engine.jar"),
new File("target/testlib/hibernate-search-v5migrationhelper-orm.jar"));
}
private static Asset warManifest() {
String manifest = Descriptors.create(ManifestDescriptor.class)
// We're not using Hibernate Search 6 @Indexed annotations,
// so we need to depend on org.hibernate.search.orm and to import services.
// The V5 migration helper leaks Lucene APIs, so we need a dependency to org.apache.lucene.
.attribute("Dependencies", "org.hibernate.search.orm services,org.apache.lucene")
.exportAsString();
return new StringAsset(manifest);
}
private static Asset persistenceXml() {
String persistenceXml = Descriptors.create(PersistenceDescriptor.class)
.version("2.0")
.createPersistenceUnit()
.name("cmt-test")
.jtaDataSource("java:jboss/datasources/ExampleDS")
.clazz(Singer.class.getName())
.getOrCreateProperties()
// Configuration properties need to be those of Hibernate Search 6;
// the migration helper doesn't change that.
.createProperty().name("hibernate.hbm2ddl.auto").value("create").up()
.createProperty().name("hibernate.search.schema_management.strategy").value("drop-and-create-and-drop").up()
.createProperty().name("hibernate.search.backend.type").value("lucene").up()
.createProperty().name("hibernate.search.backend.lucene_version").value("LUCENE_CURRENT").up()
.createProperty().name("hibernate.search.backend.directory.type").value("local-heap").up()
.createProperty().name("hibernate.search.automatic_indexing.enabled").value("false").up()
.up().up()
.exportAsString();
return new StringAsset(persistenceXml);
}
@Inject
private SingersSingleton singersEjb;
@Test
public void testMassIndexerWorks() throws Exception {
assertNotNull(singersEjb);
singersEjb.insertContact("John", "Lennon");
singersEjb.insertContact("Paul", "McCartney");
singersEjb.insertContact("George", "Harrison");
singersEjb.insertContact("Ringo", "Starr");
assertEquals("Don't you know the Beatles?", 4, singersEjb.listAllContacts().size());
assertEquals("Beatles should not yet be indexed", 0, singersEjb.searchAllContacts().size());
assertTrue("Indexing the Beatles failed.", singersEjb.rebuildIndex());
assertEquals("Now the Beatles should be indexed", 4, singersEjb.searchAllContacts().size());
}
}
| 6,688 | 48.183824 | 125 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/hibernate/search/v5migrationhelper/massindexer/SingersSingleton.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.hibernate.search.v5migrationhelper.massindexer;
import org.apache.lucene.search.MatchAllDocsQuery;
import org.hibernate.CacheMode;
import org.hibernate.search.jpa.FullTextEntityManager;
import org.hibernate.search.jpa.FullTextQuery;
import org.hibernate.search.jpa.Search;
import jakarta.ejb.Singleton;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import jakarta.persistence.Query;
import java.util.List;
/**
* A singleton session bean.
*
* @author Hardy Ferentschik
*/
@Singleton
// We know the migration helper is deprecated; we want to test it anyway.
@SuppressWarnings("deprecation")
public class SingersSingleton {
@PersistenceContext(unitName = "cmt-test")
private EntityManager entityManager;
public void insertContact(String firstName, String lastName) {
Singer singer = new Singer();
singer.setFirstName(firstName);
singer.setLastName(lastName);
entityManager.persist(singer);
}
public boolean rebuildIndex() throws InterruptedException {
FullTextEntityManager fullTextEntityManager = Search
.getFullTextEntityManager(entityManager);
try {
fullTextEntityManager
.createIndexer()
.batchSizeToLoadObjects(30)
.threadsToLoadObjects(4)
.cacheMode(CacheMode.NORMAL)
.startAndWait();
} catch (Exception e) {
return false;
}
return true;
}
public List<?> listAllContacts() {
Query query = entityManager.createQuery("select s from Singer s");
return query.getResultList();
}
public List<?> searchAllContacts() {
FullTextEntityManager fullTextEntityManager = Search
.getFullTextEntityManager(entityManager);
FullTextQuery query = fullTextEntityManager.createFullTextQuery(
new MatchAllDocsQuery(),
Singer.class
);
return query.getResultList();
}
}
| 3,116 | 33.633333 | 85 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/hibernate/search/v5migrationhelper/massindexer/Singer.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.hibernate.search.v5migrationhelper.massindexer;
import org.hibernate.search.annotations.DocumentId;
import org.hibernate.search.annotations.Field;
import org.hibernate.search.annotations.Indexed;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import java.io.Serializable;
@Entity
@Indexed
// We know the migration helper is deprecated; we want to test it anyway.
@SuppressWarnings("deprecation")
public class Singer implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@DocumentId
private long id;
@Field
private String firstName;
@Field
private String lastName;
public long getId() {
return this.id;
}
public void setId(long id) {
this.id = id;
}
public String getFirstName() {
return this.firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return this.lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
@Override
public String toString() {
return "[#" + id + "] " + lastName + ", " + firstName;
}
}
| 2,412 | 27.72619 | 85 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/hibernate/generator/Employee.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2015, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.hibernate.generator;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
/**
* Employee entity class
*
* @author Scott Marlow
*/
@Entity
public class Employee {
@Id
private int id;
private String name;
private String address;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
| 1,719 | 24.671642 | 70 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/hibernate/generator/PooledGeneratorTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2015, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.hibernate.generator;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.EnterpriseArchive;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* PooledGeneratorTestCase
*
* @author Scott Marlow
*/
@RunWith(Arquillian.class)
public class PooledGeneratorTestCase {
private static final String ARCHIVE_NAME = "PooledGenerator.ear";
@Deployment
public static Archive<?> deploy() {
EnterpriseArchive ear = ShrinkWrap.create(EnterpriseArchive.class, ARCHIVE_NAME);
JavaArchive ejbModule = ShrinkWrap.create(JavaArchive.class, "my-ejb-module.jar");
ejbModule.addClasses(PooledGeneratorTestCase.class, TestSlsb.class);
ejbModule.addAsManifestResource(PooledGeneratorTestCase.class.getPackage(), "persistence.xml", "persistence.xml");
ejbModule.addAsManifestResource(PooledGeneratorTestCase.class.getPackage(), "orm.xml", "orm.xml");
ear.addAsModule(ejbModule);
JavaArchive jar = ShrinkWrap.create(JavaArchive.class, "jarfile.jar");
jar.addClass(Employee.class);
ear.addAsLibrary(jar);
return ear;
}
@Test
public void testEntityInJarFileArchive() throws NamingException {
TestSlsb slsb = (TestSlsb) new InitialContext().lookup("java:module/" + TestSlsb.class.getSimpleName());
for (int looper = 0; looper < 500; looper++) {
Employee employee = new Employee();
employee.setName("Sarah" + looper);
employee.setAddress(looper + " Main Street");
slsb.save(employee);
}
}
}
| 2,922 | 37.973333 | 122 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/hibernate/generator/TestSlsb.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2015, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.hibernate.generator;
import jakarta.ejb.Stateless;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
@Stateless
public class TestSlsb {
@PersistenceContext
private EntityManager em;
public void save(Employee employee) {
em.persist(employee);
}
}
| 1,374 | 35.184211 | 70 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/xerces/JSFManagedBean.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.xerces;
import java.io.Serializable;
import jakarta.faces.annotation.FacesConfig;
import jakarta.faces.view.ViewScoped;
import jakarta.inject.Named;
/**
* User: jpai
*/
@Named
@ViewScoped
@FacesConfig
public class JSFManagedBean implements Serializable {
private static final long serialVersionUID = 1L;
}
| 1,376 | 34.307692 | 70 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/xerces/XercesUsageServlet.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.xerces;
import java.io.IOException;
import java.io.InputStream;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.xerces.parsers.DOMParser;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
/**
* User: jpai
*/
@WebServlet (urlPatterns = XercesUsageServlet.URL_PATTERN)
public class XercesUsageServlet extends HttpServlet {
public static final String URL_PATTERN = "/xercesServlet";
public static final String XML_RESOURCE_NAME_PARAMETER = "xml";
public static final String SUCCESS_MESSAGE = "Success";
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
final String xmlResource = req.getParameter(XML_RESOURCE_NAME_PARAMETER);
final InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(xmlResource);
if (inputStream == null) {
throw new ServletException(xmlResource + " could not be found");
}
try {
this.parse(inputStream);
resp.getOutputStream().print(SUCCESS_MESSAGE);
} catch (SAXException saxe) {
throw new ServletException(saxe);
}
}
private void parse(final InputStream inputStream) throws IOException, SAXException {
DOMParser domParser = new DOMParser();
domParser.parse(new InputSource(inputStream));
}
}
| 2,644 | 36.253521 | 113 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/xerces/unit/XercesUsageTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2021, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.xerces.unit;
import java.io.IOException;
import java.net.URL;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.OperateOnDeployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.test.integration.xerces.JSFManagedBean;
import org.jboss.as.test.integration.xerces.XercesUsageServlet;
import org.jboss.as.test.shared.integration.ejb.security.PermissionUtils;
import org.jboss.logging.Logger;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.EnterpriseArchive;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.jboss.shrinkwrap.resolver.api.maven.Maven;
import org.jboss.shrinkwrap.resolver.api.maven.PomEquippedResolveStage;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Tests that packaging the xerces jar within a deployment does not cause deployment or runtime failures in the application
*
* @author Jaikiran Pai
*/
@RunWith(Arquillian.class)
@RunAsClient
public class XercesUsageTestCase {
private static final String WEB_APP_CONTEXT = "xerces-webapp";
private static final String JSF_WEB_APP_CONTEXT = "xerces-jsf-webapp";
private static final Logger logger = Logger.getLogger(XercesUsageTestCase.class);
@ArquillianResource
@OperateOnDeployment("app-without-jsf")
private URL withoutJsf;
@ArquillianResource
@OperateOnDeployment("app-with-jsf")
private URL withJsf;
/**
* Create a .ear, containing a web application (without any Jakarta Server Faces constructs) and also the xerces jar in the .ear/lib
*
* @return
*/
@Deployment(name = "app-without-jsf", testable = false)
public static EnterpriseArchive createDeployment() throws IOException {
final WebArchive war = ShrinkWrap.create(WebArchive.class, WEB_APP_CONTEXT + ".war");
war.addClasses(XercesUsageServlet.class);
// add a dummy xml to parse
war.addAsResource(XercesUsageServlet.class.getPackage(), "dummy.xml", "dummy.xml");
final EnterpriseArchive ear = ShrinkWrap.create(EnterpriseArchive.class, "xerces-usage.ear");
// add the .war
ear.addAsModule(war);
// add the xerces jar in the .ear/lib
final PomEquippedResolveStage resolver = Maven.resolver().loadPomFromFile("pom.xml");
ear.addAsLibrary(resolver.resolve("xerces:xercesImpl:2.12.1").withoutTransitivity().asSingleFile());
ear.addAsManifestResource(PermissionUtils.createPermissionsXmlAsset(
new RuntimePermission("accessClassInPackage.org.apache.xerces.util"),
new RuntimePermission("accessClassInPackage.org.apache.xerces.xni.grammars"),
new RuntimePermission("accessClassInPackage.org.apache.xerces.impl.validation"),
new RuntimePermission("accessClassInPackage.org.apache.xerces.impl.dtd"),
new RuntimePermission("accessClassInPackage.org.apache.xerces.impl.*")
), "permissions.xml");
return ear;
}
/**
* Create a .ear, containing a Jakarta Server Faces web application and also the xerces jar in the .ear/lib
*
* @return
*/
@Deployment(name = "app-with-jsf", testable = false)
public static EnterpriseArchive createJSFDeployment() throws IOException {
final WebArchive war = ShrinkWrap.create(WebArchive.class, JSF_WEB_APP_CONTEXT + ".war");
war.addClasses(XercesUsageServlet.class, JSFManagedBean.class);
// add a dummy xml to parse
war.addAsResource(XercesUsageServlet.class.getPackage(), "dummy.xml", "dummy.xml");
final EnterpriseArchive ear = ShrinkWrap.create(EnterpriseArchive.class, "xerces-usage-jsf.ear");
// add the .war
ear.addAsModule(war);
// add the xerces jar in the .ear/lib
final PomEquippedResolveStage resolver = Maven.resolver().loadPomFromFile("pom.xml");
ear.addAsLibrary(resolver.resolve("xerces:xercesImpl:2.12.1").withoutTransitivity().asSingleFile());
ear.addAsManifestResource(PermissionUtils.createPermissionsXmlAsset(
new RuntimePermission("accessClassInPackage.org.apache.xerces.util"),
new RuntimePermission("accessClassInPackage.org.apache.xerces.impl.*"),
new RuntimePermission("accessClassInPackage.org.apache.xerces.xni.grammars")
), "permissions.xml");
return ear;
}
/**
* Test that a non-Jakarta Server Faces web application, with xerces jar packaged within the deployment, functions correctly
* while using the packaged xerces API.
*
* @throws Exception
*/
@OperateOnDeployment("app-without-jsf")
@Test
public void testXercesUsageInServletInNonJSFApp() throws Exception {
final HttpClient httpClient = new DefaultHttpClient();
final String xml = "dummy.xml";
final String requestURL = withoutJsf.toExternalForm() + XercesUsageServlet.URL_PATTERN
+ "?" + XercesUsageServlet.XML_RESOURCE_NAME_PARAMETER + "=" + xml;
final HttpGet request = new HttpGet(requestURL);
final HttpResponse response = httpClient.execute(request);
int statusCode = response.getStatusLine().getStatusCode();
Assert.assertEquals("Unexpected status code", 200, statusCode);
final HttpEntity entity = response.getEntity();
Assert.assertNotNull("Response message from servlet was null", entity);
final String responseMessage = EntityUtils.toString(entity);
Assert.assertEquals("Unexpected echo message from servlet", XercesUsageServlet.SUCCESS_MESSAGE, responseMessage);
}
/**
* Test that a Jakarta Server Faces web application, with xerces jar packaged within the deployment, functions correctly while using
* the packaged xerces API.
*
* @throws Exception
*/
@OperateOnDeployment("app-with-jsf")
@Test
public void testXercesUsageInServletInJSFApp() throws Exception {
final HttpClient httpClient = new DefaultHttpClient();
final String xml = "dummy.xml";
final String requestURL = withJsf.toExternalForm()+ XercesUsageServlet.URL_PATTERN
+ "?" + XercesUsageServlet.XML_RESOURCE_NAME_PARAMETER + "=" + xml;
final HttpGet request = new HttpGet(requestURL);
final HttpResponse response = httpClient.execute(request);
int statusCode = response.getStatusLine().getStatusCode();
Assert.assertEquals("Unexpected status code", 200, statusCode);
final HttpEntity entity = response.getEntity();
Assert.assertNotNull("Response message from servlet was null", entity);
final String responseMessage = EntityUtils.toString(entity);
Assert.assertEquals("Unexpected echo message from servlet", XercesUsageServlet.SUCCESS_MESSAGE, responseMessage);
}
}
| 8,306 | 44.146739 | 136 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/xerces/ws/XercesUsageWSEndpoint.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.xerces.ws;
import jakarta.jws.WebService;
import jakarta.jws.soap.SOAPBinding;
/**
* User: jpai
*/
@WebService
@SOAPBinding
public interface XercesUsageWSEndpoint {
String parseUsingXerces(String xmlResource);
}
| 1,283 | 33.702703 | 70 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/xerces/ws/XercesUsageWebService.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.xerces.ws;
import org.apache.xerces.parsers.DOMParser;
import org.xml.sax.InputSource;
import jakarta.jws.WebService;
import jakarta.jws.soap.SOAPBinding;
import java.io.InputStream;
/**
* User: jpai
*/
@WebService (serviceName = "XercesUsageWebService", targetNamespace = "org.jboss.as.test.integration.xerces.ws")
@SOAPBinding
public class XercesUsageWebService implements XercesUsageWSEndpoint {
public static final String SUCCESS_MESSAGE = "Success";
@Override
public String parseUsingXerces(String xmlResource) {
final InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(xmlResource);
if (inputStream == null) {
throw new RuntimeException(xmlResource + " could not be found");
}
DOMParser domParser = new DOMParser();
try {
domParser.parse(new InputSource(inputStream));
return SUCCESS_MESSAGE;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
| 2,078 | 35.473684 | 112 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/xerces/ws/unit/XercesUsageInWebServiceTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.xerces.ws.unit;
import java.io.IOException;
import java.net.URL;
import javax.xml.namespace.QName;
import jakarta.xml.ws.Service;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.OperateOnDeployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.test.integration.xerces.XercesUsageServlet;
import org.jboss.as.test.integration.xerces.ws.XercesUsageWSEndpoint;
import org.jboss.as.test.integration.xerces.ws.XercesUsageWebService;
import org.jboss.logging.Logger;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.jboss.shrinkwrap.resolver.api.maven.Maven;
import org.jboss.shrinkwrap.resolver.api.maven.PomEquippedResolveStage;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Tests that packaging a xerces jar within a web application containing a webservice implementation, doesn't break the
* functioning of the webservice.
*
* @author Jaikiran Pai
*/
@RunWith(Arquillian.class)
@RunAsClient
public class XercesUsageInWebServiceTestCase {
private static final String WEBSERVICE_WEB_APP_CONTEXT = "xerces-webservice-webapp";
private static final Logger logger = Logger.getLogger(XercesUsageInWebServiceTestCase.class);
@ArquillianResource
private URL url;
/**
* Creates a .war file, containing a webservice implementation and also packages the xerces jar within the
* web application's .war/WEB-INF/lib
*
* @return
*/
@Deployment(name = "webservice-app-with-xerces", testable = false)
public static WebArchive createWebServiceDeployment() throws IOException {
final WebArchive war = ShrinkWrap.create(WebArchive.class, WEBSERVICE_WEB_APP_CONTEXT + ".war");
war.addClasses(XercesUsageWebService.class, XercesUsageWSEndpoint.class);
// add a web.xml containing the webservice mapping as a servlet
war.addAsWebInfResource(XercesUsageServlet.class.getPackage(), "xerces-webservice-web.xml", "web.xml");
// add a dummy xml to parse
war.addAsResource(XercesUsageServlet.class.getPackage(), "dummy.xml", "dummy.xml");
// add the xerces jar in the .war/WEB-INF/lib
final PomEquippedResolveStage resolver = Maven.resolver().loadPomFromFile("pom.xml");
war.addAsLibraries(resolver.resolve("xerces:xercesImpl:2.12.1").withoutTransitivity().asSingleFile());
return war;
}
/**
* Test that the webservice invocation works fine
*
* @throws Exception
*/
@OperateOnDeployment("webservice-app-with-xerces")
@Test
public void testXercesUsageInWebService() throws Exception {
final QName serviceName = new QName("org.jboss.as.test.integration.xerces.ws", "XercesUsageWebService");
final URL wsdlURL = new URL(url.toExternalForm() + "XercesUsageWebService?wsdl");
final Service service = Service.create(wsdlURL, serviceName);
final XercesUsageWSEndpoint port = service.getPort(XercesUsageWSEndpoint.class);
final String xml = "dummy.xml";
final String result = port.parseUsingXerces(xml);
Assert.assertEquals("Unexpected return message from webservice", XercesUsageWebService.SUCCESS_MESSAGE, result);
}
}
| 4,488 | 40.564815 | 120 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jsp/JspWithUnusedDoubleTestCase.java
|
package org.jboss.as.test.integration.jsp;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.OperateOnDeployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.test.integration.common.HttpRequest;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.UrlAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(Arquillian.class)
@RunAsClient
public class JspWithUnusedDoubleTestCase {
private static final String DEPLOYMENT = "jsp-with-unused-double.war";
@Deployment(name = DEPLOYMENT)
public static WebArchive deployment() {
WebArchive war = ShrinkWrap.create(WebArchive.class, DEPLOYMENT);
war.add(new UrlAsset(JspWithUnusedDoubleTestCase.class.getResource("jsp-with-unused-double.jsp")), "jsp-with-unused-double.jsp");
return war;
}
@Test
@OperateOnDeployment(DEPLOYMENT)
public void testUnusedDoubleInJsp(@ArquillianResource URL url) throws TimeoutException, ExecutionException, IOException {
String response = HttpRequest.get(url + "jsp-with-unused-double.jsp", 10, TimeUnit.SECONDS);
Assert.assertEquals("Jsp doesn't contain valid output", "1.0", response.trim());
}
}
| 1,645 | 38.190476 | 137 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jsf/deployment/NonExistingJsfImplDeploymentTestCase.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2020, Red Hat, Inc. and/or its affiliates, and individual
* contributors by the @authors tag. See the copyright.txt in the
* distribution for a full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.as.test.integration.jsf.deployment;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OUTCOME;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUCCESS;
import org.jboss.arquillian.container.spi.client.container.DeploymentException;
import org.jboss.arquillian.container.test.api.Deployer;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.arquillian.api.ContainerResource;
import org.jboss.as.arquillian.api.ServerSetup;
import org.jboss.as.arquillian.container.ManagementClient;
import org.jboss.as.controller.client.helpers.Operations;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.client.ModelControllerClient;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.jsf.logging.JSFLogger;
import org.jboss.as.test.shared.ServerReload;
import org.jboss.as.test.shared.SnapshotRestoreSetupTask;
import org.jboss.dmr.ModelNode;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(Arquillian.class)
@RunAsClient
@ServerSetup(NonExistingJsfImplDeploymentTestCase.SetupTask.class)
public class NonExistingJsfImplDeploymentTestCase {
@ContainerResource
private ManagementClient managementClient;
@ArquillianResource
private Deployer deployer;
@Deployment(testable = false, managed = false, name = "test_jar")
public static Archive<?> deploy() {
JavaArchive archive = ShrinkWrap.create(JavaArchive.class);
archive.addClass(NonExistingJsfImplDeploymentTestCase.class);
return archive;
}
private static final PathAddress JSF_ADDRESS = PathAddress.pathAddress(ModelDescriptionConstants.SUBSYSTEM, "jsf");
@Test
public void testDeploymentDoesntFailBecauseOfNPE() throws Exception {
try {
deployer.deploy("test_jar");
Assert.fail("Expected DeploymentException not thrown");
} catch (Exception e) {
Assert.assertTrue(e instanceof DeploymentException);
Assert.assertTrue(e.getMessage().contains(JSFLogger.ROOT_LOGGER.invalidDefaultJSFImpl("idontexist").getMessage()));
}
}
static class SetupTask extends SnapshotRestoreSetupTask {
@Override
protected void doSetup(ManagementClient client, String containerId) throws Exception {
ModelControllerClient mcc = client.getControllerClient();
ModelNode writeJSFAttributeOperation = Operations.createWriteAttributeOperation(JSF_ADDRESS.toModelNode(), "default-jsf-impl-slot", "idontexist");
ModelNode response = mcc.execute(writeJSFAttributeOperation);
Assert.assertEquals(SUCCESS, response.get(OUTCOME).asString());
ServerReload.executeReloadAndWaitForCompletion(client);
}
}
}
| 3,950 | 44.94186 | 158 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jsf/doctype/Bean.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2017, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jsf.doctype;
import java.io.Serializable;
import jakarta.enterprise.context.SessionScoped;
import jakarta.faces.annotation.FacesConfig;
import jakarta.inject.Named;
/**
* A simple bean.
*
* @author <a href="[email protected]">Farah Juma</a>
*/
@Named("bean")
@SessionScoped
@FacesConfig
public class Bean implements Serializable {
private String name;
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
}
| 1,561 | 30.24 | 70 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jsf/doctype/DoctypeDeclTestCase.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2021, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jsf.doctype;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.arquillian.container.ManagementClient;
import org.jboss.as.controller.client.helpers.ClientConstants;
import org.jboss.as.controller.client.helpers.Operations;
import org.jboss.as.test.integration.management.ManagementOperations;
import org.jboss.as.test.shared.ServerReload;
import org.jboss.dmr.ModelNode;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Tests for disallowing and allowing DOCTYPE declarations in Jakarta Server Faces apps.
*
* @author Farah Juma
*/
@RunWith(Arquillian.class)
@RunAsClient
public class DoctypeDeclTestCase {
@ArquillianResource
private URL url;
@ArquillianResource
private ManagementClient managementClient;
private final Pattern viewStatePattern = Pattern.compile("id=\".*jakarta.faces.ViewState.*\" value=\"([^\"]*)\"");
@Deployment(testable = false)
public static Archive<?> deploy() {
WebArchive war = ShrinkWrap.create(WebArchive.class, "jsf-test.war");
war.addPackage(DoctypeDeclTestCase.class.getPackage());
// register.xhtml contains a DOCTYPE declaration
war.addAsWebResource(DoctypeDeclTestCase.class.getPackage(), "register.xhtml", "register.xhtml");
war.addAsWebResource(DoctypeDeclTestCase.class.getPackage(), "confirmation.xhtml", "confirmation.xhtml");
war.addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml");
return war;
}
@Test
public void testDoctypeDeclDisallowed() throws Exception {
writeDisallowDoctypeDeclAttributeAndReload(true);
// ensure an internal server error occurs
register("Bob", 500);
undefineDisallowDoctypeDeclAttributeAndReload();
}
@Test
public void testDoctypeDeclAllowed() throws Exception {
writeDisallowDoctypeDeclAttributeAndReload(false);
String responseString = register("Bob", 200);
assertTrue(responseString.contains("registered"));
undefineDisallowDoctypeDeclAttributeAndReload();
}
private String register(String name, int expectedStatusCode) throws Exception {
DefaultHttpClient client = new DefaultHttpClient();
try {
// Create and execute a GET request
String jsfViewState = null;
String requestUrl = url.toString() + "register.jsf";
HttpGet getRequest = new HttpGet(requestUrl);
HttpResponse response = client.execute(getRequest);
try {
// Get the Jakarta Server Faces view state
String responseString = IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8);
Matcher jsfViewMatcher = viewStatePattern.matcher(responseString);
if (jsfViewMatcher.find()) {
jsfViewState = jsfViewMatcher.group(1);
}
} finally {
HttpClientUtils.closeQuietly(response);
}
// Create and execute a POST request with the given name
HttpPost post = new HttpPost(requestUrl);
List<NameValuePair> list = new ArrayList<NameValuePair>();
list.add(new BasicNameValuePair("jakarta.faces.ViewState", jsfViewState));
list.add(new BasicNameValuePair("register", "register"));
list.add(new BasicNameValuePair("register:inputName", name));
list.add(new BasicNameValuePair("register:registerButton", "Register"));
post.setEntity(new StringEntity(URLEncodedUtils.format(list, StandardCharsets.UTF_8), ContentType.APPLICATION_FORM_URLENCODED));
response = client.execute(post);
try {
assertEquals(expectedStatusCode, response.getStatusLine().getStatusCode());
return IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8);
} finally {
HttpClientUtils.closeQuietly(response);
}
} finally {
HttpClientUtils.closeQuietly(client);
}
}
private void writeDisallowDoctypeDeclAttributeAndReload(boolean value) throws Exception {
final ModelNode address = Operations.createAddress(ClientConstants.SUBSYSTEM, "jsf");
final ModelNode op = Operations.createWriteAttributeOperation(address, "disallow-doctype-decl", value);
ManagementOperations.executeOperation(managementClient.getControllerClient(), op);
ServerReload.executeReloadAndWaitForCompletion(managementClient);
}
private void undefineDisallowDoctypeDeclAttributeAndReload() throws Exception {
final ModelNode address = Operations.createAddress(ClientConstants.SUBSYSTEM, "jsf");
final ModelNode op = Operations.createUndefineAttributeOperation(address, "disallow-doctype-decl");
ManagementOperations.executeOperation(managementClient.getControllerClient(), op);
ServerReload.executeReloadAndWaitForCompletion(managementClient);
}
}
| 7,184 | 43.90625 | 140 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jsf/unsupportedwar/HelloBean.java
|
/*
* Copyright 2020 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.as.test.integration.jsf.unsupportedwar;
import jakarta.enterprise.context.RequestScoped;
import jakarta.inject.Named;
@Named(value = "helloBean")
@RequestScoped
public class HelloBean {
private String name;
public HelloBean() {
this("World");
}
public HelloBean(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| 1,084 | 23.659091 | 75 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jsf/unsupportedwar/FaceletsViewMappingsTestCase.java
|
/*
* Copyright 2021 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.as.test.integration.jsf.unsupportedwar;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.hamcrest.CoreMatchers;
import org.hamcrest.MatcherAssert;
import org.jboss.arquillian.container.test.api.Deployer;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.arquillian.container.ManagementClient;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* <p>Tests the Jakarta Server Faces deployment failure due to UnsupportedOperationException when
* <em>jakarta.faces.FACELETS_VIEW_MAPPINGS</em> is defined with something that
* does not include <em>*.xhtml</em>.</p>
* <p>
* For details check https://issues.redhat.com/browse/WFLY-13792
*
* @author Ranabir Chakraborty <[email protected]>
*/
@RunWith(Arquillian.class)
@RunAsClient
@Ignore("WFLY-16521")
public class FaceletsViewMappingsTestCase {
public static final String FACELETS_VIEW_MAPPINGS_TEST_CASE = "FaceletsViewMappingsTestCase";
private static final String DEPLOYMENT = FaceletsViewMappingsTestCase.class.getSimpleName();
@ArquillianResource
private Deployer deployer;
@ArquillianResource
private ManagementClient managementClient;
@Deployment(name = FACELETS_VIEW_MAPPINGS_TEST_CASE, testable = false, managed = false)
public static WebArchive deployment() {
final Package DEPLOYMENT_PACKAGE = HelloBean.class.getPackage();
WebArchive war = ShrinkWrap.create(WebArchive.class, DEPLOYMENT + ".war");
war.addClasses(HelloBean.class, ConfigurationBean.class);
war.addAsWebInfResource(DEPLOYMENT_PACKAGE, "web.xml", "web.xml");
war.addAsWebResource(DEPLOYMENT_PACKAGE, "hello.jsf", "hello.jsf");
return war;
}
@Before
public void setup() {
deployer.deploy(FACELETS_VIEW_MAPPINGS_TEST_CASE);
}
@After
public void tearDown() {
deployer.undeploy(FACELETS_VIEW_MAPPINGS_TEST_CASE);
}
@SuppressWarnings("deprecation")
@Test
public void testHelloWorld() throws Exception {
try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
HttpGet httpget = new HttpGet(managementClient.getWebUri() + "/" + DEPLOYMENT);
HttpResponse response = httpclient.execute(httpget);
String result = EntityUtils.toString(response.getEntity());
Assert.assertEquals("Jakarta Server Faces deployment failed due to UnsupportedOperationException when jakarta.faces.FACELETS_VIEW_MAPPINGS valued wrong",
HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
MatcherAssert.assertThat("Hello World is in place", result, CoreMatchers.containsString("Hello World!"));
}
}
}
| 3,901 | 37.633663 | 165 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jsf/unsupportedwar/ConfigurationBean.java
|
/*
* Copyright 2020 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.as.test.integration.jsf.unsupportedwar;
import jakarta.faces.annotation.FacesConfig;
/**
*
* @author Ranabir Chakraborty <[email protected]>
*/
@FacesConfig(version = FacesConfig.Version.JSF_2_3)
public class ConfigurationBean {
}
| 852 | 29.464286 | 75 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jsf/injection/FacesConverterInjectionTestCase.java
|
/*
* Copyright (c) 2020. Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.as.test.integration.jsf.injection;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.hamcrest.CoreMatchers;
import org.hamcrest.MatcherAssert;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.OperateOnDeployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.Asset;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.jboss.shrinkwrap.descriptor.api.Descriptors;
import org.jboss.shrinkwrap.descriptor.api.beans11.BeansDescriptor;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Test case for a FacesConverter injected using annotation=true.
*
* @author rmartinc
*/
@RunWith(Arquillian.class)
@RunAsClient
public class FacesConverterInjectionTestCase {
private static final String TEST_NAME = "FacesConverterInjectionTestCase";
@ArquillianResource
@OperateOnDeployment(TEST_NAME)
private URL url;
private static Asset createBeansXml(String beanDiscoveryMode) {
return new StringAsset(Descriptors.create(BeansDescriptor.class)
.version("1.1")
.beanDiscoveryMode(beanDiscoveryMode)
.exportAsString());
}
@Deployment(name = TEST_NAME)
public static Archive<?> deploy() {
final Package resourcePackage = FacesConverterInjectionTestCase.class.getPackage();
WebArchive archive = ShrinkWrap.create(WebArchive.class, TEST_NAME + ".war")
.addClasses(JSF23ConfigurationBean.class, URLConverter.class, URLConverter.class, UrlConverterBean.class)
.addAsWebResource(resourcePackage, "url.xhtml", "url.xhtml")
.addAsWebInfResource(resourcePackage, "web.xml", "web.xml")
.addAsWebInfResource(createBeansXml("all"), "beans.xml");
return archive;
}
private void test(String urlToCheck, String containsText) throws Exception {
try (CloseableHttpClient client = HttpClientBuilder.create().build()) {
HttpUriRequest getRequest = new HttpGet(url.toExternalForm() + "faces/url.xhtml");
try (CloseableHttpResponse getResponse = client.execute(getRequest)) {
MatcherAssert.assertThat("GET success", getResponse.getStatusLine().getStatusCode(), CoreMatchers.equalTo(HttpURLConnection.HTTP_OK));
String text = EntityUtils.toString(getResponse.getEntity());
Document doc = Jsoup.parse(text);
Element form = doc.select("form").first();
MatcherAssert.assertThat("form is included in the response", form, CoreMatchers.notNullValue());
List<NameValuePair> params = new ArrayList<>();
for (Element input : form.select("input")) {
String value = input.attr("value");
if (value != null && !value.isEmpty()) {
params.add(new BasicNameValuePair(input.attr("name"), value));
} else {
params.add(new BasicNameValuePair(input.attr("name"), urlToCheck));
}
}
Assert.assertFalse("Form paramaters are filled", params.isEmpty());
URI uri = new URIBuilder().setScheme(url.getProtocol())
.setHost(url.getHost()).setPort(url.getPort())
.setPath(form.attr("action")).build();
HttpPost postRequest = new HttpPost(uri);
postRequest.setEntity(new UrlEncodedFormEntity(params));
try (CloseableHttpResponse postResponse = client.execute(postRequest)) {
MatcherAssert.assertThat("POST success", postResponse.getStatusLine().getStatusCode(), CoreMatchers.equalTo(HttpURLConnection.HTTP_OK));
text = EntityUtils.toString(postResponse.getEntity());
MatcherAssert.assertThat("Expected text is in POST response", text, CoreMatchers.containsString(containsText));
}
}
}
}
@Test
public void testConverterSuccess() throws Exception {
test("http://wildfly.org/index.html", "Valid URL.");
}
@Test
public void testConverterError() throws Exception {
test("http://wildfly.org:wrong/index.html", "Invalid URL:");
}
}
| 5,953 | 44.106061 | 156 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jsf/injection/URLConverter.java
|
/*
* Copyright (c) 2020. Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.as.test.integration.jsf.injection;
import java.net.URI;
import jakarta.faces.application.FacesMessage;
import jakarta.faces.component.UIComponent;
import jakarta.faces.context.FacesContext;
import jakarta.faces.convert.Converter;
import jakarta.faces.convert.FacesConverter;
/**
* Converter that converts an object into an URL.
*
* @author rmartinc
*/
@FacesConverter(value = "urlConverter", managed = true)
public class URLConverter implements Converter {
public URLConverter() {
}
@Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
try {
URI uri = new URI(value).parseServerAuthority();
return uri.toURL();
} catch (Exception e) {
context.addMessage(component.getClientId(context), new FacesMessage("Invalid URL:", e.getMessage()));
return null;
}
}
@Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
return value.toString();
}
}
| 1,664 | 30.415094 | 113 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jsf/injection/UrlConverterBean.java
|
/*
* Copyright (c) 2020. Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.as.test.integration.jsf.injection;
import java.net.URL;
import jakarta.enterprise.context.RequestScoped;
import jakarta.faces.application.FacesMessage;
import jakarta.faces.component.UIComponent;
import jakarta.faces.context.FacesContext;
import jakarta.faces.convert.FacesConverter;
import jakarta.inject.Inject;
import jakarta.inject.Named;
/**
* Converter bean used in the url.xhtml.
*
* @author rmartinc
*/
@Named(value="urlConverterBean")
@RequestScoped
public class UrlConverterBean {
@Inject
@FacesConverter(value = "urlConverter", managed = true)
private URLConverter urlConverter;
@Inject
private FacesContext context;
private String value;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String submit(UIComponent component) {
URL url = (URL) urlConverter.getAsObject(context, component, value);
if (url != null) {
// do whatever with the URL
context.addMessage(component.getClientId(context), new FacesMessage("Valid URL.", ""));
}
return "";
}
}
| 1,770 | 27.111111 | 99 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jsf/injection/JSF23ConfigurationBean.java
|
/*
* Copyright (c) 2021. Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.as.test.integration.jsf.injection;
import static jakarta.faces.annotation.FacesConfig.Version;
import jakarta.faces.annotation.FacesConfig;
/**
* Configuration bean to specify Jakarta Server Faces 2.3 version.
*
* @author rmartinc
*/
@FacesConfig(
// Activates CDI build-in beans that provide the injection this project
version = Version.JSF_2_3
)
public class JSF23ConfigurationBean {
}
| 1,030 | 29.323529 | 79 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jsf/testurl/ForbiddenUrlTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
/**
* UnallowedUrlTestCase
* For more information visit <a href="https://issues.redhat.com/browse/WFLY-13439">https://issues.redhat.com/browse/WFLY-13439</a>
*
* @author Petr Adamec
*/
package org.jboss.as.test.integration.jsf.testurl;
import java.net.URL;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Test if 404 is returned for url address which isn't allowed
*/
@RunWith(Arquillian.class)
@RunAsClient
public class ForbiddenUrlTestCase {
private static final String ALLOWED_URL = "faces/jakarta.faces.resource/lala.js?con=lala";
private static final String FORBIDDEN_URL = "faces/jakarta.faces.resource/lala.js?con=lala/../lala";
private static final int ALLOWED_STATUS_CODE = 200;
private static final int FORBIDDEN_STATUS_CODE = 404;
@ArquillianResource
private URL url;
@Deployment
public static Archive<?> deploy() {
final WebArchive war = ShrinkWrap.create(WebArchive.class, "jsf-resources.war");
war.addAsWebInfResource(ForbiddenUrlTestCase.class.getPackage(), "web.xml", "web.xml");
//war.addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml");
war.addAsWebResource(ForbiddenUrlTestCase.class.getPackage(), "index.xhtml", "index.xhtml");
war.addAsWebResource(ForbiddenUrlTestCase.class.getPackage(), "lala.jsp", "lala.jsp");
war.addAsWebResource(ForbiddenUrlTestCase.class.getPackage(), "lala.js", "contracts/lala/lala.js");
return war;
}
/**
* Test if 200 is returned for allowed url
* <br /> For more information see https://issues.redhat.com/browse/WFLY-13439.
*
* @throws Exception
*/
@Test
public void testAllowedUrl() throws Exception {
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
try (CloseableHttpClient client = httpClientBuilder.build()) {
HttpUriRequest getVarRequest = new HttpGet(url.toExternalForm() + ALLOWED_URL);
try (CloseableHttpResponse getVarResponse = client.execute(getVarRequest)) {
int statusCode = getVarResponse.getStatusLine().getStatusCode();
Assert.assertEquals("Status code should be " + ALLOWED_STATUS_CODE + ", but is " + statusCode +
". For more information see JBEAP-18842. ", ALLOWED_STATUS_CODE, statusCode);
}
}
}
/**
* Test id 404 is returned fot forbidden url.
* <br /> For more information see https://issues.redhat.com/browse/WFLY-13439
*
* @throws Exception
*/
@Test
public void testForbiddenUrl() throws Exception {
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
try (CloseableHttpClient client = httpClientBuilder.build()) {
HttpUriRequest getVarRequest = new HttpGet(url.toExternalForm() + FORBIDDEN_URL);
try (CloseableHttpResponse getVarResponse = client.execute(getVarRequest)) {
int statusCode = getVarResponse.getStatusLine().getStatusCode();
Assert.assertEquals("Status code should be " + FORBIDDEN_STATUS_CODE + ", but is " + statusCode +
". For more information see JBEAP-18842. ", FORBIDDEN_STATUS_CODE, statusCode);
}
}
}
}
| 4,948 | 41.663793 | 131 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jsf/managedbean/managedproperty/InjectionTargetBean.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2022, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jsf.managedbean.managedproperty;
import jakarta.annotation.PostConstruct;
import jakarta.enterprise.context.RequestScoped;
import jakarta.faces.annotation.ManagedProperty;
import jakarta.inject.Inject;
import jakarta.inject.Named;
/**
* A CDI bean that injects various beans provided by Jakarta Faces
* via its @ManagedProperty facility.
*
* @author Farah Juma
* @author Brian Stansberry
*/
@Named("testTarget")
@RequestScoped
public class InjectionTargetBean {
private boolean postConstructCalled = false;
private boolean greetingBeanInjected = false;
/** Injects using the Faces facility that exposes the request parameter map */
@Inject
@ManagedProperty(value = "#{param.testName}")
private String testName;
/** Injects using the Faces facility that exposes the FacesContext */
@Inject
@ManagedProperty("#{facesContext.externalContext.requestContextPath}")
private String contextPath;
/** Injects a bean included in the deployment */
@Inject
@ManagedProperty(value = "#{greetingBean}")
private GreetingBean greetingBean;
@PostConstruct
public void postConstruct() {
if ((greetingBean != null) && greetingBean.greet("Bob").equals("Hello Bob")) {
greetingBeanInjected = true;
}
postConstructCalled = true;
}
public String getTestName() {
return testName;
}
public String getContextPath() {
return contextPath;
}
public boolean isGreetingBeanInjected() {
return greetingBeanInjected;
}
public boolean isPostConstructCalled() {
return postConstructCalled;
}
}
| 2,699 | 31.142857 | 86 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jsf/managedbean/managedproperty/ManagedPropertyInjectionTestCase.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2022, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jsf.managedbean.managedproperty;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.OperateOnDeployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.test.shared.util.AssumeTestGroupUtil;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Test that Jakarta Server Faces managed properties are injected before @PostConstruct methods
* are called and that beans for JSF implicit objects are injectable.
*
* @author Farah Juma
* @author Brian Stansberry
*/
@RunWith(Arquillian.class)
@RunAsClient
public class ManagedPropertyInjectionTestCase {
@ArquillianResource
private URL url;
/** Creates a war with beans annotated with @ManagedProperty but nothing to activate FacesServlet */
@Deployment(name = "jsfmanagedproperty-cruft.war")
public static Archive<?> cruftDeployment() {
return baseDeployment("jsfmanagedproperty-cruft.war");
}
/** Creates a war equivalent to {@link #cruftDeployment()} but with a
* faces-config.xml included in order to active the FacesServlet */
@Deployment(name = "jsfmanagedproperty.war")
public static Archive<?> accessibleDeployment() {
final WebArchive war = baseDeployment("jsfmanagedproperty.war");
war.addAsWebInfResource(InjectionTargetBean.class.getPackage(), "faces-config.xml", "faces-config.xml");
return war;
}
private static WebArchive baseDeployment(String warName) {
final WebArchive war = ShrinkWrap.create(WebArchive.class, warName);
war.addClasses(InjectionTargetBean.class, GreetingBean.class);
if (!AssumeTestGroupUtil.isWildFlyPreview()) {
// JSF 2.3 impl requires using @FacesConfig on a bean to turn on CDI integration
// TODO remove this once standard WildFly uses Faces 4
war.addClass(JSF23ConfigurationBean.class);
}
war.addAsWebResource(InjectionTargetBean.class.getPackage(), "managedproperties.xhtml", "managedproperties.xhtml");
war.addAsWebResource(InjectionTargetBean.class.getPackage(), "index.html", "index.html");
return war;
}
@Test
@OperateOnDeployment("jsfmanagedproperty-cruft.war")
public void testWithoutFacesServlet() throws IOException {
// TODO remove this once standard WildFly uses Faces 4
AssumeTestGroupUtil.assumeWildFlyPreview();
DefaultHttpClient client = new DefaultHttpClient();
try {
// Confirm the war is accessible
String relativePath = "index.html";
executeRequest(client, relativePath, 200);
// Confirm the FacesServlet is not accessible (sanity check that the deployment works as expected)
relativePath = "managedproperties.jsf?testName=" + getClass().getSimpleName();
executeRequest(client, relativePath, 404);
} finally {
HttpClientUtils.closeQuietly(client);
}
}
@Test
@OperateOnDeployment("jsfmanagedproperty.war")
public void testWithFacesServlet() throws IOException {
DefaultHttpClient client = new DefaultHttpClient();
try {
// Access the URL and validate injections
String relativePath = "managedproperties.jsf?testName=" + getClass().getSimpleName();
String responseString = executeRequest(client, relativePath, 200);
checkKeyValue(responseString, "TestName", getClass().getSimpleName());
checkKeyValue(responseString, "ContextPath", "/jsfmanagedproperty");
checkKeyValue(responseString, "PostConstructCalled", "true");
checkKeyValue(responseString, "GreetingBeanInjected", "true");
} finally {
HttpClientUtils.closeQuietly(client);
}
}
private String executeRequest(HttpClient client, String relativePath, int expectedStatus) throws IOException {
String requestUrl = url.toString() + relativePath;
HttpGet getRequest = new HttpGet(requestUrl);
HttpResponse response = client.execute(getRequest);
try {
String responseString = IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8);
assertEquals(requestUrl + "\n" + responseString, expectedStatus, response.getStatusLine().getStatusCode());
return responseString;
} finally {
HttpClientUtils.closeQuietly(response);
}
}
private static void checkKeyValue(String responseString, String key, String value) {
assertTrue(key + " must be " + value + " in " + responseString, responseString.contains(key+":"+value));
}
}
| 6,430 | 43.659722 | 123 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jsf/managedbean/managedproperty/JSF23ConfigurationBean.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2022, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jsf.managedbean.managedproperty;
import static jakarta.faces.annotation.FacesConfig.Version;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.faces.annotation.FacesConfig;
/**
* TODO remove once standard WildFly moves to Faces 4
*/
@FacesConfig(
// Activates CDI build-in beans that provide the injection this project
version = Version.JSF_2_3
)
@ApplicationScoped
public class JSF23ConfigurationBean {
}
| 1,499 | 37.461538 | 79 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jsf/managedbean/managedproperty/GreetingBean.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2014, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jsf.managedbean.managedproperty;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Named;
/**
* A greeting bean.
*
* @author Farah Juma
*/
@Named("greetingBean")
@ApplicationScoped
public class GreetingBean {
public String greet(String name) {
return "Hello " + name;
}
}
| 1,374 | 33.375 | 73 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jsf/jsf23/DummyBean.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2018, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jsf.jsf23;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.faces.annotation.FacesConfig;
/**
*
* @author <a href="mailto:[email protected]">Farah Juma</a>
*/
@ApplicationScoped
@FacesConfig(version = FacesConfig.Version.JSF_2_3)
public class DummyBean {
}
| 1,343 | 35.324324 | 70 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jsf/jsf23/ConfirmRegistrationBehavior.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2018, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jsf.jsf23;
import jakarta.faces.component.behavior.ClientBehaviorBase;
import jakarta.faces.component.behavior.ClientBehaviorContext;
import jakarta.faces.component.behavior.FacesBehavior;
import jakarta.inject.Inject;
/**
*
* @author <a href="mailto:[email protected]">Farah Juma</a>
*/
@FacesBehavior(value = "confirm", managed = true)
public class ConfirmRegistrationBehavior extends ClientBehaviorBase {
@Inject
ConfirmBean confirmBean;
@Override
public String getScript(ClientBehaviorContext behaviorContext) {
return "return confirm('" + confirmBean.getConfirmMsg() + "');";
}
}
| 1,681 | 36.377778 | 72 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jsf/jsf23/ConfirmBean.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2018, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jsf.jsf23;
import jakarta.enterprise.context.RequestScoped;
import jakarta.inject.Named;
/**
*
* @author <a href="mailto:[email protected]">Farah Juma</a>
*/
@Named
@RequestScoped
public class ConfirmBean {
private String confirmMsg;
public ConfirmBean(){
confirmMsg = "Are you sure you want to register?";
}
public String getConfirmMsg() {
return confirmMsg;
}
public void setConfirmMsg(String confirmMsg) {
this.confirmMsg = confirmMsg;
}
}
| 1,565 | 30.32 | 70 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jsf/jsf23/JSF23SanityTestCase.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2021, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jsf.jsf23;
import static org.junit.Assert.assertTrue;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* A simple test to verify that Jakarta Server Faces 2.3 is used.
*
* @author <a href="mailto:[email protected]">Farah Juma</a>
*/
@RunWith(Arquillian.class)
@RunAsClient
public class JSF23SanityTestCase {
@ArquillianResource
private URL url;
private final Pattern viewStatePattern = Pattern.compile("id=\".*jakarta.faces.ViewState.*\" value=\"([^\"]*)\"");
@Deployment(testable = false)
public static Archive<?> deploy() {
WebArchive war = ShrinkWrap.create(WebArchive.class, "registration-jsf.war");
war.addClass(ConfirmBean.class);
war.addClass(ConfirmRegistrationBehavior.class);
war.addClass(DummyBean.class);
war.addAsWebResource(JSF23SanityTestCase.class.getPackage(), "index.xhtml", "index.xhtml");
war.addAsWebResource(JSF23SanityTestCase.class.getPackage(), "confirmation.xhtml", "confirmation.xhtml");
war.addAsWebInfResource(JSF23SanityTestCase.class.getPackage(), "beans.xml", "beans.xml");
war.addAsWebInfResource(JSF23SanityTestCase.class.getPackage(), "register.taglib.xml", "register.taglib.xml");
war.addAsWebInfResource(JSF23SanityTestCase.class.getPackage(), "faces-config.xml", "faces-config.xml");
war.addAsManifestResource(new StringAsset("Manifest-Version: 1.0\n"), "MANIFEST.MF");
return war;
}
@Test
public void testJSF23InjectCanBeUsed() throws Exception {
String responseString;
DefaultHttpClient client = new DefaultHttpClient();
try {
// Create and execute a GET request
String jsfViewState = null;
String requestUrl = url.toString() + "index.jsf";
HttpGet getRequest = new HttpGet(requestUrl);
HttpResponse response = client.execute(getRequest);
try {
responseString = IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8);
// Get the Jakarta Server Faces view state
Matcher jsfViewMatcher = viewStatePattern.matcher(responseString);
if (jsfViewMatcher.find()) {
jsfViewState = jsfViewMatcher.group(1);
}
} finally {
HttpClientUtils.closeQuietly(response);
}
// Create and execute a POST request
HttpPost post = new HttpPost(requestUrl);
List<NameValuePair> list = new ArrayList<NameValuePair>();
list.add(new BasicNameValuePair("jakarta.faces.ViewState", jsfViewState));
list.add(new BasicNameValuePair("register", "register"));
list.add(new BasicNameValuePair("register:registerButton", "Register"));
post.setEntity(new StringEntity(URLEncodedUtils.format(list, StandardCharsets.UTF_8), ContentType.APPLICATION_FORM_URLENCODED));
response = client.execute(post);
try {
responseString = IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8);
} finally {
HttpClientUtils.closeQuietly(response);
}
} finally {
HttpClientUtils.closeQuietly(client);
}
assertTrue(responseString.contains("Jakarta Server Faces 2.3 Inject worked!"));
}
}
| 5,542 | 42.304688 | 140 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jsf/beanvalidation/cdi/Team.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2013, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jsf.beanvalidation.cdi;
import java.io.Serializable;
import jakarta.enterprise.context.SessionScoped;
import jakarta.inject.Named;
import jakarta.validation.constraints.Size;
/**
* A Team.
*
* @author Farah Juma
*/
@Named("team")
@SessionScoped
public class Team implements Serializable {
@CustomMin
private int numberOfPeople;
@Size(min = 3, message = "Team name must be at least 3 characters.")
private String name;
public Team() {
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public int getNumberOfPeople() {
return this.numberOfPeople;
}
public void setNumberOfPeople(int numberOfPeople) {
this.numberOfPeople = numberOfPeople;
}
}
| 1,850 | 27.921875 | 73 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jsf/beanvalidation/cdi/MinimumValueProvider.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2013, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jsf.beanvalidation.cdi;
/**
* Provides a minimum value for the number of people for a Team instance.
*
* @author Farah Juma
*/
public class MinimumValueProvider {
public int getMin() {
return 3;
}
}
| 1,275 | 35.457143 | 73 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jsf/beanvalidation/cdi/CustomMin.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2013, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jsf.beanvalidation.cdi;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import jakarta.validation.Constraint;
import jakarta.validation.Payload;
/**
* A custom constraint that uses CDI in its validator class.
*
* @author Farah Juma
*/
@Constraint(validatedBy = CustomMinValidator.class)
@Documented
@Target({ METHOD, FIELD, TYPE, PARAMETER })
@Retention(RUNTIME)
public @interface CustomMin {
String message() default "Not enough people for a team.";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
| 1,957 | 35.943396 | 73 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jsf/beanvalidation/cdi/BeanValidationCdiIntegrationTestCase.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2021, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jsf.beanvalidation.cdi;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Tests for the integration of Jakarta Server Faces, CDI, and Jakarta Bean Validation.
* TODO. Faces 4 does not support Faces ManagedBeans so this has been adapted
* to only use CDI beans. The effect is this is no longer really a test of the Faces
* integration with Bean Validation. It does however test CDI + BV. Presumably that's
* well covered elsewhere though.
*
*
* @author Farah Juma
*/
@RunWith(Arquillian.class)
@RunAsClient
public class BeanValidationCdiIntegrationTestCase {
@ArquillianResource
private URL url;
private final Pattern viewStatePattern = Pattern.compile("id=\".*jakarta.faces.ViewState.*\" value=\"([^\"]*)\"");
private final Pattern nameErrorPattern = Pattern.compile("<div id=\"nameError\">([^<]+)</div>");
private final Pattern numberErrorPattern = Pattern.compile("<div id=\"numberError\">([^<]+)</div>");
@Deployment(testable = false)
public static Archive<?> deploy() {
WebArchive war = ShrinkWrap.create(WebArchive.class, "registration-jsf.war");
war.addPackage(BeanValidationCdiIntegrationTestCase.class.getPackage());
war.addAsWebResource(BeanValidationCdiIntegrationTestCase.class.getPackage(), "register.xhtml", "register.xhtml");
war.addAsWebResource(BeanValidationCdiIntegrationTestCase.class.getPackage(), "confirmation.xhtml", "confirmation.xhtml");
war.addAsWebInfResource(new StringAsset("<beans bean-discovery-mode=\"all\"></beans>"), "beans.xml");
war.addAsWebInfResource(BeanValidationCdiIntegrationTestCase.class.getPackage(), "faces-config.xml","faces-config.xml");
return war;
}
@Test
public void testSuccessfulBeanValidation() throws Exception {
String responseString = registerTeam("Team1", 6);
Matcher errorMatcher = nameErrorPattern.matcher(responseString);
assertTrue(responseString, !errorMatcher.find());
errorMatcher = numberErrorPattern.matcher(responseString);
assertTrue(responseString, !errorMatcher.find());
}
@Test
public void testFailingBeanValidation() throws Exception {
String nameError = null;
String numberError = null;
String responseString = registerTeam("", 1);
Matcher errorMatcher = nameErrorPattern.matcher(responseString);
if (errorMatcher.find()) {
nameError = errorMatcher.group(1).trim();
}
errorMatcher = numberErrorPattern.matcher(responseString);
if (errorMatcher.find()) {
numberError = errorMatcher.group(1).trim();
}
assertEquals(responseString,"Team name must be at least 3 characters.", nameError);
assertEquals(responseString, "Not enough people for a team.", numberError);
}
private String registerTeam(String name, int numberOfPeople) throws Exception {
DefaultHttpClient client = new DefaultHttpClient();
try {
// Create and execute a GET request
String jsfViewState = null;
String requestUrl = url.toString() + "register.jsf";
HttpGet getRequest = new HttpGet(requestUrl);
HttpResponse response = client.execute(getRequest);
try {
String responseString = IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8);
assertEquals(responseString, 200, response.getStatusLine().getStatusCode());
// Get the Jakarta Server Faces view state
Matcher jsfViewMatcher = viewStatePattern.matcher(responseString);
if (jsfViewMatcher.find()) {
jsfViewState = jsfViewMatcher.group(1);
}
} finally {
HttpClientUtils.closeQuietly(response);
}
// Create and execute a POST request with the given team name and
// the given number of people
HttpPost post = new HttpPost(requestUrl);
List<NameValuePair> list = new ArrayList<NameValuePair>();
list.add(new BasicNameValuePair("jakarta.faces.ViewState", jsfViewState));
list.add(new BasicNameValuePair("register", "register"));
list.add(new BasicNameValuePair("register:inputName", name));
list.add(new BasicNameValuePair("register:inputNumber", Integer.toString(numberOfPeople)));
list.add(new BasicNameValuePair("register:registerButton", "Register"));
post.setEntity(new StringEntity(URLEncodedUtils.format(list, StandardCharsets.UTF_8), ContentType.APPLICATION_FORM_URLENCODED));
response = client.execute(post);
try {
String responseString = IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8);
assertEquals(responseString, 200, response.getStatusLine().getStatusCode());
return responseString;
} finally {
HttpClientUtils.closeQuietly(response);
}
} finally {
HttpClientUtils.closeQuietly(client);
}
}
}
| 7,394 | 43.548193 | 140 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jsf/beanvalidation/cdi/CustomMinValidator.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2013, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jsf.beanvalidation.cdi;
import jakarta.inject.Inject;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
/**
* A validator that uses constructor injection.
*
* @author Farah Juma
*/
public class CustomMinValidator implements ConstraintValidator<CustomMin, Integer> {
private final MinimumValueProvider minimumValueProvider;
@Inject
public CustomMinValidator(MinimumValueProvider minimumValueProvider) {
this.minimumValueProvider = minimumValueProvider;
}
@Override
public void initialize(CustomMin constraintAnnotation) {
}
@Override
public boolean isValid(Integer value, ConstraintValidatorContext context) {
return value >= minimumValueProvider.getMin();
}
}
| 1,831 | 34.921569 | 84 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jsf/phaselistener/injectiontarget/TestEJB.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2016, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jsf.phaselistener.injectiontarget;
import jakarta.ejb.Stateless;
@Stateless
public class TestEJB {
public static String MESSAGE = "TestEJB Injected";
public String ping(){
return MESSAGE;
}
}
| 1,271 | 34.333333 | 73 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jsf/phaselistener/injectiontarget/InjectionToPhaseListenerTest.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2016, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jsf.phaselistener.injectiontarget;
import java.net.URL;
import jakarta.ws.rs.client.Client;
import jakarta.ws.rs.client.ClientBuilder;
import jakarta.ws.rs.client.WebTarget;
import jakarta.ws.rs.core.Response;
import com.fasterxml.jackson.core.util.JacksonFeature;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* @author Tomas Remes
*/
@RunWith(Arquillian.class)
@RunAsClient
public class InjectionToPhaseListenerTest {
@ArquillianResource
URL url;
@Deployment(testable = false)
public static Archive<?> deploy() {
final WebArchive war = ShrinkWrap.create(WebArchive.class, "jsfphaseListener.war");
war.addPackage(InjectionToPhaseListenerTest.class.getPackage());
war.addAsWebInfResource(InjectionToPhaseListenerTest.class.getPackage(), "web.xml", "web.xml");
war.addAsWebInfResource(InjectionToPhaseListenerTest.class.getPackage(), "faces-config.xml", "faces-config.xml");
war.addAsWebResource(InjectionToPhaseListenerTest.class.getPackage(), "home.xhtml", "home.xhtml");
return war;
}
@Test
public void test() throws Exception {
try (Client client = ClientBuilder.newClient().register(JacksonFeature.class)) {
WebTarget target = client.target(url.toExternalForm() + "home.jsf");
Response response = target.request().get();
String value = response.getHeaderString("X-WildFly");
Assert.assertNotNull(value);
Assert.assertEquals(value, TestEJB.MESSAGE);
}
}
}
| 2,973 | 39.189189 | 121 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jsf/phaselistener/injectiontarget/TestPhaseListener.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2016, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jsf.phaselistener.injectiontarget;
import jakarta.ejb.EJB;
import jakarta.faces.event.PhaseEvent;
import jakarta.faces.event.PhaseId;
import jakarta.faces.event.PhaseListener;
public class TestPhaseListener implements PhaseListener{
@EJB
TestEJB testEJB;
@Override
public void afterPhase(PhaseEvent phaseEvent) {
}
@Override
public void beforePhase(PhaseEvent phaseEvent) {
if (phaseEvent.getPhaseId().equals(PhaseId.RENDER_RESPONSE)) {
phaseEvent.getFacesContext().getExternalContext().addResponseHeader("X-WildFly", testEJB.ping());
}
}
@Override
public PhaseId getPhaseId() {
return PhaseId.ANY_PHASE;
}
}
| 1,750 | 33.333333 | 109 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jsf/phaselistener/injectiontarget/bean/TestPhaseListener.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2016, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jsf.phaselistener.injectiontarget.bean;
import jakarta.faces.event.PhaseEvent;
import jakarta.faces.event.PhaseId;
import jakarta.faces.event.PhaseListener;
import jakarta.inject.Inject;
public class TestPhaseListener implements PhaseListener{
@Inject
SimpleBean simpleBean;
@Override
public void afterPhase(PhaseEvent phaseEvent) {
}
@Override
public void beforePhase(PhaseEvent phaseEvent) {
if (phaseEvent.getPhaseId().equals(PhaseId.RENDER_RESPONSE)) {
phaseEvent.getFacesContext().getExternalContext().addResponseHeader("X-WildFly", simpleBean.ping());
}
}
@Override
public PhaseId getPhaseId() {
return PhaseId.ANY_PHASE;
}
}
| 1,772 | 34.46 | 112 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jsf/phaselistener/injectiontarget/bean/SimpleBean.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2016, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jsf.phaselistener.injectiontarget.bean;
public class SimpleBean {
public static String MESSAGE = "SimpleBean Injected";
public String ping(){
return MESSAGE;
}
}
| 1,240 | 36.606061 | 77 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jsf/phaselistener/injectiontarget/bean/InjectionBeanToPhaseListenerTest.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2016, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jsf.phaselistener.injectiontarget.bean;
import java.net.URL;
import jakarta.ws.rs.client.Client;
import jakarta.ws.rs.client.ClientBuilder;
import jakarta.ws.rs.client.WebTarget;
import jakarta.ws.rs.core.Response;
import com.fasterxml.jackson.core.util.JacksonFeature;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* @author Tomas Remes
*/
@RunWith(Arquillian.class)
@RunAsClient
public class InjectionBeanToPhaseListenerTest {
@ArquillianResource
URL url;
@Deployment(testable = false)
public static Archive<?> deploy() {
final WebArchive war = ShrinkWrap.create(WebArchive.class, "jsfphaseListenerBean.war");
war.addPackage(InjectionBeanToPhaseListenerTest.class.getPackage());
war.addAsWebInfResource(InjectionBeanToPhaseListenerTest.class.getPackage(), "web.xml", "web.xml");
war.addAsWebInfResource(InjectionBeanToPhaseListenerTest.class.getPackage(), "faces-config.xml", "faces-config.xml");
war.addAsWebResource(InjectionBeanToPhaseListenerTest.class.getPackage(), "home.xhtml", "home.xhtml");
war.addAsWebInfResource(new StringAsset("<beans bean-discovery-mode=\"all\"></beans>"), "beans.xml");
return war;
}
@Test
public void test() throws Exception {
try (Client client = ClientBuilder.newClient().register(JacksonFeature.class)) {
WebTarget target = client.target(url.toExternalForm() + "home.jsf");
Response response = target.request().get();
String value = response.getHeaderString("X-WildFly");
Assert.assertNotNull(value);
Assert.assertEquals(value, SimpleBean.MESSAGE);
}
}
}
| 3,166 | 40.671053 | 125 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jsf/undertow/CallEnumParameterMethodTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2021, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jsf.undertow;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.test.integration.jsf.undertow.deployment.SpecificOrder;
import org.jboss.as.test.integration.jsf.undertow.deployment.OrdersSearchQuery;
import org.jboss.as.test.integration.jsf.undertow.deployment.Order;
import org.jboss.as.test.integration.jsf.undertow.deployment.PersonalID;
import org.jboss.as.test.integration.jsf.undertow.deployment.PersonalDetails;
import org.jboss.as.test.integration.jsf.undertow.deployment.PersonalOrder;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.net.URL;
import static org.junit.Assert.assertEquals;
/**
* Test calls deployed application with a Jakarta Server Faces page. No error should occur when
* the class called from the Jakarta Server Faces has a superclass and the called method has an
* Enum as a parameter.
*
* Automated test for [ WFLY-11224 ].
*
* @author Daniel Cihak
*/
@RunWith(Arquillian.class)
@RunAsClient
public class CallEnumParameterMethodTestCase {
private static final String DEPLOYMENT = "DEPLOYMENT";
@ArquillianResource
private URL url;
@Deployment
public static WebArchive deployment() {
final Package DEPLOYMENT_PACKAGE = SpecificOrder.class.getPackage();
WebArchive war = ShrinkWrap.create(WebArchive.class, DEPLOYMENT + ".war")
.addClasses(SpecificOrder.class, Order.class, PersonalOrder.class, PersonalDetails.class, PersonalID.class, OrdersSearchQuery.class)
.addAsWebResource(DEPLOYMENT_PACKAGE, "search.xhtml", "search.xhtml")
.addAsWebInfResource(DEPLOYMENT_PACKAGE, "web.xml", "web.xml")
.addAsWebInfResource(DEPLOYMENT_PACKAGE, "faces-config.xml", "faces-config.xml");
return war;
}
@Test
public void testCallEnumParameterMethodFromJsf() throws Exception {
try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
String jspUrl = url.toExternalForm() + "search.jsf";
HttpGet httpget = new HttpGet(jspUrl);
httpclient.execute(httpget);
HttpResponse response2 = httpclient.execute(httpget);
assertEquals(200, response2.getStatusLine().getStatusCode());
}
}
}
| 3,776 | 40.966667 | 148 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jsf/undertow/deployment/PersonalID.java
|
package org.jboss.as.test.integration.jsf.undertow.deployment;
public enum PersonalID {
ID1(1100),
ID2(1111);
private final int specificId;
PersonalID(final int specificId) {
this.specificId = specificId;
}
public int getSpecificId() {
return specificId;
}
}
| 307 | 17.117647 | 62 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jsf/undertow/deployment/SpecificOrder.java
|
package org.jboss.as.test.integration.jsf.undertow.deployment;
import java.util.HashMap;
import java.util.Map;
public class SpecificOrder extends Order {
private Map<PersonalID, PersonalOrder> personInformation = new HashMap<PersonalID, PersonalOrder>();
public SpecificOrder(String name, PersonalID personalID) {
PersonalOrder personalOrder = new PersonalOrder(name);
personInformation.put(personalID, personalOrder);
}
@Override
public PersonalOrder getPersonalDetails(PersonalID id) {
return personInformation.get(id);
}
}
| 579 | 28 | 104 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jsf/undertow/deployment/PersonalDetails.java
|
package org.jboss.as.test.integration.jsf.undertow.deployment;
public class PersonalDetails {
private String name;
public PersonalDetails(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| 328 | 16.315789 | 62 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jsf/undertow/deployment/PersonalOrder.java
|
package org.jboss.as.test.integration.jsf.undertow.deployment;
public class PersonalOrder extends PersonalDetails {
public PersonalOrder(String name) {
super(name);
}
}
| 187 | 19.888889 | 62 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jsf/undertow/deployment/Order.java
|
package org.jboss.as.test.integration.jsf.undertow.deployment;
public abstract class Order {
public abstract PersonalDetails getPersonalDetails(final PersonalID id);
}
| 174 | 24 | 76 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jsf/undertow/deployment/OrdersSearchQuery.java
|
package org.jboss.as.test.integration.jsf.undertow.deployment;
import jakarta.enterprise.context.SessionScoped;
import jakarta.faces.model.ArrayDataModel;
import jakarta.faces.model.DataModel;
import jakarta.inject.Named;
import java.io.Serializable;
@Named
@SessionScoped
public class OrdersSearchQuery implements Serializable {
private static final long serialVersionUID = 134313L;
private static final SpecificOrder[] ORDERS = new SpecificOrder[] {
new SpecificOrder("PersonalOrder-1", PersonalID.ID1),
new SpecificOrder("PersonalOrder-2", PersonalID.ID2)
};
private transient DataModel<SpecificOrder> paidOrders = new ArrayDataModel<>(ORDERS);
public DataModel<SpecificOrder> getPaidOrders() {
return paidOrders;
}
}
| 784 | 28.074074 | 89 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jsf/el/ElServlet.java
|
/*
*
* * JBoss, Home of Professional Open Source.
* * Copyright $year Red Hat, Inc., and individual contributors
* * as indicated by the @author tags.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
*
*/
package org.jboss.as.test.integration.jsf.el;
import java.io.IOException;
import jakarta.el.ExpressionFactory;
import jakarta.faces.FactoryFinder;
import jakarta.faces.application.Application;
import jakarta.faces.context.FacesContext;
import jakarta.faces.context.FacesContextFactory;
import jakarta.faces.lifecycle.LifecycleFactory;
import jakarta.servlet.ServletConfig;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.jsp.JspFactory;
@WebServlet(urlPatterns = {"/ElServlet"})
public class ElServlet extends HttpServlet {
private ServletContext servletContext;
private volatile Application application;
public void init(ServletConfig config) throws ServletException {
super.init(config);
servletContext = config.getServletContext();
}
protected void doGet(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException {
initApplication(req, response);
ExpressionFactory jspFactory = JspFactory.getDefaultFactory()
.getJspApplicationContext(servletContext).getExpressionFactory();
ExpressionFactory applicationFactory = application.getExpressionFactory();
if (!jspFactory.equals(applicationFactory)) {
throw new IllegalStateException(String.format("Application factory %s@%d/%s does not match JSP factory %s%d/%s",
applicationFactory.getClass(), System.identityHashCode(applicationFactory), applicationFactory,
jspFactory.getClass(), System.identityHashCode(jspFactory), jspFactory));
}
}
private void initApplication(ServletRequest request,
ServletResponse response) {
if (application == null) {
FacesContextFactory facesContextFactory = (FacesContextFactory) FactoryFinder
.getFactory(FactoryFinder.FACES_CONTEXT_FACTORY);
LifecycleFactory lifecycleFactory = (LifecycleFactory) FactoryFinder
.getFactory(FactoryFinder.LIFECYCLE_FACTORY);
FacesContext facesContext = facesContextFactory.getFacesContext(servletContext, request,
response,
lifecycleFactory.getLifecycle(LifecycleFactory.DEFAULT_LIFECYCLE));
application = facesContext.getApplication();
}
}
}
| 3,404 | 40.024096 | 124 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jsf/el/FacesExpressionFactoryTestCase.java
|
/*
*
* * JBoss, Home of Professional Open Source.
* * Copyright $year Red Hat, Inc., and individual contributors
* * as indicated by the @author tags.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
*
*/
package org.jboss.as.test.integration.jsf.el;
import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset;
import java.net.HttpURLConnection;
import java.net.URL;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.OperateOnDeployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(Arquillian.class)
@RunAsClient
public class FacesExpressionFactoryTestCase {
private static final String TEST_NAME = "FacesExpressionFactoryTestCase";
@Deployment(name = TEST_NAME)
public static Archive<?> deploy() {
final Package resourcePackage = FacesExpressionFactoryTestCase.class.getPackage();
return ShrinkWrap.create(WebArchive.class, TEST_NAME + ".war")
.addClasses(ElServlet.class)
.addAsWebInfResource(resourcePackage, "beans.xml", "beans.xml")
.addAsWebInfResource(resourcePackage, "faces-config.xml", "faces-config.xml")
.addAsManifestResource(createPermissionsXmlAsset(
new RuntimePermission("getClassLoader")),
"permissions.xml");
}
@ArquillianResource
@OperateOnDeployment(TEST_NAME)
private URL url;
@Test
public void testApplicationExpressionFactory() throws Exception {
try (CloseableHttpClient client = HttpClientBuilder.create().build()) {
HttpUriRequest getRequest = new HttpGet(url.toExternalForm() + "ElServlet");
try (CloseableHttpResponse getResponse = client.execute(getRequest)) {
org.junit.Assert.assertEquals(EntityUtils.toString(getResponse.getEntity()), HttpURLConnection.HTTP_OK, getResponse.getStatusLine().getStatusCode());
}
}
}
}
| 3,178 | 40.285714 | 165 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jsf/version/JSFDeploymentProcessorTestCase.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2021, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jsf.version;
import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset;
import java.io.FilePermission;
import java.io.IOException;
import java.net.URL;
import java.util.Arrays;
import java.util.Collection;
import java.util.PropertyPermission;
import jakarta.faces.context.FacesContext;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.jboss.arquillian.container.test.api.Deployer;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.OperateOnDeployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.junit.InSequence;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.arquillian.api.ContainerResource;
import org.jboss.as.arquillian.api.ServerSetup;
import org.jboss.as.arquillian.container.ManagementClient;
import org.jboss.as.test.integration.jsf.version.ejb.JSFMyFacesEJB;
import org.jboss.as.test.integration.jsf.version.ejb.JSFVersionEJB;
import org.jboss.as.test.integration.jsf.version.war.JSFMyFaces;
import org.jboss.as.test.integration.jsf.version.war.JSFVersion;
import org.jboss.as.test.shared.TestLogHandlerSetupTask;
import org.jboss.as.test.shared.util.LoggingUtil;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.EnterpriseArchive;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.jboss.shrinkwrap.resolver.api.maven.Maven;
import org.jboss.shrinkwrap.resolver.api.maven.PomEquippedResolveStage;
import org.junit.Assert;
import org.junit.Assume;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Tests different ways to add Jakarta Server Faces implementation in ear files
*
* @author tmiyar
*/
@RunWith(Arquillian.class)
@ServerSetup({JSFDeploymentProcessorTestCase.TestLogHandlerSetup.class})
@RunAsClient
public class JSFDeploymentProcessorTestCase {
private static final String WEB_BUNDLED_JSF = "bundled-jsf";
private static final String WEB_BUNDLED_JSF_WEB_XML = "bundled-jsf-web.xml";
private static final String WEB_FACES_CONFIG_XML = "faces-config-xml";
private static final String MYFACES = "MyFaces JSF-2.0 Core API";
@ContainerResource
private ManagementClient managementClient;
@ArquillianResource
protected static Deployer deployer;
// [WFLY-16450] TODO No MyFaces implementation of Faces 4 available, so injection and tests that use it are disabled
//@ArquillianResource
private URL bundledJsf;
@ArquillianResource
@OperateOnDeployment(WEB_FACES_CONFIG_XML)
private URL facesConfigXml;
/**
* Creates a war with all the libraries needed in the war/lib folder, this sample does not call the
* ejb as it is not necessary to test if the bundled Jakarta Server Faces is loaded
*
* @return
*/
@Deployment(name = WEB_BUNDLED_JSF, testable = false, managed = false)
public static EnterpriseArchive createDeployment1() throws IOException {
final EnterpriseArchive ear = ShrinkWrap.create(EnterpriseArchive.class, WEB_BUNDLED_JSF + ".ear");
ear.addAsManifestResource(JSFDeploymentProcessorTestCase.class.getPackage(), WEB_BUNDLED_JSF + "-application.xml", "application.xml");
ear.addAsManifestResource(createPermissionsXmlAsset(
new RuntimePermission("getClassLoader"),
new RuntimePermission("accessDeclaredMembers"),
new PropertyPermission("*", "read"),
new FilePermission("/-", "read")), "permissions.xml");
JavaArchive ejb = ShrinkWrap.create(JavaArchive.class, "bundled-jsf-ejb.jar");
ejb.addClasses(JSFMyFacesEJB.class);
//add the ejb
ear.addAsModule(ejb);
final WebArchive war = ShrinkWrap.create(WebArchive.class, WEB_BUNDLED_JSF + "-webapp.war");
war.addClasses(JSFMyFaces.class);
war.addAsWebResource(JSFVersion.class.getPackage(), "jsfmyfacesversion.xhtml", "jsfmyfacesversion.xhtml");
war.addAsWebInfResource(JSFVersion.class.getPackage(), WEB_BUNDLED_JSF_WEB_XML, "web.xml");
//add Jakarta Server Faces as webapp lib
final PomEquippedResolveStage resolver = Maven.resolver().loadPomFromFile("pom.xml");
war.addAsLibraries(
resolver.resolve(
"commons-beanutils:commons-beanutils:1.9.3",
"commons-collections:commons-collections:3.2.2",
"commons-digester:commons-digester:1.8",
"org.apache.myfaces.core:myfaces-api:2.0.24",
"org.apache.myfaces.core:myfaces-impl:2.0.24"
)
.withoutTransitivity()
.asFile()
);
// add the .war
ear.addAsModule(war);
return ear;
}
/**
* Creates a war with only the faces-config to indicate it is using Jakarta Server Faces, that way it will load the one provided by Wildfly
*
* @return
*/
@Deployment(name = WEB_FACES_CONFIG_XML, testable = false)
public static EnterpriseArchive createDeployment2() {
final EnterpriseArchive ear = ShrinkWrap.create(EnterpriseArchive.class, WEB_FACES_CONFIG_XML + ".ear");
ear.addAsManifestResource(JSFDeploymentProcessorTestCase.class.getPackage(), WEB_FACES_CONFIG_XML + "-application.xml", "application.xml");
JavaArchive ejb = ShrinkWrap.create(JavaArchive.class, "ejb.jar");
ejb.addClasses(JSFVersionEJB.class);
//add the ejb
ear.addAsModule(ejb);
final WebArchive war = ShrinkWrap.create(WebArchive.class, WEB_FACES_CONFIG_XML + "-webapp.war");
war.addClasses(JSFVersion.class);
war.addAsWebInfResource(JSFVersion.class.getPackage(), WEB_FACES_CONFIG_XML + "-faces-config.xml", "faces-config.xml");
war.addAsWebResource(JSFVersion.class.getPackage(), "jsfversion.xhtml", "jsfversion.xhtml");
// add the .war
ear.addAsModule(war);
return ear;
}
@Test
@InSequence(1)
public void deployBundledJsf() {
Assume.assumeFalse("[WFLY-16450] No MyFaces implementation of Faces 4 available", true);
// in order to use @ArquillianResource URL from the unmanaged deployment we need to deploy the test archive first
deployer.deploy(WEB_BUNDLED_JSF);
}
/**
* Facing intermitent problem on myfaces 2.3 documented here https://issues.jboss.org/browse/WELD-1387
* using myfaces 2.0 instead
*
* @throws Exception
*/
@Test
@InSequence(2)
@OperateOnDeployment(WEB_BUNDLED_JSF)
public void bundledJsf() throws Exception {
Assume.assumeFalse("[WFLY-16450] No MyFaces implementation of Faces 4 available", true);
try {
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
try (CloseableHttpClient client = httpClientBuilder.build()) {
HttpUriRequest getVarRequest = new HttpGet(bundledJsf.toExternalForm() + "jsfmyfacesversion.xhtml");
try (CloseableHttpResponse getVarResponse = client.execute(getVarRequest)) {
String text = EntityUtils.toString(getVarResponse.getEntity());
Assert.assertTrue("Text should contain [" + MYFACES + "] but it contains[" + text + "]", text.contains(MYFACES));
}
}
Assert.assertFalse("Unexpected log message: " + LOG_MESSAGE, LoggingUtil.hasLogMessage(managementClient, TEST_HANDLER_NAME, LOG_MESSAGE));
} finally {
deployer.undeploy(WEB_BUNDLED_JSF);
}
}
@Test
public void facesConfigXmlTest() throws Exception {
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
try (CloseableHttpClient client = httpClientBuilder.build()) {
HttpUriRequest getVarRequest = new HttpGet(facesConfigXml.toExternalForm() + "jsfversion.xhtml");
try (CloseableHttpResponse getVarResponse = client.execute(getVarRequest)) {
String text = EntityUtils.toString(getVarResponse.getEntity());
Package aPackage = FacesContext.class.getPackage();
System.err.println("***** package = " + aPackage);
String facesVersion = aPackage.getSpecificationTitle();
Assert.assertTrue("Text should contain [" + facesVersion + "] but it contains [" + text + "]", text.contains(facesVersion));
}
}
Assert.assertFalse("Unexpected log message: " + LOG_MESSAGE, LoggingUtil.hasLogMessage(managementClient, TEST_HANDLER_NAME, LOG_MESSAGE));
}
private static final String TEST_HANDLER_NAME;
private static final String TEST_LOG_FILE_NAME;
private static final String LOG_MESSAGE;
static {
/*
* Make both the test handler name and the test log file specific for this class and execution so that we do not
* interfere with other test classes or multiple subsequent executions of this class against the same container
*/
TEST_HANDLER_NAME = "test-" + JSFDeploymentProcessorTestCase.class.getSimpleName();
TEST_LOG_FILE_NAME = TEST_HANDLER_NAME + ".log";
LOG_MESSAGE = "WFLYJSF0005";
}
public static class TestLogHandlerSetup extends TestLogHandlerSetupTask {
@Override
public Collection<String> getCategories() {
return Arrays.asList("org.jboss.as.jsf");
}
@Override
public String getLevel() {
return "WARN";
}
@Override
public String getHandlerName() {
return TEST_HANDLER_NAME;
}
@Override
public String getLogFileName() {
return TEST_LOG_FILE_NAME;
}
}
}
| 11,261 | 42.992188 | 150 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jsf/version/ejb/JSFMyFacesEJB.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2019, Red Hat, Inc. and/or its affiliates, and individual
* contributors by the @authors tag. See the copyright.txt in the
* distribution for a full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.as.test.integration.jsf.version.ejb;
import jakarta.ejb.Stateless;
import jakarta.faces.context.FacesContext;
@Stateless
public class JSFMyFacesEJB {
public String getJSFVersion() {
return "JSF VERSION: " + FacesContext.class.getPackage().getSpecificationTitle();
}
}
| 1,104 | 35.833333 | 89 |
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.