com.evasion.plugin.geoloc.SearchEngine Maven / Gradle / Ivy
The newest version!
package com.evasion.plugin.geoloc;
import com.evasion.entity.geolocation.Location;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.security.PermitAll;
import javax.ejb.LocalBean;
import javax.ejb.Remote;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.compass.annotations.config.CompassAnnotationsConfiguration;
import org.compass.core.*;
import org.compass.core.config.CompassConfiguration;
import org.compass.gps.CompassGps;
import org.compass.gps.CompassGpsException;
import org.compass.gps.device.jpa.JpaGpsDevice;
import org.compass.gps.impl.SingleCompassGps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author sebastien
*/
@Singleton
@Startup
@TransactionManagement(TransactionManagementType.BEAN)
@LocalBean
public class SearchEngine {
private static Logger LOGGER = LoggerFactory.getLogger(SearchEngine.class);
private Compass compass = null;
private CompassGps gps = null;
@PostConstruct
public void initialiser() {
CompassConfiguration conf = new CompassAnnotationsConfiguration();
conf.configure(getClass().getClassLoader().getResource("compass.cfg.xml"));
conf.addClass(Location.class);
compass = conf.buildCompass();
gps = new SingleCompassGps(compass);
// Création du composant JPA
EntityManagerFactory emf = Persistence.createEntityManagerFactory("EvasionPU");
JpaGpsDevice jpaDevice = new JpaGpsDevice("jpa", emf);
jpaDevice.setInjectEntityLifecycleListener(true);
jpaDevice.setNativeExtractor(new GlassfishV3NativeJpaExtractor());
gps.addGpsDevice(jpaDevice);
gps.start();
}
@PermitAll
public boolean start() {
if (!gps.isRunning()) {
try {
gps.index();
} catch (CompassGpsException ex) {
LOGGER.warn("Erreur d'indexation:", ex);
return false;
}
LOGGER.debug("Start OK");
}
return true;
}
@PreDestroy
public void preDestroy() {
if (compass != null) {
compass.close();
}
}
public Collection search(String searchTerms, String sortTerm) {
CompassSession session = compass.openSession();
Collection result = null;
CompassTransaction ctx = null;
CompassHits hits;
try {
ctx = session.beginTransaction();
CompassQuery qb = session.queryBuilder().queryString(searchTerms).toQuery();
if (sortTerm != null && !sortTerm.isEmpty()) {
qb.addSort(sortTerm, CompassQuery.SortPropertyType.STRING);
}
hits = qb.hits();
result = new ArrayList(hits.getLength());
for (Iterator it = hits.iterator(); it.hasNext();) {
result.add(it.next().getData());
}
ctx.commit();
} catch (CompassException ce) {
if (ctx != null) {
ctx.rollback();
}
} finally {
session.close();
}
return result;
}
}